core: bind modeled-point causality to revisions - #474
Conversation
|
Warning Review limit reachedYou’ve reached a temporary PR review limit under our Fair Usage Limits Policy. Next review available in: 51 minutes Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available. How can I continue?After more reviews become available, a review can be triggered using the 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 configurationConfiguration used: Path: .coderabbit.yaml Review profile: ASSERTIVE Plan: Pro Plus Run ID: 📒 Files selected for processing (2)
WalkthroughДобавлена генерация и хранение point-causal evidence для point presentations, включая replay steps, selected/considered состояния и расчёт ёмкости буферов. Обновлены absence-summary API, интеграционные тесты, boundary-проверки и SHA-256 метаданные доказательства. ChangesPoint-causal evidence
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
Possibly related PRs
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
Comment |
|
@coderabbitai review |
✅ Action performedReview finished.
|
There was a problem hiding this comment.
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
📒 Files selected for processing (8)
crates/labcolors-core/contracts/point-support-reference-surplus-q55-bps-proof-v1.jsoncrates/labcolors-core/src/appearance.rscrates/labcolors-core/src/lib.rscrates/labcolors-core/src/program_boundary_tests.rscrates/labcolors-core/src/program_joint_integration_tests.rscrates/labcolors-core/src/program_point_causality_tests.rscrates/labcolors-core/src/program_session.rsscripts/verify_point_support_surplus.py
|
Проверка двух outside-diff замечаний на exact head b00f3c9:
Все 9 inline-тредов разобраны: 7 доказанных замечаний исправлены, 2 предложения отклонены с архитектурным обоснованием. Полный workspace, clippy, rustfmt, MSRV, wasm, rustdoc и независимый proof verifier зелёные; targeted mutation guards: 14/14 caught. |
|
@coderabbitai review |
✅ Action performedReview finished.
|
There was a problem hiding this comment.
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
📒 Files selected for processing (3)
crates/labcolors-core/src/program_joint_integration_tests.rscrates/labcolors-core/src/program_point_causality_tests.rscrates/labcolors-core/src/program_session.rs
Что изменено
Это 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 --lockedcargo +1.96.0 clippy --workspace --all-targets --locked -- -D warningscargo +1.96.0 fmt --all --checkcargo +1.85.0 check --workspace --all-targets --lockedcargo +1.96.0 check -p labcolors-wasm --target wasm32-unknown-unknown --lockedRUSTDOCFLAGS="-D warnings" cargo +1.96.0 doc --workspace --no-deps --lockedstate × case × (root,target)corpusSummary by CodeRabbit
Новые возможности
Исправления
Тесты