Skip to content

fix(query): Lower agg metrics into SQL and derive the AST wire schema - #5356

Merged
Sinity merged 4 commits into
masterfrom
fix/query-terminal-execution
Sep 21, 2026
Merged

Sinity merged 4 commits into
masterfrom
fix/query-terminal-execution

Conversation

@Sinity

@Sinity Sinity commented Sep 21, 2026 •

Copy link
Copy Markdown
Owner

Summary

Three o21 leaves on the query terminal-execution path. This moves the index
schema identity
— see the landing window below.

polylogue-o21.5 — the 50k cap silently truncated, and it wasn't the only defect

Pre-change behaviour at the boundary, measured not reasoned

Probe with _AGG_ROW_FETCH_CAP monkeypatched to 2 over a 3-row population:

CAPPED metrics: [(None, 2, {'count': 2, 'sum_word_count': 8.0, 'avg_word_count': 4.0, ...})]
CAPPED pipeline result: {..., 'exact': False, 'sampled_rows': 2}

It silently truncates — it does not refuse — and the truncation is only
partly flagged. Metric values and per-group count describe the first N rows in
time-ascending order. pipeline.result.exact=false and sampled_rows are set, but
the terminal outcome stays ok and never degraded, has_next is computed over
truncated groups, and selected_rows_exact becomes None. A complete-looking
envelope carrying sample numbers
— which is the outcome contract's
degraded-outranks-empty rule violated at the other end.

percentile lowered faithfully, and got more correct

Nearest rank is an integer definition; the Python reducer computed
math.ceil(rank / 100 * n) in binary floating point. Enumerated: 290 of 198,000
(rank, n) pairs for n ≤ 2000 pick the wrong element
— e.g. p7 over 100
distinct values selected the 8th smallest instead of the 7th. SQL uses exact
integer arithmetic, MAX(1, MIN(n, (rank * n + 99) / 100)). Confirmed by mutation:
replacing it with CAST(CEIL(rank / 100.0 * n) AS INTEGER) reproduces the float
artifact in SQLite, so the defect was the float, not the definition. Deliberate
behaviour change, stated in the commit message.

The bead's concrete input is wrong twice

agg avg(duration_ms) by tool cannot parse: the syntax is | agg avg:FIELD, and
duration_ms is not in action's aggregate_metric_fields. The entire non-count
metric surface is three (unit, field) pairs — message.word_count,
action.is_error, action.exit_code. A real input is
messages where role:assistant | agg avg:word_count.

polylogue-o21.8 — understated, not overstated

The bead records that the audit tried to turn the duplicated field maps into a
reachable wrong output and failed, so it is filed as consolidation. That
holds for the bracket path it examined — but a reachable wrong output does
exist on the aggregate path:

_AGGREGATE_ROW_FIELDS had no session.repo entry for any unit, while
session.repo is a declared aggregate_group_fields member for every SQL unit.
Measured at base: messages where role:assistant | group by session.repo | agg count, avg:word_count returned a single [missing] group over all rows, while
the count terminal on the same expression returned the two real repositories.

A second divergence: delegations | group by basis | agg count grouped by raw
instruction_tool_use_block_id values while the count terminal groups by the
edge/action discriminator.

The o21.8 commit stays framed as consolidation; the defect sits in the o21.5
commit, which is what fixes it.

polylogue-o21.7 — the mirror was already broken at head

The bead describes drift hypothetically. In fact explanation_payload_to_ast
rejected the producer's own output for any | agg ... expression with 7
validation errors. It is a test-gate and published-schema defect rather than a live
route failure — no production path calls it — but docs/openapi/search.yaml and
webui/src/api/generated.ts described a shape the server does not emit. The
existing parity test's corpus contained no agg case, which is why it survived.

Byte-equivalence of the refactor

Captured explain_expression(...).to_payload() for a 38-expression corpus covering
every predicate kind, pipeline stage, clause kind, entry branch and conditional key.
After converting all 28 producers to declaration-driven rendering:

IDENTICAL: 38 expressions, payloads equal after timestamp redaction

The only redaction is the since:7d relative-date resolution.
QUERY_DEFINITION_PROTOCOL_VERSION untouched; query_ref identity cannot move,
because predicate payloads are unchanged and hash_payload sorts keys.

Wire change is additive plus one narrowing (terminal.action from string to
"rows" | "count" | "agg"); nothing removed, nothing widened; no repository
consumer reads these types.

Anti-vacuity — nine mutations executed, all restored

Including G, the bead's exact o21.8 condition: a single deletion of
"type": "message_type" reddens three tests across both paths. Others: the
LIMIT 50000 restoration (assert 50000 == 50001), the float percentile
({'p7_word_count': 8.0} != {'p7_word_count': 7.0}), removing the progress handler
(DID NOT RAISE QueryWorkBudgetExceededError), and "avg": "SUM" in the reducer
map, caught by the cross-surface parity test.

Mutation C reproduces the observable of the deleted lookup rather than literally
restoring the Python reducer — labelled as a proxy, not a literal restore.
Nothing material is reasoned-not-executed.

Parity, pagination, cancellation

  • Cancellation: 20,000 rows through InterruptibleSQLiteRead with a 10,000-opcode
    budget; both the agg and rows branches raise with receipt.interrupted is True.
  • Pagination: a 5-group aggregate walked at offsets 0/2/4, asserting
    selected_rows_exact == 5 on every page — the total, not the page.
  • CLI/API/MCP/HTTP: one grouped agg page walked through Polylogue.query_units,
    the daemon HTTP route and the MCP query tool, resuming by continuation between
    pages, all three compared against word counts the test computes itself.

THE LANDING WINDOW

All three index fingerprints move; the index tier must reconverge. This must land
before a fresh rebuild starts, never during one.

base 2bbecb9cd branch
lowering 74fafc04… a9bdbc48…
materializer 9dc1287d… 8216f7ff…
replay_routing eef8760e… b14bb766…
index identity 0356cac3… 1a1bda47…
ops identity 3d18f2a0… unchanged

Closure membership is a one-for-one swap, 555 → 555: payload_schema.py enters,
query_ast_schema.py leaves.

Two bead closure verdicts were wrong at my base: query_ast_schema.py was
recorded IN but measures out after the change (the schema module became
downstream of the producers instead of upstream), and render_openapi.py is out.
Neither daemon/event_bus.py nor archive_tiers/ops_write.py was touched.

Useful for scheduling: #5352, #5353 and #5354 did not move the identity —
origin/master read 0356cac3… at 540228b, 51222af and 2bbecb9 alike.

Verification (post-rebase)

devtools verify --quick exit 0, all 25 gates including schema-closure and
controlled-read. devtools render all --check exit 0, 0 lines matching out of sync (grepped, not inferred). Focused suites green across
tests/unit/archive, the AST schema, field map, metadata, continuation parity,
and the query exec laws. Broad selection of 2163 tests: 10 non-pass, all
inherited
, proven by detached checkout of origin/master inside this worktree.

One of those I'd have miscounted: test_descriptor_runtime_transform_units_reject_aggregate_pipeline
is a skip (got empty parameter set), not a failure.

Residuals

  • _LARGE_POPULATION is pinned to the historically deleted bound (50,001), not
    to "any bound".
    A future implementation introducing a cap above 50,000 would
    not be caught. No test can catch an unknown bound; the declared condition is the
    concrete one.
  • The 50k exactness test costs ~11 s. The size is deliberate — anything smaller
    stays green under mutation A.
  • to_payload() is derived, but four escape hatches remain in the declarations
    (omit_when callables ×2, read-only payload_* properties ×4). Declared per
    field, so no mirror exists, but they are hand-written logic.
  • WithUnitWindow, SessionQueryPipeline and SessionQueryTerminalStage keep
    hand-written to_payload() — not part of the published AST schema, so converting
    them would widen the diff without removing a mirror. Stated, not hidden.
  • Two follow-ups filed separately: test_schema_closure.py's IN_CLOSURE roster is
    stale at master (daemon/write_coordinator.py left the closure and the test
    was not updated — 3 reds unrelated to this swap), and
    analysis/orchestration_evidence.py:140 compares a possibly-None count with >
    (6 MCP reds, already filed as polylogue-w4hfb).

Closes polylogue-o21.5, polylogue-o21.7, polylogue-o21.8. polylogue-o21.6 untouched.

🤖 Generated with Claude Code

https://claude.ai/code/session_015WCh9YW3cRfsg3CZBKU7Fq

Summary by CodeRabbit

  • New Features

    • Added named aggregate metrics, including count, sum, average, minimum, maximum, and percentile calculations.
    • Added grouping support and paginated aggregate results across the Python API, HTTP API, MCP, and CLI.
    • Aggregate results are now exact across complete matching datasets, including large result sets and NULL values.
    • Added support for aggregate stages and metric results in API schemas and generated client types.
    • Expanded field resolution for grouping and bracket predicates across query unit types.
  • Documentation

    • Updated aggregate metric documentation with exact calculation and percentile behavior.

Sinity and others added 4 commits September 21, 2026 16:35
`| agg sum|avg|min|max|pNN:FIELD` fetched at most 50,001 predicate-matching
rows through the unit's row query and reduced them in Python. Above that
bound the reported metric, and the per-group `count`, described the first
50,000 rows in time order rather than the match set, while the terminal
outcome stayed `ok`; only `pipeline.result.exact` and `sampled_rows` hinted
at the truncation.

`ArchiveStore.query_unit_agg_metrics` now evaluates every reducer over the
complete relation in one statement, so Python retains only the requested
group page. `_AGG_ROW_FETCH_CAP`, `_reduce_agg_metric`, `_AGGREGATE_ROW_FIELDS`
and the `exact`/`sampled_rows` payload keys are deleted rather than kept
behind a flag: with one regime there is nothing left to flag.

Two observable results change, both toward the documented contract:

- `| group by session.repo | agg ...` grouped every row under `[missing]`,
  because the deleted payload-attribute map had no `session.repo` entry for
  any unit. It now groups by the owning repository, agreeing with the
  `count` terminal.
- Percentiles use exact-integer nearest rank. `rank / 100 * n` in binary
  floating point overshoots for 290 of the 198,000 `(rank, n)` pairs under
  n=2000 -- `p7` over 100 values selected the 8th smallest.

Grouping keeps the multi-field count lowerer's lossless value contract,
None-for-empty-group is preserved, an empty match set still emits no group,
and the aggregate runs on the reader's connection so the SQLite progress
handler interrupts it exactly as it interrupts the row terminal.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_015WCh9YW3cRfsg3CZBKU7Fq
Two hand-maintained restatements of "DSL field name -> the unit's own row
attribute" existed: the terminal executor's aggregate field map and
`QueryUnitDescriptor.attached_bracket_fields`. Nothing kept them in step and
they had already diverged -- one carried `block` and `delegation` and omitted
`assertion`, the other the reverse. This is duplication, not a demonstrated
defect on the bracket path: `with blocks[...]` and `with delegations[...]`
are rejected earlier in the grammar, so the divergent entries were
unreachable there.

`QueryUnitDescriptor.row_field_attributes` is now the one map. The bracket
predicate reads the attribute off a projected payload row; the SQL aggregate
group lowerer reads the identically-named column off the unit's relation.
Membership is the union, stated rather than inherited from one side:

- `block`, `observed-event` and `delegation` gain the entries their declared
  `aggregate_group_fields` need. None is in the projection unit set, so the
  bracket grammar does not widen on any reachable path.
- Session-scoped fields stay out. They are not the unit's own columns and the
  SQL layer resolves them from the owning-session join.
- `delegation.basis` keeps its `edge`/`action` discriminator and `assertion`
  keeps its declared status/visibility/author-kind defaults in the SQL layer:
  those are value shapes, not field names.

A declaration test asserts every non-session `aggregate_group_fields` entry
resolves through the map, so the drift the second map hid is now a red test.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_015WCh9YW3cRfsg3CZBKU7Fq
…itions

`query_ast_schema.py` held 29 Pydantic classes that restated, one-to-one, the
payload shape of 28 hand-written `to_payload()` methods, with nothing deriving
either side from the other. The mirror had already fallen behind: it declared
no `agg` pipeline stage and no `agg_metrics` result key, so
`explanation_payload_to_ast` rejected the producer's own valid output for any
`| agg ...` expression, and the published OpenAPI and generated webui client
described a shape the server does not emit. The existing parity test could not
see it -- it fed the producer's output to the mirror, and its expression corpus
contained no `agg` case.

Each AST node now declares its payload once (`payload_schema.py`): the wire
keys, their types, the attribute each reads from, and when a key is omitted.
`render_payload` produces the dict and `payload_model` produces the published
model from that same declaration, so a mirror has nowhere to live and adding a
payload key reaches the rendered OpenAPI with no second edit. Three further
hand-rolled restatements collapse into the nodes they describe: the inline
`unit_source` block and `reference_lineage` dict in the explain path, and the
sort spec that was spelled out in three places.

`QUERY_DEFINITION_PROTOCOL_VERSION` is untouched, and every predicate payload
is byte-identical: all 38 expressions of a corpus covering every predicate
kind, pipeline stage, clause kind and entry branch render exactly what they
rendered before, so query identity does not move.
`QUERY_AST_SCHEMA_VERSION` also stays at v1 because the wire change is
additive -- `QueryUnitAggStageAst` and `QueryUnitAggMetricAst` appear,
`agg` joins the stage discriminator, `agg_metrics` joins the result and unit
source -- plus one narrowing: the published `terminal.action` is now the
declared `rows`/`count`/`agg` enum instead of a bare string. No repository
consumer reads these types; `webui/src/api/` holds only generated files.

Derived-schema closure is a one-for-one swap at 555 members:
`payload_schema.py` enters and `query_ast_schema.py` leaves, because the
schema module is now downstream of the producers instead of upstream.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_015WCh9YW3cRfsg3CZBKU7Fq
The named-metric aggregate had no cross-surface coverage: only the storage
route was exercised, which is why the published AST schema could reject its
own pipeline unnoticed. Walk one grouped `agg` page through the Python API,
the daemon HTTP route and the MCP query tool with a continuation between
pages, and assert the three agree with word counts this test computes; render
the same aggregate through the CLI's JSON output and assert the metrics map
and the absence of the deleted exactness flag.

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

Copy link
Copy Markdown

You have reached your Codex usage limits for security reviews. Please try again later.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 21, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-21T14:46:30.546559Z a9affbf PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@Sinity
Sinity enabled auto-merge (squash) September 21, 2026 14:40
@coderabbitai

coderabbitai Bot commented Sep 21, 2026

Copy link
Copy Markdown

Review Change StackReview Change Stack

Note

Currently processing new changes in this PR. This may take a few minutes, please wait...

⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Advanced

Run ID: 758fa07a-33c9-4721-b80a-c853cd5c9fc9

📥 Commits

Reviewing files that changed from the base of the PR and between a08dbda and a9affbf.

📒 Files selected for processing (19)
  • docs/openapi/search.yaml
  • docs/plans/schema-closure-baseline.json
  • docs/search.md
  • polylogue/archive/query/attached_units.py
  • polylogue/archive/query/expression.py
  • polylogue/archive/query/metadata.py
  • polylogue/archive/query/payload_schema.py
  • polylogue/archive/query/predicate.py
  • polylogue/archive/query/query_ast_schema.py
  • polylogue/archive/query/unit_results.py
  • polylogue/storage/sqlite/archive_tiers/archive.py
  • polylogue/storage/sqlite/archive_tiers/archive_query_reads.py
  • tests/unit/archive/query/test_continuation_surface_parity.py
  • tests/unit/archive/query/test_query_ast_schema.py
  • tests/unit/archive/test_query_agg_metrics.py
  • tests/unit/archive/test_query_metadata.py
  • tests/unit/archive/test_query_unit_field_map.py
  • tests/unit/cli/test_query_exec_laws.py
  • webui/src/api/generated.ts
 ___________________________________________
< That's not a fallback, that's a trapdoor. >
 -------------------------------------------
  \
   \   (\__/)
       (•ㅅ•)
       /   づ
✨ Finishing Touches
📝 Generate docstrings
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR

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: a9affbf10c

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@Sinity
Sinity merged commit 779a701 into master Sep 21, 2026
2 of 3 checks passed
@Sinity
Sinity deleted the fix/query-terminal-execution branch September 21, 2026 14:51
Sinity added a commit that referenced this pull request Sep 21, 2026
## Summary

Acts on the operator ruling of 2026-09-21 — *"there should not be caps
on things
like this"* — by censusing every numeric bound in `polylogue/` and
`devtools/`,
classifying each, and fixing the four that **silently truncate a
computed answer**.

The denominator was built from the code: three greps (module-level
`^[A-Z_]*(CAP|LIMIT|MAX|BUDGET|SAMPLE|SIZE|ROWS|COUNT)… = <int>` at 236
hits,
literal `[:N]` slices, literal `LIMIT <n>` in SQL).

## Class 3 — silent truncation of a computed answer (fixed)

| Bound | Measured boundary **before** the change |
| --- | --- |
| `_MAX_ROWS_PER_SESSION=200` / `_MAX_ROWS_PER_PAGE=5000` in
`attached_units.py` | Executed: a 250-message session returned **200
rows, first `m-0000` last `m-0199`**, no flag in the returned dict, no
gap, `outcome: ok`. Worse at page scale — `query_session_messages`
orders `BY m.position` across **all** sessions under one global LIMIT,
so a page of >25 sessions gives each ~5000/n rows and **a session can
receive zero**. |
| `FACET_SCOPE_SESSION_CAP` dropped by the daemon route | Executed with
the cap patched to 1 on a 2-session archive: the daemon route returned
`outcome ok, total_sessions 1, family_errors {}`. **The API route on the
identical cap returns `degraded`** — so the production route the CLI
reads through was the silent one. |
| `_ENUM_OUTPUT_CAP=20` in `field_annotations.py` | Executed: 25
distinct values → **20 emitted, `['role_20'..'role_24']` missing**, and
the loss inventory said nothing about them. Truncation **inside a
declared protocol vocabulary, where the member list *is* the answer.** |
| `GROUP BY r.origin … LIMIT 16` in `archive_readiness.py` | **Latent**,
not live: `len(list(Origin)) == 12`, so the cut cannot bite today. But
the exact `total` in the same payload keeps counting rows the breakdown
would drop, so a 17th origin makes the two stop adding up with no gap
named. |

## What the fix does — and does not do

`attached_units` keeps its ceiling (it is real work protection) but
**converts it
to a reported bound**: it fetches `fetch_limit + 1` so "the ceiling
bound this
fetch" is *observed* rather than inferred from a row count that could
legitimately
equal the bound, and returns a frozen `AttachedUnitRows(rows, gaps)`.
The gap is a
**return value, not an optional out-parameter — precisely because an
optional
collector is what `_facets_payload` forgot.**

`_facets_payload` threads the *existing* `scope_gaps` collector through
both
call sites. `decide_outcome` moved to **after** the projection runs, so
a cut
projection can degrade the envelope. Where the carrier has no outcome
envelope
(`SessionSummary`/`Session`), the gap is emitted as a WARNING event
rather than
dropped.

`_ENUM_OUTPUT_CAP` was **removed with no replacement bound** — what
remains is
`ENUM_MAX_CARDINALITY`, which *is* the enum-ness criterion, plus #5357's
`PUBLISHABLE_VOCABULARY_ROLES`. Post-fix: 25 of 25. Likewise the `LIMIT
16` is
simply gone; the group key's vocabulary is validated at the write
boundary, so the
aggregate is exhaustive by construction.

**No arbitrary number was replaced by another arbitrary number.**

## Three of my suggested candidates were refuted, with evidence

- **`SLO_SAMPLE_ROW_CAP = 20_000` is not a sampled percentile.** There
are no
percentiles in the module and **no importers at all** — grep across
`polylogue/`,
`devtools/` and `tests/` returns only the module itself. It is a
write-side
retention prune on the disposable ops tier. **The whole module is
unreachable
  code.**
- **`ENUM_VALUE_CAP = 200` cannot manufacture a false enum.** Overflow
past 200
  leaves `len(observed_values) == 200 > ENUM_MAX_CARDINALITY (50)`, so
  `is_enum_like` is False and **no value list is emitted at all**;
`distinct_value_count` stays honest. The real defect was one layer down.
- **`DELETE_PREVIEW_MAX_SESSION_IDS` refuses properly.** Executed at the
boundary:
  n=10000 returns all 10000; n=10001 **refuses by name** with
`selection_exceeds_preview_work_budget`. An operator cannot approve a
preview that
  dropped targets.

## Class 2 — the models the fixes copied

`POST_FILTER_HYDRATION_CAP` (counts first, fetches cap+1,
`PostFilterScopeTooLargeError`
with `gap_reason`), and the best example in the repo: `codex_state`'s
bounds, where
every decline is named in a durable `CodexStateReadBound` with
`rows_available`
counted **before** the capped select, so `rows_declined` is exact.

## Anti-vacuity — six mutations executed, all restored

Populations strictly larger than each removed bound (25 values vs a
20-ceiling, 250
rows vs 200, 2 sessions vs a cap of 1).

| Mutation | Red |
| --- | --- |
| Reinstate `_ENUM_OUTPUT_CAP` | `Right contains 5 more items, first
extra item: 'evt_20'` |
| Drop the +1 probe | `assert () ==
('attached_unit_truncated:message:200',)` |
| `>=` instead of `>` | **turns a correct answer into a false
degradation** — `Left contains one more item` |
| `provably_complete = False` | same, for a satisfied `first:N`/`last:N`
window |
| Stop passing `scope_gaps` | `assert 'ok' == 'degraded'` |
| `decide_outcome` before the projection | `assert 'ok' == 'degraded'` |

**One change landed without test evidence, stated rather than buried**:
the
`LIMIT 16` removal has no non-vacuous test, because its anti-vacuity
condition is a
17th distinct `raw_sessions.origin` and the vocabulary holds 12. Writing
17
synthetic origin strings into a fixture would put out-of-vocabulary data
in the tree
to prove a latent bound. Existing assertions still pass.

## Landing window

`attached_units.py` **IN**, `archive_execution.py` **IN**,
`field_annotations.py`
**IN**, `archive_readiness.py` **IN**, `daemon_reads.py` **out**.
Neither known trap
was touched.

**The derived index identity moves** — lowering `95da1717→f49f91fc`,
materializer
`38c8cedd→bea73d3e`, replay `e43587d1→4b663ccc`, index
`1aeddaa4→203a77cd`; ops
unchanged. **Must land before a fresh rebuild starts, never during
one.**

Closure **membership is unchanged**: 555 → 555, zero entered, zero left.
The
identity moves through edits to existing members, not a membership
change.

## Verification

`devtools verify --quick` **exit 0, all 25 gates** · `devtools render
all --check`
exit 0, `grep -c 'out of sync'` = 0 · focused 9-module selection 533
passed / 4
failed, **all four proven inherited** by a detached checkout at the
exact base
(identical node ids, none of the changes present). **Zero new reds.**

Rebased twice. The first rebase onto #5357 **changed the severity of a
finding** —
that PR narrowed publication to `message_role` slots, so the enum cap is
now
latent-on-a-declared-vocabulary rather than live on every enum-like
leaf. The
docstring and tests were re-measured and rewritten rather than carried
forward.

## Residuals

- **Medium**: `annotations/join.py` computes `groups` over the
**selected page**
while `matched_annotation_count` is exact. `selection_truncated` is set,
but
`AnnotationStructuralJoinResult` carries **no `outcome` field at all** —
the
pre-#5356 shape, partially flagged and never `degraded`. Fix is a
surface-contract
  change on a different envelope type.
- **Low but unfair**: attached-unit truncation is distributed
arbitrarily across a
page — the per-session allowance is ~`fetch_limit/n`, so a long session
loses more
than a short one. This PR makes the cut **visible**; it does not make it
**fair**.
The fix is `ROW_NUMBER() OVER (PARTITION BY session_id …)`, a SQL
behaviour change
  with a much larger blast radius.
- **Latent**: `mutation_actuators.py:2439` resolves a full
insights-rebuild scope via
`list_summaries(limit=1_000_000)` and then calls `build_plan`, which
refuses above
`MAX_MUTATION_PLAN_TARGETS = 256` — so a full-scope rebuild appears to
raise for any
archive with more than 256 sessions. **Read, not executed**; worth a
targeted check.
- **Informational**: `operations/slo.py` has zero importers anywhere.
Under the
  no-legacy rule that is a removal target, not a cap to tune.

Acts on the 2026-09-21 operator ruling; no bead was opened or modified.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

https://claude.ai/code/session_015WCh9YW3cRfsg3CZBKU7Fq


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

- **New Features**
- Query results now clearly indicate when attached-unit data is
truncated, including the affected unit and limit.
- Facet responses report degraded status when session-scope limits are
reached.
- Schema annotations now include all qualifying observed values instead
of applying a fixed output cap.
- Archive readiness details now provide a complete breakdown across all
source origins.

- **Bug Fixes**
- Prevented bounded reads from being reported as fully complete when
data was cut off.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
Sinity added a commit that referenced this pull request Sep 29, 2026
## Summary

Lands 24 verified storage fixes from the worker-6 Codex-debt batch
(beads polylogue-1tyq5.101, .102, .103). Each fix was rechecked against
current master and has a regression test on its production route. One
worker fix was dropped because it contradicts documented policy
(103-09). The other 50 findings are recorded below as fixed-already,
stale, refuted or not reached.

## Problem

The worker could not run tests. Its draft (ca8dbff) was based on
e1a2f75, and master has moved on since then. Each "fixed" claim
therefore had to be checked again on current master. The defects that
remain on master:

- **Material admission** (`storage/materials.py`)
  - A valid JSON document larger than 2 MB was marked `malformed`.
- Multi-record NDJSON was marked `malformed` too, because it is not a
single JSON value.
- ZIP entry names were copied without a bound into durable manifest
metadata.
- Readmitting a material returned the caller's arguments rather than the
stored row.
- An idempotent retry matched its own row and was rewritten as
`duplicate`.
- A malformed URL raised out of the API before any durable claim was
recorded.
  - A material linked twice to one evidence ref was listed twice.
- A chunked response carrying a stale `Content-Length` was stored as
`partial`.
  - A redirected HTTP failure did not record which hop failed.
  - A relative file path raised in `Path.as_uri`.
- **Raw frontier** (`storage/raw_retention.py`)
- The integrity projection and the selected-frontier admission helpers
opened `source.db` with `validate_schema=False`. A source tier at an
unadmitted schema version could then report healthy frontier evidence.
- A pinned operation read with no ops handle fell back to opening the
live `ops.db` path.
- **Index tier and reads**
- Trigger-maintained action pairs copied the stale outcome cached on the
tool_use block. Pair outcomes now come from the paired result block.
- A work-event payload could override the validated
`event_id`/`summary`.
- Reviving or re-deleting a displaced saved view cleared another view's
watch.
- A NaN or infinite metadata value was accepted on first write, after
which the key could not be changed.
  - An empty aggregate page reported `total_groups=0`.
  - Session timestamps dropped their milliseconds.
- The observed-tool rollup and the observed-event relation, including
its status pushdown, reinterpreted a retained exit code 0 as success
even when the canonical outcome was a deliberate `unknown`.
- Changing an attachment ref's target or position did not invalidate the
profile binding.
- `list_embedding_catchup_runs` rejected the `completed_with_failures`
status that its writer accepts.
- **Bootstrap** (`archive_tiers/bootstrap.py`)
  - The OPS same-digest shortcut returned without enabling foreign keys.
- A failure after `.bootstrap` was published, but before the format
marker, left an archive that could not be recovered.

## Solution

Most fixes are the worker's patch, with these changes:

- **101-02:** JSON documents are validated as a stream with
`ijson.basic_parse`, so a large material is never loaded as Python
objects. NDJSON is parsed line by line.
- **101-04:** readmission returns the persisted row and does not
overwrite stored filename, media type, privacy or supersession metadata.
The worker's version replaced them with the new call's arguments,
including `None`.
- **101-05:** the extra "never mark malformed as duplicate" condition is
dropped. Only the self-match is fixed.
- **101-21:** the siblings are fixed too:
`raw_frontier_blocked_raw_ids`, `_raw_frontier_blocked_selected_paths`
and `raw_frontier_blocked_source_paths` open `source.db` with schema
admission and report `SchemaSkew` as unavailable.
- **101-23:** the ops-unavailable branch is typed and explicit.
- **103-15:** the finding's cited route (evidence summary) already reads
`result_state` on master. The same defect is fixed in the two remaining
readers: the rollup and `run_projection_relations` (projection and
pushdown).
- **103-09 dropped:** see the table.

## Verification

- `agentctl job start polylogue pytest_focused --workspace
/realm/worktrees/salvage-w6 -- <28 files>` (job 2539): 631 passed, 12
failed, 1 error. The same 9 failures and 1 error occur on base (job
2601: `test_user_state_contracts` FacadeDaemonRequiredError x7,
`test_session_partition_convergence` x2,
`test_frontier_admission::test_changed_keys_beyond_one_batch_are_all_checked`
timeout). The other 3 were test defects in the new file (DSL `AND`,
source-tier raw lookup), fixed and rerun in job 2603: 43 passed, 1
failed (the same base timeout).
- Revert proof: the production files restored from origin/master, with
the new tests kept (job 2540): 35 failed. Every new test fails, each on
the defect it names (for example `ValueError: relative paths can't be
expressed as file URIs`, `DID NOT RAISE`, `KeyError:
'uncompressed_bytes'`, and assertion failures).
- `agentctl job start polylogue verify_quick --workspace
/realm/worktrees/salvage-w6` (job 2639): `verify: PASSED exit=0` at
2fcacb6 (the first run, job 2559, failed on a moved
sqlite-degradation anchor; the anchor was updated in the baseline).

## Self-review

**Sibling sites.** Each defect class was searched across the codebase.
- Unchecked durable-tier opens: three sibling source opens in
`raw_retention.py` were fixed. The two `ops.db` opens keep
`validate_schema=False`, because OPS is a disposable tier whose identity
converges in place.
- Exit-code success reinterpretation: the rollup and both observed-event
sites were fixed. `archive.py` still has error-count columns that count
error signals; they make no success claim, so they were left unchanged.
`archive/actions/parsing.py` and `rendering/semantic_cards.py` are
presentation-layer and out of scope.
- The watch-clearing fix covers both `save_view` and `delete_view`.

**Cancellation and shutdown.** No loops or long-running work were added.

**Unbounded reads.** JSON validation now streams rather than
materializing a whole document. The ZIP manifest no longer copies names.
`admit_material_file` still reads the whole file (103-13, not reached).

**Fail-open fallbacks.** Removed rather than added: the pinned read no
longer falls back to the live ops path. Schema skew now blocks admission
instead of passing silently.

**Compatibility shims.** None added.

**Removed symbols.** The unused `require_operation_lifecycle_status`
import is gone. No monkeypatch targets or fakes reference anything
removed.

**Tests prove the production route.** Every test goes through
`admit_material`/`acquire_material`, `ArchiveStore`,
`initialize_active_archive_root`, the trigger DDL, or the query route
(`query_unit_counts`). The revert run shows they fail on master's code.

## Per-finding table

| key | disposition | evidence | test |
|---|---|---|---|
| 101-01 #5249 `polylogue/storage/index_generation.py:1599` |
fixed-already | `polylogue/daemon/cli.py:3376`: Shutdown discard is
submitted through write_coordinator.run_sync before coordinator drain. |
— |
| 101-02 #4241 `polylogue/storage/materials.py:73` | fixed | Validates
the whole document as a stream (ijson) and NDJSON record by record;
trailing garbage stays malformed. |
test_material_json_admission_validates_the_complete_document,
test_material_ndjson_admission_parses_each_record. |
| 101-03 #4241 `polylogue/storage/materials.py:80` | fixed | Manifest
keeps entry_count and uncompressed_bytes only; names stay in the
retained CAS bytes. |
test_material_zip_manifest_does_not_copy_entry_names. |
| 101-04 #4241 `polylogue/storage/materials.py:139` | fixed |
admit_material returns the persisted row (get_material) instead of its
arguments; stored filename/media/privacy/creation time are not
overwritten on readmission. |
test_material_readmission_returns_the_persisted_row. |
| 101-05 #4320 `polylogue/storage/materials.py:150` | fixed | Duplicate
detection excludes the admitted material_id. |
test_material_readmission_does_not_duplicate_itself (a distinct
observation of the same bytes is still 'duplicate'). |
| 101-06 #4320 `polylogue/storage/materials.py:236` | fixed-already |
`polylogue/storage/materials.py:662-674;
polylogue/storage/materials.py:715-720`: List extracts IDs from tuple
rows or sqlite3.Row; get_material maps cursor.description for tuples. |
— |
| 101-07 #4623 `polylogue/storage/materials.py:240` | fixed | URL
parsing and InvalidURL/ValueError from connection construction become a
durable non-retryable 'malformed' claim. |
test_material_invalid_url_is_a_durable_malformed_claim,
test_material_invalid_http_target_is_a_durable_claim. |
| 101-08 #4241 `polylogue/storage/materials.py:240` | fixed | Evidence
filter uses EXISTS, one row per material. |
test_material_evidence_listing_returns_one_observation_per_identity. |
| 101-09 #5408 `polylogue/storage/materials.py:262` | fixed |
Content-Length is ignored when Transfer-Encoding frames the response. |
test_material_chunked_response_ignores_stale_content_length. |
| 101-10 #4623 `polylogue/storage/materials.py:315` | fixed | HTTP
failure diagnostic carries the failing hop URL when it differs from
source_uri. | test_material_http_error_retains_redirect_destination. |
| 101-11 #4623 `polylogue/storage/materials.py:345` | fixed |
admit_material_file uses Path.absolute() before as_uri(). |
test_material_relative_file_admission_retains_success_or_absence. |
| 101-12 #4623 `polylogue/storage/materials.py:345` | fixed | Same fix
as the sibling comment on this line (Path.absolute()). |
test_material_relative_file_admission_retains_success_or_absence. |
| 101-13 #4623 `polylogue/storage/materials.py:347` | not reached |
`polylogue/storage/materials.py:591-594`: Local material admission reads
the entire file into memory. | — |
| 101-14 #5626 `polylogue/storage/materials.py:741` | not reached |
`polylogue/storage/materials.py:739-752`: Timestamp/hash keyset cursor
can miss subsequent inserts sorting before the cursor at the same
timestamp. | — |
| 101-15 #4039
`polylogue/storage/raw_authority_verdict_projection.py:103` | not
reached |
`polylogue/storage/raw_authority_verdict_projection.py:86-148`:
Projection promotes every byte-proven append leaf independently of
accepted-chain ambiguity. | — |
| 101-16 #4556 `polylogue/storage/raw_failure_lifecycle.py:111` |
fixed-already | `polylogue/storage/raw_failure_lifecycle.py:124-139`:
Ordinary source open performs admission and reports SchemaSkewError as
unavailable. | — |
| 101-17 #5301 `polylogue/storage/raw_reconciler.py:213` | not reached |
`polylogue/storage/raw_reconciler.py:108-127`: Renamed pass_id payload
still advertises the previous census.v1 schema. | — |
| 101-18 #5350 `polylogue/storage/raw_reconciler.py:324` | refuted |
`polylogue/storage/raw_reconciler.py:314-381`: Explicitly requires an
archive predating the raw-ID change; current assignment is fresh v1 with
no carry-forward of that state. | — |
| 101-19 #5350 `polylogue/storage/raw_reconciler.py:549` | refuted |
`polylogue/storage/raw_reconciler.py:564-615`: Requests migration of
durable candidate assertions from a deleted framework; outside the
fresh-v1/no-carry-forward contract. | — |
| 101-20 #5301 `polylogue/storage/raw_reconciler.py:1049` | not reached
| `polylogue/storage/raw_reconciler.py:394-473`: Blocker ID selection
only searches its proposed ID; a unique open plan conflict can suppress
the insert while returning a nonexistent ID. | — |
| 101-21 #4556 `polylogue/storage/raw_retention.py:1231` | fixed |
Frontier projection opens source.db with schema admission and reports
SchemaSkew as unavailable; the selected-frontier admission helpers
(raw_frontier_blocked_raw_ids, _raw_frontier_blocked_selected_paths,
raw_frontier_blocked_source_paths) do the same. |
test_frontier_projection_refuses_a_source_from_a_newer_schema. |
| 101-22 #4683 `polylogue/storage/raw_retention.py:1302` | not reached |
`polylogue/storage/raw_retention.py:1387-1420`: Admission attributes a
sampled million-row projection without refusing truncated populations. |
— |
| 101-23 #5020 `polylogue/storage/raw_retention.py:1688` | fixed | With
ops_conn=None the pinned snapshot reports cursor status 'unknown' and
never opens ops_db_path. |
test_pinned_frontier_does_not_substitute_a_live_ops_file_for_missing_reader.
|
| 101-24 #5371 `polylogue/storage/raw_retention.py:2350` | not reached |
`polylogue/storage/raw_retention.py:2478-2491`: Residual test uses
post-filter candidate count, which cannot prove the SQL selection was
exhausted. | — |
| 101-25 #4538
`polylogue/storage/search_providers/sqlite_vec_runtime.py:98` |
fixed-already |
`polylogue/storage/search_providers/sqlite_vec_runtime.py:239-249`:
Managed provider rejects missing active index before attempting
attachment; pinned snapshot uses read-only attachment at 120-133. | — |
| 102-01 #4538
`polylogue/storage/search_providers/sqlite_vec_runtime.py:115` | not
reached |
`polylogue/storage/search_providers/sqlite_vec_runtime.py:34-108;251-256`:
Managed connections rebuild and hash the complete eligible-message TEMP
projection on each acquisition. | — |
| 102-02 #5274 `polylogue/storage/source_generation_receipts.py:252` |
not reached | `polylogue/operations/daemon_ingest.py:881-999`:
Historical receipt serializes raw identities/completeness but not
source-item blockers and member dispositions. | — |
| 102-03 #4719 `polylogue/storage/sqlite/action_pairs.py:44` | fixed |
Action pairs take the outcome from the paired result block, 'no_result'
when absent, matching _reconcile_tool_use_outcomes. |
test_action_pairs_follow_paired_result_updates_and_deletes. |
| 102-04 #5275 `polylogue/storage/sqlite/archive_tiers/__init__.py:43` |
fixed-already |
`polylogue/storage/sqlite/archive_tiers/__init__.py:21-26;42-49`:
Exported durable tier constants and ARCHIVE_VERSION_BY_TIER all use
version one. | — |
| 102-05 #4201 `polylogue/storage/sqlite/archive_tiers/archive.py:416` |
fixed-already | `polylogue/mcp/archive_support.py:165-179;
polylogue/surfaces/payloads.py:1311-1315`: MCP delegates to canonical
hydration and the shared summary envelope explicitly supplies
terminal_state, total_cost_usd, cost_provenance and relative_time. | — |
| 102-06 #4353 `polylogue/storage/sqlite/archive_tiers/archive.py:1085`
| not reached |
`polylogue/storage/sqlite/archive_tiers/archive.py:1622-1629`:
Work-event append reverses public Origin into guessed Provider. | — |
| 102-07 #4353 `polylogue/storage/sqlite/archive_tiers/archive.py:1086`
| fixed | Validated event_id and summary are merged after the caller
payload. | test_work_event_payload_cannot_override_validated_identity. |
| 102-08 #4816 `polylogue/storage/sqlite/archive_tiers/archive.py:2459`
| stale | `polylogue/storage/sqlite/archive_tiers/archive.py:4492-4513`:
Named list_session_work_event_insights LIKE implementation is gone;
current insight dispatch is elsewhere. No claim of testing successor
search. | — |
| 102-09 #4225 `polylogue/storage/sqlite/archive_tiers/archive.py:2542`
| not reached | `polylogue/storage/sqlite/archive_tiers/archive.py:3168;
polylogue/storage/sqlite/archive_tiers/archive.py:3952`: Full catalog
coverage sets cost_is_estimated=0, confusing completeness with monetary
authority. | — |
| 102-10 #4293 `polylogue/storage/sqlite/archive_tiers/archive.py:2681`
| not reached |
`polylogue/storage/sqlite/archive_tiers/archive.py:3351-3360;3400-3419`:
Outer cohort dedup count is reused for raw-model breakdown and status
classification. | — |
| 102-11 #4395 `polylogue/storage/sqlite/archive_tiers/archive.py:2957`
| fixed-already |
`polylogue/storage/sqlite/archive_tiers/archive.py:3280;3311;3351`:
Session populations use json_group_array and lossless
_decode_session_id_set instead of comma splitting. | — |
| 102-12 #4692 `polylogue/storage/sqlite/archive_tiers/archive.py:3380`
| fixed-already |
`polylogue/storage/sqlite/archive_tiers/archive.py:3971;8398`: Profile
SELECT and domain mapper both carry input_content_hash. | — |
| 102-13 #5408 `polylogue/storage/sqlite/archive_tiers/archive.py:5215`
| fixed | save_view clears the previous name's watch only when this view
still owns that name. |
test_resurrected_view_rename_does_not_clear_another_views_watch. |
| 102-14 #5408 `polylogue/storage/sqlite/archive_tiers/archive.py:5284`
| fixed | delete_view clears the watch only on a successful delete of
the name's active owner. |
test_redeleting_view_does_not_clear_reassigned_name_watch. |
| 102-15 #5307 `polylogue/storage/sqlite/archive_tiers/archive.py:6193`
| not reached |
`polylogue/storage/sqlite/archive_tiers/archive.py:6222-6229`: Provider
usage readiness takes archive-global status counters, not the requested
origin/time scope. | — |
| 102-16 #5307 `polylogue/storage/sqlite/archive_tiers/archive.py:6195`
| not reached |
`polylogue/storage/sqlite/archive_tiers/archive.py:6222-6229`: Provider
usage readiness hardcodes stale count zero and only compares row
coverage. | — |
| 102-17 #4238 `polylogue/storage/sqlite/archive_tiers/archive.py:6730`
| not reached |
`polylogue/storage/sqlite/archive_tiers/archive.py:7688-7699`: Display
duration subtracts normalized session endpoints, including synthesized
endpoints. | — |
| 102-18 #4649 `polylogue/storage/sqlite/archive_tiers/archive.py:7271`
| not reached |
`polylogue/storage/sqlite/archive_tiers/archive.py:8140-8146`: Missing
persisted provenance is labeled with current materializer version. | — |
| 102-19 #5362 `polylogue/storage/sqlite/archive_tiers/archive.py:7408`
| not reached |
`polylogue/storage/sqlite/archive_tiers/archive.py:7672-7679`: All
heuristic titles are suppressed, not only prompt echoes. | — |
| 102-20 #4221 `polylogue/storage/sqlite/archive_tiers/archive.py:7539`
| stale | `polylogue/storage/sqlite/archive_tiers/archive.py:8454-8504`:
Former profile-cost fallback was removed; current cost insight uses
canonical usage authority and reports no_tokens explicitly rather than
labeling fallback as catalog-priced. | — |
| 102-21 #4804 `polylogue/storage/sqlite/archive_tiers/archive.py:7839`
| fixed | set_user_metadata canonicalizes every value before the first
write, so NaN/inf are refused inside the transaction. |
test_metadata_first_write_refuses_nonfinite_json_atomically. |
| 102-22 #5275
`polylogue/storage/sqlite/archive_tiers/archive_plan.py:189` |
fixed-already |
`polylogue/storage/sqlite/archive_tiers/archive_plan.py:181-213`: Schema
fingerprint and version readers now use canonical
open_readonly_connection URI construction. | — |
| 102-23 #5275
`polylogue/storage/sqlite/archive_tiers/archive_plan.py:261` | stale |
`polylogue/storage/sqlite/archive_tiers/archive_plan.py:181-223;bootstrap.py:877-924`:
initialize_archive_tier_files_from_plan is deleted; ordinary fresh root
bootstrap now records and admits pending intent. | — |
| 102-24 #5356
`polylogue/storage/sqlite/archive_tiers/archive_query_reads.py:3424` |
fixed | The aggregate page selects a count row over all groups joined to
the requested page, so an empty page keeps total_groups. |
test_empty_aggregate_page_preserves_total_group_count. |
| 102-25 #5514
`polylogue/storage/sqlite/archive_tiers/archive_tiers_specs.py:48` |
fixed-already |
`polylogue/storage/sqlite/archive_tiers/vocabulary_inventory.py:138-153`:
core_types is scanned before consumer re-exports, retaining declaration
ownership. | — |
| 103-01 #5521
`polylogue/storage/sqlite/archive_tiers/archive_tiers_specs.py:49` | not
reached | `docs/atlas/00-core.md:59-67;docs/atlas/storage.md:35-40`:
Identity anchors no longer point at their generated-key declarations. |
— |
| 103-02 #4678
`polylogue/storage/sqlite/archive_tiers/archive_tiers_specs.py:729` |
fixed | Session created_at/updated_at project
strftime('%Y-%m-%dT%H:%M:%fZ', ms/1000.0). |
test_session_record_reads_preserve_milliseconds. |
| 103-03 #4177
`polylogue/storage/sqlite/archive_tiers/archive_tiers_specs.py:885` |
not reached | `polylogue/maintenance/archive_verification.py:1443-1467`:
Lineage sanity checks message existence but not branch-point content
address agreement. | — |
| 103-04 #5476
`polylogue/storage/sqlite/archive_tiers/archive_tiers_specs.py:1217` |
not reached | `docs/atlas/storage.md:79-87`: Session-link/branch-point
explanation anchors shifted away from their declarations. | — |
| 103-05 #4302 `polylogue/storage/sqlite/archive_tiers/bootstrap.py:249`
| not reached |
`polylogue/storage/sqlite/archive_tiers/bootstrap.py:435-451;501-561`:
OPS sentinel fast path neither recreates nor refuses missing canonical
objects. | — |
| 103-06 #4302 `polylogue/storage/sqlite/archive_tiers/bootstrap.py:249`
| fixed | _materialize_archive_tier enables foreign keys before the OPS
same-digest shortcut. |
test_cached_ops_initialization_enables_connection_foreign_keys. |
| 103-07 #4560 `polylogue/storage/sqlite/archive_tiers/bootstrap.py:254`
| fixed-already |
`polylogue/storage/sqlite/archive_tiers/bootstrap.py:407-417`: Derived
identity stamp is followed by conn.commit(). | — |
| 103-08 #4560 `polylogue/storage/sqlite/archive_tiers/bootstrap.py:845`
| fixed-already |
`polylogue/storage/sqlite/archive_tiers/bootstrap.py:1159-1178`: Stored
user_version is admitted before materialization; skew raises SchemaSkew.
| — |
| 103-09 #4560 `polylogue/storage/sqlite/archive_tiers/bootstrap.py:846`
| dropped (not a defect) | ops.db identity converges in place by
documented policy (`initialize_archive_database`); worker's refusal
reverted | — |
| 103-10 #5275 `polylogue/storage/sqlite/archive_tiers/bootstrap.py:848`
| fixed-already |
`polylogue/storage/sqlite/archive_tiers/bootstrap.py:877-905`: Pending
fresh bootstrap intent is validated and exempts incomplete first
creation from completed-marker admission. | — |
| 103-11 #5275 `polylogue/storage/sqlite/archive_tiers/bootstrap.py:883`
| fixed-already |
`polylogue/storage/sqlite/archive_tiers/bootstrap.py:888-920`: Marker
admission and fresh-bootstrap classification are keyed to durable tier
files, not replaceable-only tiers. | — |
| 103-12 #5275 `polylogue/storage/sqlite/archive_tiers/bootstrap.py:959`
| fixed | Fresh bootstrap publishes (or validates an already published)
format marker before the completed bootstrap marker, so the pending
intent survives until both exist. |
test_fresh_bootstrap_format_publication_failure_is_resumable. |
| 103-13 #4323 `polylogue/storage/sqlite/archive_tiers/embeddings.py:20`
| refuted |
`polylogue/storage/sqlite/archive_tiers/embeddings.py:7;26-31`: Finding
requires opening the pre-v1 version-five vector table; this assignment
starts fresh with embeddings version one and canonical model column, no
prior archives. | — |
| 103-14 #4719 `polylogue/storage/sqlite/archive_tiers/index.py:868` |
not reached |
`polylogue/storage/sqlite/archive_tiers/archive_query_reads.py:121-143;1066-1088`:
Public action row and selected column list omit canonical
unknown-outcome reason. | — |
| 103-15 #4719 `polylogue/storage/sqlite/archive_tiers/index.py:877` |
fixed | The cited evidence-summary route already reads result_state on
master (operations/http_read_models.py read_session_evidence). The same
exit-code reinterpretation remained in
list_tool_observed_event_count_rows and the observed-event relation and
its status pushdown (run_projection_relations.py); all three now map
only the canonical tool_outcome. |
test_observed_tool_rollup_respects_canonical_outcome_over_exit_code. |
| 103-16 #4630 `polylogue/storage/sqlite/archive_tiers/index.py:1090` |
not reached |
`polylogue/storage/sqlite/archive_tiers/index.py:1319-1320`: Thread
search projection only includes thread ID, repo and session IDs;
evidence-kind/support terms are absent. | — |
| 103-17 #5312 `polylogue/storage/sqlite/archive_tiers/index.py:1257` |
fixed-already | `tests/infra/reindex_differential.py:95-98`:
session_usage_rollup_bindings now has an explicit exact deterministic
census classification. | — |
| 103-18 #5410 `polylogue/storage/sqlite/archive_tiers/index.py:1499` |
fixed | session_profile_binding_refs_au now fires on attachment_id and
position updates. |
test_attachment_reference_identity_and_order_invalidate_profile_binding.
|
| 103-19 #4630 `polylogue/storage/sqlite/archive_tiers/index.py:1786` |
not reached |
`polylogue/storage/sqlite/archive_tiers/index.py:2150-2158`: Child
monetary amount may use provider evidence while its estimated flag is
derived from catalog coverage. | — |
| 103-20 #4630 `polylogue/storage/sqlite/archive_tiers/index.py:1919` |
not reached | `polylogue/storage/sqlite/archive_tiers/index.py:2289`:
Tag-rollup materialized_at is literal query-time rather than an ISO
timestamp or missing value. | — |
| 103-21 #5373 `polylogue/storage/sqlite/archive_tiers/ops.py:209` |
refuted |
`polylogue/storage/sqlite/archive_tiers/ops.py:1-220;bootstrap.py:888-909`:
Finding asks to carry and drop objects in archives from the prior OPS
schema. Fresh-v1/no-prior-state assignment excludes that upgrade. | — |
| 103-22 #5521
`polylogue/storage/sqlite/archive_tiers/ops_write.py:1237` | fixed |
list_embedding_catchup_runs validates the filter with
OperationRunStatus, the writer's vocabulary. |
test_embedding_catchup_filter_accepts_completed_with_failures. |
| 103-23 #4324
`polylogue/storage/sqlite/archive_tiers/read_insights.py:28` |
fixed-already |
`polylogue/storage/sqlite/archive_tiers/read_insights.py:27-36`:
Date-window parser delegates to shared parse_query_date. | — |
| 103-24 #4354
`polylogue/storage/sqlite/archive_tiers/read_insights.py:82` | not
reached |
`polylogue/storage/sqlite/archive_tiers/read_insights.py:123-145`:
Episode context scans only physical session messages and misses composed
inherited prefix. | — |
| 103-25 #4354
`polylogue/storage/sqlite/archive_tiers/read_insights.py:83` |
fixed-already |
`polylogue/storage/sqlite/archive_tiers/read_insights.py:115-136`: LIMIT
3 is inside the row-producing subqueries consumed by GROUP_CONCAT. | — |

## Derived-identity closure

All ten changed production files are members of the checked-in
`docs/plans/schema-closure-baseline.json`:

`storage/materials.py`, `storage/raw_retention.py`,
`storage/sqlite/action_pairs.py`,
`storage/sqlite/run_projection_relations.py`, and in
`storage/sqlite/archive_tiers/`: `archive.py`, `archive_query_reads.py`,
`archive_tiers_specs.py`, `bootstrap.py`, `index.py`, `ops_write.py`.

The index trigger DDL, the session timestamp projection and the
action-pair lowering all change, so the derived identity moves. This
must land before the fresh rebuild. `devtools schema closure` could not
run in this checkout because its environment is not provisioned, so
membership was read from the committed baseline.

## Residuals

- 26 findings are not reached, and they stay open in their beads. Among
them are 101-13 (local file admission reads the whole file into memory)
and 101-14 (keyset cursor).
- Session `created_at`/`updated_at` strings change format from
`YYYY-MM-DD HH:MM:SS` to ISO-8601 `...T...sssZ`. No reader in this
repository parses the old format; `annotations/join.py` slices the first
10 characters, which is unaffected.

🤖 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]>
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