Skip to content

⚡ Bolt: Optimize O(N*M) loop to O(N) dict lookup in material extraction#142

Open
glacy wants to merge 1 commit into
mainfrom
bolt/optimize-nested-loops-4559772483844363549
Open

⚡ Bolt: Optimize O(N*M) loop to O(N) dict lookup in material extraction#142
glacy wants to merge 1 commit into
mainfrom
bolt/optimize-nested-loops-4559772483844363549

Conversation

@glacy

@glacy glacy commented Jun 23, 2026

Copy link
Copy Markdown
Owner

💡 What: Replaced two identical O(N*M) nested loops in get_all_exercises (evolutia/material_extractor.py) and index_materials (evolutia/rag/rag_indexer.py) with an O(N) approach using a pre-computed dictionary lookup (solutions_by_label).

🎯 Why: The original implementation mapped solutions to exercises using a linear search over the solutions array for each exercise. This results in quadratic time complexity (O(N*M)) which scales poorly when processing materials with a large number of exercises and solutions.

📊 Impact: Reduces time complexity of solution mapping from O(N*M) to O(N+M), significantly speeding up material extraction and RAG index generation for large datasets.

🔬 Measurement: The change was thoroughly verified using the existing test suite (pytest tests/) ensuring no behavioral regressions. The solutions_by_label mapping was intentionally implemented to preserve the original "first-match" break behavior in the event of duplicate labels. LF line endings and codebase formatting (black, ruff) were maintained.


PR created automatically by Jules for task 4559772483844363549 started by @glacy

Identified and optimized two identical O(N*M) nested loops in `evolutia/material_extractor.py` (`get_all_exercises`) and `evolutia/rag/rag_indexer.py` (`index_materials`) where the code was mapping exercises to their corresponding solutions using linear searches.

These loops were replaced with an O(N) approach by pre-computing a lookup dictionary `solutions_by_label`. This significantly improves the scaling behavior for materials containing many exercises and solutions.

The refactor carefully preserves the original "first-match" semantics of the `break` statement by conditionally populating the dictionary: `if sol['exercise_label'] not in solutions_by_label:`.

Co-authored-by: glacy <1131951+glacy@users.noreply.github.com>
@google-labs-jules

Copy link
Copy Markdown
Contributor

👋 Jules, reporting for duty! I'm here to lend a hand with this pull request.

When you start a review, I'll add a 👀 emoji to each comment to let you know I've read it. I'll focus on feedback directed at me and will do my best to stay out of conversations between you and other bots or reviewers to keep the noise down.

I'll push a commit with your requested changes shortly after. Please note there might be a delay between these steps, but rest assured I'm on the job!

For more direct control, you can switch me to Reactive Mode. When this mode is on, I will only act on comments where you specifically mention me with @jules. You can find this option in the Pull Request section of your global Jules UI settings. You can always switch back!

New to Jules? Learn more at jules.google/docs.


For security, I will only act on instructions from the user who triggered this task.

Copilot AI review requested due to automatic review settings June 23, 2026 17:54

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR optimizes solution lookup during material extraction and RAG indexing by replacing per-exercise linear searches over solutions with a precomputed solutions_by_label dict, reducing mapping from O(N*M) to O(N+M) while preserving “first-match” semantics for duplicate labels.

Changes:

  • Precompute solutions_by_label in MaterialExtractor.get_all_exercises to avoid nested loops.
  • Precompute solutions_by_label in RAGIndexer.index_materials to avoid nested loops.
  • Additional formatting/cleanup adjustments applied in both touched modules.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 3 comments.

File Description
evolutia/material_extractor.py Builds a per-material dict for solution lookup in get_all_exercises; also includes cache-related edits in the same file.
evolutia/rag/rag_indexer.py Builds a per-material dict for solution lookup in index_materials; also includes refactors/formatting in embedding/chunking code paths.
Comments suppressed due to low confidence (1)

evolutia/material_extractor.py:331

  • _is_cache_valid actualmente ignora la información del caché (no usa el entry salvo para comprobar existencia) y depende de stat() del archivo. Esto rompe el objetivo de “cachear errores para evitar reintentos fallidos” (si el archivo no existe, stat() falla y siempre retorna False) y no aplica _cache_ttl. Con file_mtime/cached_at en el entry, se puede validar por TTL y mtime sin forzar stat() para entradas de error.
            _ = self._file_cache[file_path]
            file_mtime = file_path.stat().st_mtime

            # Usar el timestamp de escaneo más reciente para verificar
            if file_mtime > self._last_scan_timestamp:

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines 122 to 125
self._file_cache[file_path] = {
'data': result,
'timestamp': file_path.stat().st_mtime
"data": result,
"timestamp": file_path.stat().st_mtime,
}
Comment on lines +197 to +200
elif self.embedding_provider == "sentence-transformers":
return self.embedding_model.encode(
texts, show_progress_bar=True, batch_size=32
).tolist()
Comment on lines 142 to 145
self._file_cache[file_path] = {
'data': error_result,
'timestamp': time.time() # Usar tiempo actual para archivos que no existen
"data": error_result,
"timestamp": time.time(), # Usar tiempo actual para archivos que no existen
}
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.

2 participants