Skip to content

Core: задать точную контекстную family-область - #494

Merged
lemone112 merged 11 commits into
mainfrom
agent/v5b2b-contextual-region
Jul 29, 2026
Merged

Core: задать точную контекстную family-область#494
lemone112 merged 11 commits into
mainfrom
agent/v5b2b-contextual-region

Conversation

@lemone112

@lemone112 lemone112 commented Jul 29, 2026

Copy link
Copy Markdown
Collaborator

Что изменено

  • добавлено crate-private точное определение contextual family-region: exact-dyadic parser, строго положительно определённая матрица 2×2, замкнутый tone-domain и одна piecewise-linear tube-геометрия без semantic recipes;
  • добавлен канонический ASCII SSA artifact contextual-region-formula-v1.lcir, который фиксирует nominal exact-real lift sRGB8 → XYZ(D65) → CAT16/CAM16 → CAM16-UCS и membership law;
  • formula release теперь является domain-separated content address байтов artifact-а, а не числовым tag;
  • strict parser/typed reconstructor/encoder проверяет единственную каноническую форму, типы, arity, backward references, ABI checkpoints, reachability и отсутствие неиспользуемых declarations;
  • все 56 binary64 literals artifact-а побитово связаны с числовыми владельцами, реально используемыми production sRGB/D65, CAT16, viewing-conditions, CAM16 и CAM16-UCS math;
  • provider по-прежнему возвращает только FamilyDefinitionDigestV2: не минтит image/release/certificate, не знает token names, cleanliness, neutral, brand или sentiment и не открывает public API;
  • source-bound receipts пересвязаны fail-closed после изменения зарегистрированного module graph; Python bytecode исключён из Git.

Зачем

Это завершает V5b2b: Core получает одно воспроизводимое математическое определение непрерывной contextual family-области до offline proof/materialisation. Formula, region и context становятся одной canonical identity, но runtime ещё не получает временный classifier или bitmap.

Доказательства

  • exact HEAD 442bc772ff47ce99b3fb3b485b6ee8e6a4d649e7, tree d78faae14a421de349e5cf81780c92056b0f9d42, base f900fb8192eb9ffe5f31091e100fca5a380f1201;
  • raw formula SHA-256 a6f77ac462f226453b1c27bbd8637b62780b9a640c317a6f50028dacd1de8540;
  • domain-separated formula release 2c626d8ee60eeb62ae4db53660d61bbc25e0efd4e557f0dc1e77565c130b6e52;
  • canonical family definition digest 0a8d1c3d2f0052be84b5783071699861aad0ac83dae62de3275267754681cdc9;
  • hostile well-typed 1-ULP mutation меняет identity и отвергается exact owner binding;
  • exact i128 differential/property oracles для segment и singleton law; decode+XYZ побитово связан с runtime; point graph имеет отдельный явно empirical binary64 characterization ratchet, не выдаваемый за exact proof;
  • parser/canonical/mutation/property suite: 7/7; Core: 1001 passed, 7 ignored; весь workspace и 37 Core doctests: PASS;
  • clean-set product receipt a1cedccfe9acf5feeb9244e4c9ed3dc7ee1c1703fc6910c665dbd88443899b14: PASS; point-support independent replay: PASS;
  • mutation-harness hostile suite после актуального main: 50/50 PASS;
  • remote exact-head gates: MSRV, test, clippy/rustfmt, docs, RustSec, WASM/headless/size, Node 22 и Swift conformance — PASS;
  • reproducible release diff: public API/exports/dependencies и достижимый WASM code не изменились; raw WASM и оба dylib сохранили размер, formula/test-parser bytes отсутствуют во всех release outputs. Static archive вырос на 20,560 bytes из-за нового staged crate-private region module; это реальный archive-size cost, а не runtime/heap cost, и он явно не маскируется как binary identity;
  • независимый архитектурно-численный аудит нашёл пробел exact literal/source binding; пробел исправлен и повторный аудит не нашёл blocker-ов. Все доказанные CodeRabbit threads исправлены и разрешены. Повторный review текущего head был rate-limited и не засчитывается как содержательный review.

Границы

Binary64 characterization не доказывает exact-real эквивалентность. V5b2c отдельно выполнит all-domain interval classification относительно этого frozen artifact двумя независимо source-bound engine-ами; связь artifact с production numeric owners уже замкнута этим PR. V5b2d отдельно материализует полный sRGB8 image. BoundaryUnproven, resource exhaustion, crash или disagreement никогда не минтят release.

Публичного API, runtime family image, cleanliness verdict, solver rule или client-specific vocabulary в этом PR нет.

