Skip to content

feat(core): add transactional point attachment - #478

Merged
lemone112 merged 3 commits into
mainfrom
agent/o1b-point-attachment
Jul 27, 2026
Merged

feat(core): add transactional point attachment#478
lemone112 merged 3 commits into
mainfrom
agent/o1b-point-attachment

Conversation

@lemone112

@lemone112 lemone112 commented Jul 27, 2026

Copy link
Copy Markdown
Collaborator

Результат

  • добавляет приватный Attachment, который линейно владеет Session, точной compiled generation и sink lease;
  • разделяет authored output→sink и output→presentation, проверяет полное fan-out покрытие и пишет физический output ровно один раз;
  • заменяет вторую authority Projection/Set/Remove одним whole-snapshot протоколом SetAll | RevokeAll | ConfirmExact;
  • публикует Session только после успешного атомарного sink install, а при любой fallible ошибке сохраняет прежние snapshot, revision, Stamp и Session;
  • отзывает весь owned scope до освобождения lease/session/pin;
  • удерживает post-install хвост без allocator/destructor traffic; это утверждение не распространяется на весь update;
  • публичные Rust/WASM/FFI API не меняются.

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

  • RED: поздняя ошибка после физического swap оставляла новую revision при старой Session;
  • hostile faults после Busy acquisition, после SetAll swap и после RevokeAll swap;
  • mutation controls отдельно убивают удаление rollback snapshot, revision и Stamp для обеих whole-patch веток;
  • exact point proof: source closure 2bb05b04027f4415e3511db43a324b697f0f1dcee6294ec10c539c2ea6ce65b7, 43 negative controls;
  • clean-set product receipt: 9190d17fe46f6588cd26fd0a65eed4956afbffefba7d1ef34e192fcf0922f418 (PRODUCT_IDENTITY_VERIFIED; research replay намеренно не заявлен).

Проверки

  • cargo +1.96.0 fmt --all -- --check
  • cargo +1.96.0 test -p labcolors-core --all-targets --locked
  • cargo +1.96.0 clippy --workspace --all-targets --locked -- -D warnings
  • RUSTDOCFLAGS='-D warnings' cargo +1.96.0 doc --workspace --no-deps --locked
  • cargo +1.96.0 package -p labcolors-core --allow-dirty --locked — 129 files, package verify GREEN
  • python3 scripts/verify_point_support_surplus.py
  • python3 scripts/verify_clean_set_receipt.py product --product-root .
  • python3 -m unittest discover -s scripts -p 'test_verify_clean_set_receipt.py' — 31/31
  • python3 -m unittest discover -s scripts -p 'test_program_public_surface.py' — 8/8

Граница

Это O1b-1: приватная транзакционная authority. Немедленный следующий отдельный срез O1b-1a заменит pre-existing open-address ScenarioId admission на bounded deterministic sorts до любого public export.

Summary by CodeRabbit

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

    • Добавлена поддержка привязки точечных выходов к презентациям и их публикации в sink.
    • Реализованы атомарные обновления, подтверждение точных снимков и отзыв устаревших данных.
    • Добавлена проверка соответствия выходов, презентаций, идентификаторов и областей владения.
  • Исправления

    • Улучшена обработка ошибок и частично выполненных обновлений без повреждения ранее опубликованного снимка.
    • Уточнён жизненный цикл сессий и порядок освобождения устаревших данных.
  • Проверки

    • Расширено тестирование привязок, повторных попыток, конфликтов, отказов sink и проверки целостности артефактов.

@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: 26 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: 6a0f80ae-94fd-4b03-80b2-3f9a6c42aa76

📥 Commits

Reviewing files that changed from the base of the PR and between ca8f2c8 and d68e661.

📒 Files selected for processing (15)
  • 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/appearance.rs
  • crates/labcolors-core/src/generic_boundary_tests.rs
  • crates/labcolors-core/src/program/attachment.rs
  • crates/labcolors-core/src/program/attachment/support.rs
  • crates/labcolors-core/src/program/attachment/tests.rs
  • crates/labcolors-core/src/program_api_tests.rs
  • crates/labcolors-core/src/program_boundary_tests.rs
  • crates/labcolors-core/src/program_mixed_evaluator_tests.rs
  • crates/labcolors-core/src/program_session.rs
  • crates/labcolors-core/src/program_session_tests.rs
  • scripts/test_verify_clean_set_receipt.py
  • scripts/verify_point_support_surplus.py

Walkthrough

Добавлены terminal point-attachment и атомарная публикация snapshot-ов через linear sink. Session-переходы переведены на evidence-only API с deferred retirement, добавлена привязка output к point presentation, расширены тесты и receipt/verifier-контракты.

Changes

Point-attachment и публикация

Layer / File(s) Summary
Evidence-only API и deferred commit
crates/labcolors-core/src/session.rs, crates/labcolors-core/src/program.rs, crates/labcolors-core/src/*_tests.rs
PreparedSessionTransition получает prospective disposition и deferred retirement, а Program возвращает EvidenceViewV1 вместо owner-bound projection; тесты обновлены под новый контракт.
Привязка output к presentation
crates/labcolors-core/src/appearance.rs, crates/labcolors-core/src/program_session.rs, crates/labcolors-core/src/*tests.rs
Добавлены cold lookup occurrence subject и bind_point_output_presentation с проверкой ordinal, paint identity и точных ошибок.
Attachment и sink lifecycle
crates/labcolors-core/src/program/attachment.rs, crates/labcolors-core/src/program/attachment/*
Добавлены bindings, sink-протокол, валидация attachment, patch staging, atomic install, revocation, retirement и post-commit render outputs; in-memory sink и тесты покрывают ошибки границ и порядок освобождения.
Receipt и verifier-контракты
crates/labcolors-core/contracts/*, scripts/verify_clean_set_receipt.py, scripts/test_verify_clean_set_receipt.py, scripts/verify_point_support_surplus.py, scripts/verify_program_public_surface.py
В product source cone добавлены attachment-артефакты, обновлены proof/receipt hashes, hostile-проверки отсутствующих и изменённых артефактов, а также обнаружение nested program sources.

Estimated code review effort: 5 (Critical) | ~120 minutes

Sequence Diagram(s)

sequenceDiagram
  participant OwnerV1
  participant Attachment
  participant Session
  participant LinearPointSinkLeaseV1
  OwnerV1->>Attachment: attach bindings and sink lease
  Attachment->>Session: prepare_update(update)
  Session-->>Attachment: prepared disposition
  Attachment->>LinearPointSinkLeaseV1: prepare(intent, patches, stamp)
  LinearPointSinkLeaseV1-->>Attachment: proposed stamp
  Attachment->>LinearPointSinkLeaseV1: try_install()
  Attachment->>Session: commit_deferred()
  Attachment->>LinearPointSinkLeaseV1: finish_after_session()
  Attachment-->>OwnerV1: AttachmentCommitV1 and render outputs
Loading

Possibly related PRs

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 47.42% 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 Title clearly summarizes the main change: adding transactional point attachment in core.
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/o1b-point-attachment

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

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

Caution

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

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

89-91: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

certificate_count больше ничего не проверяет.

После удаления обхода operations() переменная только считается и гасится через let _ = .... Либо утверждать что-то содержательное (например, что повторный проход даёт то же число), либо убрать её.

♻️ Предлагаемое упрощение
-    let certificates = exact_size(view.certificates());
-    let certificate_count = certificates.len();
-    for certificate in certificates {
+    for certificate in exact_size(view.certificates()) {
-    let _ = certificate_count;
 }

Also applies to: 190-191

🤖 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_boundary_tests.rs` around lines 89 - 91,
Remove the unused certificate_count calculation in the certificate iteration
within the program boundary tests, including the corresponding occurrence around
the second referenced section. Do not retain a suppressed value; only keep the
certificate traversal and assertions that provide meaningful validation.

863-889: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Имя теста осталось в терминах projection.

Остальные тесты в этом слое переименованы под evidence-контракт; здесь ..._commit_returns_the_new_projection теперь описывает EvidenceViewV1. Переименование сохранит согласованность номенклатуры.

🤖 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_boundary_tests.rs` around lines 863 - 889,
Переименуйте тест `..._commit_returns_the_new_projection` в терминологию
evidence-контракта, используя `EvidenceViewV1` вместо `projection`; поведение и
проверки теста оставьте без изменений.
crates/labcolors-core/src/generic_boundary_tests.rs (1)

428-465: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Запреты по подстроке в целом PROGRAM_SOURCE хрупки.

"SetV1", "RemoveV1", "HoldV1" проверяются как подстроки всего файла, поэтому любое будущее легитимное имя (например OutputSetV1, ThresholdV1) начнёт валить тест по ложной причине. Стоит привязать запреты к синтаксическим формам (enum SetV1, SetV1 {, -> SetV1), как это уже сделано для pub(crate) fn project(.

🤖 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/generic_boundary_tests.rs` around lines 428 - 465,
Уточни проверки запрещённых API в тесте вокруг массива forbidden: замени общие
подстроки SetV1, RemoveV1 и HoldV1 на синтаксически специфичные формы объявлений
или использования, например enum, структурный вариант и возвращаемый тип, по
аналогии с проверкой pub(crate) fn project(. Сохрани запрет на реальные
устаревшие sink-authority конструкции, но не блокируй легитимные имена, лишь
содержащие эти фрагменты.
🤖 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/appearance.rs`:
- Around line 1943-1951: Упростите occurrence_subject: после успешного
binary_search_by_key напрямую извлекайте элемент по найденному индексу и
возвращайте его subject_id, устранив повторный get и лишнюю недостижимую ветку.
Сохраните Option-поведение для случая, когда поиск не находит occurrence, в
стиле соседних bind_occurrence/occurrence.

In `@crates/labcolors-core/src/program_api_tests.rs`:
- Around line 46-54: Update the test around projection.certificates() and
certificate.outputs() to retain both iterators and assert that each has no
second element after validating the first Verified certificate and certified
Paint output. Preserve the existing assertions for output_slot() and source(),
while explicitly enforcing the single-certificate and single-output contract.

In `@crates/labcolors-core/src/program_mixed_evaluator_tests.rs`:
- Line 732: Rename the evidence-only helper function consume_public_projection
to consume_public_evidence and the associated ProjectionProbe type to
EvidenceProbe. Update all references and usages in the affected tests while
preserving their existing behavior with EvidenceViewV1.
- Line 1524: Удалите тождественные псевдонимы ready_evidence в тестах и
используйте исходную переменную ready напрямую во всех соответствующих
выражениях; примените то же изменение к аналогичным присваиваниям на позициях
1576, 1606 и 1640.
- Around line 2546-2547: Удалите избыточную строку `let _ = owner;` перед
вызовом `assert_projection_matches_model` в соответствующем тесте, оставив
использование `owner` в ветвях `prepare_modeled_payload` и `commit` без
изменений.

In `@crates/labcolors-core/src/program_session_tests.rs`:
- Around line 554-559: Добавьте короткий комментарий перед проверками
output_ordinal() и presentation_ordinal(), поясняющий, что ожидаемое значение 1
основано на каноническом возрастающем порядке числовых ID, где EARLIER_OUTPUT и
EARLIER_PRESENTATION_ROOT имеют меньшие значения. Не изменяйте сами проверки.

In `@crates/labcolors-core/src/program_session.rs`:
- Around line 1398-1416: Добавьте doc-комментарии к вариантам
MissingPresentationTarget и InternalInvariant в enum
PointOutputPresentationBindErrorV1, описав отсутствие цели presentation для
указанного root/occurrence и нарушенный внутренний инвариант соответственно;
остальные варианты и поля не изменяйте.

In `@crates/labcolors-core/src/program/attachment.rs`:
- Around line 827-887: В обработке ConfirmExact сохраните ссылку на validated
published_stamp при построении action и переиспользуйте её при создании
PointSinkIntentV1::ConfirmExact и проверке ConfirmStampMismatch. Удалите
повторные вызовы self.published_stamp.as_ref().ok_or(...) в этих участках,
сохранив существующее поведение для отсутствующего stamp и остальных вариантов
action.
- Around line 507-509: Document the invariant for committed_sink_patch in the
surrounding struct: it is retained as a reusable buffer solely so mem::swap and
clear() preserve its allocation capacity across updates. If the implementation
does not require that capacity-preservation behavior, remove the field and
update the related swap/clear logic accordingly.
- Around line 521-551: Refactor UnpublishedSinkGuardV1 to store L directly
instead of Option<L>, removing the unreachable!() branches from sink() and
accept(). Implement accept(self) by extracting the owned sink while suppressing
Drop with ManuallyDrop, so the guard’s Drop implementation still revokes the
sink unless ownership is successfully accepted.

In `@crates/labcolors-core/src/program/attachment/support.rs`:
- Around line 260-354: Уточните семантику счётчиков в prepare: state.counts.*
сейчас увеличивается до ветки reject_next_prepare и учитывает отклонённые
intent. Переместите инкремент после точки, где prepare уже не может быть
отклонён, чтобы считать только intent, дошедшие до install, либо добавьте явный
комментарий, что счётчики означают предъявленные intent; изменяйте
соответствующую ветку match по intent_kind в prepare.

In `@crates/labcolors-core/src/program/attachment/tests.rs`:
- Around line 606-664: Improve diagnostics in
source_guards_keep_the_post_install_tail_destructor_free by replacing bare
find/split unwraps and contains assertions with explicit assertion messages
identifying the missing source anchor or expected invariant. Preserve the
existing ordering and content checks, but make failures report which symbol or
guard was not found instead of only panicking on Option::unwrap.

In `@scripts/test_verify_clean_set_receipt.py`:
- Around line 464-489: Объедините проверки отсутствующих и изменённых артефактов
в общие параметризованные хелперы, чтобы не дублировать отдельные тесты для
каждой роли. Обновите существующие
`test_product_only_mode_rejects_each_missing_transitive_executor` и
`test_product_only_mode_rejects_each_mutated_transitive_executor` либо их общие
вспомогательные методы, передавая кортеж ролей и соответствующие пути
артефактов; сохраните текущие ожидания ошибок и `subTest` для каждой роли.

---

Outside diff comments:
In `@crates/labcolors-core/src/generic_boundary_tests.rs`:
- Around line 428-465: Уточни проверки запрещённых API в тесте вокруг массива
forbidden: замени общие подстроки SetV1, RemoveV1 и HoldV1 на синтаксически
специфичные формы объявлений или использования, например enum, структурный
вариант и возвращаемый тип, по аналогии с проверкой pub(crate) fn project(.
Сохрани запрет на реальные устаревшие sink-authority конструкции, но не блокируй
легитимные имена, лишь содержащие эти фрагменты.

In `@crates/labcolors-core/src/program_boundary_tests.rs`:
- Around line 89-91: Remove the unused certificate_count calculation in the
certificate iteration within the program boundary tests, including the
corresponding occurrence around the second referenced section. Do not retain a
suppressed value; only keep the certificate traversal and assertions that
provide meaningful validation.
- Around line 863-889: Переименуйте тест `..._commit_returns_the_new_projection`
в терминологию evidence-контракта, используя `EvidenceViewV1` вместо
`projection`; поведение и проверки теста оставьте без изменений.
🪄 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: 5f8aa058-a22c-4c1c-be51-4c64e8855422

📥 Commits

Reviewing files that changed from the base of the PR and between b92c4b7 and ca8f2c8.

📒 Files selected for processing (23)
  • 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/appearance.rs
  • crates/labcolors-core/src/appearance_graph_tests.rs
  • crates/labcolors-core/src/generic_boundary_tests.rs
  • crates/labcolors-core/src/program.rs
  • crates/labcolors-core/src/program/attachment.rs
  • crates/labcolors-core/src/program/attachment/support.rs
  • crates/labcolors-core/src/program/attachment/tests.rs
  • crates/labcolors-core/src/program_api_tests.rs
  • crates/labcolors-core/src/program_boundary_tests.rs
  • crates/labcolors-core/src/program_clean_set_tests.rs
  • crates/labcolors-core/src/program_mixed_evaluator_tests.rs
  • crates/labcolors-core/src/program_session.rs
  • crates/labcolors-core/src/program_session_tests.rs
  • crates/labcolors-core/src/session.rs
  • crates/labcolors-core/src/session_tests.rs
  • scripts/test_program_public_surface.py
  • scripts/test_verify_clean_set_receipt.py
  • scripts/verify_clean_set_receipt.py
  • scripts/verify_point_support_surplus.py
  • scripts/verify_program_public_surface.py

Comment thread crates/labcolors-core/src/appearance.rs
Comment thread crates/labcolors-core/src/program_api_tests.rs Outdated
Comment thread crates/labcolors-core/src/program_mixed_evaluator_tests.rs Outdated
Comment thread crates/labcolors-core/src/program_mixed_evaluator_tests.rs Outdated
Comment thread crates/labcolors-core/src/program_mixed_evaluator_tests.rs Outdated
Comment thread crates/labcolors-core/src/program/attachment.rs Outdated
Comment thread crates/labcolors-core/src/program/attachment.rs
Comment thread crates/labcolors-core/src/program/attachment/support.rs
Comment thread crates/labcolors-core/src/program/attachment/tests.rs
Comment thread scripts/test_verify_clean_set_receipt.py Outdated
@lemone112

Copy link
Copy Markdown
Collaborator Author

Review closure on exact head d68e661:

  • all 13 inline threads addressed and resolved;
  • outside-diff findings fixed: removed dead certificate_count, renamed the evidence test, and replaced raw substring bans with identifier-bound guards;
  • ConfirmExact now reads one published stamp;
  • unpublished sink cleanup is panic-free and remains safe Rust via an armed borrowing guard (no ManuallyDrop/unsafe);
  • exact proof and receipt were rebound.

Local gates: core all-targets 888 passed / 6 ignored, workspace clippy -D warnings, rustdoc, 129-file package, point-proof replay, 31 receipt hostile tests, and 8 public-surface tests all GREEN.

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jul 27, 2026

Copy link
Copy Markdown

@lemone112 Thanks for the detailed closure report. I’ll review the current PR state, including the updated transactional attachment and verification artifacts.

✅ 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
lemone112 merged commit 4096844 into main Jul 27, 2026
10 checks passed
@lemone112
lemone112 deleted the agent/o1b-point-attachment branch July 27, 2026 16:25
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