Skip to content

perf(insights): fan out per-session insight compute across threads - #3167

Merged
Sinity merged 2 commits into
masterfrom
feature/perf/insight-compute-fanout
Jul 19, 2026
Merged

Sinity merged 2 commits into
masterfrom
feature/perf/insight-compute-fanout

Conversation

@Sinity

@Sinity Sinity commented Jul 19, 2026

Copy link
Copy Markdown
Owner

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

Sinity and others added 2 commits July 19, 2026 21:08
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]>
@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 19, 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: 5 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: 314d9440-5a60-4231-8192-f51c9daf963a

📥 Commits

Reviewing files that changed from the base of the PR and between e3c6885 and 5f089bf.

📒 Files selected for processing (3)
  • polylogue/storage/insights/session/rebuild.py
  • polylogue/storage/insights/session/refresh.py
  • tests/unit/storage/test_session_insight_parallel_fanout.py
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/perf/insight-compute-fanout

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 e080e0b into master Jul 19, 2026
3 checks passed
@Sinity
Sinity deleted the feature/perf/insight-compute-fanout branch July 19, 2026 19:29
Sinity added a commit that referenced this pull request Jul 19, 2026
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