Skip to content

perf: shrink the single-threaded post-extraction tail (~28% of wall, grows with repo size) #3183

Closed

Description

@squid-protocol

Context / baseline

Sibling of #3182 (Optical Detector regex). Both trace to the profiled all_language_repo scan (16.53s wall, 1.22M LOC) done alongside #3175 / PR #3181.

The scan splits into parallel extraction ≈ 11.9s (72% of wall) and a single-threaded tail ≈ 4.6s (28%) that gets zero benefit from cores. Because the tail is serial, its share grows with repo size (Amdahl) — a prime suspect for scan-rate degradation on large repos. Tail breakdown (wall):

Serial step Wall
PASS_2 structural impact / tiered normalization ~1.86s
Phase 10 ecosystem audits (X-Ray / Firewall / API Mapper) ~2.07s
master.db write + audit.json seal ~1.86s
recorders (LLM / SARIF / SBOM / GPU) ~1.1s

Goal

Shrink and/or overlap the serial tail. Byte-identical outputs are non-negotiable.

B1 — master.db file_data write: remove the row-by-row bottleneck (cheap, high-confidence)

gitgalaxy/recorders/record_keeper.py already sets PRAGMA journal_mode=WAL + synchronous=NORMAL (L407-408), single commit (L1642), and uses executemany for functions/classes/edges (L1372/1415/1532/1631). But file_data is still inserted one row at a time (~L1285) purely to read cursor.lastrowid (~L1311) into path_to_file_id.

Autoincrement IDs are deterministic path-order = 1..N. Precompute file_id = i+1 over the already-path-sorted parsed_files, build path_to_file_id up front, then executemany all file_data rows.

  • Precomputed-ID executemany for file_data; master.db row IDs byte-identical vs baseline.

B2 — Concurrent recorders (~1.1s, independent I/O)

The LLM / SARIF / SBOM / GPU recorders read the same RAM state and write different files — run them on a thread pool. Files: recorders/{llm,sarif,sbom,gpu}_recorder.py; orchestration in galaxyscope.py (record_mission call sites ~L1438-1537).

  • Recorders parallelized; all four artifacts byte-identical vs serial output.

B4 — Phase 10 ecosystem audits (~2.07s)

galaxyscope.py "Phase 10" runs X-Ray / Firewall / API Mapper serially. Profile the three; run the independent ones concurrently or fold into the worker pass.

  • Phase 10 sub-audits profiled; independent ones parallelized.

B3 — Two-phase / overlapped DB build (answers "can we build the DB earlier / in batches?")

Partially — via overlap, not true per-file streaming. Two hard blockers to writing final rows as each file leaves the pool:

  1. Global graph columns. file_data carries pagerank_score, betweenness_score, normalized_blast_radius, closeness_score, ecosystem_role — all computed from the whole import graph (network_sensor / auditor) after every file is extracted. Not knowable per-file mid-scan.
  2. Deterministic row IDs. IDs must be path-ordered for byte-stability, but the pool completes out of order (as_completed); the existing ram_cache path re-sort is the buffer that fixes this. Streaming INSERT-on-arrival would reorder IDs.

Feasible design: once extraction + path-sort finishes, the graph-independent columns (LOC, structural_mass, cog_raw, functions, classes, imports) are fully known. INSERT those rows on a background thread while PASS_2 + network + auditor compute the ~2s of graph metrics, then UPDATE the ~8 graph columns at the end. Overlaps ~1s of INSERT with ~2s of compute, zero determinism loss (IDs still assigned in path order up front, per B1). Net: the DB write stops being purely additive to wall.

  • Prototype only if B1 + B2 leave a meaningful DB-write gap. Higher risk (silent-reorder) — gate behind a focused review.

Recommended order

B1 + B2 are the cheap, low-risk wins and likely capture most of the tail. B4 next. Reach for B3's overlapped writer only if a gap remains.

Verification methodology

tests/tools/phase_ab.py --rounds 3 --control (curl + all_language_repo), engines main vs change. Env: GITGALAXY_LICENSE_KEY=COMMUNITY_FREE_TIER, PYTHONPATH, KEYWORD_ROSETTA_PATH + LANGUAGE_CRUCIBLE_PATH, sandbox OFF, v6/.venv python. Prove audit.json + sarif.json byte-identical; A-vs-A control separates real deltas from hash-seed noise; golden crucible both legs. Judge wall for this issue.

Sibling: #3182. Baseline: #3175 / #3181.

🤖 Generated with Claude Code

Activity

  1. added
    enhancement
    on Sep 18, 2026
  2. added a commit that references this issue on Sep 18, 2026
  3. squid-protocol commented on Sep 19, 2026

    @squid-protocol
    OwnerAuthor

    Closing: B1 shipped; B2/B4 are measured dead ends; B3 deferred

    Recording the outcome of each sub-task so the analysis isn't re-derived.

    B1 — file_data/class_data executemany ✅ SHIPPED (PR #3186)

    Batched the per-row inserts. The per-row execute() only existed to read cursor.lastrowid into path_to_file_id/class_id_map; IDs are precomputed from the AUTOINCREMENT sequence (SELECT seq FROM sqlite_sequence WHERE name=?, 0 if absent — not i+1, which is wrong on a re-scan into an existing DB because the idempotent per-commit DELETE FROM file_data doesn't reset the sequence). FK ordering (file_data → class_data → function → edge, parents first, foreign_keys=ON) preserved. Proven byte-identical on curl (PYTHONHASHSEED=0): audit.json + sarif.json + all four master.db tables. Wall-neutral at ALR size — the saving is size-proportional and sits below the ~0.3% phase_ab noise floor, but it removes the row-by-row scaling term.

    B2 — concurrent recorders ❌ DEAD END (unsafe)

    audit_recorder mutates the shared graph in place — telemetry["control_flow_ratio"]=…, file_data["file_impact"]=…, file_data.pop("risk_vector") — which peer recorders then read. Parallelizing races them → nondeterministic output, violating the byte-identical constraint. gpu_recorder is destructive too (clears RAM state). The only race-free subset (llm/sarif/sbom) is GIL-bound → ~0 gain.

    B4 — parallelize Phase 10 audits ❌ DEAD END (as specced)

    The audits (api_mapper 0.35s, xray 1.73s) are CPU-bound Python: a ThreadPool gives zero (serial 2.08s vs threaded 2.10s — GIL serializes). A fork ProcessPool does help (2.08→1.76s, ~0.3s ≈ 2% of a 15.5s scan) but xray needs self.config, and ResolvedConfig is not picklable — its __getattr__ infinite-recurses on unpickle (a latent bug in config_resolver.py). So the only real lever needs hand-marshalling a fragile config-subset dict for a ~2% gain that's below box-noise. A ThreadPool version was written and reverted as worthless.

    Net: the serial tail is GIL-bound Python + SQLite I/O; the CPU parts can't cheaply move to processes (unpicklable config / graph too large to pickle).

    B3 — overlapped DB writer ⏸️ DEFERRED (not filing a follow-up)

    The one structurally-feasible lever left: once extraction + path-sort finish, INSERT the graph-independent columns on a background thread while PASS_2 + network + auditor compute the ~2s of graph metrics, then UPDATE the ~8 graph columns at the end (IDs still assigned in path order up front per B1, so determinism holds). Overlaps ~1s of INSERT with ~2s of compute. Not worth opening as its own issue right now — revisit only if scan-tail rate becomes a priority again. Sibling perf work: #3182.

    Closing as B1-complete; B2/B4 won't-fix; B3 recorded above.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementperformance

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions