Repository navigation
refactor(v4.8.0 Fase 6): hotspot decomposition — 40+ helpers extracted, complexity D->C - #153
Merged
Merged
Conversation
… change) 12 functions >30 lines with F1-F5 touch flagged for refactor. File-level extract (server.py=3938 lines) deferred to v4.9.0 due to test_backwards_compat.py AST contract validation risk. Full audit report: docs/refactor-audit-v4.8.0-fase-6.md
… <=30 line limit Split gate 1 (count) and gates 2+3 (canonical queries) into private helpers. Orchestrator becomes short dispatcher. Sizes: _validate_staging: 56 -> 24 lines _validate_staging_count: 13 lines (new) _validate_staging_canonical_queries: 23 lines (new) Behavior binary-identical: 15/15 test_swap_zero_downtime.py green.
…lections_atomic Step 2 (rename staging to prod + rollback on failure) is the semantic core with try/except nesting. Extracting isolates the rollback contract and shrinks the orchestrator below the 30-line limit. Docstring compacted without losing the ChromaDB race-window rationale. Sizes: _swap_collections_atomic: 43 -> 25 lines _promote_staging_or_rollback: 19 lines (new) Behavior binary-identical: 15/15 test_swap_zero_downtime.py green.
Per-collection classification + deletion logic pulled into a helper. Orchestrator keeps prefix/now/stats setup, list_collections error handling and final logging; iteration delegates work to the helper. Sizes: _cleanup_stale_staging_collections: 48 -> 26 lines _process_staging_candidate: 28 lines (new) Behavior binary-identical: 15/15 test_swap_zero_downtime.py green.
… <=30 line limit The zero-downtime orchestrator was 66 lines mixing baseline read, validation logging, rollback and completion banner into one body. Split into focused helpers that each own one concern. Sizes: _rebuild_via_swap: 66 -> 29 lines _read_baseline_count: 7 lines (new) _enforce_staging_validation: 15 lines (new) _rollback_and_cleanup_staging: 9 lines (new) _finalize_swap_stats: 11 lines (new) Behavior binary-identical: 15/15 test_swap_zero_downtime.py green.
…compliance Tri-state dispatch (false/auto/true) shrinks to a 4-way if/elif, each branch owned by a helper. Removes the sprawling body that mixed CPU enforcement, CUDA probing with fallback, and forced-CUDA semantics. Sizes: _route_load: 41 -> 9 lines _load_forced_cpu: 4 lines (new) _load_auto: 15 lines (new) _load_forced_cuda: 20 lines (new) Behavior binary-identical: 13/13 test_gpu_auto.py + 15/15 test_swap_zero_downtime.py green.
…r <=30 line compliance Banner logic split by outcome: active branch handles the ACTIVE header + provider/device/VRAM/mode lines, unavailable branch handles the CPU fallback header + reason/missing/hint lines. Orchestrator keeps the top/bottom rule + dispatch by active flag. Sizes: _print_gpu_banner: 46 -> 20 lines _print_gpu_active: 14 lines (new) _print_gpu_unavailable: 20 lines (new) Behavior binary-identical: 13/13 test_gpu_auto.py green.
The reindex orchestrator ballooned to 246 lines after F3 (batch/parallel) and F4 (checkpoint/resume) merged. Split into thirteen single-concern helpers organized by phase: setup, per-doc processing, progress metrics, persistence, teardown. Introduces _SKIP_DOC sentinel to distinguish "caller must skip" from "no existing doc, index fresh" without truthy ambiguity. Sizes: _index_all_impl: 246 -> 23 lines _init_index_stats: 14 lines (new, staticmethod) _scan_and_count_documents: 8 lines (new) _build_path_to_docid_map: 6 lines (new) _prune_orphan_documents: 21 lines (new) _init_reindex_tracking: 22 lines (new) _seed_chunks_total_estimate: 11 lines (new) _process_one_document: 28 lines (new) _resolve_existing_or_skip: 29 lines (new) _commit_indexed_doc: 22 lines (new) _unchanged_since_last_index: 13 lines (new) _evict_stale_doc: 9 lines (new) _register_indexed_doc: 21 lines (new) _update_progress_metrics: 26 lines (new) _sample_throughput: 20 lines (new, staticmethod) _refine_chunks_total: 16 lines (new, staticmethod) _maybe_persist_checkpoint: 28 lines (new) _maybe_print_progress: 10 lines (new) _finalize_reindex: 15 lines (new) Behavior binary-identical: 57/57 tests green (test_reindex_resume.py + test_swap_zero_downtime.py + test_batch_parallel.py).
…dators Config.__post_init__ ballooned to 185 lines across F1 (embedding profile), F2 (gpu mode) and F3 (batch/parallel). Split by validation domain: each helper owns one config surface (chunking, indexing, embedding profile, embedding types, GPU, transport, formats, lists/maps, docs dir warning, directory creation). Orchestrator becomes a linear pipeline. Sizes: __post_init__: 185 -> 12 lines _validate_chunking: 18 lines (new) _validate_indexing: 27 lines (new) _resolve_embedding_profile: 25 lines (new) _apply_embedding_profile: 14 lines (new) _validate_embedding_types: 21 lines (new) _normalize_gpu_mode: 24 lines (new) _validate_server_transport: 15 lines (new) _validate_supported_formats: 10 lines (new) _validate_lists_and_maps: 4 lines (new) _validate_exclude_and_routes: 14 lines (new) _validate_query_expansions: 18 lines (new) _warn_missing_documents_dir: 9 lines (new) _ensure_directories: 6 lines (new) Behavior binary-identical: 58/58 tests green (test_config + test_embedding_profile + test_gpu_auto + test_batch_parallel).
…rallel-add helpers Post-F3 (batch/parallel) growth pushed _index_document to 91 lines mixing dedup, batch sizing, and the sequential-vs-parallel branch. Extract each concern; orchestrator becomes a linear pipeline. Sizes: _index_document: 91 -> 19 lines _dedup_chunks: 30 lines (new, staticmethod) _add_chunks_batched: 15 lines (new) _add_chunks_parallel: 21 lines (new) Behavior binary-identical: 46/46 tests green (test_batch_parallel.py + test_ingestion.py).
The MCP tool body ballooned to 100 lines mixing pre-flight validation, mode resolution, checkpoint hydration and response formatting. Extract each concern to module-level helpers. Docstring trimmed to the tool contract essentials while keeping the resume semantics documented. Sizes: reindex_documents: 100 -> 30 lines _reindex_error_response: 7 lines (new) _resolve_reindex_mode: 13 lines (new) _load_reindex_resume_state: 16 lines (new) _format_reindex_response: 23 lines (new) Behavior binary-identical: 27/27 tests green (test_reindex_resume + test_backwards_compat).
…_reindex_status start_reindex_background: extract initial progress dict builder so the launcher itself becomes a linear check + dict-init + dispatch + spawn. get_reindex_status: extract active vs idle payload builders — the active branch alone was 18 lines of dict construction with per-field defaults; splitting halves the orchestrator. Sizes: start_reindex_background: 46 -> 26 lines _fresh_reindex_progress: 25 lines (new, staticmethod) get_reindex_status: 49 -> 12 lines _active_reindex_status: 21 lines (new, staticmethod) _idle_reindex_status: 8 lines (new, staticmethod) Behavior binary-identical: 22/22 test_reindex_resume.py green.
|
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 (4)
📝 WalkthroughWalkthroughThe PR extracts configuration validation, GPU and embedding routing, indexing, reindexing, staging, rollback, and response logic into private helpers. It adds the ChangesServer and configuration refactor
Estimated code review effort: 4 (Complex) | ~60 minutes Sequence Diagram(s)sequenceDiagram
participant reindex_documents
participant _index_all_impl
participant _add_chunks_batched
participant ChromaDB
reindex_documents->>_index_all_impl: start indexing operation
_index_all_impl->>_add_chunks_batched: insert document chunks
_add_chunks_batched->>ChromaDB: write batches
ChromaDB-->>_index_all_impl: write results
_index_all_impl-->>reindex_documents: progress and final response
Possibly related PRs
Suggested reviewers: ✨ Finishing Touches 💡 1🛠️ Fix failing CI checks 💡
📝 Generate docstrings
🧪 Generate unit tests (beta)
Comment |
5 of 6 tasks
This was referenced Aug 8, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
v4.8.0 Fase 6 — refactor performance oportunistico dos hotspots que F1-F5 deixou fora dos limites Core. Escopo estrito: só funções tocadas em F1-F5 (
8910c35..2e02c1d) que violavamfunção ≤30 linhas. Zero mudança de comportamento — refactor puro.radon cc mcp_server/ -a -nc+ scanner AST próprio +git blamefiltrado por SHAs F1-F5 identificaram 12 funções para refatorar e 9 borderline deferidas (marginais / touch mínimo).server.py= 4009 linhas viola forte o limite de 300 linhas, mastest_backwards_compat.pyvalida contrato MCP por AST — mover classes multiplica superficie de regressão. Escalado pra v4.9.0.Funções refatoradas
_index_all_implConfig.__post_init__reindex_documents_index_document_rebuild_via_swap_validate_stagingget_reindex_status_cleanup_stale_staging_collections_print_gpu_bannerstart_reindex_background_swap_collections_atomic_route_loadNovo sentinel
_SKIP_DOCdistingue "caller deve skip" de "index como fresh" no per-doc worker.Test plan
Suite completa em chunks pequenos (evita crash CLI do pytest full):
tests/test_config.py+test_embedding_profile.py+test_gpu_auto.py— 38 passedtests/test_batch_parallel.py+test_reindex_resume.py+test_swap_zero_downtime.py— 57 passedtests/test_backwards_compat.py(contract MCP AST) — 5 passedtests/test_bm25_unicode_tokenizer.py+test_bm25_tokenizer_fragment.py— 41 passedtests/test_search.py+test_dedup.py— 34 passedtests/test_ingestion.py+test_ingestion_property.py— 26 passed, 1 skippedtests/test_lazy_embeddings.py+test_reranker_fallback.py— 16 passedtests/security/— 143 passed, 8 xfailedtest_exclude_patterns+test_format_smoke+test_installer_no_data_loss+test_instance_lock+test_ipynb_parser+test_locale+test_memory_baseline) — 109 passed, 1 skipped, 1 xfailedtest_pr114_regression+test_pr98_regression+test_preflight+test_presets+test_pytest_atexit_patch+test_security_docs+test_stdout_protection+test_tools) — 88 passed, 1 skippedTotal: 557 pass / 3 skip / 9 xfailed / 0 fail.
Radon post-refactor:
Escopo respeitado
Nenhuma função pre-existente (não tocada em F1-F5) foi refatorada, mesmo quando o radon flagou D+. Isso preserva o princípio da PR: refactor oportunístico da superfície tocada em F1-F5, sem gambling em código estável.
Docs
docs/refactor-audit-v4.8.0-fase-6.md— audit report completo (12 funções refatoradas, 9 borderline deferidas com justificativa).README.md§ Unreleased — CHANGELOG entry v4.8.0 Fase 6.Closes o roadmap v4.8.0 (F1-F5 shipping + F6 hardening = release-ready).
🤖 Generated with Claude Code
Summary by CodeRabbit
Documentation
Refactor
Greptile Summary
This PR mechanically decomposes configuration validation, indexing, reindexing, GPU loading, and collection-swap hotspots into focused helpers while preserving their existing contracts.
Config.__post_init__into ordered domain-specific validators.Confidence Score: 5/5
The PR appears safe to merge because the executable changes preserve the prior branch ordering, state mutations, fallback behavior, and public response shapes.
Base-to-head comparison found the extracted helpers equivalent across configuration initialization, GPU routing, document indexing, checkpointing, progress reporting, staging validation, collection swapping, rollback, and reindex API formatting.
Important Files Changed
Reviews (1): Last reviewed commit: "docs(changelog): v4.8.0 Fase 6 refactor ..." | Re-trigger Greptile