Skip to content

feat: Serve read --view messages from the daemon and gate controlled reads - #5354

Merged
Sinity merged 2 commits into
masterfrom
fix/controlled-read-boundary
Sep 21, 2026
Merged

Sinity merged 2 commits into
masterfrom
fix/controlled-read-boundary

Conversation

@Sinity

@Sinity Sinity commented Sep 21, 2026 •

Copy link
Copy Markdown
Owner

Summary

Moves read --view messages onto the daemon, and makes the controlled-read
boundary an executable gate rather than prose.

The bead's design was not implementable as written

fko9.3 says to lower the messages view onto session.read's transcript
kind. Doing that would have:

  • replaced the rich MessageRowEnvelope rows (tokens, model, timestamp,
    attachment refs, ~32 fields) with the transcript kind's 5-field identity
    projection
    — a silent output regression on --format json; and
  • minted continuations in a different vocabulary (operation="session.read",
    projection session-read-v1) than the one this view belongs to
    (sessions.read / session-owner-v1), breaking
    test_continuation_surface_parity.py
    , which requires a token minted by
    read_transcript_window to resume on the CLI.

Built instead: session.read gains a messages kind whose handler is framed
by operations/transcript_window.py::read_transcript_window_sync — the shared
window owner — so both the continuation family and the rich row vocabulary are
preserved. It refuses a filtered window by name rather than answering with
unfiltered rows, because the pinned page reader has no filter vocabulary.

Two further bead claims did not hold: run_read_messages did not compute via
api.iter_messages (that was only the --to file writer path), and the sibling
--view summary does not print served-by: on the cited input — line 924 is
the ordinary find/list page path, and --id <sid> read --view summary returns
through _emit_session_result well before it. No read view printed served-by:
at the base.

t46.11: the claimed defect does not reproduce, and the rule already half-existed

vclez's "six production ArchiveStore.open_existing() reads outside the
controlled boundary" cannot be reproduced at any head measured — there are
zero.
The guard that did exist licensed any read_only=False open with no
stated reason, which is exactly why the survivors could not be audited and why a
count of "six" could be asserted without contradiction.

The rule, now a gate in the quick set

A direct ArchiveStore.open_existing is exactly one of three things.
read_boundary — a read-only open installing the read control plane
(admission, pinned tier snapshot, cancellation/progress guard, receipt). There
are two owners, not one, because read parity is an equivalence between two
declared executors, not convergence on one route.
writer — an explicit read_only=False open taking the writer lease, with a
named role. The write-owner rule governs it.
violation — anything else.

The load-bearing check is not "is this open read-only". It is that a site
declared a writer still passes read_only=False — the realistic silent
regression is a declared writer losing its explicit write mode and becoming an
uncontrolled read while its census row still reads "writer". Which module may own
the boundary is policy (read_boundary_owners), so a new uncontrolled read
cannot license itself by claiming to be the boundary.

Census — every survivor classified

26 direct opens: 3 read-boundary owners, 23 licensed writers, 0 uncontrolled
reads, 5 recorded debt.
Reproduce with devtools gate controlled-read --json.

Classification n
read_boundary 3
writer / daemon_write 8
writer / facade_mutation 5
writer / ingest_write 5
writer / generation_lifecycle 2
writer / durable_probe 2
writer / fixture_seeding 1
violation 0

Debt named rather than licensed: four api/archive.py facade mutations taking the
writer lease in-process instead of admitting through the daemon write coordinator
(sole-writer completion work, not an alternate write policy), and
cold_build.py::active_index_generation_is_empty, which takes the writer lease
to answer a question that is a read
— its writable open is deliberate because it
bootstraps the durable tiers, but separating the bootstrap from the question would
let the question go through the read boundary.

Deleted tests/unit/archive/query/test_read_surface_control.py: the gate
enforces its rule and more, so keeping it would be a second, weaker restatement.

The doctrine sheet's open question "process-level sole writership is not proven by
the writer gate" is updated — the census is the evidence that question asked for,
while staying explicit that it records rather than enforces.

Two defects found and fixed on the way, both outside the bead text

  • RootModeRequest had no owner for "which configuration am I reading".
    Routes read request.params["_config"] directly, which is None for every
    invocation the root callback does not pin — i.e. every real polylogue read.
    run_read_hooks carried the same latent bug.
  • A typed refusal lost its declared code in both executors.
    operation_kernel._execute_directly flattened every ValueError to
    "invalid_request"; daemon_execution used code=str(exc) — the whole message
    as the code. A stale continuation therefore could not be reported as
    query_continuation_stale through the operation route.

Anti-vacuity — executed against the real tree

Mutation Red
Never ask the daemon (daemon_disabled = True) AssertionError: served-by: direct (23ms)
Falsify the served-by identity AssertionError: served-by: daemon (uds, 28ms) — reds two tests
Add an unlicensed open_existing to an unlisted file controlled_read_site_undeclared, gate exit 1
Remove read_only=False from one declared writer controlled_read_writer_is_not_explicit (declared a writer but opens without read_only=False, so it is an uncontrolled read), gate exit 1

Five more are encoded as unit tests over synthetic trees (self-declared boundary,
stale declaration, no boundary at all, unknown role, renamed owner path). Nothing
is reasoned-not-executed.

Schema closure — all 25 changed files out, measured at the real base

polylogue/surfaces/payloads.py is IN and was deliberately not touched —
read_contracts.py exists precisely so a new operation declaration does not move
the identity, and the new kind lives there. archive_tiers/archive.py and
write.py are IN and were avoided by discovering that
ArchiveSessionEnvelope already carries lineage_complete /
lineage_truncation_reason through read_archive_session_page, so the truncation
signal survives the move with no storage edit. That is what kept this leaf off
the rebuild boundary.

Verification

  • devtools verify --quick — exit 0, 25/25 gates, including the new
    gate controlled-read ... ok (4.4s)
  • devtools render all --check — exit 0, grep -c "out of sync" = 0
  • devtools gate controlled-read — exit 0, 26 observed, 0 violations
  • test_daemon_golden_parity.py 5 passed (incl. the new messages parity test
    against a real UDS daemon), test_messages.py 18,
    test_verify_controlled_read.py 11, test_archive_query.py 111
  • devtools test tests/unit/cli — 3166 passed / 37 failed, all inherited,
    proven by a detached checkout at the branch base inside the same worktree (406
    passed / 38 failed, identical node-id set; the 38th is outside tests/unit/cli)

Two reds were mine and are fixed, not excused: a pinned read-view partition
that moved by design, and two test_archive_query.py tests that appeared after
the rebase (new from #5350–#5353) monkeypatching a symbol this branch renamed.
That is why the post-rebase full-directory rerun mattered.

Residuals

  • --format json block payloads narrow slightly. content_blocks entries
    lose explicit-null keys. Cause: the daemon route hydrates through
    archive_block_to_domain, which deliberately drops None so an absent field
    stays absent rather than becoming an explicit null in every public block payload;
    the old async decode path emitted them. Measured empirically as the only
    field difference between the two projections, and render all --check is clean
    so no committed schema changed. Strictly narrowing and consistent with declared
    policy — named rather than buried.
  • The 8 MiB operation bound now applies to this view. A single window wider
    than the bound is a typed refusal naming the limit, where the in-process reader
    had none. --full and any --limit above 200 compose from bounded windows, so
    realistic cases are unaffected; a single --limit 1500 on very large messages
    could now refuse.
  • The gate observes AST over literal ArchiveStore.open_existing(...). An open
    reached through getattr, an alias, or a stored callable is not resolved —
    stated in the module docstring, not hidden.
  • tests/unit/cli/test_messages.py lost its _FakeApi message-path tests: they
    mocked Polylogue.open, which the route no longer uses, so a double could not
    have proven the route. Replaced with seeded real archives via SessionBuilder,
    including a genuine prefix-sharing fork with a hard-deleted parent branch point.

Closes polylogue-fko9.3, polylogue-t46.11.

🤖 Generated with Claude Code

https://claude.ai/code/session_015WCh9YW3cRfsg3CZBKU7Fq

Summary by CodeRabbit

  • New Features

    • Added support for viewing messages through the session read operation.
    • Added message pagination, continuation tokens, full transcript output, and lineage metadata.
    • Added consistent JSON and NDJSON message output across direct and daemon execution.
    • Added executor authority details to read results.
  • Bug Fixes

    • Preserved specific error codes for invalid, stale, or expired continuation requests.
    • Improved handling and reporting of missing sessions and read failures.
  • Documentation

    • Documented controlled archive-read boundaries and associated verification rules.

Sinity and others added 2 commits September 21, 2026 15:33
`read --view messages` was the one read view that still computed its answer
in this process: a healthy daemon paid for a local archive open and the
`polylogue.api` facade import on every invocation, while every sibling view
was served over UDS.

`session.read` grows a `messages` kind -- the same bounded message window as
`transcript`, projected in the full message-row envelope vocabulary the
`read --view messages` document is made of. It is framed by
`operations/transcript_window.py` rather than by `session.read`'s own
framing, so a continuation minted by the Python API, MCP or HTTP still
resumes on the CLI and vice versa; a filtered window has no reader here and
is refused by name instead of answered with unfiltered rows.

The verb now lowers and renders only. `--verbose` prints `served-by:` naming
the executor the result's own authority reports, and the read-view registry
moves `messages` off the shrink-only `IN_PROCESS_READ_VIEWS` ratchet onto
`session-read-projection`.

Two defects found on the way:

- `RootModeRequest` had no owner for "which configuration am I reading":
  routes read `params["_config"]` directly, which is `None` for every
  invocation the root callback does not pin. `request.config()` falls back to
  the active configuration, as the one existing resolution already did.
- A typed refusal lost its declared code in both executors -- the direct one
  flattened every `ValueError` to `invalid_request`, the daemon one used the
  whole message as the code. A stale or foreign continuation now reaches a
  caller by the same token on both legs.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_015WCh9YW3cRfsg3CZBKU7Fq
polylogue-vclez claimed "six production ArchiveStore.open_existing() reads
outside the controlled boundary" and no artifact said which call sites those
were, so the claim could not be audited and the work it gated could not be
given disjoint ownership. The population is 26 direct opens at this head and
it grows; a prose list of them is wrong the first time somebody adds one.

The rule, written down: a direct archive open is either a declared
read-boundary owner, or an explicit `read_only=False` writer-lease open with a
stated writer role, and anything else is a read that escaped admission,
snapshot pinning, cancellation and receipts. There are two boundary owners,
not one, because read parity is an equivalence between two declared executors
(6fcfe44) rather than convergence on one route.

`devtools gate controlled-read` censuses every call site against
`docs/plans/controlled-read-census.yaml`, which classifies all 26 with a
reason each. The census verdict at this head: 3 read-boundary owners, 23
licensed writers, 0 uncontrolled reads -- vclez's six do not reproduce. Five
sites carry a recorded `debt`: the four Python-API facade mutations take the
writer lease in-process rather than admitting through the daemon write
coordinator, and `active_index_generation_is_empty` takes it to answer a
question that is a read.

`tests/unit/archive/query/test_read_surface_control.py` is deleted: the gate
enforces its rule and more. The test licensed any `read_only=False` open with
no stated reason, which is exactly why the surviving population could not be
audited.

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-21T13:59:56.730195Z 421eda3 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 13:48
@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: 547af93c-1227-463c-96c9-22c673f48427

📥 Commits

Reviewing files that changed from the base of the PR and between 51222af and 421eda3.

📒 Files selected for processing (26)
  • devtools/gate.py
  • devtools/verify_controlled_read.py
  • docs/atlas/doctrine.md
  • docs/atlas/query-read-path.md
  • docs/plans/controlled-read-census.yaml
  • polylogue/cli/archive_query.py
  • polylogue/cli/lowering.py
  • polylogue/cli/messages.py
  • polylogue/cli/operation_kernel.py
  • polylogue/cli/query_verbs.py
  • polylogue/cli/read_dispatch.py
  • polylogue/cli/read_view_registry.py
  • polylogue/cli/read_views/messages.py
  • polylogue/cli/root_request.py
  • polylogue/operations/daemon_execution.py
  • polylogue/operations/daemon_reads.py
  • polylogue/operations/read_contracts.py
  • tests/unit/archive/query/test_read_surface_control.py
  • tests/unit/cli/test_archive_query.py
  • tests/unit/cli/test_daemon_client.py
  • tests/unit/cli/test_daemon_golden_parity.py
  • tests/unit/cli/test_messages.py
  • tests/unit/cli/test_read_view_classification.py
  • tests/unit/cli/test_read_view_execution_routes.py
  • tests/unit/devtools/test_verify_controlled_read.py
  • tests/unit/operations/test_transcript_window_route.py
 __________________________________
< The only good bug is a dead bug. >
 ----------------------------------
  \
   \   \
        \ /\
        ( )
      .( o ).
✨ 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.

@Sinity
Sinity merged commit 2bbecb9 into master Sep 21, 2026
2 of 3 checks passed
@Sinity
Sinity deleted the fix/controlled-read-boundary branch September 21, 2026 13:59

@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: 421eda3c81

ℹ️ About Codex in GitHub

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

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

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

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

Comment thread polylogue/cli/read_views/messages.py Resolved
Comment thread polylogue/cli/messages.py Resolved
Comment thread polylogue/cli/messages.py Resolved
Comment thread polylogue/operations/daemon_reads.py Resolved
Comment thread polylogue/cli/messages.py Resolved
Comment thread polylogue/operations/daemon_reads.py Resolved
Sinity added a commit that referenced this pull request Sep 21, 2026
…#5356)

## 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.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**
* 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.

<!-- 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 21, 2026
)

## Summary

`events` and `raw` were the two `IN_PROCESS_READ_VIEWS` that **#5370
could not
move for contract reasons rather than effort**. Both are fixed here; the
ratchet
drops **8 → 6**.

