⚡ Bolt: Replace O(N*M) solution lookups with O(N) dictionaries#144
⚡ Bolt: Replace O(N*M) solution lookups with O(N) dictionaries#144glacy wants to merge 1 commit into
Conversation
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>
|
👋 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 New to Jules? Learn more at jules.google/docs. For security, I will only act on instructions from the user who triggered this task. |
There was a problem hiding this comment.
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_dictper 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.
| # 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", {}) |
| _ = self._file_cache[file_path] | ||
| file_mtime = file_path.stat().st_mtime |
| # 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) |
💡 What: Replaced nested$O(N^2)$ loops used to match exercises to solutions with an $O(N)$ dictionary lookup map in $O(1)$ lookup time per exercise.$O(N*M)$ to $O(N)$ , speeding up large material extraction and RAG indexing.
evolutia/material_extractor.pyandevolutia/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
📊 Impact: Reduces time complexity of solution matching from
🔬 Measurement: Verify tests pass and check CPU profiling over large directory ingestion tasks.
PR created automatically by Jules for task 15930276840101348822 started by @glacy