Skip to content

feat(sources): pre-parse watcher full-ingest candidates off the writer hold - #3301

Merged
Sinity merged 2 commits into
masterfrom
feature/feat/watcher-parallel-parse-stage
Jul 27, 2026
Merged

Sinity merged 2 commits into
masterfrom
feature/feat/watcher-parallel-parse-stage

Conversation

@Sinity

@Sinity Sinity commented Jul 27, 2026

Copy link
Copy Markdown
Owner

Summary

Adds LiveParseStage, an opt-in (default off) bounded thread pool that pre-parses the live watcher's small-JSONL full-ingest candidates before the writer hold is requested, mirroring the daemon census route's existing DaemonParseStage (polylogue-m6tp phase (a)) seam for the watcher's catch-up/live-batch route.

Problem

The live watcher's writer-held full-ingest pass (catch-up chunks and live batches) parses each small JSONL candidate synchronously while holding the single archive writer. That decode work is CPU-bound and has no dependency on the writer lock — it can run in parallel ahead of the hold, exactly as the daemon's raw-materialization census path already does via DaemonParseStage. This is one slice of the larger free-threading prep epic (polylogue-xikl); it does not close that epic.

Solution

  • polylogue/sources/live/parse_prefetch.py (new): LiveParseStage — bounded thread pool + path-keyed prewarm cache (LiveParsePrefetchCache). warm() is synchronous, always called via asyncio.to_thread, and never runs under the writer hold. LiveParsePrefetchCache.pop() re-verifies the cached parse's payload bytes match exactly before returning it — a live-appending file can grow between the prewarm read and the writer-held read, and any mismatch is treated as a cache miss (falls back to inline parsing, never returns a stale parse).
  • polylogue/sources/live/batch.py: _live_parse_stage_candidates() selects a strict subset — plain .jsonl provider-session files below _STREAMING_FULL_INGEST_BYTES — using the same detection helper (_jsonl_provider_and_session_artifact) the writer-held pass already uses, so provider identity can never diverge between prewarm and the real parse. _ingest_full_paths warms candidates before requesting the writer hold; a warm() failure never aborts ingestion — every candidate just falls back to inline parsing as before. _ingest_full_paths_sync bridges the path-keyed cache to the raw_id keyspace via cache.pop(str(path), payload=payload) the instant raw_id becomes known, still inside the writer hold.
  • polylogue/sources/live/watcher.py: LiveWatcher accepts an optional parse_stage; when unset and live_watcher_parse_stage_split is enabled, it creates and owns one, shut down in stop().
  • polylogue/config.py: live_watcher_parse_stage_split (off by default) + worker/inflight-bytes/warm-timeout overrides, following daemon_parse_stage_*'s existing conventions.
  • docs/configuration.md: documented the 4 new config keys (docs-coverage gate requires this).

Verification

  • mypy --strict clean on all touched files.
  • ruff check / ruff format --check clean.
  • New equivalence test (test_live_watcher_parse_stage_equivalence.py) proves flag-on vs flag-off produce byte-identical archive content over a real LiveBatchProcessor.ingest_files run, including an adversarial out-of-order-completion case (slowest-submitted file forced to finish last) asserting raw_sessions insertion order is unaffected by parallel parse completion order.
  • devtools test tests/unit/sources/test_live_watcher_parse_stage_equivalence.py tests/unit/sources/test_live_batch_convergence.py tests/unit/sources/test_live_batch_observability.py tests/unit/sources/test_live_batch_support.py — 75 passed.
  • devtools test tests/unit/sources/test_live_watcher.py tests/unit/sources/test_live_watcher_parse_stage_equivalence.py — 89 passed, 1 pre-existing failure (test_live_full_ingest_over_ambiguous_membership_fails_closed_with_diagnostic), confirmed unrelated via git stash of the 3 modified files against the exact same test (fails identically), plus structurally — the failing test's file type (browser-capture .json) is never selected by _live_parse_stage_candidates.
  • devtools verify --quick (format/lint/mypy/render-all-check/docs-coverage/etc.) green via the pre-push hook.

Ref polylogue-wf8a

Sinity added 2 commits July 27, 2026 07:50
…r hold

Problem: the live watcher's writer-held full-ingest pass (catch-up chunks
and live batches) parses each small JSONL candidate synchronously while
holding the single archive writer -- CPU-bound decode work that could run
in parallel ahead of the hold instead, mirroring the daemon census route's
existing DaemonParseStage (polylogue-m6tp phase a) seam.

What changed:
- polylogue/sources/live/parse_prefetch.py (new): LiveParseStage, a bounded
  thread pool + path-keyed prewarm cache. warm() is synchronous, called via
  asyncio.to_thread, and NEVER runs under the writer hold. LiveParsePrefetchCache.pop()
  re-verifies the cached parse's payload bytes match exactly before
  returning it -- a live-appending file can grow between the prewarm read
  and the writer-held read, and any mismatch is treated as a cache miss
  (falls back to inline parsing, never returns a stale parse).
- polylogue/sources/live/batch.py: _live_parse_stage_candidates() selects a
  strict subset -- plain .jsonl provider-session files below
  _STREAMING_FULL_INGEST_BYTES -- using the SAME detection helper
  (_jsonl_provider_and_session_artifact) the writer-held pass already uses,
  so provider identity can never diverge between prewarm and the real
  parse. _ingest_full_paths warms candidates before requesting the writer
  hold; a warm() failure never aborts ingestion, it only means every
  candidate falls back to being parsed inline as before.
  _ingest_full_paths_sync bridges the path-keyed cache to the raw_id
  keyspace via cache.pop(str(path), payload=payload) the instant raw_id
  becomes known, still inside the writer hold.
- polylogue/sources/live/watcher.py: LiveWatcher accepts an optional
  parse_stage; when unset and live_watcher_parse_stage_split is enabled,
  it creates and owns one, shut down in stop().
- polylogue/config.py: live_watcher_parse_stage_split (off by default) +
  worker/inflight-bytes/warm-timeout overrides, following
  daemon_parse_stage_*'s existing conventions.

Off by default (polylogue-wf8a). One slice of the larger free-threading
prep epic (xikl); does not close it.

Verification: mypy --strict clean on all touched files. ruff check/format
clean. New equivalence test (test_live_watcher_parse_stage_equivalence.py)
proves flag-on vs flag-off produce byte-identical archive content over a
real LiveBatchProcessor.ingest_files run, including an adversarial
out-of-order-completion case (slowest-submitted file forced to finish
LAST) that asserts raw_sessions insertion order is unaffected by parallel
parse completion order -- 75 passed across that file plus
test_live_batch_convergence.py/test_live_batch_observability.py/
test_live_batch_support.py. devtools test tests/unit/sources/test_live_watcher.py
tests/unit/sources/test_live_watcher_parse_stage_equivalence.py: 89 passed,
1 pre-existing failure (test_live_full_ingest_over_ambiguous_membership_fails_closed_with_diagnostic,
confirmed unrelated via git stash of the 3 modified files against the
exact same test, plus structurally -- the failing test's file type
(browser-capture .json) is never selected by _live_parse_stage_candidates).
devtools render topology-projection/topology-status regenerated for the
new module.

Ref polylogue-wf8a
Fix: docs-coverage flagged the 4 new watcher parse-stage config keys as
undocumented public surface. Added rows mirroring the existing
daemon_parse_stage_* documentation pattern.
@chatgpt-codex-connector

Copy link
Copy Markdown

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

@coderabbitai

coderabbitai Bot commented Jul 27, 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: 36 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 Plus

Run ID: e61a63d9-adaa-457a-b053-c4edba919da3

📥 Commits

Reviewing files that changed from the base of the PR and between 151be34 and b6dd1ff.

📒 Files selected for processing (8)
  • docs/configuration.md
  • docs/plans/topology-target.yaml
  • docs/topology-status.md
  • polylogue/config.py
  • polylogue/sources/live/batch.py
  • polylogue/sources/live/parse_prefetch.py
  • polylogue/sources/live/watcher.py
  • tests/unit/sources/test_live_watcher_parse_stage_equivalence.py
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/feat/watcher-parallel-parse-stage

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 added a commit that referenced this pull request Jul 27, 2026
@Sinity
Sinity merged commit 4e5db51 into master Jul 27, 2026
3 checks passed
@Sinity
Sinity deleted the feature/feat/watcher-parallel-parse-stage branch July 27, 2026 06:05
Sinity added a commit that referenced this pull request Jul 27, 2026
## Summary

Strengthens 5 test sites in
`tests/unit/sources/test_live_batch_support.py` that CodeRabbit flagged
on #3282 as asserting cursor-complete/non-retryable/deferred-debt
behavior only *indirectly* (via the in-memory `succeeded`/`failed`
batch-result lists) rather than the durable state those claims are
actually about. None were bugs — the assertions were correct, just less
protective against a future regression than they could be.

## Problem

CodeRabbit's review on #3282 identified 4-5 spots where tests check
`result.succeeded == [x]` / `result.failed == []` as a proxy for a
comment's claim about persisted state ("cursor advances", "deferred
authority debt persisted", "cursor is complete rather than retried",
"must remain retryable"), without ever reading the actual persisted
record. This was deferred rather than blocking #3282's merge (which
fixed the real critical bug CodeRabbit also found in that PR).

## Solution

-
`test_incomplete_full_jsonl_capture_retries_without_losing_split_record`:
this test goes through `LiveBatchProcessor.ingest_files`, which *does*
have a `CursorStore` row, and already checked it directly
(`final_cursor.byte_offset`/`failure_count`). The specific gap was the
FTS deferral claim: `record_convergence_debt(stage="fts", ...)` gets
called mid-parse but the **same** `ingest_files` call's own synchronous
convergence pass clears it again before returning — confirmed
empirically (`cursor.list_convergence_debt()` is `[]` either way,
recorded-then-cleared or never-recorded look identical from outside).
Added a spy on `CursorStore.record_convergence_debt` to prove the debt
row was actually recorded for the session before this batch's
convergence consumes it.
- `test_live_multi_session_divergence_reopens_raw_authority`,
`test_live_third_raw_reunifies_with_backfill_retired_siblings`,
`test_bundle_replay_respects_unconvertible_single_session_head`,
`test_single_session_full_cannot_overwrite_divergent_membership_head`:
these drive `LiveBatchProcessor` via `_ingest_full_paths_sync` directly
— a layer with **no `CursorStore` row of its own** (cursor persistence
happens one level up, inside `ingest_files`, confirmed by tracing
`batch.py`). The durable non-retry evidence at this layer is
`raw_sessions.parse_error` staying `NULL` (what a later full-ingest pass
treats as needing retry) plus, for the membership case, the
exact-path-scoped
`raw_session_memberships.decision`/`revision_authority` row. Added those
direct checks instead of a `cursor.get_record()` call that would always
return `None` at this layer.

Existing indirect assertions are all kept — only additive direct checks
were introduced.

## Verification

- `devtools test tests/unit/sources/test_live_batch_support.py` → `71
passed`.
- `ruff check` / `ruff format --check` / `mypy --strict` on the touched
test file → clean.
- **Anti-vacuity proof #1**: temporarily commented out
`self._cursor.record_convergence_debt(stage="fts", ...)` in
`polylogue/sources/live/batch.py` — the strengthened split-record test
failed (`assert False` on the spy check), where it previously would have
passed silently (the manual `repair_message_fts_index_sync` call masks a
missing debt). Reverted after confirming.
- **Anti-vacuity proof #2**: temporarily forced `decisions: dict[str,
str] = {}` in `apply_raw_membership_classification` (`archive.py`)
instead of populating from `classification.ambiguous_raw_ids` — the
strengthened divergence test failed on the new
`parse_error`/`decision`/`revision_authority` assertion, *before* the
file's own pre-existing indirect assertions further down even got a
chance to fail. Reverted after confirming.
- `devtools verify --quick`: found pre-existing
`docs/topology-status.md`/`docs/plans/topology-target.yaml` drift
inherited from #3301 (`LiveParseStage` added without the topology render
step) — unrelated to this change but blocking the pre-push gate for any
branch off current master. Folded in a small separate regen commit
(`devtools render topology-projection && devtools render
topology-status`) so the branch can push; `devtools render all --check`
now reports all surfaces sync OK.

Ref polylogue-y9d0

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

---------

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