Repository navigation
perf(sources): thread-parallel census parse under free-threaded Python - #3161
Conversation
Problem: polylogue-7mtf's control-run measurement proved GIL-build threads give zero parse speedup (0.93x-0.96x) and inflate a concurrent writer thread's commit latency ~5000x (208ms vs ~5ms cadence) when CPU-bound parse threads run alongside it. Under a genuinely free-threaded interpreter (3.14t), the identical ThreadPoolExecutor code measured 3.9x-9.6x speedup (w=4..16) with zero writer interference. The process-pool parse path in _parse_unique_retained_raws (sources/revision_backfill.py) carries two GIL-only costs -- pickle-back of ParsedSession graphs (#3136, 0.63x/net-loss above 256KiB) and per-worker spawn+import tax (#3149, ~1.5-2s floor) -- that simply don't exist for threads sharing one already-imported interpreter. Solution: - polylogue/pipeline/services/process_pool.py: add parallel_threads_effective(), a sys._is_gil_enabled()-backed probe (AttributeError -> "GIL enabled", the safe default for pre-3.13 interpreters). Resolved via getattr rather than a literal attribute expression so mypy --strict needs no per-version type: ignore. - polylogue/sources/revision_backfill.py: _parse_unique_retained_raws routes to a new _parse_unique_retained_raws_via_threads whenever parallel_threads_effective() is true, applying NO size partition and NO amortization floor (both exist solely to protect the process-pool's two named costs, which threads don't pay). The GIL-build ProcessPoolExecutor path below is otherwise byte-for-byte unchanged -- it remains the deployed daemon's fallback until the daemon itself migrates to 3.14t (a later, separate step per the epic's deployment ordering). - The thread path dispatches the existing _census_parse_worker function (unchanged), NOT _parse_retained_raw(archive, raw_id) directly: ArchiveStore lazily opens its source.db connection with the default check_same_thread=True, so calling archive.raw_revision_descriptor from a worker thread other than the connection's owning thread raises sqlite3.ProgrammingError (confirmed empirically). _census_parse_worker never touches the shared ArchiveStore -- only a fresh, stateless ArchiveBlobPublisher built from primitive strings, whose blob reads are plain filesystem I/O. - Two pre-existing tests asserting process-pool-specific size-partition/floor mechanics now pin parallel_threads_effective() to False, since those claims are GIL-build-fallback-specific and would otherwise depend on which interpreter runs the suite. Verification: - devtools test tests/unit/sources/test_revision_backfill.py tests/unit/pipeline/test_process_pool.py: 41 passed (standard GIL build). - Anti-vacuity: temporarily made _parse_unique_retained_raws_via_threads drop the first raw_id from dispatch; all 4 new thread-path tests failed (KeyError / missing session rows); reverted, all 41 pass again. - mypy --strict polylogue/pipeline/services/process_pool.py polylogue/sources/revision_backfill.py tests/unit/{pipeline/test_process_pool,sources/test_revision_backfill}.py: clean. ruff check/format --check: clean. devtools verify --quick: exit 0. - Real 3.14t smoke: built a scratch venv via `nix shell nixpkgs#python314FreeThreading` (orjson deliberately excluded -- polylogue-xikl.3's core/json.py facade falls back to msgspec, no shim needed), ran the same two test modules: 41/41 pass with parallel_threads_effective() naturally True (unforced). A broader tests/unit/sources + tests/unit/pipeline sweep under the same interpreter found 14 pre-existing failures in unrelated modules (live/batch, validation_flow, parsing_service, quarantine, drive mocks); spot-verified one (test_ingest_empty_sources_returns_empty_result) reproduces identically on the standard GIL 3.13.13 devshell, confirming pre-existing/unrelated rather than caused by this change. Ref polylogue-xikl.4, polylogue-xikl Co-Authored-By: Claude <[email protected]>
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
|
Warning Review limit reached
Next review available in: 58 minutes Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available. How can I continue?After more reviews become available, a review can be triggered using the 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 configurationConfiguration used: Path: .coderabbit.yaml Review profile: ASSERTIVE Plan: Pro Run ID: 📒 Files selected for processing (4)
✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
…c) (#3162) ## Summary Adds `packages.polylogue-freethreaded`: the polylogue CLI built on `pkgs.python314FreeThreading` with the dependency set adjusted per the #3155 facade (orjson dropped — no free-threaded wheels/build upstream yet; msgspec added as the fast JSON backend), plus the `overrideScope`-based check/doc-closure overrides required to build the dependency set on the free-threaded interpreter. ## Problem The free-threading adoption program (`Ref polylogue-xikl`; gate results on `polylogue-7mtf`: 3.9-9.6x thread-parallel parse at ~7.7% single-thread tax, zero writer interference vs ~5000x under GIL) needs a runnable 3.14t artifact. The deployment edge is CLI-first: the offline bulk rebuild can run free-threaded with zero daemon blast radius. orjson refuses free-threaded compilation upstream, which #3155 made survivable via the three-tier backend facade. ## Solution - `flake.nix`: `polylogue-freethreaded` package on `python314FreeThreading` via `overrideScope` (the earlier `.override { packageOverrides }` form was verified ineffective at the derivation level and replaced); dependency deltas: `-orjson +msgspec`; targeted `doCheck`/doc-input removals for chain members whose test/doc closures fail under 3.14t (inventory in the flake comments). - Provenance note: this branch was authored by a lane agent that stalled in a build-wait loop one derivation short of success; the coordinator salvaged the uncommitted work, completed the build, and ran the acceptance below. ## Verification - `nix build .#polylogue-freethreaded` → `/nix/store/j942p5kkbl42w2pjbh7vggwdlcspil7q-python3.14t-polylogue-0.3.0` (cached-clean rebuild reproduces in seconds). - GIL proof: closure interpreter `python3-3.14.4` → `sys._is_gil_enabled() == False`. - Demo cold-pass ON the free-threaded binary (clean env): `polylogue demo seed` + `demo verify` → `Demo archive verification: ok — Sessions 16, Messages 62, Query hits 4`. - `polylogue --version` → `0.3.0+2123ea55`; `--help` clean. - Known caveat (follow-up, not blocking): the bin wrapper inherits the caller's `PYTHONPATH` — a 3.13-era PYTHONPATH in the environment breaks `_sysconfigdata` resolution (`ModuleNotFoundError: _sysconfigdata__linux_x86_64-linux-gnu`); reproduced and worked around with a clean env. The wrapper should unset/scrub `PYTHONPATH` — filed as follow-up on the epic. - With #3161 merged, `parallel_threads_effective()` is naturally true on this build: census parse runs thread-parallel out of the box. Ref polylogue-xikl 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01QUsH3Rhq6oAZpYPWcsZqnZ
…3167) ## Summary Fans per-session insight compute (profile, latency, timeline, run-projection counts) out across a bounded `ThreadPoolExecutor`, gated on `parallel_threads_effective()` (3.14t free-threaded builds only), while keeping every SQLite write on the calling thread. Sequential fallback is byte-identical to today's behavior on the standard GIL build (the only build the daemon currently deploys). ## Problem `rebuild_session_insights_sync` / `rebuild_session_insights_async` (the final phase of every insight rebuild) and the post-ingest-batch incremental refresh path (`_apply_session_insight_session_updates_async`) each compute per-session insight bundles one session at a time, even though every session's compute is pure, read-only over an already-hydrated `Session` in memory — no shared SQLite connection, no shared mutable state beyond an optional timing sink. polylogue-xikl's free-threading program already landed the exact gating this needs: `parallel_threads_effective()` in `pipeline/services/process_pool.py` (PR #3161), which the polylogue-7mtf control-run measured at 3.9x-9.6x speedup (w=4..16) for the structurally identical parse-fan-out pattern on a real free-threaded (3.14t) interpreter, versus zero speedup and writer-thread-starvation risk on the standard GIL build. ## Solution - `polylogue/storage/insights/session/rebuild.py`: new `compute_session_insight_bundles(jobs)` — a small, generic (TypeVar) `ThreadPoolExecutor` fan-out gated on `parallel_threads_effective()` (sequential fallback for 0/1 jobs or a non-free-threaded interpreter). `build_session_insight_record_bundles` now builds a list of per-session compute jobs and delegates to it. This single change covers **both** `rebuild_session_insights_sync` and `rebuild_session_insights_async` — the two call sites daemon convergence (`daemon/convergence_stages.py`, 4 call sites) and `pipeline/run_stages.py` already share. - `polylogue/storage/insights/session/refresh.py`: the incremental `chunk_full_ids` loop (post-ingest-batch refresh, called from `pipeline/services/ingest_batch/_core.py`) is refactored the same way — split "which sessions have hydrated content" from "compute their bundles" — so the post-ingest-batch path benefits too, not just full/ scoped rebuilds. - Worker threads never touch SQLite: sessions are already batch-hydrated on the calling thread before fan-out (bulk `load_sync_batch`/`load_async_batch` + `hydrate_sessions`), so no per-thread read-only connection is needed for this compute stage — unlike the census-parse fan-out, which reads blobs per-worker from a fresh `ArchiveBlobPublisher`. - `stage_timing_add`'s timing dict is the one shared mutable side channel worker threads can still reach (a real production path: `daemon/convergence_stages.py::_archive_insights_execute_ids` passes a real `stage_timings_s` dict). `rebuild_session_insights_sync`'s `add_timing` closure now holds a `threading.Lock` around the dict's read-modify-write so concurrent workers can't silently drop increments. **Not in scope** (documented in the commit body, not silently dropped): the "degraded/large session" bounded fallback (`build_large_session_insight_record_bundle_sync`/`_async`) still reads a single row per session directly off the caller's connection. Fanning that out would need per-worker read-only connections (the pattern `sources/revision_backfill.py`'s census parse uses for exactly this reason). Left sequential since it's a rare bounded-fallback path (huge sessions only), not the primary compute cost. Filed as remaining scope below. ## Verification - `devtools test tests/unit/storage/test_session_insight_parallel_fanout.py tests/unit/storage/test_session_insight_refresh.py tests/unit/storage/test_session_insight_rebuild_progress.py tests/unit/storage/test_repair.py tests/unit/pipeline/test_process_pool.py tests/unit/daemon/test_convergence_stages.py` → **141 passed**. - Broader affected-area sweep: `devtools test tests/unit/api/test_facade_contracts.py tests/unit/daemon/test_convergence_stages.py tests/unit/pipeline/test_run_stages_runtime.py tests/unit/pipeline/test_ingest_batch.py tests/unit/storage/test_perf_rescue_1314.py tests/unit/cli/test_insights.py` → **418 passed**. - `mypy --strict` on all three touched files → **no issues found**. - `devtools verify --quick` → **exit 0** (format, lint, mypy, render-all-check, layering, all static gates); also ran automatically and passed on `git push` via the pre-push hook. - New test `tests/unit/storage/test_session_insight_parallel_fanout.py` covers, deliberately verified against mutation (reverted, not shipped): - **Equivalence**: identical 6-session corpus (plain text / tool_use+ tool_result / thinking-block variants) rebuilt once with `parallel_threads_effective` forced False and once forced True (same monkeypatch pattern `test_revision_backfill.py` uses for the analogous parse fan-out) → byte-identical `session_profiles` / `session_latency_profiles` / `session_work_events` / `session_phases` rows (`frozen_clock` pins the one wall-clock-derived field, `materialized_at`). - **Determinism**: jobs completing in the reverse of submission order still return results in submission order. Swapping the result assembly to `as_completed()` order breaks this test (`[4,3,2,1,0] != [0,1,2,3,4]`, confirmed then reverted). - **Write boundary**: forces the thread-pool path over a real rebuild, instruments `build_session_insight_records` and every bulk writer to record the calling thread, asserts compute ran off the calling thread (fan-out genuinely engaged, not vacuously passing) while every write stayed on it. Wrapping one bulk-write call in a background thread breaks this test ("a bulk SQLite writer ran off the calling thread", confirmed then reverted). - **Not run**: a live 3.14t free-threaded benchmark. No free-threaded interpreter with polylogue installed was available in this session/worktree (the flake's 3.14t derivations exist in the Nix store but no built devshell lane was set up here). This mirrors the same deployment-order rationale polylogue-xikl already states: CLI/offline rebuild adopts 3.14t first, daemon second — this PR lands the code-level fan-out ahead of that adoption, gated off by default. The polylogue-7mtf control-run measurement (3.9x-9.6x for the structurally identical parse fan-out) is the closest available evidence for expected speedup shape; a dedicated 3.14t benchmark for insight rebuild is a reasonable follow-up (not filed as a separate bead yet — flagging for the coordinator to decide whether it's worth a dedicated tracking item or folds into polylogue-7mtf's existing scope). Ref polylogue-syz2 --------- Co-authored-by: Claude <[email protected]>
Summary
_parse_unique_retained_rawsinsources/revision_backfill.pygains aThreadPoolExecutor-based parse path, gated on a newparallel_threads_effective()probe (sys._is_gil_enabled()). The pathengages only under a genuinely free-threaded interpreter (3.14t); the
standard GIL-build
ProcessPoolExecutorfallback is unchanged.Problem
polylogue-7mtf's control-run measurement (recorded on the epic) proved two
things about threads under the current standard (GIL) build:
ThreadPoolExecutorparse gives zero speedup (0.93x-0.96x,pure lock overhead) — confirmed by the exact same code under 3.14t
measuring 3.9x-9.6x (w=4..16) instead.
(208ms vs an ~5ms cadence) when CPU-bound parse threads run alongside it
under the GIL; under 3.14t there is zero interference (0.04ms).
The process-pool parse path also carries two GIL-only amortization costs
that don't apply to threads at all: pickle-back of
ParsedSessiongraphsacross the process boundary (#3136, measured 0.63x/net-loss above 256KiB)
and per-worker spawn+import tax (#3149, ~1.5-2s floor). Threads share one
already-imported interpreter, so neither cost exists for them.
Solution
polylogue/pipeline/services/process_pool.py: addparallel_threads_effective() -> bool, resolvingsys._is_gil_enabledvia
getattr(so mypy --strict needs no per-Python-versiontype: ignore); its absence (pre-3.13 interpreters) is treated as "GILenabled" — the safe default.
polylogue/sources/revision_backfill.py:_parse_unique_retained_rawsroutes to a new
_parse_unique_retained_raws_via_threadswhenever theprobe is true. That path applies no size partition and no amortization
floor — both exist solely to protect the process pool's two named costs.
The
ProcessPoolExecutorbranch below it is byte-for-byte unchanged; itstays the deployed daemon's fallback until the daemon itself migrates to
3.14t (a separate, later step per the epic's deployment ordering — CLI/
offline rebuild adopts 3.14t first).
_census_parse_workerfunction,not
_parse_retained_raw(archive, raw_id)directly.ArchiveStorelazily opens its
source.dbconnection with the defaultcheck_same_thread=True; callingarchive.raw_revision_descriptorfroma worker thread other than the connection's owning thread raises
sqlite3.ProgrammingError— confirmed empirically (see PR discussion /commit message).
_census_parse_workernever touches the sharedArchiveStoreat all — it reconstructs a statelessArchiveBlobPublisherfrom primitive strings, whose blob reads are plain filesystem I/O.
mechanics without pinning which branch they exercise; they now force
parallel_threads_effective() -> Falseso their claims hold regardless ofwhich interpreter runs the suite (one of them,
test_size_aware_dispatch_ keeps_large_raws_off_the_process_pool, was found failing under a real3.14t smoke run precisely because it wasn't pinned — see Verification).
Verification
devtools test tests/unit/sources/test_revision_backfill.py tests/unit/pipeline/test_process_pool.py: 41 passed (standard GILbuild, Python 3.13.13).
_parse_unique_retained_raws_via_threadsdrop the firstraw_idfromdispatch (
for raw_id in raw_ids[1:]:) — all 4 new thread-path testsfailed (
KeyError/ missing session rows). Reverted; all 41 pass again.mypy --stricton all 4 touched files: clean.ruff check/ruff format --check: clean.devtools verify --quick: exit 0.nix shell nixpkgs#python314FreeThreading+uv, withorjsondeliberately excluded (polylogue-xikl.3's
core/json.pyfacade falls backto
msgspec, no shim needed — confirms polylogue now genuinely runs on3.14t today). Ran the same two test modules: 41/41 pass, with
parallel_threads_effective()naturallyTrue(unforced — this is areal free-threaded interpreter). A broader
tests/unit/sources+tests/unit/pipelinesweep under the same interpreter found 14pre-existing failures in unrelated modules (live/batch watcher timing,
validation_flowdecode-error-message text,parsing_service/quarantine_fixturesmock specs, drive mocks) plus one collection errorfrom a test file that imports
orjsondirectly outside the facade(
test_validation_parallelism_contracts.py, excluded from this run) — allpre-existing 3.14t-migration gaps outside this PR's scope. Spot-verified
one (
test_ingest_empty_sources_returns_empty_result) reproducesidentically on the standard GIL 3.13.13 devshell, confirming
pre-existing/unrelated rather than caused by this change.
devtools verify --seed-testmon --skip-slowbootstrap attempthit
sqlite3.OperationalError: database is lockedinside an unrelatedCLI-snapshot fixture (
tests/unit/cli/test_plain_cli_snapshots.py) —transient contention from other concurrent agent sessions' full-suite
pytest runs on this shared host (confirmed via
ps auxat the time: 3+concurrent
devtools verify --seed-testmonprocesses across otherworktrees), not a regression from this change. Not retried given ongoing
host contention; the targeted +
--quick+ real-3.14t verification abovestands in its place.
Follow-ups
closing, polylogue-9as9 (the GIL-world pass-scoped-executor design): the
daemon has not yet migrated to 3.14t, so that bead's warm-pool/
worker-side-lowering design retains narrow, near-term value for the
still-deployed GIL-build daemon specifically. Recorded on both beads.
Ref polylogue-xikl.4, polylogue-xikl
🤖 Generated with Claude Code