Repository navigation
fix(read): Bound the session loaders and share the page budget equally - #5381
Conversation
The database-backed session routes composed a whole transcript to serve a window, and numbering one message in a prefix-sharing lineage child needed the same composition. Both now read what they serve. `ArchiveStore.locate_composed_message` answers a composed index from the segment plan `read_archive_session_page` already windows with: one indexed count per ancestor plus one rank count, never a composed transcript. Head statements are `5·links + 1` -- 21 for a 4-link chain and 81 for 16, at both 40 and 400 messages per link. `Polylogue.get_session_page` is the bounded twin of `get_session`, and both now go through one reader so they cannot drift about hydration, display labels or content projection. `_do_get_session` serves its declared window from it; `_do_get_messages` reads the session row rather than the session, places its semantic cards over the window it serves (as the archive-backed twin and the CLI already do), and resolves a deep link through the shared window route. `word_count` now comes from the session summary on that route: summing the rows served would report the window's word count as the session's. `locate_message_in_order` is removed with its last caller. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01ToWqpkXotr573DiQex5vcy
polylogue-fvsjn: attached-unit truncation was distributed arbitrarily across a
page. The page ceiling was spent in the page's own row order, so a long session
could take the allowance a short one never received.
A tail-first read is where that bit hardest. Measured on a skewed page -- one
5-message session followed by 13 sessions of 400 -- a `last:5` projection gave
every long session its 5 rows and the short session ZERO, inside a clean
envelope. Nothing in the result distinguished "this session has no messages"
from "this session's allowance was eaten".
Every selected session now gets the same allowance,
`min(_MAX_ROWS_PER_SESSION, _MAX_ROWS_PER_PAGE // session_count)`, so what a
session receives no longer depends on how many sessions share the page or where
its rows sort within it. Both declared ceilings still hold; only their
distribution changed. One row past the allowance is requested and discarded, so
reaching it is observed rather than inferred from a count that could
legitimately equal the bound.
A page holding more sessions than the ceiling can give a row each raises
`AttachedUnitPageTooWideError` rather than serving nothing for every session.
Under the 2026-09-21 ruling an allowance of zero is not a bound on the answer,
it is the absence of one, and quietly serving nothing would be exactly the
silent truncation this module exists to stop reporting as complete.
Verification (exit codes read directly, not through a filter):
devtools test tests/unit/archive/test_with_units_projection.py \
tests/unit/storage/test_archive_tiers_write.py -> PASSED exit=0
receipt .cache/verify/runs/20260922T011906Z-focused-test-244363-545cee4f/run.json
Anti-vacuity EXECUTED, not asserted. Mutating `_per_session_allowance` to ignore
`session_count` and capping the fetch at `_MAX_ROWS_PER_PAGE` -- the pre-fvsjn
shared budget -- turns the suite red (`devtools test` FAILED exit=1, 2 tests).
Directly measured on the skewed page: mutated `last:5` gives short=0,
long={5}, starved=1; restored, short=5, long={5}, starved=0.
An earlier pair of tests over 26 *uniform* sessions was discarded: the same
mutation left them green, because a flat page limit spread over equal-size
sessions already lands on roughly equal counts. Only the skew above separates
the fix from the defect.
Schema identity: attached_units.py, archive.py and archive_query_reads.py are
all closure IN; the derived index identity moves to 4700fef2.., ops unchanged at
86866235... Closure membership is unchanged. Must land before a fresh rebuild
starts, never during one.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01ToWqpkXotr573DiQex5vcy
|
Warning Review limit reachedNext included review available in 13 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 (13)
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. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 00a3002976
ℹ️ 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".
| source_sql = f"""( | ||
| SELECT m.*, {_per_partition_rank_sql("m.session_id", order_by)} | ||
| FROM messages m INDEXED BY idx_messages_session_position | ||
| WHERE {filter_clause} | ||
| ) m""" |
There was a problem hiding this comment.
Bound each partition before computing window ranks
For a session with a very large message history, the new ROW_NUMBER() subquery ranks every matching message before the outer unit_rank <= ? filter and LIMIT can apply. Thus with messages on a one-million-message session scans and sorts the whole million-row partition to return the 201-row allowance/probe, whereas the previous indexed ORDER BY ... LIMIT could stop at the cap; the same ranking shape is also used for actions and assertions. Apply a bounded indexed read per selected partition rather than using an unbounded window function, otherwise the declared row ceiling no longer bounds database work.
Useful? React with 👍 / 👎.
## Problem `query_session_messages(per_session_limit=...)` ranked every matching row of every selected session with `ROW_NUMBER() OVER (PARTITION BY m.session_id ...)` and applied `unit_rank <= ?` only in the outer query. The declared row ceiling therefore bounded the answer but not the work: a session with a very long history sorted its whole history to hand back a 201-row allowance. Measured on a seeded archive, the same 201-row page cost 427k / 813k / 1585k VDBE step units over 2,000 / 4,000 / 8,000-message sessions, against a flat 42k for the unbounded indexed read the window replaced. ## Solution `idx_messages_session_position` covers `(session_id, position, variant_index)`, which is exactly this read's order, so each session's allowance is now a bounded indexed read that stops at the cap. The candidates are merged, ordered and paged, and the expensive projection (repo rollup, block text) runs only on the page's rows rather than on every session's allowance. The fairness property the window was introduced for is unchanged: each session still contributes at most `per_session_limit` rows chosen in its own transcript order, so the equal-allowance guarantee and the named truncation gap from #5381 still hold over the SKEWED fixture. ## Verification Same page, same partition sizes, after the change: 47k step units at 2,000, 4,000 and 8,000 messages. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01ToWqpkXotr573DiQex5vcy
…tier (#5408) ## Summary Seventeen live P1 review findings closed across the storage tier, consolidating two review lanes that were dispatched over overlapping finding sets. Supersedes #5406, whose six non-overlapping fixes are cherry-picked here with `-x` attribution. ## Problem A `git blame` filter over the review backlog selected 80 storage P1 findings whose anchored line had not moved since review. Full triage at HEAD: **49 LIVE, 27 STALE, 4 WONTFIX** — the filter over-selects by ~34% in this area, with no detectable false negative. Its failure mode is exactly as predicted: heavy refactors move code without touching the anchored line (`bootstrap.py` was 6-for-6 stale after its rewrite), and the durable-lineage reset invalidated the whole v37/v40 migration family. Two lanes worked this set concurrently and independently fixed three of the same defects. Landing both would have meant a 12-commit rebase across three shared files, so they are consolidated here instead. ## Solution **Reads and cost** - `archive_query_reads.py` ranked the entire partition before applying `unit_rank <= ?`. Measured at base on seeded archives, one 201-row page: **427k / 813k / 1585k VDBE step units** over 2,000 / 4,000 / 8,000-message sessions — linear in partition size — against a flat 42k for the indexed read. `_bounded_partition_message_ids` now does one indexed `ORDER BY … LIMIT` per selected session over `idx_messages_session_position`, merges, orders and pages the candidates, then runs the expensive projection on the page alone. **After: flat 47k at all three sizes.** #5381's fairness contract is preserved — each session keeps the same allowance in its own transcript order — and its SKEWED fixture still passes. **Durable integrity** - The `additive-no-backup` marker was a self-declaration nothing checked: `_requires_migration_backup` read the header and never looked at the statements. The finding is **declined as filed** — that classification is operator-ratified from #2905 with its own authorization mode, and slot 002 is one `CREATE TABLE IF NOT EXISTS` that writes, reads and moves no row — but the unchecked claim is now proved: a file claiming the marker must contain only `CREATE TABLE/VIEW/INDEX`, refused by name otherwise. Slot 002 still loads `requires_backup=False`, so no shipped behaviour changed. - A durable tier below its recorded birth version was accepted. Bootstrap stamps `tier_versions.source = 2`; a transplanted version-1 database cleared the floor and skipped the fingerprint because `1 != 2`. The condition is now `version <= versions[tier]`, so the below-birth case is decided by the recorded fingerprint rather than bypassed. - `acquired_with_bytes_count` decided coverage with `BlobStore.exists`, so an object overwritten at the recorded hash's path counted as coverage with both debt counters zero and `ok` true. It now requires a re-hash, and a present-but-contradicted object lands in a new `acquired_corrupt_count` bucket kept **separate** from `acquired_missing_blob_count` — the object is present, so re-fetch is the wrong remedy. - `additional_blob_refs` bypassed the excision ledger. **Lineage** - `_record_lineage_prefix_debt` resolved `ops.db` via `PRAGMA database_list`, which SQLite answers with the *resolved* promotion symlink, so on a promoted generation it named a nonexistent file and returned silently. New `archive_root_for_index_path` unwinds the generation directory; `index_generation._is_generation_member` now delegates to it so the depth rule has one definition. - A witness-mismatched branch point was re-anchored onto different content. The re-anchor now applies only when the replacement's content address matches the stored witness; otherwise the edge stays dangling, is counted, and its child is named stranded with retryable debt. The repairable half still re-resolves in-write. - Recursive topology DFS hit `RecursionError` at the writer's own 1024 budget. The iterative walk handles an 1100-deep lineage, and **3000 random graphs produce identical cycle sets under both implementations**. - A relocated lineage anchor was not reported as resolved. **Saved views, frontier, misc** - View rename and delete both left `query_names.watch = 1`, so one saved view returned two watched definitions and a deleted view stayed watched. Both bindings are cleared in the same transaction as the upsert/tombstone. - A content-addressed `pass_id` made `INSERT … ON CONFLICT DO NOTHING` never reopen an acknowledged obligation whose evidence still reproduced. Reconciliation now mints a successor derived from the row it supersedes, so the operator's resolution receipt stays intact and repeated identical passes converge on the same successor. A chain beyond 64 is refused by name. - Source blob authority is earned from the catalog, not the stamp. The version-1 instance is stale (#5387 raised `SOURCE_TIER_VERSION` to 2), but the collision moved with the stamp: a pre-reset database stamped exactly 2 reproduces it today. - EOF after a short HTTP body persisted as `acquired` instead of `partial`; durable-writer lease checks used `self.archive_root` rather than the declared root; an unreadable schema identity became a non-transient skew instead of a retry. ## Conflict resolution The two lanes' frontier fixes **diverge semantically**. #5406 reopens the same row, keeping the original `blocker_id`; this branch mints a successor id. Its test asserting the id is unchanged is therefore true of its fix and false of this one, so it was deliberately **not** taken — only the topology half of that commit is cherry-picked, with the reasoning in the commit message. `tests/unit/storage/test_frontier_reopen.py` pins the behaviour that actually ships. ## Verification Rebased onto master `17566b048` and re-verified there. Two gate failures were found and fixed during the rebase, both described below. - `devtools verify --quick` → **25/25 gates green** at `03bc4b0f8` pre-rebase; re-run clean after each rebase fix. - `devtools gate layering` → **exit 0, 0 violations** (it was red mid-rebase; see below). - `devtools gate atlas` → **exit 0**, "Every atlas citation and declared owning gate resolves", 40 checkable symbol claims, **0 misaimed** (was 1). - `devtools render all --check` → exit 0, `grep -c 'out of sync'` = **0**, checked explicitly rather than inferred from the exit code. - Focused batch A (7 files) → **exit 0, 40/40**. Receipt `.cache/verify/runs/20260922T072851Z-focused-test-1387181-0795e112/`, `git_head dc2222cbb`, not dirty. - Focused batch B (7 files) → **exit 0, 62/62**. Receipt `.cache/verify/runs/20260922T072855Z-focused-test-1387396-15cfa190/`. - The delta from the tested SHA `dc2222cbb` to final head `9aa1a247b` is `docs/atlas/daemon.md` and `docs/plans/durable-write-census.yaml` only — both gate inputs that no test reads. Stated rather than claiming the receipts name the tip. - Pre-consolidation each lane established its own inherited-red baseline by detaching at `9f450db36` and diffing failing nodeid sets programmatically: `NEW = []`, `FIXED = []` on the durable-migration suites (44 inherited), and an identical two-nodeid inherited set on the daemon preflight suites. Neither absorbed nor fixed here. ### Two gates went red during the rebase **`gate layering`.** #5393 adjudicated the `query_names` watch entry to `lifecycle_transition` but kept the key on `register_query_watch`, which after this branch delegates rather than writing. The gate reported exactly that pair — `durable_write_census_stale` on the old key plus `durable_write_undeclared` on `clear_query_watch`. The key is moved to the owner that holds the statement; #5393's classification and reason are kept verbatim apart from naming that owner. Same statement, same guard `WHERE name = ? AND watch = 1`, one owner. **`gate atlas` is red on master, not on this branch.** Both cited files are byte-identical here to `17566b048`, and the gate reproduces the same single misaimed anchor at either head. #5407 moved `hook_carriers` in `intake_adapters.py` from the cited `1116-1132` to `1147-1165`, and the symbol check that notices this is recent enough that #5407's own verification predates it — a gate going red on master from two separately-green PRs. The prose is still true, so the anchor is re-aimed rather than rewritten: `FileIntakeAdapter(..., class_name="hook_carrier")` at `:1156` and the multiplexed registration at `:1165` still say what the sentence claims. ### Anti-vacuity, executed Every mutation was applied, run, and reverted — not asserted: - window rank → `allowance cost follows history: 330 -> 1199 step units for the same 201-row allowance` - watch bindings → `a deleted view's name is still watched` / `the previous name is still watched beside the new one` - ops.db root → the generation case went red while the plain-archive and no-ops-tier cases stayed green, proving the fix is not a blanket change - witness → `re-anchored onto a different message`, with `test_witness_agreement_still_repairs` green under the same mutation - attachment coverage → `a contradicted object was certified as coverage` - birth version → `DID NOT RAISE RuntimeError`, both opposite-direction cases green - source blob authority → only the `stamp_offset=0` parametrisation went red; the other two staying green **is** the evidence the finding as filed is stale - frontier reopen → `assert successor_id != original_id`, both opposite-direction cases green - additive claim → `DID NOT RAISE MigrationError` - excision ledger → both writers `ACCEPTED the excised sibling`, refs `0 → 4`; after, both refuse and an admissible sibling still writes - short body → `state=acquired retryable=False diag=''` → `state=partial retryable=True`; correct-length and undeclared-length stay `acquired` - topology → `RecursionError` over an 1100-deep accepted lineage - schema identity → `SchemaSkewError … found None` → `SchemaVersionMismatchError lifecycle_action=retry` Every test file also pins the opposite direction, so a blanket refusal or a no-op cannot pass. ## Schema closure Re-measured at the consolidated head, including the cherry-picked files the deeper lane never measured. **IN (13):** `archive_identity.py`, `index_generation.py`, `materials.py`, `derived/topology/derivation.py`, `sqlite/schema.py`, `sqlite/schema_bootstrap.py`, `sqlite/migration_runner.py`, `sqlite/query_watch.py`, `archive_tiers/{archive,archive_plan,archive_query_reads,source_write,write}.py` **out (4):** `maintenance/archive_verification.py`, `operations/ref_resolution.py`, `storage/blob_integrity.py`, `storage/raw_reconciler.py` Membership is unchanged, so `gate schema-closure` needed no `--update` and passes. - `DerivedTier.index`: `752d44b9ad5a2d0d08fdff7eababe6334575ea4223a44d60b05c41f9ea0eced2` (base `17566b048`, measured in a detached worktree at that exact SHA) → **`c284f2341743d8a8ac36009fe8281dfe206f04ad795c8221f3798ceb2bdd636b`** - `DerivedTier.ops`: `86866235…` **unchanged** The archive must reconverge. **This must land before a fresh rebuild starts, never during one.** Both values are measured at the current base rather than the stale one the lane first reported; re-measure again if master moves before merge. ## Scope expansion (declared) - `polylogue/maintenance/archive_verification.py` — the attachment-coverage fix is inert without it; the reviewer's complaint names the surface, so `acquired_corrupt_count` had to enter `debt_count`, `details` and the summary, and the green wording moved from "have bytes" to "re-hash to their recorded bytes". - `docs/plans/durable-write-census.yaml` — moving the `query_names` watch-clearing UPDATE into `clear_query_watch` made `gate layering` red with one `durable_write_undeclared` and one `durable_write_census_stale`. The commit renames exactly that one key (same statement, same table, one owner) and is isolated as `7e38022b6` so it can be reverted alone. - `tests/unit/storage/test_durable_change_train.py` — three rollback tests reached their mid-apply failure with `INSERT INTO table_that_does_not_exist` under an `additive-no-backup` header, which the new guard refuses at discovery. The fixture now fails additively (two conflicting `CREATE TABLE durable_items`), raising at the same point with an additive-only statement set and preserving every assertion. Isolated as `fa7965cf8`. - `polylogue/operations/ref_resolution.py` — the relocated-lineage finding is anchored in `storage/block_anchor.py`, but the resolver is correct; the consuming boundary that drops the state lives in `operations/`. ## Residuals - **Watch baseline** (#5375) reproduces and is **not** fixed. `save_view(watch=True)` writes `queries` + `query_names` only, and `_materialize_watch_evaluation` returns early when `baseline is None`, so the first archive change after creation is absorbed silently. The remedy needs scheduling the storage tier does not own: neither creation route carries a `CanonicalPlanEvaluator` (it is injected into the daemon stage by `make_standing_query_stage`), and calling a planner from the substrate is a substrate→surface import the ratchet forbids outright. `get_watched_query_baseline(...) is None` is already the durable "never evaluated" signal, so no migration is needed for the state — only something that drives an evaluation after creation. For the daemon/standing-query owner. - **FK-cascade deletion** — `_delete_sessions_without_fk_cascade` discovers only tables with a direct `REFERENCES sessions` FK. Five tables moved to `FOREIGN KEY(message_id, session_id) REFERENCES messages(...)`, so with FKs suspended during bulk ingest a session replacement commits orphaned attachment/paste/edit/web-content/action rows. Needs a transitive closure through `messages`/`blocks`; the fix site is in `pipeline/`. - **Readiness** still treats an absent blocker row as proof, and `inspect_raw_authority_frontier` has no daemon stage. This branch closes the reopen half only. - **Archive-root cluster** — root derived from the active index's physical directory rather than `archive_file_set_root` also affects blob GC, Drive catch-up, and two unleased bootstrap/adoption paths. Not fixed: each moves a refusal on a route not exercisable without a real daemon lease. - `scan_attachment_coverage` now re-hashes every acquired attachment blob on every call. `archive verify` already re-hashes the whole namespace, but other callers were not surveyed for a cost budget; a presence-only projection would need its own explicitly-named unverified term, never a silent fallback. - The `additive-no-backup` guard excludes `CREATE TRIGGER` deliberately — it destroys nothing at apply time but arms future writes against existing rows. A legitimately additive trigger migration is the decision to revisit; that is a judgement call, not a measurement. - `_iter_migration_statements` duplicates the statement-splitting logic of `_execute_migration_sql`; they should share one splitter, kept separate here to avoid touching the apply path in a review sweep. - `relink_orphaned_attachments` still has no production caller. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01ToWqpkXotr573DiQex5vcy <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit - **Bug Fixes** - Attachment verification now detects corrupted content instead of treating it as valid. - Incomplete downloads are marked retryable when fewer bytes arrive than declared. - Relocated references now report as resolved when valid. - Saved-view watches are correctly retired during rename and deletion. - Excised attachments can no longer be reintroduced through session imports. - Schema read failures now receive retryable handling instead of incorrect rebuild guidance. - **Performance** - Large per-session message queries use bounded reads to reduce unnecessary database work. - Deep lineage processing no longer risks recursion-limit failures. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
## Summary Bounds three read/queue paths from the read-bounds bug family: yooge, buuxr, 1gxyu. ## Problem - **yooge:** `DeferredEffectQueue` stored a receipt per `effect:staleness_key` for the process lifetime. The key embeds the batch's session ids, so it grew with every distinct ingest batch in a long-running daemon. No production code reads those receipts. - **buuxr:** a full-scope insight rebuild ran `list_summaries(limit=1_000_000)` and built four archive-sized collections (manifest JSON, targets, target refs) per `prepare`, twice per mutation. `apply` ignores them for the full scope. On an archive past the plan's target ceiling, `build_plan` refused to plan the rebuild at all. - **1gxyu:** attachment availability on every session read called `BlobStore.verify`, which streams and SHA-256s the whole blob, so reading a session with large attachments cost their full size every time. ## Solution - **yooge:** the queue keeps only the in-flight key set (for de-duplication) and drops settled deliveries; failures are still reported by `archive.write_effect.failed`. The unused receipt API is removed. - **buuxr:** a full-scope plan carries no per-session targets; its manifest digest is the scope identity (scope, index path, materializer version). Explicit scopes still name their sessions. - **1gxyu:** read paths use `BlobStore.verify_for_read`, which hash-verifies once and then trusts the result while the blob file keeps the same device, inode, size and nanosecond mtime; any change forces a full re-hash. The memo is a pacing bound (eviction only re-hashes). `verify`/`verify_all` stay uncached integrity checks. Already fixed on master, recorded on the beads: fvsjn (per-session bounds, #5381) and 0bn4p (facet scope bound with a named `facet_scope_truncated` gap and shared cancellation). ## Verification - `devtools test` over the three new test files plus `test_mutation_actuators.py` and `test_blob_store.py`: all passed except `TestSessionExcisionActuator::test_prepare_and_apply_expose_marker_carrier_terminal_evidence`, which fails with `UnclassifiedSessionCarrierError: raw_existence_changes` — a table added on master by #5657 without an excision carrier declaration, not touched here. - `devtools schema closure`: all five production files are IN; this must land before the fresh build. ## Residuals - 2fguj (per-row text materialized before truncation) and gzmd4 (several unbounded storage reads) need a query-contract change and stay open. - `verify_for_read` does not detect an in-place rewrite that restores the same size and nanosecond mtime. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_013Vn4qhKjhyaVBG4aPiqNW4 --------- Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
…#5785) ## Summary This PR salvages ChatGPT fleet worker 12's Codex-debt batch (beads `polylogue-1tyq5.55`, `.56`, `.60`, `.62`; 72 findings) and turns it into verified changes. Five fixes land with regression tests that fail on master. The worker's sixth fix (a negative completion cache) was dropped, and its health-check fix was replaced with a stricter version. ## Problem - **55.05** `health_check()` raises `SchemaSkew` when a tier is on another version. The tier probe opened the file with schema admission but caught only `sqlite3.Error`, so the probe crashed instead of reporting an error check. - **55.10** `list_assertion_candidate_reviews(limit=10)` computed `total` with a second, unbounded review read. That read ran the per-candidate judgment lookup (N+1) across the whole candidate history. - **60.01** `--stream --limit N` followed continuations with no limit. The final page could therefore fetch rows past N, and the resulting `result_too_large` refusal was re-raised for continuations instead of narrowing the page. - **60.20** `raw-authority-frontier` printed the all-state `plan_count` as `obligations=`, including terminal `superseded` plans. - **62.01** Named `analyze postmortem|portfolio|cost-outlook` computed the inherited root format but rendered from the local `None` format, so they printed text when JSON was requested. ## Solution - `_archive_tier_readiness_check` keeps admission, passes `tier=`, and reports any `SchemaRefusalError` as an ERROR check. The worker's `validate_schema=False` version was replaced because it compared only `user_version`, so a derived tier with a stale identity at the right version was reported OK. `test_health_check_reports_derived_identity_skew` fails on the worker's version. - `_archive_list_assertion_candidate_reviews` returns `(page, count)` from one read transaction. The count comes from `count_assertion_claims`, which now accepts `target_ref` and `statuses=None`. The count includes expired claims, matching the review read model. - `_read_session_windows` sends the remaining bound with every continuation. An oversized resumed page halves in place, and later pages keep the narrowed bound, because `session.read` refuses a continuation that widens its window. - The plain frontier line says `plans=` (the neutral label the finding offered). - `analyze_verb` renders every branch from the effective format: the local format if given, otherwise the root format, normalized with `normalize_output_dialect`. An explicit local `--format` still wins. - **62.16 dropped.** The deleted-candidate case was already fixed on master in 8cb1133 (#5722): each successful answer, empty or not, removes the cached matches for the refreshed prefix. The worker added a cache of empty answers that offline completion would treat as authoritative. Nothing invalidated it except a later contradicting daemon answer or the 24h TTL, and an offline reader cannot tell whether the archive changed without opening it. The cold-cache message on a miss is displayed rather than inserted, and it is accurate. - Two stale tests in `test_archive_query.py` expected `_emit_stats` to exit 0 over a converging archive. #5700 made that outcome degraded with a nonzero exit, so the tests now expect that. They failed on master before this PR. ## Verification - `agentctl job start polylogue verify_quick --workspace /realm/worktrees/salvage-w12 --wait` → job 2374: `verify: PASSED exit=0` (head 331a204ddd, pre-rebase; the rebase onto 4501f13 touched none of these files). Earlier job 2368 failed on format and mypy in the worker's commit; commit 3561647 fixes both. - `agentctl job start polylogue pytest_focused --workspace /realm/worktrees/salvage-w12 --wait -- tests/unit/api/test_archive_health_tier_skew.py tests/unit/api/test_assertion_candidate_review_count.py tests/unit/cli/test_analyze_named_projection_format.py tests/unit/cli/test_raw_authority_frontier_output.py tests/unit/cli/test_session_window_continuation_bounds.py tests/unit/cli/test_analyze_projections.py tests/unit/cli/test_archive_query.py tests/unit/cli/test_completion_daemon_boundary.py tests/unit/api/test_assertion_candidate_queue_health.py` → job 2405 at head 3561647: `devtools test: PASSED exit=0 diagnosis=pytest_passed`, 168 passed. - Anti-vacuity: the new tests were run on an origin/master checkout (job 2351). Every fix test failed there (11 failures, plus the 2 stale stats tests). The one exception is `test_named_analysis_local_format_overrides_inherited_json`, a precedence guard that should pass on both. Job 2355 ran the health tests against the worker's `validate_schema=False` variant, and the derived-identity case failed (status OK instead of ERROR). - Inherited, not addressed here: `tests/unit/api/test_facade_contracts.py::test_archive_facet_buckets_count_unique_sessions_for_duplicate_hits` and `::test_no_undiscovered_async_methods` fail identically on master 4501f13 (job 2401). ## Self-review - **Sibling sites.** The review count had one caller, and `judge.py` consumes the facade's `total`. The daemon health endpoint has its own tier checks and is out of scope. The other `validate_schema=False` opens are reset, paths and export tools, not health reporting. - **Cancellation and loops.** The window retry loop is bounded by halving to 1 and then re-raising. No new loop reads without a bound. - **Unbounded reads.** This PR removes one, the unbounded review read, and adds none. - **Fail-open fallbacks.** The health probe now reports refusals instead of hiding them. The dropped completion change would have turned a cache miss into an authoritative empty answer. - **Compatibility shims.** None. `count_assertion_claims` gained optional parameters, and its existing `annotations/join.py` callers are unchanged. - **Removed symbols.** No production symbol was removed. The `test_codex_debt_w12.py` files were renamed by behaviour. - **Production route.** The API tests go through `Polylogue.health_check` and `list_assertion_candidate_reviews` on bootstrapped archives. The CLI tests go through `cli` or the real command with a mocked transport (`dispatch_read`) and the real `lower_session_read`. ## Derived-identity closure `polylogue/storage/sqlite/archive_tiers/user_write.py` is a member of `docs/plans/schema-closure-baseline.json`, so this PR moves the candidate derived identity. Closure membership does not grow (the `schema-closure` gate passed). No other changed production file is a member. ## Per-finding dispositions Counts: 5 fixed, 60 fixed-already, 2 stale, 1 refuted, 4 not reached. The not-reached findings (55.18, 55.22, 60.12, 62.08) stay open on their beads. | key | disposition | evidence | test | | --- | --- | --- | --- | | 55.01 #4326 `polylogue/api/__init__.py:51` | refuted | `polylogue/api/parity.py:472–491`: The explicit context-pack exclusion includes topic_pack; composed builders do not own a separate operation identity under this contract. | — | | 55.02 #5381 `polylogue/api/archive.py:410` | fixed-already | `polylogue/api/archive.py::_read_session_transcript_page`: The normalized offset is used for both the read and returned page coordinates. | — | | 55.03 #4287 `polylogue/api/archive.py:818` | fixed-already | `polylogue/api/archive.py::_archive_list_summaries_with_post_filters`: Effective specification pagination is restored after content filtering. | — | | 55.04 #4295 `polylogue/api/archive.py:871` | fixed-already | `polylogue/api/archive.py::_archive_aggregate_facet_families / keyed`: Repeated facet bucket counts are added across chunks rather than overwritten. | — | | 55.05 #4871 `polylogue/api/archive.py:1114` | fixed | `_archive_tier_readiness_check` keeps admission and reports `SchemaRefusalError` as ERROR | `api/test_archive_health_tier_skew.py` | | 55.06 #4192 `polylogue/api/archive.py:1152` | fixed-already | `polylogue/api/archive.py::_archive_list_assertion_claims`: Uses _readable_user_tier rather than an index-backed query runner. | — | | 55.07 #4794 `polylogue/api/archive.py:1546` | fixed-already | `polylogue/storage/sqlite/connection_profile.py::_install_progress_handler`: Read frames install an expiry/cancellation-aware SQLite progress handler, including work using the bound connection. | — | | 55.08 #4552 `polylogue/api/archive.py:1691` | fixed-already | `polylogue/api/archive.py::_archive_list_assertion_candidates`: Calls the canonical actionable queue reader rather than the expiry-retaining review reader. | — | | 55.09 #4295 `polylogue/api/archive.py:3066` | fixed-already | `polylogue/api/archive.py::pathology_report`: replace(spec, limit=None, offset=0) removes query pagination from the scope denominator. | — | | 55.10 #4295 `polylogue/api/archive.py:3448` | fixed | one read transaction; scalar `count_assertion_claims` replaces the second unbounded review read | `api/test_assertion_candidate_review_count.py` | | 55.11 #4552 `polylogue/api/archive.py:3453` | fixed-already | `polylogue/api/archive.py::_readable_user_tier`: Missing/non-file and unreadable durable-tier failures retain typed unavailability rather than returning an empty list. | — | | 55.12 #4295 `polylogue/api/archive.py:3503` | fixed-already | `polylogue/cli/commands/judge.py::judge_command`: Preserves authoritative review totals; additional client-side time filtering reads the complete selection before recounting. | — | | 55.13 #5302 `polylogue/api/archive.py:4021` | fixed-already | `polylogue/operations/facade_writers.py::record_manual_continuation_product`: Invokes _resolve_session_graph before committing the manual link, refreshing topology projections. | — | | 55.14 #5302 `polylogue/api/archive.py:4021` | fixed-already | `polylogue/operations/facade_writers.py::record_manual_continuation_product`: Invokes the canonical cycle/quarantine pass instead of leaving the direct insert unchecked. | — | | 55.15 #4180 `polylogue/api/archive.py:5081` | fixed-already | `polylogue/api/archive.py::search_session_hits`: Passes unresolved spec.to_plan() to failure-classifying search_hits_for_plan. | — | | 55.16 #4180 `polylogue/api/archive.py:5512` | fixed-already | `polylogue/api/archive.py::filter`: Constructs SessionFilter without vector-provider initialization. | — | | 55.17 #5362 `polylogue/api/archive.py:5557` | fixed-already | `polylogue/api/archive.py::query_sessions`: Includes title_is_synthesized from display_label_source. | — | | 55.18 #5370 `polylogue/api/archive.py:5561` | not reached | `polylogue/api/archive.py::read_transcript_window`: Anchor lookup and transcript-window reading still have separate read lifetimes. Single-snapshot implementation remains necessary; no fix written. | — | | 55.19 #5370 `polylogue/api/archive.py:5563` | fixed-already | `polylogue/api/archive.py::read_transcript_window`: Explicitly rejects around combined with transcript filters. | — | | 55.20 #4357 `polylogue/api/archive.py:6330` | fixed-already | `polylogue/api/archive.py::get_effective_context`: Canonical ID resolution plus read_summary replaces full transcript hydration for the existence check. | — | | 55.21 #4261 `polylogue/api/insights.py:753` | fixed-already | `polylogue/api/insights.py::cost_outlook`: Restricts the cost query to the selected cycle's since/until rather than the whole archive. | — | | 55.22 #5007 `polylogue/api/insights.py:916` | not reached | `polylogue/api/insights.py::get_ancestors/get_descendants/get_siblings/get_thread/get_logical_session`: Exhaustive relationship helpers still consume the default topology page without exhaustion. No implementation written. | — | | 55.23 #5007 `polylogue/api/insights.py:927` | fixed-already | `polylogue/api/insights.py::_resolve_for_topology`: Uses canonical archive resolve_session_id, preserving native-ID resolution. | — | | 55.24 #4799 `polylogue/api/insights.py:1030` | fixed-already | `polylogue/api/insights.py::compact_lineage`: Both public page defaults use DEFAULT_LINEAGE_PAGE_LIMIT. | — | | 55.25 #4539 `polylogue/api/search_envelope_builder.py:138` | fixed-already | `polylogue/api/search_envelope_builder.py::build_search_envelope_for_spec; polylogue/operations/authority.py::authority_for_config`: The envelope delegates authority resolution to the owner that resolves the active archive root. | — | | 56.01 #4603 `polylogue/api/search_envelope_builder.py:148` | fixed-already | `polylogue/api/search_envelope_builder.py::build_search_envelope_for_spec`: Reports matched=total and analyzed=len(hits). | — | | 60.01 #5337 `polylogue/cli/archive_query.py:360` | fixed | continuations carry the remaining bound; resumed pages halve in place, never widen | `cli/test_session_window_continuation_bounds.py` | | 60.02 #4402 `polylogue/cli/archive_query.py:390` | fixed-already | `polylogue/surfaces/cursor_identity.py::search_cursor_request_identity`: Presentation-only parameters are excluded from cursor identity. | — | | 60.03 #4987 `polylogue/cli/archive_query.py:1913` | fixed-already | `polylogue/cli/render/rows.py::project_payload`: Outcome is preserved independently of selected result fields. | — | | 60.04 #5249 `polylogue/cli/click_app.py:479` | fixed-already | `polylogue/cli/query_contracts.py::QueryOutputSpec.from_params`: Explicit file destination and path retain typed FILE identity even for reserved-looking filenames. | — | | 60.05 #4337 `polylogue/cli/click_app.py:554` | fixed-already | `polylogue/cli/query_group.py::_asks_for_query_workflow_help`: The advertised find help route is handled while respecting option arity. | — | | 60.06 #4340 `polylogue/cli/click_app.py:628` | fixed-already | `polylogue/cli/click_app.py::main`: Runtime checks run inside guarded_entry passed to run_machine_entry. | — | | 60.07 #4651 `polylogue/cli/click_command_registration.py:192` | fixed-already | `polylogue/cli/commands/insights_alias.py`: The existing root group exposes only Fable, not the entire operational group. No alias is introduced by this batch. | — | | 60.08 #4580 `polylogue/cli/click_command_registration.py:192` | fixed-already | `polylogue/cli/commands/insights_alias.py`: The existing narrow route preserves the promised Fable-packet command. No alias is introduced by this batch. | — | | 60.09 #4550 `polylogue/cli/click_command_registration.py:192` | fixed-already | `polylogue/cli/commands/insights_alias.py::_register_fable_packet`: Registers only the intended Fable command rather than the entire operational group. | — | | 60.10 #4698 `polylogue/cli/commands/check.py:41` | fixed-already | `polylogue/scenarios/operational_surfaces.py`: Authored doctor scenarios use current routes without the retired repair flags. | — | | 60.11 #5349 `polylogue/cli/commands/diagnostics.py:992` | fixed-already | `polylogue/cli/commands/diagnostics.py::latency_command`: The empty-bucket branch still renders incomplete-drop accounting. | — | | 60.12 #5639 `polylogue/cli/commands/import_command.py:117` | not reached | `polylogue/cli/commands/import_command.py::_wait_for_demo_ingest`: Owner completion accounting improved, but a degraded receipt still causes immediate failure instead of waiting through the remaining convergence budget. No implementation written. | — | | 60.13 #5314 `polylogue/cli/commands/insights.py:147` | fixed-already | `polylogue/scenarios/insight_surfaces.py; tests/unit/cli/test_stdout_stderr_split.py`: Inventories use current rather than retired commands. | — | | 60.14 #4678 `polylogue/cli/commands/insights.py:224` | fixed-already | `polylogue/cli/commands/insights.py::_render_status_plain`: Plain output includes degraded counts and fallback reasons. | — | | 60.15 #4292 `polylogue/cli/commands/insights.py:450` | fixed-already | `polylogue/cli/commands/insights.py::_packet_json_document`: Dataclass tuples are lowered to JSON-native arrays. | — | | 60.16 #5311 `polylogue/cli/commands/judge.py:417` | fixed-already | `polylogue/cli/commands/judge.py::judge_command`: Interactive approval forwards the evidence digest and checks failed counts before printing success. | — | | 60.17 #4133 `polylogue/cli/commands/maintenance/_blob_gc.py:81` | fixed-already | `polylogue/cli/commands/maintenance/_blob_gc.py::blob_gc_command`: Blocked previews set ok=false and exit nonzero in both formats. | — | | 60.18 #4955 `polylogue/cli/commands/maintenance/_blob_gc.py:211` | stale | `polylogue/cli/commands/maintenance/_blob_gc.py`: gc_recover_command is gone; the remaining command is preview-only. | — | | 60.19 #5345 `polylogue/cli/commands/maintenance/_blob_integrity.py:52` | stale | `polylogue/cli/commands/maintenance/_blob_integrity.py`: _submit_replace_from_source and its cited relative-output forwarding route are gone. | — | | 60.20 #5350 `polylogue/cli/commands/maintenance/_raw_identity.py:47` | fixed | plain line labels the all-state count `plans=` | `cli/test_raw_authority_frontier_output.py` | | 60.21 #5301 `polylogue/cli/commands/maintenance/_raw_identity.py:59` | fixed-already | `polylogue/cli/commands/maintenance/_raw_identity.py::raw_authority_blockers_command`: Paginated public blocker inspection exposes expected/observed evidence. | — | | 60.22 #4955 `polylogue/cli/commands/maintenance/_raw_identity.py:247` | fixed-already | `polylogue/cli/commands/maintenance/_raw_identity.py::raw_authority_blocker_resolve_command`: Checks the affected count rather than presenting no-op resolution as an applied mutation. | — | | 60.23 #4824 `polylogue/cli/commands/maintenance/_verify_archive.py:85` | fixed-already | `polylogue/cli/commands/maintenance/_verify_archive.py::verify_archive_command`: Source-frontier construction is conditional on selected source-conservation work. | — | | 60.24 #5491 `polylogue/cli/commands/paths.py:75` | fixed-already | `polylogue/cli/commands/paths.py::_raw_materialization_readiness`: Propagates the selected index path through archive_debt_list(index_db_path=...). | — | | 60.25 #5353 `polylogue/cli/commands/status.py:342` | fixed-already | `polylogue/operations/daemon_status.py::produce_operation_status`: Merges runtime collection metadata into pinned readiness components. | — | | 62.01 #5422 `polylogue/cli/query_verbs.py:2434` | fixed | `analyze_verb` renders from the effective (normalized, inherited) format | `cli/test_analyze_named_projection_format.py` | | 62.02 #5007 `polylogue/cli/read_views/lineage.py:78` | fixed-already | `polylogue/cli/read_views/lineage.py`: The replacement operation-backed route uses the resolved target; the old _run path is gone. | — | | 62.03 #5407 `polylogue/cli/read_views/messages.py:226` | fixed-already | `polylogue/cli/read_views/messages.py::_write_messages_file`: Resolves symlink output before choosing the staging sibling. | — | | 62.04 #5407 `polylogue/cli/read_views/messages.py:227` | fixed-already | `polylogue/cli/read_views/messages.py::_write_messages_file`: Flushes and fsyncs the staged descriptor before replacement and synchronizes the directory. | — | | 62.05 #4291 `polylogue/cli/read_views/query_set.py:196` | fixed-already | `polylogue/cli/read_views/correlation.py::run_read_correlation`: Renders a string and delivers it through deliver_content instead of an uncaptured console-only renderer. | — | | 62.06 #5374 `polylogue/cli/read_views/session_evidence.py:180` | fixed-already | `polylogue/cli/read_views/session_evidence.py::_read_evidence_window`: Projection body coordinates take precedence before operation lowering. | — | | 62.07 #5520 `polylogue/cli/read_views/standard.py:99` | fixed-already | `polylogue/cli/query_output.py::deliver_query_output`: File delivery retains secret-candidate scanning. | — | | 62.08 #5520 `polylogue/cli/read_views/standard.py:99` | not reached | `polylogue/cli/read_views/standard.py::run_read_summary_or_transcript; polylogue/cli/archive_query.py::_read_session_windows`: The standard file path still accumulates the transcript and buffers its rendered document. End-to-end operation-backed streaming is not implemented. | — | | 62.09 #5520 `polylogue/cli/read_views/standard.py:99` | fixed-already | `polylogue/cli/read_views/standard.py::run_read_summary_or_transcript`: Forwards a typed FILE QueryDeliveryTarget, preserving reserved-looking filenames. | — | | 62.10 #5520 `polylogue/cli/read_views/standard.py:99` | fixed-already | `polylogue/operations/daemon_reads.py::_session_identity_projection; polylogue/cli/archive_query.py::_session_message_text`: The operation preserves tool_input; rendering includes structured tool input and omits reasoning blocks. | — | | 62.11 #5520 `polylogue/cli/read_views/standard.py:99` | fixed-already | `polylogue/cli/archive_query.py::_read_session_windows`: Initial oversized pages already halve their bound at the inspected base. This batch additionally fixes resumed-page narrowing under 60.01. | — | | 62.12 #5266 `polylogue/cli/session_rows.py:141` | fixed-already | `polylogue/cli/session_rows.py::_query_page_with_authority`: Synthetic missing-session selections explicitly include next_offset=None. | — | | 62.13 #5426 `polylogue/cli/shared/machine_errors.py:233` | fixed-already | `polylogue/cli/shared/machine_errors.py::error_archive_writer_ownership`: Undecidable ownership has a separate remedy that does not assert an observed resident daemon. | — | | 62.14 #5426 `polylogue/cli/shared/machine_errors.py:285` | fixed-already | `polylogue/cli/shared/machine_errors.py::extract_command`: Recognizes --output-format as a value-bearing option. | — | | 62.15 #5545 `polylogue/cli/shell_completion_values.py:117` | fixed-already | `polylogue/cli/shell_completion_values.py::_cached_value_matches`: Session IDs match native-ID and title substrings. | — | | 62.16 #5545 `polylogue/cli/shell_completion_values.py:135` | fixed-already | deleted-candidate case fixed by 8cb1133 (#5722): every successful answer prunes the refreshed prefix; negative-answer cache declined (see Solution) | — | | 62.17 #5545 `polylogue/cli/shell_completion_values.py:145` | fixed-already | `polylogue/cli/shell_completion_values.py::_remember_completion_values`: A per-archive map retains more than the most recent archive. | — | | 62.18 #5545 `polylogue/cli/shell_completion_values.py:157` | fixed-already | `polylogue/cli/shell_completion_values.py::_remember_completion_values`: Removes an existing value before reinsertion at the retention tail. | — | | 62.19 #5545 `polylogue/cli/shell_completion_values.py:178` | fixed-already | `polylogue/cli/shell_completion_values.py::_remember_completion_values`: Global serialized-byte eviction precedes publication. This batch includes new empty observations in that accounting. | — | | 62.20 #5545 `polylogue/cli/shell_completion_values.py:181` | fixed-already | `polylogue/cli/shell_completion_values.py::_remember_completion_values`: flock serializes the full cache read-modify-write sequence. | — | | 62.21 #5382 `polylogue/cli/write_authority.py:104` | fixed-already | `polylogue/storage/sqlite/write_lease.py::arm_write_lease_enforcement`: Locked process-wide user/suppressor counts make arming overlap-safe. | — | ## Residuals - The four not-reached findings remain open. - Changing `user_write.py` moves the derived identity, so this PR has to land before a rebuild starts. - The two `test_facade_contracts.py` failures are inherited from master. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_015pdKaZWyGe6Ngvsz468dzg --------- Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
|
Closing out open Codex review threads on this PR (evidence checked against master at ef10e59):
Resolving the fixed, stale and refuted threads; tracked threads stay open. |
Summary
Two related read-path bounds:
polylogue-2go3o(bound the database-backed session loader and the lineage locate at the storage layer) andpolylogue-fvsjn(attached-unit truncation was distributed arbitrarily across a page).Problem (evidence)
The attached-unit page ceiling was spent in the page's own row order, so a long session could take the allowance a short one never received.
A tail-first read is where that bit hardest. Measured on a skewed page — one 5-message session followed by 13 sessions of 400 — a
last:5projection gave every long session its 5 rows and the short session zero, inside a clean envelope. Nothing in the result distinguished "this session has no messages" from "this session's allowance was eaten".Solution
Every selected session now gets the same allowance,
min(_MAX_ROWS_PER_SESSION, _MAX_ROWS_PER_PAGE // session_count), so what a session receives no longer depends on how many sessions share the page or where its rows sort within it. Both declared ceilings still hold; only their distribution changed. One row past the allowance is requested and discarded, so reaching it is observed rather than inferred from a count that could legitimately equal the bound.A page holding more sessions than the ceiling can give a row each raises
AttachedUnitPageTooWideErrorrather than serving nothing for every session. Under the 2026-09-21 ruling an allowance of zero is not a bound on the answer, it is the absence of one — quietly serving nothing would be exactly the silent truncation this module exists to stop reporting as complete.Verification
Exit codes read directly, not through a filter.
Anti-vacuity executed, not asserted. Mutating
_per_session_allowanceto ignoresession_countand capping the fetch at_MAX_ROWS_PER_PAGE— the pre-fvsjn shared budget — turns the suite red (devtools testFAILED exit=1, 2 tests). Directly measured on the skewed page:last:5last:5An earlier pair of tests over 26 uniform sessions was written and then discarded: the same mutation left them green, because a flat page limit spread over equal-size sessions already lands on roughly equal counts. Only the skew above separates the fix from the defect. That discarded pair is the reason this PR asserts on a skewed page rather than a convenient one.
Schema identity
attached_units.py,archive.pyandarchive_query_reads.pyare all closure IN; the derived index identity moves to4700fef2…, ops unchanged at86866235…. Closure membership is unchanged. Must land before a fresh rebuild starts, never during one.🤖 Generated with Claude Code
https://claude.ai/code/session_01ToWqpkXotr573DiQex5vcy