Repository navigation
perf(insights): fan out per-session insight compute across threads - #3167
Conversation
Problem: rebuild_session_insights_sync/_async and the post-ingest incremental refresh path (_apply_session_insight_session_updates_async) each compute per-session insight bundles (profile, latency, timeline, run-projection counts) 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 pattern this needs (parallel_threads_effective() in pipeline/services/process_pool.py, PR #3161): threads give zero speedup and can starve a concurrent SQLite writer under the standard GIL build, but measured 3.9x-9.6x under a real free-threaded (3.14t) interpreter for the analogous parse fan-out. Solution: storage/insights/session/rebuild.py gains compute_session_insight_bundles(jobs), a small ThreadPoolExecutor fan-out gated on parallel_threads_effective() (sequential, byte- identical fallback otherwise). 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 and pipeline/run_stages.py already share. storage/insights/session/ refresh.py's incremental chunk_full_ids loop is refactored the same way (split "which sessions have hydrated content" from "compute their bundles"), so the post-ingest-batch refresh path benefits too. Worker threads never touch SQLite: sessions are already batch-hydrated on the calling thread before fan-out, so no per-thread read-only connection is needed for this compute stage (unlike the parse fan-out, which reads blobs per-worker). The one shared mutable side channel -- stage_timing_add's timing dict -- gets a lock in rebuild_session_insights_sync so concurrent workers can't race on its read-modify-write. Not in scope: 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 revision_backfill.py's census parse uses); left sequential since it is a rare bounded-fallback path, not the primary compute cost. Follow-up tracked as polylogue-syz2 remaining scope in the PR body. Verification: devtools test 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 -- 94 passed, behavior unchanged with fan-out gated off on this standard (GIL) interpreter. Ref polylogue-syz2 Co-Authored-By: Claude <[email protected]>
…fan-out
Problem: the per-session insight compute fan-out (previous commit) needs
proof it cannot silently diverge from sequential output, cannot reorder
per-session results (which would let the single writer apply them
non-deterministically), and cannot let a worker thread perform a SQLite
write. None of that was covered yet.
What changed:
- compute_session_insight_bundles is now generic in its result type
(TypeVar) instead of pinned to SessionInsightRecordBundle -- a pure
job-runner with no knowledge of what a job computes, directly testable
with trivial int-returning jobs instead of constructing full bundle
objects.
- tests/unit/storage/test_session_insight_parallel_fanout.py:
- equivalence: seeds two identical 6-session corpora (plain text /
tool_use+tool_result / thinking-block variants), rebuilds one with
parallel_threads_effective forced False and the other forced True
(same monkeypatch pattern test_revision_backfill.py uses for the
analogous census-parse fan-out), and asserts session_profiles /
session_latency_profiles / session_work_events / session_phases rows
are byte-identical (frozen_clock pins now_iso()'s materialized_at,
the only wall-clock-derived field on this path).
- determinism: jobs that complete in the reverse of submission order
still return results in submission order.
- write boundary: forces the thread-pool path over a real rebuild,
wraps build_session_insight_records and every bulk writer to record
the calling thread, and asserts compute ran off the calling thread
(fan-out genuinely engaged) while every write stayed on it.
Anti-vacuity, verified by deliberate mutation (reverted after, not part
of this commit):
- Swapping compute_session_insight_bundles's result assembly to
as_completed() order broke the determinism test
([4,3,2,1,0] != [0,1,2,3,4]).
- Wrapping the session_profiles bulk-write call in a background thread
broke the write-boundary test ("a bulk SQLite writer ran off the
calling thread").
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.
mypy --strict polylogue/storage/insights/session/rebuild.py
polylogue/storage/insights/session/refresh.py
tests/unit/storage/test_session_insight_parallel_fanout.py -- no issues.
devtools verify --quick -- exit 0 (format, lint, mypy, render-all-check,
layering, all static gates).
Ref polylogue-syz2
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: 5 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 (3)
✨ 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 |
Summary
Fans per-session insight compute (profile, latency, timeline, run-projection
counts) out across a bounded
ThreadPoolExecutor, gated onparallel_threads_effective()(3.14t free-threaded builds only), whilekeeping 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(thefinal phase of every insight rebuild) and the post-ingest-batch incremental
refresh path (
_apply_session_insight_session_updates_async) each computeper-session insight bundles one session at a time, even though every
session's compute is pure, read-only over an already-hydrated
Sessioninmemory — 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()inpipeline/services/process_pool.py(PR #3161), which the polylogue-7mtfcontrol-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: newcompute_session_insight_bundles(jobs)— a small, generic (TypeVar)ThreadPoolExecutorfan-out gated onparallel_threads_effective()(sequential fallback for 0/1 jobs or a non-free-threaded interpreter).
build_session_insight_record_bundlesnow builds a list of per-sessioncompute jobs and delegates to it. This single change covers both
rebuild_session_insights_syncandrebuild_session_insights_async— thetwo call sites daemon convergence (
daemon/convergence_stages.py, 4 callsites) and
pipeline/run_stages.pyalready share.polylogue/storage/insights/session/refresh.py: the incrementalchunk_full_idsloop (post-ingest-batch refresh, called frompipeline/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.
the calling thread before fan-out (bulk
load_sync_batch/load_async_batchhydrate_sessions), so no per-thread read-only connection is needed forthis 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 channelworker threads can still reach (a real production path:
daemon/convergence_stages.py::_archive_insights_execute_idspasses a realstage_timings_sdict).rebuild_session_insights_sync'sadd_timingclosure now holds a
threading.Lockaround the dict's read-modify-write soconcurrent 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 asingle 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.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 --stricton 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 pushvia the pre-push hook.
tests/unit/storage/test_session_insight_parallel_fanout.pycovers, deliberately verified against mutation (reverted, not shipped):
tool_result / thinking-block variants) rebuilt once with
parallel_threads_effectiveforced False and once forced True (samemonkeypatch pattern
test_revision_backfill.pyuses for the analogousparse fan-out) → byte-identical
session_profiles/session_latency_profiles/session_work_events/session_phasesrows (
frozen_clockpins the one wall-clock-derived field,materialized_at).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).
instruments
build_session_insight_recordsand every bulk writer torecord 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).
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