Skip to content

perf(sources): overlap parsing, decode once, never abandon preparation - #5691

Merged
Sinity merged 28 commits into
masterfrom
claude/perf-sources
Sep 28, 2026
Merged

Sinity merged 28 commits into
masterfrom
claude/perf-sources

Conversation

@Sinity

@Sinity Sinity commented Sep 27, 2026 •

Copy link
Copy Markdown
Owner

Summary

This PR also fixes polylogue-slc55: preparation is never abandoned at a wall-clock deadline, and cold-build cursor corroboration reads the candidate index.

Live intake now prepares the next files while the writer publishes the current group. It also caps the default process parse pool and decodes each sealed prepared session once instead of once per pass.

polylogue-slc55: never abandon progressing preparation

A 419 MB Codex file never finished a cold build. Its preparation outlived the 60 s warm deadline, so the writer deferred the file and re-acquired it on the next pass, eight times. When one pass finally succeeded, cursor corroboration checked the still-empty active index rather than the candidate generation being built, demoted the new cursor and re-ingested the file. The run wrote 117 GiB and never promoted.

  • warm_paths, the in-memory warm, CensusParseStage.warm and retained raw preparation no longer have deadlines. They wait for their workers.
  • Forward progress (attempt-directory growth, or completions) decides only when a stall is reported: live.parse_prefetch.preparation_stalled, daemon.parse_prefetch.preparation_stalled and storage.raw_observation.preparation_stalled. A report never defers, terminates or discards work.
  • Cursor corroboration resolves _published_index_path, which is the candidate generation during a cold build.
  • Tests that asserted the retired deadline behaviour are rewritten to the new contract or removed where the pending state they covered no longer exists. Deferral on worker failure keeps its tests.

Problem (evidence)

Numbers come from devtools bench fresh-build (#5678). Each run cold-builds a sealed 144-file (276 MiB) private sample of Claude Code, Codex and Gemini sources through polylogued run --cold-build-index on a shared host (load 18-35). Only aggregate numbers are quoted. Wall times move with host load; writer holds, stage timers and CPU seconds move less.

On master plus #5674, intake ran at 0.45 MiB/s with a mean of 0.34 cores. A stack profile of the daemon (the benchmark's in-process sampler, because py-spy cannot attach to 3.14t) showed three causes:

  • At most 2 parse paths ran in parallel. _max_path_pending was 1 per worker slot, and nothing was submitted until the writer asked for a path.
  • The unconfigured process pool took every core (23 workers here). Peak RSS for the daemon tree reached 3.7 GB.
  • The writer re-validated each sealed session's messages with pydantic on every pass over it, about 20 passes per session. This was 45% of writer CPU.

Solution

  • LiveParseStage.prefetch_paths starts preparing the next page's cursorless paths while the current page publishes. Read-ahead has a bounded lifecycle:
    • The parent only stats a path and reads its cursor. Candidate sampling and preparation run in the stage's executor (live_lookahead_path_worker), so a stalled source read never blocks a parent thread.
    • Read-ahead is charged to the slot and byte budget from submission until it ends. It never takes the last worker.
    • A warm whose required path does not fit preempts running unclaimed read-ahead. After a short grace the read-ahead is reaped: the process pool is terminated and restarted, and the warm resubmits its own collateral work. Unclaimed read-ahead that outlives eight stage calls is reaped the same way.
    • Finished read-ahead releases its charge at once and pays its full artifact digest only when a warm claims it.
  • Publication order is enforced in one place, reconciliation. A warm reconciles its paths in intake order, admits one path per canonical session, and returns later same-session paths as held. The batch publishes held paths in the next progress group, after a fresh warm. A reconciliation is valid only for the warm that made it.
  • The path-pending bound is one per worker. The default process pool is capped at 8 unless configured (_DEFAULT_PROCESS_WORKER_CAP).
  • SqliteMessageSink keeps a bounded LRU of decoded sessions (64 MiB; a session larger than half the budget is not retained). The key is the sealed file's path, ordinal, and dev/ino/mtime/ctime/size, so a changed file never serves a stale decode. PreparedJsonl.discard drops the entries.

Verification

  • devtools test tests/unit/sources/test_prepared_jsonl.py tests/unit/sources/test_live_watcher_parse_stage_equivalence.py tests/unit/daemon/test_fair_resumable_intake.py: 223 passed. The run includes new tests for decode-once, discard or oversize re-decode, a sealed-digest-bound cache key, prefetch without waiting, and the pool cap.

  • Benchmark: with the 23-worker pool, intake reached 1.44 MiB/s at 3.7 GB RSS. With the cap it runs at 1.9 GB RSS. The combined branch (this PR plus the drains, ops and digest PRs) promoted in 114.6 s (intake alone took 623 s before), reached terminal and qualified, and its per-origin intake projection for the sampled population fell from 37.8 h to 6.2 h.

  • Lookahead rework: devtools test over the parse-stage equivalence, live watcher, fair intake, parse prefetch, cursor locking, schema preflight, watcher locking, batch support and read-amplification files: 530 passed, 4 failed. Two of the four failures (test_watcher_queues_behind_daemon_maintenance_writer, test_live_full_ingest_offloads_sync_work_to_keep_loop_responsive) also fail on origin/master cf6d12d. The third, test_source_only_full_ingest_streams_admitted_zip_members_without_decoding, patches a batch._detect_provider_from_raw_bytes attribute that does not exist on master. The fourth, test_path_stage_shutdown_terminates_stalled_process, hit its 5 s spawn wait under load and passes when run alone. Each of the three new P1 regression tests (wedge, reap of a worker stuck on a FIFO read, same-session order) fails when its fix is disabled. devtools verify --quick: PASSED.

Residuals

  • These files are in the derived schema-identity closure (devtools schema closure: batch.py, parse_prefetch.py, watcher.py, prepared_jsonl.py and prepared_message_sink.py are IN). The change must land before the fresh build starts.
  • The individual contribution of prefetch versus the decode cache is not separated. Both runs share the other changes.

🤖 Generated with Claude Code

https://claude.ai/code/session_013Vn4qhKjhyaVBG4aPiqNW4

@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-28T23:40:18.533297Z f7f6d0d 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: 7ee6a90a4f

ℹ️ 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/operations/intake_adapters.py Resolved
Comment thread polylogue/operations/intake_adapters.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: 2f9cf2ad74

ℹ️ 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".

@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: 9822f566a6

ℹ️ 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".

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

ℹ️ 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/operations/intake_adapters.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: 39d3cbf7d7

ℹ️ 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".

@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: 9d17a3c425

ℹ️ 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/operations/intake_adapters.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: 0076f437b9

ℹ️ 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/watcher.py Resolved
Comment thread polylogue/storage/derived/raw.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: 274000dcb6

ℹ️ About Codex in GitHub

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

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

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

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

@Sinity
Sinity force-pushed the claude/perf-sources branch from 274000d to d2a6cc4 Compare September 28, 2026 03:40
@Sinity Sinity changed the title perf(sources): overlap parsing with publication and decode sessions once perf(sources): overlap parsing, decode once, never abandon preparation Sep 28, 2026

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

ℹ️ 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

@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: 9b27e9d7a8

ℹ️ About Codex in GitHub

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

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

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

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

Sinity and others added 11 commits September 28, 2026 09:28
Review findings on parse prefetch and the decoded-session cache:
- a prefetched path no warm claims within four warms is discarded with
  its scratch (selection may skip it, e.g. a cursor restored from the
  archive), instead of being held until shutdown;
- a speculative stat or submission failure is not recorded, and a
  claimed speculative retryable failure is prepared again, so the warm
  never inherits a transient prefetch failure;
- existing-session reconciliation covers only the paths being warmed, so
  a later group's prefetched result is reconciled after the earlier
  groups publish;
- the decoded-session budget counts stored UTF-8 bytes, not code points.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_013Vn4qhKjhyaVBG4aPiqNW4
A walk whose files are all skipped after cursor reconciliation prefetches
without ever warming, so aging speculation only on warms let its results
and scratch accumulate. Count prefetches as well and drop stale guesses
at the end of each prefetch.

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

A warm now awaits the speculative preparations it claims before deciding
what to submit, so a retryable failure that finishes during the warm is
re-prepared rather than returned. Expired speculative futures still run
to completion but no longer count against the pending or byte budget of
required submissions.

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

- read-ahead never takes the last parse worker, so required work always
  has an executor slot even behind expired speculation;
- raw-observation replay evicts cached decodes of its scratch carriers
  before removing the scratch tree;
- the multiplex adapter no longer prefetches every group before admitting
  the first; each file adapter still reads ahead within its own page, so
  a slow source cannot hold back a healthy one.

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

- a warm submits and waits for its own candidates first, then re-prepares
  any claimed read-ahead that ended in a retryable failure, so a slow
  claimed file no longer spends the deadline before others are submitted;
- read-ahead needs a spare worker: a one-worker stage reads nothing ahead;
- the paths a submission actually creates are returned, so a resubmitted
  read-ahead is marked speculative and ages out.

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

A large file's preparation outlived the 60 s warm deadline, so the writer
deferred it, re-acquired it on the next pass and deferred it again; the
in-memory and census warms likewise abandoned slow workers for an inline
reparse, and retained raw preparation terminated its pool at 600 s and
retried from scratch. None of these deadlines measured a failure: they
discarded progress.

- LiveParseStage.warm_paths waits for every selected preparation through
  limited capacity; the attempt directory's growth is the forward-progress
  signal, and a window without progress only emits
  live.parse_prefetch.preparation_stalled;
- LiveParseStage.warm, CensusParseStage.warm and retained raw preparation
  wait likewise and report stalls instead of abandoning or terminating;
- cursor corroboration during a cold build reads the candidate generation
  the writer publishes into, not the still-empty active index, so a file
  the build just ingested is no longer demoted and re-ingested.

Tests that asserted the retired deadline behaviour are rewritten to the
new contract (awaited, reported) or removed where the pending state they
covered no longer exists; deferral on worker failure keeps its tests.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_013Vn4qhKjhyaVBG4aPiqNW4
Read-ahead calls deliberately never collect finished futures, and
`_drop_stale_speculation` skipped every path still in `_path_futures`. A
prefetched path that finished and was then skipped by cursor
reconciliation therefore kept its sealed attempt scratch and its
speculative slot until an unrelated warm or shutdown. Expiry now collects
a finished expired future, and an expired collection discards the result
without the full byte verification.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01P8nGdByCWAzpk78ko2xza6
@Sinity
Sinity force-pushed the claude/perf-sources branch from 9b27e9d to cab5a47 Compare September 28, 2026 07:29

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

ℹ️ 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/operations/intake_adapters.py Resolved
…windows

Fresh discovery stopped walking once a page was pending, so the intake
prefetch never saw a path beyond the batch it was about to warm. The
walk now keeps one further page pending and refills it behind a
carried-over page.

A cancelled full ingest released the ingest lock while its unbounded
warm thread still ran. The warm now takes a cancellation event: the
caller shields it, sets the event on cancellation and awaits the thread,
and a cancelled warm stops at its next poll without recording results or
installing prepared writes from its snapshot.

The parse-stage warm timeouts are stall-report windows, not bounds. The
settings are renamed to `*_stall_report_seconds` (TOML, environment and
config inventory) with descriptions that say so; the old keys are
refused like any undeclared key.

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

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

ℹ️ 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/operations/intake_adapters.py Resolved
Comment thread polylogue/operations/intake_adapters.py Resolved
The intake prefetch awaited provider sampling of the next page before
the current page's ingest, so a slow lookahead file delayed healthy
files already admitted, and it submitted the current page first, filling
the read-ahead slots with work the following warm needed anyway. Intake
now offers only the next page. Selection and sampling run on a worker
thread, and a full ingest submits the sampled candidates between its own
warm and its publication. A lookahead that is not ready by then is not
used, and it is dropped when its batch ends.

A warm cancelled while reconciling closes the prepared writes it built
instead of installing them, so a retry reconciles against a fresh
snapshot.

Discovery tests now expect the queued rescan one discovery sooner,
because the lookahead reaches the end of the walk earlier. The
cancelled-warm test waits on the held worker's start event instead of
reading the clock.

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

@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: 09abedf7fe

ℹ️ 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
Comment thread polylogue/sources/live/watcher.py Resolved
… offers

The retained wait checks cancellation before each wait and before accepting a finished result; reconciliation checks it per session in a carrier; a batch refused by the cursor-authority gate drops its lookahead offer.

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

@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: 1350c2e860

ℹ️ 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
Sinity disabled auto-merge September 28, 2026 21:20
…line

A claimed read-ahead's full digest polls the warm's cancellation between chunks and drops the artifact when cancelled. A retained wait whose future finishes as the wait expires re-reads it instead of re-raising the wait's TimeoutError.

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

@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: 5bb95c39e7

ℹ️ 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/storage/derived/raw.py Resolved
…ained phases

Stage calls hold one lock; shutdown sets the running warm's cancellation and takes the lock before stopping the pool. Retained preparation checks the owner's cancellation inside blob and carrier digests and between reconciliation steps, refusing retryably.

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

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

ℹ️ 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
A warm publishes its cancellation under the same lock shutdown uses to close the stage; completion-time and restart-salvage verification honour the active warm's cancellation, and reaped read-ahead is dropped without a digest; the membership classifier's blob re-hash takes the compute owner's stop predicate.

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

@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: 80ce367c43

ℹ️ 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
# Conflicts:
#	polylogue/sources/prepared_message_sink.py
@Sinity
Sinity merged commit b5fd10a into master Sep 28, 2026
3 of 4 checks passed
@Sinity
Sinity deleted the claude/perf-sources branch September 28, 2026 23:42
Sinity added a commit that referenced this pull request Sep 29, 2026
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
…acts

The run route reads operation_runtime.embedding_convergence from the
API server (#5727), so the fake server declares it. Since #5691 a
cancelled compute owner stops its retained preparation, so the raw
owner test asserts nothing is published on cancel and the next pass
publishes the session and its FTS rows.

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
…#5782)

## Summary

`tests/unit/daemon/test_daemon_cli.py` failed on master because of a
production defect, not the dependency bump. #5727 made a root-bound
writer lease refuse any write that omits its archive identity, but it
left callers that open without one. On fddc7a1 the daemon could not
start: `DaemonLifecycle.start` opened `ops.db` unnamed under
`polylogued`'s root-bound lease. #5769 has since fixed the lifecycle and
several daemon ops writers. This PR fixes the routes that were still
refused and realigns three tests with contracts that later PRs changed.

## Problem (evidence)

- `devtools test tests/unit/daemon/test_daemon_cli.py` on plain
origin/master 4cbf83b, with no lockfile bump: `29 failed`, the same
set as the bumped run. That rules out starlette, uvicorn, watchfiles,
ruff, hypothesis and networkx.
- 28 of the 29 were `UnleasedWriteError:
open_daemon_connection(.../ops.db) omitted archive identity for writer
daemon.lifecycle.start`, raised while the daemon started. The tests' own
`watch stopped`, `server stopped` and `shutdown marker failed`
expectations never ran. The 29th was the #5727 pidfile message change.
- With the lifecycle fixed, nine more failures appeared. The same tests
pass on 841bbb3, the commit before #5727. Traced causes:
- `SQLiteBackend.__init__` now runs the lease-gated
`initialize_active_archive_root` on every construction, even for an
established archive. The live batch reads `Polylogue.backend` outside
the lease, so each intake item came back `retryable: UnleasedWriteError:
active archive bootstrap requires the daemon write lease`.
- Nested `write_lease(actor)` re-entry called `require_write_lease`
without a root, so any derivation publish under a root-bound lease
raised "omitted archive identity".
- Daemon-emitted events re-resolved the ambient archive root instead of
the daemon's own.
- On master tip 14a63dc, the three touched test files still fail 14
tests: `devtools test --on-default-branch
tests/unit/daemon/test_daemon_cli.py
tests/unit/daemon/test_daemon_lifecycle.py
tests/unit/storage/test_write_lease.py` gives `151 passed, 14 failed`.

## Solution

Production (`fix(daemon)` commit):
- Pass `archive_root` at the write opens that still omitted it. These
are the FTS automerge, judgment automation, daemon assertion mutation,
schema drift sampling, schema sampling and verification, secret scan,
blob GC history, sqlite-vec runtime, the non-daemon branch of
`open_initialized_tier_connection`, and `connection_context`, which
gains the parameter.
- Daemon lifecycle, parked-loop and live-batch events name
`archive_root_path`.
- Nested `write_lease` re-entry checks the held lease's own identity. It
no longer checks an absent one.
- `initialize_backend_state` runs the active-root bootstrap only when
the caller may write: the bootstrap is needed, a lease is held, or
enforcement is off. A daemon-armed caller without a lease gets the
read-only `assert_archive_format_lineage` proof. An established archive
therefore still has to prove its lineage marker, as #5727 intended.
- `arm_write_lease_enforcement(process_wide=True)` no longer saves and
restores the thread-local flag. #5722's overlapping-arming test exits
out of order, which restored a stale `armed=True` and left the pytest
thread armed for every later test in `test_write_lease.py`.

Tests, each disposition against the PR that changed the contract:

| Test(s) | Cause | Disposition |
| --- | --- | --- |
| 14 `UnleasedWriteError` plus 13 `watch/server stopped` and `shutdown
marker failed` | lifecycle start under the root-bound lease (#5727) |
production bug. #5769 fixed the lifecycle, and this PR fixes the
remaining writers |
| `test_pidfile_remains_locked_until_admitted_writers_are_drained` |
#5727 widened the refusal wording | superseded contract. #5769 already
realigned it |
|
`test_an_orphaned_service_retains_archive_ownership_on_the_production_route`
(TimeoutError) | never reached `health_check` because the lifecycle
start raised | production bug, same root cause |
| `test_daemon_watcher_hints_wake_fair_intake_and_canonical_derivation`
×4 | backend bootstrap outside the lease (#5727) | production bug, fixed
|
| `test_cold_build_*` ×4,
`test_daemon_startup_catch_up_and_restart_repair_session_profiles` |
nested-lease re-entry, event root, and state leaked from the failing
watcher test | production bug, fixed |
| `test_run_daemon_services_waits_for_fts_startup_before_watcher` ×2 |
#5727 reads `operation_runtime.embedding_convergence` | superseded test
stub. The fake server declares the attribute |
| `test_raw_owner_cancellation_settles_publication_and_fts` (fails on
the current tip) | #5691 made a cancelled compute owner stop its
retained preparation | superseded contract. Renamed to
`..._stops_preparation_and_the_next_pass_publishes`: cancellation
publishes nothing, and the next pass publishes the session and its FTS
rows |
| `test_archive_bound_lease_can_delegate_without_dropping_identity` |
asserted `adopted is lease`, but adoption returns a per-thread view by
design | the test was wrong when #5727 added it. It now asserts that the
adopted view carries the archive identity and authorizes a write for
that archive |

New regression tests, each naming its anti-vacuity condition: nested
re-entry inherits the outer archive identity; an unleased backend admits
an established archive read-only and still refuses one without a marker;
lifecycle start and the signal marker persist under a root-bound lease.

## Verification

- `devtools test tests/unit/daemon/test_daemon_cli.py
tests/unit/daemon/test_daemon_lifecycle.py
tests/unit/storage/test_write_lease.py
tests/unit/cli/test_cli_write_authority.py
tests/unit/daemon/test_daemon_events_endpoint.py
tests/unit/storage/test_write_guard.py
tests/unit/daemon/test_write_coordinator.py
tests/unit/daemon/test_judgment_automation.py
tests/unit/daemon/test_secret_scan_sweep.py
tests/unit/daemon/test_standing_queries.py
tests/unit/daemon/test_standing_queries_default_evaluator.py
tests/unit/daemon/test_standing_query_clock.py
tests/unit/mcp/test_mcp_call_log.py
tests/unit/pipeline/test_schema_drift_sentinel_ingest.py
tests/unit/schemas/test_drift_sentinel.py
tests/unit/schemas/test_drift_sentinel_sampling.py
tests/unit/security/test_secret_scan.py` at 3a56a1e: `devtools test:
PASSED`, `445 passed`.
- `devtools verify --quick` at 3a56a1e: `verify: PASSED`.
- The head was then rebased over #5778, which touches none of these
files.

## Residuals

- `devtools schema closure` reports these touched files as IN:
`write_lease.py`, `async_sqlite.py`, `connection_profile.py`,
`bootstrap.py`, `blob_gc.py`, `sqlite_vec_runtime.py` and
`sampling_db.py`. The derived schema identity may move, so this must
land before a fresh build starts.
- Some writers outside the daemon still resolve the ambient root: the
HTTP reset event, browser capture and judgment receipt events. In
production that root equals the lease root. In tests it can differ when
`polylogue.daemon.events` is first imported under a
`patch("polylogue.paths.archive_root")`, which binds the mock into the
module.
- `open_profiled_connection` still has no `archive_root` for write
profiles. Every current caller uses a read profile.
- An `arm_write_lease_enforcement(armed=False, process_wide=True)`
suppressor no longer clears a thread-local arming. Nothing calls that
combination.

🤖 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
#5691 rewrote the live parse stage around worker read-ahead, pool
restarts, and preemption. The worker-death and hang handling from this
branch is re-implemented on that model: per-file attribution by attempt
markers, solo suspects, and escalation after repeated losses on an
unchanged observation. The submission-time deadline reaper is replaced
by a per-path no-progress hang bound that stops workers through the
same pool restart that reaps read-ahead. daemon/cli.py takes master's
_derivation_admission and keeps the failed outcome's transient flag.

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

Lands the verified part of ChatGPT worker 9's pass over Codex review
findings in `polylogue/sources` (beads polylogue-1tyq5.90, .91, .92; 75
findings). 13 fixes are kept, each with a regression test that fails on
master. The other 62 are recorded below as fixed-already, stale, refuted
or not reached.

## Problem

The findings are Codex P2 review threads on earlier PRs. The kept ones
reproduce on current master:

- ChatGPT extracted-export asset acquisition follows leaf symlinks, so
it archives bytes from outside the export.
- Replay's bounded probe drops the Claude project keys, so a retained
UNKNOWN project whose keys sit past the 8 KiB prefix stays UNKNOWN and
is refused.
- Drive-like lowering drops `source_path` when it reclassifies a Gemini
CLI document, so a matching sidecar is skipped.
- The Drive cache rejects valid `null` JSONL records and large integers,
and leaks its temporary file when a write or close fails.
- Import preflight reports SUPPORTED even when it records a degradation
caveat.
- A lost best-effort `cursor_update` leaves a completed attempt with
`materialized_count=0`.
- Source-only (acquire-only) intake still requires the Antigravity
language server before it keeps `.pb` bytes.
- The JSONL blank-line regex matches every newline-terminated payload,
so the `bytes.count` fast path never runs.
- The ops checkpoint holder looks for `-shm` beside a symlinked `ops.db`
rather than beside its target.
- A sealed, complete cold-build count loses its zero ETA once it stops
advancing.
- Hook paste enrichment checks the write lease against the
index-generation directory instead of the archive root.

## Solution

- `sources/assembly_chatgpt.py`: the walk admits only lstat-regular
files. Each asset is opened with `O_NOFOLLOW|O_NONBLOCK`, checked with
fstat, then streamed with `write_from_fileobj`. Asset refusals are
emitted as one structured event, `sources.chatgpt.asset_refused`.
- `sources/revision_backfill.py`: `docs`, `prompt_template` and
`is_starter_project` added to the probe's retained root keys.
- `sources/dispatch.py`: `_lower_drive_like_payload` forwards
`source_path` through both recursive branches and the Gemini CLI spec.
- `sources/drive/__init__.py`: a successful decode is enough to validate
a cache, and ijson runs in its lossless number mode. One cleanup path
covers temporary creation, write, close and replace.
- `sources/import_preflight.py`: any caveat now reports DEGRADED, which
is still admissible. The bounded-trajectory test expectation changes to
match.
- `sources/live/batch.py`: the completed progress update carries
`materialized_count`. Source-only intake skips the language-server
cohort, so `.pb` files take the ordinary raw snapshot.
- `sources/live/batch_support.py`: the regex no longer treats the empty
line after a final newline as blank.
- `sources/live/cold_build.py`: the holder resolves `ops.db` before
deriving `-shm`. A sealed count at or above its denominator returns ETA
0.
- `sources/live/hook_paste_enrichment.py`: the lease check uses the
configured archive root.

Worker changes not landed:

- `census_parse_stage.py` idle-wait fix: the module has no production
instance and polylogue-rykzt retires it. The live `LiveParseStage` has
no such event pair.
- `parse_prefetch.py` cohort scoping: already on master through #5691
(`_prepare_existing_session_writes(paths=...)`).
- Source-only ZIP provider stamp (92-01): it does not fix the reported
case. The OTel GenAI spec declares a catch-all `.*\.json$` rule, so
`declared_artifact_provider` returns None for every `.json` member,
`tool-results/dump.json` included.
- The worker's `docs(review)` commit: per-finding records belong in this
body, not in tracked files.

## Verification

- `agentctl job start polylogue verify_quick --workspace
/realm/worktrees/salvage-w9 --wait` → job 2346: `verify: PASSED exit=0
... head=edfab65f2749`
- `agentctl job start polylogue pytest_focused --workspace
/realm/worktrees/salvage-w9 --wait --
tests/unit/sources/test_codex_debt_w9_regressions.py
tests/unit/sources/test_import_preflight.py
tests/unit/sources/test_drive_source_client.py
tests/unit/sources/test_live_batch_support.py
tests/unit/sources/test_cold_build_generation.py
tests/unit/sources/test_cold_build_durability_policy.py
tests/unit/sources/test_revision_backfill.py
tests/unit/sources/test_dispatch_payloads.py` → job 2347: `passed 470,
failed 1, total 471` at head edfab65. The one failure,
`test_import_preflight.py::test_unidentified_trajectory_rows_keep_distinct_identities`
(a `LogicalExportError` from `parse_trajectory_db`), fails the same way
on unmodified master (jobs 2284 and 2348).
- Proof that the tests fail without the fixes: the final
`test_codex_debt_w9_regressions.py` was copied into a worktree at
unmodified master and run as job 2348, with 17 failures (`17 failed in
21.74s`). That covers every kept finding's test. The 92-13 ETA test
fails only on its complete-count case; its two control cases pass on
both heads, as intended.

## Self-review

- **Sibling sites.** The other asset reader is the ZIP branch, which
reads members, not filesystem paths. `_lower_drive_like_payload` has one
caller and `_enrich_archive_paste_from_hooks` has one. The
cache-validator change covers both Drive routes (byte and streamed).
Other `-shm`/`-wal` derivations elsewhere in the daemon are outside this
finding and are listed as a residual. The 92-01 gap is shared by the
ordinary live ZIP route and `retained_acquisition.py`, which is why the
one-route stamp was dropped rather than landed.
- **Cancellation and shutdown in loops.** No loop or wait was added. The
asset loop keeps its per-file `continue` on `OSError`.
- **Unbounded reads.** Assets still stream through `write_from_fileobj`
under the existing `MAX_UNCOMPRESSED_SIZE` check. The Drive validators
keep their streaming form.
- **Fail-open fallbacks and compatibility shims.** None added.
Source-only `.pb` intake retains raw bytes without parsing, and parsing
still needs the language server once derived tiers return. There is no
alias or dual path.
- **Removed symbols.** None removed. Tests patch `local_agent`,
`tempfile` and `time` directly rather than through attributes the source
modules do not export.
- **Tests prove the production route.** The tests drive `parse_payload`,
`iter_drive_raw_data`, `preflight_import_source`,
`LiveBatchProcessor.ingest_files` / `_ingest_full_paths_sync`,
`jsonl_complete_prefix`, `_hold_ops_checkpoints`,
`enrich_paste_from_hooks` and the retained-UNKNOWN detector
`_detect_unknown_retained_provider`, which is the same private entry
point `test_revision_backfill.py` already uses. The ETA test calls the
`accepted_progress` property on a hand-set generation.

## Per-finding dispositions

Counts: 13 fixed, 0 dropped as not real, 22 fixed-already, 3 stale, 2
refuted, 35 not reached.
Per bead: .90 6 fixed / 6 fixed-already / 2 stale / 1 refuted / 10 not
reached. .91 3 / 5 / 1 / 1 / 15. .92 4 / 11 / 0 / 0 / 10.

| key | disposition | evidence | test |
|---|---|---|---|
| 90-01 (#4803) | fixed | `sources/assembly_chatgpt.py`: Regular-file
lstat admission and no-follow/nonblocking opened-file validation prevent
leaf-symlink and FIFO substitution from being acqu... |
`test_w9_asset_acquisition_rejects_symlink_leaves` |
| 90-02 (#4234) | stale | dead `census_parse_stage.py`, retired by
polylogue-rykzt; live `LiveParseStage` has no such event pair | — |
| 90-03 (#4928) | refuted | `sources/codex_state_evidence.py`: The
requested reconciliation depends on upgrading an earlier archive. This
batch explicitly targets fresh v1 and forbids migrations/... | — |
| 90-04 (#4889) | not reached | `sources/codex_state_evidence.py`:
Same-ID admission still needs an acquisition-state preservation proof;
leave replay/storage reconciliation to follow-up. | — |
| 90-05 (#4229) | stale | `sources/codex_state_evidence.py`:
event_identity and its hook-event emission are gone; Codex thread state
is now projected through codex_state_projection instead. | — |
| 90-06 (#5626) | not reached | `sources/codex_state_evidence.py`: State
snapshot chunks are processed within the same writer ownership; no
bounded writer-handoff implementation supplied. | — |
| 90-07 (#4622) | not reached | `sources/codex_state_evidence.py`:
Backlog is fetched as a whole and consumed in one retained-receipt pass;
replacing this needs end-to-end paging, not a cap. | — |
| 90-08 (#5626) | not reached | `sources/codex_state_evidence.py`:
Replaying a shorter logical state value does not reconcile removed
trailing chunk observations. | — |
| 90-09 (#5581) | not reached | `sources/codex_state_evidence.py`: The
frame consumer still needs explicit cancelled/expired-read propagation
instead of interpreting an empty projection as current. | — |
| 90-10 (#4174) | not reached | `sources/cursor.py`: ZIP skip accounting
counts every physical member, unlike the declaration-aware acquisition
population. | — |
| 90-11 (#4661) | fixed-already | `sources/decoder_zip.py`: Explicit
suffix/predicate callers disable inferred declaration-path widening. | —
|
| 90-12 (#4661) | fixed-already | `sources/decoder_zip.py`: Only strong
artifact declarations widen the inferred member admission route. | — |
| 90-13 (#4661) | fixed-already | `sources/decoder_zip.py`:
Unknown-inbox admission now uses cross-provider strong declarations;
ordinary live ZIP acquisition retains their sidecars. | — |
| 90-14 (#4661) | fixed-already | `sources/decoder_zip.py`: Source-only
ZIP admission supplies is_declared_artifact_path, so declared non-JSON
sidecars are retained. Provider stamping is a separate fin... | — |
| 90-15 (#4721) | fixed | `sources/dispatch.py`: The bounded streaming
document probe retains the three Claude project shape keys, without
retaining their unbounded values. |
`test_w9_retained_unknown_project_is_detected_beyond_prefix` |
| 90-16 (#4720) | fixed | `sources/dispatch.py`: Drive lowering forwards
source_path through recursive wrappers and the Gemini CLI document
specification; all internal callers updated. |
`test_w9_drive_lowering_preserves_gemini_source_path` |
| 90-17 (#4184) | not reached | `sources/dispatch.py`: Current master
adds chatgpt_rejected_mapping_candidates; consumer-to-durable-accounting
trace remains incomplete, so no resolution claimed. | — |
| 90-18 (#4652) | fixed-already | `sources/dispatch.py`:
lower_chatgpt_documents now lowers shared decode records inside specs as
well as the direct top-level case. | — |
| 90-19 (#4188) | not reached | `sources/dispatch.py`: Codex-task
conservation exclusion still needs population-level treatment, not
simply returning an empty document list. | — |
| 90-20 (#5584) | fixed-already | `sources/dispatch.py`: The production
streamed generic caller normalizes ijson numbers before
parse_generic_messages_stream; no additional dispatcher normalization is
... | — |
| 90-21 (#4654) | not reached | `sources/dispatch.py`: Shared-decode
conservation and parser identity precedence require a joint
production-route fix. | — |
| 90-22 (#4188) | not reached | `sources/dispatch.py`: DOM capture
fallback IDs still require the same normalization as the production
parser; old supported input is not automatically exempted by the... | —
|
| 90-23 (#4174) | fixed | `sources/drive/__init__.py`: Both
cache-reading and streamed revision-proof routes accept syntactically
valid null JSONL records. | `test_w9_drive_cache_accepts_null_jsonl` |
| 90-24 (#4174) | fixed | `sources/drive/__init__.py`: The finally
cleanup covers tempfile write and close failures as well as rename
failure, preserving the previous destination. |
`test_w9_drive_failed_cache_publication_removes_temporary` |
| 90-25 (#5421) | fixed | `sources/drive/__init__.py`: Lossless ijson
number parsing prevents repeated downloads of Python-JSON-readable large
integers. |
`test_w9_drive_unchanged_large_integer_cache_does_not_download` |
| 91-01 (#5447) | not reached | `sources/hook_producer.py`:
Alternate-producer/compaction quiescence needs a complete
writer-protocol trace; no fix or dismissal claimed. | — |
| 91-02 (#4269) | not reached | `sources/hooks.py`: Legacy-root source
identifiers remain positional; no interface replacement/consumer update
supplied. | — |
| 91-03 (#4932) | fixed | `sources/import_preflight.py`: Supported
inputs with degradation caveats report DEGRADED. The existing
bounded-trajectory test expectation is updated to the same hones... |
`test_w9_trajectory_preflight_reports_degraded_steps` |
| 91-04 (#4275) | stale | `sources/live/admission.py`: The unreachable
terminal branch cited by the review has been removed; current policy
reacquires non-accepted receipts. | — |
| 91-05 (#5263) | not reached | `sources/live/append_ingest.py`:
Asserted hook-carrier baseline versus byte-proven resynthesis needs a
coordinated authority-proof change. | — |
| 91-06 (#5530) | not reached | `sources/live/append_ingest.py`: Success
artifact observation still precedes single-session/chain-authority
acceptance. | — |
| 91-07 (#4683) | not reached | `sources/live/batch.py`: Offered/default
queued population is computed after blocking filters. | — |
| 91-08 (#5403) | not reached | `sources/live/batch.py`: Re-resolving
historical blocked spellings can implicate a retargeted symlink
destination; needs durable-identity handling. | — |
| 91-09 (#4587) | not reached | `sources/live/batch.py`: Direct deferred
resynthesis is preserved, but deferred flush still re-reads an absent
ops cursor; full deferred-plan regression not supplied. | — |
| 91-10 (#5015) | not reached | `sources/live/batch.py`: Deferred
catch-up convergence still needs its own canonical receipt or duration
attribution to the originating attempt. | — |
| 91-11 (#4809) | fixed-already | `sources/live/batch.py`: ingest_files
catches escaped failures and finalizes the attempt, including
writer-hold budget failures. | — |
| 91-12 (#4713) | not reached | `sources/live/batch.py`: Current byte
accounting labels unattempted bytes, but that does not establish a
per-file deferred/excluded disposition for an outer-loop time-... | — |
| 91-13 (#4730) | not reached | `sources/live/batch.py`: A structural
halt still marks subsequent unattempted source groups as failed rather
than refused/unattempted. | — |
| 91-14 (#4874) | not reached | `sources/live/batch.py`: Materialized
sessions versus successfully parsed file units still needs all
reader/telemetry consumers reviewed together. | — |
| 91-15 (#4874) | fixed | `sources/live/batch.py`: The completed
progress event repeats the already-computed unique materialized-session
count after best-effort cursor_update loss. |
`test_w9_completed_ingest_repeats_materialized_count` |
| 91-16 (#5300) | not reached | `sources/live/batch.py`: Live metrics
now expose deferred_file_count, but typed catch-up receipt/CLI
propagation is not fully established here. | — |
| 91-17 (#4330) | fixed | `sources/live/batch.py`: Source-only
acquisition bypasses Antigravity language-server protobuf conversion and
retains original bytes. |
`test_w9_source_only_protobuf_does_not_invoke_converter` |
| 91-18 (#5526) | refuted | `sources/live/batch.py`: This asks to
migrate debts stored under predecessor subjects. Prior archive state is
explicitly out of scope for fresh v1; current code emits ... | — |
| 91-19 (#4175) | fixed-already | `sources/live/batch.py`: Full
file-backed JSONL acquisition computes and carries complete_prefix_size
rather than requiring an in-memory raw payload. | — |
| 91-20 (#4229) | fixed-already | `sources/live/batch.py`: Boundary
determination now checks the tail; an interior malformed line does not
truncate the cursor before later accepted records. | — |
| 91-21 (#4883) | not reached | `sources/live/batch.py`: Snapshot scope
selection for a renamed Antigravity SQLite store needs further current
policy tracing; no fix or refutation claimed. | — |
| 91-22 (#5263) | not reached | `sources/live/batch.py`: Full
hook-carrier raw bytes/frontier authority with a partial tail still
needs coordinated baseline treatment. | — |
| 91-23 (#4661) | fixed-already | `sources/live/batch.py`: ZIP safety
admission now precedes provider sniffing on the ordinary live route. | —
|
| 91-24 (#4661) | fixed-already | `sources/live/batch.py`:
Declaration-owned sidecars are excluded from ordinary ZIP provider
sniffing. | — |
| 91-25 (#4661) | not reached | `sources/live/batch.py`: --explain still
sniffs the whole infolist and retains provider_hint when constructing
member classification; route equivalence remains open. | — |
| 92-01 (#4661) | not reached | worker fix dropped: OTel `.*\.json$`
rule makes `declared_artifact_provider` ambiguous for every `.json`
member | — |
| 92-02 (#4549) | fixed-already | `sources/live/batch.py`: Legacy
promotion is now a deferred thunk, not an eager write during initial
reconstruction. No legacy upgrade code added. | — |
| 92-03 (#4587) | not reached | `sources/live/batch.py`: Full-head
reconstruction still requires the old full-file digest before composing
a mutable-header Claude semantic frontier. | — |
| 92-04 (#5568) | not reached | `sources/live/batch.py`: Equal-metadata
measurement-only update handling needs an accepted-change regression; no
new fix supplied. | — |
| 92-05 (#4587) | not reached | worker refutation rejected: promotion
thunk is live; no proof v1 never writes frontier-less appends | — |
| 92-06 (#4660) | fixed-already | `sources/live/batch.py`: Cursor
publication compares the post-proof file observation with the pre-proof
observation. | — |
| 92-07 (#4660) | fixed-already | `sources/live/batch.py`: Non-frontier
prefix hashing charges cursor hash-read bytes. | — |
| 92-08 (#4660) | fixed-already | `sources/live/batch.py`: Publication
rebases the accepted body end against the current Claude header length.
| — |
| 92-09 (#4662) | fixed-already | `sources/live/batch.py`: The rebased
publication_end is used for the cursor offset and corresponding
file-length guard. | — |
| 92-10 (#4662) | fixed-already | `sources/live/batch.py`: Claude
frontier read bytes are charged before rejecting an unavailable/invalid
proof. | — |
| 92-11 (#5258) | fixed | `sources/live/batch_support.py`: The regex no
longer treats the virtual empty EOF after a delimiter as a physical
blank line; actual blank lines retain their existing ... |
`test_w9_jsonl_boundary_keeps_newline_fast_path` |
| 92-12 (#5389) | fixed | `sources/live/cold_build.py`:
Checkpoint-holder attachment checks the SHM file beside the resolved
physical SQLite filename. |
`test_w9_ops_holder_accepts_symlinked_database` |
| 92-13 (#5609) | fixed | `sources/live/cold_build.py`: A valid sealed
complete count reports zero ETA after the advancement freshness window;
incomplete and unsealed stale counts still report ... |
`test_w9_completed_cold_build_eta_does_not_expire` |
| 92-14 (#5609) | not reached | `sources/live/cold_build.py`: Projection
refresh time, not receipt acceptance time, still renews the advancement
clock. | — |
| 92-15 (#5619) | fixed-already | `sources/live/cold_build.py`:
refresh_faulted_baseline calls _reset_accepted_progress(merged), then
refresh_accepted_progress; the denominator and weights no longer re... |
— |
| 92-16 (#4185) | not reached | `sources/live/cursor.py`:
Completed-with-failures reader/metric label propagation needs all public
consumers updated together. | — |
| 92-17 (#4730) | not reached | `sources/live/dedup.py`: Structural
failure installs a per-source halt; the test autouse fixture only clears
the global degraded flag. | — |
| 92-18 (#4795) | fixed | `sources/live/hook_paste_enrichment.py`: The
enrichment route carries the configured archive root into its
write-lease check instead of treating a generation index dir... |
`test_w9_hook_paste_uses_archive_lease_for_generation_index` |
| 92-19 (#4713) | fixed-already | `sources/live/metrics.py`:
LiveBatchMetrics.to_payload serializes both excluded_file_count and
excluded_reasons. | — |
| 92-20 (#5546) | not reached | `sources/live/parse_prefetch.py`:
Attempt cleanup exists, but retention of every unconsumed
candidate/shard across warm cohorts is not fully resolved here. | — |
| 92-21 (#5546) | not reached | `sources/live/parse_prefetch.py`:
Hashless worker errors remain reusable across changed source content;
freshness/deferred disposition needs a full route fix. | — |
| 92-22 (#5568) | fixed-already | #5691:
`_prepare_existing_session_writes(paths=...)` scoped to current
candidates | — |
| 92-23 (#5634) | not reached | `sources/live/parse_prefetch.py`:
Per-path reconciliation opens concurrent read frames without
establishing independent scan admission in this function. | — |
| 92-24 (#5542) | fixed-already | `sources/live/production_baseline.py`:
Baseline.verify delegates to
unretained_source_decisions/open_readonly_connection; the manually
interpolated SQLite URI is gone. | — |
| 92-25 (#5640) | fixed-already | `sources/live/production_baseline.py`:
Baseline emits its hashing phase before archive-member expansion and
decomposition. | — |

## Derived-identity closure

These changed files are members of
`docs/plans/schema-closure-baseline.json`, so the derived schema
identity moves: `sources/assembly_chatgpt.py`, `sources/dispatch.py`,
`sources/drive/__init__.py`, `sources/live/batch.py`,
`sources/live/batch_support.py`, `sources/live/cold_build.py`,
`sources/live/hook_paste_enrichment.py`, `sources/revision_backfill.py`.
`sources/import_preflight.py` is not a member. Membership was read from
the committed baseline, not recomputed, because the bulk pool that runs
`devtools schema closure` jobs was paused. No module was added to the
closure.

## Residuals

- 92-01 stays open: declaration lookup needs to prefer a unique
raw-only/fact rule over broad session patterns, applied on all three ZIP
routes.
- 92-05: the worker's fresh-v1 refutation was rejected, because the
legacy-append promotion thunk is live code and `ops.db` is disposable.
The finding stays open.
- Other `-shm`/`-wal` path derivations (`daemon/status.py`,
`daemon/health.py`, `daemon/backup.py`, among others) do not resolve
symlinks and were not reviewed here.
- Preflight now reports DEGRADED for a bounded trajectory probe or a
truncated directory walk, not only for parser flags.
- `test_unidentified_trajectory_rows_keep_distinct_identities` already
fails on master.

🤖 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
…#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
…#5809)

## Summary

Realigns three tests in
`tests/unit/storage/test_lineage_normalization.py` that fail on master
(polylogue-ezvw3). Each one encodes a contract that a named PR changed
deliberately. No production code changes.

## Problem

At master 1beb2e5 (AgentCTL job 2441), these fail:

-
`test_prefix_sharing_child_provider_usage_keeps_its_own_reported_totals`
(line 352). The child's `total_tokens`-only event (272 000) stores NULL
input, cached and output totals, but the test expects 0. #5530
(904b2f8) replaced `_payload_int` with `_payload_optional_int` in
`_provider_usage_event_row`, so an unreported lane now stays NULL.
- `test_child_before_parent_reextracts_provider_usage_tail` (line 1730).
The child rollup reads 0 instead of 130. The test put an all-zero
cumulative tick after the child's 160/30/25 cumulative. #5530 also
changed `_provider_usage_row_has_lane_totals` from "any non-zero" to
"any present", and added
`test_explicit_zero_cumulative_supersedes_prior_positive`. An explicit
zero cumulative is now a measurement, and the latest one wins.
- `test_late_parent_resolution_invalidates_child_derived_products` (line
873). The child is non-valid right after the test seeds a fresh profile.
#5525 (ca25740) added trigger-captured `session_profile_demand`, and
`_classify_partition_with_demand` reports a demanded session as stale
until publication consumes the demand. The test's seed never consumed
it.

None of the suspects named on the bead (#5803, #5792, #5764, #5691) is
the cause. #5803's PR body already lists these three as pre-existing
failures.

## Solution

- Prefix-sharing test: the `total_tokens`-only row now expects NULL
input, cached and output totals. The docstring cites #5530. The rollup
assertion (130/25/30) is unchanged, which proves the NULL row does not
displace the latest lane totals.
- Child-before-parent test: the same measured-zero tick, unchanged, now
comes before the child's latest cumulative. The rollup stays exactly
130/25/30 before and after the parent arrives. The re-extraction
assertion keeps both `cy` rows, including the tick's `request_id`, in
their new order. A stale comment about the evidence predicate is
corrected.
- Late-parent test: `_seed_fresh_session_products` deletes the session's
`session_profile_demand` row, as
`publish_prepared_session_insight_partition` does. The docstring now
says the retained-row assertion carries the anti-vacuity, because
re-captured demand alone would also mark the child stale.

Schema classification: none. No production file changes, so nothing
enters the derived-identity closure.

## Verification

- `agentctl job start polylogue pytest_focused --workspace
/realm/worktrees/polylogue-mh-lineage --
tests/unit/storage/test_lineage_normalization.py` → job 2573: `devtools
test: PASSED exit=0` (`105 passed` of 105, head 2d1d0a4).
- `agentctl job start polylogue verify_quick --workspace
/realm/worktrees/polylogue-mh-lineage` → job 2584: `verify: PASSED
exit=0` (head 2d1d0a4).

## Self-review

- **Contract, not bug.** For each failure I found the commit that
changed the behavior and checked that it was intended. #5530's summary
says "distinguish absent usage from explicit zero", and it added a test
asserting that a zero cumulative supersedes a prior positive one. #5525
added the demand table, its triggers and the demand-aware classifier on
purpose. No assertion was loosened. Every expected value is still exact.
- **Anti-vacuity.** Test 1 would fail if re-extraction kept the `c1`
row, dropped a `cy` row, or rebased the child against the parent. Test
2's NULL expectation fails if absent lanes are coerced to 0 again. Test
3's retained-row assertion fails if `_reextract_prefix_tail_db` stops
deleting profiles.
- **Siblings.** `_seed_fresh_session_products` has one caller. No other
test in this file seeds profiles or reads partition status.
- **Public boundary.** Test-only diff with synthetic fixtures.

## Residuals

- Under #5530, a zero cumulative that follows a positive one within a
session sets the rollup to 0. That is the declared contract. Whether a
real provider emits such a reset, and whether billing should then take
the maximum, is a product question this PR does not reopen.

polylogue-ezvw3

🤖 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
Batch `polylogue-20260929-130016-35798596` on base `0914f89d4c72`.

**polylogue-9m93s** Use one retained-input route for every file size
- [ ] One ordinary retained-input route handles every file size and
removes the size branches that silently exclude or separately defer
valid inputs. Focused synthetic tests show complete membership, per-re
- [x] Worker isolation and focused fault tests turn a killed parse
worker into a typed per-file failure while the daemon survives, and
ensure queue/memory accounting does not lie or starve foreground progre
- [ ] Focused devtools tests and relevant quick gates pass on the fixed
code candidate with exact selectors and receipts. The measured 419 MB
RSS bound and 1.6 GB scratch daemon convergence remain open in t

**polylogue-i07pw** Complete prepared publication and useful worker
parallelism on the ordinary route
- [ ] 1. The ordinary daemon path consumes prepared work and removes the
displaced writer-side reconstruction.
2. Selected concurrency actually supplies work; configured thread count
is not performance evid

**polylogue-6xcqj** One acquisition-to-publication path for incremental
updates and fresh construction
- [ ] 1. Live and fresh source inputs reach the same
interpretation/publication owner through ordinary daemon entry.
2. Interrupted acquisition/publication has an identifiable accepted
operation or private

**polylogue-s8x8s** Remove the super-linear and redundant work in parse
and cursor commit
- [ ] 1. next_ordinal is O(1); the 419 MB codex file
(manifest-whale-codex.json) ingests in under half its measured 245 s on
the same driver. 2. The pickle spool is replaced by an in-memory record
list unde

**polylogue-aar35** Delete the inert wanted-source receipt machinery and
per-origin path overrides

**polylogue-5hcbg** Explicit cold build can promote a candidate missing
sessions the active index serves

**polylogue-8j9rh** Session excision leaves its tool-result sidecar raws
and bytes behind

**polylogue-b8of0** A kill inside an append's index write leaves the
tail unmaterialized and acknowledged
- [x] The append variant of
tests/unit/sources/test_live_ingest_kill_recovery.py (kill after the
append's index write, restart, admit) ends with 6 messages, 6 distinct,
1 session, no parse errors, through t
- [x] A page does not report DUPLICATE for a source whose acquired
revision has no materialized sessions.

## Self-review

**polylogue-9m93s**: 3 pass(es) against
`docs/review/codex-review-guide.md`, `polylogue/daemon/AGENTS.md,
polylogue/sources/AGENTS.md, polylogue/storage/AGENTS.md (Code Review
Rules)`,
`/realm/project/sinnix/dots/_ai/skills/orchestrate/references/worker-contract.md
(generic list)`
- [x] worker-contract 1: each assigned criterion is met on the
production path, or an unmet one names its blocker: F02 is exercised
through _iter_ingest_results_sync, the function _consume_ingest_results
calls, with fake executors only at process_pool_executor; F58 through
session_evidence_timestamps and a real SqliteMessageStore; F61 through
normalize_active_branch (called by write.py prepare_session_rows and
_prepared_message_context) and SqliteMessageSink.normalize_active_path
(called by append_session_to_shard); the kill test drives
FileIntakeAdapter over LiveWatcher in a SIGKILLed child. Every unmet
criterion (INTAKE-PREP-1, INTAKE-PREP-3, the whole 6xcqj and i07pw
fields) names its blocker in its evidence.
- [x] worker-contract 2: each defect class is handled at every site
(search and count): Inline pool fallback: `grep -rn 'PicklingError'
polylogue` found 2 sites (ingest_batch/_core.py, validation_flow.py),
both removed. Undelivered work: the stall path dropped unsubmitted raws,
now refused. Worker-death policy: live parse_prefetch (loss streak),
storage/derived/raw.py (always retryable) and ingest_batch (sole =
defect, shared = retryable) still differ; recorded in unresolved.
Admission rule: every append_session_to_shard/prepare_session_shard site
in prepared_jsonl.py (13) is preceded by the rule (grep listing
checked). Active-branch leaf deciders: write.py list normalizer and sink
normalizer unified; prepared_merge's own leaf choice now clears the
inherited marker; parsers that set leaves (chatgpt, drive, claude
common) are producer evidence and unchanged.
- [x] worker-contract 3: every consumer of a changed interface is
updated and the predecessor deleted: _normalized_messages removed; its 2
write.py callers, 3 test references and the prepare_session_rows
docstring now use normalize_active_branch (git grep _normalized_messages
= 0). _ACTIVE_PARENT_LOOKUP_SQL replaced by two occurrence queries; the
query-plan test checks both. whale_outbox.py deleted with cli.py drains,
_WHALE_RECEIPT_ROOT, tests in test_daemon_cli.py and
test_whale_outbox.py, the exclusive-create-write baseline line and
docs/daemon.md (git grep = 0). ParsedMessage.active_leaf_fallback is
declared in pipeline/ids.py _EXCLUDED_FIELDS (partition test passes) and
serialized only in message JSON. The moved normalizer stays in
prepared_message_sink.py so the closure baseline does not grow (the
first attempt added a module and the schema-closure gate refused it).
- [x] worker-contract 4: every failure path is typed and visible: Pool
start failure, submission failure, stall and worker death each yield one
IngestRecordResult with outcome_code, retryable and evidence_ref
(worker:pool_start:*, worker:submit:*, worker:progress_deadline,
worker:BrokenProcessPool); validation raises instead of switching mode;
occurred_at_bounds raises on an unreadable sink instead of answering
None.
- [x] worker-contract 5: each new test fails when the behaviour it names
is removed: Each new test states its anti-vacuity: restoring the inline
fallback makes inline_runs non-empty and delivers raw-1 twice; charging
every break as a defect turns the shared-death raws non-retryable,
treating every break as transient turns the sole-death raw retryable;
dropping refuse_remaining loses raw-3; reading messages first makes
visits 3000 and decodes 4; by-id marking or last-occurrence parent
lookup changes the dup and nearest-earlier paths; dropping the marker
flips both explicit False paths on the second pass; copying the revision
marker in the merge leaves the cohort paths False; the kill test's
DUPLICATE-with-3-rows outcome is the b8of0 regression.
- [x] worker-contract 6: no secret, private path or personal data:
Fixtures are synthetic (neutral ids, texts and /tmp paths); the only
absolute paths in this result are the batch worktree and its receipts.
The pre-commit secret-scan flagged a candidate span in
revision_backfill.py's staged content; the diff there is a 3-line
comment and parameter rename with no credential-shaped text.
- [x] review guide 1: siblings and owners: The admission rule's owner
for sealed carriers is prepare_jsonl_blob; in-process parse routes still
own their own call and are listed in unresolved. The active-branch
meaning has one home (prepared_message_sink.py) with two physical forms.
The worker-death classification is decided in three routes; the
divergence is pre-existing and recorded rather than widened.
- [x] review guide 2: the fix itself: Review found and fixed defects
inside the fixes: the marker write was also applied to attachment JSON
(mypy caught it); cohorts were first keyed by id() of a pool that could
be collected and reused; a TypeError at submission was first classified
retryable (endless retry); the merge copied a revision's marker onto the
cohort. BrokenExecutor is a RuntimeError subclass, so the retryable test
covers both.
- [x] review guide 3: memory and limits: No cap or timeout added. The
coordinator's refusal queue is a deque bounded by the chunk. The disk
walk uses a temp table and per-row seeks, not a fetchall;
occurred_at_bounds is one aggregate query. positions_by_id holds ints
for a list that is already resident.
- [x] review guide 4: cost per unit: The chain walk is one indexed
lookup per chain step (EXPLAIN QUERY PLAN test covers both queries);
bounds replace a Python decode per message with one SQL aggregate; the
producer-pair short-circuit removes a traversal entirely.
- [x] review guide 5: interruption: The stall branch terminates the pool
as before and now also settles unsubmitted raws; the kill-recovery tests
prove a SIGKILL inside the index write loses and duplicates nothing.
- [x] review guide 6: ordering and races: occurred_at_bounds reads
current rows, so an unsealed sink edited after a call reports its new
timeline (tested); sealed sinks are immutable. Pool replacement happens
only for a raw whose submit raised, so no accepted raw is resubmitted.
- [x] review guide 7: failure classification: Shared worker death and a
shut-down or broken pool are retryable; a sole worker death and a
deterministic submission refusal are parser defects so they are not
retried forever.
- [x] review guide 8: silent outcomes: Every raw of a chunk now yields
exactly one result, including unsubmitted raws after a stall and every
raw when the pool cannot start.
- [x] review guide 9: cleanup on failure: A replaced broken pool is shut
down; the current pool is shut down in finally; the new tests close
their stores.
- [x] review guide 10: identity and keys: active_leaf_fallback,
is_active_leaf and is_active_path are excluded from the semantic hash;
message and block ids do not depend on them. Changed files in the
derived-identity closure, which must land before a rebuild:
polylogue/core/timestamp_authority.py, polylogue/pipeline/ids.py,
polylogue/sources/dispatch.py, polylogue/sources/live/batch.py,
polylogue/sources/parsers/base_models.py,
polylogue/sources/prepared_jsonl.py,
polylogue/sources/prepared_merge.py,
polylogue/sources/prepared_message_sink.py,
polylogue/sources/revision_backfill.py,
polylogue/storage/sqlite/archive_tiers/write.py (membership read from
docs/plans/schema-closure-baseline.json; gate schema-closure ok, no new
members).
- [x] review guide 11: lossless transforms: Lowering updates only leaf,
marker and path fields and is idempotent; the merge clears only the
marker with the leaf flag; timestamps keep precedence, one-sided and
inverted handling (parametrized test).
- [x] review guide 12: degenerate inputs: Empty sessions return
unchanged; a producer leaf without a provider id infers no path; a
parent cycle ends the walk (tested); zero raws and worker_count below
one are handled by max(1, ...).
- [x] review guide 13: consumers: Covered under worker-contract 3.
- [x] review guide 14: tests and stubs: monkeypatch targets follow the
renames (write.normalize_active_branch); removed
_drain_whale_receipt_outbox patches; the query-plan test imports the new
constants; the stale Grok no-callback test now asserts the admission
owner's refusal.
- N/A review guide 15: trust boundaries: No argv, credential,
file-permission or ownership handling is touched.
- [x] nested AGENTS (daemon, sources, storage) code review rules: No
timeout that abandons progressing work is added; no live-archive write
outside the writer route; no pre-acquisition exclusion predicate; no
DDL, CHECK, migration or embeddings change; no rebuildable state used as
durable authority.

**polylogue-s8x8s**: 3 pass(es) against
`docs/review/codex-review-guide.md`, `polylogue/sources/AGENTS.md (Code
Review Rules)`,
`/realm/project/sinnix/dots/_ai/skills/orchestrate/references/worker-contract.md`
- [x] worker-contract 1: each criterion met on the production path: AC2
goes through the production route: dispatch.parse_stream_payload ->
codex.parse_stream -> _parse_records ->
_CodexLookaheadIndex.retain_records. The new tests call parse_stream
(the same entry dispatch uses), and the whale tests call
parse_stream_payload itself. AC1 throughput, AC4 and addendum 4 are
operational and unmet; the blocker is the polylogue-hqha5 finished-build
measurement.
- [x] worker-contract 2 / guide 1: siblings of the defect class:
Searched for other per-record pickle spools in the parsers: grep
'pickle.dumps(record\|spool' polylogue/sources/parsers/*.py outside
codex.py finds only Hermes durable-spool prose, so there is no sibling
record spool. Inside codex.py, spool_records has one caller, the new
retain_records spill (grep count 2: definition and call). The Sequence
route in _parse_records was already in-memory.
- [x] guide 2: the fix itself: Found in pass 1: the local name
'retained' in _parse_records collided with the world_state branch's dict
local (mypy, job 3106). Renamed it to in_memory (commit 65afa93).
_retained_record_bytes is iterative, so deep nesting cannot raise
RecursionError, and a seen-set guards cycles. _drain yields in order
while releasing memory. An exception from the source iterator propagates
exactly as it did before.
- [x] guide 3: memory and limits: The in-memory tier holds at most 8 MiB
of estimated retained bytes plus the one record that crosses the budget;
everything above that spills to the same disk index as before. The
budget chooses a storage tier and never refuses or truncates input.
Traced-peak controls pass: 40 MB bound at 120,000 records, and the peak
does not grow with 10x the records (job 3172).
- [x] guide 4: cost per unit: The size walk costs O(nodes) per record
and runs only until the spill; after the spill it stops. A stdlib
microbenchmark on 10 MB of Codex-shaped records measured about 26 ms for
the walk against about 38 ms for pickle-dump plus two unpickle passes
plus the SQLite inserts. That is host-local and illustrative only; whale
attribution belongs to polylogue-hqha5.
- [x] guide 5/6: interruption, ordering and races: This is a pure
in-process transform. The scratch SQLite connection is still closed by
contextlib.closing on every exit. Record order is preserved on both
tiers and across the spill boundary (spill-midstream test).
- N/A guide 7/8/9: failure classification, silent outcomes, cleanup:
N/A: the change adds no except clause, skip or acquired resource.
Admission accounting is unchanged: every record is still replayed, and
conservation holds in the whale dispatch tests.
- [x] guide 10/11: identity and lossless transforms: The parse result is
identical across tiers: the prefix test compares the full ParsedSession
to parse(list) for every prefix on all three tiers, with
lookahead-dependent records (repeated code-mode call ids, compaction,
task_complete). codex.py is in the derived schema-identity closure (the
schema-closure gate passed), so this must land before a rebuild starts.
- [x] guide 12: degenerate inputs: An empty stream returns [] and takes
the Sequence route. A budget of 0 spills at the first record
(spill-first case). A single oversized nested record spills (the
nested-payload test).
- [x] guide 13 / worker-contract 3: consumers and predecessor: No
interface changed. The always-spool call is replaced, not kept beside
the new path. The whale-test comment and docstring that described
disk-only retention now describe the budgeted tier
(tests/unit/sources/test_codex_whale_fixtures.py:56-59, :107-108). grep
'spool\|codex_records' docs finds nothing to update.
- [x] guide 14 / worker-contract 5: tests fail when behavior is removed:
The memory tier goes red if streams are always spooled (the spy records
a spool). Spill-midstream goes red if the retained head is dropped or
reordered on spill (parse or spool mismatch). The nested test goes red
if the estimate is shallow sys.getsizeof(record) (nothing spools under
16 KiB). The ordinal test goes red if next_ordinal reads _outcomes or
_materialized runs. These red cases come from reading the code; the
mutations were not executed.
- [x] guide 15 / worker-contract 6: trust boundary, secrets, private
data: Fixtures are synthetic (replay-tier, nested, future_record_kind).
The diff and this result hold no private paths or data; the paths cited
are repository paths and the worktree receipt paths.

**polylogue-aar35**: 2 pass(es) against
`docs/review/codex-review-guide.md`, `polylogue/daemon/AGENTS.md and
polylogue/sources/AGENTS.md Code Review Rules`, `orchestrate
worker-contract generic list`
- [x] Guide 1: siblings and owners: Pass 1 found that three places read
HERMES_HOME: resolve_runtime_config, paths.hermes_sessions_path, and
agent_integration/installer.py. They disagreed on a blank value (the
installer turned it into Path('')). Fixed in 2a2b8c5: hermes_home()
in paths/_roots.py is now the only reader (`git grep HERMES_HOME --
polylogue` shows only its docstring and body, plus docs and comments).
Pass 1 also found a missed caller: test_hook_producer.py still
monkeypatched the removed _configured_provider; fixed in 7ee3f4b.
Sweeps for every removed name (browser_capture_spool_path, hermes_root
key, hook_sidecar_dir, hook_provider, drive_*_path keys,
antigravity_language_server, their POLYLOGUE_* env vars, spool-path,
--spool, WantedSource*/wanted-source) across the repo except CHANGELOG
found only the canonical path helpers and the new refusal test.
- [x] Guide 2: the fix itself: The component_started lifecycle event
used to read server.config.spool_path, which test fakes do not have, and
7 daemon tests failed on it. It now reads browser_capture_spool_root(),
the same value make_server defaults to (polylogue/daemon/cli.py, the
enable_browser_capture block). build_daemon_status's unknown-enabled
default is still True: the removed spool expression could never be None,
so it was always True before. Drive auth errors are still typed
DriveAuthError, and their messages now name the canonical paths.
- N/A Guide 3: memory and limits: N/A: the diff only deletes code or
removes parameters. It adds no reads, buffers or caps. The one new probe
is a single is_file() on the /usr/share path.
- N/A Guide 4: cost per unit: N/A: no per-item work was added.
discover_language_server gains one stat before the Nix-store scan.
- N/A Guide 5: interruption: N/A: no loops, waits or multi-step state
changes were added. The cold build's begin() only loses a validation
read that ran before any generation was created.
- N/A Guide 6: ordering and races: N/A: no check-then-use sequence was
introduced. The spool and hook roots are now fixed at the archive root,
so they cannot diverge between the receiver, the watcher and status.
- [x] Guide 7: failure classification: A removed key in polylogue.toml
now fails the load with the existing typed ConfigError that names the
key or its undeclared table. test_removed_path_override_is_refused
(tests/unit/core/test_config_inventory.py) asserts the refusal text for
all 7 TOML paths. The removed env vars are simply no longer read,
because nothing declares them.
- [x] Guide 8: silent outcomes: polylogued status now always probes the
live daemon first; before, the removed --spool flag forced a local
recompute. The browser_capture status payload leaves out spool_path, as
the default route already did. Nothing is skipped without a disposition.
- N/A Guide 9: cleanup on failure: N/A: nothing is acquired on a new
path. dev_loop_service no longer creates an artifact-root spool
directory it had passed through --spool.
- [x] Guide 10: identity and keys: No hash or ID formula changed.
source_manifest_continuity.py is in the derived-identity closure
(docs/plans/schema-closure-baseline.json). Editing it and cold_build.py
can move the candidate derived identity, so this must land before a
rebuild starts. The schema-closure gate passed on 2a2b8c5.
- N/A Guide 11: lossless transforms: N/A: no copy, replay or
regeneration path changed.
- [x] Guide 12: degenerate inputs: A blank or unset HERMES_HOME falls
back to <home>/.hermes in hermes_home(). A missing /usr/share binary
falls through to the Nix-store scan. An empty [sources] table is still
refused by _undeclared_toml_keys, whose existing semantics report an
undeclared table by name.
- [x] Guide 13: consumers: Updated every consumer: config inventory and
defaults; resolve_runtime_config; polylogued run/status and
browser-capture status/serve/action --spool; run_daemon_services and the
writer-lease helper; configure_runtime_components; build_daemon_status
and daemon_status_payload; daemon_watch_sources;
watched_source_presence; status diagnostics; init; drive auth; the three
hook carriers (hook_producer, packaging/polylogue-hooks,
contrib/polylogue-hook); nix/lib/settings.nix spool-path; devtools
dev_loop_service and isolated_environment; docs (configuration, daemon,
hooks, hermes-operators, architecture, maintenance); and tests. One
consumer is outside this repository: sinnix
flake/overlay/package/polylogue-status-document.patch patches the old
status_command spool plumbing. It is recorded in unresolved because this
worker may not write there.
- [x] Guide 14: tests and stubs: Removed tests that exercised only the
deleted behaviour (receipt round-trip, tampering, preflight, spool
override, env and TOML overrides, --spool local answer). Converted the
same-byte-replacement test to build_source_frontier. New tests and what
turns each red: test_removed_path_override_is_refused (declaring a key
again), test_detect_chat_sources_reads_hermes_home and
test_hermes_root_is_hermes_home (ignoring HERMES_HOME),
test_discover_language_server_finds_the_system_install (dropping the
/usr/share probe),
test_a_pending_capture_in_the_archive_spool_is_a_source (dropping the
archive spool from the watch set). conftest now scrubs HERMES_HOME, so
host state cannot leak into tests.
- N/A Guide 15: trust boundaries: N/A: no secret handling changed. The
Drive token and credential files keep their XDG locations and existing
modes.
- N/A Daemon AGENTS: timeouts and writer route: N/A: no timeout or
archive mutation was added. The daemon only lost a parameter.
- N/A Sources AGENTS: parser fields, detector tightness, pre-acquisition
owner: N/A: no parser, detector or exclusion predicate changed. The
antigravity edit is binary discovery only.
- [x] Worker 1: criteria met on the production path: Receipt machinery:
the module shrank from 838 to 289 lines, and cold_build.begin() no
longer reads a receipt. Overrides: each is gone from config.py (grep
count 0 for every property name). The focused suite drives CLI
run/status, resolve_runtime_config and discover_language_server: 1024
passed, and every one of the 10 failures reproduces on the base tree.
- [x] Worker 2: every site of the defect class: Same as guide item 1:
one repo-wide git grep per removed name and env var. The installer's
HERMES_HOME reader and the stale test monkeypatch were the only siblings
found, and both are fixed.
- [x] Worker 3: predecessor deleted with callers, tests, docs: The
receipt API, its tests and its doc sentence are deleted. So are the
override keys, env vars, CLI options, nix option, docs rows and tests.
No alias or fallback remains: a removed key is refused, not ignored.
- [x] Worker 4: failure paths typed and visible: A removed key raises
ConfigError. Missing Drive files raise DriveAuthError naming the
canonical path. An undiscoverable language server keeps its existing
None route into AntigravityExportError.
- [x] Worker 5: each new test fails when its behaviour is removed: See
guide item 14. Each new test's docstring names the change that turns it
red.
- [x] Worker 6: no secrets or private paths: Fixtures use tmp_path and
synthetic values. The only literal paths are the public vendor install
path /usr/share/antigravity/... and the public /nix/store.

**polylogue-5hcbg**: 2 pass(es) against
`docs/review/codex-review-guide.md (checklist items 1-15, Compatibility,
Limits, Do not flag)`, `orchestrate worker-contract generic list (items
1-6)`, `polylogue/daemon/AGENTS.md Code Review Rules`
- [x] Guide 1 / contract 2: siblings and owners: The only production
promotion of a cold-build candidate is ColdBuildGeneration.promote,
called only from settle_cold_build in polylogue/daemon/cli.py (grep
'_store.promote\|store.promote(' finds one call site,
cold_build.py:1046; grep 'generation.promote' finds only daemon/cli.py).
That call now goes through promote_cold_build_covering_active_index, so
every production promotion is covered; reconcile_promoted and
reconcile_interrupted_promotions finish an already-swapped pointer and
have nothing to compare. The retention predicate reuses the raw_sessions
row, the same retention statement production_baseline.verify reads; no
second classifier of 'retained' was added.
- [x] Guide 2: the fix itself (new exception reaches every caller):
ColdBuildCoverageError is raised inside the settle try block and
classified in classify_cold_build_settlement_failure
(operations/intake_adapters.py) as ('active_coverage_incomplete',
False), so the existing blocked path records it, emits
daemon.cold_build.settlement, and retries only when
settlement_evidence_revision changes (candidate index stat or source
evidence). No other caller invokes the wrapper. A first draft put the
check inside cold_build.py; devtools schema closure reported that file
IN the index identity closure and a base/head identity computation
showed the index identity moving (3010010c... to a9d7e842...). I moved
the check to polylogue/operations/cold_build_coverage.py (closure: out)
and restored cold_build.py to its base bytes; head identity is again
3010010c..., ops b3d33f04... unchanged.
- [x] Guide 3: memory and limits: The comparison pages the active
sessions table by keyset (session_id > ? ORDER BY session_id LIMIT 512);
per page it holds at most 512 rows plus two sets of the same size. Only
two integers and one id grow across pages. The 512 is a paging size, not
a cap: every active session is compared. No outcome-changing limit or
timeout was added.
- [x] Guide 4: cost per unit: Keyset paging on the UNIQUE session_id,
not OFFSET; three indexed queries per 512 sessions (sessions page,
raw_sessions IN on its primary key, candidate sessions IN on UNIQUE
session_id). The active pages come from one snapshot (explicit BEGIN on
the read connection). The candidate and source.db are read inside the
same writer-coordinator call, so no daemon write lands between pages.
- [x] Guide 5: interruption: The comparison is a read-only loop inside
one write_coordinator.run_sync call, like the readiness pass beside it;
it mutates nothing, so a cancel, kill, or restart mid-loop leaves
nothing to clean up, and the next settle recomputes it. It does not poll
cancellation; its cost is bounded by the active session count at three
indexed queries per page.
- [x] Guide 6: ordering and races: Check and promotion run in one writer
call (promote_cold_build_covering_active_index), so no daemon write
lands between them. Residual: an external CLI writer is not excluded by
the process-local lease (AGENTS.md Runtime), so a session written
straight to the active index after the comparison and before the pointer
swap is outside this check. That window is the same one the existing
baseline verify has. Recorded in unresolved.
- [x] Guide 7: failure classification: The coverage refusal is
deterministic and classified as non-retryable blocked, re-evaluated only
on changed evidence, not retried on a timer. Read faults from the three
connections are sqlite3 errors that the existing classifier maps (BUSY
to sqlite_busy retryable, CANTOPEN to sqlite_open_unavailable
retryable); none is turned into a negative answer. The refusal is
recorded in settlement status with reason active_coverage_incomplete and
emitted as daemon.cold_build.coverage_refused with registered fields
(reason, generation_id, sessions).
- [x] Guide 8: silent outcomes: The check decides a refusal and nothing
is skipped. Active sessions whose raw_id is NULL or no longer in
raw_sessions are deliberately not coverage obligations, because no
durable evidence remains that any build could replay, and rebuildable
state is never the authority. The require_active_coverage docstring
states this rule. The settle outcome stays 'blocked' with a named
reason, never 'complete', while coverage is missing.
- [x] Guide 9: cleanup on failure: All three read connections are opened
under contextlib.closing in one with-statement and close on every exit
path. The refusal acquires nothing: no pointer change, no receipt write,
no capacity observation (those run inside promote, after the check). An
unsettled candidate is still discarded at daemon shutdown by the
existing path.
- [x] Guide 10: identity and keys: Coverage is keyed by
sessions.session_id, the generated origin:native_id column. It stays
stable across raw revisions, so a candidate that accepted a newer
revision of the same source still covers the session. No hash, ID
formula, or receipt key changed.
- N/A Guide 11: lossless transforms: N/A: the change copies, replays,
and regenerates nothing. It only reads and refuses.
- [x] Guide 12: degenerate inputs: Missing active index: return. Empty
active (the automatic fresh-root build): the first page is empty and it
passes; the other running-daemon cold-build tests, which promote on a
fresh root, stay green. The pointer already resolving to the candidate,
or generation.promoted: return, and promote finishes the interrupted
publication. A page with no retained raws: skipped with continue.
raw_ids is never empty when rows is non-empty, so there is never an
empty IN ().
- [x] Guide 13 / contract 3: consumers: The new names are exported
through operations/intake_adapters.__all__ and the daemon seam
daemon/intake_adapters.__all__, and daemon/cli.py imports them from that
seam as it does its other cold-build names.
ColdBuildGeneration.promote's signature is unchanged, so tests calling
or patching it still apply. docs/maintenance.md (cold build source
baseline section) documents the refusal and its reason token. No CLI
option, config key, schema, or generated reference changed. The
--cold-build-index help text still describes promotion accurately.
- [x] Guide 14 / contract 5: tests fail when the behaviour is removed:
test_explicit_cold_build_keeps_sessions_the_active_index_serves drives
the real run_daemon_services with cold_build_index=True over an active
index holding a session whose raw is retained but whose file was deleted
outside the watched root. Red proof, run twice: with the check call
removed (first in cold_build.promote, job 3186; then in
promote_cold_build_covering_active_index, job 3213) the [False] case
fails at the active-still-serves assertion (test_daemon_cli.py:4122),
because the promoted candidate lost codex-session:cold-imported. The
[True] case proves there is no false refusal when coverage is complete.
The classifier test pins the typed mapping.
- [x] Guide 15 / contract 6: trust boundaries, secrets and private data:
Fixtures are synthetic Codex JSONL under tmp_path. The error text
carries only a count and one synthetic-origin session id. The diff holds
no operator paths, archives, or secrets.
- [x] Contract 1: criterion met on the production path: The acceptance
route is the production daemon cold build: the explicit flag, fair
intake into the candidate, settle_cold_build, and promotion or refusal.
Evidence: job 3223 (58 passed at f544fc6), including both
parametrizations of the new daemon test, plus the two red runs above.
- [x] Compatibility, Limits, and daemon/AGENTS.md rules: The diff has no
shim, alias, or dual path. settle_cold_build now calls the wrapper
instead of generation.promote, and the direct call is gone. No cap or
timeout was added. The comparison runs inside the daemon's single writer
route (write_coordinator.run_sync), so it needs no
declared_unguarded_write, and it abandons no in-progress work.

**polylogue-8j9rh**: 2 pass(es) against
`docs/review/codex-review-guide.md`, `worker-contract generic list
(/realm/project/sinnix/dots/_ai/skills/orchestrate/references/worker-contract.md)`
- [x] Guide 1: Siblings and owners: Every excision route resolves
targets through _resolve_session_excision_target (grep of
resolve/apply/plan_session_excision outside excision.py: CLI excise.py,
operations/mutation_actuators.py, security/lifecycle.py, all via
plan_/apply_session_excision), so the sidecar reach covers CLI, daemon
actuator, lifecycle and cascade members alike. Ownership duplicates a
decision the joins own
(sources/live/tool_result_sidecars._join_from_index,
prepared_message_sink.GeminiToolOutputIndex.join); pass 1 found my first
predicate diverged from them: it read only matched events, so an owned
but refused file (size_exceeded, read_error, value-bound, less-complete)
with a pointer-only name stayed behind. Fixed by reading the joins' own
recorded outcome: every sidecar event of the session names an owned file
except no_owning_* debt, the joins' single ownerless reason (both
literals checked). The exact-stem rule is kept for files the join never
recorded. Sidecar modules are in the derived-identity closure
(docs/plans/schema-closure-baseline.json:338,345,348,384), so I kept the
rule in security/excision.py (not in the closure) and did not touch
them; schema-closure gate ok.
- [x] Guide 2: The fix itself: Resolution is read-only and adds no
exception type: a corrupt session_events payload raises from json.loads
and the excision refuses before any tier is touched, same as other index
reads. Pass 1 found a mypy error from reusing the name directory
(Path|None vs str) in _gemini_owned_sidecar_raw_ids; renamed to
scope_directory. A retry after an interrupted apply re-resolves:
already-deleted sidecar raws are simply absent, so it is idempotent.
Sidecar raws carry per-raw pending logical keys
(source_write.pending_raw_logical_source_key), so seeding them into
_durable_revision_closure does not widen to other files.
- [x] Guide 3: Memory and limits: Pass 1 found the first gemini resolver
fetchall'd every retained path under the project's tool-outputs/, which
grows with the project. Replaced by deriving candidates from the chat
identity's colon prefixes (at most a few range queries) and made the
scope query iterate its cursor. Remaining fetchalls are bounded by one
session (its tool_result tool ids, its sidecar events, its transcript
paths), the same bound as the existing block_ids read. No cap or
truncation added.
- [x] Guide 4: Cost per unit: Per transcript path one indexed range
query on raw_sessions.source_path (idx_raw_sessions_source_path,
source.py:457), using a half-open range rather than LIKE so the index
stays usable; paths are deduplicated across revisions. One extra bounded
revision-closure call per resolution. Cost is per excised session, not
per archive.
- N/A Guide 5: Interruption: N/A: the change adds reads to the up-front
resolution only; the apply's per-tier transactions, ordering and receipt
logic are unchanged.
- [x] Guide 6: Ordering and races: apply_session_excision already
resolves under exclude_archive_blob_publishers; sidecar raws are
resolved in the same source read as the other raw targets, so they share
that exclusion. The dry-run/apply gap is the existing contract for every
raw class.
- [x] Guide 7: Failure classification: No except clause added (grep of
the diff for 'except': 0). Query failures propagate and the resolve
refuses.
- [x] Guide 8: Silent outcomes: Owned files that ended as refused debt
were a silent residual in pass 1 (fixed, see item 1). Files no
transcript claims (no_owning_* debt, e.g. an orphan in tool-results/)
are deliberately kept, stated in the module docstring and
docs/security.md, and pinned by the subagent and gemini tests; whether
the receipt should name them is listed in unresolved. The plan and
receipt count the reach as source_sidecar_rows.
- N/A Guide 9: Cleanup on failure: N/A: nothing is acquired; resolution
only reads.
- [x] Guide 10: Identity and keys: No hashed field, ID formula or key
changes. Filenames are compared exactly as RetainedSidecarFile.filename
derives them (Path(source_path).name), and the stem uses the join's own
rsplit('.', 1).
- N/A Guide 11: Lossless transforms: N/A: no copy, replay or
regeneration path changed.
- [x] Guide 12: Degenerate inputs: Empty ownership skips the scan;
session id without a native part, no transcript raws, or a session
missing from the index yields no sidecars; a filename without an
extension uses the whole name, as the join does; a gemini native id
always has two colons (gemini_cli_chat_identity), and a candidate that
is not one path component is refused by resolve_tool_outputs_dir.
- [x] Guide 13: Consumers: New ExcisionTarget.sidecar_raw_ids and
ExcisionPlan.source_sidecar_rows (keyword-only construction, grep
'ExcisionPlan(' / 'ExcisionTarget(': only excision.py), plan.as_dict
key, receipt counts key, CLI preview line (cli/commands/excise.py),
docs/security.md section. No exact-key-set assertions on plan or counts
exist in tests (grep). No predecessor to delete: the strict xfail marker
is removed.
- [x] Guide 14: Tests and stubs: All four sidecar tests drive
LiveBatchProcessor acquisition and apply_session_excision. Red
conditions: dropping the sidecar seed fails
test_excising_a_forgets_the_tool_output_only_it_had (A-only raw
retained, hash unmarked); owns() returning true fails
test_excising_a_parent_keeps_its_subagents_sidecar (subagent raw
removed); ignoring sidecar events fails it too (the parent sidecar
b7x3kq.txt is pointer-named, not stem-named); dropping the gemini branch
fails test_excising_a_gemini_chat_forgets_its_tool_output_sidecar
(slug-named file only the event names). No monkeypatch targets touched.
- [x] Guide 15: Trust boundaries: Paths and filenames come from
source.db and index.db and are used only in bound SQL parameters and
comparisons; gemini candidates pass resolve_tool_outputs_dir's
single-component check. No secrets or logging added.
- [x] Contract 1: criteria met on the production path: Each acceptance
clause is exercised through production acquisition and
apply_session_excision (job 3162, 89/89 passed at d69c649); see the
bead criteria.
- [x] Contract 2: defect class handled at every site: The class is
tool-output sidecars no excision reach names. Sidecar artifact rules
exist for exactly two origins (grep kind="tool_result_sidecar" in
sources/origin_specs.py: 2 hits, Claude Code and gemini-cli); both are
covered and tested. The other sidecar-bearing table, history_sidecars,
has no writer in the package (grep 'INSERT INTO history_sidecars': 0)
and carries no session key.
- [x] Contract 3: consumers updated, predecessor deleted: Same as guide
item 13; the xfail and the module docstring's 'does not yet reach' text
are removed.
- [x] Contract 4: failure paths typed and visible: No fallback or
swallowed error; unclaimed files are a documented, tested decision, and
the open question is in unresolved.
- [x] Contract 5: each new test fails when its behavior is removed: See
guide item 14 for the change that turns each test red.
- [x] Contract 6: no secret, private path or personal data: Fixtures are
synthetic (invented uuids, zz_* text, -realm-project-sub following the
existing fixture pattern). Scratch output stayed in the session
scratchpad and is not committed; .agentctl/ is untracked.

**polylogue-b8of0**: 1 pass(es) against
`docs/review/codex-review-guide.md`,
`/realm/project/sinnix/dots/_ai/skills/orchestrate/references/worker-contract.md
(generic list)`
- [x] codex-review-guide 1. Siblings and owners: The defect class is a
test that forces its restart deferral through a knob the product no
longer reads. #5691 (b5fd10a) retired the parse-stage warm deadline,
so POLYLOGUE_LIVE_WATCHER_PARSE_STAGE_WARM_TIMEOUT_SECONDS became inert,
the first restart page admitted the tail, and the all-DEFERRED assertion
at tests/unit/sources/test_live_ingest_kill_recovery.py:275 failed (job
3061 at base 0914f89). I checked for other sites. `grep -rln
'WARM_TIMEOUT|warm_timeout|warm window' polylogue tests docs devtools`
finds only a prose comment at
polylogue/sources/live/parse_prefetch.py:1928 and no knob. Tests set 61
distinct POLYLOGUE_* variables with setenv or delenv; 57 are read in
polylogue/ or devtools/. POLYLOGUE_LIFECYCLE_RECEIPT_DIR is read by
tests/infra/daemon_service_harness.py:29, and the POLYLOGUE_TEST_* pair
is forged input in a devtools test. That leaves POLYLOGUE_DB_PATH as a
possibly stale knob, recorded in unresolved. The diff adds no product
predicate. It reuses the deferral producer that remains (a failing
live_parse_path_worker fills preparation_deferred and
_defer_full_cursor_retry, polylogue/sources/live/batch.py:1792-1800),
and tests/unit/sources/test_live_watcher_parse_stage_equivalence.py:877
and :929 drive the same producer.
- [x] codex-review-guide 2. The fix itself: The failing worker is
installed with monkeypatch and restored explicitly before the final
admission, so the watcher's own process stage prepares the tail and
pytest teardown restores the patch again. The injected thread
LiveParseStage is shut down in a finally block. LiveWatcher does not own
an injected stage (watcher.py:394 `_owns_parse_stage = parse_stage is
None`), so watcher.stop() leaves it alone and the test shuts it down.
The new `parse_stage` keyword on _admit_pages defaults to None, which
keeps the existing callers (_admit, the first-ingest test) on the
production default stage.
- N/A codex-review-guide 3. Memory and limits: N/A: the diff changes
only test code and adds no read, cache, buffer, cap or timeout.
- N/A codex-review-guide 4. Cost per unit: N/A: no product code changed.
The test still offers three restart pages, as before.
- [x] codex-review-guide 5. Interruption: This is the subject of the
test. A child SIGKILLed right after
revision_governance._write_parsed_precedence_result returns for the
append is followed by restart pages whose preparation defers. The test
asserts the index still holds (3, 3, 1) and that no page reports
DUPLICATE, then that the due retry materializes (6, 6, 1) with no parse
errors (job 3091 passed).
- [x] codex-review-guide 6. Ordering and races: The thread stage uses
max_workers=1, and three pages are offered sequentially on one watcher.
The retry is made due only after the pages, with the delay set to 0 and
defer_full_cursor_reconciliation called, as before. The diff adds no new
concurrency.
- [x] codex-review-guide 7. Failure classification: The synthetic
RuntimeError from the worker is the retryable worker-loss class. The
product defers it without spending the cursor failure budget
(test_deferred_preparation_does_not_spend_cursor_failure_budget), and
the restart pages report DEFERRED, which the test now proves again.
- [x] codex-review-guide 8. Silent outcomes: This is criterion
no-false-duplicate. Every restart page item carries a typed DEFERRED
outcome, 'source retry pending', from FileIntakeAdapter
(polylogue/operations/intake_adapters.py:853-860). A mutation run proves
the test catches a silent acknowledgement: with
classify_ingest_candidates returning `needed, ()` (watcher.py:592), job
3108 failed at the DEFERRED assertion
(test_live_ingest_kill_recovery.py:299) and two restart pages reported
DUPLICATE.
- [x] codex-review-guide 9. Cleanup on failure: stage.shutdown() runs in
a finally block even when a restart page raises. The parse-shard scratch
directory is under the test's state_dir (workspace_env), which pytest
removes.
- N/A codex-review-guide 10. Identity and keys: N/A: no hash, ID or key
changed.
- N/A codex-review-guide 11. Lossless transforms: N/A: no copy, replay
or regeneration path changed.
- N/A codex-review-guide 12. Degenerate inputs: N/A: the fixture keeps
the same six synthetic messages and adds no new input shape.
- [x] codex-review-guide 13. Consumers: The only interface change is an
optional `parse_stage` keyword on the test-local helper _admit_pages.
`grep -n '_admit_pages('
tests/unit/sources/test_live_ingest_kill_recovery.py` shows its three
sites (definition, _admit, the append test), and each is consistent. The
retired env knob has no remaining reader or setter anywhere, per the
item 1 grep.
- [x] codex-review-guide 14. Tests and stubs: The monkeypatch target,
parse_prefetch.live_parse_path_worker, is the name LiveParseStage
resolves when it submits (parse_prefetch.py:1221), so the patch reaches
the worker. The test drives the production route:
FileIntakeAdapter.admit_page over LiveWatcher with open_operation_read.
The only substitute is a thread stage in place of the process stage,
which the product supports (use_processes=False). Anti-vacuity: at base
the stale knob made the test fail (job 3061), and after the change the
pending-retry mutation makes it fail (job 3108).
- N/A codex-review-guide 15. Trust boundaries: N/A: the change handles
no secrets, credentials or file permissions.
- [x] worker-contract 1. Criteria met on the production path:
append-kill: job 3091 at 1b525da passed 2/2, including
test_sigkill_inside_an_append_index_write_recovers_exactly, which
asserts (6, 6, 1) and no parse errors through FileIntakeAdapter.
no-false-duplicate: the same test asserts all restart pages are DEFERRED
while the retry is pending, and the mutation probe (job 3108) shows it
fails when that is removed. The cold-build clause rests on code reading:
cold-build suspension applies only to RawMaterializationIntakeAdapter
(intake_adapters.py:1385, wired at daemon/cli.py:3071), and
FileIntakeAdapter has no suspension hook. No test runs this kill under
an unsettled cold build; that is recorded in unresolved.
- [x] worker-contract 2. Defect class handled at every site: See
review-guide item 1 for both greps (retired-knob references: 0 in tests
and product; tests' POLYLOGUE_* variables: 61 total, 1 possibly stale
variable recorded as unrelated).
- [x] worker-contract 3. Consumers updated, predecessor deleted: The
retired knob's last test use is removed. The product had already deleted
it in #5691, and no fallback or dual path was added.
- [x] worker-contract 4. Failure paths typed and visible: Restart pages
must report the typed DEFERRED outcome, and a silent DUPLICATE fails the
test (job 3108).
- [x] worker-contract 5. New tests fail when behavior is removed:
Removing the pending-retry split in classify_ingest_candidates
(returning `needed, ()` at polylogue/sources/live/watcher.py:592) turns
the test red at test_live_ingest_kill_recovery.py:299, with DUPLICATE
outcomes (job 3108; the mutation was reverted, and `git status --short`
is clean). Removing idempotent message identity or the retry's
materialization would turn the (6, 6, 1) assertion red.
- [x] worker-contract 6. No secrets or private data: The diff touches
only a synthetic test. The narration contains worktree paths and job IDs
but no operator data.

---------

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant