Skip to content

fix(storage): authenticate durable migration receipts (#2708) - #2708

Merged
Sinity merged 4 commits into
masterfrom
feature/fix/authenticated-backup-receipts
Jul 11, 2026
Merged

Sinity merged 4 commits into
masterfrom
feature/fix/authenticated-backup-receipts

Conversation

@Sinity

@Sinity Sinity commented Jul 11, 2026 •

Copy link
Copy Markdown
Owner

Summary

Authenticate durable-tier migration authority with per-tier HMAC receipts, exact scratch-restore evidence, and a closed recursive backup inventory. Migration now fails closed before SQL unless the backup remains an independent, byte-exact copy of the live tier it protects.

Problem

The durable migration runner accepted a hand-written manifest containing only a format token and tier name. The rejected intermediate repair added public hashes but still allowed anyone with the backup bytes to fabricate a success receipt. Independent review then reproduced four further recoverability failures: artifact A could be paired with live fingerprint B, backup tiers could alias the live inode, an unbound SQLite WAL could change logical contents without changing the main-file hash, and auxiliary/undeclared files were outside receipt authority.

Solution

  • Add a versioned, domain-separated HMAC attestation per durable tier, using an independently derived 0600 key outside the backup.
  • Checkpoint each tier, acquire the SQLite writer lock, detect and retry writes in the checkpoint-to-lock gap, then fingerprint and copy under that lock.
  • Scratch-restore every included SQLite tier and resolve the exact referenced/reserved blob set before issuing a receipt.
  • Bind manifest bytes, every tier, every blob, source fingerprints, and a closed recursive inventory of all bundle paths.
  • Require contained, single-link regular files with real directory ancestry; reject aliases to the live tier, links, special files, and SQLite sidecars.
  • Revalidate once before locking and again under BEGIN IMMEDIATE before executing migration SQL.
  • Report the accepted receipt on the maintenance CLI and reconcile schema/durable-window documentation and Beads authority.

The local key protects against artifact-only fabrication and accidental transplant. It is not a privilege boundary against arbitrary hostile code already running as the same Unix user.

Acceptance Criteria

  • AC1 satisfied: unverified and failed-verification backups emit no successful receipt and execute no migration SQL.
  • AC2 satisfied: receipts are issued only after scratch restore, SQLite integrity checks, exact blob resolution, and post-verify byte revalidation.
  • AC3 satisfied: missing/failed/wrong-tier/unsupported/transplanted/changed artifacts, source drift, aliases, sidecars, undeclared files, and all blob mutation classes fail before SQL.
  • AC4 satisfied: mutation-style tests block SQL on negative paths and fail when authentication, snapshot retry, alias rejection, sidecar rejection, or closed-world inventory enforcement is removed.
  • AC5 satisfied: the final candidate was exercised against a scratch v4 archive with the production symlink topology; unverified and one-byte-tampered backups stayed at v4, while a fresh verified receipt migrated v4 to v5 and passed integrity/table checks.

Verification

  • devtools test tests/unit/daemon/test_backup.py tests/unit/storage/test_durable_migrations.py tests/unit/cli/test_archive_maintenance_cli.py
    • 96 passed in 222.20s
  • devtools verify --quick
    • 13/13 steps passed; pre-push run 20260711T152226Z-quick-338134-beee644d
  • .agent/scripts/bd-graph-lint
    • no cycles; zero duplicate labels, inversions, or missing ACs
  • Final scratch CLI proof:
    • missing receipt: exit 1, user version 4
    • tampered tier byte: exit 1, user version 4
    • fresh receipt: applied [5], integrity ok, both v5 tables present
    • receipt inventory: exactly manifest.json and user.db; user attestation present; key mode 0600

Adversarial Review

Five independent iterations converged:

  1. Found artifact/source fingerprint cross-equality gap; fixed at issuance and migration.
  2. Found symlink/hardlink live-tier aliasing; fixed with real-file containment and inode independence.
  3. Found unbound SQLite sidecars; fixed with sidecar rejection and immutable artifact reads.
  4. Found non-closed auxiliary file evidence; fixed with the recursive signed inventory.
  5. No legitimate gaps found on the final diff.

Ref polylogue-8jg9.5

Summary by CodeRabbit

  • New Features

    • Added cryptographically authenticated backup verification receipts for durable-tier migrations.
    • Added stronger backup integrity checks, including artifact, fingerprint, sidecar, and blob-inventory validation.
    • migrate-tier now requires verified backups and reports the validated receipt.
    • Added User schema version 5 with durable context-delivery receipts.
  • Bug Fixes

    • Prevented migrations from proceeding with missing, forged, tampered, stale, or mismatched backup evidence.
  • Documentation

    • Clarified backup, vacuum, schema migration, and rollback procedures, including required maintenance windows and recovery steps.

Sinity added 3 commits July 11, 2026 15:49
Problem: durable-tier migrations trusted backup manifests that only proved JSON shape and included tier names. A hand-written or failed/unverified backup manifest could authorize irreversible source/user migrations.

What changed: backup verification now writes a success-only receipt after scratch restore, integrity checks, and blob resolution pass. The receipt binds manifest bytes, copied tier artifacts, live source fingerprints, and the ordered blob inventory. The durable migration runner revalidates that receipt, checkpoints and fingerprints the live tier, and refuses missing, failed, stale, wrong-tier, or tampered evidence before loading migration SQL. The CLI reports the receipt path used for migration.

Verification: uv run ruff format --check polylogue/daemon/backup.py polylogue/storage/sqlite/migration_runner.py polylogue/cli/commands/maintenance.py tests/unit/daemon/test_backup.py tests/unit/storage/test_durable_migrations.py tests/unit/cli/test_archive_maintenance_cli.py; uv run ruff check same paths; uv run mypy same paths; uv run python -m devtools test tests/unit/storage/test_durable_migrations.py; uv run python -m devtools test tests/unit/daemon/test_backup.py; uv run python -m devtools test tests/unit/cli/test_archive_maintenance_cli.py.

Ref polylogue-8jg9.5
Problem: receipt validation could race concurrent SQLite writes, and a\nsuccess receipt could be assembled from bytes that changed after scratch\nverification.\n\nWhat changed: durable snapshots now hold the SQLite write lock while\nrecording their source fingerprints and copying bytes. Receipts use\nevidence captured in the scratch restore, reject post-verification\nchanges, bind the raw blob inventory file, and validate every included\ntier artifact. Migrations validate once before locking and again under\nthe lock before executing migration SQL.\n\nVerification: focused backup, durable-migration, and archive-maintenance\nCLI tests; exact-path Ruff and mypy; scratch CLI verified-success,\nunverified-rejection, and one-byte-tamper-rejection flows.\n\nRef polylogue-8jg9.5
Problem: a locally fabricated or transplanted backup manifest could
authorize an irreversible durable-tier migration without proving that the
backup had been restored, checked, or remained an independent copy of the
live database.

What changed: verified backups now emit per-tier HMAC attestations over a
closed file inventory, exact tier/blob evidence, and the quiesced live
fingerprint. Snapshotting closes the checkpoint-to-lock WAL race.
Verification and migration reject changed, linked, aliased,
sidecar-backed, or undeclared artifacts before migration SQL, with a
second validation under BEGIN IMMEDIATE.

The operator surface reports the accepted receipt, schema documentation
now reflects durability-keyed migrations, and the next durable window
targets user v6/source v8 after user v5 was consumed.

Verification: 96 focused backup/migration/CLI tests; devtools verify
--quick (13/13); scratch symlink-layout CLI proof for unverified reject,
tamper reject, and verified user v4 to v5 success.

Ref polylogue-8jg9.5
@Sinity Sinity changed the title fix(storage): authenticate durable migration receipts fix(storage): authenticate durable migration receipts (#2708) Jul 11, 2026
@coderabbitai

coderabbitai Bot commented Jul 11, 2026 •

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@Sinity, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 43 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

Run ID: 3044c9ad-38b7-41ce-8cba-77aad25faac3

📥 Commits

Reviewing files that changed from the base of the PR and between 763c912 and b5ab5c1.

📒 Files selected for processing (1)
  • tests/unit/storage/test_durable_migrations.py
📝 Walkthrough

Walkthrough

Durable backups now generate authenticated verification receipts containing filesystem, SQLite, tier-fingerprint, and blob-inventory evidence. Durable migrations validate these receipts against live tiers, while CLI output, documentation, topology metadata, and tests reflect the new workflow.

Changes

Authenticated durable migration flow

Layer / File(s) Summary
Per-tier attestation authority
polylogue/storage/backup_attestation.py
Adds per-tier key management, canonical receipt signing, and strict HMAC verification.
Verified backup evidence
polylogue/daemon/backup.py, polylogue/storage/blob_integrity.py, devtools/build_topology_projection.py, docs/daemon.md, docs/plans/topology-target.yaml, docs/topology-status.md
Creates checkpointed SQLite snapshots, fingerprints, artifact inventories, blob evidence, and atomically written verification receipts while rejecting aliases, sidecars, and invalid filesystem entries.
Receipt-gated durable migrations
polylogue/storage/sqlite/migration_runner.py, polylogue/cli/commands/maintenance.py, docs/schema.md, docs/internals.md, docs/maintenance.md, .beads/issues.jsonl
Authenticates and reconciles receipts before and during additive migrations, returns the receipt path, exposes it through the CLI, and updates schema, recovery, and coordination specifications.
Receipt and tamper validation
tests/unit/daemon/test_backup.py, tests/unit/storage/test_durable_migrations.py, tests/unit/cli/test_archive_maintenance_cli.py
Adds coverage for receipt structure, failed verification, forged authority, tampering, aliases, sidecars, races, inventory changes, and migration results.

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

Sequence Diagram(s)

sequenceDiagram
  participant BackupCLI
  participant backup_archive
  participant AttestationAuthority
  participant migration_runner
  participant LiveTier
  BackupCLI->>backup_archive: create and verify backup
  backup_archive->>AttestationAuthority: sign verification receipt
  AttestationAuthority-->>backup_archive: authenticated receipt
  migration_runner->>LiveTier: checkpoint and quiesce
  migration_runner->>AttestationAuthority: verify receipt for live tier
  migration_runner->>LiveTier: apply additive migration
Loading

Possibly related PRs

  • Sinity/polylogue#2534: Updates the durable-tier migration machinery that this receipt-gated flow extends.
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: authenticating durable migration receipts.
Description check ✅ Passed The description largely matches the template with clear Summary, Problem, Solution, and Verification sections; only Changelog and Risks are missing.
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 unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/fix/authenticated-backup-receipts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

github-actions Bot pushed a commit that referenced this pull request Jul 11, 2026
Build the forged-MAC fixture from the SHA-256 public key identifier and public attestation constants instead of copying fields from a trusted receipt object. This preserves the real MAC-verification path without presenting receipt metadata to CodeQL as clear-text secret storage.\n\nVerification: forged-receipt tests (2 passed); devtools verify --quick (13/13).\n\nRef polylogue-8jg9.5
@Sinity
Sinity merged commit a21b907 into master Jul 11, 2026
14 checks passed
@Sinity
Sinity deleted the feature/fix/authenticated-backup-receipts branch July 11, 2026 15:33
@github-actions github-actions Bot mentioned this pull request Jul 11, 2026

@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

Caution

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

⚠️ Outside diff range comments (1)
polylogue/daemon/backup.py (1)

276-297: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Disk-space headroom ignores the blob store.

needed is computed purely from tier .db/.db-wal sizes, but scratch verification (_copy_backup_artifact_to_scratch) copies the entire backup directory including blob/. For attachment-heavy archives where blobs dominate total size, this warning will understate required free space, risking disk exhaustion mid-backup or mid-verify without any prior warning.

🐛 Proposed fix
         db_size = 0
         for path in _profile_archive_tiers(root, profile).values():
             if path.exists():
                 db_size += path.stat().st_size
                 wal = path.with_suffix(".db-wal")
                 if wal.exists():
                     db_size += wal.stat().st_size
+        blob_root = root / "blob"
+        if blob_root.is_dir():
+            db_size += sum(f.stat().st_size for f in blob_root.rglob("*") if f.is_file())
         # Leave headroom beyond the two simultaneous file sets.
         needed = int(db_size * 2.5)

Note this walk adds I/O cost proportional to blob-store size for what's just a prerequisite estimate; a cheaper directory-size proxy may be preferable if that matters for very large stores.

🤖 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 `@polylogue/daemon/backup.py` around lines 276 - 297, Update the disk-space
calculation in the backup headroom check to include the backup directory’s blob
store alongside tier database and WAL sizes, matching the full directory copied
by _copy_backup_artifact_to_scratch. Use an appropriate blob-size estimate that
preserves the warning’s purpose, while keeping the existing headroom and
free-space comparison behavior unchanged.
🤖 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 @.beads/issues.jsonl:
- Line 252: Reconcile the open polylogue-rxdo.2 rider with the user-v6 window:
retarget it to schema:user-v6 and update its migration target if
implementation-ready, or explicitly defer/close it and remove its dependency on
polylogue-60i5. Ensure no active dependency or rider remains labeled
schema:user-v5 or targeting v4→v5 before declaring the window.

In `@polylogue/daemon/backup.py`:
- Around line 961-971: Update the authority_paths construction before
sign_verification_receipt to include every tier_artifacts entry with a valid
source_fingerprint.path, rather than restricting tiers to source and user.
Inspect migrate_archive_tier and ArchiveTier to confirm which tiers can reach
the receipt-gated migration path, preserving attestation coverage for all
durable tiers such as embeddings.
- Around line 306-339: The _backup_sqlite retry loop should handle transient
SQLITE_BUSY failures from _checkpoint_sqlite_for_snapshot instead of aborting
immediately. Catch the checkpoint RuntimeError within each
_SNAPSHOT_LOCK_ATTEMPTS iteration and continue to the next attempt, while
preserving propagation of non-transient errors and the existing WAL-growth retry
behavior.

---

Outside diff comments:
In `@polylogue/daemon/backup.py`:
- Around line 276-297: Update the disk-space calculation in the backup headroom
check to include the backup directory’s blob store alongside tier database and
WAL sizes, matching the full directory copied by
_copy_backup_artifact_to_scratch. Use an appropriate blob-size estimate that
preserves the warning’s purpose, while keeping the existing headroom and
free-space comparison behavior unchanged.
🪄 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

Run ID: 29aa5c4a-d0c3-4ed1-986a-0ac37a1bbc56

📥 Commits

Reviewing files that changed from the base of the PR and between 6e74b2c and 763c912.

📒 Files selected for processing (16)
  • .beads/issues.jsonl
  • devtools/build_topology_projection.py
  • docs/daemon.md
  • docs/internals.md
  • docs/maintenance.md
  • docs/plans/topology-target.yaml
  • docs/schema.md
  • docs/topology-status.md
  • polylogue/cli/commands/maintenance.py
  • polylogue/daemon/backup.py
  • polylogue/storage/backup_attestation.py
  • polylogue/storage/blob_integrity.py
  • polylogue/storage/sqlite/migration_runner.py
  • tests/unit/cli/test_archive_maintenance_cli.py
  • tests/unit/daemon/test_backup.py
  • tests/unit/storage/test_durable_migrations.py

Comment thread .beads/issues.jsonl
{"_type":"issue","id":"polylogue-37t.16","title":"Claim-kind -\u003e allowed grounding-class compatibility registry","description":"The generalized recovery-digest fix as a small declarative registry: each claim kind declares which anchor classes can prove it (pr_merged: external_pr | git_commit | tool_result, never agent_session/transcript-quote; assistant_said: raw transcript IS correct grounding; command_outcome: tool_result/exit-code keystone; decision_made: human_message | human_judgment). The verdict computation consults it to set compatible_claim per anchor. Without this, the closed-loop gate is a checkbox — any external-ish ref would release any claim.","design":"Registry rows next to the measure-registry discipline (9l5.7 sibling — a claim kind is an operationalization with validity metadata). Closed vocabulary in code, versioned; unknown claim kinds get the most restrictive class set. Wire into the citation-anchor resolver.","acceptance_criteria":"Compatibility matrix is table-driven + tested; a transcript anchor sets compatible_claim=0 for pr_merged and 1 for assistant_said; verdicts change accordingly. Verify: focused resolver tests.","notes":"[Delivery upgrade 2026-07-07T00:05:00Z] Release=D-agent-context-coordination; lane=agent-coordination; readiness=D-horizon-ready; proof=two-agent separate-worktree proof with before/after coordination envelopes. Original readiness=D-horizon-ready.","status":"open","priority":2,"issue_type":"task","owner":"[email protected]","created_at":"2026-07-05T23:31:00Z","created_by":"Sinity","updated_at":"2026-07-08T20:14:31Z","labels":["area:context","area:substrate","delivery:D-agent-context-coordination","horizon:mid","lane:agent-coordination","tech-tree"],"dependencies":[{"issue_id":"polylogue-37t.16","depends_on_id":"polylogue-37t","type":"parent-child","created_at":"2026-07-06T01:31:00Z","created_by":"Sinity","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
{"_type":"issue","id":"polylogue-37t.14","title":"Recursive-safety substrate: citation anchors, provenance edges, grounding verdicts (closed-loop/cycle/drift)","description":"THE load-bearing safety invariant for a self-ingesting archive (browser capture auto-ingests the operator R\u0026D chats; distilled findings become assertions; assertions can inject into future context — the recovery-digest fabrication class generalizes to: an agent claim laundered through other agent claims until it re-enters context as truth). Substrate: assertion_citation_anchors (evidence ref resolved to typed anchor with grounding_class {human_message, human_judgment, tool_result, source_raw, git_commit, external_pr/issue/doc, agent_session, assertion, unknown} + COMPATIBLE_CLAIM bit + content hash pair + drift flag), assertion_provenance_edges (cites edges, quarantinable, reusing the TopologyEdgeStatus vocabulary but NOT the session_links table), assertion_grounding_verdicts (materialized by a converger stage: grounded | closed_loop | cycle | drifted | unknown via recursive CTE over the closure). KEY INSIGHT beyond the flag-level design: compatible_claim is what makes this construct-valid — a raw transcript proves \"assistant SAID X\", never X itself; a transcript anchor cannot ground a pr-merged claim. Closed-loop predicate: agent-authored claim whose closure reaches NO compatible non-drifted external grounding =\u003e quarantined from injection until an external citation or human judgment breaks the loop. Missing/uncomputable observed hash = unknown = NOT fresh (fail closed).","design":"Derived verdict tier (fail-closed when absent) + durable policy mutation on quarantine (candidate + inject:false + quarantine_reason in context_policy; NO new AssertionStatus axis — reuse candidate machinery). Cycle detection: recursive CTE with path-string membership, depth backstop; quarantined edges block auto-promotion. Drift: anchors store resolved-against hash; converger pass flags mismatches and forces inject:false + staleness.hash_drift. Promotion release function: accepted candidates do NOT inherit inject — injection is a second explicit decision (judge --accept --inject or set-policy). Too-tight guards to avoid: one compatible external anchor on SOME path suffices (not every citation); operator_command / human messages inside captured chats count as grounding for said-claims; deterministic detectors over structured tool-result evidence may rank as tool_result class.","acceptance_criteria":"The laundering scenario is structurally blocked in a test: agent assertion citing only agent sessions/assertions never appears in compiled context; adding a git/tool-result/human-judgment anchor or judging it releases it; cycle + drift each independently quarantine; a transcript-only anchor cannot release a world-claim (compatibility matrix test). Verify: focused tests over the CTE + scheduler gate fixture.","notes":"[Delivery upgrade 2026-07-07T00:05:00Z] Release=D-agent-context-coordination; lane=agent-coordination; readiness=A-implementation-ready; proof=two-agent separate-worktree proof with before/after coordination envelopes. Original readiness=A-implementation-ready.\n[Prework packet 2026-07-07] Static execution packet (anchors, mechanism, plan, tests, verification): .agent/scratch/corpus-gpt-pro-2026-07-07/prework-v2/task_packets/task_packets/172_polylogue_37t_14.md (depth: bead-localized-from-export; urgency: T2-foundation-before-feature-proof). Generated from master @ 8a975a40 2026-07-06 — verify source anchors before coding; line numbers are snapshot-relative.","status":"open","priority":2,"issue_type":"task","owner":"[email protected]","created_at":"2026-07-05T23:30:57Z","created_by":"Sinity","updated_at":"2026-07-07T13:05:25Z","labels":["area:context","area:substrate","delivery:D-agent-context-coordination","horizon:mid","lane:agent-coordination","spine","tech-tree"],"dependencies":[{"issue_id":"polylogue-37t.14","depends_on_id":"polylogue-37t","type":"parent-child","created_at":"2026-07-06T01:30:56Z","created_by":"Sinity","metadata":"{}"},{"issue_id":"polylogue-37t.14","depends_on_id":"polylogue-svfj","type":"related","created_at":"2026-07-06T01:36:15Z","created_by":"Sinity","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
{"_type":"issue","id":"polylogue-60i5","title":"Durable-tier batch coordination: one user v4-\u003ev5 and one source v2-\u003ev3 migration window","description":"Cross-cutting operational constraint (the single biggest insight across the R\u0026D specs): MANY pending designs each want a durable-tier bump — user v5: recursive-safety columns, content-variants tables, s7ae coordination messages, config-engine settings, queries/result-sets/analyses (rxdo.2, rxdo.8); source v3: compaction snapshots, ingest-fidelity fingerprints, secret-redaction tombstones, zstd blob placement. Durable migrations run behind verified backup manifests one user_version step at a time — landing them piecemeal means repeated backup+migrate ceremonies on the live 38GB archive. This bead is the COORDINATION POINT: collect the ready durable-tier changes, cut ONE numbered migration per tier per window, land together. Blocks nothing by itself; each schema:user-v5 / schema:source-v3 labeled bead should reference it and hold its migration file until a window is declared.","design":"Process: when \u003e=2 labeled beads are execution-ready, declare a window, write migrations NNN as one coherent set per tier, verify backup manifest, apply one step, run parity tests. The z7rv migration framework (closed 2026-07-04) is the runner substrate. Index-tier (v24-\u003ev25) batching is separate and cheaper (blue-green b5l removes downtime) but the same batching discipline applies — coordinate via the schema-bumps bd memory.\n[WINDOW PLAN v1 — 2026-07-08, post-ratification of ze5 + rxdo epic adjacency]\nThe first user v4-\u003ev5 window is now CONCRETELY COMPOSED of: (a) ze5 epistemic sufficiency — record_relations(record_id, relation CHECK IN supersedes|contradicts|refines|derives_from, target_ref, created_at_ms, author_ref) + record_revisions append-only shadow (record_id, changed_at_ms, old_body, author_ref) + assertions.confidence REAL NULL (epistemic kinds only, enforced in code not CHECK — kind column is open-vocab TEXT); (b) rxdo.2 analysis provenance — queries(query_hash PK, canonical_plan_json, created_at_ms), query_names(name PK, query_hash, created_at_ms), result_sets(result_set_id PK, query_hash, run_ref, grain, member_count, exactness, corpus_epoch, manifest_json), query_edges(src_query_hash, dst_ref, edge_kind); (c) s7ae coordination-message columns if s7ae.3 is execution-ready when the window opens (soft passenger — do NOT hold the window for it); (d) w8db user_settings extensions if ready (same passenger rule). WINDOW MECHANICS: one migrations/user/005_*.sql set authored together, single PRAGMA user_version step 4-\u003e5, behind verified backup manifest (z7rv runner); parity tests per table; every rider bead lands its code in the SAME release train as the migration so no half-live schema. CLASS FIELD: ze5 class taxonomy (epistemic|curation|workspace|comms) is DERIVED from kind in code (no schema column) — vocabulary doctrine, zero migration surface. PASSENGER RULE (generalizes): a window departs when \u003e=2 primary riders are execution-ready; late riders wait for v6 rather than delaying departure — window cadence beats window completeness. SOURCE v2-\u003ev3 window remains separately triggered (l4kf.2 provenance multimap + 83u riders) — do not couple the tiers.\n","acceptance_criteria":"First batch window executed with a single user-tier migration covering all ready v5 consumers; no durable migration lands outside a declared window. Verify: migration chain contiguity test + backup manifest check.","notes":"[Delivery upgrade 2026-07-07T00:05:00Z] Release=B-storage-rebuild-bytes; lane=blob-integrity; readiness=A-implementation-ready; proof=leased-blob race fixture, blob-reference resolver report, SHA-256 restore/compression proof. Original readiness=A-implementation-ready.\n[Prework packet 2026-07-07] Static execution packet (anchors, mechanism, plan, tests, verification): .agent/scratch/corpus-gpt-pro-2026-07-07/prework-v2/task_packets/task_packets/174_polylogue_60i5.md (depth: bead-localized-from-export; urgency: T2-foundation-before-feature-proof). Generated from master @ 8a975a40 2026-07-06 — verify source anchors before coding; line numbers are snapshot-relative.","status":"open","priority":2,"issue_type":"task","owner":"[email protected]","created_at":"2026-07-05T23:26:57Z","created_by":"Sinity","updated_at":"2026-07-08T18:49:29Z","labels":["area:substrate","delivery:B-storage-rebuild-bytes","horizon:frontier","lane:blob-integrity","schema:source-v3","schema:user-v5","tech-tree"],"dependencies":[{"issue_id":"polylogue-60i5","depends_on_id":"polylogue-8jg9.5","type":"blocks","created_at":"2026-07-10T18:15:06Z","created_by":"Sinity","metadata":"{}"}],"dependency_count":1,"dependent_count":0,"comment_count":0}
{"_type":"issue","id":"polylogue-60i5","title":"Coordinate the next durable-tier migration windows","description":"## Current authority (2026-07-11)\n\nDurable changes must be coordinated by the next version from the version currently shipped on master, not by stale version literals. PR #2703 consumed user schema v5 for context_deliveries outside the previously planned v4-\u003ev5 batch. Source schema is already v7. The former user-v5/source-v3 plan is therefore historical, not executable.\n\nThis bead coordinates the next declared windows: user v5-\u003ev6 and source v7-\u003ev8. Previously named riders (ze5, rxdo, s7ae, w8db, l4kf/83u) must be re-audited against current master and may join only if implementation-ready. Late riders wait for the following window rather than reopening a landed migration.","design":"Treat a window as a release train, not a permanent list of speculative tables. Before declaring it, audit all open schema:user-v6 or schema:source-v8 consumers, record exact columns/tables and owning code paths, and require at least two ready primary riders unless an independently urgent trust-floor fix justifies a single-rider exception. Source and user windows remain independent.\n\nEvery durable window uses the authenticated verified-backup receipt gate from polylogue-8jg9.5, one contiguous numbered migration step, fresh-DDL parity, per-rider behavioral tests, and one live stopped-daemon rollout proof. Schema code, migration SQL, and every rider's runtime wiring land in the same release train; a table-only or test-only rider does not count as shipped.","acceptance_criteria":"1. Reconcile every open durable-schema consumer to the current target labels (schema:user-v6 or schema:source-v8), removing stale v5/v3 assumptions and naming exact production wiring.\n2. Declare each tier window only after its ready-rider set and drop order are durable in Beads; source and user may depart independently.\n3. Land exactly one contiguous migration step per declared tier, with fresh-DDL parity and no half-live rider.\n4. Authorize and prove the rollout with an authenticated receipt from polylogue-8jg9.5; stop the daemon, migrate a copy/live tier as appropriate, verify integrity and row parity, then restart and prove schema convergence.\n5. Record the exceptional fact that user v5 was consumed by PR #2703; no remaining rider may target v5.","notes":"[Delivery upgrade 2026-07-07T00:05:00Z] Release=B-storage-rebuild-bytes; lane=blob-integrity; readiness=A-implementation-ready; proof=leased-blob race fixture, blob-reference resolver report, SHA-256 restore/compression proof. Original readiness=A-implementation-ready.\n[Prework packet 2026-07-07] Static execution packet (anchors, mechanism, plan, tests, verification): .agent/scratch/corpus-gpt-pro-2026-07-07/prework-v2/task_packets/task_packets/174_polylogue_60i5.md (depth: bead-localized-from-export; urgency: T2-foundation-before-feature-proof). Generated from master @ 8a975a40 2026-07-06 — verify source anchors before coding; line numbers are snapshot-relative.\n2026-07-11 authority repair: supersedes the stale v4-\u003ev5/source-v2-\u003ev3 window plan after master reached source v7 and PR #2703 consumed user v5 for context_deliveries. The next executable targets are user v6 and source v8; rider readiness must be re-audited rather than inherited from the old plan.","status":"open","priority":2,"issue_type":"task","owner":"[email protected]","created_at":"2026-07-05T23:26:57Z","created_by":"Sinity","updated_at":"2026-07-11T14:23:58Z","labels":["area:substrate","delivery:B-storage-rebuild-bytes","horizon:frontier","lane:blob-integrity","schema:source-v8","schema:user-v6","tech-tree"],"dependencies":[{"issue_id":"polylogue-60i5","depends_on_id":"polylogue-8jg9.5","type":"blocks","created_at":"2026-07-10T18:15:06Z","created_by":"Sinity","metadata":"{}"}],"dependency_count":1,"dependent_count":0,"comment_count":0}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

Reconcile the stale user-v5 rider before declaring the v6 window.

This entry says no remaining rider may target user v5, but polylogue-rxdo.2 at Line [255] is still open, labeled schema:user-v5, targets v4→v5, and depends on this coordination bead. Retarget, explicitly defer/close, or remove that dependency so the release-train audit cannot omit an active v5 migration consumer.

🤖 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 @.beads/issues.jsonl at line 252, Reconcile the open polylogue-rxdo.2 rider
with the user-v6 window: retarget it to schema:user-v6 and update its migration
target if implementation-ready, or explicitly defer/close it and remove its
dependency on polylogue-60i5. Ensure no active dependency or rider remains
labeled schema:user-v5 or targeting v4→v5 before declaring the window.

Comment on lines +306 to +339
def _checkpoint_sqlite_for_snapshot(conn: sqlite3.Connection, path: Path) -> None:
row = conn.execute("PRAGMA wal_checkpoint(TRUNCATE)").fetchone()
if row is None:
raise RuntimeError(f"could not checkpoint {path} before backup")
busy, log_frames, checkpointed_frames = (int(value) for value in row)
if busy or log_frames != checkpointed_frames:
raise RuntimeError(f"could not quiesce {path} before backup")


def _backup_sqlite(src: Path, dst: Path) -> tuple[int, dict[str, object]]:
"""Copy a checkpointed tier while excluding concurrent SQLite writers."""
live_path = src.resolve(strict=True)
conn = sqlite3.connect(str(live_path), timeout=30.0)
try:
_backup_db_vacuum_into(src, dst)
except sqlite3.OperationalError:
_backup_db_copy(src, dst)
return dst.stat().st_size if dst.exists() else 0
conn.execute("PRAGMA busy_timeout = 30000")
for _attempt in range(_SNAPSHOT_LOCK_ATTEMPTS):
_checkpoint_sqlite_for_snapshot(conn, live_path)
conn.execute("BEGIN IMMEDIATE")
wal_path = live_path.with_name(f"{live_path.name}-wal")
if wal_path.exists() and wal_path.stat().st_size:
conn.rollback()
continue
fingerprint = _sqlite_source_fingerprint(live_path)
try:
shutil.copy2(live_path, dst)
except Exception:
dst.unlink(missing_ok=True)
raise
return dst.stat().st_size, fingerprint
raise RuntimeError(f"could not obtain a checkpointed write-locked snapshot of {live_path}")
finally:
if conn.in_transaction:
conn.rollback()
conn.close()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect the backup code and any tests around checkpoint retries.
git grep -n "_checkpoint_sqlite_for_snapshot\|_SNAPSHOT_LOCK_ATTEMPTS\|wal_checkpoint(TRUNCATE)\|BEGIN IMMEDIATE" -- polylogue/daemon/backup.py tests/unit/daemon/test_backup.py

echo
echo "=== backup.py excerpt ==="
sed -n '300,345p' polylogue/daemon/backup.py

echo
echo "=== related tests excerpt ==="
sed -n '100,180p' tests/unit/daemon/test_backup.py

Repository: Sinity/polylogue

Length of output: 6322


🌐 Web query:

SQLite PRAGMA wal_checkpoint(TRUNCATE) busy return semantics transient writer checkpoint behavior

💡 Result:

When executing PRAGMA wal_checkpoint(TRUNCATE) in SQLite, the command follows specific lock acquisition and busy-handling semantics designed to ensure the checkpoint runs to completion [1]. Locking and Busy Handling 1. Exclusive Locks: A TRUNCATE checkpoint acquires an exclusive "checkpoint" lock on the database file, followed by an exclusive "writer" lock [1]. 2. Concurrent Checkpoints: If another process is already performing a checkpoint, the exclusive checkpoint lock cannot be obtained, and the operation immediately returns SQLITE_BUSY [1]. The busy-handler is not invoked in this specific case [1]. 3. Writer Lock and Busy Handler: If the checkpoint cannot immediately acquire the necessary exclusive "writer" lock, or if it must wait for existing database readers, the configured busy-handler is invoked [1]. The system will retry the operation according to the busy-handler (e.g., waiting for the duration of the busy_timeout) until either the lock is obtained or the handler returns 0 [1]. 4. Fallback Behavior: If the busy-handler returns 0 before the writer lock is acquired or while waiting for readers, the checkpoint operation degrades to PASSIVE mode [1]. In this state, it proceeds to checkpoint as much as possible without blocking, but it will return SQLITE_BUSY to the caller [1]. Transient Writer Behavior In the context of SQLite checkpoints, a "transient writer" typically refers to the connection performing the checkpoint operation itself as it acts to move data from the WAL file into the main database [1]. Because TRUNCATE mode requires obtaining the exclusive writer lock, this connection effectively prevents other writers from modifying the database during the checkpoint [2][1]. If the operation is unable to secure the necessary locks (due to concurrent activity that exceeds the busy-timeout), it terminates, potentially leaving the WAL file untruncated, and returns SQLITE_BUSY [1]. Therefore, the behavior is inherently blocking and requires careful configuration of busy-handlers to avoid frequent busy returns in highly concurrent environments [3][1]. Top results: [1], [3], [2]

Citations:


Checkpoint busy should stay inside the snapshot retry loop.

PRAGMA wal_checkpoint(TRUNCATE) can return SQLITE_BUSY under lock contention, but _checkpoint_sqlite_for_snapshot() raises immediately, so a transient checkpoint failure aborts _backup_sqlite before _SNAPSHOT_LOCK_ATTEMPTS can retry. Catch that failure in the loop and continue, like the WAL-growth race.

🤖 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 `@polylogue/daemon/backup.py` around lines 306 - 339, The _backup_sqlite retry
loop should handle transient SQLITE_BUSY failures from
_checkpoint_sqlite_for_snapshot instead of aborting immediately. Catch the
checkpoint RuntimeError within each _SNAPSHOT_LOCK_ATTEMPTS iteration and
continue to the next attempt, while preserving propagation of non-transient
errors and the existing WAL-growth retry behavior.

Comment on lines +961 to +971
authority_paths: dict[str, Path] = {}
artifacts = verified_evidence.get("tier_artifacts")
if isinstance(artifacts, list):
for artifact in artifacts:
if not isinstance(artifact, dict) or artifact.get("tier") not in {"source", "user"}:
continue
fingerprint = artifact.get("source_fingerprint")
source_path = fingerprint.get("path") if isinstance(fingerprint, dict) else None
if isinstance(source_path, str) and source_path:
authority_paths[str(artifact["tier"])] = Path(source_path).resolve(strict=False)
receipt = sign_verification_receipt(receipt_body, authority_paths=authority_paths)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win

Hardcoded {"source", "user"} tier allowlist for attestation authority.

Only tiers literally named source/user get an HMAC attestation attached; any other durable tier included in a profile (e.g. embeddings, which docs/daemon.md also lists as a non-rebuildable durable tier) would silently receive no attestation and later fail durable-tier migration authentication with no signal at write time.

Consider deriving authority_paths from all tiers present in verified_evidence["tier_artifacts"] that carry a source_fingerprint.path, rather than a fixed literal set, so adding a new durable tier doesn't require remembering to update this allowlist too.

Please confirm whether ArchiveTier (consumed by migrate_archive_tier) currently only ever migrates source/user, or if other tiers could reach this receipt-gated path.

🤖 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 `@polylogue/daemon/backup.py` around lines 961 - 971, Update the
authority_paths construction before sign_verification_receipt to include every
tier_artifacts entry with a valid source_fingerprint.path, rather than
restricting tiers to source and user. Inspect migrate_archive_tier and
ArchiveTier to confirm which tiers can reach the receipt-gated migration path,
preserving attestation coverage for all durable tiers such as embeddings.

Sinity added a commit that referenced this pull request Jul 17, 2026
Automated release PR opened by release-please. See
[docs/release.md](docs/release.md).
---


## [0.3.0](v0.2.0...v0.3.0)
(2026-07-11)


### Added

* **context:** persist exact delivery receipts
([#2703](#2703))
([37bdfa0](37bdfa0))
* **demos:** enforce Demo Packet v2 contracts
([#2704](#2704))
([0395f83](0395f83))
* **query:** constrain action sequence edges
([#2705](#2705))
([3926432](3926432))
* **rendering:** add semantic transcript evidence cards
([#2700](#2700))
([0f50590](0f50590))


### Fixed

* **demos:** bind packet claims to receipt bytes
([#2709](#2709))
([885b46d](885b46d))
* **devtools:** count raw artifacts in workload boundary
([#2711](#2711))
([#2711](#2711))
([5d2bd72](5d2bd72))
* **storage:** authenticate durable migration receipts
([#2708](#2708))
([#2708](#2708))
([a21b907](a21b907))

---
This PR was generated with [Release
Please](https://github.com/googleapis/release-please). See
[documentation](https://github.com/googleapis/release-please#release-please).

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: Sinity <[email protected]>
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.

2 participants