Skip to content

feat(storage): decouple checkpoint repository from worker roots - #6929

Merged
M4n5ter merged 3 commits into
apache:rust-previewfrom
MicroGery:codex/rust-session-repository
Nov 16, 2026
Merged

M4n5ter merged 3 commits into
apache:rust-previewfrom
MicroGery:codex/rust-session-repository

Conversation

@MicroGery

@MicroGery MicroGery commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Checkpoint objects and the authoritative Head currently live under the publishing worker Root. This adds a durable logical Session/agent binding and replaceable immutable-object and Session Repository ports, and connects the existing publisher, Head reads, exact reads and publication recovery to them.

The default local adapter retains the existing Head table and local restore behavior. Trusted bootstrap can inject a FileRepository outside worker Roots; its objects, Head and original commit receipts remain readable after the source Root is removed. Shared workers retain capture/recovery records without maintaining a second Head. Head CAS and its terminal receipt commit atomically, and lost replies recover the original result without recapture.

Refs #2370. This is PR1 of the control-plane-neutral continuation work; it does not close the issue.

Implementation

  • Repository reads return the persisted Binding together with the Head. Exact checkout validates logical identity, Manifest provenance, object bytes and Workspace dependencies, then rejects changes to either the Head or Binding during verification.
  • Local capture promotes verified private staging files with hard links and synchronizes the object directory before recording Prepared. Fresh local publication carries that capture's verification witness; recovery and external publication still verify the retained object closure. Existing deduplicated objects are checked before reuse.
  • Root-private Head/source SQL lives in the local adapter; Root assembly lives in authority. The independent repository has its own schema and explicit repository identity column, and uses a bounded persistent connection worker. EventLog stores one Local/Shared authority instead of duplicate agent fields and a nil UUID sentinel.
  • Root migration 42 follows the existing Rooms (40) and history tool metadata (41) migrations. The composed product catalog is tested on fresh initialization, upgrade from the target catalog, and actual database reopen.

Boundaries

  • The reference adapter supports private directories on Unix local filesystems. It does not provide a distributed database, network-filesystem lease or cloud-provider integration.
  • Trusted assembly selects storage before recovery. Startup requires the same repository, object-store and agent binding. Existing local publications require explicit migration before switching authorities; missing shared configuration never silently falls back to local.
  • Checkout selects only the current retained Head. Publishing r2 makes r1 unavailable to checkout even while its objects and original receipt remain. The canonical history owner remains responsible for history format and semantic validation.
  • Reading grants no execution authority. Activation/generation fencing, cross-Root execution handoff, checkpoint Fork, historical revision indexing, CLI storage configuration and GC remain follow-ups. Shared load/restore is explicitly rejected until a handoff exists.
  • External streaming publication creates an independent durable copy. Objects remain retained without GC; the local optimization does not claim zero I/O or bounded retention.

Verification

All Rust validation ran on a Mac mini against rust-preview@b08f13270 plus this change. No Rust builds ran on the editing machine.

  • cargo nextest run --locked -p maka-event-log -p maka-agent-state --test-threads 1 --no-fail-fast: 46 passed. The one manual performance case was skipped by the normal suite and then explicitly executed successfully.
  • Reproduced the swapped-Manifest checkout failure and composed migration collision before their fixes. Coverage also includes two independent commit processes, CAS single-winner arbitration, Head/receipt rollback, lost replies, source removal, missing/corrupt objects, concurrent initialization, local/shared behavior, legacy Head continuity, and recovery after a fresh capture loses its in-process verification witness.
  • cargo clippy --locked -p maka-event-log -p maka-agent-state --all-targets --no-deps -- -D warnings: passed.
  • cargo check --locked -p maka-agent-native --lib: passed.
  • Affected-crate formatting, ASF headers and diff checks: passed. Local and remote changed-source hashes match.
  • Full repository CI and Linux/Windows execution remain for hosted CI. Dependency-inclusive Clippy was not rerun for this revision; an earlier run on the previous base was blocked by an upstream clippy::needless_update in plugins/agent/provider-protocol/src/chat_completions/response.rs.

Local capture measurement

The comparison below used d317be2bc, the same Mac mini and debug/test profile; three fresh Roots, each with ten distinct 10 MiB Workspace files. The interval measures awaited publish_fenced; source creation and fence acquisition are outside it. Each result is subsequently checked out and verified.

Implementation Samples (ms) Median (ms)
Upstream d317be2bc with the same standalone fixture 828 / 798 / 811 811
Previous PR implementation on that base 2202 / 2431 / 2204 2204
Revised implementation 776 / 759 / 822 776

Run the manual case with cargo test --locked -p maka-event-log --test checkpoint_repository local_workspace_capture_baseline -- --ignored --nocapture. After rebasing to b08f13270 and allocating migration 42, the final-head repeat measured 888 / 790 / 767 ms (median 790 ms). These measurements support removal of the local-path regression for this workload; they are not a production latency guarantee.

AI use

  • No generative tool made a substantive contribution
  • Generative tooling made a substantive contribution

Tool(s) and scope: OpenAI Codex assisted with implementation, adversarial review, regression tests and this description. Commits include Generated-by: Codex.

Checklist

  • Tests cover the change and fail without it
  • Format, typecheck and the affected suites pass locally

Does this PR entail a change in behavior?

  • Yes — described under Summary above
  • No

@Astro-Han Astro-Han left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I checked the checkpoint migration and the product migration catalog at 4ef96e95876c1f6fba828864f8d82123f109aebd against the current rust-preview (7e1e0ca05de94cd20fcf4e508879d80de56a6059). The static merge succeeds, but its composed migration catalog contains two different migrations numbered 40. This is now a current integration problem because Rooms has landed.

The inline P2 identifies the conflicting declaration. In temporary SQLite databases, using the actual catalog SQL and production ledger DDL/INSERT, the current base and this PR separately passed; the merged fresh catalog failed with UNIQUE constraint failed: _sqlx_migrations.version, and upgrading a database initialized with the current base encountered the version-40 checksum mismatch. Changing only the checkpoint migration's version to 41 made both controls pass. Use the next unused version when updating the PR, and cover fresh initialization plus upgrade/reopen with the composed product catalog.

These were controlled SQL checks, not execution of Rust migration::run, RootStore, or a real Host. I did not complete the full 21-file storage review or verify multi-process publication, recovery, or platform behavior. Existing CI results on the older base do not establish that this integration works.


Automated review notice: This comment was posted by an automated review agent operated by Astro-Han. It is not an independent human review and does not replace one.

Comment thread platform/event-log/src/schema.rs Outdated
sql: include_str!("../migrations/0036_pending_content_release.sql"),
},
crate::migration::Migration {
version: 40,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[P2] Allocate an unused version after the Rooms migration

rust-preview now includes maka_agent_state::MIGRATIONS version 40 (0040_rooms.sql). products/maka/native/src/lib.rs::root_migrations concatenates that catalog with ROOT_MIGRATIONS, so this second version 40 breaks the otherwise clean merge: a fresh database inserts 40 for the checkpoint migration and fails inserting the Rooms ledger entry; a database already initialized by the current base rejects the checkpoint migration's different checksum for 40. I reproduced both with the actual migration SQL/ledger in temporary SQLite databases; only renumbering this new migration to 41 made both controls pass. Please use the next unused number and exercise the composed fresh/upgrade/reopen paths. The PR's standalone-base tests do not include the newly landed Rooms migration.

@M4n5ter

M4n5ter commented Nov 15, 2026

Copy link
Copy Markdown
Member
English

The core consistency and recovery model here is solid: keeping shared worker Roots free of a second Head, committing Head CAS atomically with CommitReceipt, distinguishing transient object-store read outages from permanent material loss, and gating SessionRepository::commit behind a VerifiedCheckpoint witness are all well thought out.

Before this lands, there are a few blockers, a noticeable local hot-path I/O regression, and some layering/state cleanups worth addressing:

  1. [Blocker] Composed migration version collision (version: 40) & shared SQL across distinct databases

    • platform/event-log/src/schema.rs allocates version: 40 (0040_checkpoint_repository.sql), which now collides with 0040_rooms.sql (version: 40) in maka_agent_state::MIGRATIONS on rust-preview. Applying this PR onto rust-preview@e52c87cc3 immediately fails maka-agent-state's migration_tests::composed_product_migrations_initialize_upgrade_and_reopen (UNIQUE constraint failed: _sqlx_migrations.version on fresh init, and version-40 checksum mismatch on upgrade).
    • Beyond bumping the Root migration to the next unused version, FileRepository::open (platform/event-log/src/checkpoints/repository/files.rs) should not include_str!("../../../migrations/0040_checkpoint_repository.sql") as its version: 1 while placing 0002_heads.sql under migrations/repository/. Sharing one SQL file across two independent SQLite databases couples their migration histories and currently stores two incompatible JSON schemas in the same checkpoint_repository_settings.configuration_json column (Configuration tagged enum JSON in root.sqlite vs. a bare UUID string in repository.sqlite). Please give migrations/repository/ its own self-contained 0001 schema with an explicit repository identity column.
  2. [Performance] Default local capture regresses from 1R/1W/1H to 3R/2W/3H per new object (~2.6x slower on larger workspaces)

    • Routing Objects::link_staged and Objects::publish (platform/event-log/src/root_store/checkpoints/objects.rs) unconditionally through ImmutableObjectStore::put(&mut dyn Read) drops the zero-copy hard_link path even for default local RootStore::open, where staging/ and objects/ sit in the same directory tree. Every newly staged file is re-opened, copied in full into a second NamedTempFile, hashed a second time, sync_all()'d again, and triggers a per-file directory sync_all().
    • In addition, routing normal in-process publication through repository::commit -> VerifiedCheckpoint::verify (platform/event-log/src/root_store/checkpoints.rs, platform/event-log/src/root_store/checkpoints/repository.rs) re-reads and re-hashes the entire object closure right after capture just wrote and hashed it (previously only crash recovery resume() re-verified retained bytes).
    • Benchmarked on rust-preview@e52c87cc3 (macOS Apple Silicon NVMe), a local RootStore::open fenced capture of 10 × 10 MiB workspace files regresses from ~701 ms (638 / 701 / 821 ms) to ~1802 ms (1710 / 1802 / 1830 ms). Meanwhile, linked in workspace.rs and Objects::sync_objects() (now reduced to self.validate()) are left behind as dead plumbing.
    • Please preserve zero-copy staging promotion (or stream directly into object staging without double-buffering) on the local path, avoid redundant full-closure re-reads when committing freshly captured objects in the same worker turn, and clean up the dead linked / sync_objects remnants.
  3. [Layering] Inverted table ownership in checkpoints::repository::sql and duplicate repository module names

    • platform/event-log/src/checkpoints/repository.rs is documented as "Checkpoint authority independent of worker Roots", yet checkpoints/repository/sql.rs introduces Layout::{Local, Shared} and directly queries/mutates worker-Root-internal tables (session_control, history_checkpoint_bindings, history_checkpoint_heads), while root_store/checkpoints/repository.rs also reads/writes history_checkpoint_bindings and history_checkpoint_heads directly.
    • Having both checkpoints::repository and root_store::checkpoints::repository touch the same Root-private tables blurs the boundary this PR is introducing. Keep worker-Root SQL inside root_store::checkpoints (Local adapter) and keep checkpoints::repository strictly independent of Root schema.
  4. [Implementation & State Modeling] Connection churn in FileRepository, split fields on EventLog, and helper naming

    • FileRepository::run opens a new rusqlite::Connection, sets pragmas, queries + parses checkpoint_repository_settings, runs one closure, and closes the connection on every port call—a single publish opens and closes repository.sqlite 3 times (bind -> receipt -> commit). Managing a persistent connection worker (similar to OwnedConnection) would avoid repeated WAL open/close churn.
    • EventLog (platform/event-log/src/lib.rs) adds both checkpoint_storage: Option<Storage> and checkpoint_agent: Uuid (initialized to a Uuid::nil() sentinel before configure), duplicating Storage.agent. Modeling this as a single configured enum (e.g. Local { agent: Uuid } | Shared(Storage)) removes the Uuid::nil() state and duplicate agent field.
    • fn unavailable(error: &StoreError) -> bool (root_store/checkpoints/repository.rs) reads backwards next to its doc comment: returning true marks the publication permanently Unavailable (corrupt/missing bytes), whereas false treats it as a transient outage and retains Prepared. Consider renaming to is_permanent_material_error or corrupt_or_missing.
  5. [Contract note for follow-ups] Head-only retention in Storage::checkout_exact

    • Since checkpoint_repository_heads overwrites head_json per session_id without a committed-revisions index table, Storage::checkout_exact(identity, rev) rejects r1 as soon as r2 is published (and rejects reads if Head moves during verification), even though r1's objects and commit receipt remain intact on disk. That matches current local RootStore semantics for PR1, just worth keeping explicit that #1415 (forking at arbitrary committed revisions) will need a durable revision index rather than filtering read_head.
简体中文

这个 PR 在一致性与崩溃恢复边界上的核心设计是扎实的:共享模式下 worker Root 不再维护第二个本地 Head、Head CAS 与 CommitReceipt 同事务原子落盘、区分对象存储临时读取故障与材料永久损坏,以及用 VerifiedCheckpoint 作为证明类型卡住 SessionRepository::commit 入口,这些约束都想得很清楚。

在合入前,有几个阻塞问题、默认本地热路径的 I/O 退化以及模块分层/状态建模上的毛刺需要处理一下:

  1. 【阻塞】组合 migration 版本号冲突(version: 40)与跨库强行复用 SQL 文件

    • platform/event-log/src/schema.rs 新增了 version: 40(0040_checkpoint_repository.sql),但当前 rust-preview 已合入的 Rooms 迁移在 maka_agent_state::MIGRATIONS 中占用了 40(0040_rooms.sql)。基于 rust-preview@e52c87cc3 实测合并后,maka-agent-state 的 migration_tests::composed_product_migrations_initialize_upgrade_and_reopen 会直接挂掉(新建库报 UNIQUE constraint failed: _sqlx_migrations.version,升级路径报 version 40 checksum 不一致)。
    • 除了把 Root 侧迁移顺延到未占用的版本号外,FileRepository::open(platform/event-log/src/checkpoints/repository/files.rs)不应该直接 include_str!("../../../migrations/0040_checkpoint_repository.sql") 当作自己的 version: 1,再从 migrations/repository/0002_heads.sql 引 version: 2。把两个独立 SQLite 数据库的 schema 演进绑在同一个 SQL 文件上很脆弱,而且目前导致两边在同名同列 checkpoint_repository_settings.configuration_json 里塞了两种完全不同的 JSON 结构(root.sqlite 存的是 Configuration 枚举对象,而 repository.sqlite 存的是裸 UUID 字符串)。建议给 migrations/repository/ 拆出独立的 0001 初始 schema,并用明确的字段表达仓库 identity。
  2. 【性能】默认本地模式的快照捕获从每个新对象“1读1写1哈希”退化为“3读2写3哈希”(大文件场景实测慢 ~2.6 倍)

    • platform/event-log/src/root_store/checkpoints/objects.rs 把 Objects::link_staged 和 Objects::publish 无条件改走 ImmutableObjectStore::put(&mut dyn Read),导致默认的本地 RootStore::open 模式也丢掉了同目录树下的 hard_link 零拷贝快路径:每个刚写入 staging/ 的文件都要被重开、全量拷贝进第二个 NamedTempFile、重算第二遍 SHA-256、做第二次文件 sync_all(),并在循环内逐文件对 objects 目录执行 sync_all()。
    • 同时,正常进程内发布路径改调 repository::commit 后也会强制跑一遍 VerifiedCheckpoint::verify(此前只有崩溃恢复 resume() 才会重验保留字节),把刚由 capture 写盘校验过的整个对象闭包又全量重读、重算第三遍 SHA-256。
    • 在 rust-preview@e52c87cc3(macOS Apple Silicon NVMe)上实测默认本地 RootStore::open 捕获 10 × 10 MiB 的 workspace 文件,耗时从基线的 ~701 ms(638 / 701 / 821 ms)退化到 ~1802 ms(1710 / 1802 / 1830 ms)。此外 workspace.rs 里的 linked 标记和被掏空成 self.validate() 的 Objects::sync_objects() 也成了残留的死逻辑。
    • 建议保留本地同文件系统的零拷贝晋升路径(或直接流式写入目标对象暂存区避免二次落盘),避免对同轮刚完成捕获校验的对象重复全量扫描,并清理 linked / sync_objects 残留逻辑。
  3. 【分层】checkpoints::repository::sql 反向依赖 worker Root 私有表,且存在两个同名 repository 模块

    • platform/event-log/src/checkpoints/repository.rs 模块注释声明其“独立于 worker Roots”,但子模块 checkpoints/repository/sql.rs 却定义了 Layout::{Local, Shared},在 Local 分支里直接读写 worker Root 私有的 session_control、history_checkpoint_bindings 和 history_checkpoint_heads 表;与此同时 root_store/checkpoints/repository.rs 也在直接操作后两张表。
    • 两个同名的 repository 模块跨层共享同一批私有表,把刚拆出来的边界又搅在一起了。建议将 worker Root 本地表操作完全收敛在 root_store::checkpoints 的 Local 适配层内,让 checkpoints::repository 保持纯粹的外部控制面契约与独立参考实现。
  4. 【实现与状态建模】FileRepository 逐次调用开闭连接、EventLog 状态拆分及辅助函数命名

    • FileRepository::run 在每次调用 lookup / bind / read_head / receipt / commit 时都会 spawn_blocking 重新打开 repository.sqlite、设 pragma、查询并反序列化 checkpoint_repository_settings,执行完立即关闭连接——单次正常 publish 就会开闭外部 WAL 数据库 3 次(bind -> receipt -> commit)。建议参考同 crate 的 OwnedConnection 维护常驻连接线程。
    • EventLog(platform/event-log/src/lib.rs)同时挂了 checkpoint_storage: Option<Storage> 和初始为 Uuid::nil() 占位哨兵的 checkpoint_agent: Uuid,与 Storage.agent 重复存了两份 agent。用单一枚举(如 Local { agent: Uuid } | Shared(Storage))表达装配后的 authority 可以消除 Uuid::nil() 非法中间态与重复字段。
    • root_store/checkpoints/repository.rs 里的 fn unavailable(error: &StoreError) -> bool 命名与注释刚好拧着:返回 true 代表材料永久损坏/缺失(推进到 Unavailable 终态),返回 false 才代表底层临时不可用(保留 Prepared 重试),建议改名为 is_permanent_material_error 或 corrupt_or_missing。
  5. 【后续范围确认】Storage::checkout_exact 目前仅支持单 Head 检出

    • 由于 checkpoint_repository_heads 以 session_id 为主键原地覆盖、没有独立的已提交 revision 索引表,推进到 r2 后即便磁盘上 r1 的对象与回执依然完好可验,调 Storage::checkout_exact(identity, r1.revision) 也会报错(验证期间 Head 移动同样会被拒绝)。这作为延续现有本地单 Head 行为的 PR1 可以理解,但值得明确一下后续 #1415 如果要支持在任意历史 committed revision 上检出/Fork,还需要补上持久化的 revision 索引而不能只靠过滤当前 Head。

@ARE404 ARE404 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I reproduced the migration collision by merging 4ef96e9 onto the current rust-preview and running the composed migration test: it fails with UNIQUE constraint failed: _sqlx_migrations.version. Please allocate the next unused migration version and cover fresh initialization plus upgrade/reopen on the current target branch.

Storage::checkout_exact also verifies object integrity without verifying that the returned Manifest belongs to the requested logical Session’s persisted Binding. A valid but swapped Head can therefore return another Session’s history. Please expose the Binding on the read path, compare the Manifest source before returning it, and add a swapped-Head regression test.

I also agree that the repeated local-path copying/hashing and the Root-private SQL ownership should be resolved before merge.

let objects = self.objects.clone();
let reference = head.manifest.clone();
let (manifest, snapshot) = tokio::task::spawn_blocking(move || {
let verified = VerifiedCheckpoint::verify(objects.as_ref(), reference)?;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[P1] Verify the Manifest belongs to the requested logical Session

VerifiedCheckpoint::verify proves the object closure is intact, but this checkout path never compares the Manifest’s {root_id, scope, session_id} with the persisted Binding for identity. If a valid Head is associated with the wrong logical Session (for example through control-plane corruption or a faulty replaceable repository implementation), this returns another Session’s history instead of failing closed. Please have the read path expose the Binding/source, validate the Manifest against it before returning, and cover a swapped-Head case.

@github-actions github-actions Bot added the effort/XXL Over 2500 readable lines label Nov 16, 2026
@MicroGery
MicroGery force-pushed the codex/rust-session-repository branch from 4ef96e9 to d91cbae Compare November 16, 2026 08:04
Add stable logical Session bindings, pluggable immutable object and repository ports, and a durable independent reference adapter. Route existing checkpoint publication and reads through the selected authority, preserve original commit receipts, and cover failure, concurrency and upgrade boundaries.

Generated-by: Codex
…e efficiency

Return the persisted Binding with each repository Head and reject Manifest
provenance mismatches on exact checkout. Separate external repository schema
and connection ownership from Root storage, and allocate migration 42 after
Rooms and history tool metadata in the composed product catalog.

Promote verified local staging without another copy and carry its verification
through fresh publication. Keep full verification on recovery and shared paths,
with regressions for swapped material, corrupt deduplication and recovery.

Generated-by: Codex
@MicroGery
MicroGery force-pushed the codex/rust-session-repository branch from d91cbae to bff94de Compare November 16, 2026 08:08

@Astro-Han Astro-Han left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I rechecked the migration numbering at bff94deb2018b9e5af7de0cd3ce6f9331b9a96bd. The collision reported in my earlier review is fixed: the checkpoint migration now uses version 42, after Rooms at 40 and history tool metadata at 41. I no longer hold that migration P2 against this revision.

I read the catalog declarations, migration SQL, product composition and migration-runner checksum/ledger logic, and extracted their exact sources from the static merge with rust-preview@074c1ebd7004ddda606613fe4529009c00c73eaf. In controlled SQLite executions, the current base, this PR alone, a fresh merged catalog, and an upgrade from the current base all succeeded. Changing only the checkpoint catalog entry back to 41 made the fresh merged database fail on the duplicate ledger version and made the upgrade fail on the previously applied checksum. This checks the actual SQL and ledger identities; I did not execute Rust migration::run, RootStore, or a real Host upgrade.

The intermediate d91cbaef revision still collided at 41 after history metadata landed. That intermediate failure does not apply to this revision. The latest range comparison moves the checkpoint SQL and declaration to 42 and includes the current history-metadata baseline.

This follow-up resolves the numbering finding. I have not completed independent verification of the full 24-file repository implementation, multi-process publication and recovery, source removal, or platform behavior. The author's Mac execution results remain the author's results. The static merge succeeds; current hosted checks are still pending completion.


Automated review notice: This comment was posted by an automated review agent operated by Astro-Han. It is not an independent human review and does not replace one.

…identity in tests

Update `checkpoint_repository` test fixtures after apache#6941 removed
`WorkspaceCapture::identity`.

Generated-by: Antigravity
@M4n5ter
M4n5ter merged commit af64a31 into apache:rust-preview Nov 16, 2026
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

effort/XXL Over 2500 readable lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants