Skip to content

perf: preserve pytest width and share wire receipts - #4867

Merged
Sinity merged 97 commits into
masterfrom
perf/pytest-slot-wire-cache
Sep 12, 2026
Merged

Sinity merged 97 commits into
masterfrom
perf/pytest-slot-wire-cache

Conversation

@Sinity

@Sinity Sinity commented Sep 12, 2026

Copy link
Copy Markdown
Owner

Summary

  • Size an admitted corpus from its local pytest slice, not ambient fleet memory.
  • Reuse immutable wire-support receipts across xdist processes in one harness run.

Problem

The corpus width collapsed under unrelated agent usage, and each worker rebuilt the same expensive wire-support receipt.

Solution

Host pressure remains an admission decision; command width now uses the local pytest slice. Wire receipts use an atomic, run-scoped JSON cache with a flock and typed recovery.

Verification

  • nix develop --command devtools verify --quick
  • nix develop --command devtools test tests/unit/devtools/test_corpus_worker_memory_bound.py tests/unit/core/test_synthetic_wire_support.py -k 'worker_memory or run_cache' — 43 passed\n\n## Residuals\n\nThe two independently slow raw-admission tests remain open pending profiling; no broad corpus was run.

@coderabbitai

coderabbitai Bot commented Sep 12, 2026

Copy link
Copy Markdown

Important

  • 🔍 Trigger review

This repository does not receive automatic reviews because it has fewer than 10 stars.

⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Advanced

Run ID: d92b2090-85ea-4273-9cfe-eef45d28bf2b


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 commented Sep 12, 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-12T03:27:54.254219Z 7b834aa 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 12, 2026 03:18
@Sinity
Sinity merged commit 1d901ec into master Sep 12, 2026
3 checks passed
@Sinity
Sinity deleted the perf/pytest-slot-wire-cache branch September 12, 2026 03:21

@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: 7b834aa44f

ℹ️ 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/commands/status.py Resolved
Comment thread docs/atlas/daemon.md Resolved
Comment thread polylogue/daemon_client.py Resolved
Comment thread polylogue/daemon/http.py Resolved
Comment thread polylogue/cli/archive_query.py Resolved
Sinity added a commit that referenced this pull request Sep 13, 2026
#5030)

Closes the largest cluster under `polylogue-7lhl5` — 11 test failures
plus the 6
pre-existing `test_facade_contracts.py` failures.

## Summary

Replace a leaked internal `MutationTransactionError` with a typed,
actionable
refusal naming the sanctioned route, and retarget the insight
materialization
laws onto their production materializer.

## Problem