Taken over directly after the lane died mid-run on a network error with
uncommitted work.

## Why they could not move as they were

**`events`** accepted `--limit` and reported the **clipped** row count
as its own
`total`. An evidence kind is answered whole, so lowering it unchanged
would have
made `session.read` report `complete=true` for a truncated body — which
`SessionReadResult`'s validator refuses outright. Nothing in the payload
separated a cut body from a finished one.

**`raw`** is genuinely windowed, with a real limit/offset and a real
total — but
`operations/transcript_window.py` owns the **message** window vocabulary
(`TRANSCRIPT_WINDOW_PROJECTION`, `session-owner-v1`). Minting artifact
continuations into that family is exactly the mixing the family exists
to
prevent: **a token that resumes "artifacts 50..100" while carrying the
message
projection is readable by a reader that will compose messages with it.**

## The contract

`operations/evidence_window.py` declares a **second continuation family,
per
relation rather than per surface**. A family names three things and
nothing else:

- the `session.read` kind it pages,
- **its own projection token** — what makes a foreign continuation
refusable *by
  name* instead of silently resumable, and
- the stable order the relation is windowed in, because a continuation
is only
  meaningful against an order the reader guarantees.

It deliberately does **not** own the window arithmetic or the snapshot
binding.
`next_offset` / `complete` / token minting and the before-and-after
epoch check
come from `transcript_window`'s `window_result` / `bind_snapshot`, which
take a
transaction and know nothing about messages. **An off-by-one or a
missing epoch
revalidation therefore stays one defect across both families instead of
two
independent ones.** The separation that matters is the vocabulary.

The bound is declared and reported, never silent: `total` is the
relation's own
row count, `returned` is the page's, and a page that does not reach the
total
mints a continuation instead of claiming completeness.

## Anti-vacuity — executed

Make the events reader return the page length as the relation total
(`return rows, len(rows)`) and **both** new tests go red with `assert
None` on the
continuation — because a page that believes it is whole mints no token.
A `limit`
at or above the relation's row count cannot witness this, so the window
in the
test is strictly smaller.

The second test asserts the families refuse each other: a continuation
minted for
`events` is rejected when presented to `transcript`.

## Two doubles removed rather than repaired

`tests/unit/cli/test_messages.py` drove `run_raw` and
`run_session_events`
through a `_FakeApi` with `patch("polylogue.api.Polylogue.open")`. Those
functions no longer exist — both views route through the declared
operation — and
**per #5354's precedent a double could not have proven the route in any
case.**
Their subject is covered by the new contract tests and the existing
golden-parity suite.

## Landing window

**All changed production files measure `out`; the derived identity does
not move**
— this can land during a rebuild. That held because a new operation
declaration
goes in `read_contracts.py` (which exists precisely so it stays off the
boundary)
rather than in `surfaces/payloads.py`, which is **IN**.

## Verification

`devtools verify --quick` — exit 0, all gates. `devtools render all
--check` —
exit 0, zero `out of sync`. `devtools test` over the evidence readers,
the
execution-route ratchet, continuation-surface parity and the daemon
golden parity
— exit 0. The evidence-reader module runs 5 passed including the two new
contract tests.

## Residual

**Six views remain in-process, and each needs its own operation
declaration
rather than a `session.read` kind**: `dialogue`, `temporal` and
`chronicle`
accept query sets rather than one exact reference; `effective_context`
is a
compaction-aware replay with `--at-position`; `neighbors` and
`correlation` reach
different subsystems.

A harness note for anyone adding tests here: `tests/conftest.py`
rewrites any
nodeid over 100 characters into a digest form, so a long test name
becomes
**unselectable by id** and reports as `not found` while the module
imports fine.
Both new names are kept under the threshold.

Advances polylogue-r3cuz (8 of 11 moved).

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

https://claude.ai/code/session_01ToWqpkXotr573DiQex5vcy

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
@Sinity

Sinity commented Sep 29, 2026

Copy link
Copy Markdown
Owner Author

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.

@Sinity

Sinity commented Sep 29, 2026

Copy link
Copy Markdown
Owner Author

Closing out open Codex review threads on this PR (evidence checked against master at c950478):

Resolving every thread listed; confirmed defects are fixed under the named bead.

@Sinity

Sinity commented Oct 1, 2026

Copy link
Copy Markdown
Owner Author

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

  • 60.F051 / P1: fixed-already at the checked revision: Message-file output streams into a sibling temporary file and removes it on read failure. Only after the complete sequence is written and synced does polylogue/cli/read_views/messages.py:245 atomically replace the destination, preserving an existing file when the first read fails.

Only the rows listed above are dispositioned. Held findings remain open.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant