Repository navigation
feat(queries): Give standing queries a creation route - #5375
Conversation
…exact deltas Two defects that together made the standing-query domain dormant and, where it did fire, capable of claiming a membership change it had not measured. NO PRODUCTION ROUTE CREATED A WATCH (polylogue-pm8cj) put_query_name(..., watch=True) had no production caller anywhere in the repository: list_watched_queries only ever returned rows a test had written directly. The convergence stage has been production-wired with a real ArchiveCanonicalPlanEvaluator since #2899, and #5355 optimized its candidate selection -- but nothing in the product let a user or an agent create a watch, so the stage had nothing to re-evaluate and the optimization's real-world benefit was zero. The route is deliberately not a new object. A saved view already is the product's named query, so marking one watch=True promotes that name into the durable queries/query_names substrate the stage reads. The promotion happens in the SAME transaction as the saved-view assertion: a name whose view committed but whose watch did not would be silently unwatched. What the promotion costs is exactness. A watch is re-evaluated by the canonical-plan evaluator, which executes a typed v1 predicate and nothing else, so a view whose selection has no evaluable predicate is refused at creation rather than watched under a different set than the user named. A NON-EXACT EVALUATION CLAIMED A DEFINITIVE DELTA (polylogue-uwm6y) member_refs from a capped, sampled or estimated evaluation is a bounded view of the watched relation, not the relation, so its merkle root answers a different question than the baseline's. Comparing them let a shifting cap window alone emit an unconditional "membership changed" assertion. That path now never advances the baseline, never writes a watch result set and never emits query-delta. Emitting nothing would be the mirror defect -- an unmeasured negative reported as a measured one -- so the degraded receipt is always written, and when a measured baseline existed (there was a real drift question this tick was supposed to answer) exactly one query-delta-unmeasured candidate names the condition. LAYERING The validator is pure and lives in archive/query/watch_definition.py so the daemon HTTP route and the MCP write tool can answer "is this watchable?" with a typed 400 without importing polylogue/storage, which the layering rule forbids outright. The durable registration stays in storage/sqlite/query_watch.py, because it must run inside the caller's transaction, and is declared in the writer-module census as a user-tier writer. CLOSURE: both new modules enter the derived closure (555 -> 557) because archive_tiers/archive.py reaches them, so the index identity moves 91de2642 -> 99dae61a; ops is unchanged. The baseline records the growth. This must land before a fresh rebuild starts, never during one. VERIFICATION: devtools verify --quick exit 0 (all gates, including layering and schema-closure); devtools render all --check exit 0 with zero "out of sync"; devtools test over the standing-query suites and query objects -- 28 passed, plus 17 in the stage suite. ANTI-VACUITY, EXECUTED. pm8cj: the new tests create a watch THROUGH THE PRODUCTION SURFACE and assert the convergence stage picks it up on the next tick, that unwatching stops it, and that an unexecutable view is refused. A test that writes the row directly cannot see a missing route -- which is exactly how this went unnoticed. uwm6y: removing the exactness branch makes the capped tick assert query-delta on a membership the evaluator never enumerated ("a capped view is not a membership"), and the baseline advances to a capped root. Closes polylogue-pm8cj, polylogue-uwm6y. Advances polylogue-tegww. 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 29 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 (14)
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: 07ff663781
ℹ️ 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".
…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]>
|
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. |
|
Closing out open Codex review threads on this PR (evidence checked against master at 64a9bd0):
Resolving every thread listed; confirmed defects are fixed under the named bead. |
feat(queries): Give standing queries a creation route and refuse non-exact deltas
Two defects that together made the standing-query domain dormant and, where it
did fire, capable of claiming a membership change it had not measured.
NO PRODUCTION ROUTE CREATED A WATCH (polylogue-pm8cj)
put_query_name(..., watch=True) had no production caller anywhere in the
repository: list_watched_queries only ever returned rows a test had written
directly. The convergence stage has been production-wired with a real
ArchiveCanonicalPlanEvaluator since #2899, and #5355 optimized its candidate
selection -- but nothing in the product let a user or an agent create a watch,
so the stage had nothing to re-evaluate and the optimization's real-world
benefit was zero.
The route is deliberately not a new object. A saved view already is the
product's named query, so marking one watch=True promotes that name into the
durable queries/query_names substrate the stage reads. The promotion happens in
the SAME transaction as the saved-view assertion: a name whose view committed
but whose watch did not would be silently unwatched.
What the promotion costs is exactness. A watch is re-evaluated by the
canonical-plan evaluator, which executes a typed v1 predicate and nothing else,
so a view whose selection has no evaluable predicate is refused at creation
rather than watched under a different set than the user named.
A NON-EXACT EVALUATION CLAIMED A DEFINITIVE DELTA (polylogue-uwm6y)
member_refs from a capped, sampled or estimated evaluation is a bounded view of
the watched relation, not the relation, so its merkle root answers a different
question than the baseline's. Comparing them let a shifting cap window alone
emit an unconditional "membership changed" assertion.
That path now never advances the baseline, never writes a watch result set and
never emits query-delta. Emitting nothing would be the mirror defect -- an
unmeasured negative reported as a measured one -- so the degraded receipt is
always written, and when a measured baseline existed (there was a real drift
question this tick was supposed to answer) exactly one query-delta-unmeasured
candidate names the condition.
LAYERING
The validator is pure and lives in archive/query/watch_definition.py so the
daemon HTTP route and the MCP write tool can answer "is this watchable?" with a
typed 400 without importing polylogue/storage, which the layering rule forbids
outright. The durable registration stays in storage/sqlite/query_watch.py,
because it must run inside the caller's transaction, and is declared in the
writer-module census as a user-tier writer.
CLOSURE: both new modules enter the derived closure (555 -> 557) because
archive_tiers/archive.py reaches them, so the index identity moves
91de2642 -> 99dae61a; ops is unchanged. The baseline records the growth. This
must land before a fresh rebuild starts, never during one.
VERIFICATION: devtools verify --quick exit 0 (all gates, including layering and
schema-closure); devtools render all --check exit 0 with zero "out of sync";
devtools test over the standing-query suites and query objects -- 28 passed,
plus 17 in the stage suite.
ANTI-VACUITY, EXECUTED. pm8cj: the new tests create a watch THROUGH THE
PRODUCTION SURFACE and assert the convergence stage picks it up on the next
tick, that unwatching stops it, and that an unexecutable view is refused. A test
that writes the row directly cannot see a missing route -- which is exactly how
this went unnoticed. uwm6y: removing the exactness branch makes the capped tick
assert query-delta on a membership the evaluator never enumerated
("a capped view is not a membership"), and the baseline advances to a capped
root.
Closes polylogue-pm8cj, polylogue-uwm6y. Advances polylogue-tegww.
Co-Authored-By: Claude Opus 5 (1M context) [email protected]
Claude-Session: https://claude.ai/code/session_01ToWqpkXotr573DiQex5vcy