`Polylogue.rebuild_insights` was dead. It called
`_execute_facade_mutation`
(`api/archive.py:2734-2770`) into `executor.execute_bound`, which is
refused at
`operations/mutation_transaction.py:910-920`. Landing commit `1d901ec73`
(#4867)
added the whole insight-acceptance machine and never touched
`api/archive.py`,
so the facade was simply left behind.

Live impact: MCP's `rebuild_insights` dispatcher
(`mcp/server_cutover.py:2384-2389`, gated on `confirm=true`) was the
sole
non-test production caller and was dead; the public Python API was dead.
The
daemon route (`maintenance.insights.rebuild`) always worked. The CLI has
no
rebuild-insights verb.

## Decision: typed refusal, not delegation

The facade cannot hold the authority. A sweep is sealed page by page —
manifest
frozen, previews staged, parts sealed, ordinals started through
`begin_accepted_insight_part` — which needs durable audit authority, a
pinned
index generation and recipe binding, and the resident session-profile
publication owner. CLAUDE.md names `polylogued run` the required
live-write
owner for exactly this.

**Delegation was pursued and rejected on evidence, not preference.** The
transport does exist and is reusable: `daemon_client.py` has
`DaemonClient.operation_to_completion`, already used by CLI verbs to
delegate
mutations from non-daemon processes. It was rejected on a concrete
blocker — the
completed insight envelope's result is the machine-lifecycle state from
`machine_request_state`, carrying `parts`/`affected_count` but **not**
the
declared `InsightRebuildResult` counts, so `validate_operation_result`
would
reject the daemon's own result. Delegating today means shipping
unverifiable
code against a wire contract that is itself unfulfilled. When that
contract is
completed, this refusal is the natural place to swap in delegation.

Neither guard was loosened, and `InsightsRebuildActuator` is untouched —
it
remains the plan builder used by `insight_planning.py`.

### What callers now experience

- **Library:** `InsightMaintenanceRequiresDaemonError`
(`code="daemon_required"`,
HTTP 503) naming `polylogued run` and `maintenance.insights.rebuild`.
The
message is fixed strings only, never user data, so any surface can
forward it.
- **MCP:** a clean `daemon_required` error envelope carrying that route,
instead
  of `internal_error` wrapping a `MutationTransactionError`.

Neither can run a rebuild — which is honest, and an improvement over
dead.

## The six facade-contract failures

All confirmed pre-existing on untouched tip `a3d6ffe2b` (receipt
`20260913T193858Z-focused-test-1293934-0eb4f721`) before being touched:

- Four were the sealing cluster; retargeted to the shared materializer.
- `test_no_undiscovered_async_methods` was **the discovery gate working
correctly** — `get_session_orchestration` is genuinely uncovered there.
It is
  now categorized as bespoke, naming the file that covers it.
- `stale_work_event_inference_count` was a stale expectation: the
profile row is
hand-inserted with no input binding, so binding-based inspection (#4849)
correctly calls its inference rows stale. Asserting 1 is the honest
reading.

## Scope widened where the same root cause reached

`tests/unit/core/test_resume.py` and `test_insight_export_bundles.py`
also called
the dead facade. Tests now go through one helper on a real production
route —
both `InsightsRebuildActuator.apply` and the daemon's own per-session
publication
path call `rebuild_session_insights_sync`. Per-law anti-vacuity
conditions are in
the test commit message.

## Verification

```
focused suites (11 cluster tests + 6 facade contracts + MCP)  PASSED exit=0
devtools verify --quick                                       exit 0
```

**Schema closure — measured, not assumed.** `devtools schema closure`
marks
`polylogue/core/errors.py` **IN** the derived closure, so the identity
was
computed rather than inferred: index and ops identities are
byte-identical
before and after (`bd388fcf53e4…` / `0a44d6a6764c…`). **No reconvergence
is
required.** Closure membership is not the same as an identity move.

## Residuals

Not this cluster, left for its owner:
`test_resume_candidates_preserve_resolvable_exact_jaccard` fails on the
untouched tip (receipt `20260913T200236Z-focused-test-1339607-d2348922`)
— a
resume overlap-scorer failure unconnected to insight maintenance.
Tracked under
`polylogue-7lhl5`.

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

https://claude.ai/code/session_01DYUNBGoE652b3nfmq3CtqK

---------

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

Triage of the CLI-output share of the 58 failures from the first
complete
full-corpus run (job 650). **Only 4 of 18 were test problems.** The
other 14 are
product defects, now on beads.

## The lead I was given was wrong, and that mattered

I was told the two `convergence debt:` assertions were almost certainly
asserting
a surface deliberately removed by #5027. **They are not stale.** The
renderer
still emits `Convergence debt:` at
`cli/commands/status.py:363/:454/:460`, and
the `convergence_debt` table survives across ~20 modules.

Both tests die *before* any convergence rendering — on the daemon
refusal.
Reproduced without pytest, same workspace both ways:

```
POLYLOGUE_DAEMON_URL=http://127.0.0.1:1 → "Daemon: running / Status snapshot: unavailable"
(unset)                                 → "Daemon: not running / No archive found."
```

Fixing `polylogue-2d8oq` should turn them green **with no test change**.
Recorded on that bead so it is not re-derived.

## Fixed (4)

| Test | Class | Cause |
|---|---|---|
| `test_query_composition_laws` | TEST-INFRA | The
`_daemon_delete_route` double returned `authorization_token`; #4867
renamed the contract to `authorization_refs`. Every other double was
already migrated — including the one this test's docstring says it
mirrors. |
| `test_paths::test_archive_override_unifies_…` | STALE-TEST | #4955
moved reset behind `maintenance.reset`; the test asserted the deleted
in-process bypass. Now asserts the refusal *and* that the override still
reaches the read-only preview. |
| `test_plain_cli_snapshots::test_json_analyze_snapshot` | STALE-TEST |
Snapshot updated — scoped to the single node, recording the terminal
`outcome` field the envelope now carries. |
| `test_maintenance_registration::test_blob_conservation_json_…` |
ORDER-DEPENDENT | Verified: passes alone and in a 74-test cross-file
selection; fails at directory scope and in the corpus. |

## Not fixed — 14 product defects, on beads

- **7 → `polylogue-2d8oq`** (existing): `basic_usage_cli` ×3,
`json_envelope_contract` ×2, `test_json_status_snapshot`,
`test_terminal_snapshots`, `test_convergence_surface_contract`.
- **5 → `polylogue-jih4s`** (filed): read-only query verbs take an
**exclusive maintenance ownership lock** and mint an auth token into the
archive root. Regression from #4867.
- **1 → `polylogue-kjy0a`** (filed): `ops status` publishes `converged:
false` with `reason: "ready"` on a pristine empty archive.
`daemon_status.py:158-162` derives `ready` and `summary` from
*different* predicates, and omits `determinate` — so the
converged-vs-unknown collapse from `polylogue-bp12n.1` is **still live
on this path**.
- **1 → `polylogue-uf7un`** (filed): daemon and direct `find` disagree
on the resolved root filter.

## #4867 again

`1d901ec73` now accounts for **12 of these 18** — 7 via 2d8oq, 5 via
jih4s — on
top of the five clusters already attributed to it on `polylogue-7lhl5`.

## Verification

```
devtools test tests/unit/cli   3040 collected, 12 not-green — every one on a filed bead
devtools verify --quick        15/15 gates, exit 0
```

One snapshot updated, justified above. No test was written that agrees a
nonexistent daemon is running.

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

https://claude.ai/code/session_01DYUNBGoE652b3nfmq3CtqK

---------

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
Sinity added a commit that referenced this pull request Sep 14, 2026
A deliberate three-pass audit of `1d901ec73` ("perf: preserve pytest
width and
share wire receipts", #4867 — 176 files, +23,948/−9,052).

That commit already accounted for ~35 defects found incidentally across
this
campaign. Auditing it directly found **16 more, none of which any test
would
catch**. Its own recorded verification (`verify --quick` plus 43 focused
tests)
could not have caught any of them — and there is a structural reason:
**`gate atlas` is not among `verify --quick`'s 15 gates**
(`polylogue-6cdzy`).

## Fixed here (5)

**The daemon cannot restart after `kill -9` or an OOM kill.** The
pre-bind unlink
was deleted, and the CLI silently degrades, so the cause is invisible to
the
operator. Restored *with a liveness probe*, so it cannot resurrect the
kadx3
socket-stealing bug the unlink removal was presumably guarding against.
This
matters directly: the campaign's build runs a long-lived daemon, and an
unclean
exit would have left it unable to come back.

**Session profile cost columns reported VALID while stale.**
`_refresh_provider_usage_rollup` reads `source_message_id` and
`occurred_at_ms`,
neither of which was projected. The completeness guard covered 2
relations; it now
covers all 6.

**Three lost failure contracts on pinned-connection readers.** The
squash added
pinned-connection twins throughout and repeatedly copied the queries
*without*
their failure contract — one systematic error, found in three separate
files. The
pinned frontier reader had lost its path twin's
`sqlite3.Error → RawRetentionSafetyError` conversion; two more instances
in
`archive_readiness.py`.

**`classify_gaps` default inverted** against the documented
bounded-status
contract — **40× measured**, and during a rebuild nearly every raw is
unmaterialized, so this is a rebuild-time status regression rather than
an edge
case. Fixed at the definition rather than the caller, respecting another
worker's
scope on `daemon_status.py`.

**Two durable doc anchors** pointing into the 1,685 deleted lines of
`status.py`.

Each fix has its anti-vacuity condition proven.

## Filed (15 beads; 4 linked as blocking `polylogue-reindex-2026.1`)

**Rebuild-blocking:**
- `polylogue-163ku` — one unparseable file refuses an **entire source
generation**
on the reacquisition route. The `FAILED` branch is unreachable because
the
  callable *raises*.
- `polylogue-g827i` — embeddings status reports a **complete vector set
as
`none`** and prescribes a paid Voyage backfill when sqlite-vec cannot
load.
That corrupts the go/no-go decision on whether `embeddings.db` survived,
which
  the campaign explicitly relies on (vectors are expensive to rebuild).
- `polylogue-2kbrl` — a failed `accept_ingest` **permanently wedges the
audit
tier**, which is append-only and irreplaceable; recovery replays the
same
  payload.
- `polylogue-gwns3` — `settled_read` leaks a non-`Pending` error through
all six
  handlers, breaking exactly the bootstrap ordering a rebuild performs.

**Other P0/P1:** `go581` — a semantic query can **DROP every stored
vector** on
dimension mismatch (pre-existing, #915, *not* this commit — but
destructive and
provably untested) · `ji49p` pre-dispatch refusals reported as
indeterminate
mutations · `b9egs` principal granted all 22 capabilities, writing false
authority
into `audit.db` · `pw5jd` reads raise instead of degrading · `bwu75` one
bad ZIP
member aborts the whole input · `nd2tb` 543 lines of dead ingest code.
Plus
`hfyig`, `6cdzy`, `g8uvu`, `lyqzg`, `ms4uy`.

## Established clean — so it is not re-audited

113 removed symbols: every surviving reference is a *moved* definition,
not a
stranded caller. The `authorization_token` → `authorization_refs` rename
is fully
swept. No route or operation verb was dropped.

**The enumeration/sealing path** — chased hardest as the rebuild risk —
is
coherent: coordinate/member parity holds, empty inputs seal correctly,
the gate is
opt-in per generation. Also clean: `source_generation_receipts.py`,
`audit_leaf.py`, `raw_failure_lifecycle`, `blob_publication`, live
`metrics`/`cursor`, and the watcher's session-profile callback (opt-in
and
bounded — the *opposite* of the known always-on defect).

One assigned lead was **disproved**: the `raw_convergence` attachment
hazard was
real in the squash, but the scanner has since been deleted.

## Verification

```
devtools verify --quick   exit 0, 15 gates, no "out of sync"
```

Focused runs all PASSED across `test_archive_readiness`,
`test_raw_retention`,
`test_session_partition_convergence`,

`test_session_profile_{derivation,cost_columns,model_usage_consistency}`,
`test_session_insight_refresh`, `test_uds_socket_scoping`,
`test_uds_diagnostic_capture`, `test_derived_schema_identity`,
`test_verify_schema_manifest`.

Honest residuals: `gate atlas` shows 123 BLOCKs, **all pre-existing** —
none of
these files appear. `polylogue-2kbrl`'s deterministic trigger could not
be
constructed from source; the design gap stands regardless.

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

https://claude.ai/code/session_01DYUNBGoE652b3nfmq3CtqK

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

## Summary by CodeRabbit

- **Bug Fixes**
- Daemon restarts now recover from stale socket files without disrupting
active connections.
- Readiness and retention checks return safe, readable status when
underlying storage is damaged, unavailable, or incomplete.
- Active socket conflicts continue to surface instead of being
overwritten.

- **Documentation**
- Updated archive readiness, socket behavior, and schema documentation
to reflect current system behavior.

- **Reliability**
- Improved validation of session-related data inputs and projections for
more consistent derived results.

<!-- 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 14, 2026
## Summary

`settled_read` is on every operation read, and the one audit-continuity
error shape it can raise on a not-yet-seeded archive was the one no
degradation handler caught. Widen the handlers and give the wider state
its own named gap.

## Problem

`AuditContinuityCoordinator.is_available`
(`polylogue/storage/sqlite/audit_continuity.py:305`, `:307`, `:314`)
raises the base `AuditContinuityError`, not the
`AuditContinuityPendingError` subclass, for an archive whose source or
audit tier carries a continuity-era schema version without the matching
`audit_continuity_control` / `audit_continuity_head` table. All seven
degradation handlers (`operations/operation_context.py:141` and
`daemon/operation_runtime.py:252`, `:274`, `:376`, `:573`, `:687`)
caught only the subclass.

Concrete input: a bootstrapped archive (`bootstrap_archive_root`, source
`user_version` 44) whose `audit_continuity_control` table is absent.

Wrong observable outcome: `observe_control_authority(root)` raises

```
AuditContinuityError: current source schema is missing audit continuity control
```

out of a read that is documented never to repair or wait. Before the
squash in #4867 operation reads did not consult audit continuity at all,
so this is an always-on dependency whose bootstrap shape is unhandled.

## Solution

- Catch `AuditContinuityError` at all seven sites;
`AuditContinuityPendingError` is a subclass, so the pending behaviour is
unchanged.
- `observe_control_authority` now names the wider state
`audit_continuity_unavailable` rather than reusing
`audit_continuity_pending`, so a degraded read still carries an explicit
gap instead of collapsing to an empty scope.
- No write path is widened: an audit *mutation* still raises. Nothing is
discarded, and no audit state is lost.

## Verification

```
devtools test tests/unit/operations/test_operation_snapshot.py
devtools test: PASSED exit=0 diagnosis=pytest_passed
devtools verify --quick   # exit=0, no gate FAILED
```

Anti-vacuity, verified by reverting the handler in
`observe_control_authority` to `AuditContinuityPendingError` and
re-running:

```
devtools test: FAILED exit=1 diagnosis=pytest_failed
AuditContinuityError: current source schema is missing audit continuity control
  polylogue/operations/operation_context.py:139 in observe_control_authority
  polylogue/storage/sqlite/audit_continuity.py:306 AuditContinuityError
```

`devtools schema closure`: `polylogue/operations/operation_context.py`
out, `polylogue/daemon/operation_runtime.py` out,
**`polylogue/operations/audit.py` IN** — the one-line re-export there
moves the derived schema identity, so this must land before a fresh
rebuild starts, never during one. No durable DDL changes; no migration.

## Closure

Closes the defect in polylogue-gwns3.

## Residuals

- The regression test covers the `operations/operation_context.py`
handler through the real route. The five `daemon/operation_runtime.py`
handlers are the same one-word widening but are not independently
covered here; standing up a `DaemonOperationRuntime` for each was out of
proportion to the change.
- This does not change `is_available`'s classification of those states.
If any of the three is genuinely a fault rather than a bootstrap
condition, it still deserves a louder signal than a degraded read — that
judgement is left open.

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

https://claude.ai/code/session_01DYUNBGoE652b3nfmq3CtqK

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

Four `test_plain_cli_snapshots.py` failures. Two were stale snapshots
from additive changes that were never re-recorded. One was a **product
defect** in `daemon_status.py` — a never-derived profile domain reported
as `stale`, which flipped global `ok` to false on a pristine archive —
fixed here, which is what lets its snapshot be re-recorded honestly. The
fourth is a genuine read-path parity defect, filed and left red.

## Evidence

Full-corpus `verify_all` on frozen `master` (`890a2921e`), job 1570,
receipt `.cache/verify/runs/20260914T200510Z-all-4027943-f8bc83ff`,
22,524 selected, **147 failures with zero schema skew**. Four of them in
this file.

## Per-failure classification

| Failure | Classification |
| --- | --- |
| `test_json_analyze_snapshot` | **Stale snapshot** (#5146) —
re-recorded |
| `test_json_read_all_snapshot` | **Stale snapshot** (#5152) —
re-recorded |
| `test_json_status_snapshot` | **Product defect** (#5027) — product
fixed; snapshot then re-recorded |
| `test_facets_command_json_matches_analyze_facets` | **Product defect**
(#4867) — **not fixed**, filed as `polylogue-mtxl2`, left red |

### `test_json_analyze_snapshot` — stale, purely additive

Two fields on `ArchiveStats.to_dict()` / `query_stats`:
`embedding_coverage_measurable: true`,
`embedding_coverage_unmeasurable_reason: null`. Added by **e991cfa5e /
#5146** ("Read an unloadable vec0 extension as unmeasurable, not zero"),
confirmed with `git log -S` on `archive/stats.py` and
`cli/query_stats.py`.

Values verified correct rather than merely current:
`embedding_coverage_measurable` is defined as
`embedding_coverage_unmeasurable_reason is None`, and the seeded
archive's embeddings tier *is* inspectable — so `embedded_sessions: 0`
is a measured zero, not an unknown. That is consistent with the
pre-existing `embedding_coverage_percent: 0.0`, since an unmeasurable
tier renders `null` there. Nothing removed, nothing changed.

### `test_json_read_all_snapshot` — stale, purely additive

`outcome: {state: "ok", reason: null, detail: {}}` and `source:
"direct"`. Added by **8d981b806 / #5152** ("Serve every root query
through one declared read operation"), which deleted the local
`ArchiveStore` branch of `_execute_archive_query_stdout` and routed root
queries through `operations/daemon_reads.py`.

Values verified: the envelope reports `total: 2`, and
`decide_outcome(matched=2)` is `ok` — not `empty`, not `degraded` — per
the `surfaces/outcome.py` contract. `source: "direct"` is correct
because the test environment has no daemon, matching `ops status`'s own
`source` on the same archive.

### `test_json_status_snapshot` — product defect, fixed

This one was **not** merely stale: `polylogue ops status --format json`
*exited 1* on the seeded archive, so no re-record could have made it
green. Root cause:

`_session_profile_component` (`operations/daemon_status.py`) collapsed
every not-ready shape into `STALE`. On the seeded archive 0 of 2
profiles had ever been materialized — nothing was computed, so nothing
could have gone out of date. That is `MISSING`, not `STALE`.

The distinction is load-bearing: `_status_ok` tolerates a
never-converged derived family through the `required_missing` allowlist,
but treats `stale` as unconditionally not-ok. So on one archive,
`embeddings` (`missing`) and `transforms` (`unknown`) were correctly
tolerated as never-converged while `session_profiles` — equally
never-converged — flipped global `ok` to false. Introduced by
**14e1d821f / #5027** ("Rewrite convergence around a domain-owned
derivation kernel"), which is when this test went red.

`component_from_derived_model`, in the same file, already draws exactly
this line (`source_rows == 0 and materialized_rows == 0` → `MISSING`;
stale rows → `STALE`). The profile domain was the outlier; it now
follows the same rule.

The fix is not a green-washing of the signal. The re-recorded snapshot
still reports the domain honestly and the claim guard still refuses to
certify:

```
"session_profiles": { "state": "missing", "summary": "session profiles not derived",
                      "missing_profiles": 2, "repair_hint": "polylogued run" }
"converged": { "value": false, "determinate": true,
               "reason": "session profiles not derived",
               "signal": "derived_domain_readiness.session_profiles" }
```

`ok: true` (the archive is usable) and `converged: false` (a derived
family has not run) are different claims, and both are now reported
correctly. Note the stored snapshot already expected `"ok": true` — the
product fix restores what the test always asserted.

The snapshot was *also* independently stale by several PRs, which the
re-record picks up. That diff is strictly an improvement: it replaces
zeros with the seeded archive's real measurements (`raw_artifact_count`
0→2, `materialized_raw_artifact_count` 0→2, `archive_session_count` 0→2,
`message_indexed_count` 12) and adds the `search`, `session_profiles`
and `session_summary` components that did not exist when it was
recorded. Removed fields (`raw_records`, `unidentified_artifacts`) and
the constant `next_action` / `config_path: null` are the deliberate
shape of the pinned-archive route, which states in its own
`diagnostic.reason` that it excludes CLI first-run diagnostics.

### `test_facets_command_json_matches_analyze_facets` — product defect,
left red

Not a snapshot — a real parity assertion between `polylogue facets` and
`analyze --facets`, and genuinely broken.
`operations/daemon_reads.py::_facets_payload` *reimplements* the facets
envelope while its docstring claims it reuses the API's canonical
`facets()` (`api/archive.py:6053`); it reuses only
`_archive_facet_buckets`. Measured divergence on the seeded archive:

| field | `facets` (operation route) | `analyze --facets` (API) |
|---|---|---|
| `family_status` | `{}` | full per-family descriptors |
| `availability` | `null` | `{projection, state: ready, deadline_s,
elapsed_s, …}` |
| `deadline_s` / `elapsed_s` | `null` / `null` | `2.0` / measured |
| `complete_families` | `["origins","tags"]` |
`["total_counts","origins","tags"]` |
| `deferred_families` | spurious `"omitted"` | no `"omitted"` |

The direct `facets` command loses the family-state reporting its own
docstring promises ("reports their state explicitly instead of rendering
empty buckets as authoritative facts") — it renders exactly the empty
buckets that docstring disclaims. Red since **1d901ec73 / #4867**.

**Deliberately not fixed here.** `facets()` is `async`, owns its own
archive acquisition, and computes `availability` / `deadline_s` /
`elapsed_s` under a deadline from
`analysis.projection_contracts.facets_availability`. Delegating properly
means running it over a caller-pinned `ArchiveStore` without changing
its cancellation and deadline semantics — a read-path design decision
that owes CLI/API/MCP parity, pagination and cancellation evidence per
CLAUDE.md, not a patch at the tail of a test-failure sweep. Filed as
**`polylogue-mtxl2`** (P1) with the measured table and the introducing
commit. The test stays red and the bead names the wanted outcome; its
existing parity assertion is its own anti-vacuity condition.

## Verification

```
devtools test tests/unit/cli/test_plain_cli_snapshots.py -k test_json_status_snapshot --snapshot-update
devtools test: PASSED exit=0 diagnosis=pytest_passed receipt=.cache/verify/runs/20260914T224544Z-focused-test-97274-741f4d02/run.json
```

```
devtools test tests/unit/cli/test_plain_cli_snapshots.py
devtools test: FAILED exit=1 receipt=.cache/verify/runs/20260914T231034Z-focused-test-152736-9534a424/run.json
  23 of 24 pass. The single remaining failure is test_facets_command_json_matches_analyze_facets,
  the filed defect above (polylogue-mtxl2), left deliberately red.
```

`devtools gate format` / `devtools gate lint` — clean.

## Schema closure

```
out  polylogue/operations/daemon_status.py
out  tests/unit/cli/__snapshots__/test_plain_cli_snapshots.ambr
```

Neither is in the derived-schema identity closure; this PR does not gate
the archive rebuild.

## Residuals

- `test_facets_command_json_matches_analyze_facets` remains red, tracked
by `polylogue-mtxl2`.
- `_status_ok` still treats `stale` as unconditionally not-ok while
gating `missing` and `unknown` through allowlists. This PR fixes the one
domain that was mis-stating its state; it does not revisit whether that
asymmetry is right in general.
- The `session_profiles` state now depends on `profile_row_count == 0
and total_sessions > 0`. A *partially* derived set (some profiles
present, some missing) is still `STALE`, which is the intended reading.

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

https://claude.ai/code/session_01DYUNBGoE652b3nfmq3CtqK


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

## Summary by CodeRabbit

- **Bug Fixes**
- Session profile status now clearly reports when profiles have not yet
been derived, rather than labeling them as incomplete.

- **CLI Improvements**
- Updated JSON analysis output with clearer embedding coverage details
and reasons when coverage cannot be measured.
  - Enhanced read-all results with outcome and source information.
- Refined status output with additional readiness indicators, clearer
configuration and claim status details, and more transparent
unavailable-data reasons.

<!-- 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 15, 2026
`analyze --facets` and `polylogue facets` returned different documents for the
same question. The first routed to the canonical builder in `api/archive.py`;
the second routed to `_facets_payload` in `operations/daemon_reads.py`, whose
docstring claimed to reuse that implementation but reused only the bucket
scan and restated the assembly around it.

The restatement had drifted. It emitted no `family_status`, `availability`,
`deadline_s`, `elapsed_s` or `stale_age_s`; hard-coded `budget_exceeded=False`
and `cost_class="cheap"` rather than reading the projection contract; carried
its own family lists, with `omitted` in both complete and deferred and
`total_counts` missing; and had no `PostFilterScopeTooLargeError` handling, so
a scope too large to post-filter raised instead of degrading -- against the
rule that a named gap must not read as an empty scope.

#4867 caused it by deleting the API fallback from `facets_command`, so the
daemon-less path stopped answering from the shared builder.

Adding the five missing keys by hand would restart the same drift, so the
assembly is extracted into `build_facets_response` and both callers build the
same model. The daemon read dumps it. The two surfaces are now equal by
construction rather than by keeping two key lists in agreement.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01DYUNBGoE652b3nfmq3CtqK
Sinity added a commit that referenced this pull request Sep 15, 2026
## Summary

`analyze --facets` and `polylogue facets` returned different documents
for the same question. This is a real product defect, not a test drift,
and the parity test was correctly reporting it.

## Evidence

Receipt `.cache/verify/runs/20260914T233651Z-all-207009-89ddea6b`
(`verify_all`, job 1699, 22,540 selected, 29 failed).

**Caveat on that receipt:** its `run.json` records `git_head:
f7964ac` — the tip of branch
`rebase-5165`, *not* `master` and not an ancestor of it — and
`final_git_head: 724d175`. The shared checkout advanced across 7
merged PRs during the run, so it is not evidence of a frozen tree. I
re-ran all 29 node ids at true `master` HEAD: 17 reproduce, 12 do not.
This one is among the 17.

Observed diff: `{'family_status': {}}` against a populated per-family
state map, and `{'deadline_s': None}` against `{'deadline_s': 2.0}`.

## Per-failure classification

| Failure | Classification | Cause |
| --- | --- | --- |
|
`test_plain_cli_snapshots::test_facets_command_json_matches_analyze_facets`
| **product defect** | `operations/daemon_reads._facets_payload` is a
drifted hand-copy of the canonical envelope assembly in `api/archive.py`
|

## Problem

Two implementations answered the same envelope:

- `analyze --facets` → `query_verbs.py` → `env.polylogue.facets(...)` →
the canonical builder in `api/archive.py`.
- `polylogue facets` → `commands/facets.py` →
`configured_read_operation(config, "facets", …)` →
`daemon_reads._facets_payload`.

`_facets_payload`'s docstring claimed *"Reuse the API's canonical
aggregate implementation over this reader"*, but it reused only
`_archive_facet_buckets` — the bucket scan — and restated the assembly
around it. That restatement had drifted:

- never emitted `family_status`, `availability`, `deadline_s`,
`elapsed_s`, `stale_age_s`;
- hard-coded `budget_exceeded=False` and `cost_class="cheap"` instead of
reading the projection contract, so a facets run over budget reported
itself cheap and within budget;
- carried its own divergent family lists — `omitted` in **both**
complete and deferred, `total_counts` missing entirely — versus
`_FACET_CORE_FAMILIES` / `_FACET_DEFERRED_FAMILIES`;
- had no `PostFilterScopeTooLargeError` handling, so a scope too large
to post-filter **raised** instead of degrading. That one is the
sharpest: it is directly against the rule that a named gap must never
read as an empty scope, and it made the two surfaces disagree about
whether the question was answerable at all.

**Breaking PR: #4867 (`1d901ec73`)**, which deleted the API fallback
from `facets_command`, so the daemon-less path stopped answering from
the shared builder and started answering from `_facets_payload`.

## Solution

Adding the five missing keys by hand would reproduce the same drift on
the next change to either side, so the assembly is extracted once:

- `api/archive.py` gains `build_facets_response(...)` — availability,
family lists, `family_status`, gap classification, buckets, IDF, outcome
— and `Polylogue.facets` delegates to it.
- `daemon_reads._facets_payload` builds the same model (including the
`PostFilterScopeTooLargeError` → degraded path it previously lacked) and
dumps it with `model_dump(by_alias=True, mode="json")`.

The two surfaces are now equal **by construction** rather than by
keeping two key lists in agreement.

## Anti-vacuity

The existing parity test is the condition, and it is a strong one: drop
any field from the shared builder, or reintroduce a second assembly on
either side, and `test_facets_command_json_matches_analyze_facets` goes
red on the exact key. It compares complete documents, so it cannot be
satisfied by patching individual keys.

## Verification

```
devtools test tests/unit/cli/test_plain_cli_snapshots.py tests/unit/archive/test_facets.py \
  tests/unit/operations/test_daemon_reads.py tests/unit/cli/test_daemon_golden_parity.py
devtools test: PASSED exit=0 diagnosis=pytest_passed receipt=.cache/verify/runs/20260915T015123Z-focused-test-334855-17879b1d/run.json
```

Because this changes a product read path, I ran the wider
facets/daemon-read surface as well:

```
devtools test tests/unit/archive/test_facets.py tests/unit/api/test_facade_contracts.py \
  tests/unit/operations/test_daemon_reads.py tests/unit/operations/test_daemon_protocol.py \
  tests/unit/cli/test_daemon_golden_parity.py tests/unit/daemon/test_daemon_http_contracts.py \
  tests/unit/insights/test_projection_contracts.py tests/unit/cli/test_query_verbs_runtime.py \
  tests/unit/daemon/test_web_reader.py
devtools test: PASSED exit=0 diagnosis=pytest_passed receipt=.cache/verify/runs/20260915T014520Z-focused-test-329027-25d72753/run.json
```

```
devtools verify --quick
17/17 gates ok (format, lint, mypy, generated-surfaces, layering, patterns, doc-commands,
schema-manifest, oracle-integrity, testmon-selection, consumer-reachability, test-packages,
timestamp-doctrine, durable-enum-checks, schema-privacy, atlas, population-coverage)
```

## Schema closure

```
devtools schema closure polylogue/api/archive.py
out  polylogue/api/archive.py
devtools schema closure polylogue/operations/daemon_reads.py
out  polylogue/operations/daemon_reads.py
```

**Both OUT of the derived schema-identity closure.** Does not need to
land before an archive rebuild.

## Residuals

- This PR also turns `test_json_status_snapshot` green, which was
failing in the original receipt but did **not** reproduce at HEAD — I am
not claiming it as a fix, only noting it now passes.
- `cwd_prefixes` and `time_range` are set by neither surface. That was
true before this change and is unchanged; the shared builder makes it
visible in one place rather than two.

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

https://claude.ai/code/session_01DYUNBGoE652b3nfmq3CtqK

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

Sinity commented Sep 28, 2026

Copy link
Copy Markdown
Owner Author

Codex review threads on this PR whose cited code is gone (checked against master at 23f91a5):

Resolving these threads.

@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 64a9bd0):

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

@Sinity

Sinity commented Sep 29, 2026

Copy link
Copy Markdown
Owner Author

Fix record for Codex review threads on this PR (checked at master 5d56c3a):

These threads were already resolved by the triage post that assigned them to polylogue-9kemf; this comment records the fix.

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