Repository navigation
feat(indexing): batch_size + parallel_workers + fix max_results asymmetry (v4.8.0 Fase 3) - #150
Conversation
… default to 100 - New batch_size (default 500) exposes the previously hardcoded _CHROMA_BATCH_SIZE in server.py:1417 for tuning without a code change. - New parallel_workers (default 1) opt-in gate for ThreadPoolExecutor around ChromaDB batch adds; single-thread default preserves current behavior byte-for-byte on all platforms. - Both are clamped in __post_init__: batch_size [1, 5000], workers [1, 16]. Workers > 4 on Windows emits an extra WARN about ONNX threading and SQLite lock contention. - search.max_results default raised from 20 to 100 to eliminate the asymmetric candidate pool in hybrid retrieval (_do_semantic clamped to min(max_results * 3, 20) = 20 while BM25 pulled up to max_results * 20 = 400 — semantic silently starved). External API callers passing max_results explicitly are unaffected. v4.8.0 Fase 3.
- _index_document now reads config.batch_size via getattr with the module constant _CHROMA_BATCH_SIZE (500) as fallback. - Fallback preserves test isolation: tests that build an Orchestrator via object.__new__ (tests/test_search.py, tests/test_pr98_regression.py) never touch Config and would AttributeError otherwise. - Zero behavior change when batch_size uses the default 500. v4.8.0 Fase 3.
- _index_document now branches on config.parallel_workers (default 1): - workers==1: unchanged sequential loop, byte-identical to prior code - workers>1: ThreadPoolExecutor around per-batch collection.add(...) - Parallel path only engages when the document produces >1 batch (len(unique_ids) > bs). Single-batch docs have no parallelism to exploit, so skipping the pool avoids Executor setup overhead. - Gain vs. sequential comes from SQLite writes overlapping with the NEXT batch's ONNX inference. ONNX embedding is single-locked, so the tool NEVER runs multiple embed calls concurrently. Config docs spell this out to prevent expectations mismatch. - futures[i].result() propagates the first exception in the same shape a sequential add() would raise — no swallowed indexing errors. v4.8.0 Fase 3.
- New bench/test_bench_reindex.py exercises _index_document under the
3 configs enabled by v4.8.0 Fase 3:
* reindex_default (bs=500, w=1) — v4.7.1 baseline
* reindex_batch_2000 (bs=2000, w=1) — fewer round-trips
* reindex_parallel_4 (bs=50, w=4, 200-chunk doc) — SQLite overlap
- Uses a _SleepingCollection stub with a 5ms per-add() delay (time.sleep,
not busy-wait — thread pool actually gets to overlap the sleeps).
- Bypasses __init__ via object.__new__ like tests/test_search.py — no
real ChromaDB, FastEmbed download, or disk I/O in CI. Deterministic.
- Local numbers (Windows, Python 3.14.6):
reindex_batch_2000 5.66ms (1 batch × 5ms)
reindex_default 5.68ms (1 batch × 5ms — 100 chunks < 500)
reindex_parallel_4 7.30ms (200 chunks / 50 = 4 batches parallel;
sequential would be ~20ms)
- Absolute numbers not comparable to production nuclear_rebuild wall
time. Purpose: catch regressions in the dispatch path itself
(e.g. accidental Pool per-batch, materialize of batch_slices).
v4.8.0 Fase 3.
- 20 tests across 3 classes:
* TestBatchSizeConfig (6 tests) — default/override/clamp/type
* TestParallelWorkersConfig (7 tests) — default/override/clamp/type/Windows-warn
* TestIndexingBatching (7 tests) — sequential/parallel dispatch + edge cases
- Bypasses __init__ via object.__new__ (same pattern used in
tests/test_search.py) — no ChromaDB, FastEmbed, or disk I/O.
- Verifies:
- workers=1: ThreadPoolExecutor NEVER constructed
- workers>1 AND len(chunks) > batch_size: pool called with correct
max_workers, one submit() per batch
- workers>1 BUT single batch: pool skipped (no gain to extract)
- getattr fallback to _CHROMA_BATCH_SIZE when config missing attr
- first exception from a worker propagates via .result()
- empty doc short-circuits before any config lookup
- Suite runs in ~1.6s. All 20 green locally.
v4.8.0 Fase 3.
…amped at 20)
- New TestDoSemanticCandidateMath class with 2 regression tests:
* test_semantic_asks_chromadb_for_3x_max_results — proves the fix
from v4.8.0 Fase 3 (config.max_results bumped 20 → 100). With
max_results=5, semantic now asks for 15 candidates instead of
the old clamped-at-20.
* test_semantic_pool_is_bounded_by_config_max_results — pins the
OTHER side of the min(): when max_results * 3 would exceed
config.max_results, the config value still wins as intended.
- Fake collection captures the n_results kwarg the orchestrator passes
to collection.query() — no ChromaDB, no embedding, no disk.
- hybrid_alpha=1.0 forces the semantic-only branch (skips BM25) so we
isolate the arg being tested.
- If a future PR reintroduces the '20' cap (or drops the config default
bump), test_semantic_asks_chromadb_for_3x_max_results will fail with
a message pointing at server.py::_do_semantic.
v4.8.0 Fase 3.
…default bump
- New 'Indexing performance tuning (v4.8.0+)' subsection under
'documents' explaining:
* batch_size (default 500) — RAM/throughput tradeoff, [1, 5000]
* parallel_workers (default 1) — opt-in threading with the WHY
(SQLite writes overlap with NEXT batch inference, NOT parallel
inference — ONNX kernel is serial). Warns about Windows cap.
- 'search.max_results' comment now explains the v4.8.0 Fase 3 default
bump 20 → 100 with the concrete asymmetric-pool bug that motivated
it. Callers passing max_results explicitly unaffected.
v4.8.0 Fase 3.
Two entries added under ### Unreleased: 1. PERF (indexing) — batch_size + parallel_workers config with the WHY (SQLite/inference overlap, ONNX serial constraint, single-batch skip, Windows caveat), the bench numbers (5.66/5.68/7.30ms), and the test coverage summary. Defaults preserve v4.7.1 byte-for-byte. 2. FIX (search) — max_results 20 → 100 with the concrete asymmetric pool bug (semantic clamped at 20 vs BM25 up to 400 candidates). Only the config default changed; explicit callers unaffected. v4.8.0 Fase 3.
|
Caution Review failedThe pull request is closed. ℹ️ Recent review info⚙️ Run configurationConfiguration used: defaults Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (7)
📝 WalkthroughWalkthroughThe change adds configurable document indexing batch sizes and parallel workers, with validation, fallback behavior, warnings, benchmarks, and tests. It also raises the default search candidate limit from 20 to 100 and adds regression coverage for candidate sizing. ChangesIndexing and search behavior
Estimated code review effort: 4 (Complex) | ~45 minutes Suggested labels: Suggested reviewers: ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Comment |
| # to `min(max_results * 3, 20) = 20` while BM25 pulled up to | ||
| # `max_results * 20 = 400` — semantic silently starved on hybrid mode. | ||
| # Callers passing `max_results` explicitly are unaffected. | ||
| max_results: int = field(default_factory=lambda: _get("search", "max_results", 100)) |
There was a problem hiding this comment.
When a default-config deployment receives a search_knowledge request with an explicit max_results between 21 and 100, the new default raises the public cap rather than only expanding the semantic candidate pool, causing the tool to return more than the documented 20-result maximum.
Prompt To Fix With AI
This is a comment left during a code review.
Path: mcp_server/config.py
Line: 690
Comment:
**Public result cap increases**
When a default-config deployment receives a `search_knowledge` request with an explicit `max_results` between 21 and 100, the new default raises the public cap rather than only expanding the semantic candidate pool, causing the tool to return more than the documented 20-result maximum.
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.| with ThreadPoolExecutor(max_workers=workers) as pool: | ||
| futures = [ | ||
| pool.submit( | ||
| self.collection.add, | ||
| ids=unique_ids[i : i + bs], | ||
| documents=unique_docs[i : i + bs], | ||
| metadatas=unique_metas[i : i + bs], | ||
| ) | ||
| for i in range(0, len(unique_ids), bs) | ||
| ] | ||
| # .result() propagates the first exception; caller sees | ||
| # it as an indexing failure (same shape as sequential). | ||
| for f in futures: | ||
| f.result() |
There was a problem hiding this comment.
Failed batches leave partial state
When one parallel collection.add fails while sibling batches succeed, every batch has already been submitted and successful writes remain in ChromaDB, while BM25 and _indexed_docs are not updated, leaving the failed document partially searchable and untracked.
Prompt To Fix With AI
This is a comment left during a code review.
Path: mcp_server/server.py
Line: 1487-1500
Comment:
**Failed batches leave partial state**
When one parallel `collection.add` fails while sibling batches succeed, every batch has already been submitted and successful writes remain in ChromaDB, while BM25 and `_indexed_docs` are not updated, leaving the failed document partially searchable and untracked.
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.
Summary
Fase 3 do roadmap v4.8.0 — indexing perf configurável + hybrid search symmetry fix.
What changes
config.py— 3 campos novos:batch_size(default 500),parallel_workers(default 1),max_resultsdefault 20→100server.py::_index_document— respeitaconfig.batch_size+ThreadPoolExecutoropt-in quandoparallel_workers > 1bench/test_bench_reindex.pyNEW — 3 configurações comparadas (mock collection sleep 5ms)tests/test_batch_parallel.pyNEW — 302L, config validation + routing coveragetests/test_search.py— pin_do_semanticcandidate math (era clamp em 20, agoramax_results * 3)config.example.yaml— documenta 3 campos + WARN sobre Windows > 4 workersREADME.md### Unreleased— 2 entriesBackwards compatibility
_CHROMA_BATCH_SIZE = 500fica como fallback constantmax_resultsdefault 100 só afeta callers que NÃO passavam explícito (recebiam 20 clamped, agora 100 — fix, não breaking)CI status
Actions bloqueado account-level nesse repo desde ontem — investigação em progresso. Testes locais parciais rodaram durante criação dos commits. Merge pretendido via
--adminbypass (mesma estratégia F1 #148 e F2 #149).Summary by CodeRabbit
New Features
Bug Fixes
Documentation
Greptile Summary
This PR makes indexing batch size and worker count configurable and increases the semantic-search candidate ceiling. It also adds focused tests and benchmarks.
documents.batch_sizeanddocuments.parallel_workersconfiguration.search.max_resultsfrom 20 to 100 and tests semantic candidate-pool calculations.Confidence Score: 4/5
The public result-cap regression and inconsistent partial state after parallel write failures should be fixed before merging.
The new configuration default changes externally visible
search_knowledgebehavior for explicit limits above 20, while the parallel executor can allow all sibling writes to commit even when the document operation ultimately fails.Files Needing Attention: mcp_server/config.py, mcp_server/server.py
Important Files Changed
max_results; the latter also unintentionally changes the publicsearch_knowledgehard cap for explicit requests.Flowchart
%%{init: {'theme': 'neutral'}}%% flowchart TD D[Parsed document chunks] --> B[Split by configured batch_size] B --> W{parallel_workers > 1<br/>and multiple batches?} W -- No --> S[Add batches sequentially] W -- Yes --> P[Submit every collection.add<br/>to ThreadPoolExecutor] P --> R[Read future results] S --> M[Update BM25] R -->|all succeed| M R -->|one fails| E[Document error caught] E --> O[Successful sibling batches remain<br/>without BM25 or indexed-doc metadata]Prompt To Fix All With AI
Reviews (1): Last reviewed commit: "docs(changelog): v4.8.0 Fase 3 batch par..." | Re-trigger Greptile