Skip to content

fix(devtools): Adjudicate every pinned census site and make the renderer total - #5393

Merged
Sinity merged 2 commits into
masterfrom
fix/adjudicate-census-sites
Sep 22, 2026
Merged

Sinity merged 2 commits into
masterfrom
fix/adjudicate-census-sites

Conversation

@Sinity

@Sinity Sinity commented Sep 22, 2026

Copy link
Copy Markdown
Owner

Summary

polylogue-1or21 plus the 159 sites both censuses pinned at unclassified. Durable-write census 138 → 134 adjudicated + 7 honestly unclassified; derived-sweep census 21 → 0 unclassified. The 9 red test_layering_gates.py tests are green (42/42). Three real findings surfaced; none was labelled to make it go away.

The renderer could not report its own census

verify_layering.py fell through to violation['file'] / violation['import'] for any rule family without a branch, and the durable_write_* family from #5377 had none. gate layering was green only because it renders on a finding — the census was armed and unable to speak.

Anti-vacuity executed: restoring the base renderer gives KeyError: 'file' and KeyError: 'import' at verify_layering.py:1016, 18 failed / 42. Both directions pinned — one test asserts imports polylogue.storage (disallow) still prints (so a generic dump fails), another parametrizes 10 census shapes asserting none lands on <no renderer for rule family> (so merely making the fall-through total also fails).

F1 — an analysis-tier materializer rewrites durable source.db behind the producers

analysis/claude_workflow_materializer.py:286-386. For every CLAUDE_CODE_SESSION raw row it re-derives artifact_kind, support_status, classification_reason, parse_as_session, schema_eligible, link_group_key from the OriginSpec taxonomy via ON CONFLICT(artifact_id) DO UPDATE, and DELETEs durable raw_artifacts rows whose content evidence disagrees with the rule.

Its own docstring says the quiet part: "the same source-tier invariant is repaired here for daemon/direct raw writers", and an inline comment records a prior incident where "the durable table ended up reflecting whichever pass ran last."

No permitted classification fits — not guarded (outside the producer), not a declared state advance, nothing re-acquired, not retention, not operator destruction. It is left unclassified with that reasoning rather than stretched into a member. masking_backfill is forbidden and was not used as a resting place.

F3 — a schema qualifier hid three durable user.db rewrites from the census, now fixed

_REWRITE_RE bound table to the ATTACH alias, so UPDATE user_tier.assertions resolved to a table named user_tier, which no tier declares. Three durable rewrites in storage/derived/feedback/__init__.py — one upsert and two SET status='deleted' — were dropped by the census that exists to enumerate them. Fixed; exactly 3 new entries appeared and all were adjudicated. That is why the total is 141, not 138.

Residual noted: those three bypass upsert_assertion, the declared write chokepoint. Benign today because CORRECTION is not in ASSERTION_CLAIM_KINDS — worth a design note if that changes.

F2 / F4 — recorded, not fixed here

  • excision_policy_projections is invisible to the census because it is created by a runtime CREATE TABLE IF NOT EXISTS in a function body, so durable_table_tiers() returns None and its upsert is dropped before classification. That upsert retro-rewrites what an already-published generation claims it excluded — exactly what j264r's design forbids. Sequencing note: fix(schema): Register excision_policy_projections in canonical source DDL #5387 moved the DDL, so the census will now see it and will need a verdict.
  • Neither vocabulary has a member for a censused statement that provably cannot rewrite a durable row — five entries sit at the floor for that reason alone, including UPDATE assertions SET updated_at_ms = updated_at_ms WHERE 0, which exists only to force a RESERVED lock.

A reproduction that did NOT hold

daemon/status.py::build_daemon_status::overall_status was named as a likely finding. It does not reproduce: the only substitution is fail-closed — a collected HealthSeverity.OK is escalated when its snapshot is unavailable/timed-out/degraded, with a named alert. It can never report clean for a collector that did not complete.

Verification

devtools test test_layering_gates.py (base)     FAILED 9/42, KeyError
devtools test test_layering_gates.py (branch)   PASSED 42/42
devtools gate layering                          exit 0, violations 0
devtools verify --quick                         exit 0, 25/25
devtools render all --check                     exit 0, 'out of sync' 0
devtools schema closure (6 files)               all 'out' — no identity movement

🤖 Generated with Claude Code

https://claude.ai/code/session_01ToWqpkXotr573DiQex5vcy

Sinity and others added 2 commits September 22, 2026 07:36
`_format_violation` fell through to `violation['file']` / `violation['import']`
for any rule family without a branch. The `durable_write_*` and
`caller_supplied_sql_*` families from #5377 report declaration rows keyed on a
census key, not import edges, and some of their shapes carry no `file` at all
(a missing declaration; a stale helper entry). Rendering one raised KeyError
and took the whole plaintext report down with it, so an armed census could not
report a finding and 9 tests in tests/unit/devtools/test_layering_gates.py were
red at master.

One branch now covers every declaration-census family, the import fall-through
only fires when the violation actually carries an import edge, and the terminal
fall-through names the missing renderer and dumps the payload -- a future family
without a branch is loud in the report instead of crashing it or reading as if
it were understood.

`_write_ratchet_fixture` now seeds empty census declarations. Its package
executes no DML, so an empty declaration is the truthful one; without it three
ratchet tests failed on an unrelated missing declaration rather than on the
import property they are about.

Verification:
  devtools test tests/unit/devtools/test_layering_gates.py -> 42 passed
  Reverting _format_violation alone: 18 failed, including
  `KeyError: 'file'` and `KeyError: 'import'` at verify_layering.py:1016.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01ToWqpkXotr573DiQex5vcy
Both structural censuses landed with an honest floor: 138 of 138 durable-write
entries and 21 of 27 derived-sweep entries sat at `classification: unclassified`
with the reason "pinned by the initial census". That kept the gate green without
asserting any site was legitimate. This replaces the floor with read verdicts.

Every entry was decided by reading the call site and grouped by the actual
pattern, not by file. Durable writes: 69 lifecycle_transition (guarded declared
state machines -- audit mutation authority, revision governance, GC generations,
publication obligations), 23 row_supersession (content-keyed rows and receipts
replaced wholesale by re-observing unchanged evidence), 22 deliberate_redaction
(session and query excision), 9 declared_retention, 8
guarded_producer_refinement (NULL/placeholder fills guarded in the WHERE), 2
two_phase_recovery, 1 test_or_fixture_construct. Derived sweeps: 9
producer_scoped_transaction, 6 presentation_projection, 5 declared_retention, 4
whole_relation_derivation, 2 bounded_key_publication, 1 operator_mutation.

Seven durable entries stay `unclassified` on purpose, each with a reason saying
why no permitted member fits. Two are the finding this census exists to surface:
`analysis/claude_workflow_materializer.py::_ensure_current_artifact_inventory`
re-derives raw_artifacts classification for every Claude raw and deletes rows
whose content evidence disagrees, from the analysis tier, outside the
acquisition writer that owns those columns -- its own docstring calls it a
repair for "daemon/direct raw writers". Five are a vocabulary gap: statements
that provably cannot rewrite a durable row (four whose table is a parameter
every caller binds to an index-tier name, and one `WHERE 0` lock-acquisition
write), for which every legitimacy member would assert a rewrite that does not
happen.

The durable census also could not see a schema-qualified table: `UPDATE
user_tier.assertions` bound `table` to the ATTACH alias, so three durable
user.db rewrites in storage/derived/feedback were dropped by the census that
exists to enumerate them. The verb pattern now treats the qualifier as part of
the reference; those three sites are censused and adjudicated.

Verification:
  devtools gate layering -> exit 0, 0 violations
  devtools verify --quick -> exit 0, 25/25 gates
  devtools render all --check -> exit 0, 0 "out of sync"
  schema closure: all six changed files report `out`

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01ToWqpkXotr573DiQex5vcy
@coderabbitai

coderabbitai Bot commented Sep 22, 2026

Copy link
Copy Markdown

Warning

Review limit reached

Next included review available in 27 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available.

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Learn how review limits work.

Review configuration:

⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Advanced

Run ID: bfa719cd-e31c-481a-8cb9-1c6e6fc85341

📥 Commits

Reviewing files that changed from the base of the PR and between 9f450db and 7f352d7.

📒 Files selected for processing (6)
  • devtools/derived_sweep_census.py
  • devtools/durable_write_census.py
  • devtools/verify_layering.py
  • docs/plans/derived-sweep-census.yaml
  • docs/plans/durable-write-census.yaml
  • tests/unit/devtools/test_layering_gates.py

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.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 22, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-22T05:50:08.243090Z 7f352d7 PR opened
🔒 Security Review ✅ Completed 2026-09-22T05:46:02.313558Z 7f352d7 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@Sinity
Sinity enabled auto-merge (squash) September 22, 2026 05:36
@Sinity
Sinity merged commit f2f1422 into master Sep 22, 2026
3 checks passed
@Sinity
Sinity deleted the fix/adjudicate-census-sites branch September 22, 2026 05:48

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 7f352d7059

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread docs/plans/durable-write-census.yaml Resolved
Comment thread docs/plans/durable-write-census.yaml Resolved
Comment thread devtools/derived_sweep_census.py Resolved
Sinity added a commit that referenced this pull request Sep 22, 2026
…5400)

## Summary

`polylogue-r29bv` AC3, asserted by `gjwto`/`re6s3`. `polylogue
annotations import` was **the last CLI-invisible durable writer** — it
drove `OperationExecutor` against `user.db` in-process. It now goes
through a declared daemon operation, and the CLI-mutation-authority
baseline shrinks 3 → 2.

## A real bug the work surfaced

Driving the actuator's `async def import_annotation_batch` from a
synchronous handler with a bare `asyncio.run(...)` **mints a new asyncio
task and loses the write lease**, which is bound to the calling
thread/task — `UnleasedWriteError`, confirmed by direct reproduction.

That is the same property #5382 recorded from the other side:
`write_lease` binds `owner_task_id`/`owner_thread_id` at **mint time**.
Fixed with the declared `delegate_write_lease()`/`adopt_write_lease()`
handoff — the existing `write_coordinator.py` pattern, not a new one —
and verified end to end against a real daemon stack (session written,
audit row present).

## A gap it exposed by keeping a test honest

Adding a 12th CLI-bound mutating operation tripped `re6s3` AC4's
coverage test. Fixing *that* surfaced an independent defect:
**`annotations import` had no `--format` option at all**, so the
machine-format daemon-down check failed on Click's own `--format json`
before ever reaching the daemon probe. Added `-f/--format text|json`,
defaulting to `json` so every existing caller is unaffected.

The lane could have exempted the new operation from the matrix. It
extended the matrix instead, which is why the missing flag was found.

## Verification

```
devtools test test_annotation_import_command.py            3 passed
devtools test <+ test_cli_operation_authority.py>         33 passed
devtools test <10 modules>                     87 passed, 9 failed
devtools verify --quick        25/25 ok (run once per commit)
devtools render all --check    exit 0, zero 'out of sync'
devtools schema closure        every changed file OUT — no rebuild implication
```

All 9 failures are in `test_layering_gates.py` (`KeyError: 'file'`, the
`durable_write_census` renderer gap). Confirmed inherited: `git diff
--stat HEAD --` over the three implicated files is **empty** — none was
touched. That is `polylogue-1or21`, fixed in #5393.

**Anti-vacuity executed:** reverted `annotations.py` to the in-process
writer, ran `test_annotations_import_refuses_without_a_daemon` → real
failure (`assert 0 != 0`; the row imported **with no daemon running**),
restored, re-ran → 3 passed.

## `d02y8` deliberately not implemented — and its bead contradicts
itself

The bead carries a 2026-09-20 note recording *"DECISION RESOLVED
(coordinator): the daemon DOES hold the provider credential"* with
reasoning, and a later 2026-09-22 scoping note saying *"NOT
DISPATCHABLE: an operator policy decision a worker must not answer"* —
apparently written against the stale DESIGN section rather than the
resolution above it.

The lane treated neither as authorization and made no credential choice.
The three options and the implementation path under (a) are recorded on
the PR for whoever rules.

## Residuals

- `gjwto` AC6 asks to reopen/supersede `polylogue-5vps8.2`, which is
**closed on a reason resting on a baseline the extended rule now proves
could not see facade-routed writes**. A Beads action for the
coordinator.
- `gjwto` AC1/AC2 stay blocked on decision D2:
`_execute_facade_mutation` still has **20 call sites**, and the 2
surviving baseline entries are both `polylogue/api`.
- `re6s3` AC3's `pipeline/services/archive_ingest.py` and the
direct-tier-writer list (embed backfill, scan-secrets, backup, demo,
archive-init, blob-*) were out of the collision boundary and untouched.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

https://claude.ai/code/session_01ToWqpkXotr573DiQex5vcy

---------

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
Sinity added a commit that referenced this pull request Sep 22, 2026
The watch-clearing UPDATE moves out of register_query_watch so delete_view
and the rename route can retire a stale binding in their own transaction.
register_query_watch now delegates rather than writing, so its census key is
stale and clear_query_watch's write is undeclared -- `gate layering`
reported exactly that pair (durable_write_census_stale +
durable_write_undeclared) before this commit.

#5393 adjudicated this entry to lifecycle_transition in the meantime; that
classification and reason are kept verbatim apart from naming the owner the
statement actually lives in. Same statement, same guard
(`WHERE name = ? AND watch = 1`), same table, one owner.

`devtools gate layering` -> exit 0, violations 0.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01ToWqpkXotr573DiQex5vcy
Sinity added a commit that referenced this pull request Sep 22, 2026
…tier (#5408)

## Summary

Seventeen live P1 review findings closed across the storage tier,
consolidating two review lanes that were dispatched over overlapping
finding sets. Supersedes #5406, whose six non-overlapping fixes are
cherry-picked here with `-x` attribution.

## Problem

A `git blame` filter over the review backlog selected 80 storage P1
findings whose anchored line had not moved since review. Full triage at
HEAD: **49 LIVE, 27 STALE, 4 WONTFIX** — the filter over-selects by ~34%
in this area, with no detectable false negative. Its failure mode is
exactly as predicted: heavy refactors move code without touching the
anchored line (`bootstrap.py` was 6-for-6 stale after its rewrite), and
the durable-lineage reset invalidated the whole v37/v40 migration
family.

Two lanes worked this set concurrently and independently fixed three of
the same defects. Landing both would have meant a 12-commit rebase
across three shared files, so they are consolidated here instead.

## Solution

**Reads and cost**

- `archive_query_reads.py` ranked the entire partition before applying
`unit_rank <= ?`. Measured at base on seeded archives, one 201-row page:
**427k / 813k / 1585k VDBE step units** over 2,000 / 4,000 /
8,000-message sessions — linear in partition size — against a flat 42k
for the indexed read. `_bounded_partition_message_ids` now does one
indexed `ORDER BY … LIMIT` per selected session over
`idx_messages_session_position`, merges, orders and pages the
candidates, then runs the expensive projection on the page alone.
**After: flat 47k at all three sizes.** #5381's fairness contract is
preserved — each session keeps the same allowance in its own transcript
order — and its SKEWED fixture still passes.

**Durable integrity**

- The `additive-no-backup` marker was a self-declaration nothing
checked: `_requires_migration_backup` read the header and never looked
at the statements. The finding is **declined as filed** — that
classification is operator-ratified from #2905 with its own
authorization mode, and slot 002 is one `CREATE TABLE IF NOT EXISTS`
that writes, reads and moves no row — but the unchecked claim is now
proved: a file claiming the marker must contain only `CREATE
TABLE/VIEW/INDEX`, refused by name otherwise. Slot 002 still loads
`requires_backup=False`, so no shipped behaviour changed.
- A durable tier below its recorded birth version was accepted.
Bootstrap stamps `tier_versions.source = 2`; a transplanted version-1
database cleared the floor and skipped the fingerprint because `1 != 2`.
The condition is now `version <= versions[tier]`, so the below-birth
case is decided by the recorded fingerprint rather than bypassed.
- `acquired_with_bytes_count` decided coverage with `BlobStore.exists`,
so an object overwritten at the recorded hash's path counted as coverage
with both debt counters zero and `ok` true. It now requires a re-hash,
and a present-but-contradicted object lands in a new
`acquired_corrupt_count` bucket kept **separate** from
`acquired_missing_blob_count` — the object is present, so re-fetch is
the wrong remedy.
- `additional_blob_refs` bypassed the excision ledger.

**Lineage**

- `_record_lineage_prefix_debt` resolved `ops.db` via `PRAGMA
database_list`, which SQLite answers with the *resolved* promotion
symlink, so on a promoted generation it named a nonexistent file and
returned silently. New `archive_root_for_index_path` unwinds the
generation directory; `index_generation._is_generation_member` now
delegates to it so the depth rule has one definition.
- A witness-mismatched branch point was re-anchored onto different
content. The re-anchor now applies only when the replacement's content
address matches the stored witness; otherwise the edge stays dangling,
is counted, and its child is named stranded with retryable debt. The
repairable half still re-resolves in-write.
- Recursive topology DFS hit `RecursionError` at the writer's own 1024
budget. The iterative walk handles an 1100-deep lineage, and **3000
random graphs produce identical cycle sets under both implementations**.
- A relocated lineage anchor was not reported as resolved.

**Saved views, frontier, misc**

- View rename and delete both left `query_names.watch = 1`, so one saved
view returned two watched definitions and a deleted view stayed watched.
Both bindings are cleared in the same transaction as the
upsert/tombstone.
- A content-addressed `pass_id` made `INSERT … ON CONFLICT DO NOTHING`
never reopen an acknowledged obligation whose evidence still reproduced.
Reconciliation now mints a successor derived from the row it supersedes,
so the operator's resolution receipt stays intact and repeated identical
passes converge on the same successor. A chain beyond 64 is refused by
name.
- Source blob authority is earned from the catalog, not the stamp. The
version-1 instance is stale (#5387 raised `SOURCE_TIER_VERSION` to 2),
but the collision moved with the stamp: a pre-reset database stamped
exactly 2 reproduces it today.
- EOF after a short HTTP body persisted as `acquired` instead of
`partial`; durable-writer lease checks used `self.archive_root` rather
than the declared root; an unreadable schema identity became a
non-transient skew instead of a retry.

## Conflict resolution

The two lanes' frontier fixes **diverge semantically**. #5406 reopens
the same row, keeping the original `blocker_id`; this branch mints a
successor id. Its test asserting the id is unchanged is therefore true
of its fix and false of this one, so it was deliberately **not** taken —
only the topology half of that commit is cherry-picked, with the
reasoning in the commit message.
`tests/unit/storage/test_frontier_reopen.py` pins the behaviour that
actually ships.

## Verification

Rebased onto master `17566b048` and re-verified there. Two gate failures
were found and fixed during the rebase, both described below.

- `devtools verify --quick` → **25/25 gates green** at `03bc4b0f8`
pre-rebase; re-run clean after each rebase fix.
- `devtools gate layering` → **exit 0, 0 violations** (it was red
mid-rebase; see below).
- `devtools gate atlas` → **exit 0**, "Every atlas citation and declared
owning gate resolves", 40 checkable symbol claims, **0 misaimed** (was
1).
- `devtools render all --check` → exit 0, `grep -c 'out of sync'` =
**0**, checked explicitly rather than inferred from the exit code.
- Focused batch A (7 files) → **exit 0, 40/40**. Receipt
`.cache/verify/runs/20260922T072851Z-focused-test-1387181-0795e112/`,
`git_head dc2222cbb`, not dirty.
- Focused batch B (7 files) → **exit 0, 62/62**. Receipt
`.cache/verify/runs/20260922T072855Z-focused-test-1387396-15cfa190/`.
- The delta from the tested SHA `dc2222cbb` to final head `9aa1a247b` is
`docs/atlas/daemon.md` and `docs/plans/durable-write-census.yaml` only —
both gate inputs that no test reads. Stated rather than claiming the
receipts name the tip.
- Pre-consolidation each lane established its own inherited-red baseline
by detaching at `9f450db36` and diffing failing nodeid sets
programmatically: `NEW = []`, `FIXED = []` on the durable-migration
suites (44 inherited), and an identical two-nodeid inherited set on the
daemon preflight suites. Neither absorbed nor fixed here.

### Two gates went red during the rebase

**`gate layering`.** #5393 adjudicated the `query_names` watch entry to
`lifecycle_transition` but kept the key on `register_query_watch`, which
after this branch delegates rather than writing. The gate reported
exactly that pair — `durable_write_census_stale` on the old key plus
`durable_write_undeclared` on `clear_query_watch`. The key is moved to
the owner that holds the statement; #5393's classification and reason
are kept verbatim apart from naming that owner. Same statement, same
guard `WHERE name = ? AND watch = 1`, one owner.

**`gate atlas` is red on master, not on this branch.** Both cited files
are byte-identical here to `17566b048`, and the gate reproduces the same
single misaimed anchor at either head. #5407 moved `hook_carriers` in
`intake_adapters.py` from the cited `1116-1132` to `1147-1165`, and the
symbol check that notices this is recent enough that #5407's own
verification predates it — a gate going red on master from two
separately-green PRs. The prose is still true, so the anchor is re-aimed
rather than rewritten: `FileIntakeAdapter(...,
class_name="hook_carrier")` at `:1156` and the multiplexed registration
at `:1165` still say what the sentence claims.

### Anti-vacuity, executed

Every mutation was applied, run, and reverted — not asserted:

- window rank → `allowance cost follows history: 330 -> 1199 step units
for the same 201-row allowance`
- watch bindings → `a deleted view's name is still watched` / `the
previous name is still watched beside the new one`
- ops.db root → the generation case went red while the plain-archive and
no-ops-tier cases stayed green, proving the fix is not a blanket change
- witness → `re-anchored onto a different message`, with
`test_witness_agreement_still_repairs` green under the same mutation
- attachment coverage → `a contradicted object was certified as
coverage`
- birth version → `DID NOT RAISE RuntimeError`, both opposite-direction
cases green
- source blob authority → only the `stamp_offset=0` parametrisation went
red; the other two staying green **is** the evidence the finding as
filed is stale
- frontier reopen → `assert successor_id != original_id`, both
opposite-direction cases green
- additive claim → `DID NOT RAISE MigrationError`
- excision ledger → both writers `ACCEPTED the excised sibling`, refs `0
→ 4`; after, both refuse and an admissible sibling still writes
- short body → `state=acquired retryable=False diag=''` → `state=partial
retryable=True`; correct-length and undeclared-length stay `acquired`
- topology → `RecursionError` over an 1100-deep accepted lineage
- schema identity → `SchemaSkewError … found None` →
`SchemaVersionMismatchError lifecycle_action=retry`

Every test file also pins the opposite direction, so a blanket refusal
or a no-op cannot pass.

## Schema closure

Re-measured at the consolidated head, including the cherry-picked files
the deeper lane never measured.

**IN (13):** `archive_identity.py`, `index_generation.py`,
`materials.py`, `derived/topology/derivation.py`, `sqlite/schema.py`,
`sqlite/schema_bootstrap.py`, `sqlite/migration_runner.py`,
`sqlite/query_watch.py`,
`archive_tiers/{archive,archive_plan,archive_query_reads,source_write,write}.py`
**out (4):** `maintenance/archive_verification.py`,
`operations/ref_resolution.py`, `storage/blob_integrity.py`,
`storage/raw_reconciler.py`

Membership is unchanged, so `gate schema-closure` needed no `--update`
and passes.

- `DerivedTier.index`:
`752d44b9ad5a2d0d08fdff7eababe6334575ea4223a44d60b05c41f9ea0eced2` (base
`17566b048`, measured in a detached worktree at that exact SHA) →
**`c284f2341743d8a8ac36009fe8281dfe206f04ad795c8221f3798ceb2bdd636b`**
- `DerivedTier.ops`: `86866235…` **unchanged**

The archive must reconverge. **This must land before a fresh rebuild
starts, never during one.** Both values are measured at the current base
rather than the stale one the lane first reported; re-measure again if
master moves before merge.

## Scope expansion (declared)

- `polylogue/maintenance/archive_verification.py` — the
attachment-coverage fix is inert without it; the reviewer's complaint
names the surface, so `acquired_corrupt_count` had to enter
`debt_count`, `details` and the summary, and the green wording moved
from "have bytes" to "re-hash to their recorded bytes".
- `docs/plans/durable-write-census.yaml` — moving the `query_names`
watch-clearing UPDATE into `clear_query_watch` made `gate layering` red
with one `durable_write_undeclared` and one
`durable_write_census_stale`. The commit renames exactly that one key
(same statement, same table, one owner) and is isolated as `7e38022b6`
so it can be reverted alone.
- `tests/unit/storage/test_durable_change_train.py` — three rollback
tests reached their mid-apply failure with `INSERT INTO
table_that_does_not_exist` under an `additive-no-backup` header, which
the new guard refuses at discovery. The fixture now fails additively
(two conflicting `CREATE TABLE durable_items`), raising at the same
point with an additive-only statement set and preserving every
assertion. Isolated as `fa7965cf8`.
- `polylogue/operations/ref_resolution.py` — the relocated-lineage
finding is anchored in `storage/block_anchor.py`, but the resolver is
correct; the consuming boundary that drops the state lives in
`operations/`.

## Residuals

- **Watch baseline** (#5375) reproduces and is **not** fixed.
`save_view(watch=True)` writes `queries` + `query_names` only, and
`_materialize_watch_evaluation` returns early when `baseline is None`,
so the first archive change after creation is absorbed silently. The
remedy needs scheduling the storage tier does not own: neither creation
route carries a `CanonicalPlanEvaluator` (it is injected into the daemon
stage by `make_standing_query_stage`), and calling a planner from the
substrate is a substrate→surface import the ratchet forbids outright.
`get_watched_query_baseline(...) is None` is already the durable "never
evaluated" signal, so no migration is needed for the state — only
something that drives an evaluation after creation. For the
daemon/standing-query owner.
- **FK-cascade deletion** — `_delete_sessions_without_fk_cascade`
discovers only tables with a direct `REFERENCES sessions` FK. Five
tables moved to `FOREIGN KEY(message_id, session_id) REFERENCES
messages(...)`, so with FKs suspended during bulk ingest a session
replacement commits orphaned attachment/paste/edit/web-content/action
rows. Needs a transitive closure through `messages`/`blocks`; the fix
site is in `pipeline/`.
- **Readiness** still treats an absent blocker row as proof, and
`inspect_raw_authority_frontier` has no daemon stage. This branch closes
the reopen half only.
- **Archive-root cluster** — root derived from the active index's
physical directory rather than `archive_file_set_root` also affects blob
GC, Drive catch-up, and two unleased bootstrap/adoption paths. Not
fixed: each moves a refusal on a route not exercisable without a real
daemon lease.
- `scan_attachment_coverage` now re-hashes every acquired attachment
blob on every call. `archive verify` already re-hashes the whole
namespace, but other callers were not surveyed for a cost budget; a
presence-only projection would need its own explicitly-named unverified
term, never a silent fallback.
- The `additive-no-backup` guard excludes `CREATE TRIGGER` deliberately
— it destroys nothing at apply time but arms future writes against
existing rows. A legitimately additive trigger migration is the decision
to revisit; that is a judgement call, not a measurement.
- `_iter_migration_statements` duplicates the statement-splitting logic
of `_execute_migration_sql`; they should share one splitter, kept
separate here to avoid touching the apply path in a review sweep.
- `relink_orphaned_attachments` still has no production caller.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

https://claude.ai/code/session_01ToWqpkXotr573DiQex5vcy


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

- **Bug Fixes**
- Attachment verification now detects corrupted content instead of
treating it as valid.
- Incomplete downloads are marked retryable when fewer bytes arrive than
declared.
  - Relocated references now report as resolved when valid.
  - Saved-view watches are correctly retired during rename and deletion.
- Excised attachments can no longer be reintroduced through session
imports.
- Schema read failures now receive retryable handling instead of
incorrect rebuild guidance.

- **Performance**
- Large per-session message queries use bounded reads to reduce
unnecessary database work.
  - Deep lineage processing no longer risks recursion-limit failures.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
@Sinity

Sinity commented Sep 29, 2026

Copy link
Copy Markdown
Owner Author

Closing out open Codex review threads on this PR (evidence checked against master at ef10e59):

Resolving the fixed, stale and refuted threads; tracked threads stay open.

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