Skip to content

core: bind modeled-point causality to revisions - #474

Merged
lemone112 merged 4 commits into
mainfrom
agent/o1ac-causal-certificate
Jul 27, 2026
Merged

core: bind modeled-point causality to revisions#474
lemone112 merged 4 commits into
mainfrom
agent/o1ac-causal-certificate

Conversation

@lemone112

@lemone112 lemone112 commented Jul 27, 2026

Copy link
Copy Markdown
Collaborator

Что изменено

  • Program-отчёт хранит revision-bound causal evidence для каждого объявленного modeled terminal root: exact normal/counterfactual replay, physical case, Program identity и versioned absence/composition path.
  • Verified результат выдаёт только typed fixed/selected certificate; exhaustive conflict выдаёт отдельно названное considered evidence и не притворяется выбором.
  • Selected и exhaustive-conflict владеют раздельными preflight-аренами: успешный отчёт не удерживает память полного перебора, а конфликт сохраняет полный набор evidence.
  • Causal storage каждого отчёта остаётся плоским; borrowed projection не аллоцирует и не пересчитывает graph.
  • Все cardinality/allocations проверяются до graph/evaluator work. Общий exact-cardinality guard отдельно отвергает дрейф cells, causal records, replay steps и output storage.
  • Source-bound point-support proof перепривязан к точным байтам изменённого private semantic cone без изменения claim, формул или Q55 dependency.

Это modeled point claim. Он не сертифицирует renderer/browser pixels, attachment, actual sink или cleanliness. NonEmptyReplaySpanV1 — только диапазон индексов внутренней истории пересчёта; непрерывная LCS-растяжка и swatches не затронуты.

Корневая причина

