Skip to content

fix(storage): prune orphaned raw-authority plans in retention purge - #3530

Merged
Sinity merged 2 commits into
masterfrom
feature/fix/raw-retention-orphaned-authority-plans
Aug 1, 2026
Merged

Sinity merged 2 commits into
masterfrom
feature/fix/raw-retention-orphaned-authority-plans

Conversation

@Sinity

@Sinity Sinity commented Aug 1, 2026 •

Copy link
Copy Markdown
Owner

Summary

Retention-driven raw deletion in cleanup_superseded_raw_snapshots (polylogue/storage/raw_retention.py) now prunes raw_authority_plans rows that become both raw-orphaned (every input raw gone) AND already census-free (zero remaining rows in raw_authority_census_plans / _post_plans / raw_authority_blockers), in the same transaction as the raw delete.

Problem

raw_authority_plans.input_raw_ids_json references raws by JSON string, not by FK, so nothing cascades when raw_sessions rows are deleted. Ref polylogue-i3zo.

Revision history on this PR: the first version deleted raw_authority_census_plans/_post_plans/raw_authority_blockers rows for any orphaned plan unconditionally. A real automated review finding (chatgpt-codex-connector, comment 3696483963) caught that this corrupts the immutable census ledger: raw_authority_censuses.plan_count/post_plan_count are read verbatim by read_raw_authority_census (polylogue/storage/raw_authority.py) as both the reported total and the pagination-termination signal (next_offset < max(total, post_total)). Deleting a census's plan-membership rows without adjusting those counts makes the total lie, and once a census's rows are all removed, next_offset (driven by len(plans), now always 0) stops advancing -- next_query_handle is reissued forever. Deleting an unresolved raw_authority_blockers row is worse: prune_raw_authority_census_history (same module) already treats an unresolved blocker as "a live durable obligation, not history" and refuses to touch it for exactly this reason -- the first draft silently violated that established invariant.

Solution (revised)

  • _delete_orphaned_raw_authority_plans no longer deletes from raw_authority_census_plans/_post_plans/raw_authority_blockers at all. It only hard-deletes a raw_authority_plans row once it also has zero remaining references in all three of those tables.
  • This composes with, rather than fights, the existing prune_raw_authority_census_history retention path: every raw_authority_plans row is inserted in the same transaction as its owning census's raw_authority_census_plans row (record_raw_authority_census), so a plan can only reach zero census references once that function's own plan-retention window (8 generations, RAW_AUTHORITY_CENSUS_PLAN_RETENTION) has already judged its census-plan detail safe to drop -- which it only does once no unresolved blocker remains. This function therefore never advances that judgment early and cannot itself corrupt plan_count/post_plan_count, because it never deletes the rows those counts describe.
  • RawSnapshotCleanupResult.deleted_orphaned_authority_plan_count (additive, default 0) reports the count; repair.py's repair_superseded_raw_snapshots detail surfaces it when non-zero.

Design decision, restated: hard-delete a raw_authority_plans row, but only once established machinery (the census plan-retention window) has already judged its last remaining references safe to drop. This is stricter than the original hard-delete-on-orphan design and deliberately narrower than the bead's literal "prune every orphaned plan" framing, because the census ledger's immutability invariant takes priority.

Consequence, stated honestly: a plan still referenced by an active ('planned', unresolved) census is left untouched by this function even if every raw it names is already gone -- a genuine live obligation is never silently dropped. This differs from the 2026-07-22 live incident cited in the bead, which was caused by a since-deleted one-time repair script (hook_deinflation.py) deleting raws out from under an in-flight census apply directly, bypassing retention authority entirely; cleanup_superseded_raw_snapshots only ever deletes raws proven superseded via active_raw_retention_authority/the file-set recency heuristic, an orthogonal concern from census membership, so it's not expected to reproduce that failure mode. Two follow-ups filed for what this PR deliberately leaves open:

  • polylogue-7f8yc: teach the reconciler a typed outcome for "this census plan's raw evidence is already gone" instead of falling through to a generic RuntimeError.
  • polylogue-4uzoo: the pre-existing (not introduced by this PR) plan_count/pagination staleness that prune_raw_authority_census_history itself already has once its own plan-retention window elapses and a census header outlives its plan detail. This PR's design was specifically checked to never trigger that bug any earlier than it already fires today, since it never touches census_plans/post_plans at all.

Verification

  • devtools test tests/unit/storage/test_raw_retention.py -- 64 passed. test_superseded_raw_cleanup_prunes_orphaned_raw_authority_plans now seeds four plans: one with zero census references (pruned), one still referenced by a live census_plans row (untouched -- asserts raw_authority_censuses.plan_count still matches the actual surviving raw_authority_census_plans row count for that census, before and after the purge: the ledger-consistency proof the review asked for), one referenced only by an unresolved blocker (untouched, defensive), and one whose raw survives (untouched, not even an orphan candidate).
  • devtools test tests/unit/storage/test_repair.py -k superseded -- 3 passed.
  • devtools verify --quick -- exit 0 (also ran via the pre-push hook).

Ref polylogue-i3zo.

Problem: cleanup_superseded_raw_snapshots deletes raw_sessions rows for
retention-driven purge, but raw_authority_plans/blockers/census_plans/
census_post_plans reference raws via a JSON string (input_raw_ids_json),
not an FK, so nothing cascades. A plan whose every input raw is gone
survives the purge and the daemon reconciler's next convergence pass
throws RuntimeError("duplicate strategy did not reach its typed
terminal postcondition") on the dangling plan -- the same live-incident
shape previously patched only for the now-deleted one-time
hook-deinflation repair (unmerged commit c2554a6, "prune orphaned
raw-authority plans in hook-deinflation repair"; that repair module
was deleted in ee22574 once it had run, but the pruning logic never
migrated to ordinary retention).

What changed:
- raw_retention.py: new _delete_orphaned_raw_authority_plans, called in
  the same transaction as (and right after) the raw_sessions DELETE in
  cleanup_superseded_raw_snapshots. Set-based orphan identification
  (json_each expand + LEFT JOIN on the raw_id PK + GROUP BY, keeping
  plans whose inputs are ALL missing) instead of correlated subqueries,
  with temporary plan_id indexes on the three child tables so both the
  IN-delete and FK checks are index-driven; both perf fixes are carried
  over from the same prior-art commit, which measured a >1h hang on the
  live archive without them.
- RawSnapshotCleanupResult gets a new deleted_orphaned_authority_plan_count
  field (default 0, additive); compact_paths_superseded_raw_snapshots
  accumulates it; repair.py's superseded-raw-snapshot repair detail
  reports it when non-zero.

Design decision -- hard delete, not a soft terminal-state transition:
mirrors the only prior art for this exact gap (the unmerged
hook-deinflation commit). A plan is durable evidence of a reconciliation
*attempt*; once every raw it names is gone it cannot be replayed,
retried, or inspected against source evidence, and nothing reads
historical plans for audit purposes. This differs from user.db
assertions (durable, human-authored, always additive) and from
superseded-but-still-byte-reconstructible raw revision chains, so those
patterns don't apply here.

Verification: devtools test tests/unit/storage/test_raw_retention.py
(64 passed, including new
test_superseded_raw_cleanup_prunes_orphaned_raw_authority_plans, which
seeds a plan naming only the about-to-be-deleted raw plus one naming a
surviving raw, runs cleanup_superseded_raw_snapshots, and asserts only
the orphan (and its blocker/census rows) is pruned);
devtools test tests/unit/storage/test_repair.py -k superseded (3
passed); devtools verify --quick (exit 0).

Ref polylogue-i3zo.

Co-Authored-By: Claude <[email protected]>
@coderabbitai

coderabbitai Bot commented Aug 1, 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: 13 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: 892d259e-197e-4e08-b107-b905dd9d081a

📥 Commits

Reviewing files that changed from the base of the PR and between 84f82f3 and 46b12a0.

📒 Files selected for processing (3)
  • polylogue/storage/raw_retention.py
  • polylogue/storage/repair.py
  • tests/unit/storage/test_raw_retention.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 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: 462283899e

ℹ️ 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 polylogue/storage/raw_retention.py Resolved
Problem: the previous version of this fix (this same PR) deleted
raw_authority_census_plans / raw_authority_census_post_plans /
raw_authority_blockers rows for any orphaned plan (all input raws
gone), unconditionally, before hard-deleting the plan itself. A
real automated review (chatgpt-codex-connector, PR #3530) found this
corrupts the immutable census ledger: raw_authority_censuses.plan_count
/ post_plan_count are read verbatim by read_raw_authority_census as
both the reported total and the pagination-termination signal
(next_offset < max(total, post_total)). Deleting a census's
plan-membership rows without adjusting those counts makes the total
lie, and once every plan-membership row for a census is gone,
next_offset (driven by len(plans), now always 0) stops advancing --
next_query_handle is reissued forever. Deleting an unresolved
raw_authority_blockers row is worse: prune_raw_authority_census_history
(same module) already treats an unresolved blocker as "a live durable
obligation, not history" and refuses to touch it for exactly this
reason; the previous draft silently dropped that obligation.

What changed: _delete_orphaned_raw_authority_plans no longer deletes
from raw_authority_census_plans / _post_plans / raw_authority_blockers
at all. It only hard-deletes a raw_authority_plans row once it ALSO has
zero remaining references in all three of those tables. This composes
with, rather than fights, prune_raw_authority_census_history: every
raw_authority_plans row is inserted in the same transaction as its
owning census's raw_authority_census_plans row, so a plan can only
reach zero census references once that function's own plan-retention
window (8 generations) has already judged its census-plan detail safe
to drop -- which it only does once no unresolved blocker remains. This
function therefore never advances that judgment early and cannot
itself corrupt plan_count/post_plan_count, because it never deletes
the rows those counts describe.

Consequence, stated honestly: a plan still referenced by an active
('planned', unresolved) census is left untouched even if every raw it
names is already gone. Filed polylogue-7f8yc to give the reconciler a
typed outcome for that case instead of falling through to a generic
RuntimeError, and polylogue-4uzoo for the pre-existing (not introduced
here) plan_count/pagination staleness that prune_raw_authority_census_history
itself already has once its own plan-retention window elapses --
verified this PR's design cannot trigger that bug any earlier than it
already fires today, since it never touches census_plans/post_plans.

Verification: devtools test tests/unit/storage/test_raw_retention.py
(64 passed) -- the regression test now seeds a plan with zero census
references (pruned), a plan still referenced by a live census_plans row
(untouched, plan_count vs actual surviving row count asserted equal
before and after the purge -- the ledger-consistency proof the review
asked for), a plan referenced only by an unresolved blocker (untouched,
defensive), and a plan whose raw survives (untouched). devtools test
tests/unit/storage/test_repair.py -k superseded (3 passed). devtools
verify --quick (exit 0).

Ref polylogue-i3zo.

Co-Authored-By: Claude <[email protected]>
@Sinity
Sinity merged commit 665ca1d into master Aug 1, 2026
3 checks passed
@Sinity
Sinity deleted the feature/fix/raw-retention-orphaned-authority-plans branch August 1, 2026 20:08
Sinity added a commit that referenced this pull request Aug 2, 2026
…story (#3559)

## Summary

Fixes the census/plan-ledger side of the raw-authority obligation-guard
defect: `prune_raw_authority_census_history`'s per-census plan-row
window (`RAW_AUTHORITY_CENSUS_PLAN_RETENTION`) no longer stays
permanently pinned by a structurally-unresolvable blocker. Census
headers keep their guard (a real FK), plan-row detail now prunes on the
ordinary retention window regardless of blocker state.

## Problem

`polylogue-z7ko` and `polylogue-f4z9` describe the same mechanism from
two angles:
`raw_authority_census_plans`/`raw_authority_census_post_plans` (a
durable `source.db` tier) grew ~100k rows/hour, reaching 709,264 rows
and ~870 MiB, with only 41 of the ~112 most recent censuses (sequence
820-932) holding plan rows at all — far more than
`RAW_AUTHORITY_CENSUS_PLAN_RETENTION=8` should allow. `fixed_point`
never reached 1 on any of 256 censuses ever measured.

Root cause: `prune_raw_authority_census_history`'s plan-row window
required every blocker attached to a census to be resolved before that
census's `raw_authority_census_plans`/`_post_plans` rows could be
dropped. The dominant blocker reason ("accepted raw authority remains
quarantined pending exact refinement proof", ~4,400 rows) is a
structurally permanent fact about a raw's own data — nothing about it
changes between census passes, so it never resolves. Continuous live
ingestion keeps producing new instances of this same permanent
obligation; each one anchors whichever census first observed it, and
that census's entire plan-row snapshot stays pinned forever. Over time
more and more censuses accumulate this pin, which is why the guard
eventually stopped bounding growth at all despite existing.

I verified this is a genuinely separate exception from `polylogue-wkc6`
(PR #3530, already merged): that PR fixed pruning of *orphaned*
`raw_authority_plans` rows (plans no census references at all). This
PR's guard is a different code path in the same function — the
*per-census plan-row retention window itself* refusing to advance while
any attached blocker is open, which `wkc6` did not touch.

I also checked `polylogue-u19l` (PR #3539, merged,
`live_source_reconciliation.py`): that module is a read-only classifier
over `raw_sessions.revision_authority='quarantined'`, entirely separate
from the `raw_authority_blockers`/census obligation mechanism this bug
lives in — it never marks a blocker resolved and isn't wired to this
guard. It is not usable to unblock this issue's plans, because the
underlying obligation here is not "unproven," it's provably permanent
(see `_strategy_overrides`' ineligible branch in `raw_reconciler.py`,
from the already-merged PR #3466).

## Solution

`polylogue/storage/raw_authority.py`,
`prune_raw_authority_census_history`:

- The plan-row window (`raw_authority_census_plans`/`_post_plans`) now
deletes purely by the `sequence_no` retention floor, unconditionally. A
blocker's own `expected_json`/`observed_json` columns already carry a
complete, self-contained snapshot of the plan and its evidence (written
by `_reconcile_frontier_obligations`), and
`resolve_raw_authority_blocker` reads that plus the census-independent
`raw_authority_plans` table — never
`raw_authority_census_plans`/`_post_plans`. So gating this window on
blocker resolution bought nothing but the unbounded pin.
- Already-*resolved* blockers tied to a pruned census are deleted in the
same pass (nothing needs them once their census ages out);
still-*unresolved* ones are left alone — deleting those would be the
actual "silently report the obligation as cleared" failure mode the old
guard existed to avoid.
- The header window (`raw_authority_censuses`) keeps its existing guard
unchanged: `raw_authority_blockers` has a real foreign key on
`census_id`, so a header can only be dropped once nothing references it.

No schema/DDL change: `source.db`'s table definitions are untouched,
this is a behavior-only fix to an existing maintenance routine that
already runs inside every census-recording transaction.

## What's intentionally out of scope

- The underlying quarantine pile itself (why ~4,400 raws are permanently
ineligible) is `polylogue-u19l`'s territory, already addressed there.
- A full `RawAuthorityReconciler` rewrite
(`polylogue-lkrc`/`hjpx`/`yla8`) remains explicitly gated on separate
operator authorization.
- I don't touch `_reconcile_frontier_obligations`'s blocker-insert path
at all: I initially suspected `blocker_id` being keyed on `(census_id,
plan_id)` caused duplicate unresolved rows per pass, but a pre-existing
partial unique index (`idx_raw_authority_blockers_open_plan` on `plan_id
WHERE resolved_at_ms IS NULL`) already prevents that — there is exactly
one unresolved blocker row per `plan_id`, always. That hypothesis was
wrong; I reverted the speculative change once I found the index and
re-diagnosed against the actual mechanism above.

## Verification

```
devtools test tests/unit/storage/test_raw_authority_ledger.py tests/unit/storage/test_raw_retention.py
devtools verify --quick
```

New test
`test_census_plan_rows_prune_past_retention_even_with_an_unresolved_blocker`
plants a durable, permanently-unresolved blocker on the first of nine
census passes and asserts: the blocker itself is never silently marked
resolved; its census header survives (the real FK); its plan-row detail
prunes to the retention window like any other census's. Confirmed this
test fails against the pre-fix code (`assert 'census:1:...' not in
{...}` — the first census's rows were still present after 8 more passes)
and passes after.

10 pre-existing failures in `test_raw_authority_ledger.py` are unchanged
before and after this diff (verified against both the pre-fix and
post-fix tree) — an unrelated `_write_codex_raw` test-fixture regression
where an empty-text message is now rejected by dispatch ("no messages,
no positive conversational evidence"). Not touched by this PR; filing a
follow-up bead is worth doing separately.

Ref polylogue-z7ko
Ref polylogue-f4z9

Co-authored-by: Claude <[email protected]>
Sinity added a commit that referenced this pull request Aug 2, 2026
Problem: polylogue-wkc6 (census-plan bookkeeping 89% of source.db, growing
~1GB/day) overlapped in scope with the in-flight raw-authority redesign
(polylogue-lb39z Phase 1, polylogue-w6hql Phase 2), so it needed an
investigation to determine whether it was already covered or needed its own
action.

What changed: verified live against /realm/db/polylogue that the bead's
urgent retention ask already shipped in a prior session (PR #3390 wires
prune_raw_authority_census_history into the census-record path; PR #3530
adds _delete_orphaned_raw_authority_plans). Current live state:
raw_authority_census_plans/post_plans steady at 761,602 rows each (down from
6,621,562/6,621,527 on 2026-07-29), source.db shrunk 6.6GB->1.48GB,
freelist_count=0. Closed wkc6 with that evidence. Its two remaining
architectural DO items (stop recording carried_forward rows at all; decide
whether census bookkeeping belongs in the durable vs disposable tier) are
real but non-urgent and distinct from w6hql's "collapse verdict vocabulary"
scope, so they're split into a new bead (polylogue-ubdxf) rather than lost.
Cross-referenced the finding on w6hql's notes.

No source code changed this session -- this was a verification-only
investigation confirming a previous fix already landed and is holding.

Co-Authored-By: Claude <[email protected]>
Sinity added a commit that referenced this pull request Aug 2, 2026
Problem: polylogue-wkc6 (census-plan bookkeeping 89% of source.db, growing
~1GB/day) overlapped in scope with the in-flight raw-authority redesign
(polylogue-lb39z Phase 1, polylogue-w6hql Phase 2), so it needed an
investigation to determine whether it was already covered or needed its own
action.

What changed: verified live against /realm/db/polylogue that the bead's
urgent retention ask already shipped in a prior session (PR #3390 wires
prune_raw_authority_census_history into the census-record path; PR #3530
adds _delete_orphaned_raw_authority_plans). Current live state:
raw_authority_census_plans/post_plans steady at 761,602 rows each (down from
6,621,562/6,621,527 on 2026-07-29), source.db shrunk 6.6GB->1.48GB,
freelist_count=0. Closed wkc6 with that evidence. Its two remaining
architectural DO items (stop recording carried_forward rows at all; decide
whether census bookkeeping belongs in the durable vs disposable tier) are
real but non-urgent and distinct from w6hql's "collapse verdict vocabulary"
scope, so they're split into a new bead (polylogue-ubdxf) rather than lost.
Cross-referenced the finding on w6hql's notes.

No source code changed this session -- this was a verification-only
investigation confirming a previous fix already landed and is holding.

Co-Authored-By: Claude <[email protected]>
Sinity added a commit that referenced this pull request Aug 2, 2026
## Summary
Investigation bead polylogue-wkc6 (census-plan bookkeeping at 89% of source.db, growing ~1GB/day) is closed: its urgent retention ask already shipped in a prior session and is verified holding live. Remaining architectural items split into a new bead so they aren't lost.

## Problem
wkc6 overlapped in scope with the in-flight raw-authority redesign (polylogue-lb39z Phase 1, polylogue-w6hql Phase 2), so it needed investigation to determine whether it was fully covered by that track or needed its own action.

## Solution
No source code changed. Verified live against /realm/db/polylogue that PR #3390 (wires `prune_raw_authority_census_history` into the census-record path) and PR #3530 (`_delete_orphaned_raw_authority_plans`) already landed and are holding: `raw_authority_census_plans`/`_post_plans` steady at 761,602 rows each (down from 6,621,562/6,621,527 measured 2026-07-29), `source.db` shrunk 6.6GB -> 1.48GB, `PRAGMA freelist_count`=0.

Closed wkc6 with that evidence. Its two remaining architectural DO items (stop recording carried_forward rows at all; decide durable vs disposable tier placement) are real but non-urgent, and distinct from w6hql's "collapse the verdict vocabulary to one closed enum" scope -- split into polylogue-ubdxf and cross-referenced on w6hql's notes.

## Verification
- `bd show polylogue-wkc6 --json` / `bd show polylogue-ubdxf --json` / `bd show polylogue-w6hql --json` reflect the new state.
- Live query against `/realm/db/polylogue/source.db` (read-only): census/plan/post-plan row counts and file size as stated above.
- `gh pr view 3390/3530 --json state,mergedAt` confirm both MERGED.
@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.

  • 72.F093 / P1: stale at the checked revision: The immutable census/plan-membership ledger being partially deleted is retired, as documented at polylogue/storage/sqlite/archive_tiers/source.py:591-592. The retained blocker row now carries its own expected_json evidence at :604 and is not a child of a pruned raw plan, eliminating the old orphaned census totals and zero-advance pagination route.

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