Skip to content

⚡ Bolt: Replace O(N*M) solution lookups with O(N) dictionaries#144

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

⚡ Bolt: Replace O(N*M) solution lookups with O(N) dictionaries#144
glacy wants to merge 1 commit into
mainfrom
bolt-optimize-nested-loops-15930276840101348822

Conversation

@glacy

@glacy glacy commented Jun 25, 2026

Copy link
Copy Markdown
Owner

💡 What: Replaced nested $O(N^2)$ loops used to match exercises to solutions with an $O(N)$ dictionary lookup map in evolutia/material_extractor.py and evolutia/rag/rag_indexer.py.
🎯 Why: Searching a list of solutions repeatedly for every exercise is highly inefficient as document sizes grow. Pre-computing a hash map ensures $O(1)$ lookup time per exercise.
📊 Impact: Reduces time complexity of solution matching from $O(N*M)$ to $O(N)$, speeding up large material extraction and RAG indexing.
🔬 Measurement: Verify tests pass and check CPU profiling over large directory ingestion tasks.


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

Replaces nested loops for solution matching in `material_extractor.py` and `rag_indexer.py` with pre-computed hash maps. This drops the lookup complexity from O(N*M) to O(N), improving performance when parsing large exercise sets without altering behavior.

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 25, 2026 18:11

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 improves performance in solution matching by replacing repeated nested scans over solutions with per-material dictionaries for O(1) lookups during material extraction and RAG indexing.

Changes:

  • Precomputes solutions_dict per material to reduce solution matching from O(N*M) to ~O(N+M).
  • Refactors related code for consistency (quoting/formatting) in both the extractor and RAG indexer.
  • Minor internal cleanup adjustments around caching/vector-store code paths.

Reviewed changes

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

File Description
evolutia/rag/rag_indexer.py Uses per-material solutions_dict for O(1) solution lookup during indexing; includes formatting/refactors in indexing helpers.
evolutia/material_extractor.py Uses per-material solutions_dict for O(1) matching in get_all_exercises; includes formatting/refactors in extraction and cache stats.

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

Comment on lines +348 to +372
# 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 []

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

source = metadata.get("source_file", "reading")

for i, (chunk, embedding) in enumerate(zip(chunks, embeddings)):
chunk_id = self._create_chunk_id(f"{source}_{i}", i)
chunk_ids.append(chunk_id)
documents.append(chunk)
metadatas.append({**chunk_metadata, "chunk_index": str(i)})
"""Limpia la colección (útil para re-indexar)."""
collection_name = self.collection.name
self.client.delete_collection(name=collection_name)
_ = self.config.get("vector_store", {})
Comment on lines +328 to 329
_ = self._file_cache[file_path]
file_mtime = file_path.stat().st_mtime
Comment on lines +288 to +312
# 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)):
chunk_id = self._create_chunk_id(
f"{exercise.get('label', 'exercise')}_{i}", i
)
chunk_ids.append(chunk_id)
documents.append(chunk)
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