После exact replay (#472) его результат ещё не принадлежал revision-bound Program report, а размеры новых evidence-буферов не входили в общий fail-before-work preflight. Первоначальная реализация также объединяла selected и exhaustive capacities через max, поэтому успешный результат удерживал память полного joint-перебора. Раздельное владение устраняет это без поздних аллокаций и без изменения публичного API.

Проверки

  • cargo +1.96.0 test --workspace --all-features --locked
  • cargo +1.96.0 clippy --workspace --all-targets --locked -- -D warnings
  • cargo +1.96.0 fmt --all --check
  • cargo +1.85.0 check --workspace --all-targets --locked
  • cargo +1.96.0 check -p labcolors-wasm --target wasm32-unknown-unknown --locked
  • RUSTDOCFLAGS="-D warnings" cargo +1.96.0 doc --workspace --no-deps --locked
  • Program public-surface gates
  • point-support source-binding tests и independent verifier
  • targeted mutation: 14/14 storage/cardinality guard mutants killed; preflight arenas — 0 missed viable mutants
  • hostile target-order mutant: RED на полном state × case × (root,target) corpus

Summary by CodeRabbit

  • Новые возможности

    • Добавлены причинные свидетельства для точек: воспроизводимые шаги, состояния и сертификаты.
    • Отчёты и конфликты теперь предоставляют доступ к причинным данным.
    • Расширено планирование ресурсов с учётом причинных записей и шагов воспроизведения.
  • Исправления

    • Уточнена логика домена для отсутствующих точек при равенстве корней.
    • Исправлено поведение при исчерпании ресурсов: вычислитель не запускается до успешного резервирования.
    • Обновлены контрольные криптографические суммы в проверочных доказательствах.
  • Тесты

    • Расширены поведенческие и интеграционные проверки причинности, границ ёмкостей и корректной последовательности preflight-резерваций.

@coderabbitai

coderabbitai Bot commented Jul 27, 2026

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

You’ve reached a temporary PR review limit under our Fair Usage Limits Policy.

Your recent review volume is higher than typical usage, so adaptive limits are currently applied.

Next review available in: 51 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 44bace27-e9b6-425f-b01d-90433457d5ad

📥 Commits

Reviewing files that changed from the base of the PR and between c0772fb and 01381b5.

📒 Files selected for processing (2)
  • crates/labcolors-core/src/program_point_causality_tests.rs
  • crates/labcolors-core/src/program_session.rs

Walkthrough

Добавлена генерация и хранение point-causal evidence для point presentations, включая replay steps, selected/considered состояния и расчёт ёмкости буферов. Обновлены absence-summary API, интеграционные тесты, boundary-проверки и SHA-256 метаданные доказательства.

Changes

Point-causal evidence

Layer / File(s) Summary
Сводка absence replay
crates/labcolors-core/src/appearance.rs
Добавлены ExactFinalOwnedPointDomainV1::from_roots и PointOccurrenceAbsenceSummaryV1; методы replay делегируют вычисления общей сводке.
Контракты и ёмкость causal buffers
crates/labcolors-core/src/program_session.rs
Добавлены типы causal evidence, поля отчёта, агрегированные point presentations и расчёт ёмкости records/replay steps с подготовкой буферов.
Сканирование и выдача evidence
crates/labcolors-core/src/program_session.rs
scan_program_candidate создаёт replay evidence для presentations, а verified/conflict reports извлекают selected и considered evidence из канонических буферов.
Интеграционные и boundary-проверки
crates/labcolors-core/src/lib.rs, crates/labcolors-core/src/program_boundary_tests.rs, crates/labcolors-core/src/program_joint_integration_tests.rs, crates/labcolors-core/src/program_point_causality_tests.rs
Добавлены проверки cardinality, replay/stale revision, selected/considered evidence, preflight-порядка и независимости evidence_cell_bounds.
Обновление digest-связей
crates/labcolors-core/contracts/...proof-v1.json, scripts/verify_point_support_surplus.py
Обновлены SHA-256 значения proof payload, source closure, исходных файлов и source capsule.

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

Sequence Diagram(s)

sequenceDiagram
  participant ProgramSession
  participant PreparedProgramEvaluationBuffersV1
  participant scan_program_candidate
  participant replay_point_occurrence_absence_into
  participant ProgramReportV1
  ProgramSession->>PreparedProgramEvaluationBuffersV1: reserve causal records and replay steps
  ProgramSession->>scan_program_candidate: scan candidate with causal buffers
  scan_program_candidate->>replay_point_occurrence_absence_into: replay each point presentation
  replay_point_occurrence_absence_into-->>scan_program_candidate: return replay steps and roots
  scan_program_candidate->>ProgramReportV1: store causal records and replay steps
Loading

Possibly related PRs

  • Labpics-Team/lab-colors#447: Обновляет связанный point-support retained-surplus proof и проверку source binding.
  • Labpics-Team/lab-colors#468: Затрагивает порядок diagnostic-фаз в связанной логике сбора candidate evidence.
  • Labpics-Team/lab-colors#472: Затрагивает связанные типы counterfactual absence replay в appearance.rs.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 32.47% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed Заголовок точно отражает основную идею PR: привязку modeled-point causality к ревизиям.
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.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch agent/o1ac-causal-certificate

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

Copy link
Copy Markdown
Collaborator Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jul 27, 2026

Copy link
Copy Markdown
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@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: 9

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
crates/labcolors-core/src/program_session.rs (1)

1966-1974: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Имя тестового хелпера теперь противоречит его содержимому.

checked_program_evaluation_cardinality_for_test вызывает checked_program_evaluation_cell_counts и возвращает только cell-счётчики, тогда как продовая checked_program_evaluation_cardinality (Line 1902) возвращает полную cardinality вместе с point-causal ёмкостями. Одинаковый префикс создаёт впечатление, что тест покрывает новую cardinality-функцию, хотя он проверяет только cells.

♻️ Предлагаемое переименование
 #[cfg(test)]
-pub(crate) fn checked_program_evaluation_cardinality_for_test(
+pub(crate) fn checked_program_evaluation_cell_counts_for_test(
     physical_case_count: usize,
     constraint_count: usize,
     state_count: usize,
 ) -> Option<(usize, usize)> {

Вызов в crates/labcolors-core/src/program_joint_integration_tests.rs (импорт на строке 26 и использование в evaluation_cell_cardinality_checks_both_products_without_a_numeric_cap) нужно обновить синхронно.

🤖 Prompt for 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.

In `@crates/labcolors-core/src/program_session.rs` around lines 1966 - 1974,
Rename the test-only helper checked_program_evaluation_cardinality_for_test to
clearly indicate it returns cell counts, while preserving its existing
checked_program_evaluation_cell_counts behavior. Update the corresponding import
and call in
evaluation_cell_cardinality_checks_both_products_without_a_numeric_cap in
program_joint_integration_tests.rs.
scripts/verify_point_support_surplus.py (1)

185-188: 🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

assert отключается под python -O, превращая верификацию в no-op.

Вся проверка привязки — включая мутационные контроли на строках 236 и 241 — держится на assert. Запуск с -O или PYTHONOPTIMIZE=1 (например, в оптимизированном CI-образе) заставит скрипт завершиться с кодом 0, ничего не проверив. Для инструмента доказательства это молчаливый ложноположительный результат.

🛡️ Предлагаемое исправление
-    assert digest == EXPECTED_SOURCE_CAPSULE_SHA256, (
-        f"point-support semantic source drifted: {digest} != "
-        f"{EXPECTED_SOURCE_CAPSULE_SHA256}"
-    )
+    if digest != EXPECTED_SOURCE_CAPSULE_SHA256:
+        raise SystemExit(
+            f"point-support semantic source drifted: {digest} != "
+            f"{EXPECTED_SOURCE_CAPSULE_SHA256}"
+        )

Аналогично для мутационных контролей:

    for path, old, new in mutations:
        mutated = mutate_source(sources, path, old, new)
        if source_closure_digest(mutated) == digest:
            raise SystemExit("source mutation escaped complete-file binding")

As per coding guidelines, «invalid, unreachable, unsupported и incomplete context должны возвращаться типизированно» — а не давать правдоподобный успешный fallback.

🤖 Prompt for 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.

In `@scripts/verify_point_support_surplus.py` around lines 185 - 188, Replace the
verification asserts in the script, including the digest check and mutation
controls in the surrounding verification flow, with explicit failure handling
that raises SystemExit when a condition is violated. Ensure optimized Python
execution still validates the source binding and exits nonzero for digest
mismatches or mutations that escape the complete-file binding.

Source: Coding guidelines

🤖 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/program_joint_integration_tests.rs`:
- Line 1488: Расширьте успешный путь вокруг цикла reservation_index, чтобы после
проверки индексов 0..=2 явно подтвердить SessionState::Ready и отсутствие
резервирования для первого неиспользуемого индекса (3). Сохраните существующие
проверки индексов 0..=2 и добавьте отдельную проверку верхней границы по образцу
program_point_causality_tests.rs, чтобы новые fallible-резервации не оставались
непокрытыми.
- Line 1557: Вынесите повторяющуюся проверку инъецированной резервации из joint-
и fixed-тестов в общий хелпер. Перенесите в него границу перебора
reservation_index 0..=2 и семантику, что нулевая арена не резервирует; оба теста
должны вызывать хелпер вместо дублирующихся блоков успешной проверки.

In `@crates/labcolors-core/src/program_point_causality_tests.rs`:
- Line 669: Replace the duplicated reservation limit in the loop around
reservation_index and the fail_program_preflight_reservation_for_test call with
one shared constant representing the first free index. Use that constant for
both the loop range and the preflight reservation assertion so they remain
synchronized.
- Around line 194-196: Добавьте краткий комментарий рядом с входами OpacityInput
и ожидаемым значением [252; 3], объясняющий расчёт 255 + 0.01 * (0 - 255) =
252.45 и его квантование до 252; свяжите это пояснение с альфами 0.01, 0.95 и
0.5 и диапазоном ожидаемых значений 252–257, не изменяя логику теста.
- Around line 630-652: Добавьте комментарий перед сравнениями указателей в тесте
с `replayed` и `stale`, объясняющий инвариант переиспользования causal-арены при
точном replay и stale-состоянии. Укажите, что основным доказательством
отсутствия повторной оценки служит `source_over_evaluation_count() == 0`, а
сравнение `steps().as_ptr()` дополнительно проверяет сохранение того же буфера,
не представляя самостоятельное доказательство.
- Around line 295-304: Replace the compound certificates.iter().all assertion
with an indexed loop over certificates, using separate assert_eq! checks for
each expected certificate field and step value. Include the certificate index in
each assertion message or comparison context so failures identify the specific
certificate and violated property.
- Around line 594-602: Update the positive cardinality assertion using
pairwise-distinct multiplier arguments, especially the second and third
arguments, so swapping them changes the result. Recalculate and replace the
expected tuple in the call to checked_program_point_causal_cardinality_for_test,
preserving the existing test structure and the separate negative cases.

In `@crates/labcolors-core/src/program_session.rs`:
- Around line 2573-2600: Добавьте явный комментарий перед проверкой ёмкости и
преобразованием ошибок в блоке `point_causal`, объясняющий оба инварианта:
`InsufficientCapacity` недостижим благодаря гарантии
`checked_program_evaluation_cardinality` и предварительному резервированию, а
`IncompatibleEvaluation` невозможен, поскольку `presentation.path` принадлежит
тому же compiled-графу. Сохраните существующее преобразование обеих ошибок в
`ProgramSessionEvaluationError::InternalInvariant`.

In `@scripts/verify_point_support_surplus.py`:
- Around line 60-62: Update the verification flow in
scripts/verify_point_support_surplus.py to load the expected digest from the
contract’s source_closure_sha256 field instead of maintaining
EXPECTED_SOURCE_CAPSULE_SHA256 locally. Retain only the comparison between the
contract digest and the digest computed from the actual source bytes.

---

Outside diff comments:
In `@crates/labcolors-core/src/program_session.rs`:
- Around line 1966-1974: Rename the test-only helper
checked_program_evaluation_cardinality_for_test to clearly indicate it returns
cell counts, while preserving its existing
checked_program_evaluation_cell_counts behavior. Update the corresponding import
and call in
evaluation_cell_cardinality_checks_both_products_without_a_numeric_cap in
program_joint_integration_tests.rs.

In `@scripts/verify_point_support_surplus.py`:
- Around line 185-188: Replace the verification asserts in the script, including
the digest check and mutation controls in the surrounding verification flow,
with explicit failure handling that raises SystemExit when a condition is
violated. Ensure optimized Python execution still validates the source binding
and exits nonzero for digest mismatches or mutations that escape the
complete-file binding.
🪄 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: babc07ba-6b91-4dd6-9152-16e965a69b29

📥 Commits

Reviewing files that changed from the base of the PR and between 744b94c and ceaed9a.

📒 Files selected for processing (8)
  • crates/labcolors-core/contracts/point-support-reference-surplus-q55-bps-proof-v1.json
  • crates/labcolors-core/src/appearance.rs
  • crates/labcolors-core/src/lib.rs
  • crates/labcolors-core/src/program_boundary_tests.rs
  • crates/labcolors-core/src/program_joint_integration_tests.rs
  • crates/labcolors-core/src/program_point_causality_tests.rs
  • crates/labcolors-core/src/program_session.rs
  • scripts/verify_point_support_surplus.py

Comment thread crates/labcolors-core/src/program_joint_integration_tests.rs Outdated
Comment thread crates/labcolors-core/src/program_joint_integration_tests.rs Outdated
Comment thread crates/labcolors-core/src/program_point_causality_tests.rs
Comment thread crates/labcolors-core/src/program_point_causality_tests.rs Outdated
Comment thread crates/labcolors-core/src/program_point_causality_tests.rs
Comment thread crates/labcolors-core/src/program_point_causality_tests.rs
Comment thread crates/labcolors-core/src/program_point_causality_tests.rs Outdated
Comment thread crates/labcolors-core/src/program_session.rs
Comment thread scripts/verify_point_support_surplus.py
@lemone112

Copy link
Copy Markdown
Collaborator Author

Проверка двух outside-diff замечаний на exact head b00f3c9:

  • test-only helper уже переименован в checked_program_evaluation_cell_counts_for_test вместе с импортом/вызовом;
  • предположение о silent no-op под python -O опровергнуто: verify_point_support_surplus.py на строках 19–20 явно запрещает optimized mode и завершается с кодом 1 до assert-проверок. Живой запуск python3 -O scripts/verify_point_support_surplus.py подтверждает exit 1.

Все 9 inline-тредов разобраны: 7 доказанных замечаний исправлены, 2 предложения отклонены с архитектурным обоснованием. Полный workspace, clippy, rustfmt, MSRV, wasm, rustdoc и независимый proof verifier зелёные; targeted mutation guards: 14/14 caught.

@lemone112
lemone112 marked this pull request as ready for review July 27, 2026 05:07
@lemone112

Copy link
Copy Markdown
Collaborator Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jul 27, 2026

Copy link
Copy Markdown
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@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/program_point_causality_tests.rs`:
- Around line 436-446: Add a concise comment near the root presentation
declarations explaining that their reversed order is intentional:
`opaque_root_id`/`60` follows `translucent_root_id`/`61` in the declarations
while `exhaustive_causal_projection_is_state_case_presentation_lexicographic`
validates canonical `60 → 61` ordering during compilation. Do not reorder the
presentations.
- Around line 362-366: Добавьте в тестах с OpacityInput в
exhaustive_causal_projection_is_state_case_presentation_lexicographic и
связанном блоке комментарии, объясняющие роли альф 0.01, 0.95 и 0.5 в расчёте
source-over, а также почему целевой цвет [128; 3] недостижим из состояний [0; 3]
и [255; 3]. Сохраните текущие значения и ожидание SessionState::Failed,
документируя логику по аналогии с fanout_program.

In `@crates/labcolors-core/src/program_session.rs`:
- Around line 2204-2247: Добавьте комментарий перед последовательностью вызовов
try_reserve_program_evaluation_buffer, явно фиксирующий, что их порядок является
тестируемым контрактом: индексы fail_program_preflight_reservation_for_test и
FIRST_UNUSED_RESERVATION_INDEX зависят от этой последовательности. Укажите, что
перестановка или добавление резервирования сдвинет индексы инъекций сбоя; не
изменяйте сам порядок резервирований.
🪄 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: 23b14436-5b91-4f33-9d91-d6870286e307

📥 Commits

Reviewing files that changed from the base of the PR and between ceaed9a and b00f3c9.

📒 Files selected for processing (3)
  • crates/labcolors-core/src/program_joint_integration_tests.rs
  • crates/labcolors-core/src/program_point_causality_tests.rs
  • crates/labcolors-core/src/program_session.rs

Comment thread crates/labcolors-core/src/program_point_causality_tests.rs
Comment thread crates/labcolors-core/src/program_point_causality_tests.rs
Comment thread crates/labcolors-core/src/program_session.rs
@lemone112
lemone112 merged commit 47c2621 into main Jul 27, 2026
10 checks passed
@lemone112
lemone112 deleted the agent/o1ac-causal-certificate branch July 27, 2026 05:21
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