Skip to content

fix(intake): one interpretation across live and retained routes - #5643

Merged
Sinity merged 28 commits into
masterfrom
claude/prep-intake
Sep 29, 2026
Merged

Sinity merged 28 commits into
masterfrom
claude/prep-intake

Conversation

@Sinity

@Sinity Sinity commented Sep 27, 2026 •

Copy link
Copy Markdown
Owner

Summary

Intake preparation batch: live and retained routes now publish the same interpretation of the same bytes, pending live paths prewarm their existing retained members off the writer, Gemini CLI sidecar joins and ChatGPT text-node attachment/event evidence move to sealed scratch, and one-shot teardown no longer stops the parse stage under an admitted writer.

Problem

  • The live route sealed sessions without provider assembly. A synthetic one-file Codex input produced title = native id and a different content_hash on the live and owned-cold routes than on retained replay (which titles it from the first authored prompt). The raw owner then reported the live output as valid, so it never converged. A fresh build through the live route would have kept native-id titles and dropped curated Claude Code index titles.
  • Enriching append chunks exposed a latent defect: a tail append merged the newest chunk's own title over the chain's title winner. A full replace would have stored the winner.
  • The writer reparsed existing retained members inline under its lease. A multi-raw accepted chain with a path carrier was deferred to the raw owner without that carrier, so the prepared write was discarded.
  • A cancelled one-shot ingest called parse_stage.shutdown() before waiting for the coordinator, so an admitted writer could lose its preparation.
  • Gemini CLI checkpoints with an available tool-output scope still fell back to whole-document parsing. ChatGPT text nodes kept their attachment and event evidence in memory.

Solution

  • RetainedSessionEnricher (in revision_backfill) applies retained archive evidence one session at a time. Live path workers open read-only source/index frames and enrich each admitted session. The writer's inline fallback, the legacy retained reparse and append chain replay use the same enrichment.
  • apply_raw_revision_replay copies the aggregate's title triple onto a tail merge. The site is declared in the derived-sweep census.
  • Install-global retained sidecars (Claude Code/Codex history and session indexes) are parsed once per content hash, using a small bounded memo. Per-file enrichment therefore does not reparse history for every transcript.
  • Retained prewarm seals carriers for existing JSON/JSONL members. It uses the raw owner's predicate, and each carrier is bound to its raw descriptor. A per-member prewarm miss falls back to the writer and does not defer the live path. A chain is composed in the writer when every older member has a current carrier.
  • The one-shot teardown waits for the coordinator to go idle before shutting down the stage.
  • Cherry-picked verified slices: Gemini CLI sidecar joins in SQLite scratch, and ChatGPT text-node attachment/event spill. A route characterization test now asserts that session rows are equal across live, retained and cold routes.

Supersession check (against master 2714453)

Compared by behavior, not by file. Master does not contain this PR's core: no retained enrichment on the live/writer routes (RetainedSessionEnricher, session_enrichment_bindings), no chain title carry on tail merges, no retained prewarm (retained_prefetch.py), no typed value-bound refusal (value_bounds.py), no ChatGPT scratch spill for attachments/events/timings, and the one-shot teardown still stops the stage first. Master covers adjacent parts: #5762 streams Gemini CLI sidecar joins through scratch (this PR keeps only the completeness check against the advertised excerpt length and the read race check), and #5776 streams the Claude AI, AI Studio and Hermes object shapes that were a residual here. The merge resolves the overlap on master's side.

Self-review

  • Sibling sites per defect class. Enrichment binding runs at three writer sites (ingest batch, retained precedence write, chain replay). All three now return early for providers without late-arriving evidence. Before, two sites ran the source/index queries first. Retained-member publication goes through PreparedLiveRetainedRaw.current at both consumer sites in batch.py.
  • Cancellation and shutdown in loops. Retained prewarm ran every member serially without checking the warm's cancellation. It now checks before each member and during verification, and discards what it sealed. The one-shot teardown ran settle, shutdown and close in sequence. A raising settle wait skipped shutdown and leaked the worker pool. The three steps are now nested finally blocks.
  • Unbounded reads. A Gemini sidecar read went to EOF on a file that could still be growing. It now stops one byte past the enumerated size. Scratch string-set iteration used fetchall; it now uses a cursor. The sibling append-chain walk rescanned every append per step, which is quadratic on long live chains. It now uses a predecessor index.
  • Fail-open fallbacks. Writer enrichment read getattr(archive, "index_connection", None), so an archive without the attribute silently enriched with no evidence. It now reads the attributes directly. A prewarm miss (OSError, ValueError, retryable read) falls back to the writer's own replay, which is the owner, not a skip.
  • Compatibility shims. None added. The pre-existing descriptor_reader is None branch in batch.py (a master-era test-double path) is untouched and listed below.
  • Tests prove the production route. New tests drive parse_sources_archive with a failing settle wait, prepare_live_retained_raws over a real ingested archive with a stop callback, and RawMaterializationDiscovery against a real source table. Each names its anti-vacuity condition.
  • Duplicated queue state. A re-arrived sessions-index.json queued a second scan of the same project. The queue now holds one scan per project, restarted from the first transcript.

Verification

  • agentctl job start polylogue verify_quick (job 1927) → 12/12 gates passed, including gate schema-closure and gate mypy.
  • agentctl job start polylogue pytest_focused -- <15 touched test files> (job 1928) → devtools test: PASSED exit=0, 672 selected, 672 passed. test_live_append_takes_the_latest_rename hit the 120 s pytest timeout under pool load (three full ingests) and passed alone on the harness rerun in 18.7 s.

Derived identity

Every changed production file except operations/canonical_archive_ingest.py is in the derived-identity closure. retained_prefetch.py and value_bounds.py join the closure baseline, and index.db gains session_enrichment_bindings. This moves the derived schema identity, so it must land before the fresh rebuild starts.

Residuals

  • Retained prewarm over-approximates members (membership, retired siblings, head, replay plan) and prepares them serially while one read snapshot is pinned. That moves bounded work off the writer; it is not a measured throughput gain.
  • In a cold build, the worker reads evidence from the active index. Codex state-title projection written only to the candidate index is not visible to the worker. Parsed-content fallbacks still apply.
  • The in-memory ChatGPT route (no scratch spill) keeps master's 512 sandbox-attachment bound per message, reported as a counted degradation. The prepared route records every link.
  • batch.py's descriptor_reader is None branch predates this PR. It now reaches _parse_retained_raw_sessions, which needs the descriptor, so it only serves test doubles that patch that method. Removing it is a separate cleanup.
  • test_live_append_takes_the_latest_rename runs three full ingests and can exceed the 120 s pytest timeout on a loaded pool.
  • The whale qualification has not been run.

🤖 Generated with Claude Code

https://claude.ai/code/session_015pdKaZWyGe6Ngvsz468dzg

@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 27, 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-29T01:07:23.112675Z fa016dc New commits
ℹ️ 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.

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

ℹ️ 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/sources/revision_backfill.py Resolved
Sinity added a commit that referenced this pull request Sep 27, 2026
Review of #5643:
- Live path carriers seal an enrichment dependency digest; the writer
  recomputes it against what it has admitted and re-enriches a stale
  carrier (a sidecar admitted in the same pass). Retained prewarm members
  use the raw owner's own index/evidence checks.
- Cold builds enrich against the candidate index.
- Chunk title ties go to the later chunk for provider records, so a later
  rename wins as in the whole-file parse; the tail carry compares the full
  title/source/ref triple.
- Writer-side enrichment resolves an UNKNOWN acquisition provider.
- A broken pool is not replaced once shutdown starts; retained member
  preparation waits at most the warm timeout.

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

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

ℹ️ 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/sources/live/batch.py Resolved
Sinity added a commit that referenced this pull request Sep 27, 2026
…adline

Review of #5643 (Codex, e5ff48f):
- A pass admits enrichment evidence (session indexes, prompt history,
  export asset maps) ahead of session files, so a transcript discovered
  before its sessions-index.json in the same pass is revalidated against
  the admitted index instead of publishing its prewarmed heuristic title.
- Retained-member prewarm spends one deadline across all members and
  stops submitting once it is spent, instead of a fresh wait per member.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_013Vn4qhKjhyaVBG4aPiqNW4
@Sinity
Sinity enabled auto-merge (squash) September 27, 2026 19:19

@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: 952ea547e5

ℹ️ 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/sources/live/batch.py Resolved
Sinity added a commit that referenced this pull request Sep 27, 2026
Review of #5643 (Codex, 952ea54): during a cold build the retained
prewarm sealed members against the active index, so the writer publishing
into the candidate refused them and deferred the path. Members are now
prepared against the publication index, and any carrier the writer cannot
publish falls back to the writer's own retained parse.

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

@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: 88f15a3602

ℹ️ 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/sources/live/batch.py Resolved
Sinity added a commit that referenced this pull request Sep 27, 2026
Review of #5643 (Codex, 88f15a3): a source batch with more than one
progress group split the discovery-ordered list before evidence was moved
first, so the first group published heuristic titles. Evidence is now
ordered across the whole source before grouping. Also types the
fallback regression test for mypy.

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

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

ℹ️ 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/sources/live/batch.py Resolved
Comment thread polylogue/sources/live/batch.py Resolved
Sinity and others added 11 commits September 28, 2026 09:23
A cancelled one-shot ingest shut the parse stage down before waiting for
the admitted writer, so a writer still consuming its prepared carrier
could see its workers terminated and its result discarded. Wait for the
coordinator to go idle first.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_013Vn4qhKjhyaVBG4aPiqNW4
Live intake sealed sessions without provider assembly, so a Codex or
Claude Code session ingested live kept its native id (or heuristic) title
and a different content hash than retained replay of the same bytes, and
the raw owner then accepted the live output as current. A fresh build
through the live route would have lost curated titles.

- Live path workers enrich each admitted session from retained archive
  evidence (RetainedSessionEnricher), as retained replay does; the writer's
  inline fallback, legacy retained reparse and append chain replay use the
  same enrichment.
- A tail append now carries the chain's title winner instead of the newest
  chunk's own title.
- Parsed install-global sidecars (history, session indexes) are memoized
  by content hash so per-file enrichment does not reparse them per file.
- Retained prewarm (polylogue-i07pw): pending live paths seal carriers for
  existing JSON/JSONL members off the writer, bound to their raw
  descriptor; a multi-raw accepted chain whose members are all prepared is
  composed by the writer instead of deferred without its path carrier.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_013Vn4qhKjhyaVBG4aPiqNW4
Review of #5643:
- Live path carriers seal an enrichment dependency digest; the writer
  recomputes it against what it has admitted and re-enriches a stale
  carrier (a sidecar admitted in the same pass). Retained prewarm members
  use the raw owner's own index/evidence checks.
- Cold builds enrich against the candidate index.
- Chunk title ties go to the later chunk for provider records, so a later
  rename wins as in the whole-file parse; the tail carry compares the full
  title/source/ref triple.
- Writer-side enrichment resolves an UNKNOWN acquisition provider.
- A broken pool is not replaced once shutdown starts; retained member
  preparation waits at most the warm timeout.

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

Review of #5643 (Codex, e5ff48f):
- A pass admits enrichment evidence (session indexes, prompt history,
  export asset maps) ahead of session files, so a transcript discovered
  before its sessions-index.json in the same pass is revalidated against
  the admitted index instead of publishing its prewarmed heuristic title.
- Retained-member prewarm spends one deadline across all members and
  stops submitting once it is spent, instead of a fresh wait per member.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_013Vn4qhKjhyaVBG4aPiqNW4
Review of #5643 (Codex, 952ea54): during a cold build the retained
prewarm sealed members against the active index, so the writer publishing
into the candidate refused them and deferred the path. Members are now
prepared against the publication index, and any carrier the writer cannot
publish falls back to the writer's own retained parse.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_013Vn4qhKjhyaVBG4aPiqNW4
Review of #5643 (Codex, 88f15a3): a source batch with more than one
progress group split the discovery-ordered list before evidence was moved
first, so the first group published heuristic titles. Evidence is now
ordered across the whole source before grouping. Also types the
fallback regression test for mypy.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_013Vn4qhKjhyaVBG4aPiqNW4
Sessions were enriched against whatever index, prompt history or thread
state the archive held when they were written, and nothing revisited them
when that evidence was admitted afterwards, so ingest order decided the
stored title and content hash. Each enrichment now stamps the key of the
exact evidence it read; the writer binds the session to it only while that
is still the archive's evidence; raw-observation inspection re-derives any
output whose binding no longer matches, on the retained route. A project's
new session index queues its transcripts for prompt inspection; the sweep
covers install-wide evidence.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_013Vn4qhKjhyaVBG4aPiqNW4
Master removed PreparedJsonl.load_sessions; the spill test now takes the
first session from the streaming accessor.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01P8nGdByCWAzpk78ko2xza6
Sinity added a commit that referenced this pull request Sep 28, 2026
Review of #5643:
- Live path carriers seal an enrichment dependency digest; the writer
  recomputes it against what it has admitted and re-enriches a stale
  carrier (a sidecar admitted in the same pass). Retained prewarm members
  use the raw owner's own index/evidence checks.
- Cold builds enrich against the candidate index.
- Chunk title ties go to the later chunk for provider records, so a later
  rename wins as in the whole-file parse; the tail carry compares the full
  title/source/ref triple.
- Writer-side enrichment resolves an UNKNOWN acquisition provider.
- A broken pool is not replaced once shutdown starts; retained member
  preparation waits at most the warm timeout.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_013Vn4qhKjhyaVBG4aPiqNW4
Sinity added a commit that referenced this pull request Sep 28, 2026
…adline

Review of #5643 (Codex, e5ff48f):
- A pass admits enrichment evidence (session indexes, prompt history,
  export asset maps) ahead of session files, so a transcript discovered
  before its sessions-index.json in the same pass is revalidated against
  the admitted index instead of publishing its prewarmed heuristic title.
- Retained-member prewarm spends one deadline across all members and
  stops submitting once it is spent, instead of a fresh wait per member.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_013Vn4qhKjhyaVBG4aPiqNW4
Sinity added a commit that referenced this pull request Sep 28, 2026
Review of #5643 (Codex, 952ea54): during a cold build the retained
prewarm sealed members against the active index, so the writer publishing
into the candidate refused them and deferred the path. Members are now
prepared against the publication index, and any carrier the writer cannot
publish falls back to the writer's own retained parse.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_013Vn4qhKjhyaVBG4aPiqNW4
Sinity added a commit that referenced this pull request Sep 28, 2026
Review of #5643 (Codex, 88f15a3): a source batch with more than one
progress group split the discovery-ordered list before evidence was moved
first, so the first group published heuristic titles. Evidence is now
ordered across the whole source before grouping. Also types the
fallback regression test for mypy.

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

