Skip to content

⚡ Bolt: [performance improvement] Optimize nested loops for exercise-solution lookups#98

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

⚡ Bolt: [performance improvement] Optimize nested loops for exercise-solution lookups#98
glacy wants to merge 1 commit into
mainfrom
bolt-optimize-nested-loops-13445378598198440381

Conversation

@glacy
Copy link
Copy Markdown
Owner

@glacy glacy commented May 10, 2026

💡 What: Replaced nested $O(n^2)$ loops searching for solutions by exercise label with pre-computed dictionaries in MaterialExtractor and RagIndexer, resulting in an $O(n)$ search time.

🎯 Why: As the number of exercises and solutions grows, searching linearly through all solutions for each exercise becomes a bottleneck during material extraction and indexing.

📊 Impact: Significantly reduces lookup time for matching exercises to solutions. Benchmark showed a drop from ~0.37s to ~0.01s (a ~96% improvement) for 10,000 exercises across materials.

🔬 Measurement: The change was verified to pass existing tests by mimicking the exact first-match behavior via dictionary manual insertion (if key not in dict:).


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

- Pre-computes solution dictionaries to replace O(N*M) lookups with O(N) lookup.
- Impacts `get_all_exercises` in MaterialExtractor and `index_materials` in RagIndexer.
- Converts modified files to LF.
- Applies auto-formatting with black and ruff.

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 May 10, 2026 17:49
Copy link
Copy Markdown

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

Optimizes exercise→solution matching during material extraction and RAG indexing by replacing nested solution scans with precomputed dictionaries, reducing lookup time from O(n²) to O(n) while preserving “first match wins” behavior.

Changes:

  • Precomputes solutions_by_label dictionaries to avoid per-exercise linear scans in MaterialExtractor.get_all_exercises() and RAGIndexer.index_materials().
  • Refactors/reformats rag_indexer.py and material_extractor.py for consistency (quotes, wrapping, spacing).
  • Adds a standalone benchmark.py script to compare original vs optimized lookup performance.

Reviewed changes

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

File Description
evolutia/rag/rag_indexer.py Uses a per-material solutions_by_label dict for O(1) solution lookup during indexing; also includes significant formatting/refactor churn.
evolutia/material_extractor.py Uses a per-material solutions_by_label dict for O(1) solution lookup when aggregating exercises; formatting cleanup.
benchmark.py Adds a quick benchmark script comparing nested-loop vs dict-based lookups.

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

Comment on lines +288 to +307
# Generar embeddings
embeddings = self._generate_embeddings_batch(chunks)

# Sincronizar chunks con embeddings (por si se filtraron vacíos en _generate_embeddings_batch)
# Aunque aquí preferimos filtrar antes para mantener consistencia
valid_indices = [i for i, chunk in enumerate(chunks) if chunk and chunk.strip()]
chunks = [chunks[i] for i in valid_indices]

if not chunks:
logger.warning(
f"Ejercicio {exercise.get('label', 'unknown')} no tiene contenido válido para indexar"
)
return []

# Crear IDs y documentos
chunk_ids = []
documents = []
metadatas = []

for i, (chunk, embedding) in enumerate(zip(chunks, embeddings)):
Comment on lines +348 to +360
# Generar embeddings
embeddings = self._generate_embeddings_batch(chunks)

# Sincronizar chunks con embeddings
valid_indices = [i for i, chunk in enumerate(chunks) if chunk and chunk.strip()]
chunks = [chunks[i] for i in valid_indices]

if not chunks:
logger.warning(
f"Lectura {metadata.get('title', 'unknown')} no tiene contenido válido para indexar"
)
return []

Comment thread benchmark.py
Comment on lines +38 to +51
# Generate dummy data
materials = []
for i in range(10):
exercises = [{'label': f'ex_{j}'} for j in range(1000)]
solutions = [{'exercise_label': f'ex_{j}', 'label': f'sol_{j}'} for j in range(1000)]
materials.append({'exercises': exercises, 'solutions': solutions})

start = time.time()
get_all_exercises_original(materials)
print(f"Original: {time.time() - start:.4f}s")

start = time.time()
get_all_exercises_optimized(materials)
print(f"Optimized: {time.time() - start:.4f}s")
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