@coderabbitai

coderabbitai Bot commented Jul 29, 2026

Copy link
Copy Markdown

Review Change Stack

Walkthrough

Добавлен crate-private модуль contextual-region с точной dyadic-геометрией, валидацией pipeline и каноническим формированием FamilyDefinitionDigestV2. Подключены property-based и boundary-тесты, обновлены связанные контрольные суммы.

Changes

Определение contextual-region

Layer / File(s) Summary
Точная геометрия contextual-region
crates/labcolors-core/src/contextual_region.rs
Добавлены exact-dyadic значения, сравнение произведений, проверки положительной определённости shape-матрицы и валидация tube knots.
Pipeline и canonical identity
crates/labcolors-core/src/contextual_region.rs
Добавлены проверки согласованности pipeline, length-prefixed кодирование identity и провайдер, создающий FamilyDefinitionDigestV2.
Проверка геометрии и identity
crates/labcolors-core/src/contextual_region_tests.rs
Добавлены property-based и unit-тесты арифметики, структурных ошибок, mutation-bound digest и canonical byte encoding.
Регистрация и boundary-инварианты
crates/labcolors-core/src/lib.rs, crates/labcolors-core/src/generic_boundary_tests.rs
Модуль подключён как crate-private, тесты зарегистрированы, generic-source и definition-only проверки расширены.
Обновление контрольных сумм
crates/labcolors-core/contracts/clean-set-srgb8-v1/*, crates/labcolors-core/contracts/point-support-reference-surplus-q55-bps-proof-v1.json, scripts/verify_point_support_surplus.py
Обновлены receipt, proof-контракт и ожидаемый SHA-256 source capsule.

Estimated code review effort: 4 (Complex) | ~60 minutes

Sequence Diagram(s)

sequenceDiagram
  participant ContextualRegionPipelineV1
  participant PiecewiseLinearCartesianTubeV1
  participant ContextualRegionFamilyProviderV1
  participant FamilyDefinitionDigestV2
  ContextualRegionPipelineV1->>ContextualRegionFamilyProviderV1: передаёт согласованный pipeline
  PiecewiseLinearCartesianTubeV1->>ContextualRegionFamilyProviderV1: передаёт проверенный регион
  ContextualRegionFamilyProviderV1->>ContextualRegionFamilyProviderV1: кодирует canonical identity
  ContextualRegionFamilyProviderV1->>FamilyDefinitionDigestV2: создаёт digest
Loading

Possibly related PRs

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed Заголовок кратко и точно отражает основное изменение: добавление точной контекстной family-области в core.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch agent/v5b2b-contextual-region

Comment @coderabbitai help to get the list of available commands.

@lemone112

Copy link
Copy Markdown
Collaborator Author

@coderabbitai full review

@coderabbitai

coderabbitai Bot commented Jul 29, 2026

Copy link
Copy Markdown
✅ Action performed

Full review finished.

coderabbitai[bot]
coderabbitai Bot previously requested changes Jul 29, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@crates/labcolors-core/src/contextual_region.rs`:
- Around line 120-128: Добавьте рядом со сдвигами в ветке Ordering::Equal явный
комментарий об инварианте безопасности: при равных self_top и other_top
выровненная длина битов каждой significand не превышает 107, поэтому сдвиг в
u128 не теряет старшие биты. Не изменяйте логику сравнения или существующий
комментарий о приведении индекса бита.
- Around line 89-94: Согласуйте равенство ExactDyadicProductV1 с его точным
сравнением по значению: уберите производные PartialEq и Eq и реализуйте их через
результат существующего cmp, чтобы эквивалентные ненормализованные представления
считались равными. Сохраните текущую семантику Ord и обеспечьте, чтобы cmp(a, b)
== Equal всегда совпадало с a == b.
- Around line 59-69: Добавьте комментарий непосредственно перед вычислением
показателя в методе magnitude_parts, объясняющий, что поле fraction занимает 52
младших бита, normal significand включает скрытый бит 2^52, а bias IEEE-754
равен 1023; зафиксируйте из этого выводы e - 1075 для normal и -1074 для
subnormal. Логику и значения констант не изменяйте.

In `@crates/labcolors-core/src/generic_boundary_tests.rs`:
- Around line 324-325: Update the production-signature assertion in the generic
boundary tests to avoid depending on the formatting or line placement of the
return type: remove the brittle "-> familydefinitiondigestv2" check and retain
the stable familydefinitiondigestv2::from_digest marker, or normalize whitespace
before matching.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 176e60fa-d47e-4eaa-8101-04d1a493c548

📥 Commits

Reviewing files that changed from the base of the PR and between 26a69c8 and 6926e61.

📒 Files selected for processing (8)
  • crates/labcolors-core/contracts/clean-set-srgb8-v1/receipt-v1.json
  • crates/labcolors-core/contracts/clean-set-srgb8-v1/receipt-v1.sha256
  • crates/labcolors-core/contracts/point-support-reference-surplus-q55-bps-proof-v1.json
  • crates/labcolors-core/src/contextual_region.rs
  • crates/labcolors-core/src/contextual_region_tests.rs
  • crates/labcolors-core/src/generic_boundary_tests.rs
  • crates/labcolors-core/src/lib.rs
  • scripts/verify_point_support_surplus.py

Comment thread crates/labcolors-core/src/contextual_region.rs
Comment thread crates/labcolors-core/src/contextual_region.rs Outdated
Comment thread crates/labcolors-core/src/contextual_region.rs
Comment thread crates/labcolors-core/src/generic_boundary_tests.rs Outdated
@lemone112

Copy link
Copy Markdown
Collaborator Author

@coderabbitai full review

@coderabbitai

coderabbitai Bot commented Jul 29, 2026

Copy link
Copy Markdown
✅ Action performed

Full review finished.


Your included review limit is currently reached under our Fair Usage Limits Policy. Your recent PR review activity is in the 95th percentile or higher among CodeRabbit users, so adaptive limits apply. This review may still proceed through usage-based billing if eligible. Your next included review will be available in 14 minutes.

@lemone112

Copy link
Copy Markdown
Collaborator Author

@coderabbitai full review

@coderabbitai

coderabbitai Bot commented Jul 29, 2026

Copy link
Copy Markdown
✅ Action performed

Full review finished.

coderabbitai[bot]
coderabbitai Bot previously requested changes Jul 29, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@crates/labcolors-core/src/contextual_region_tests.rs`:
- Around line 613-627: Update field_payload_ranges to validate that at least 8
bytes remain before slicing the length prefix, and validate that the decoded
payload end does not exceed bytes.len() before slicing or recording the range.
Replace implicit out-of-range panics with assertions that clearly identify the
invalid length-prefixed encoding.
- Around line 297-308: Расширьте тест для
PiecewiseLinearCartesianTubeV1::try_from_bits так, чтобы отдельные проверки
фиксировали корректное отображение всех вариантов TubeCoordinateV1, включая
ShapeG01, ShapeG11, CenterA, CenterB, Tone и RadiusSquared, а не только CenterA.
Добавьте также проверку NegativeZero на уровне региона, сохранив ожидаемые index
и reason для каждого случая.

In `@crates/labcolors-core/src/generic_boundary_tests.rs`:
- Around line 314-324: Усилить проверку инварианта в тесте, который перебирает
forbidden_branch: буквальные подстроки недостаточны, поскольку ветвление по
center можно скрыть через локальную переменную. Либо ограничить сообщение и
проверяемое утверждение фактически обнаруживаемыми формами, либо заменить
строковой поиск на AST-проверку, выявляющую сравнение результата .center() в
условиях if/match; сохранить проверку того, что center strength остаётся данными
одного закона.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 55e67df1-e822-4e75-96ca-fff21e97b15d

📥 Commits

Reviewing files that changed from the base of the PR and between 26a69c8 and e397973.

📒 Files selected for processing (8)
  • crates/labcolors-core/contracts/clean-set-srgb8-v1/receipt-v1.json
  • crates/labcolors-core/contracts/clean-set-srgb8-v1/receipt-v1.sha256
  • crates/labcolors-core/contracts/point-support-reference-surplus-q55-bps-proof-v1.json
  • crates/labcolors-core/src/contextual_region.rs
  • crates/labcolors-core/src/contextual_region_tests.rs
  • crates/labcolors-core/src/generic_boundary_tests.rs
  • crates/labcolors-core/src/lib.rs
  • scripts/verify_point_support_surplus.py

Comment thread crates/labcolors-core/src/contextual_region_tests.rs
Comment thread crates/labcolors-core/src/contextual_region_tests.rs
Comment thread crates/labcolors-core/src/generic_boundary_tests.rs Outdated
@lemone112
lemone112 dismissed stale reviews from coderabbitai[bot] and coderabbitai[bot] July 29, 2026 11:43

Все actionable threads исправлены и разрешены; review относится к устаревшему head, а повторный bot-review на текущем head завершился rate-limit без вердикта.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant