Repository navigation
fix: Excise every revision of a session and name what survives - #5154
Conversation
resolve_session_excision_target seeded its raw ids from sessions.raw_id alone -- the most recently applied revision. Superseded baselines and append fragments stay live until an explicit retention run compacts them, each with its own blob_refs rows and its own content hash. An append revision is a byte-prefix of its successor but hashes differently, so the head's excised_content marker never covered the earlier bytes: excising a multi-revision session returned success and wrote an audit receipt while the earlier payloads stayed readable and freely re-ingestible. The resolver now expands its seeds to the full revision closure over the durable tier -- logical_source_key on raw_session_memberships and raw_sessions, then the predecessor_raw_id/baseline_raw_id links to a fixpoint, because those are plain TEXT with no cascade. The index's raw_revision_applications/raw_revision_heads widen the seed set as corroboration only; the durable tier stays the authority. Hook evidence is the same gap for a family the resolver cannot reach at all: hook payloads are session-addressable by (origin, session_native_id) but carry no raw_sessions row. Rather than let the operation keep reporting unqualified success, the target, plan, receipt and CLI now name them as a counted residual, and ExcisionReceipt.complete is false while any remain. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01DYUNBGoE652b3nfmq3CtqK
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
|
Warning Review limit reachedNext included review available in 27 minutes. View limit detailsLimit 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. Review configuration: ⚙️ Run configurationConfiguration used: Organization UI Review profile: ASSERTIVE Plan: Advanced Run ID: 📒 Files selected for processing (3)
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. Comment |
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
## Summary Closes the last two routes by which excised content survived. Session excision now reaches its hook evidence and its fact-tier TODO evidence, and whatever it cannot remove is named on the receipt instead of dropped. ## Problem **polylogue-bhhsa — hook evidence.** `raw_hook_events` rows are durable and session-addressable by `(origin, session_native_id)` but deliberately carry no `raw_sessions` row, so no raw target reached them. #5154 made `resolve_session_excision_target` resolve them and report them as `retained_hook_events`, but nothing deleted them: every PreToolUse / PostToolUse payload for an excised session — tool inputs and outputs, file contents, anything pasted — stayed readable in `source.db`, its `hook_event_carriers` row and `hook_payload` blob ref still rooting the blob against GC, and its hash never marked `excised_content`, so re-acquisition would restore it. **polylogue-si5kj — Claude TODO evidence.** `~/.claude/todos/*.json` plan snapshots are admitted `parse_policy='fact'`: they get their own `raw_sessions` row but mint no `sessions` row, so `sessions.raw_id` never names them and no index relation reaches them. Their only link to a session is the UUID in their own filename, resolved at read time by `analysis/claude_todo_projection.py`. Excise a session and `load_claude_todo_plan_states` still returned the agent's plan text under the excised session id — while `ExcisionReceipt.complete` reported True, since fact rows were counted nowhere. ## Solution Each route went to a different one of the three excision choke points, because the state lives in different tiers and takes different routes. **Hook evidence → excision enforcement**, in the apply's `source.db` transaction. Each resolved hook event's payload bytes are reachable through three durable coordinates (`raw_hook_events.blob_hash`, its `hook_event_carriers` rows, and the `hook_payload` blob ref keyed by the event id); all three are read *before* deletion, since a row predating the v22 `blob_hash` backfill has NULL there and would otherwise leave an unmarked, re-ingestible payload. Deletion goes through the source tier's own paired route `delete_source_hook_event` — event row, carriers and blob ref together — rather than open-coding the three deletes, and every hash found gets its `excised_content` marker. `write_source_hook_event` already refuses an excised hash, so non-resurrection follows from the marker. Not `reserve_many`: a batched flush would take unrelated attachments down with a refusal there. **Fact-tier evidence → excision reach**, in `resolve_session_excision_target`. `_session_fact_raw_ids` resolves TODO snapshots from their declared identity (the artifact rule decides the kind; `session_and_agent_id_from_filename` decides the owner, so a subagent's `<session>-agent-<uuid>.json` goes with its parent) and seeds them *before* `_durable_revision_closure` runs, so every retained revision of the same plan file is covered. The apply loop already iterated raw targets, so no deletion code changed. A fact kind whose identity is not session-derived is deliberately not matched. **Counted and observable.** `ExcisionReceipt.retained_hook_events` is now a post-condition read back after the commit — what actually survived, not what was assumed — and still drives `complete` and the CLI's `INCOMPLETE:` clause. New counts `source_hook_events` and `source_fact_rows` appear on the plan, the receipt and the dry-run preview. No fail-open `except sqlite3.Error` handler was added (`gate layering`'s `sqlite_degradation_site_added` rule is clean). ## Verification ``` devtools test tests/unit/security tests/unit/cli/test_excise.py tests/unit/operations → devtools test: FAILED exit=1 diagnosis=pytest_failed (sole failure: tests/unit/operations/test_mutation_actuators.py:: TestIdentityResetActuator::test_a_session_absent_from_the_index_is_still_tombstoned — fails identically on clean master, inherited, not touched here) devtools test tests/unit/security/test_excision_fact_evidence.py \ tests/unit/security/test_excision_revision_reach.py \ tests/unit/security/test_excision.py → devtools test: PASSED exit=0 diagnosis=pytest_passed devtools verify --quick → exit=0, all 17 gates ok (format, lint, mypy, layering, schema-manifest, atlas, …) ``` Anti-vacuity conditions, each verified by reverting and observing the red: | Guard reverted | Observed failure | | --- | --- | | `fact_raw_ids = _session_fact_raw_ids(...)` → `()` | `assert () == ('raw-todo',)` | | filename match uses the full stem, not the session-id group | `assert {'raw-todo'} == {'raw-todo', 'raw-todo-agent'}` | | hook deletion loop removed from `_apply_single_session_excision` | `assert receipt.counts["source_hook_events"] == 1` → `assert 0 == 1` | | post-commit read-back → `retained_hook_events = ()` | `assert () == ('hook-2',)` while the payload is still readable | The fact-tier test also asserts the plan text is readable *before* the excision and gone after (through the real `load_claude_todo_plan_states` read model), that an unrelated session's snapshot is untouched, and that re-acquiring either payload now raises `ContentExcisedError`. ## Schema closure ``` devtools schema closure polylogue/security/excision.py → IN devtools schema closure polylogue/cli/commands/excise.py → out ``` `polylogue/security/excision.py` is **IN** the derived closure: this moves the derived schema identity. **It must land before a fresh rebuild starts, never during one** — landing mid-run silently invalidates the seeded fixture cache. The other four PRs in this cluster carry the same constraint, and it is also the order the defect itself demands: non-resurrection must hold before the rebuild, not after. ## Residuals - The seven-route guarantee is now **complete** for excision and suppression as designed: all seven routes are fixed (#5137, #5148, #5151, #5154, and these two). No route in the cluster remains reported-but-unfixed. - Blob *bytes* are still reclaimed by the reference-counted blob GC on its next run, not force-unlinked by excision. Unchanged policy: removing the refs un-references the blob and the `excised_content` marker prevents re-ingest in the meantime. - Suppression is still not applied as a **read filter** (#5154's residual, unchanged). With the guard at the index write choke point no suppressed session can enter `index.db`, so this only matters for an archive already carrying rows resurrected by an earlier rebuild. - `_session_fact_raw_ids` covers the one admitted fact kind that carries a session-derived identity today (`todo_snapshot`). A future fact kind with session-derived identity must be added there; there is no gate that would catch its absence. - Inherited, not caused here: `tests/unit/operations/test_mutation_actuators.py::TestIdentityResetActuator::test_a_session_absent_from_the_index_is_still_tombstoned` fails identically on clean `master`. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01DYUNBGoE652b3nfmq3CtqK <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit - **New Features** - Session excision now removes associated durable hook events, carriers, and payloads. - Claude Code TODO snapshots associated with a session are included in excision. - Excision plans and receipts now report hook-event and fact-snapshot counts. - **Bug Fixes** - Prevents excised hook payloads and fact snapshots from being re-ingested. - Reports any hook events that remain readable after excision and marks the result incomplete. - **Documentation** - Added security documentation covering hook-event and fact-artifact excision behavior. <!-- end of auto-generated comment: release notes by coderabbit.ai --> Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
…ts (#5171) ## Summary Eleven unrelated failures on `master`, triaged one at a time. **Four were product defects** and are fixed here; five were stale tests, each naming the change that made it stale; two are left red with their cause established. ## Evidence Full-corpus `verify_all` on frozen `master` (`890a2921e`), job 1570, receipt `.cache/verify/runs/20260914T200510Z-all-4027943-f8bc83ff`, 22,524 selected, **147 failures with zero schema skew**. ## Per-failure classification | # | Failure | Classification | | --- | --- | --- | | 1 | `test_verified_backup_avoids_rehashing_scratch_blobs_after_validation` | **Stale test** (harness blind after #5147) | | 2 | `test_discovered_project_toml_capability_keys_are_refused_and_logged` | **Product defect** (#5134) | | 3 | `test_seed_demo_archive_creates_ready_queryable_archive` | **Product defect**, filed — **left red** | | 4 | `test_seeded_archive_fixture_resolves_through_the_registry` | Order-dependent, not reproducible | | 5 | `test_a_session_absent_from_the_index_is_still_tombstoned` | **Product defect** (inherited from #5154) | | 6 | `test_archive_ingest_large_zip_artifact_streams_to_blob_reference` | **Product defect** (#5117) | | 7a | `test_every_live_declaration...[blob-integrity]` | **Product defect** | | 7b | `test_every_live_declaration...[session-fingerprint-stamps]` | Poisoned shared cache, filed | | 8 | `test_append_plan_resynthesizes_an_append_kind_head` | **Stale fixture** (polylogue-u19l) | | 9 | `test_full_ingest_writes_archive_with_route_observability` | **Stale test** (#5049) | | 10 | `test_tier_prototype_is_atomically_published_and_restored_read_only` | Order-dependent, not reproducible | | 11 | `test_declared_devtools_route_runs_the_real_seeded_check` | **Stale test** (#5097 deleted the route) | ## The four product defects **(6) A ZIP member's bytes were dropped entirely.** #5117 correctly threaded `max_record_bytes` into the JSONL classification probe, but `scan_jsonl_session_artifact`'s oversized-record branch *synthesises* a `parse_as_session=True` classification ("uninspected oversized provider JSONL record retained for streaming parse"). That retention rule exists for a raw whose only other classifier is a weak path heuristic. Used as *positive* evidence in `_admit_non_session_zip_artifacts`, it overrode the OriginSpec-declared terminal artifact rule — so a `subagents/workflows/.../journal.jsonl` member was routed as a session, refused by polylogue-9ykn for want of positive conversational evidence, and **the bytes were lost** (`raw_artifacts=0`, `raw_sessions=0`). An inspection that read nothing has not answered the narrower question this caller asks. The path rule now stands and the skipped inspection is named via `sources.zip.artifact_probe_unbounded` — the same posture #5117 chose for its own ZIP probe ceiling. Verified outside pytest: `raw_artifacts=1`, `blob_size == len(payload)`. **(2) A refusal that would not say what it refused.** #5134 emitted `keys=rejected` (a `list`) on `config.capability_keys_refused`, but `keys` is not in the structured-log allowlist (`logging_fields.py`), so `emit` dropped it — and even registered, `_scalar` would have reduced a list to `<list>`. Registered a `config_keys` token field and emit the joined names. The field is drawn from a closed set of declared setting names, never a user value. **(7a) A first-party control file reported as blob corruption.** `blob_gc_index_watermark` writes `.polylogue-index-liveness-watermark.json` into the blob namespace root, but `BlobStore.iter_namespace` exempted only `.polylogue-blob-namespace` and `.staging` — so its own control file surfaced as a *critical* `invalid_namespace_entries` finding telling the operator to "quiesce blob writers". `blob_store` now owns the reserved-name set (it is the module that decides what may sit in that root) and the watermark module imports it, so the two cannot drift. **(5) A tombstone that committed and then aborted.** #5148 added the tombstone-without-index-row path; #5154 then made `ArchiveStore.delete_sessions` resolve every id and raise `KeyError` for one with no row. The apply committed the durable suppressions and *then* raised, losing the receipt for a tombstone that had already landed. Only ids PREPARE recorded in `present_in_index` now reach that call — exactly the complement of the `tombstoned_without_index_row` set the receipt already names, and deleting a row that is not there is a no-op anyway. ## The stale tests **(1)** #5147 (`ae9149902`) replaced `blob_path.read_bytes()` in `_verify_archive_file_set_backup` with a 1 MiB chunked stream. `tests/infra/backup_read_counter.py` instruments only `Path.read_bytes` and `backup._sha256_file`, so the scratch proof read became *invisible* — the blobs are still read and hashed. The counter now also counts `Path.open` on blob paths. Anti-vacuity: rereading scratch blobs during receipt construction doubles `open:scratch`; dropping the restore proof zeroes it. **(8)** polylogue-u19l (`f3bbf413a`, carried by #4549) stopped splicing a synthetic `session_meta` header into Codex append blobs so stored bytes stay a literal slice of the live file. This one fixture still wrote `_session_meta + delta` while declaring a 124-byte window over a 185-byte blob, so `verified_reconstructed_prefix_hash` could never match — every sibling fixture in the file already used literal deltas. Anti-vacuity: dropping `append_head` from the head-kind guard returns `None`. **(9)** #5049 (`73766c276`) added `repair_message_fts_index_sync` to live full ingest precisely because the `defer_fts=True` contract's promised repair was never performed — "a freshly ingested 50k-message session searched as empty" until the next 60s tick. The test still asserted `indexed == 0`. Anti-vacuity: deleting that call zeroes it. **(11)** The route it pinned was deliberately deleted by #5097 ("Delete the dormant verify export command and blob-conservation alias"), whose no-caller grep missed this test. `devtools verify blob-conservation` now falls through to the `verify` tier runner, which refuses inside an agent job and exits 2. The product check is healthy (`referenced_blobs == present_blobs == 1`). Retargeted to the one surviving declared route, `polylogue ops maintenance blob-conservation --output-format json`, and renamed accordingly. ## Left red, with cause established **(3) `test_seed_demo_archive_creates_ready_queryable_archive`** — bead **`polylogue-wrvy2`** (P0, open) is accurate and matches exactly: `codex-session` declares `topology_capabilities.parent_dispatch.state == "structurally-absent"`, so `write.py` never mints `session_links.parent_tool_use_block_id`, and the `delegations` resolved branch (`archive_tiers/index.py:1594-1596`) joins on precisely that column — the row lands as `edge_only`. The bead's open question is *adjudication*: is the codex capability declaration wrong, or does `demo/seed.py:845` assert an outcome its own origin forbids? That is a design decision, not something to settle inside a test-failure sweep. Confirmed accurate and left red, as instructed. **(7b) `[session-fingerprint-stamps]`** — not reproducible at head. A fresh schema-coverage artifact built in-process stamps the current fingerprints and reports `ok`. The receipt's artifact (`build_id = git:890a2921`) carries `recipe_id` / `source_semantics_id` / `archive_schema_id` that no clean process at that commit computes: it was published into the shared `/realm/tmp/polylogue-seeded-artifacts` cache by a process with uncommitted product changes, and `build_id` records the commit but cannot record dirtiness. Filed as **`polylogue-c4a1o`** (P2). **(4) and (10)** — pass at head in every run made; the `SchemaSkewError` appears only in multi-file runs. A prototype-cache hypothesis was **refuted** empirically: recorded tier prototypes carry an *empty* `schema_identity` table, so a page copy cannot stamp a stale identity. Classified as in-process order-sensitive contamination with the mechanism unlocalised — recorded on `polylogue-c4a1o` as adjacent evidence, explicitly not as a claim that they share its cause. **Not** called flaky: no wait is involved. ## Verification ``` devtools test tests/integration/test_backup_verification_read_amplification.py \ tests/unit/core/test_config_resolution_regression.py \ tests/unit/sources/test_live_append_cursor_resynthesis.py \ tests/unit/sources/test_live_batch_support.py \ tests/unit/storage/test_blob_conservation.py \ tests/unit/operations/test_mutation_actuators.py \ tests/unit/pipeline/test_archive_ingest_shared_raw.py \ tests/unit/maintenance/test_archive_verification.py devtools test: FAILED exit=1 receipt=.cache/verify/runs/20260914T231245Z-focused-test-159592-60c25774/run.json 317 passed, 88 failed. ``` Every one of those 88 is the `CHECK constraint failed: native_id IS NOT NULL OR content_identity IS NOT NULL` class owned by another agent — parsed from the receipt's `pytest-report.json`, **non-CHECK failures: 0**. They are concentrated in `test_archive_verification.py`, which builds archives through the affected fixtures. None of the eleven failures in scope remains red except (3), which is deliberate. `devtools gate format` / `lint` / `mypy` (2869 files) / `layering` — all clean. ## Schema closure — **all six product files are IN** ``` IN polylogue/sources/decoder_zip.py IN polylogue/config.py IN polylogue/logging_fields.py IN polylogue/operations/mutation_actuators.py IN polylogue/storage/blob_store.py IN polylogue/storage/blob_gc_index_watermark.py ``` **This moves the derived schema identity. It must land before a fresh rebuild starts, never during one.** ## Residuals - (3) stays red under `polylogue-wrvy2`; (7b) and the order-dependent pair under `polylogue-c4a1o`. - (5) is fixed at the actuator. A session vanishing *between* PREPARE and APPLY still raises. Whether `delete_sessions` should treat an absent session as an error at all is arguably the real #5154 question and needs `archive.py`, which was outside this change's scope. - (11): `polylogue ops maintenance blob-conservation` prints an `Archive root: …` banner ahead of its JSON on a `--output-format json` surface. The test slices from the first brace rather than reaching into `polylogue/cli/**`; the banner-on-JSON behaviour is untouched and arguably wrong. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01DYUNBGoE652b3nfmq3CtqK Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
Summary
Excising a multi-revision session left its earlier revisions readable and
re-ingestible while reporting success. The resolver now reaches every revision
of the session's logical source, and the one family it still cannot reach —
hook evidence — is reported as a counted residual instead of being silently
omitted from a "complete" receipt.
Fifth and sixth of the seven known instances. The rebuild blocker is #5137;
#5148 and #5151 are the others landed so far.
Problem
Earlier revisions survived (polylogue-uhafj instance 4)
resolve_session_excision_targetseeded its raw ids from one query:That is the most recently applied revision. Superseded baselines and append
fragments are retained live by default —
storage/raw_retention.py'ssuperseded_raw_snapshot_candidatesexists precisely because only an explicitretention run compacts them — and each carries its own
blob_refsrows.Concrete input: one logical source with a baseline raw (
rev-0) and an appendrevision (
rev-1) whosepredecessor_raw_id/baseline_raw_idpoint at it,with the index session pointing at
rev-1. Observed outcome before thischange:
plan.source_raw_rows == 1, the apply deleted onlyraw-head, andraw-baselineremained inraw_sessionswith a liveblob_refsrow whileits payload hash was absent from
excised_content.The last part is what makes it resurrectable, not merely retained: an append
revision's payload is a byte-prefix of its successor but hashes differently,
so the head's non-resurrection marker never covers the baseline. Ordinary
re-ingest of those bytes is admitted.
The receipt reported
found: truewith counts that were true of the deletionperformed and silent about the revision left behind.
Hook evidence was never in scope at all (polylogue-bhhsa)
Hook payloads are durable and session-addressable by
(origin, session_native_id)—idx_raw_hook_events_session— butdeliberately carry no
raw_sessions/sessionsrow, so no raw target reachesthem and nothing in
polylogue/security/mentions them.polylogue excise <session>reported a completed excision while every PreToolUse/PostToolUsepayload for that session stayed readable in
source.db, with its blobs stillrooting GC.
Solution
One resolver, not one check per family. Both of these are the same shape as
the rest of this cluster, but the choke point is different from #5137's: a
session-suppression check at
write_parsed_session_to_archivecannot help here(see Residuals). For excision the shared point every entry route already passes
through is
resolve_session_excision_target, so the reach lives there and theapply loop — which already iterates
target.raw_targetsand handles each fully— needed no change.
_durable_revision_closureexpands the seeds over the durable tier:logical_source_keyonraw_session_membershipsandraw_sessions, thenthe
predecessor_raw_id/baseline_raw_idlinks, unioned to a fixpointbecause those columns are plain TEXT with no foreign key and therefore no
cascade. Bounded at 16 passes so a corrupted cycle returns what it resolved
rather than looping.
_index_revision_raw_idswidens the seed set fromraw_revision_applications/raw_revision_heads. The index is rebuildable,so this is corroboration only: it can only grow the set the durable closure
then expands.
table_exists, never caught. An oldertier contributes nothing; a real query failure still surfaces rather than
quietly resolving as "no further revisions" — the fail-open shape that
devtools gate layering'ssqlite_degradation_site_addedrule exists tostop.
The residual is named, not hidden.
ExcisionTarget.retained_hook_event_idsflows into
ExcisionPlan.retained_hook_events,ExcisionReceipt.retained_hook_events, and a newExcisionReceipt.completethat is false while any remain. The dry-run preview prints a WARNING line and
the success line appends
INCOMPLETE: N hook event(s) ... were NOT excised.This does not fix polylogue-bhhsa — it stops the operation from claiming a
deletion it did not perform, which is the part that makes the defect dangerous.
Verification
Anti-vacuity, verified by reverting the resolver to
sessions.raw_idalone anddropping the hook-event resolution — observed:
A resolver that simply deleted every raw row would not pass either: an
unrelated logical source's raw evidence is asserted untouched in the same
archive.
Schema closure
Moves the derived schema identity, so this must land before a fresh
rebuild starts, never during one.
Residuals
hook_event_carriersare still not deleted. Doing that needs a new applystep with its own FK ordering and its own
excised_contentmarkers for thecarrier blob hashes — a real deletion path, not a resolver widening, and
worth its own review.
parse_policy='fact'with nosessionsrow and are associated to a sessiononly at read time, by filename UUID. They are not covered by the hook
residual either, so
ExcisionReceipt.completecan still beTruewhile TODOtext remains readable under the excised session id. That needs the decision
the bead asks for — which fact kinds carry session-derived identity — before
code.
Suppression and excision are two different durable forget-mechanisms:
suppression is session-level state in
user.dbenforced on index writes,excision is content-level state in
source.dbkeyed by blob hash. Hookevents, TODO facts, raw revisions and attachment blobs are durable
source.dbwrites that never pass throughwrite_parsed_session_to_archive, so no check there can reach them. Asingle check covering all seven routes does not exist; the honest structure
is two choke points — the index write path for suppression, this resolver
for excision reach — plus the reference-writer gates in fix: Keep durably excised bytes out of backfill and publication #5151.
excision.pyexposes session-scoped resolution only.
🤖 Generated with Claude Code
https://claude.ai/code/session_01DYUNBGoE652b3nfmq3CtqK