Skip to content

Speed up file reads, parsing, staging, and indexing pipeline - #87

Merged
MarcinHamiga merged 3 commits into
mainfrom
perf/file-reads-parsing-pipeline
Nov 26, 2026
Merged

MarcinHamiga merged 3 commits into
mainfrom
perf/file-reads-parsing-pipeline

Conversation

@MarcinHamiga

Copy link
Copy Markdown
Owner

Summary

Pure-Python optimizations (no compiled native wheels) across file scanning, source I/O, tree-sitter extraction, Arrow staging, progress reporting, and indexing concurrency so parsing and I/O stay ahead of fast local embedding backends (e.g., Apple Silicon MLX):

  1. Producer–consumer indexing pipeline (indexing.py, application.py)

    • Overlap directory traversal, file reads, and AST/reference extraction in a contextvars.copy_context()-propagated background producer thread feeding a bounded queue.Queue(maxsize=4) while the main thread embeds and stages chunks/references concurrently.
    • Increase CANDIDATE_GROUP_COUNT to 512 files and CANDIDATE_GROUP_CHARS to 512 KiB.
  2. Multi-process parse worker pool (parse_pool.py, settings.py, indexing.py)

    • Add a spawn-based worker pool (ParseWorkerPool, resolve_parse_workers, configurable via CODE_INDEXING_PARSE_WORKERS / IndexSettings.parse_workers, where 0 / auto picks worker count automatically up to MAX_PARSE_WORKERS = 16).
    • Exchange compact wire tuples and keep parse_pool.py free of lancedb and pyarrow imports (~99.1 ms cold worker import).
  3. Single-core extraction, columnar Arrow staging & deferred progress (extractor.py, language_rules.py, models.py, staging.py, progress.py)

    • Replace repeated AST .parent walks with _ParentMap, dispatch identifier extraction through precomputed per-language _IdentifierDispatch tables, gate JS/TS class_heritage climbs and _call_shape checks, and throttle chunk memory checks.
    • Convert hot data carriers (CallShape, ExtractedReference, _LanguageRules, ChunkRow, ReferenceRow) to __slots__ dataclasses with compact JSON dumping on CallShape.
    • Stage reference batches column-wise into Arrow via StagingJob.stage_reference_columns(...) instead of per-row dict/object construction.
    • Replace copy.deepcopy in ProgressPublisher with shallow container cloning, deferred model_copy, and throttled lazy_fields.
  4. Fast file reads and directory traversal (source_io.py, scanner.py)

    • Add _open_source_fd, a single-shot os.read fast path in _read_from_fd, and read_source_direct for pre-stat'd candidate files.
    • Detect .git repository boundaries directly inside os.scandir walks (_iter_walk_candidate_batches) and avoid redundant per-file path normalization in _scan_candidate_entries.

Benchmarks (Apple M4 Pro, Python 3.12.11, 12 CPUs, 48 GiB RAM)

Measured on the implementation commit before rebasing cleanly onto #86 (whose changes were disjoint from indexing/extraction/I/O).

Benchmark Before / Baseline After Speedup
Full Indexer.index (316 repo files, DeterministicEmbedder) 3,816 ms (parse_workers=1) 2,359 ms (parse_workers=0, auto=6) 1.62x
Simulated ~200 chunks/s MLX embedder (embed ≈ 38.1 s) Serial parse + embed 39,547 ms (in-process) / 40,108 ms (pool); parse hidden behind embed Parse overlapped (34 ms / 820 ms)
Single-core TreeSitterExtractor.extract (314-file isolated A/B) 2.240 s total (1.583 s ref extract) 1.744 s total (1.100 s ref extract) 1.29x total (1.44x refs)
Arrow reference staging (316 files, 146,109 rows) 467.3 ms (row objects) 206.1 ms (columnar Arrow) 2.27x (byte-identical)
ProgressPublisher.update ×10,000 (throttled 0.25 s) 101.7 ms 4.72–4.80 ms ~21x
5,000-file non-git walk + read (8.7 MB) 364.2 ms 255.0 ms (read_source_direct: 84.0 ms) 1.43x
Lean parse worker cold import — 99.1 ms (no lancedb / pyarrow) —

Verification

Run on branch perf/file-reads-parsing-pipeline (based on origin/main 64036f3):

  • uv run --no-sync ruff format --check . → 171 files already formatted
  • uv run --no-sync ruff check . → All checks passed!
  • uv run --no-sync mypy src → Success: no issues found in 79 source files
  • uv run --no-sync pytest tests/test_extractor_equivalence.py -v → 5 passed (tests/fixtures/extractor_snapshot.json untouched)
  • uv run --no-sync pytest -n auto --dist worksteal:
    • 2789 passed, 9 skipped across all non-socket/non-home-config tests in sandbox (includes tests/test_mlx_backend.py collection-level skip without mlx extra)
    • 234 passed, 1 skipped across the 9 Unix-socket / home-config test files (tests/test_daemon.py, tests/test_daemon_lifecycle.py, tests/test_index_worker.py, tests/test_installer_cli.py, tests/test_installer_orchestrator.py, tests/test_installer_tui.py, tests/test_mcp_timeouts.py, tests/test_tui_service.py, tests/test_worker_launcher.py) run unsandboxed (Linux runtime-dir test skipped on macOS)
    • Combined: 3,023 passed, 10 skipped, 0 failed
  • src/code_indexing_mcp/mlx_backend.py was not modified.

- Pipeline indexing in `indexing.py` so a context-propagated background
  producer scans, reads, and parses into a bounded queue (`maxsize=4`)
  while the main thread embeds and stages chunks/references concurrently;
  bump candidate group thresholds to 512 files / 512 KiB.
- Add a lean `spawn`-based multi-process parser pool (`parse_pool.py`,
  configurable via `CODE_INDEXING_PARSE_WORKERS` / `IndexSettings.parse_workers`)
  using compact wire tuples and avoiding heavy runtime imports (`lancedb`,
  `pyarrow`) in worker processes.
- Optimize single-core extraction and staging (`extractor.py`, `models.py`,
  `language_rules.py`, `staging.py`, `progress.py`): `_ParentMap` parent
  index, per-language `_IdentifierDispatch` tables, guarded `class_heritage`
  and `_call_shape` checks, slotted dataclasses (`CallShape`,
  `ExtractedReference`, `_LanguageRules`, `ChunkRow`, `ReferenceRow`),
  columnar Arrow reference staging via `StagingJob.stage_reference_columns`,
  and shallow-copied deferred updates in `ProgressPublisher`.
- Speed up file I/O and directory traversal (`source_io.py`, `scanner.py`):
  single-shot `os.read` fast path, `read_source_direct`, and `.git`
  repo-boundary detection inside `os.scandir` walks with single `rel_posix`
  computation.
…progress

- Switch ParseWorkerPool to spawn ProcessPoolExecutor so worker crashes raise BrokenProcessPool instead of deadlocking drain_one(), and enforce memory budgets in workers and batch draining.
- Preserve force/retry read-error semantics in run_pool via ParseTask.stat_matched_previous so unreadable files retain indexed chunks and record retryable failures instead of being deleted.
- Pass scan (st_dev, st_ino) identity through ScannedFile/ParseTask to read_source_direct() so PinnedDirectoryCache recovers from renamed-and-replaced directories without an extra lstat.
- Flush pending lazy_fields on ProgressPublisher.state reads and apply monotonic phase anchoring to lazy phase updates.
- Add producer liveness guard in _index_scan, deduplicate MAX_PARSE_WORKERS, WireChunk, and Indexer._reference_rows, remove dead SourceScanner._is_repository_worktree, fix CallShape non-ASCII JSON parity, and add regression tests.
@MarcinHamiga
MarcinHamiga merged commit 226a02f into main Nov 26, 2026
5 checks passed
@MarcinHamiga
MarcinHamiga deleted the perf/file-reads-parsing-pipeline branch November 26, 2026 15:19
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