Skip to content

fix: Refuse index writes for sessions the operator tombstoned - #5137

Merged
Sinity merged 1 commit into
masterfrom
fix/suppression-non-resurrection-choke-point
Sep 14, 2026
Merged

Sinity merged 1 commit into
masterfrom
fix/suppression-non-resurrection-choke-point

Conversation

@Sinity

@Sinity Sinity commented Sep 14, 2026

Copy link
Copy Markdown
Owner

Summary

An index rebuild resurrected every session the operator had ever deleted. This
puts the durable non-resurrection check at write_parsed_session_to_archive,
the single choke point shared by live ingest and full replay/reindex, and makes
each refusal counted and observable rather than a silent drop.

This is the rebuild blocker: fixing it after a rebuild does not un-resurrect
anything.

Problem

Identity-preserving reset (polylogue ops reset --session/--source)
deliberately keeps the acquired raw evidence in the durable source.db,
records the operator's deletion as a durable suppression assertion in
user.db, and drops only the rebuildable index.db row.

Nothing consulted that suppression on the way back in. operations/specs.py
even documents the intent — "source content can still repopulate index.db
rows, but the suppression hides them" — and the suppression hides nothing: at
the reviewed head the only writer of a suppression assertion was
IdentityResetActuator, and the only readers were a debt census and an
export. No write route and no read filter consulted it.

Concrete input and wrong observable outcome, as a replay performs it:

  1. Archive session unknown-export:tombstoned-one.
  2. Tombstone it — durable user.db suppression, index.db row deleted.
  3. Replay the retained raw evidence back through
    write_parsed_session_to_archive, which is exactly what
    ops maintenance rebuild-index does for accepted raw cohorts.

Before this change, step 3 returned
ArchiveWriteOutcome(wrote=True, ...) and the deleted session and its
messages were back in index.db and directly queryable. A default rebuild
processes all retained raw rows, so it resurrects every session ever
tombstoned.

Solution

One durable check at the shared choke point, not five scattered ones. The
recurring root here is a durable check present on one write route and absent
from the others, so an extra check per replay caller would reproduce the
defect on the next replay path added.

  • New storage/sqlite/archive_tiers/session_suppression.py owns the lookup.
    It resolves the user tier from the index connection itself — an already
    ATTACHed user_tier, else a sibling user.db (or one directory up, the
    promoted-generation layout). Resolution is ambient rather than a writer
    argument on purpose: a required argument is forgettable by exactly the kind
    of new replay path that caused this, and an optional one defaulting to "no
    guard" reproduces it.
  • write_parsed_session_to_archive refuses the write immediately after it
    computes session_id, before any row preparation.
  • A user.db that exists but cannot be read is a typed
    SuppressionTierUnreadableError, not a fail-open pass. A connection with no
    reachable user.db (:memory:, bare index fixtures) has no durable tier
    that could hold a tombstone and proceeds. devtools gate layering's
    sqlite_degradation_site_added rule caught two earlier fail-open
    except sqlite3.Error sites in this module; both were removed rather than
    baselined.

Refusals are counted and observable, never silently dropped — otherwise this
trades a privacy defect for a silent-loss defect:

  • ArchiveWriteOutcome.suppression_skipped
  • a storage.session_suppression.write_refused WARNING event
  • suppression_refusal_scope(), a thread-local totals window a replay run
    wraps its writes in, with describe() naming what it did not restore
  • revision_governance._write_parsed_precedence_result no longer reports
    content_changed=True for an authoritative replay the writer refused

Verification

devtools test tests/unit/storage/test_session_suppression_non_resurrection.py \
  tests/unit/pipeline/test_archive_write.py tests/unit/cli/test_reset.py \
  tests/unit/storage/test_bulk_replace.py tests/unit/storage/test_archive_tiers_assertions.py
devtools test: PASSED exit=0 diagnosis=pytest_passed

devtools verify --quick     # EXIT=0, all 17 gates ok

Anti-vacuity, verified by reverting the guard (if False and session_write_is_suppressed(...)) and re-running — observed:

FAILED test_rebuild_replay_does_not_resurrect_a_tombstoned_session
E   AssertionError: assert True is False
E    +  where True = ArchiveWriteOutcome(session_id='unknown-export:tombstoned-one', wrote=True, stale_skipped=False, suppression_skipped=False, ...).wrote
FAILED test_suppression_refusal_is_counted_not_silently_dropped
E   AssertionError: assert False is True
E    +  where False = ArchiveWriteOutcome(session_id='unknown-export:dropped-one', wrote=True, ...).suppression_skipped
FAILED test_a_revoked_suppression_lets_the_session_be_archived_again

The fourth test (test_an_archive_without_a_user_tier_is_not_blocked) stays
green under that revert, as it should: it asserts the write still happens.
Deleting the write outright does not make the suite green either — an
unsuppressed sibling session in the same replay is asserted to still be
written, and a revoked suppression is asserted to let the session back in.

Schema closure

All three product files are IN the derived schema-identity closure:

IN   polylogue/storage/sqlite/archive_tiers/session_suppression.py
IN   polylogue/storage/sqlite/archive_tiers/write.py
IN   polylogue/storage/sqlite/archive_tiers/revision_governance.py

So this moves the derived schema identity and must land before a fresh
rebuild starts, never during one
— which is also the order the defect
itself demands.

The suppression lookup deliberately matches on assertions.target_ref /
kind rather than the derived assertion id, so the index writer does not pull
the user-tier id recipe (user_write) into its closure.

Residuals

  • Suppression is still not applied as a read filter. With the guard at the
    choke point no suppressed session can enter index.db, so on a fresh
    rebuild "not present" is "not readable" — which is what the acceptance
    criterion asks for. A read filter matters only for an archive that already
    contains rows resurrected by an earlier rebuild, and there is no single
    session-read choke point to hang it on (session SELECTs are spread across
    ArchiveStore, query lowering, and MCP). Left as separate work rather than
    scattered half-coverage.
  • The other four instances of the same guarantee failing (drive attachment
    backfill, Antigravity raw publication, multi-revision excision, and the
    identity-reset PREPARE race) are not addressed here and follow separately.
  • suppression_refusal_scope() exists and is proven, but no production replay
    caller wraps its run in one yet — the per-write log event and
    ArchiveWriteOutcome field carry the observability until one does.

🤖 Generated with Claude Code

https://claude.ai/code/session_01DYUNBGoE652b3nfmq3CtqK

Identity-preserving reset keeps the acquired raw evidence in the durable
source.db and records the deletion as a durable user.db suppression
assertion, dropping only the rebuildable index.db row. Nothing consulted
that suppression on the way back in, so replaying the retained raw
evidence -- which is exactly what an index rebuild does -- recreated
every session the operator had ever deleted.

Put the check at write_parsed_session_to_archive, the single choke point
shared by live ingest and full replay/reindex, rather than at each replay
caller: the defect's shape is a durable check present on one write route
and absent from the others.

Refusals are counted and logged, never silently dropped:
ArchiveWriteOutcome.suppression_skipped, a
storage.session_suppression.write_refused event, and a
suppression_refusal_scope() totals window for a replay run's own receipt.
A user.db that exists but cannot be read is a typed refusal rather than a
fail-open pass.

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

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, add credits to your account and enable them for code reviews in your settings.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 14, 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
🔒 Security Review ✅ Completed 2026-09-14T18:54:11.500189Z fa71d86 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.

@coderabbitai

coderabbitai Bot commented Sep 14, 2026

Copy link
Copy Markdown

Warning

Review limit reached

Next included review available in 33 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: 7651dee8-2ef2-41c9-9850-9897e0bc0507

📥 Commits

Reviewing files that changed from the base of the PR and between a3f5f9c and fa71d86.

📒 Files selected for processing (4)
  • polylogue/storage/sqlite/archive_tiers/revision_governance.py
  • polylogue/storage/sqlite/archive_tiers/session_suppression.py
  • polylogue/storage/sqlite/archive_tiers/write.py
  • tests/unit/storage/test_session_suppression_non_resurrection.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.

@Sinity
Sinity merged commit 1aaa5d3 into master Sep 14, 2026
3 checks passed
@Sinity
Sinity deleted the fix/suppression-non-resurrection-choke-point branch September 14, 2026 19:35
Sinity added a commit that referenced this pull request Sep 14, 2026
## Summary

An identity reset could report `ok` while writing no tombstone at all,
leaving
the deleted content free to come back on the next ingest or index
rebuild.
`prepare` now keeps every caller-resolved target instead of re-filtering
it
against the rebuildable index, and the receipt names what had no index
row.

One of the five instances of the same guarantee failing; the rebuild
blocker
is #5137, which this complements — that change makes the durable
suppression
the load-bearing barrier, so a reset that fails to write one is now
strictly
worse than it was.

## Problem

`polylogue ops reset --session/--source` resolves its targets once in
the CLI
(`_identity_reset_targets`), then submits `mutation.identity-reset`.
`IdentityResetActuator.prepare` re-resolved that already-resolved set
against
`index.db`:

```python
existing = tuple(dict.fromkeys(_resolve_existing_session_ids(args.archive_root, args.session_ids)))
target_refs=tuple(make_target_ref("session", sid) for sid in existing),
context={"session_ids": list(existing), ...}
```

Concrete input and wrong observable outcome: a session that is resolved
by the
CLI and then leaves `index.db` before PREPARE — a concurrent reset, a
generation swap, a delete — resolves to `existing == ()`. The plan
carries no
targets, `apply` takes its `if not session_ids` branch and returns
`status="already_satisfied"`, `affected_count=0`,
`detail="no_matching_sessions"`,
and **no `user.db` suppression row is written**. The CLI reads
`suppressed_count` as 0 and still emits `status="ok"` with
`"Tombstoned session <id>: 0 suppression(s), 0 archive row(s) deleted."`

The operator is told the deletion happened. Nothing durable records it,
so the
next ingest or rebuild makes the content visible again.

## Solution

`prepare` targets every caller-resolved id. The durable `user.db`
suppression
is the tombstone and does not depend on the rebuildable index row
existing —
the actuator's own "archive tier absent" branch in
`_resolve_existing_session_ids` already says exactly that, and the
existence
re-filter contradicted it for the partial case.

The costs are asymmetric and that decides it: a suppression written for
an id
that never existed is inert (nothing to suppress, and the CLI layer
already
turns a typo into "No sessions found" before submitting), while a
suppression
dropped for a raced id is a durable privacy failure. `present_in_index`
is
still resolved, but only to describe the expected deletion, not to gate
the
tombstone.

The refusal-shaped outcome stays observable: the domain receipt now
carries
`tombstoned_without_index_row`, naming the targets that had no
rebuildable
row, so `deleted_archive_rows: 0` can never be read as "nothing was
tombstoned".

## Verification

```
devtools test tests/unit/operations/test_mutation_actuators.py \
  tests/unit/cli/test_reset.py tests/unit/operations/test_specs.py
devtools test: PASSED exit=0 diagnosis=pytest_passed
```

Anti-vacuity, verified by restoring the existence filter in `prepare`
(`target_refs`/`session_ids` back to `present`) and re-running —
observed:

```
E       AssertionError: assert () == ('session:cod...on:vanished',)
E         Right contains one more item: 'session:codex-session:vanished'
FAILED tests/unit/operations/test_mutation_actuators.py::TestIdentityResetActuator::test_a_session_absent_from_the_index_is_still_tombstoned
```

Leaving the index untouched does not make the test green either: the
surviving
unrelated session's row is asserted to still be there.

### A test changed meaning, deliberately

`test_nonexistent_session_plans_zero_targets` asserted the defective
behaviour (`plan.target_refs == ()` for a session absent from the
index). It
is replaced by
`test_a_session_absent_from_the_index_is_still_tombstoned`,
which asserts the new contract and carries the reasoning in its
docstring.
This is a real semantic change to the actuator's preview, not a test
tidy-up,
and is called out here rather than buried.

## Schema closure

```
IN   polylogue/operations/mutation_actuators.py
```

Moves the derived schema identity, so this must land **before** a fresh
rebuild starts, never during one.

## Residuals

- `_resolve_existing_session_ids` is now used only for reporting. It is
kept
rather than inlined because the deleted-row expectation is genuinely
useful
  in the receipt, but it is no longer a gate on anything.
- The preview a `--dry-run` shows still comes from the CLI's own
resolution,
which is unchanged; this only fixes the window between that resolution
and
  PREPARE.
- The other instances of this guarantee failing (index-rebuild
resurrection,
  Drive attachment backfill, Antigravity raw publication, multi-revision
  excision) are separate changes.

🤖 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]>
Sinity added a commit that referenced this pull request Sep 14, 2026
## Summary

Two routes put bytes the operator durably excised back into the archive.
Both
are gated now, and both refusals are counted rather than silent.

Third and fourth of the seven known instances of the same guarantee
failing;
the rebuild blocker is #5137 and the reset race is #5148.

## Problem

### Drive attachment backfill recreated a live reference to excised
bytes

`converge_drive_attachments` selects any `unfetched` reference with
`upload_origin = 'drive'`, downloads it, and asserts the payload hashes
to
what it publishes. Concrete input: an attachment whose blob hash is
recorded
in `excised_content`, still carrying an `unfetched` Drive reference.
Observed
outcome before this change: the stage published the bytes, called
`write_source_blob_refs` to create a live `blob_refs` row for the
excised
hash, and flipped the attachment to `acquisition_status = 'acquired'`.

Neither the stage nor `write_source_blob_refs` consulted
`is_blob_hash_excised` — and `write_source_blob_refs` was the *only*
blob-reference writer in `source_write.py` that did not.
`insert_reconstructed_raw_row`, `write_source_raw_session` and
`write_source_raw_session_blob_ref` all gate. That asymmetry is the
whole
defect: a durable check present on every write path but one.

### A refused excised write left its publication reservation behind

The publication protocol stages bytes and inserts a
`blob_publication_reservations` row *before* the archive write that will
reference them. On success, `consume_blob_publication_receipt` deletes
that
row in the same transaction that creates the referent.

On a `ContentExcisedError` refusal, the referent is never created, so
the
consumption never runs. Both handlers — `LiveBatchProcessor.
_ingest_full_records_archive` and `parse_sources_archive` — counted
`excised_skips` and returned, leaving the reservation.
`inspect_blob_reservation`
then reports `LIVE` for that hash, `_GCProtection.is_live` ORs it into
canonical liveness, and GC records `skipped_still_live`. The excised
bytes
are permanently GC-immune, and because each pass queues a fresh
`publication_id`, every repeat pass over the same unchanged source file
accrues another receipt.

## Solution

**Where the check goes, and why not one place.** For the session family
the
right answer was a single choke point (#5137). For the blob family there
is
one genuinely shared point,
`BlobPublicationReservationStore.reserve_many`,
and it is the wrong place: a flush batches many receipts, so refusing
there
either fails the whole batch — dropping unrelated legitimate
attachments,
trading a privacy defect for a silent-loss defect — or needs per-hash
partial
refusal that leaves callers holding hashes they believe were published.

The durable decision that actually matters is whether a *reference* gets
created, and that has one owner per reference kind. So:

- `write_source_blob_refs` gates on `is_blob_hash_excised` like its
three
module siblings. This is the durable backstop, and it also covers the
three
  `revision_governance` callers.
- `converge_drive_attachments` hashes the payload itself and checks
*before*
  `publisher.write_from_bytes`. Refusing there means nothing is staged,
  nothing is reserved, and nothing has to be unwound — the window after
`flush()` cannot be cleaned up by `discard_pending()`, which only
discards
  unflushed preparations.
- Both `ContentExcisedError` handlers call a new
`release_refused_publication_receipt`, which drops the reservation for a
publication whose referent was refused and hands the bytes back to
ordinary
  GC.

Counted and observable, not silent:

- `AttachmentConvergenceResult.excised`, separate from `terminal`, so a
  privacy refusal is never read as an ordinary transport failure
- `operations.attachment_convergence.excised_refused` and
`pipeline.archive_ingest.excised_publication_released` structured events
- the live-watcher log line reports whether the reservation was
released,
  rather than asserting it

## Verification

```
devtools test tests/unit/daemon/test_attachment_convergence_excision.py \
  tests/unit/daemon/test_attachment_convergence.py \
  tests/unit/security/test_excision.py tests/unit/storage/test_raw_admission.py
devtools test: PASSED exit=0 diagnosis=pytest_passed

devtools verify --quick     # EXIT=0
```

Anti-vacuity, verified by reverting each guard and observing the
failure.

Disabling the Drive gate and the `write_source_blob_refs` gate:

```
E       assert 0 == 1
E        +  where 0 = AttachmentConvergenceResult(inspected=2, acquired=2, terminal=0, deferred=0, excised=0).excised
FAILED tests/unit/daemon/test_attachment_convergence_excision.py::test_drive_backfill_refuses_bytes_the_operator_excised
```

Note `acquired=2` — without the guard both attachments, including the
excised
one, are acquired. Disabling the whole stage does not make the test
green
either: the non-excised sibling is asserted to still be acquired in the
same
pass.

Disabling the receipt release:

```
E   AssertionError: a refused excised write left its publication reservation behind
E   assert b'\x9e\xab\x98d...' not in {b'\x9e\xab\x98d...'}
FAILED tests/unit/sources/test_live_batch_support.py::test_full_ingest_skips_durably_excised_content_without_aborting_batch
```

## Schema closure

```
IN   polylogue/storage/sqlite/archive_tiers/source_write.py
IN   polylogue/storage/blob_publication.py
IN   polylogue/sources/live/batch.py
out  polylogue/operations/attachment_convergence.py
out  polylogue/pipeline/services/archive_ingest.py
```

Three files are IN, so this moves the derived schema identity and must
land
**before** a fresh rebuild starts, never during one.

## Residuals

- **Inherited failure, not caused here:**

`test_live_batch_support.py::test_full_ingest_writes_archive_with_route_observability`
fails identically on clean `master` (`assert indexed == 0` / `assert 1
== 0`,
the FTS-deferral assertion). Verified by checking out `master` in the
same
worktree and re-running the file: `1 failed, 164 passed` there and here.
Not
  fixed in this change.
- The Drive stage marks a refused attachment `acquisition_status =
'unavailable'` — the same terminal index state as an unfetchable
payload.
A distinct status would describe the refusal better but is an index-tier
  vocabulary change, kept out of a privacy fix.
- `release_refused_publication_receipt` covers the two
`ContentExcisedError` handlers. Receipts already orphaned by past
refusals
are not swept here; `maintenance blob-publications --abandon` remains
the
  operator route for those.
- `_antigravity_raw_snapshot` still publishes before the write decides.
That
ordering is what makes the release necessary; moving the check earlier
needs
a source-tier connection the picklable parse-side helper deliberately
does
  not have, and is left as separate work.

🤖 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]>
Sinity added a commit that referenced this pull request Sep 14, 2026
## 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_target` seeded its raw ids from one query:

```sql
SELECT raw_id FROM sessions WHERE session_id = ?
```

That is the *most recently applied* revision. Superseded baselines and
append
fragments are retained live by default — `storage/raw_retention.py`'s
`superseded_raw_snapshot_candidates` exists precisely because only an
explicit
retention run compacts them — and each carries its own `blob_refs` rows.

Concrete input: one logical source with a baseline raw (`rev-0`) and an
append
revision (`rev-1`) whose `predecessor_raw_id`/`baseline_raw_id` point at
it,
with the index session pointing at `rev-1`. Observed outcome before this
change: `plan.source_raw_rows == 1`, the apply deleted only `raw-head`,
and
`raw-baseline` remained in `raw_sessions` with a live `blob_refs` row
while
its 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: true` with counts that were true of the
deletion
performed 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` — but
deliberately carry no `raw_sessions`/`sessions` row, so no raw target
reaches
them and nothing in `polylogue/security/` mentions them. `polylogue
excise
<session>` reported a completed excision while every
PreToolUse/PostToolUse
payload for that session stayed readable in `source.db`, with its blobs
still
rooting 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_archive` cannot
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 the
apply loop — which already iterates `target.raw_targets` and handles
each fully
— needed no change.

- `_durable_revision_closure` expands the seeds over the durable tier:
`logical_source_key` on `raw_session_memberships` and `raw_sessions`,
then
the `predecessor_raw_id`/`baseline_raw_id` links, unioned to a fixpoint
because 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_ids` widens the seed set from
`raw_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.
- Missing relations are checked with `table_exists`, never caught. An
older
tier contributes nothing; a real query failure still surfaces rather
than
  quietly resolving as "no further revisions" — the fail-open shape that
`devtools gate layering`'s `sqlite_degradation_site_added` rule exists
to
  stop.

**The residual is named, not hidden.**
`ExcisionTarget.retained_hook_event_ids`
flows into `ExcisionPlan.retained_hook_events`,
`ExcisionReceipt.retained_hook_events`, and a new
`ExcisionReceipt.complete`
that 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

```
devtools test tests/unit/security/test_excision_revision_reach.py \
  tests/unit/security/test_excision.py tests/unit/cli/test_excise.py \
  tests/unit/security/test_excision_lifecycle.py tests/unit/security/test_excision_policy.py
devtools test: PASSED exit=0 diagnosis=pytest_passed

devtools verify --quick     # EXIT=0
```

Anti-vacuity, verified by reverting the resolver to `sessions.raw_id`
alone and
dropping the hook-event resolution — observed:

```
E       AssertionError: the superseded baseline was not resolved
E       assert {'raw-head'} == {'raw-baseline', 'raw-head'}
E         Extra items in the right set:
E         'raw-baseline'
E       AssertionError: assert () == ('hook-1',)
E         Right contains one more item: 'hook-1'
```

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

```
IN   polylogue/security/excision.py
out  polylogue/cli/commands/excise.py
```

Moves the derived schema identity, so this must land **before** a fresh
rebuild starts, never during one.

## Residuals

- **polylogue-bhhsa is reported, not fixed.** Hook events and their
`hook_event_carriers` are still not deleted. Doing that needs a new
apply
step with its own FK ordering and its own `excised_content` markers for
the
carrier blob hashes — a real deletion path, not a resolver widening, and
  worth its own review.
- **polylogue-si5kj is not addressed.** Claude TODO artifacts are
admitted
`parse_policy='fact'` with no `sessions` row and are associated to a
session
  only at read time, by filename UUID. They are not covered by the hook
residual either, so `ExcisionReceipt.complete` can still be `True` while
TODO
text remains readable under the excised session id. That needs the
decision
the bead asks for — which fact kinds carry session-derived identity —
before
  code.
- **The session-suppression choke point (#5137) does not cover any of
this.**
  Suppression and excision are two different durable forget-mechanisms:
suppression is session-level state in `user.db` enforced on index
writes,
excision is content-level state in `source.db` keyed by blob hash. Hook
  events, TODO facts, raw revisions and attachment blobs are durable
  `source.db` writes that never pass through
  `write_parsed_session_to_archive`, so no check there can reach them. A
single 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 #5151.
- Excision still has no message- or blob-scoped resolver; `excision.py`
  exposes session-scoped resolution only.

🤖 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]>
Sinity added a commit that referenced this pull request Sep 14, 2026
## 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]>
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