Skip to content

fix(sources): parallelize raw-authority census parse; hjpx.2/yla8 evidence - #3122

Merged
Sinity merged 4 commits into
masterfrom
feature/repair/raw-authority-closure
Jul 18, 2026
Merged

Sinity merged 4 commits into
masterfrom
feature/repair/raw-authority-closure

Conversation

@Sinity

@Sinity Sinity commented Jul 18, 2026

Copy link
Copy Markdown
Owner

Summary

  • Parallelizes raw-authority census parse across a process pool and decouples the spill-cache bound from the resource-envelope block, fixing the CLI rebuild-index path's dead ingest_workers parameter and silent double-parse (polylogue-9p8x).
  • Delivers a read-only yla8 live-archive authorization packet recommending the operator hold the live catch-up gate.
  • Delivers an honest hjpx.2 proof-status report: mutation-proof laws verified via existing regression coverage, but the July-15-scale execution itself did not complete this session (4 self-aborts under genuine host I/O contention — receipts included).

Problem

maintenance/replay.py::rebuild_index_from_source accepted ingest_workers but immediately deleted it, funneling the CLI rebuild-index command's parser census into one sequential call. Its spill cache also never activated on that path because it received max_payload_bytes=None, so every accepted revision was reparsed during replay after census had already parsed it once (measured live: ~204 sessions/35min single-core).

Separately, hjpx.2 needed a July-15-archive-shape proof of raw-authority replay convergence, and yla8 needed a current live-archive preflight before any operator authorization decision.

Solution

  • polylogue/sources/revision_backfill.py: new _parse_retained_raws/_census_parse_worker spread read-only blob→ParsedSession decode across a ProcessPoolExecutor; archive writes still apply in fixed pending_rows order regardless of worker completion order, proven byte-identical to sequential (test_parallel_census_matches_sequential_archive_state). New max_cached_payload_bytes parameter decouples the spill-cache bound from the resource-envelope block (the two were previously the same parameter — passing a finite cache bound on the CLI's unbounded selected_raw_ids=None full-archive census would otherwise immediately raise RawRevisionReplayResourceBlockedError, since raw_membership_census_rows(None) returns every raw in the archive in one selection).
  • polylogue/storage/repair.py, polylogue/maintenance/replay.py: both gained ingest_workers, defaulting to a new shared resolve_parse_worker_count() (polylogue/pipeline/services/process_pool.py), so the daemon convergence path and the hjpx.2 scale-proof harness get parallel census automatically with no harness changes needed.
  • Rebased onto master's #3113 (Hermes SQLite-detection fix to _parse_one); added parity so the parallel worker threads the real on-disk blob path through for Hermes raws the same way the sequential path does.
  • .agent/reports/yla8-authorization-packet-2026-07-18.md: read-only live-archive audit (no mutation). Recommends holding authorization: no current verified backup (6 days stale), archive mid-restore (99.8% unmaterialized), and at observed throughput a full drain would take days-to-weeks without polylogue-5jak landing.
  • .agent/reports/hjpx2-july15-scale-proof-2026-07-18.md: verdict per law. Envelope/fairness/conservation/interruption-resume mechanisms are proven (via existing + this session's regression tests); daemon-health responsiveness is a confirmed harness gap (polylogue-agvo filed); the July-15-scale execution itself self-aborted 4 times under genuine, sustained host I/O contention (receipts included, plus a diagnostic finding that the generation phase may be self-inducing pressure — polylogue-cmw2 filed).

Alternatives rejected

  • The bead's own suggested one-line fix (max_payload_bytes=64MiB on the CLI path) was not applied as literally stated: it would have broken the unbounded full-archive rebuild by activating the resource-envelope block archive-wide. Introduced the separate max_cached_payload_bytes parameter instead.
  • Did not implement commit-batching (the bead's own "Fix 3 (optional)") to chase the originally-hypothesized 4x speedup — measured evidence (cProfile) shows SQLite commit overhead is comparable to parse time, so parse-parallelism alone cannot reach 4x; filed polylogue-amg1 as separately-scoped follow-up rather than force a larger, transaction-boundary-touching change into this PR.
  • Did not build a real-daemon-process harness for daemon-health responsiveness within this PR; that's a genuinely separate harness component (polylogue-agvo).

Verification

  • devtools test tests/unit/sources/test_revision_backfill.py: 18 passed
  • devtools test -k "raw_materialization or raw_authority": 148 passed
  • devtools test tests/unit/devtools/test_raw_authority_scale_proof.py: 21 passed
  • devtools test tests/unit/devtools/test_raw_authority_restart_proof.py: 4 passed
  • devtools test tests/unit/storage/test_incremental_rebuild_equivalence.py tests/unit/cli/test_archive_maintenance_cli.py: 58 passed
  • devtools verify --quick: exit 0 (16/16 steps), green after every commit

AC matrix

  • polylogue-9p8x: Fix 1 (honor ingest_workers) and Fix 2 (decouple spill cache) — satisfied, tested. AC4 (≥4x measured speedup) — not satisfied, corrected by evidence to ~1.2-1.7x (Amdahl-limited); deferred to polylogue-amg1.
  • polylogue-yla8: read-only packet delivered per spec; no live mutation. Not closed (that decision is the operator's, per the packet's own yes/no question).
  • polylogue-hjpx.2: mutation-proof laws (envelope, fairness, conservation, interruption/resume) — proven via regression. Daemon-health responsiveness — not provable with current harness, polylogue-agvo filed. July-15-scale execution (AC1/AC6/AC7) — not achieved this session; 4 honest self-abort receipts recorded, polylogue-cmw2 filed for the generation-phase self-induced-pressure finding. Bead remains open, not force-closed.

Ref polylogue-9p8x
Ref polylogue-yla8
Ref polylogue-hjpx.2

Co-Authored-By: Claude [email protected]

Sinity and others added 4 commits July 18, 2026 19:11
…cache

Problem: maintenance/replay.py::rebuild_index_from_source accepted
ingest_workers but deleted it, funneling the offline rebuild-index CLI
path's parser census into one sequential asyncio.to_thread call. Its
spill cache (_ParsedSessionSpill) also silently disabled caching
because the CLI path passed max_payload_bytes=None, so every accepted
revision was reparsed during replay after census already parsed it
(measured live: ~204 sessions/35min single-core, polylogue-9p8x).

Solution: _census_historical_revision_evidence now parses pending raws
through a new _parse_retained_raws helper that spreads read-only
blob->ParsedSession decode across a ProcessPoolExecutor
(polylogue/sources/revision_backfill.py); archive writes still apply
in fixed pending_rows order regardless of worker completion order, so
parallel and sequential runs are byte-identical (proven by
test_parallel_census_matches_sequential_archive_state). Introduced
max_cached_payload_bytes as a spill-cache bound independent of
max_payload_bytes (the resource-envelope block): the two were
previously the same parameter, so passing a finite cache bound on the
CLI's unbounded (selected_raw_ids=None) full-archive census would have
immediately raised RawRevisionReplayResourceBlockedError, since
raw_membership_census_rows(None) returns every raw in the archive in
one selection. repair_raw_materialization (storage/repair.py) and
rebuild_index_from_source both gained ingest_workers, defaulting to a
new shared resolve_parse_worker_count() (process_pool.py), so the
daemon convergence path and the hjpx.2 scale-proof harness
(devtools/raw_authority_scale_proof.py, unmodified) get parallel
census automatically. archive_ingest.py's existing worker-count helper
now delegates to the shared resolver instead of duplicating it.

Evidence-driven correction to the original AC: cProfile on a synthetic
60-raw/1.7MB-avg-payload corpus shows SQLite commit/fsync
(sqlite3.Connection.__exit__) at 42.6% of wall time versus parse at
40.6% -- comparable, not parse-dominated. Parallelizing only the parse
share caps realistic speedup near 1.7x (Amdahl), not the originally
hypothesized 4x; measured 1.22x on 200 small (~50KB) payloads and 0.63x
(worse) on 80 larger (~1.7MB) payloads, where cross-process pickling of
parsed sessions exceeded the parse-time savings. Filed polylogue-amg1
for the remaining commit-batching/size-aware-dispatch levers rather
than forcing that larger, transaction-boundary-touching change into
this fix.

Verification:
- devtools test tests/unit/sources/test_revision_backfill.py: 18 passed
- devtools test -k raw_materialization: 91 passed
- devtools test -k raw_authority: 57 passed
- devtools test tests/unit/storage/test_incremental_rebuild_equivalence.py
  tests/unit/cli/test_archive_maintenance_cli.py: 58 passed
- devtools verify --quick: exit 0 (16/16 steps)

Ref polylogue-9p8x

Co-Authored-By: Claude <[email protected]>
Problem: yla8 needs a current live-archive preflight before the operator
can decide whether to authorize the ordinary catch-up gate, but the
archive is mid-restore from the same-day poisoned-index incident and
its own authority proof (hjpx.2) has not completed at scale yet.

Solution: read-only packet (no live mutation) comparing current
population counts against the 2026-07-15 baseline, a backup-manifest
currency verdict (most recent verified backup is 6 days stale),
a blocker inventory citing polylogue-5jak/emx2/5vft/hjpx.2, and the
exact apply command for reference. Recommendation is to hold
authorization; ends with the single yes/no question for the operator.

Verification: read-only commands only (`ops status --json --full`,
`ops backup --check`); no archive mutation.

Ref polylogue-yla8

Co-Authored-By: Claude <[email protected]>
Problem: hjpx.2 needs a proof-report artifact recording verdict per
law (envelope/health/fairness/fixed-point/mutations) regardless of
whether the July-15-scale execution itself completes this session.

Solution: report distinguishes proven-at-small-scale (envelope,
fairness, conservation, interruption/resume, pressure-gate mutations
-- all verified passing this session, several inherited from prior
PRs like #3080/#3029/#3031) from genuinely unproven (daemon-health
responsiveness -- confirmed no harness runs an actual daemon process
to probe; filed polylogue-agvo) and not-yet-executed-at-cardinality
(the July-15-shaped run itself -- three self-aborts under sustained,
genuine host I/O contention across 4+ concurrent warroom lanes,
receipts recorded). Explicitly states hjpx.2 is not closable this
session rather than forcing a close on unmet AC.

Verification: cited tests re-run and confirmed passing (see report
for exact node list); no archive mutation.

Ref polylogue-hjpx.2

Co-Authored-By: Claude <[email protected]>
…us worker

Problem: rebasing polylogue-9p8x's parallel census parse (8a1f827)
onto master's #3113 (Hermes SQLite-detection fix to _parse_one) left
_census_parse_worker calling _parse_one without payload_path/
archive_root, unlike the sequential parse_retained_raw_sessions.
Functionally harmless (the bounded temp-file spill fallback in
_sqlite_payload_path still parses correctly) but loses the "prefer the
already-materialized blob path, no copy" optimization #3113 added, and
the parallel path had no regression coverage proving it matches the
sequential path's parameter threading for Hermes state.db/
verification_evidence.db raws specifically.

Solution: thread payload_path (only computed for Provider.HERMES,
verified to exist on disk first) and archive_root through the worker's
_parse_one call, matching parse_retained_raw_sessions exactly. Added
test_parallel_census_threads_hermes_sqlite_payload_path (two
independent single-session state.db raws, forcing ingest_workers>1 to
actually dispatch through the pool) and updated this report with the
fourth self-abort receipt plus a diagnostic finding: attempts 3 and 4
both aborted at the identical code location right after generation
began, despite attempt 4 requiring 5 minutes of sustained external
quiet beforehand -- suggesting the generation phase's own I/O may be
self-inducing the pressure gate, not purely external contention. Filed
polylogue-cmw2 to investigate.

Verification:
- devtools test tests/unit/sources/test_revision_backfill.py: 18 passed
- devtools test -k "raw_materialization or raw_authority": 148 passed
- devtools verify --quick: exit 0 (16/16 steps)

Ref polylogue-9p8x
Ref polylogue-hjpx.2

Co-Authored-By: Claude <[email protected]>
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@coderabbitai

coderabbitai Bot commented Jul 18, 2026

Copy link
Copy Markdown

Warning

Review limit reached

@Sinity, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 15 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 690d3690-bdbf-4666-8f92-9f5cbf03136e

📥 Commits

Reviewing files that changed from the base of the PR and between b563083 and f2f8642.

📒 Files selected for processing (10)
  • .agent/reports/hjpx2-july15-scale-proof-2026-07-18.md
  • .agent/reports/yla8-authorization-packet-2026-07-18.md
  • polylogue/maintenance/replay.py
  • polylogue/pipeline/services/archive_ingest.py
  • polylogue/pipeline/services/process_pool.py
  • polylogue/sources/revision_backfill.py
  • polylogue/storage/repair.py
  • tests/unit/cli/test_archive_maintenance_cli.py
  • tests/unit/sources/test_revision_backfill.py
  • tests/unit/storage/test_incremental_rebuild_equivalence.py
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/repair/raw-authority-closure

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@Sinity
Sinity merged commit a53785b into master Jul 18, 2026
3 checks passed
@Sinity
Sinity deleted the feature/repair/raw-authority-closure branch July 18, 2026 17:26
Sinity added a commit that referenced this pull request Jul 19, 2026
## Summary

- `process_pool_context()` now unconditionally returns a `spawn`
multiprocessing context instead of preferring `forkserver` when
available.
- Added a config-assertion test pinning the exact start method, and a
regression test that dispatches a real pool from a worker thread
(mirroring the production `asyncio.to_thread -> pool -> as_completed`
shape) and asserts bounded-timeout completion.

## Problem

Production `ops maintenance rebuild-index` sat 17+ minutes at 16% CPU
with zero index-generation growth (2026-07-19). `py-spy` showed the
parent process parked forever in `as_completed`
(`revision_backfill.py:719`) while the forkserver process sat alive in
its serve loop — the multiprocessing resource-tracker and forkserver
were both running, but **zero pool workers were ever spawned**. Killing
the run and resuming with `POLYLOGUE_INGEST_PARSE_WORKERS=1` (the
sequential escape hatch) immediately went to 97% CPU and the generation
resumed growing, confirming the pooled dispatch path itself was the
failure, not the parse work.

This pooled dispatch branch (`_parse_retained_raws` in
`sources/revision_backfill.py`) had effectively been dead code before
#3122 (merged 2026-07-18) — `ingest_workers` was previously accepted and
immediately discarded. The very first real exercise of the
newly-activated pool hit this hang within ~8 hours of that merge.

## Investigation

`forkserver` forks every worker from a single process that preloads
`__main__` once via `runpy.run_path(sys.argv[0],
run_name="__mp_main__")` at forkserver boot. In production `sys.argv[0]`
resolves to `.venv/bin/polylogue`, whose top-level code is `from
polylogue.cli import main` — so the forkserver process runs polylogue's
entire CLI import graph before ever forking a worker. Any thread or lock
created as a side effect of that import would be inherited (already
running/held) by every subsequently forked worker, which is a well-known
forkserver hazard class.

An extended repro that isolates exactly this shape — a real script file
(so `sys.argv[0]` resolves like production), top-level `from
polylogue.cli import main`, then dispatching `process_pool_executor()`
from a worker thread under both `forkserver` and `spawn` — completed in
0.6s under **both** contexts. So the leading hypothesis from the initial
triage does not reproduce synthetically in isolation; the exact trigger
inside the live forkserver preload was not pinned down further within
the investigation timebox. Full bisect trail is recorded on
`polylogue-p0pw`.

## Solution

Per the fix direction agreed in the bead notes, applied the
unconditional-safe option rather than continuing to chase the exact
trigger: `spawn` reruns `__main__` fresh per worker instead of forking
one shared preloaded process, so no thread/lock state created during CLI
import can ever be inherited by a worker. This structurally eliminates
the whole class of inherited-state hazards forkserver is exposed to,
independent of whether the precise trigger is later identified. The cost
is ~1-2s import per worker, which is acceptable since pool workers here
are long-lived and reused across many parse tasks, not spun up per task.

Modules touched: `polylogue/pipeline/services/process_pool.py` (the fix
+ explanatory docstring), `tests/unit/pipeline/test_process_pool.py`
(two new tests).

## Audit (report only, no code change)

Per AC item 4 ("verify daemon census throughput with pooling active"),
audited whether the daemon's convergence process pool or the #3122-wired
census pool has ever actually parallelized in production:

- `DaemonConverger.start()` logs `"started with N worker(s)"` when any
`ConvergenceStage` is `cpu_bound=True`, else `"started without worker
pool"`. `journalctl` across 30+ `polylogued` restarts (2026-07-16..19)
shows **only** `"started without worker pool"` — zero exceptions. Every
registered stage (`fts`, `embed`, `claude_workflow`, `insights`,
`standing-queries`) sets `cpu_bound=False`, so this pool has never
activated. This corroborates the independent finding on `polylogue-7uqr`
(converger pool machinery is dead), which I cross-linked.
- The #3122-wired census/replay pool is reachable from a live daemon via
the HTTP `--daemon` bridge (`daemon/http.py`), but `journalctl` shows
every `ops maintenance rebuild-index` invocation on this host was a
direct CLI run, never with `--daemon` — so that variant has zero
production exercise to date.
- Filed `polylogue-7saq` as separate follow-up debt:
`archive_ingest.py`'s `parse_sources_archive()` builds its
`ProcessPoolExecutor` directly without going through
`process_pool_context()`, so it uses the platform-default start method
(`fork` on this host) — a strictly more dangerous hazard class than
forkserver. Currently reached only by the public async API facade and
demo seeding, not the daemon's normal ingest ticks (which already go
through the now-fixed `process_pool_executor()` helper) — out of this
PR's scope.

## Acceptance criteria

1. **Reproduce or conclusively explain the forkserver no-worker
deadlock** — partially satisfied: mechanism explained (forkserver forks
every worker from one preloaded process that runs the full CLI import
graph in production), but not conclusively reproduced in isolation — the
isolated import+dispatch repro passed under both contexts. Documented
honestly on the bead.
2. **Switch to a start method that demonstrably spawns workers under a
threaded parent** — satisfied: `spawn`, verified by the new regression
test.
3. **Regression test that a pool dispatch from a worker thread
completes** — satisfied
(`test_process_pool_dispatch_from_worker_thread_completes`). Note: this
test does not reproduce the pre-fix hang either, consistent with the
repro gap above — it's a forward-looking guard, not proof the pre-fix
code fails it.
4. **Verify daemon census throughput with pooling active** — answered
via audit above: no production daemon-census throughput exists yet to
measure (the pooled path has only run via direct CLI so far).
5. **Remove/keep the `workers=1` escape hatch documented** — kept as-is;
`resolve_parse_worker_count()`'s existing `env_var` override remains the
documented escape hatch.

## Verification

- `devtools test tests/unit/pipeline/ -k process_pool` — 7 passed in
8.05s.
- `devtools verify --quick` — all 16 steps green (ruff format/check,
mypy --strict, render all --check, topology/layering/closure-matrix,
schema roundtrip, manifests, ci-workflows, doc-commands, docs-coverage,
test-infra-currency, test-clock-hygiene, pytest-timeout-overrides,
degrade-loudly).
- Not run: full `devtools verify --all` / broad pytest suite (per-PR CI
intentionally skips the heavy suite; will run post-merge on master per
repo convention).

Ref polylogue-p0pw

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

Co-authored-by: Claude <[email protected]>
Sinity added a commit that referenced this pull request Jul 19, 2026
…er churn (#3149)

## Summary

Pool dispatch in `_parse_retained_raws` now requires the pool-eligible
aggregate payload to clear an amortization floor (default 48MiB,
`POLYLOGUE_REVISION_PARSE_POOL_MIN_BYTES` override); below it the batch
parses sequentially in-process. This stops the worker-churn pathology
where "parallel" census was nearly 100% spawn/import overhead.

## Problem

Measured live on the 2026-07-19 bulk rebuild (py-spy `--subprocesses`,
25s at 150Hz): **20 pool workers spawned in 25 seconds, each alive
~1.5-2.0s, spending ~95% of their lifetime inside `importlib`**
(`spawn_main → _find_and_load → exec_module`), with visible gaps where
no workers existed at all. Mechanics: census dispatches per-cohort
batches of 1-2 sub-256KiB raws; `_parse_retained_raws` creates a fresh
`ProcessPoolExecutor` per call with `max_workers=min(workers,
len(pool_raw_ids))` (=2); every spawn-method worker (#3143) re-imports
the full polylogue CLI graph (~1.4s — the polylogue-h1wt import tax, now
paid per worker per call) before parsing for milliseconds. Sequential
mode was strictly faster. The daemon's per-component census path (#3122)
has the same call shape.

## Solution

- New `_pool_dispatch_amortizes(pool_raw_ids, payload_sizes)`: pool only
when the pool-eligible aggregate clears
`_parse_pool_min_aggregate_bytes()` (default 48MiB — derived in the
docstring from ~20MB/s sequential small-payload parse vs ~2s worker
spawn+import at 8 workers; env-overridable). The existing per-raw size
partition (#3136, keeps >256KiB payloads off the pool) is unchanged;
genuinely large small-payload batches keep the pool path.
- Deliberately NOT a shared long-lived executor: that would fix churn
too but parks ~8 idle spawn workers (~0.5GB+ RSS with polylogue
imported) inside the long-running daemon; the floor gets ~all of the win
with zero idle cost. Recorded as a future option on polylogue-crd8
alongside the h1wt import-tax reduction which would lower the floor.

## Verification

- `devtools test tests/unit/sources/test_revision_backfill.py` — 27
passed.
- New tests: `test_pool_dispatch_floor_rejects_small_aggregate_batches`
(decision thresholds, env override, invalid-env fallback) and
`test_parse_retained_raws_small_batch_never_creates_a_pool` (end-to-end:
a sub-floor batch must never construct a `ProcessPoolExecutor` —
monkeypatched constructor raises). Anti-vacuity verified via stash of
the implementation file: both fail on pre-fix code (`2 failed`), pass
with it restored.
- `devtools verify --quick` — exit 0.

Ref polylogue-crd8

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

https://claude.ai/code/session_01QUsH3Rhq6oAZpYPWcsZqnZ

Co-authored-by: Claude <[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