Skip to content

core: close Program proof and allocation boundaries - #463

Closed
lemone112 wants to merge 3 commits into
agent/public-program-apifrom
agent/program-packed-proof-boundary
Closed

core: close Program proof and allocation boundaries#463
lemone112 wants to merge 3 commits into
agent/public-program-apifrom
agent/program-packed-proof-boundary

Conversation

@lemone112

@lemone112 lemone112 commented Jul 26, 2026

Copy link
Copy Markdown
Collaborator

DAG

Draft stacked PR. Base: agent/public-program-api / #461 at 92f8376. Do not merge before #461.

Что изменено

  • compile-fail sentinel scanner теперь отвергает production-код, оказавшийся между документными fence;
  • admitted joint order структурно непустой: первый state хранится отдельно, пустое runtime-состояние непредставимо;
  • public Program сообщает checked upper bounds для Verified/Conflict evidence cells до исполнения;
  • session использует эти же bounds для fallible allocation, без второй формулы;
  • external boundary tests связывают bounds с фактическими fixed/joint certificates, duplicate-case reduction и обоими overflow-путями.

Зачем

Предыдущая граница оставляла два proof-вакуума: отрицательный compile-fail sentinel мог пережить вставку live-кода, а максимальный размер evidence allocation не был доступен и доказан через единую Program-формулу. Этот slice закрывает оба без transport/client semantics и без расширения recipe-архитектуры.

Проверки

  • cargo +1.96.0 fmt --all --check
  • cargo +1.96.0 clippy --workspace --all-targets --locked -- -D warnings
  • cargo +1.96.0 test --workspace --locked — Core 764 passed / 6 ignored; все workspace suites и doctests green
  • focused Program boundary: 19 passed
  • focused generic boundary: 15 passed
  • Core doctests/compile-fail sentinels: 43 passed
  • git diff --check

Summary by CodeRabbit

  • Новые возможности
    • Добавлен preflight-API для предварительного расчёта границ размера доказательств: evidence_cell_bounds(scenario_count) (verified/conflict) без создания и изменения сессии.
    • Введены типы EvidenceCellBoundsV1 и EvidenceBoundsErrorV1 с диагностикой CardinalityOverflow.
    • Улучшены подсчёты при совместном выборе: корректный учёт конфликтных ячеек и количества состояний.
  • Исправления
    • Уточнена логика определения “hard”-ограничений при расчёте конфликтов и буферов оценивания.
  • Тесты
    • Расширены сценарии для границ, переполнений, дубликатов сценариев и неизменности результатов после обновлений.

lemone112 and others added 2 commits July 26, 2026 10:08
…ells

`AdmittedFiniteJointOrderV1` stored one flat tuple slice, so an empty
admitted order was representable and the evaluation path carried a
runtime `state_count == 0 -> InternalInvariant` guard to reject it. The
guard proved nothing about the type; it only re-checked a property the
constructor already enforced.

Split the order into `first + rest`. Non-emptiness becomes structural,
`state_count()` is total, and the `InternalInvariant` branch in
`prepare_program_evaluation_buffers` is deleted rather than left dead.
The `joint_state_count: Option<usize>` parameter disappears with it:
cell counts are now derived from the epoch itself.

The same pass stops reserving an exhaustive-conflict buffer that no
constraint can ever fill. `can_conflict` is false when every compiled
constraint is report-only, so a report-only program no longer reserves
`cases x constraints x states` cells and no longer reports
`ResourceExhausted` for a conflict it cannot produce.

`OwnerV1::evidence_cell_bounds` exposes the same arithmetic as a pure
preflight, with `EvidenceBoundsErrorV1::CardinalityOverflow` as the only
closed failure. It creates no Session and mutates no state.

Verified locally on the CI-pinned toolchain: full workspace tests green,
`cargo fmt --all --check` and `cargo clippy --workspace --all-targets --
-D warnings` clean.

Co-Authored-By: Claude <noreply@anthropic.com>
@coderabbitai

coderabbitai Bot commented Jul 26, 2026

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: e78fe760-7016-4f40-96a3-3a766fdcc6e3

📥 Commits

Reviewing files that changed from the base of the PR and between 4fc9521 and 412da83.

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

Walkthrough

PR добавляет публичное preflight-вычисление границ evidence, меняет хранение состояний joint-порядка, обновляет расчёт буферов оценивания и усиливает проверку compile-fail документации тестами.

Changes

Планирование границ evidence

Layer / File(s) Summary
Представление состояний joint-порядка
crates/labcolors-core/src/joint.rs
Первый tuple хранится отдельно от остальных, tuples() объединяет оба источника, а state_count() возвращает число состояний.
Расчёт границ оценивания и буферов
crates/labcolors-core/src/program_session.rs
Размеры verified/conflict-ячеек учитывают constraint’ы, отклоняющие кандидата; подготовка буферов получает эти значения непосредственно из epoch.
Публичный API и граничные тесты
crates/labcolors-core/src/program.rs, crates/labcolors-core/tests/program_boundary.rs
Добавлены EvidenceCellBoundsV1, EvidenceBoundsErrorV1 и OwnerV1::evidence_cell_bounds; тесты покрывают fixed/joint-сценарии, переполнения, конфликты, дубликаты и чистоту запросов.

Проверка compile-fail fences

Layer / File(s) Summary
Проверка содержимого compile-fail fences
crates/labcolors-core/src/generic_boundary_tests.rs
Сканер требует doc-комментарии или пустые строки внутри активного compile-fail fence и отклоняет live code отдельным тестом.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Sequence Diagram(s)

sequenceDiagram
  participant OwnerV1
  participant CompiledProgram
  participant EvaluationCounts
  OwnerV1->>CompiledProgram: evidence_cell_bounds(scenario_count)
  CompiledProgram->>EvaluationCounts: checked_program_epoch_evaluation_cell_counts
  EvaluationCounts-->>CompiledProgram: selected и exhaustive_conflict counts
  CompiledProgram-->>OwnerV1: EvidenceCellBoundsV1 или CardinalityOverflow
Loading
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed Заголовок кратко и точно отражает основную суть PR: закрытие границ доказательств и выделения ресурсов в core.
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.
✨ 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/program-packed-proof-boundary

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

Copy link
Copy Markdown
Collaborator Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jul 26, 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: 2

Caution

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

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

1626-1659: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Добавить комментарий к условию резервирования conflict_cells.

Логика верна: conflict_cells реально используется только в ветке evaluate_program_session с joint_selection (без него код всегда берёт только buffers.take_selected()), поэтому дополнительная проверка epoch.joint_selection.is_some() наряду с counts.exhaustive_conflict != 0 оправдана и предотвращает лишнюю аллокацию. Но само по себе сочетание двух условий неочевидно без пояснения — читатель может решить, что проверка joint_selection.is_some() избыточна, раз exhaustive_conflict и так равен 0 при can_conflict == false.

As per coding guidelines, "Комментарии в коде должны объяснять почему и инвариант, а не пересказывать оператор."

✏️ Предлагаемый комментарий
     let mut conflict_cells = Vec::new();
+    // `conflict_cells` is only ever populated by the joint-selection branch
+    // of `evaluate_program_session`; skip reserving it otherwise, even when
+    // `exhaustive_conflict` is nonzero for a non-joint hard constraint.
     if epoch.joint_selection.is_some() && counts.exhaustive_conflict != 0 {
🤖 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 1626 - 1659,
Добавьте поясняющий комментарий непосредственно перед условием резервирования в
prepare_program_evaluation_buffers: conflict_cells используется только при
evaluate_program_session с включённым epoch.joint_selection, поэтому проверка
joint_selection.is_some() сохраняется для предотвращения ненужной аллокации даже
при ненулевом counts.exhaustive_conflict.

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/joint.rs`:
- Around line 130-133: Добавьте комментарий перед веткой
`first_tuple.ok_or(FiniteJointOrderErrorV1::EmptyOrder)?`, объясняющий, что
проверка `authored.len() >= 1` перед циклом гарантирует установку `first_tuple`,
поэтому ошибка `EmptyOrder` недостижима при текущем инварианте; сохраните
типизированную проверку вместо паники.

In `@crates/labcolors-core/src/program_session.rs`:
- Around line 1494-1517: Добавьте рядом с вычислением state_count комментарий,
объясняющий инвариант: отсутствие joint_selection означает единственную
фиксированную конфигурацию, поэтому число состояний равно 1. Не изменяйте
поведение unwrap_or(1) и остальную логику подсчёта.

---

Outside diff comments:
In `@crates/labcolors-core/src/program_session.rs`:
- Around line 1626-1659: Добавьте поясняющий комментарий непосредственно перед
условием резервирования в prepare_program_evaluation_buffers: conflict_cells
используется только при evaluate_program_session с включённым
epoch.joint_selection, поэтому проверка joint_selection.is_some() сохраняется
для предотвращения ненужной аллокации даже при ненулевом
counts.exhaustive_conflict.
🪄 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: 2b5f5ffc-7936-49ab-a9d6-dbe93612b7ea

📥 Commits

Reviewing files that changed from the base of the PR and between 92f8376 and 4fc9521.

📒 Files selected for processing (5)
  • crates/labcolors-core/src/generic_boundary_tests.rs
  • crates/labcolors-core/src/joint.rs
  • crates/labcolors-core/src/program.rs
  • crates/labcolors-core/src/program_session.rs
  • crates/labcolors-core/tests/program_boundary.rs

Comment thread crates/labcolors-core/src/joint.rs
Comment thread crates/labcolors-core/src/program_session.rs
@lemone112

Copy link
Copy Markdown
Collaborator Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jul 26, 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.

@lemone112

Copy link
Copy Markdown
Collaborator Author

Superseded by the reviewed cumulative squash merge #465 (24fd1f4). The lower stacked branch was intentionally not merged on its own because its intermediate head was not the safe terminal public boundary.

@lemone112 lemone112 closed this Jul 26, 2026
@lemone112
lemone112 deleted the agent/program-packed-proof-boundary branch July 26, 2026 22:16
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