Skip to content

refactor(v4.8.0 Fase 6): hotspot decomposition — 40+ helpers extracted, complexity D->C - #153

Merged
lyonzin merged 13 commits into
masterfrom
refactor/v4.8.0-fase-6-hotspots
Aug 7, 2026
Merged

lyonzin merged 13 commits into
masterfrom
refactor/v4.8.0-fase-6-hotspots

Conversation

@lyonzin

@lyonzin lyonzin commented Aug 7, 2026 •

Copy link
Copy Markdown
Owner

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 violavam função ≤30 linhas. Zero mudança de comportamento — refactor puro.

  • Auditoria previa: radon cc mcp_server/ -a -nc + scanner AST próprio + git blame filtrado por SHAs F1-F5 identificaram 12 funções para refatorar e 9 borderline deferidas (marginais / touch mínimo).
  • Extract module DEFERIDO: server.py = 4009 linhas viola forte o limite de 300 linhas, mas test_backwards_compat.py valida contrato MCP por AST — mover classes multiplica superficie de regressão. Escalado pra v4.9.0.
  • Resultado: 40+ helpers extraídos, complexidade média radon caiu de D (23.4) → C (17.2), zero funções D+ no surface F1-F5 tocado.

Funções refatoradas

Função Antes Depois Helpers extraídos
_index_all_impl 246 23 14
Config.__post_init__ 185 12 13
reindex_documents 100 30 4
_index_document 91 19 3
_rebuild_via_swap 66 29 4
_validate_staging 56 24 2
get_reindex_status 49 12 2
_cleanup_stale_staging_collections 48 26 1
_print_gpu_banner 46 20 2
start_reindex_background 46 26 1
_swap_collections_atomic 43 25 1
_route_load 41 9 3

Novo sentinel _SKIP_DOC distingue "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 passed
  • tests/test_batch_parallel.py + test_reindex_resume.py + test_swap_zero_downtime.py — 57 passed
  • tests/test_backwards_compat.py (contract MCP AST) — 5 passed
  • tests/test_bm25_unicode_tokenizer.py + test_bm25_tokenizer_fragment.py — 41 passed
  • tests/test_search.py + test_dedup.py — 34 passed
  • tests/test_ingestion.py + test_ingestion_property.py — 26 passed, 1 skipped
  • tests/test_lazy_embeddings.py + test_reranker_fallback.py — 16 passed
  • tests/security/ — 143 passed, 8 xfailed
  • Misc chunk 1 (test_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 xfailed
  • Misc chunk 2 (test_pr114_regression + test_pr98_regression + test_preflight + test_presets + test_pytest_atexit_patch + test_security_docs + test_stdout_protection + test_tools) — 88 passed, 1 skipped

Total: 557 pass / 3 skip / 9 xfailed / 0 fail.

Radon post-refactor:

mcp_server/server.py:
  M FastEmbedEmbeddings.verify_gpu_readiness - E (pre-existing, NOT F1-F5)
  M KnowledgeOrchestrator.query - E (pre-existing, NOT F1-F5)
  F main - D (pre-existing, NOT F1-F5)
Average complexity: C (17.21)

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

    • Added release notes for v4.8.0 Fase 6.
    • Added an audit documenting refactoring priorities, compatibility safeguards, complexity analysis, and regression-testing coverage.
  • Refactor

    • Improved internal configuration validation and setup without changing expected behavior.
    • Streamlined GPU startup handling, embedding loading, reindexing, batch processing, cleanup, rollback, and status reporting.
    • Preserved existing configuration fallbacks and backward compatibility.

Greptile Summary

This PR mechanically decomposes configuration validation, indexing, reindexing, GPU loading, and collection-swap hotspots into focused helpers while preserving their existing contracts.

  • Splits Config.__post_init__ into ordered domain-specific validators.
  • Extracts indexing, progress, checkpoint, staging validation, swap, and reindex response helpers.
  • Documents the hotspot audit, deferred module extraction, and complexity reduction.

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

Filename Overview
mcp_server/config.py Configuration validation was divided into helpers while preserving validation order, defaults, normalization, warnings, and directory creation.
mcp_server/server.py Large GPU, indexing, reindexing, staging, swap, and status routines were mechanically decomposed without an identified behavioral divergence.
docs/refactor-audit-v4.8.0-fase-6.md Adds the hotspot-selection methodology, refactoring decisions, deferred work, and regression-test plan.
README.md Adds an Unreleased entry describing the refactoring scope, complexity improvements, and test results.

Reviews (1): Last reviewed commit: "docs(changelog): v4.8.0 Fase 6 refactor ..." | Re-trigger Greptile

lyonzin added 13 commits August 6, 2026 20:29
… 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.
@coderabbitai

coderabbitai Bot commented Aug 7, 2026 •

Copy link
Copy Markdown

Review Change Stack

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: ff1675cb-3485-4887-9d7b-602b41962dbb

📥 Commits

Reviewing files that changed from the base of the PR and between 2e02c1d and 5c4a5e0.

📒 Files selected for processing (4)
  • README.md
  • docs/refactor-audit-v4.8.0-fase-6.md
  • mcp_server/config.py
  • mcp_server/server.py

📝 Walkthrough

Walkthrough

The PR extracts configuration validation, GPU and embedding routing, indexing, reindexing, staging, rollback, and response logic into private helpers. It adds the _SKIP_DOC sentinel and documents the v4.8.0 Fase 6 audit.

Changes

Server and configuration refactor

Layer / File(s) Summary
Configuration initialization helpers
mcp_server/config.py
Config.__post_init__ delegates validation, normalization, embedding profile application, warnings, and directory creation to dedicated helpers.
GPU and embedding startup routing
mcp_server/server.py
GPU diagnostics and embedding loading use separate active, unavailable, CPU, automatic, and forced-CUDA paths.
Indexing and reindex core
mcp_server/server.py
Indexing separates document scanning, orphan cleanup, document decisions, chunk insertion, progress, checkpoints, and finalization.
Staging validation and rollback
mcp_server/server.py
Staging cleanup, validation, promotion, baseline counting, rollback, and rebuild cleanup use dedicated helpers.
Reindex responses and refactor audit
mcp_server/server.py, docs/refactor-audit-v4.8.0-fase-6.md, README.md
Reindex status and command handling use response, error, mode, and checkpoint helpers. Release documentation records the Fase 6 audit and test results.

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
Loading

Possibly related PRs

Suggested reviewers: hohlas

✨ Finishing Touches 💡 1
🛠️ Fix failing CI checks 💡
  • Create stacked PR
  • Commit on current branch
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch refactor/v4.8.0-fase-6-hotspots

Comment @coderabbitai help to get the list of available commands.

@lyonzin
lyonzin merged commit 2f41e26 into master Aug 7, 2026
26 of 29 checks passed
@lyonzin
lyonzin deleted the refactor/v4.8.0-fase-6-hotspots branch August 7, 2026 00:01
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