Skip to content

fix(storage): guard-gated bulk delete_sessions — one-pass derived maintenance instead of per-row trigger detonation - #3263

Merged
Sinity merged 2 commits into
masterfrom
fix/storage/bulk-delete-guarded
Jul 26, 2026
Merged

Sinity merged 2 commits into
masterfrom
fix/storage/bulk-delete-guarded

Conversation

@Sinity

@Sinity Sinity commented Jul 22, 2026

Copy link
Copy Markdown
Owner

Summary

ArchiveStore.delete_sessions (the product bulk-delete API used by the CLI
delete verb and SessionDeleteActuator) now wraps its whole batch in the
same derived_refresh_guard rows the bulk session-write path already uses,
and performs the derived FTS/trigram/action_pairs/delegation_facts
maintenance explicitly, one pass, instead of relying on unsuppressed
per-row triggers.

Problem

delete_sessions issued a plain per-session DELETE FROM sessions.
blocks_action_pairs_ad (storage/sqlite/archive_tiers/index.py) fires
once per deleted blocks row — both the explicit block cascade and the FK
ON DELETE CASCADE from messages/sessions still invoke AFTER DELETE
triggers per row — and each firing deletes+rebuilds the entire session's
action_pairs via two window-function scans and re-derives
delegation_facts. Live incident 2026-07-21: deleting 91 sessions ran 3h,
375GB reads, zero commit, before being killed.

The bulk session-write path already suppresses this class of cost via
derived_refresh_guard rows ('session-write', 'fts-bulk-session-write'),
see _bulk_fts_session_guard in write.py (bead polylogue-crd8's fix for
the analogous whale-lineage-prefix-delete stall). delete_sessions never set
either guard.

Solution

ArchiveStore.delete_sessions (polylogue/storage/sqlite/archive_tiers/archive.py):

  1. For each session id, explicit session-scoped deletes run first, while the
    blocks rows still exist (external-content FTS5 needs the OLD text to
    locate its postings): messages_fts / messages_fts_identity
    (delete_session_rows_sql / delete_session_identity_rows_sql) and
    blocks_command_trigram (trigram_delete_session_rows_sql, landed in
    perf(storage): enable guard-gated bulk FTS on daemon live-ingest and materialization paths #3259).
  2. Both derived_refresh_guard rows are set for the whole batch —
    'session-write' (suppresses blocks_action_pairs_a{i,d,u} and the
    delegation_facts triggers) and 'fts-bulk-session-write' (suppresses
    the messages_fts/blocks_command_trigram trigger bodies — redundant
    here since those rows are already gone by step 1, kept for guard-contract
    parity and defense-in-depth).
  3. action_pairs and delegation_facts are explicitly cleared by session
    id — belt-and-suspenders alongside the ON DELETE CASCADE FKs those
    tables already carry against sessions/blocks; this keeps the
    post-condition legible without depending on cascade-ordering.
  4. DELETE FROM sessions per id relies on indexed FK cascades (not per-row
    trigger logic) for physical messages/blocks tree removal; guard rows
    are cleared and the transaction commits once for the whole batch.

This mirrors _bulk_fts_session_guard's delete-then-guard-then-mutate shape.

Epoch triggers audit (per bead's ask): query_unit_frame_{sessions, messages,blocks}_delete fire per deleted row, ungated by either guard. Left
deliberately ungated — each firing is a single primary-key UPDATE query_unit_frame_state SET epoch = epoch + 1 WHERE singleton = 1 against a
one-row table (O(1) per row), not a window-function rebuild, so this was
never implicated by the incident and folding a third guard in for a
zero-measured cost isn't warranted.

Async path (repository/archive/writes/sessions.py ->
delete_session_via_backend -> queries/sessions_writes.py's
delete_session_sql): unaffected by this fix and left unchanged. It deletes
exactly one session per call/transaction — there is no loop batching N
session ids into a single transaction, so the "91 sessions in one
transaction" incident shape does not reproduce there. (A single very-large
session could still see a bounded version of the same per-block trigger cost
for its own row count — that's the pre-existing, already-tracked crd8
concern for whale writes, not a bulk-delete regression, and out of this
bead's scope.)

Verification

  • devtools test tests/unit/storage/test_bulk_delete_guarded.py tests/unit/storage/test_bulk_fts_prefix_reextract.py
    -> 9 passed
  • Anti-vacuity proof: sqlite3.Connection.set_trace_callback was tried
    first and rejected — it only reports the outer statement text (DELETE FROM sessions ...), never SQL executed inside a trigger body (verified
    empirically against a minimal repro). Instead, the new
    test_delete_sessions_bulk_never_fires_unguarded_per_row_canary installs
    canary triggers on blocks carrying the exact same WHEN-clause guard
    conditions
    as the real blocks_action_pairs_ad /
    blocks_command_trigram_ad triggers. With the fix reverted (git stash
    on archive.py only, canary test re-run), the canaries fire
    {'session_write': 14, 'fts_bulk': 6} for 2 sessions x 3 tool pairs each
    — i.e. the per-row rebuild machinery would have detonated. With the fix
    restored, both counts are 0. What would make this test fail: removing
    or narrowing the scope of either INSERT OR REPLACE INTO derived_refresh_guard(...) call this PR adds.
  • devtools verify --quick -> exit_code: 0 (ruff format/check, mypy
    --strict, render all --check, topology/layering/manifests/doc-commands/
    docs-coverage/test-clock-hygiene/pytest-timeout-overrides/degrade-loudly)
  • tests/unit/storage/test_archive_tiers_archive.py::test_exact_session_action_count_bounds_pairing_before_global_ranking
    fails identically with the fix reverted (git stash on archive.py only)
    — confirmed pre-existing and unrelated to this change, not touched by this
    PR.
  • Not run: full devtools verify --all / broad directory pytest (repo
    convention is testmon-affected + focused files, not blanket runs).

Ref polylogue-meoz. Relates to polylogue-crd8 (same derived_refresh_guard
mechanism, different write path — whale prefix-delete during ingest vs. bulk
session delete via the product API).

🤖 Generated with Claude Code

@coderabbitai

coderabbitai Bot commented Jul 22, 2026 •

Copy link
Copy Markdown

Warning

Review limit reached

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

Next review available in: 33 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 801f70db-ce06-41d0-9696-062532c4eed7

📥 Commits

Reviewing files that changed from the base of the PR and between 59f613e and e8ced32.

📒 Files selected for processing (2)
  • polylogue/storage/sqlite/archive_tiers/archive.py
  • tests/unit/storage/test_bulk_delete_guarded.py
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/storage/bulk-delete-guarded

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 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: 96a28f104a

ℹ️ 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".

Sinity and others added 2 commits July 26, 2026 22:23
…tenance

Problem: ArchiveStore.delete_sessions issued a plain per-session
DELETE FROM sessions. blocks_action_pairs_ad fires once per deleted
blocks row (both explicit cascades and FK ON DELETE CASCADE invoke
AFTER DELETE triggers per row); each firing deletes+rebuilds the
entire session's action_pairs via two window-function scans and
re-derives delegation_facts. Live incident 2026-07-21: deleting 91
sessions ran 3h, 375GB reads, zero commit, before being killed. The
bulk session-write path already suppresses this via
derived_refresh_guard rows, but delete_sessions never set them.

Solution: wrap the whole batch in both derived_refresh_guard rows
('session-write' suppresses blocks_action_pairs_a{i,d,u} and the
delegation_facts triggers; 'fts-bulk-session-write' suppresses the
messages_fts/blocks_command_trigram trigger bodies), and do the
derived maintenance explicitly, one pass, per session id before the
guarded delete: messages_fts/messages_fts_identity session-scoped
delete (delete_session_rows_sql/delete_session_identity_rows_sql),
blocks_command_trigram session-scoped 'delete' commands
(trigram_delete_session_rows_sql, run while blocks rows still exist
since external-content FTS5 needs the OLD text), and explicit
action_pairs/delegation_facts deletes by session id (belt-and-
suspenders alongside their existing ON DELETE CASCADE FKs). Mirrors
_bulk_fts_session_guard's delete-then-guard-then-mutate shape
(write.py). Physical row removal still relies on indexed FK cascades,
not per-row trigger logic.

Async path (repository/archive/writes/sessions.py ->
delete_session_via_backend -> queries/sessions_writes.py's
delete_session_sql) is unaffected: it deletes exactly one session per
call/transaction, never a batch, so the N-sessions-in-one-transaction
incident shape does not reproduce there.

query_unit_frame_{sessions,messages,blocks}_delete epoch-bump triggers
are deliberately left ungated: each firing is an O(1) single-row
UPDATE against a one-row table, not a window-function rebuild, so they
were never implicated by the incident.

Verification:
- devtools test tests/unit/storage/test_bulk_delete_guarded.py
  tests/unit/storage/test_bulk_fts_prefix_reextract.py -> 9 passed
- Anti-vacuity proof: reverted the guard-setting code and re-ran
  test_delete_sessions_bulk_never_fires_unguarded_per_row_canary ->
  fails with {'session_write': 14, 'fts_bulk': 6} (canary triggers
  mirroring the real trigger WHEN-clauses fire per unguarded block
  delete); passes with the fix restored.
- devtools verify --quick -> exit_code 0 (ruff format/check, mypy
  --strict, render all --check, topology/layering/manifests/etc.)
- tests/unit/storage/test_archive_tiers_archive.py::
  test_exact_session_action_count_bounds_pairing_before_global_ranking
  fails identically on unmodified archive.py (git stash verified) --
  pre-existing, unrelated to this change.

Ref polylogue-meoz. Relates to polylogue-crd8 (same
derived_refresh_guard mechanism, different write path).

Co-Authored-By: Claude <[email protected]>
…guard

Problem (CodeRabbit #3263 P1): CREATE TRIGGER IF NOT EXISTS never replaces
an existing same-name trigger, so an archive last rebuilt before the
blocks_command_trigram_ad guard clause landed (#3259) keeps its old,
ungated body forever -- reopening the archive does not upgrade it.
delete_sessions's explicit trigram pre-delete plus its
FTS_BULK_SESSION_WRITE_GUARD row assumed that guard is always honored;
on such an archive the old trigger fires anyway during the block
cascade and reissues an FTS5 'delete' command for a posting the
explicit pre-delete already removed, which raises "database disk image
is malformed" and rolls back the whole batch. Reproduced directly: a
downgraded trigger (this PR's new test fixture) makes the pre-fix code
fail with exactly that error.

What changed: delete_sessions checks once, cheaply, whether the live
blocks_command_trigram_ad trigger's sqlite_master SQL actually
references derived_refresh_guard. When it does not, the method skips
its own explicit trigram pre-delete and the FTS_BULK_SESSION_WRITE_GUARD
row entirely, letting that same (ungated) trigger clean up trigram rows
per-block during the cascade -- exactly the behavior this method had
before the guard-gated optimization existed, so it stays correct (if
unoptimized for trigram specifically) until the archive's next rebuild
picks up the current trigger DDL. No schema-version bump needed: this
is a runtime capability check, not a data migration.

Verification: devtools test tests/unit/storage/test_bulk_delete_guarded.py
(3 passed, including the new pre-guard-archive regression, confirmed to
reproduce the exact reported error against the pre-fix code); devtools
verify --quick (pass).

Co-Authored-By: Claude <[email protected]>
@Sinity
Sinity force-pushed the fix/storage/bulk-delete-guarded branch from 96a28f1 to e8ced32 Compare July 26, 2026 20:25
@Sinity

Sinity commented Jul 26, 2026

Copy link
Copy Markdown
Owner Author

Fixed the P1: delete_sessions now checks (once, cheaply, via sqlite_master) whether the live blocks_command_trigram_ad trigger actually references derived_refresh_guard before relying on the guard. When it doesn't (an archive last rebuilt before #3259), it skips its own explicit trigram pre-delete and the FTS bulk guard row entirely, letting that same ungated trigger clean up per-block during the cascade — correct, just unoptimized for trigram until the archive's next rebuild. New regression test reproduces the exact "database disk image is malformed" error against the pre-fix code (verified it fails without the fix, passes with it) using a downgraded trigger fixture, no schema-version bump needed since this is a runtime capability check, not a migration. Verified: 3 tests pass, devtools verify --quick green.

@Sinity
Sinity merged commit 0963749 into master Jul 26, 2026
3 checks passed
@Sinity
Sinity deleted the fix/storage/bulk-delete-guarded branch July 26, 2026 20:30
@Sinity

Sinity commented Oct 1, 2026

Copy link
Copy Markdown
Owner Author

Historical Codex triage: evidence checked at 5ebcfe5. This records that source revision; it does not claim a fresh review of current master.

  • 74.F038 / P1: refuted at the checked revision: The requested upgrade of an existing v43 archive's old trigram trigger is outside the fresh-format contract. AGENTS.md:74-77 requires an empty v1 archive and retains earlier Polylogue state only as salvage, without migration or readback; preserving or upgrading that predecessor trigger is not an admitted runtime requirement.

Only the rows listed above are dispositioned. Held findings remain 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