The patterns gate trusts an exemption that any parent of `HEAD` already
carried, so a PR whose tip merges `master` no longer fails for
`master`'s own baseline additions.

## Problem

`_trusted_baseline` read the committed baseline from `HEAD^` only. On a
PR whose head is a merge of `master`, `HEAD^` is the PR's previous tip,
so every exemption `master` added since the PR last merged it counts as
growth. The quick-gate of #5739 (a one-line hook change merged with
`master` at f2562c3) failed with `patterns: committed baseline grew`
over dozens of `master`'s own entries (`diagnosis=gate_input_error`);
#5643, #5696 and #5704 fail the same way.

## Solution

Read the baseline at every parent (`git rev-parse HEAD^@`) and trust
each entry at the largest count any parent carried. A merge resolution
that adds an entry present in neither parent is still growth.

## Verification

`devtools test tests/unit/devtools/test_verify_patterns.py` on a
checkout of origin/master 82e84ec with this change: 9 passed, 1
failed. The new
`test_merging_the_base_branch_does_not_count_its_exemptions_as_growth`
passes; it fails with first-parent-only trust. The failing
`test_displacing_a_baselined_match_does_not_trip_the_gate` fails the
same way on unpatched master (IndentationError in its synthetic file)
and is recorded in polylogue-rb7tx.

🤖 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]>
Sinity and others added 2 commits September 29, 2026 01:00
# Conflicts:
#	polylogue/sources/live/gemini_tool_output_sidecars.py
#	polylogue/sources/live/parse_prefetch.py
#	polylogue/sources/prepared_jsonl.py
#	polylogue/sources/prepared_message_sink.py
#	tests/unit/sources/test_prepared_jsonl.py

@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: 8a5dda0363

ℹ️ 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/sources/retained_assembly.py Resolved

@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: 0f160ecfcf

ℹ️ 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/sources/revision_backfill.py Resolved
Comment thread polylogue/sources/decoder_json.py Resolved
Sinity and others added 2 commits September 29, 2026 02:00
…gradation ratchet

Fills of the parsed retained cache are serialized, with cross-origin eviction
under the fill lock. A sidecar append step must follow its baseline in receipt
order. Prefetched JSONL blobs get the filesystem sidecar resolver, batch
observability opens the index without schema validation, the retained
prefetch no longer degrades on sqlite3.Error, and the JSON container decoder
no longer refuses an oversized field the record never uses.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_015pdKaZWyGe6Ngvsz468dzg
Master's #5691 rewrote live preparation (no wall-clock deadlines, read-ahead
prefetch, decode-once). Worker-side retained enrichment is threaded through
both required and read-ahead submissions, retained members are collected in
the new existing-session reconciliation, and the retained prewarm waits for
its members like every other preparation instead of spending a deadline.

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

Removes the CircleCI `stacked-review-threads` job,
`devtools/stacked_review_threads.py`, and its tests. The
`stacked-review-threads` commit status is now posted by a Sinnix user
timer (`stacked-review-threads-status`, Sinity/sinnix 49d11e9b), next to
the existing `codex-review` status pass.

## Problem

The job, added in #5740, failed on every PR with "no GitHub token". The
CircleCI project has no `GH_TOKEN`, and nobody can administer that
project from this login. The job also re-ran only on push, so resolving
a thread left the result stale until the next commit.

## Solution

The Sinnix pass authenticates with gh's persistent login and runs every
two minutes over every open PR targeting master. It keeps the semantics
of the deleted module. Every PR merged into the head branch counts. The
walk recurses into each stacked PR's head branch, bounded by that PR's
merge time. Expansion is keyed per PR, so each lifetime of a reused
branch name gets its own bound. The walk is cycle-safe and follows
pagination on merged PRs and threads.

It fails closed: a read error sets `pending`, never `success`. It writes
a status only when the state changes. Reads are aliased per stack level,
so a head with nothing merged into it costs no query of its own. With
two authorities for one gate, one would be dead weight, so this PR
deletes the CircleCI copy.

## Verification

- `nix develop --command devtools verify --quick`: `verify: PASSED
exit=0` (all 12 static gates ok).
- `git grep -n "stacked_review_threads\|stacked-review-threads"` on this
branch: no matches.
- Before the deletion, both implementations were run read-only against
every open master PR and gave the same verdict for all 25.
- The live Sinnix pass posted `stacked-review-threads: success` on the
open heads, for example #5643 (`1 stacked PR has no unresolved review
threads`).

## Residuals

- `stacked-review-threads` becomes a required master context after this
merges. Until then it is advisory.
- The gate now depends on the workstation timer running. If the timer
stops, no new head gets the status, so once the context is required
those merges stay blocked. That failure is closed, not open.

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

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

ℹ️ 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/storage/derived/raw.py Resolved
Sinity and others added 3 commits September 29, 2026 03:33
# Conflicts:
#	polylogue/sources/prepared_message_sink.py
…alks

- One-shot teardown stops the parse stage and closes the archive even when
  the coordinator settle wait raises.
- Retained prewarm polls the warm's cancellation before each member and
  during verification, and discards what it sealed when cancelled.
- A re-arrived session index restarts its project's queued scan instead of
  queueing a second one.
- Sibling append chains are walked through a predecessor index, not a
  quadratic rescan; a Gemini sidecar read stops one byte past its
  enumerated size; scratch string sets iterate by cursor.
- Enrichment binding skips its evidence reads for providers without
  late-arriving evidence, and writer enrichment reads the archive's
  connections directly rather than defaulting a missing one to None.

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

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, add credits to your account and enable them for code reviews in your settings.

@Sinity
Sinity merged commit 915a1f3 into master Sep 29, 2026
3 of 4 checks passed
@Sinity
Sinity deleted the claude/prep-intake branch September 29, 2026 02:40
Sinity added a commit that referenced this pull request Sep 29, 2026
## Summary
Fixes the still-real parser findings from bead polylogue-1tyq5.27
(unhandled Codex P1 review threads on merged PRs).

## Problem
- Admission accounting was fail-open: the production Claude Code
multi-session stream, Codex streams and undecorated lowered routes
produced sessions with no outer-record ledger (F695, F779), and a record
without an unknown-type sentinel was counted as materialized even when
the parser skipped it, e.g. a scalar record in a JSONL stream (F780).
- OTel GenAI: every span re-emitted the full input history, duplicating
earlier messages (F075); usage was kept only for `chat` operations
(F077); unnamed resources collapsed onto one id and merged unrelated
sessions (F079); ordinary HTTP/DB traces in a GenAI export became
zero-message sessions (F080).
- Drive: one event carried the whole citation list, so an appended
citation changed that event's identity and revision membership read
ordinary growth as ambiguous (F507).
- Preflight refused a verified Antigravity trajectory schema whose steps
produced no messages, so its typed empty/unsupported evidence could
never be acquired (F350).

## Solution
- `base_support.AdmissionObserver`: one classifier per session's outer
records (materialized / typed unknown / typed refusal for non-object
records). `parser_admission` uses it; the Claude Code stream keeps one
observer per session group; the Codex stream route and
`_parse_lowered_spec` apply it to single-session results that lack a
parser ledger.
- `otel_genai`: history-overlap suppression per conversation transcript,
usage fallback for any operation, resource ids derived from the resource
attribute set when `service.name` is absent, and a filter keeping only
traces that contain a GenAI span.
- `drive`: one `gemini_citation` event per citation with its ordinal.
- `import_preflight`: a verified schema with trajectory rows is
admissible, with caveats for no-message and degraded steps.

Other findings in the group were already fixed on master or belong to
other work: F319 (#4966/#4972), F351 (#5403), F419 (#5550), F505
(#4861), F647 (#4587), F850 (#4236); F029 is routed to the intake
enrichment work (#5643).

## Verification
- `devtools test` over the OTel, Drive contract, preflight, admission,
Codex event-stream and `tests/unit/sources/parsers` selections: 1
failure in a new test (a missing `messages=[]`), fixed; that test passes
alone.
- New tests: history dedup, distinct unnamed resources, non-GenAI trace
exclusion, non-chat usage, grown citation list, verified trajectory
without messages, Claude Code stream admission, scalar-record refusal.

## Residuals
- Hermes multi-session ATIF streams still lack per-session admission;
noted on the bead.
- `base_support.py` overlaps #5682's in-place event handling; a small
rebase conflict is expected.
- Schema closure: the parser files are in the derived identity closure,
so this must land before the fresh build.

## Self-review

I reviewed the whole diff at the final head, not only the last round.
The findings are grouped by the invariant each one protects.

**Admission conservation (every emitted session carries a closed
proof)**
- `admit_parsed_sessions` proves every session that lacks its parser's
own ledger. The document is observed once and the closed proof is shared
(`AdmissionObserver._closed_proof`), so an N-session document costs one
scan.
- Every origin's scanner reads only discriminators:
  - Claude: record `type` and block `type`.
  - Codex: envelope and payload `type`.
  - Hermes: `type`/`kind`/`record_type` and step kinds.
- OTel: span `kind`, registered under the provider token the route
passes (`opentelemetry`).
- The default scan used by the other undecorated routes never descends
into `arguments`/`input`/`output`/`result`/`attributes`, so a tool
argument `{"type": "unknown"}` is data, not a wire type.
- The streamed Hermes ATIF carrier that master added in #5776 now gets
the same proof as the dispatch route over the same bytes. Each step's
`type`/`kind` is observed as the parser consumes it, so no second decode
is needed and a future step kind beyond the classifier's 64-step witness
is still recorded as a typed unknown
(`test_streamed_atif_trajectory_carries_the_dispatch_admission_proof`).
I checked the other #5776 streaming routes. The Claude AI, AI
Studio/Drive chunked and ChatGPT routes reach decorated parsers, and
Grok admits through `grok.parse_conversation`.
- Admission events are appended in place to a disk-backed sink, and any
other non-list sequence is copied into a list first. This keeps master's
#5643 contract through the merge.
- A record the parser skips is a typed refusal, never `MATERIALIZED`:
  - a non-object;
  - a Claude record with no string type (`recognized=False`);
- a known-kind ATOF record that `looks_like_atof_payload` rejects
(`malformed=True`).

**Identity stability (an export revision updates, never duplicates, a
session)**
- OTel resource ids depend only on the resource's own stable attributes.
They exclude instance, version and cardinality, so adding a second
resource keeps the first one's sessions.
- Copies of one span coordinate that disagree on
`gen_ai.conversation.id` choose none (trace-keyed).
- A shared ancestor belongs to the conversation whose descendant started
first, so it cannot move when a sibling conversation is appended.
- Trace membership and parent links work across resources within a
trace. A span keeps its own resource (`resource_id` in its evidence),
and spans with equal ids under different resources stay distinct.
- Antigravity: rowids are never identity. Several trajectories with no
id are refused (`LogicalExportError`), and one anonymous trajectory
keeps the path fallback.

**Complexity**: the history overlap is a KMP pass, linear in both
lengths.

**Checked and left as is**: Drive chunk/citation handling after the
master merge (a conflict was resolved by combining master's
`event_rows`/`chunk_records()` with this PR's `_citation_events`), and
the Claude event ordering (`order_session_events`).

**Verification** (final head 85329da):
- `devtools test tests/unit/sources/parsers/test_otel_genai.py
tests/unit/sources/test_admission_payload.py
tests/unit/sources/parsers/test_antigravity.py
tests/unit/sources/test_prepared_hermes_atif_object.py
tests/unit/sources/test_prepared_claude_ai_object.py
tests/unit/sources/test_prepared_drive_chunked_object.py
tests/unit/sources/parsers/test_hermes_spans.py
tests/unit/sources/test_parsers_base.py
tests/unit/sources/test_parser_admission_packet.py
tests/unit/sources/test_prepared_jsonl.py
tests/unit/sources/test_first_future_type_duplicate_keys.py`: 352
passed, 0 failed.
- `agentctl job start polylogue verify_quick`: succeeded (job 2117).

**Residuals**:
- polylogue-hlghl: ParseAccounting compresses unknown outcomes
(pre-existing).
- A Hermes duplicate event key is still counted as materialized: its
evidence is carried by the first copy.

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

https://claude.ai/code/session_013Vn4qhKjhyaVBG4aPiqNW4

---------

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

## Summary

Recovers the tail of an append whose process was killed mid-write, and
turns four kinds of stuck or silent ingest/daemon failure into terminal,
visible outcomes. Beads: polylogue-b8of0, polylogue-7c5k6,
polylogue-wyi9p, polylogue-oulj2, polylogue-hu24g, polylogue-xf8qp,
polylogue-zt8is, plus two status residuals of polylogue-qw8zp /
polylogue-10a3q.

## Problem

- **Append kill loses the tail (b8of0).** Kill the process inside an
append's index write, then restart. The first page defers the path and
schedules a 60 s retry. The next page reads that not-yet-due retry as
already admitted and acknowledges it as `DUPLICATE`. Later passes defer
forever, because the writer refuses a prepared field union ("no longer
applies") that its own precedence decision no longer needs. The index
stays at 3 of 6 messages.
- **Worker death or hang never escalates (7c5k6).** Every
`BrokenProcessPool` was deferred, and a deferral resets `failure_count`,
so a file that kills its worker is retried every pass for the whole
build. A hung worker is stopped only at shutdown and holds its slot
until then.
- **Deterministic intake failures retry forever (wyi9p).** Every escaped
exception became `RETRYABLE`, and the attempt counter restarted after
each cooldown. A `sqlite3.Error` escaping page admission bypassed
`daemon.intake.page_refused`.
- **Embedding cap fails open (oulj2).** An unreadable spend probe
returned `0.0`, which granted the whole monthly budget.
- **Six swallowed failures (hu24g):** the Drive config read, both
heartbeat alert probes, the debt-retry pass, the Gemini typed-extraction
fallback, the Codex thread-state currency check, and the browser-capture
census.
- **Zero-session files are reported admitted (xf8qp)**, so the
operator's admitted count includes files that produced nothing.
- **The delegation snapshot refuses more than 100k rows or 64 MiB
(zt8is).** Those caps reject valid input.
- **Status during a first build:** the discovery overlay replaced the
build's mode and ETA with `discovery_pending` / `None` while discovery
paged. A root with no active generation had no status frame, so the
snapshot read "unavailable" for the entire first build.

## Solution

- `watcher.classify_ingest_candidates` splits a page into paths that are
needed now and paths that are waiting on a scheduled retry; it is the
only selection route (`select_ingest_candidates` is removed).
`FileIntakeAdapter` reports a pending path as `DEFERRED`, never
`DUPLICATE`. The writer drops a prepared union its precedence does not
need and writes the parsed rows it already holds.
- `LiveParseStage` (rebuilt on #5691's read-ahead model) charges each
worker loss to the one file whose task a worker held.
`_run_holding_attempt` marks the parent-assigned attempt directory when
a worker takes a task and when it lets go, so the tasks held at a pool
break are exactly those started and not finished. One held task is
charged. Several are deferred uncharged and become solo suspects, which
run on an otherwise idle pool (and are never read ahead) until a worker
comes back from them, so each later loss names one file. Losses are
counted per observation (size, mtime_ns, inode). The third consecutive
loss on an unchanged observation is a non-deferred failure carrying
`failed_observation`, and `pop_path` applies it only to a capture of
that same revision; the cursor's failure budget then quarantines the
file.
- Hangs: #5691 bounds only read-ahead (lifetime and preemption) and
leaves required work waiting forever, so this PR keeps one hang
mechanism, for required work only, and measures it the way #5691
measures progress. A process worker whose attempt directory has not
grown for 600 s plus its source size at 256 KiB/s is stopped through
`_stop_process_workers`, the same restart-and-settle path that reaps
read-ahead. Only that path is charged; interrupted required siblings
lose their restart deferral and the waiting warm resubmits them. Slow
work that keeps writing is never stopped. The earlier submission-time
deadline reaper, its `_path_started` clock and the plural
`failed_attempts` restart argument are gone.
- `AdmissionResult.transient` records whether a failure can clear on its
own. Locks, OS errors and storage faults are transient and retry without
bound. An unchanged item that repeats the same non-transient failure is
isolated after `max_deterministic_cooldowns` (3). The page handler also
catches `sqlite3.Error` and emits `page_refused`.
- The spend probe returns `None` when unreadable, and the pass then
refuses with `spend_unmeasured`.
- Each of the six hu24g sites now emits an event, returns the failure to
its owner (the debt retry re-raises into the loop's `last_error`), or
narrows its handler (Gemini now catches only `ValidationError`).
- Zero-session paths are carried through the batch result and the
metrics, and are reported `EXCLUDED`.
- Delegation evidence is read in 1,000-row keyset pages, whose key
coalesces only NULL exactly as the SQL order does. Both caps are gone,
and the snapshot digests every row.
- The overlay keeps build keys once a planned denominator exists.
`_status_frame` returns `no-active-generation` for a missing active
index.
- Retargets a stale monkeypatch in the ZIP streaming test, which named a
detector `batch.py` has not imported since #5557.

**Schema identity:** `devtools schema closure` marks
`sources/live/{batch,batch_support,metrics,parse_prefetch,watcher}.py`,
`sources/dispatch.py`, `sources/codex_state_evidence.py` and
`storage/sqlite/archive_tiers/write.py` IN, and the new
`idx_delegation_facts_query_order` changes index DDL. This PR moves the
derived identity (`parse_prefetch.py` included), so it must land before
the fresh rebuild starts.

## Verification

On head `dbccb4817b`, through AgentCTL jobs (never in-process):
- `agentctl job start polylogue verify_quick` (job `c1c21522`): `verify:
PASSED exit=0 ... head=dbccb4817b15`
- `agentctl job start polylogue pytest_focused -- <15 files: derivation
kernel laws, parse-stage equivalence, live watcher, daemon cli,
derivation admission, parse prefetch, watcher locking, prefetch cache,
dispatcher intake measurement, fair intake, delegation materializer,
page selection, batch convergence, excluded-cursor proof, canonical
ingest>` (job `f43837d3`): `580 passed, 3 failed`. Four daemon-cli tests
failed in the batch and passed on isolated rerun (host load; one of
them, the cold-build transient settlement test, also passed alone on the
previous head as `2 passed in 47.56s`).
- The 3 failures reproduce identically on master `0156f3b97a` (clean
detached worktree, `pytest_focused -- --on-default-branch`: `3 failed`),
so they are inherited, not caused here:
`test_live_batch_convergence::test_page_admission_runs_lease_free_owners_outside_the_writer_gate`,
`test_live_watcher_locking::test_watcher_queues_behind_daemon_maintenance_writer`,
`test_dispatcher_intake_measurement::test_dispatcher_page_compaction_cost_is_one_scoped_hold_at_archive_scale`.

New behavior tests, each naming what would make it fail:
- append kill: 3 restart pages all `DEFERRED` (pre-fix: `DUPLICATE`),
then 6/6/1 messages and no parse errors; a scheduled retry is `DEFERRED`
with zero cost at the adapter and `pending` in watcher classification
- a killer file escalates on its third loss on real process pools; a
pool break charges only the task still held; two held tasks charge
neither and run alone until attributed; a restart-preserved success or a
worker error ends the streak; rewritten content starts a new streak and
an escalated failure does not apply to it
- a hung required preparation is stopped at its hang bound and charged
alone while the sibling is prepared in the same warm; a slow preparation
that keeps writing is never stopped
- deterministic isolation with a draining sibling; a lock never
isolates; an `IntegrityError` page emits `page_refused`
- unmeasured spend refuses the pass; one test per hu24g site; a
zero-session file is `EXCLUDED`
- a population larger than a page materializes completely; an
empty-string block id keys the keyset as `COALESCE` does
- the overlay keeps the build ETA; the status frame names a root without
a generation

## Self-review

A full read of the PR diff against master after the merges. Each item
says how it applied.

- **Cancellation and shutdown in every loop.** `_warm_until` checks
`cancelled` on every poll, and the hang reaper runs inside that loop. It
never waits itself: it stats attempt directories and restarts the pool.
After `_closing`, pool-death attribution returns the shutdown deferral
and does not restart the pool. After an unverified stop
(`_cleanup_blocked`), it charges nothing. That second case fixes a
finding: a later collection of the same break would otherwise have
charged a sibling a second time.
- **Unbounded reads and state.** The hang signal is one `scandir` per
running required path per poll. `_path_worker_losses` and
`_path_solo_suspects` grow only with distinct files that lost a worker.
They are cleared when a worker comes back from a file, and they are not
pruned for files that are never seen again (see Residuals).
- **Fail-open fallbacks.** A loss with no submission observation is
deferred, not charged: it cannot be bound to a revision. An escalated
failure applies only while the file's (size, mtime_ns, inode) is
unchanged.
- **Sibling sites of each defect class.** The per-path bookkeeping
(future, observation, progress, attempt directory, in-flight bytes) is
released in one helper, `_release_slot`. Collection, pool restart and
thread-orphan reaping all use it. That removed the parallel
`_path_sizes` and `_path_started` dicts, each of which every release
site had to remember. A streak ends at every site where a worker comes
back from a file: a collected success, a collected exception, and a
success the restart preserved. Two sibling defects were found and fixed.
`DelegationPageKey.after_row` used `or`, so an empty-string block id
keyed on the child session id, a position the SQL `COALESCE` order never
has; it now coalesces NULL only, with a test. `pop_path`'s
changed-source branches were checked against #5643's
`_discard_retained_path`. A failed result never carries retained
members, so the new `failed_observation` branch needs no discard.
- **Master's new FAILED site.** Master added a FAILED outcome at the
post-publication requiredness recheck (`requiredness inspection:
{exc}`). Like this branch's other exception-backed FAILED sites, it now
names the exception type and carries `transient`, with a test.
- **Compatibility shims.** One was found and removed. The adapter kept
`select_ingest_candidates` as a fallback beside the new
`classify_ingest_candidates`, and `LiveWatcher.select_ingest_candidates`
had become a wrapper. Classification is now the only selection route.
Fakes, `docs/daemon.md` and the excluded-cursor proof receipt name it.
- **Tests prove the production route.** The worker-loss tests run real
process pools through `warm_paths`/`pop_path`. The worker helper is
wrapped by the production `_run_holding_attempt`, so the markers are the
production ones rather than test-written. The hang test runs a warm on a
thread with a join bound, so a missing reaper fails instead of hanging.
A slow worker whose attempt directory keeps growing proves the bound
measures lack of progress, not time since submission. The
scheduled-retry split had no test; it now has a watcher test (pending
vs. settled exclusion) and an adapter test (`DEFERRED`, `actual_cost` 0,
never `DUPLICATE`).

## Residuals

- `_path_worker_losses` and `_path_solo_suspects` are cleared when a
worker comes back from a file, but they are not pruned for a file that
never returns. They are bounded by the distinct files that lost a worker
during one daemon's life.
- A worker lost under a retained-member preparation (#5643 runs those on
the same pool during reconciliation) restarts the pool without
attribution, so such a loss is never charged. It errs toward
under-charging, never toward a false charge.

- 7c5k6 "visible in status": escalation reaches the cursor quarantine
through the writer's generic parse-failure path (`batch.py` per-record
`except Exception` → `mark_raw_parse_failed`). I confirmed this by
reading the source; no end-to-end quarantine test drives a killer file
through five cursor failures.
- The hu24g optional ratchet (a devtools pattern rule for broad excepts)
is not included.

🤖 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]>
Sinity added a commit that referenced this pull request Sep 29, 2026
## Summary

Four intake tests failed on master at 1beb2e5. Each encoded a route
or contract that an earlier PR had changed. None is a production bug, so
this PR changes tests only. One sibling guard that could never fire is
tightened too.

## Problem (evidence)

I reproduced the failures in one focused job over the four files
(agentctl job 2555) and diagnosed them with probe tests that were not
committed (including jobs 2635 and 2660). All four failures are
deterministic, not load-related.

- `test_page_admission_runs_lease_free_owners_outside_the_writer_gate`:
`admit_page` returned `RETRYABLE` with `CursorAuthorityBlockedError: ...
global raw existence is unproven: required source or index tier is
unavailable`. The fixture created only `index.db`. The cursor-authority
gate added in #5657 fails closed when one tier exists without the other,
which is the intended behavior.
- `test_watcher_queues_behind_daemon_maintenance_writer`: the test
paused `LiveParseStage.warm`. The batch has called only `warm_paths`
since #5550, so the pause never happened and `parser_started.wait(5.0)`
timed out.
-
`test_dispatcher_page_compaction_cost_is_one_scoped_hold_at_archive_scale`:
each page traced 4 SELECTs instead of 3. The fourth is `SELECT identity
FROM schema_identity WHERE tier = 'index'`, which every validated
read-only open has run since #5727. The three authority reads are
unchanged.
-
`test_flag_on_prefetch_and_flag_off_produce_identical_archive_content`:
the snapshots differ in `raw_sessions`, `raw_revision_heads` and
`raw_authority_parser_census`.
  - The prefetch arm writes `full`/`byte_proven` raws with byte heads.
- The production arm (`converge_raw_observations`, which uses the
retained preparation from #5643) writes `unknown`/`quarantined` raws
with semantic heads.
- The prefetch arm drives `DaemonParseStage` and
`backfill(prefetch_cache=...)`. No production module has constructed
`DaemonParseStage` since #5002, and `RawObservationDerivation.compute`
always builds `RawObservationReplacement(payload=None)`. So production
archive content never goes through the route that differs.

## Solution

- Lease-free owners test: bootstrap a whole archive with
`initialize_active_archive_root`, and put the source under its own root.
- Maintenance-queueing test: pause `warm_paths`, the method the batch
calls in `_ingest_full_paths`. Replace the 5 s and 1 s wall-clock waits
with waits on the events themselves: an `asyncio.Event` set with
`call_soon_threadsafe`, plus the maintenance-entered event. A `finally`
releases the parked thread. pytest-timeout bounds a hang.
- Compaction-cost test: separate the per-open identity read. Assert
there is exactly one, which means the page used one connection, then
keep the three-authority-read assertions. Raise the hang guard to 600 s,
the same as its sibling measurement test: in one probe run under host
load (average about 22), the 120 s default fired during seeding.
- Delete the prefetch equivalence test and the helpers only it used.
polylogue-fhlo1 tracks deleting or rewiring the dead `DaemonParseStage`
and `LiveParseStage.warm` routes.
- Sibling:
`test_page_admission_acquires_source_without_reading_unavailable_index`
forbade `warm`, which production never calls. The batch also swallows
prewarm exceptions, so a raising stub would have passed anyway. The test
now records calls to `warm_paths` and asserts there were none.

No production file changes, so the derived-identity closure is
untouched.

## Verification

- `agentctl job start polylogue pytest_focused --workspace
/realm/worktrees/polylogue-mh-intake --wait --
tests/unit/sources/test_live_batch_convergence.py
tests/unit/sources/test_live_watcher_locking.py
tests/unit/daemon/test_dispatcher_intake_measurement.py
tests/unit/daemon/test_raw_materialization_parse_stage_equivalence.py
tests/unit/sources/test_live_watcher.py::test_page_admission_acquires_source_without_reading_unavailable_index`
(job 2688, head d81534d): `devtools test: PASSED exit=0
diagnosis=pytest_passed`, 21/21.
- `agentctl job start polylogue verify_quick --workspace
/realm/worktrees/polylogue-mh-intake --wait` (job 2696, head
d81534d): `verify: PASSED exit=0`.

## Self-review

- **Siblings.** I searched `tests/` for patches of the unused `warm`.
One other guard patched it; it is fixed here. The remaining
`stage.warm(...)` calls in `test_parse_prefetch.py` and
`test_live_watcher_parse_stage_equivalence.py` test the dead classes
directly and belong to polylogue-fhlo1.
- **Fix itself.** The identity filter matches only `from
schema_identity`, and it asserts exactly one match, so an extra
connection per page still fails the test. The authority-read assertions
are unchanged.
- **Anti-vacuity.**
- Maintenance queueing: wrapping the page in `coordinator.run` blocks
maintenance, so `maintenance_entered` never sets and pytest-timeout
fails the test.
  - Lease-free owners: the owner-outside-gate assertions are unchanged.
- Derived-only guard: removing the `_source_tier_acquisition_required()`
gate records a call.
- **Interruption.** The parked parse thread is released on every exit
from the wait block, so a failing run does not leave a thread blocking
executor shutdown.
- **Waits.** The only wall-clock bounds left in the changed tests are
`coordinator.shutdown(timeout=1.0)` after all tasks finish, which was
already there, and the pytest-timeout marks.
- **Public boundary.** Synthetic fixtures only.
- **Docs.** `docs/design/convergence-simplification-inventory.md` still
cites the deleted equivalence test. That design note describes the dead
route as a whole, so it is left to polylogue-fhlo1.

## Residuals

- In one repro job under load, the deleted test's seeding hung for 120 s
in `BlobPublicationReservationStore.reserve_many` at `conn.close()`.
Sibling tests in that file use the same seeding and passed. I did not
reproduce it again.
- `tests/unit/daemon/test_daemon_cli.py` load-sensitivity did not show
up in my runs, so it is not addressed here.

🤖 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]>
Sinity added a commit that referenced this pull request Sep 29, 2026
…5850)

## Summary

Makes master's focused suites green again. The baseline run on master
`633ec18ffc` (job 3431, 30 files) had 41 failures and 1 error, and every
other PR was running into them. They come from 20-odd separate causes.
Where production was wrong, this PR fixes production and uses the
failing test as the regression. Where a merged PR had deliberately
changed the contract, it updates the test to the new contract and cites
that PR. Two failures remain, each with a bead and the evidence below.

Beads: polylogue-ouv5f (all eight tests fixed), polylogue-0e6m3,
polylogue-h9da0 and polylogue-wple (audited and noted; their open
criteria are listed under Residuals).

## Problem

Job 3431 (`pytest_focused --on-default-branch`, 30 files, 1539 tests)
reported `passed 1497, failed 41, error 1`. Its failed-test rerun also
crashed: the rerun passed `…::test_x@web-reader[param-…]` back to
pytest, and pytest answered `ERROR: not found`.

## Solution: production defects fixed

| Failure | Cause | Fix |
|---|---|---|
| `test_raw_observation_derivation` ×4,
`test_retained_tool_output_convergence` (Gemini) | For providers with no
assembly spec, `enrichment_dependency_digest` skipped the evidence
digest that every retained seal computes. Every prepared artifact of
those providers therefore read as stale, and `publish` returned False
forever, so Hermes, Antigravity, ChatGPT and Gemini retained raws never
converged. | Every provider digests its evidence, empty or not
(`sources/revision_backfill.py`). |
| `test_observation_runtime::test_structured_raw_only_sidecar…` | An
artifact-scoped identity hashed to the same `{"source": path}` value
that `_old_path_fallback` refuses, so new sidecar evidence never reached
the cache. | The artifact-scoped identity gets its own namespace
(`schemas/source_inference.py`). |
| `test_verification_evidence_lane` |
`reconcile_and_record_abandoned_verify_runs` compared `cache.parent`
(that is, `.cache`) to the checkout, so the test was never true. The
checkout's reconciled runs went to cache-local history, and cache-local
evidence too (#5720), instead of the durable lane. | Compare the
checkout root, `runs_root.parents[2]`. The checkout uses the XDG history
and `verification_evidence_path()`; a relocated cache keeps local files.
|
| `test_web_reader::test_archive_filter_kwargs…` | #5795 gave
`iter_search_summaries` an `actions_only` lane parameter. The count
route still counted every FTS hit for `retrieval_lane="actions"`. |
`count_search_sessions(actions_only=…)` and the count route pass the
lane. New regression:
`test_actions_lane_count_counts_only_sessions_its_search_returns`. |
| `test_command_catalog::test_tool_outcome_help…` | A Click-level
required option refused `--help` before argparse could print it (#5720).
| argparse owns requiredness, and the metavar is `PATH`. |
| idempotence properties (found while fixing the harness) |
`refresh_session_repos*` stamped `repos`, `repo_checkouts` and
`session_repos` with the wall clock, so no rebuild could reproduce them.
| Stamp them with the session's own time, as `_write_repo_edges` does.
New test: `test_refresh_stamps_the_session_time_not_the_wall_clock`. |
| `test_daemon_http_security` | The daemon client that carries the
credential was chained into the receipt call, so the token scan flagged
the receipt. | Bind the client first (`browser_capture/server.py`). No
allowlist entry was added. |
| failed-test rerun | `report_nodeid_to_selector` did not handle
`name@group[param-…]`, the shape that shortened ids take under
loadgroup, and the long-id map stored uncollectible `@group` ids. |
Handle that shape, and record both map sides in selector form
(`devtools/pytest_rerun.py`, `tests/conftest.py`). |
| `test_session_partition_convergence` (fd leak) | The per-thread
connection cache kept every archive a test built until the descriptor
check ran. | The autouse fixture clears the cache at teardown. |
| `test_session_partition_convergence` (`fields_digest`) | #5799's
column was neither projected nor excluded. | Exclude it, with the reason
(`derived/session/input_binding.py`). |

## Solution: tests updated to contracts that merged PRs changed

- `test_import_preflight`: several unidentified trajectories are refused
(#5711); the old test expected ids minted from row position.
- `test_artifact_taxonomy`: a brain sidecar is observed as
`agent_sidecar_meta` schema evidence (#5781), never as a session.
- `test_tool_result_unknown_reason_contract` ×3: a step with no verdict
field is `not_reported` (#5798). A new route covers
`unsupported_construct` with an unmapped status.
- `test_source_laws`: the stand-in parser accounts for its outer records
(#5816).
- `test_revision_replay`: the direct replay binds Codex enrichment
evidence as the retained writer does (#5643).
- `test_retained_tool_output_convergence` (Gemini): the fixture sidecar
is longer than the 40,000 characters the envelope advertises (the #5643
partial-write guard).
- `test_schema_policy_contracts`: FTS triggers are matched by whole
table name (`messages_fts_readiness_binding` is not FTS-backing); the
restart test clears the bootstrap memo as a restart does (#5428).
Deleted `test_every_prior_index_schema_version…`: at fresh v1,
`SCHEMA_VERSION - 1` is 0, which is the "interrupted create" state that
is re-created by design. No prior version exists.
- `test_durable_migrations`: an archive two slots behind gets the typed
refusal from #5806, and the tier is untouched. The docstring of
`apply_declared_durable_migrations` is corrected. Filed as
polylogue-7yq3f.
- `test_schema_validation`: the member schema names `id` (#4856 reports
unnamed fields), and the keys are plain names, so the marker is what
suppresses them.
- `test_synthetic_wire_support::test_chatgpt_witness…`: the part text
also survives on the tool block, so the test drops it there too.
- `test_archive_ingest_shared_raw`: a ZIP member with a malformed record
is `terminal_corrupt_input` (#5823 F039); a census runs once per raw.
- `test_plain_cli_snapshots`: empty is exit 2 and degraded is exit 1
(`surfaces/outcome.py`).
- `test_cross_surface_agreement`, `test_query_composition_laws`: the CLI
reads through a real daemon (#5805). The naive-join mutant lifts the
read authorizer (#5642) the way `attach_readonly_database` does.
- `test_resource_pilot` ×2: parser scratch SQLite (`:memory:` and temp
files) is allowed; any database file or tier is not.
- `test_codex_debt_w1` and the convergence properties: the harness bound
each session's own evidence to message 0 and stamped replayed messages
with the child's values. Since #5826 shares only an identical prefix, no
lineage prefix was shared at all, and the append-prefix laws were
vacuous. A fork now replays its parent's parsed prefix exactly, and its
own evidence moves to the first message it authored. The mutation test's
`_resolve_session_graph` mutant returns `set()` to match the current
signature.
- `test_query_exec_laws` ×4: stub the convergence probe in fake-store
stats tests (#5700), add the `tool_input` projection field, and expect a
second window sized to the remaining limit.
- devtools: `test_verify` stubs the executor,
`test_pytest_suite_cost_plugin` builds the recorder before patching RSS,
`test_verification_terminal_receipts` updates the sizing stub signature,
and `test_verification_result` adds the #5720 `flaky` field.
`test_http_bounded_mutations` adds the #5723 summary read to its test
double.

Derived-identity closure (`devtools schema closure`): these files are
IN: `archive/query/archive_execution.py`, `schemas/source_inference.py`,
`sources/revision_backfill.py`,
`storage/derived/session/input_binding.py`,
`storage/derived/session/repo_observations.py`,
`storage/sqlite/archive_tiers/archive.py`. The rest are out.

## Verification

- Baseline, master `633ec18ffc`, job 3431: `passed 1497, failed 41,
error 1`.
- `agentctl job start --workspace
/realm/worktrees/polylogue-master-green polylogue pytest_focused -- <61
files>`, job 3578, head `a7f4465c56`: `passed 2336, failed 2` after the
in-slot rerun. The first attempt ran under host I/O contention, with
workers in D state. 25 of its 27 first-attempt failures were `Timeout
(>120.0s)`, and every one of those passed when rerun alone.
- `test_web_reader::…searches_from_archive_tiers`: a socket timeout
under the same load. It passed alone in job 3861 (`devtools test: PASSED
exit=0`).
-
`test_supported_routes_validate_selected_schema_and_parser_entry_point`:
inherited, see Residuals.
- Master baseline for the added files, job 3562: `test_query_exec_laws`
×4, idempotence ×7 and mutations ×2 fail on master the same way. All of
them are fixed here.
- Harness consumers and count seams at head `1d3b3545c5`, job 3920 (24
files): `passed 589, failed 1` after the in-slot rerun. The one failure,
`test_inferred_corpus_loop::test_every_supported_inferred_element_reaches_convergence_and_red_twin`,
was a `Timeout (>120.0s)` inside `load_package_catalog` under the same
host load. It passed alone in job 3973 (`devtools test: PASSED exit=0`).
- `verify_quick` on head `1d3b3545c5`, job 3921: `verify: PASSED
exit=0`. The hosted `ci/circleci: quick-gate` passes.
- `verify_quick` on head `a7f4465c56`, job 3579: `verify: PASSED
exit=0`.

## Self-review

I did two passes over the full diff against `master`, using
`docs/review/codex-review-guide.md` and the generic worker-contract
list. Pass 1 found two defects, both fixed in `1d3b3545c5` and
`3ec0a5fa2f`. Pass 2 was clean.

1. ✓ **Siblings and owners.** The actions-lane count was also wrong in
two more places: the facade/daemon seam
`_archive_count_sessions_for_spec` and the daemon `count` mode
(`operations/daemon_reads.py`). Pass 1 found them with `grep -rn
count_search_sessions polylogue` (7 call sites); both are fixed and have
a regression test. The MCP route already reports `total=None` for
actions (`mcp/archive_support.py` `ranked_only`), and `sessions.search`
is lexical only. The enrichment digest has a single owner
(`enrichment_dependency_digest`) used by both the live and the retained
check. Every seal computes the evidence digest unconditionally, the live
enricher included. A search of `polylogue/storage/derived` for
wall-clock stamps found two others: the marker cursor `applied_at_ms`
(operational metadata) and `profiles.now_iso` (materialized-at). Neither
is a semantic column.
2. ✓ **The fix itself.** Pass 1 found that `_replayed_parent_prefix`
would recurse forever on a declared parent/child cycle
(`cycle_candidate=True`). It now tracks the lineage it walks, and picks
the parent revision the way `authoritative_sessions` does.
`count_search_sessions(actions_only=False)` defaults to today's
behaviour for every other caller.
3. ✓ **Memory and limits.** Nothing new grows with the input. The repo
stamp is one indexed `SELECT` per refreshed session. No caps or timeouts
were added.
4. ✓ **Cost per unit.** One predicate on the count query and one
primary-key read per repo refresh. `with_retained_assembly_evidence`
returns at once for providers without assembly evidence
(`sources/retained_assembly.py:470-479`).
5. N/A **Interruption.** No loops, waits or multi-step state changes
were added.
6. ✓ **Ordering and races.** The repo stamp is read inside the
materializer's own transaction, on the same connection that writes the
rows.
7. ✓ **Failure classification.** The reconciler's history and evidence
appends keep their existing `suppress(OSError, ValueError)`.
`verification_evidence_path()` now expands `~`, as the old inline
override did.
8. ✓ **Silent outcomes.** Actions-lane totals now count what the lane
can return. Exit codes follow outcomes (`surfaces/outcome.py`), and the
updated CLI tests assert exit 2 for empty and 1 for degraded.
9. N/A **Cleanup on failure.** Nothing new is acquired.
10. ✓ **Identity and keys.** Artifact-scoped source identity now lives
in its own `{"artifact": …}` namespace, so it can no longer collide with
the retired `{"source": path}` identity. Old cache rows under the path
identity are still refused by `_old_path_fallback`.
11. ✓ **Lossless transforms.** The rerun selector keeps the `[param-…]`
label, and the long-id map now stores both sides in collectible form.
The harness deep-copies the parent messages it replays.
12. ✓ **Degenerate inputs.** A missing session row stamps 0, the
writer's own default. A child with no own messages keeps position-0
evidence. A shared prefix of 0 replays nothing.
13. ✓ **Consumers.** `count_search_sessions` gained an optional keyword;
every test double takes `**kwargs`, and none asserts the exact kwargs
(checked at `test_query_exec_laws.py:1301,1385,2099` and
`tests/infra/archive_store_double.py:255`). The unused `now_iso`
parameters were removed, and `grep` finds no callers passing them.
14. ✓ **Tests and stubs.** Each production fix has a test that goes red
without it. The count tests go 2 → 3 without `actions_only`. The repo
test goes red if the rows are stamped with the wall clock. The
evidence-lane pair covers the checkout and the relocated cache.
`test_rerun_selector_strips_the_xdist_group_suffix` covers the new id
shape. The source-inference test goes red without the separate
namespace. Stubs follow the current signatures: the
`resolve_worker_argument` stub takes `**sizing`, the
`_resolve_session_graph` mutant returns `set()`, and the test double
implements `get_session_summaries`.
15. ✓ **Trust boundaries.** The capture handler binds the
credential-holding client apart from the receipt, and no token-scan
allowlist entry was added. The fixtures are synthetic.

Generic list: (1) criteria are met on production routes (probes and job
3578). The unmet ones name their blockers (4xyn9, 7yq3f, h9da0, 0e6m3,
wple). (2) Siblings: see item 1. (3) No predecessor is kept beside a
replacement. (4) No silent fallback was added. (5) Each new test names
the change that turns it red. (6) The diff, receipts and text carry no
secrets or private data; the paths are worktree scratch paths only.


## Residuals

- polylogue-4xyn9:
`test_supported_routes_validate_selected_schema_and_parser_entry_point`
still fails. The claude-ai v2 coverage witnesses combine mutually
exclusive groups, so 529 of 844 keywords are missing. It fails the same
way on every commit back to #5485 at least. Honoring the exclusions in
coverage mode alone still leaves 319 missing, so this needs a coverage
planner.
- polylogue-7yq3f: catch-up across more than one numbered slot is
refused, and a backup is taken before the refusal. Nothing breaks until
the second migration of a tier ships.
- polylogue-3p8p7 (owned elsewhere): a loose malformed workflow journal
still reads as `workflow_journal` through the lenient retained decode;
the ZIP route is strict.
- polylogue-h9da0: quick-pool xdist width is sized from the slice's
current headroom, not from a per-job share. Two jobs that start together
can both admit a full width. Left open.
- polylogue-0e6m3: the per-cache retention measurements need a scheduled
broad run. Left open.
- polylogue-wple: master already enforces the foreign-interpreter and
foreign-import checks. Detecting copied testmon or verify state is still
open.

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

https://claude.ai/code/session_015pdKaZWyGe6Ngvsz468dzg
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