Batch Document Embedding and Filtered Vector Retrieval
Medium · Machine Learning · Software Engineer · Technical Screen
Problem Statement
Build the two core entry points of a semantic document-retrieval service: a fault-tolerant batch indexer that chunks, embeds, normalizes, and upserts documents, and a query function that retrieves the highest-scoring distinct documents matching an optional category filter.
External dependencies are injected so the pipeline can run against mocks or production services:
- embed_model.encode(texts: List[str]) -> List[List[float]]: encodes a batch of B texts into B raw float vectors.
- split_text(text: str, max_tokens: int) -> List[str]: splits text into chunks of at most max_tokens tokens (returning [text] if it already fits).
- vector_db.upsert(records: List[dict]) -> None: writes records keyed by record['id'], overwriting any existing entry with the same 'id'.
- vector_db.query(vector: List[float], filter: dict, k: int) -> List[dict]: returns up to k stored records matching all key-value pairs in filter, each carrying an added 'score' equal to the dot product between vector and record['vector'], sorted highest score first.
Implement:
-
process_and_index_documents(documents, *, embed_model, vector_db, split_text, batch_size=32, max_retries=2, retry_delay=0.5) -> Dict[str, list]- Each input dictionary has shape
{'id': str, 'text': str, 'category': str}. - Validation & deduplication: Reject any entry missing a non-empty
'id'immediately. If the same'id'appears more than once indocuments, keep only its last occurrence and validate that surviving entry. Mark a document failed if'text'is missing, not a string, or whitespace-only, or ifsplit_text(text, 512)yields no chunks. - Batched encoding with retries: Encode chunks in batches of
batch_size. Whenembed_model.encoderaises an exception, retry up tomax_retriesadditional times with exponential backoff (retry_delay,2 * retry_delay,4 * retry_delay, ...). If all retries fail (orencodereturns the wrong number of vectors), record every document touched by that batch as failed and continue processing remaining batches. - Unit-length normalization & atomic documents: Scale each vector to Euclidean length
1.0(L2norm) so dot-product scoring equals cosine similarity; reject zero-norm or non-finite (NaN/inf) vectors. Index a document only if all of its chunks succeed. Store chunkc(0, 1, ...) ofdoc_iddeterministically as:{'id': f'{doc_id}#{c}', 'doc_id': doc_id, 'chunk': c, 'vector': unit_vector, 'category': doc.get('category'), 'text': chunk_text}. - Return
{'indexed': [doc_id, ...], 'failed': [(doc_id, reason), ...]}.
- Each input dictionary has shape
-
search_vector_store(query, category_filter, top_k=5, *, embed_model, vector_db, max_retries=2, retry_delay=0.5) -> List[dict]- Return
[]immediately (without callingembed_model) whentop_k <= 0orqueryis empty/whitespace-only. - Encode
[query]using the same retry policy and L2-normalize the resulting vector; raiseEmbeddingErrorif the query cannot be embedded or normalized. - Pass
{'category': category_filter}intovector_db.query(or{}whencategory_filter is None), over-fetching candidate chunks so multi-chunk documents do not crowd out distinct documents. - Collapse hits by
'doc_id'(retaining each document's highest-scoring chunk), rank by descending'score'with ties broken by ascending'doc_id', and return up totop_kdictionaries of shape{'id': doc_id, 'score': score, 'category': category, 'text': best_chunk_text}.
- Return
Examples
Example 1
Toy model outputs:
encode(["reset api token"]) -> [[3.0, 4.0, 0.0]]
encode(["invoice tax receipt"]) -> [[0.0, 0.0, 2.0]]
encode(["rotate secret key"]) -> [[4.0, 0.0, 3.0]]
Input:
docs = [
{"id": "kb1", "text": "reset api token", "category": "security"},
{"id": "kb2", "text": "invoice tax receipt", "category": "billing"},
]
report = process_and_index_documents(docs, embed_model=..., vector_db=..., split_text=...)
hits = search_vector_store("rotate secret key", "security", top_k=1, embed_model=..., vector_db=...)
Output:
report -> {"indexed": ["kb1", "kb2"], "failed": []}
hits -> [{"id": "kb1", "score": 0.48, "category": "security", "text": "reset api token"}]
Walk-through: "kb1#0" normalizes [3, 4, 0] (length 5) to [0.6, 0.8, 0.0], and "kb2#0" normalizes [0, 0, 2] (length 2) to [0.0, 0.0, 1.0]. The query "rotate secret key" normalizes [4, 0, 3] (length 5) to [0.8, 0.0, 0.6]. Filtering inside vector_db.query restricts candidates to "security" (excluding "kb2" even though its unfiltered dot product 0.60 would be higher) and scores "kb1" at 0.6 * 0.8 + 0.8 * 0.0 + 0.0 * 0.6 = 0.48.
Example 2
Input:
docs = [
{"id": "kb3", "text": "obsolete draft", "category": "security"},
{"id": "kb3", "text": "<700-token SSO guide split into chunk 0 and chunk 1>", "category": "security"},
{"id": "kb4", "text": " ", "category": "billing"},
]
Output:
report -> {"indexed": ["kb3"], "failed": [("kb4", "empty text")]}
search_vector_store("sso", None, top_k=2, ...) -> [{"id": "kb3", "score": 1.0, "category": "security", "text": "<chunk 1 text>"}]
Walk-through: Duplicate ID "kb3" keeps only its final 700-token version, which splits into "kb3#0" and "kb3#1". "kb4" fails validation because its text is blank. When searching "sso" across all categories (category_filter=None), both "kb3#0" and "kb3#1" match, and collapsing by doc_id returns "kb3" once using its higher-scoring chunk.
Constraints
MAX_CHUNK_TOKENS = 512and defaultEMBED_BATCH_SIZE = 32.- Re-running
process_and_index_documentson unchanged documents must overwrite existingf"{doc_id}#{chunk}"records in place rather than creating duplicates. - A multi-chunk document must never be partially indexed if one of its chunks fails encoding or L2 normalization.
- Transient model failures retry up to
max_retriestimes; exhausted query retries raiseEmbeddingError, whereas exhausted ingestion batch retries isolate the failed batch and report affected documents in'failed'.
Step-by-step walkthrough
Restate the problem and external interfaces
We are building the two halves of a semantic document-retrieval service:
- Batch ingestion (
process_and_index_documents): Take raw articles{'id': str, 'text': str, 'category': str}, split long bodies into chunks of at most512tokens, turn every chunk into a unit-length embedding vector, and write those chunks into a vector store idempotently. - Filtered search (
search_vector_store): Take a user query string and an optionalcategory_filter, embed the query with the exact same model, and return thetop_kbest-matching distinct documents in that category.
To make the code testable without live network services, the external collaborators are injected as keyword arguments:
embed_model.encode(texts)takes a list ofBstrings and returnsBfloat vectors (one list of floats per input string).split_text(text, max_tokens)splitstextinto a list of chunk strings ([text]if it already fits in512tokens).vector_db.upsert(records)inserts each record or overwrites any existing record with the samerecord['id'].vector_db.query(vector, filter, k)returns up tokstored records matching every key-value pair infilter, ranked highest dot-productscorefirst.
Here is how data flows through both pipelines:
INGESTION: docs ---> [1. Dedupe IDs] ---> [2. Validate & Chunk <=512] ---> [3. Batch Encode + Retry] | vector_db.upsert <--- [4. All-or-Nothing Records id="kb1#0"] <--- [L2 Normalize] RETRIEVAL: query ---> [Encode + Retry] ---> [L2 Normalize] ---> vector_db.query(vec, {"category": ...}, 3*k) | top_k docs <--- [Keep best chunk per doc_id]- Batch ingestion (
Why a naive `for` loop breaks in production
A beginner's first draft often loops
for doc in documents: vec = embed_model.encode([doc['text']])[0]; db.insert(vec). That breaks in five ways:- One network call per document is too slow: At
50 msper API round-trip,100,000products take5,000 seconds(~83 minutes) sequentially. Grouping32chunks per batch cuts100,000calls down to3,125. - One giant call for everything crashes: Passing all
100,000texts in a singleencodecall blows past GPU memory or HTTP payload limits. Fixed-size batching (EMBED_BATCH_SIZE = 32) hits the sweet spot. - Unnormalized dot products bias toward long vectors: Vector stores often score candidates with a fast dot product
a . b. Without scaling every vector to length1, a vector with larger magnitude wins even when it points in a worse direction. - Random IDs create duplicates on retries: Generating a fresh UUID on every run appends duplicate copies whenever an ingestion job restarts.
- Partial failures corrupt search: If chunk 0 of a 2-chunk product succeeds and chunk 1 times out, storing chunk 0 alone leaves half a product description in the index.
- One network call per document is too slow: At
Key math & invariants: unit vectors, deterministic IDs, all-or-nothing docs
1. Why L2 normalization turns dot products into cosine similarity: Cosine similarity measures the angle between two vectors
aandb, ignoring their lengths:cosine_similarity(a, b) = (a . b) / (||a|| * ||b||) where a . b = a_0*b_0 + a_1*b_1 + ... and ||a|| = sqrt(a_0^2 + a_1^2 + ...)If we divide every document vector
dby||d||during ingestion and divide the query vectorqby||q||during search, both vectors now have length1.0(||d|| = 1,||q|| = 1). The denominator becomes1 * 1 = 1, socosine_similarity(q, d)simplifies to plainq . d!Check with a tiny 3D example: - Document vector
a = [3, 4, 0]has lengthsqrt(9 + 16 + 0) = 5-> normalizedu_a = [0.6, 0.8, 0.0]. - Query vectorb = [4, 0, 3]has lengthsqrt(16 + 0 + 9) = 5-> normalizedu_b = [0.8, 0.0, 0.6]. - Their dot product is0.6*0.8 + 0.8*0.0 + 0.0*0.6 = 0.48, matching(3*4 + 0 + 0) / (5 * 5) = 12 / 25 = 0.48. - A zero vector[0, 0, 0]has length0and no direction, so we reject it withEmbeddingErrorinstead of dividing by zero.2. Deterministic chunk IDs give idempotency: Idempotency means running the exact same job once or five times leaves the database in the exact same state. By naming chunk
cof documentdoc_idasf"{doc_id}#{c}"(e.g.,"kb1#0","kb1#1") and keepingdoc_idin a separate metadata field, re-runningupsertcleanly overwrites"kb1#0"in place.3. All-or-nothing documents & isolated batch errors: If any chunk of
doc_idfails to embed or produces a zero/NaN vector, we recorddoc_idinbad_docsand skip all chunks ofdoc_idwhen writing tovector_db, while letting healthy batches finish normally.Helper functions: `l2_normalize` and `encode_with_retry`
Let's write two small, focused helpers first:
l2_normalize(vector)computes the Euclidean lengthnorm, rejects0.0,NaN, orinf(not math.isfinite(norm)), and divides every coordinate bynorm.encode_with_retry(...)retries transientembed_model.encodeexceptions up tomax_retriestimes using exponential backoff — waitingretry_delay, then2 * retry_delay,4 * retry_delay, and so on so a struggling model service has breathing room to recover. Ifencodereturns the wrong number of vectors, that is a code bug rather than a transient blip, so we raiseEmbeddingErrorimmediately.
from typing import Dict, List, Optional, Tuple import math import time MAX_CHUNK_TOKENS = 512 EMBED_BATCH_SIZE = 32 UPSERT_BATCH_SIZE = 100 CHUNK_OVERFETCH = 3 class EmbeddingError(Exception): """The embedding model kept failing (after retries) or returned an unusable vector.""" def l2_normalize(vector: List[float]) -> List[float]: # Compute Euclidean length sqrt(v_0^2 + v_1^2 + ...) so every stored vector has length 1.0 squared_sum = 0.0 for value in vector: squared_sum += value * value norm = math.sqrt(squared_sum) # A zero-length, NaN, or infinite vector has no valid direction for cosine similarity if norm == 0.0 or not math.isfinite(norm): raise EmbeddingError("vector has zero or non-finite length") unit_vector = [] for value in vector: unit_vector.append(value / norm) return unit_vector def encode_with_retry(embed_model, texts: List[str], max_retries: int, retry_delay: float) -> List[List[float]]: attempt = 0 while True: try: vectors = embed_model.encode(texts) except Exception as exc: # Catch client-specific timeout or network errors and retry with exponential backoff attempt += 1 if attempt > max_retries: raise EmbeddingError(f"encode failed after {attempt} attempts: {exc!r}") from exc sleep_seconds = retry_delay * (2 ** (attempt - 1)) time.sleep(sleep_seconds) continue # A shape mismatch is a contract bug rather than a transient outage, so fail immediately if len(vectors) != len(texts): raise EmbeddingError(f"model returned {len(vectors)} vectors for {len(texts)} texts") return vectorsBuild the batch ingestion pipeline
process_and_index_documentsruns in four clean phases:- Deduplicate input IDs: Missing IDs go straight to
failed. If the sameidappears twice in one call,latest_docs[doc_id] = dockeeps only the latest version. Notice we validate text after deduplicating: if"kb1"appears first with blank text and later with valid text, the valid update wins cleanly; if the later update is blank, it fails instead of indexing stale text. - Validate and chunk: Non-empty strings are passed to
split_text(text, 512)to produce(doc_id, chunk_index, chunk_text)tuples. - Batch encode and normalize: Slice
chunksin steps ofbatch_size. If a batch fails after retries, record eachdoc_idin that batch insidebad_docsand keep going with the remaining batches. - Upsert healthy documents: Skip any chunk whose
doc_idis inbad_docs, upsert the rest in batches of100, and return{"indexed": ..., "failed": ...}.
def process_and_index_documents(documents: List[dict], *, embed_model, vector_db, split_text, batch_size: int = EMBED_BATCH_SIZE, max_retries: int = 2, retry_delay: float = 0.5) -> Dict[str, list]: # failed: list of (doc_id, reason), e.g. [(None, "missing id"), ("kb9", "empty text")] failed: List[Tuple[str, str]] = [] # Phase 1: deduplicate by doc_id so repeated IDs in one batch keep only their latest version latest_docs: Dict[str, dict] = {} for doc in documents: doc_id = doc.get("id") if not doc_id: failed.append((doc_id, "missing id")) continue latest_docs[doc_id] = doc # Phase 2: validate surviving text and split long documents into <= 512-token chunks chunks: List[Tuple[str, int, str]] = [] bad_docs: Dict[str, str] = {} for doc_id, doc in latest_docs.items(): text = doc.get("text") if not isinstance(text, str) or not text.strip(): bad_docs[doc_id] = "empty text" continue pieces = split_text(text, MAX_CHUNK_TOKENS) if not pieces: bad_docs[doc_id] = "no chunks produced" continue for chunk_index, chunk_text in enumerate(pieces): chunks.append((doc_id, chunk_index, chunk_text)) # Phase 3: embed chunks in fixed-size batches and L2-normalize each resulting vector chunk_vectors: Dict[Tuple[str, int], List[float]] = {} for start in range(0, len(chunks), batch_size): batch = chunks[start:start + batch_size] batch_texts = [chunk_text for _, _, chunk_text in batch] try: raw_vectors = encode_with_retry(embed_model, batch_texts, max_retries, retry_delay) except EmbeddingError as exc: for doc_id, _, _ in batch: bad_docs.setdefault(doc_id, str(exc)) continue for (doc_id, chunk_index, _), raw_vector in zip(batch, raw_vectors): try: chunk_vectors[(doc_id, chunk_index)] = l2_normalize(raw_vector) except EmbeddingError as exc: bad_docs.setdefault(doc_id, str(exc)) # Phase 4: build deterministic chunk records (all-or-nothing per doc) and upsert in batches records = [] for doc_id, chunk_index, chunk_text in chunks: if doc_id in bad_docs: continue records.append({ "id": f"{doc_id}#{chunk_index}", "doc_id": doc_id, "chunk": chunk_index, "vector": chunk_vectors[(doc_id, chunk_index)], "category": latest_docs[doc_id].get("category"), "text": chunk_text, }) for start in range(0, len(records), UPSERT_BATCH_SIZE): vector_db.upsert(records[start:start + UPSERT_BATCH_SIZE]) indexed = [doc_id for doc_id in latest_docs if doc_id not in bad_docs] for doc_id, reason in bad_docs.items(): failed.append((doc_id, reason)) return {"indexed": indexed, "failed": failed}- Deduplicate input IDs: Missing IDs go straight to
Build the filtered search service
Two subtle bugs trip up vector search implementations:
- Post-filtering instead of pre-filtering: Suppose the knowledge base has 20
"billing"articles that match"reset"with score0.95and 1"security"article with score0.70. If you askvector_dbfor the global top 5 without a filter and filter"security"afterward in Python, all 5 slots are taken by"billing"and you falsely return[]! Always pass{"category": category_filter}insidevector_db.query. - Returning chunks instead of documents: A long article split into 4 chunks could occupy 4 of the
top_k = 5results. We askvector_db.queryfortop_k * CHUNK_OVERFETCH(3 * top_k) chunk hits, keep only the highest-scoring chunk perdoc_id, sort by(-score, doc_id), and slice[:top_k].
Also guard edge inputs cleanly:
top_k <= 0or a blank query returns[]immediately without callingembed_model, whereas a failed query embedding raisesEmbeddingErrorso callers never confuse an outage with "zero matching articles."def _rank_key(hit: dict) -> Tuple[float, str]: # Sort higher cosine similarity first; break score ties deterministically by doc_id return (-hit["score"], hit["doc_id"]) def search_vector_store(query: str, category_filter: Optional[str], top_k: int = 5, *, embed_model, vector_db, max_retries: int = 2, retry_delay: float = 0.5) -> List[dict]: # Guard invalid top_k or blank queries before spending a network call on embed_model if top_k <= 0 or not query or not query.strip(): return [] # Embed and L2-normalize the query with the exact same pipeline so dot product == cosine raw_query_vectors = encode_with_retry(embed_model, [query], max_retries, retry_delay) query_vector = l2_normalize(raw_query_vectors[0]) # Push category filtering into vector_db.query so non-matching categories cannot crowd out hits metadata_filter = {} if category_filter is not None: metadata_filter["category"] = category_filter chunk_hits = vector_db.query(query_vector, metadata_filter, top_k * CHUNK_OVERFETCH) # Collapse multiple matching chunks of the same document by keeping its highest-scoring chunk best_hit_by_doc: Dict[str, dict] = {} for hit in chunk_hits: doc_id = hit["doc_id"] if doc_id not in best_hit_by_doc or hit["score"] > best_hit_by_doc[doc_id]["score"]: best_hit_by_doc[doc_id] = hit ranked_hits = sorted(best_hit_by_doc.values(), key=_rank_key) results = [] for hit in ranked_hits[:top_k]: results.append({ "id": hit["doc_id"], "score": hit["score"], "category": hit["category"], "text": hit["text"], }) return results- Post-filtering instead of pre-filtering: Suppose the knowledge base has 20
Walk through Example 1 and complete solution
Trace Example 1 with our 3D toy model where
encode(["reset api token"]) -> [[3.0, 4.0, 0.0]],encode(["invoice tax receipt"]) -> [[0.0, 0.0, 2.0]], andencode(["rotate secret key"]) -> [[4.0, 0.0, 3.0]]:- Ingest
[{'id': 'kb1', 'text': 'reset api token', 'category': 'security'}, {'id': 'kb2', 'text': 'invoice tax receipt', 'category': 'billing'}]:latest_docs = {'kb1': ..., 'kb2': ...},chunks = [('kb1', 0, 'reset api token'), ('kb2', 0, 'invoice tax receipt')].l2_normalize([3.0, 4.0, 0.0])divides by5.0->[0.6, 0.8, 0.0];l2_normalize([0.0, 0.0, 2.0])divides by2.0->[0.0, 0.0, 1.0].vector_db.upsertstores'kb1#0'and'kb2#0'with unit vectors and metadata.- Returns
{'indexed': ['kb1', 'kb2'], 'failed': []}.
- Search
search_vector_store('rotate secret key', 'security', top_k=1):- Query vector
[4.0, 0.0, 3.0]normalizes to[0.8, 0.0, 0.6]. vector_db.query([0.8, 0.0, 0.6], {'category': 'security'}, 3)excludes'kb2#0'('billing') inside the store and computes dot product0.6*0.8 + 0.8*0.0 + 0.0*0.6 = 0.48on'kb1#0'.- Returns
[{'id': 'kb1', 'score': 0.48, 'category': 'security', 'text': 'reset api token'}].
- Query vector
Here is the complete
solution.py:from typing import Dict, List, Optional, Tuple import math import time MAX_CHUNK_TOKENS = 512 EMBED_BATCH_SIZE = 32 UPSERT_BATCH_SIZE = 100 # Multiple chunks of one long document can fill the top hits, so fetch extra chunk hits # before collapsing chunks back into distinct documents. CHUNK_OVERFETCH = 3 class EmbeddingError(Exception): """The embedding model kept failing (after retries) or returned an unusable vector.""" def l2_normalize(vector: List[float]) -> List[float]: # Compute Euclidean length sqrt(v_0^2 + v_1^2 + ...) so every stored vector has length 1.0 squared_sum = 0.0 for value in vector: squared_sum += value * value norm = math.sqrt(squared_sum) # A zero-length, NaN, or infinite vector has no valid direction for cosine similarity if norm == 0.0 or not math.isfinite(norm): raise EmbeddingError("vector has zero or non-finite length") unit_vector = [] for value in vector: unit_vector.append(value / norm) return unit_vector def encode_with_retry(embed_model, texts: List[str], max_retries: int, retry_delay: float) -> List[List[float]]: attempt = 0 while True: try: vectors = embed_model.encode(texts) except Exception as exc: # Catch client-specific timeout or network errors and retry with exponential backoff attempt += 1 if attempt > max_retries: raise EmbeddingError(f"encode failed after {attempt} attempts: {exc!r}") from exc sleep_seconds = retry_delay * (2 ** (attempt - 1)) time.sleep(sleep_seconds) continue # A shape mismatch is a contract bug rather than a transient outage, so fail immediately if len(vectors) != len(texts): raise EmbeddingError(f"model returned {len(vectors)} vectors for {len(texts)} texts") return vectors def process_and_index_documents(documents: List[dict], *, embed_model, vector_db, split_text, batch_size: int = EMBED_BATCH_SIZE, max_retries: int = 2, retry_delay: float = 0.5) -> Dict[str, list]: # failed: list of (doc_id, reason), e.g. [(None, "missing id"), ("kb9", "empty text")] failed: List[Tuple[str, str]] = [] # Phase 1: deduplicate by doc_id so repeated IDs in one batch keep only their latest version # latest_docs: {"kb1": {"id": "kb1", "text": "reset api token", "category": "security"}, ...} latest_docs: Dict[str, dict] = {} for doc in documents: doc_id = doc.get("id") if not doc_id: failed.append((doc_id, "missing id")) continue latest_docs[doc_id] = doc # Phase 2: validate surviving text and split long documents into <= 512-token chunks # chunks: [("kb1", 0, "reset api token"), ("kb3", 0, "..."), ("kb3", 1, "...")] chunks: List[Tuple[str, int, str]] = [] # bad_docs: maps doc_id -> first error message so partial documents are never indexed bad_docs: Dict[str, str] = {} for doc_id, doc in latest_docs.items(): text = doc.get("text") if not isinstance(text, str) or not text.strip(): bad_docs[doc_id] = "empty text" continue pieces = split_text(text, MAX_CHUNK_TOKENS) if not pieces: bad_docs[doc_id] = "no chunks produced" continue for chunk_index, chunk_text in enumerate(pieces): chunks.append((doc_id, chunk_index, chunk_text)) # Phase 3: embed chunks in fixed-size batches and L2-normalize each resulting vector # chunk_vectors: {("kb1", 0): [0.6, 0.8, ...], ...} chunk_vectors: Dict[Tuple[str, int], List[float]] = {} for start in range(0, len(chunks), batch_size): batch = chunks[start:start + batch_size] batch_texts = [chunk_text for _, _, chunk_text in batch] try: raw_vectors = encode_with_retry(embed_model, batch_texts, max_retries, retry_delay) except EmbeddingError as exc: # Isolate batch failures: mark affected documents failed, keep processing later batches for doc_id, _, _ in batch: bad_docs.setdefault(doc_id, str(exc)) continue for (doc_id, chunk_index, _), raw_vector in zip(batch, raw_vectors): try: chunk_vectors[(doc_id, chunk_index)] = l2_normalize(raw_vector) except EmbeddingError as exc: bad_docs.setdefault(doc_id, str(exc)) # Phase 4: build deterministic chunk records (all-or-nothing per doc) and upsert in batches records = [] for doc_id, chunk_index, chunk_text in chunks: if doc_id in bad_docs: continue records.append({ "id": f"{doc_id}#{chunk_index}", "doc_id": doc_id, "chunk": chunk_index, "vector": chunk_vectors[(doc_id, chunk_index)], "category": latest_docs[doc_id].get("category"), "text": chunk_text, }) for start in range(0, len(records), UPSERT_BATCH_SIZE): vector_db.upsert(records[start:start + UPSERT_BATCH_SIZE]) indexed = [doc_id for doc_id in latest_docs if doc_id not in bad_docs] for doc_id, reason in bad_docs.items(): failed.append((doc_id, reason)) return {"indexed": indexed, "failed": failed} def _rank_key(hit: dict) -> Tuple[float, str]: # Sort higher cosine similarity first; break score ties deterministically by doc_id return (-hit["score"], hit["doc_id"]) def search_vector_store(query: str, category_filter: Optional[str], top_k: int = 5, *, embed_model, vector_db, max_retries: int = 2, retry_delay: float = 0.5) -> List[dict]: # Guard invalid top_k or blank queries before spending a network call on embed_model if top_k <= 0 or not query or not query.strip(): return [] # Embed and L2-normalize the query with the exact same pipeline so dot product == cosine raw_query_vectors = encode_with_retry(embed_model, [query], max_retries, retry_delay) query_vector = l2_normalize(raw_query_vectors[0]) # Push category filtering into vector_db.query so non-matching categories cannot crowd out hits metadata_filter = {} if category_filter is not None: metadata_filter["category"] = category_filter chunk_hits = vector_db.query(query_vector, metadata_filter, top_k * CHUNK_OVERFETCH) # Collapse multiple matching chunks of the same document by keeping its highest-scoring chunk # best_hit_by_doc: {"kb1": {"doc_id": "kb1", "score": 0.87, ...}, ...} best_hit_by_doc: Dict[str, dict] = {} for hit in chunk_hits: doc_id = hit["doc_id"] if doc_id not in best_hit_by_doc or hit["score"] > best_hit_by_doc[doc_id]["score"]: best_hit_by_doc[doc_id] = hit ranked_hits = sorted(best_hit_by_doc.values(), key=_rank_key) results = [] for hit in ranked_hits[:top_k]: results.append({ "id": hit["doc_id"], "score": hit["score"], "category": hit["category"], "text": hit["text"], }) return results✅ Submit now — all tests should pass.
- Ingest
Intuition & how it works
Think of an embedding (a fixed-length list of numbers produced by a neural network to represent a text's meaning) as GPS coordinates on a semantic map: "reset api token" and "rotate secret key" land right next to each other even though they share zero words. To build a reliable search engine on top of that map, we standardize every arrow to have length 1.0 (L2 normalization, dividing each number in a vector by the square root of the sum of its squared numbers) so that comparing any two arrows only requires multiplying matching coordinates and adding them up (a dot product), which then equals cosine similarity (how closely two vectors point in the same direction, from -1 to +1).
A naive loop that embeds one document per API call, appends random record IDs, and filters categories after fetching the top 5 results breaks immediately at production scale. Calling the model one text at a time wastes hours on network round-trips (while sending all texts at once overflows GPU memory), random IDs create duplicate search hits whenever a failed job is retried, and filtering after retrieval returns empty results whenever another category crowds out the global top 5. Instead, we chunk long documents to <= 512 tokens, embed in fixed batches of 32 with retries, upsert (insert if new, overwrite if the ID already exists) using deterministic "doc_id#chunk" keys for idempotency (running the same job twice produces the exact same stored state), and push category filters directly into the vector database query.
Walk through a concrete 2-document trace in 3D:
1. Suppose "kb1" ("reset api token", "security") encodes to [3, 4, 0] (length 5 -> normalized [0.6, 0.8, 0.0]) and "kb2" ("invoice tax receipt", "billing") encodes to [0, 0, 2] (length 2 -> normalized [0.0, 0.0, 1.0]). We upsert "kb1#0" and "kb2#0".
2. An engineer searches "rotate secret key" inside "security" with top_k = 1, and the query encodes to [4, 0, 3] (length 5 -> normalized [0.8, 0.0, 0.6]).
3. vector_db.query([0.8, 0.0, 0.6], {"category": "security"}, 3) restricts candidates to "security" ("kb1#0", preventing "kb2#0" from winning with 0.60), computes dot product 0.6*0.8 + 0.8*0.0 + 0.0*0.6 = 0.48, deduplicates by doc_id, and returns [{"id": "kb1", "score": 0.48, ...}].
Complexity
Let D be the number of input documents, C be the total number of <= 512-token chunks produced across them, B be batch_size (32), d be the embedding dimension (e.g., 768), and M be the total chunks stored in vector_db.
- Ingestion time —
O(C * d)CPU work plusceil(C / B)model API calls andceil(C / 100)DB upsert calls: We scanDdocuments once to deduplicate IDs, split valid texts intoCchunks, sendceil(C / B)batches toembed_model.encode(which dominates wall-clock latency), and spendO(d)arithmetic per chunk insidel2_normalize. - Ingestion space —
O(C * d): One invocation holds theCchunks and theird-dimensional normalized float lists in memory before upserting; for millions of catalog items, stream pages of ~1,000 documents per call so memory stays bounded. - Search time —
1model call +O(d)normalization +vector_db.query+O(h log h)deduplication/sort whereh <= 3 * top_k: A brute-force flat vector store scansO(M * d)floats, whereas production approximate nearest-neighbor indexes like HNSW (Hierarchical Navigable Small World, a multi-layer proximity graph over vectors) search in roughlyO(d * log M)time. - Search space —
O(d + h): We hold only the singled-float query vector and at mosth = 3 * top_kcandidate chunk records in memory.
Edge cases
- Empty
documentslist ([]): Makes zero calls toembed_modelorvector_dband returns{"indexed": [], "failed": []}. - Missing
idor blank/whitespacetext: Caught before callingembed_modeland reported in"failed". - Duplicate
idwithin the samedocumentscall: Deduplicated up front so the last occurrence wins; if"kb1"arrives blank first and valid second it succeeds cleanly, whereas valid first and blank second marks"kb1"failed without indexing stale text. - Splitter produces zero chunks (e.g., punctuation-only text stripped by tokenizer): Caught by
if not pieces:and marked failed rather than falsely reported as indexed with zero stored vectors. - Zero-length,
NaN, orinfvector from the model: Rejected byl2_normalize(norm == 0.0 or not math.isfinite(norm)), failing the owning document cleanly instead of storingNaNscores that poison rankings. - Multi-chunk document partially fails across batch boundaries: Because
recordsskips every chunk whosedoc_idappears inbad_docs, a document is indexed all-or-nothing. - Blank query,
top_k <= 0, or category with zero matches: Returns[]cleanly (and blank/top_k <= 0skips theembed_modelcall completely), whereas a broken query model raisesEmbeddingErrorso the caller can return HTTP 503 instead of fake empty search results.
Common mistakes
- Normalizing stored vectors without normalizing the query (or vice versa): If stored document vectors are unnormalized, longer vectors artificially inflate dot products and corrupt the ranking order; if the query vector is unnormalized, relative order holds for one query but similarity scores are scaled by
||query||and lose their[-1, 1]cosine meaning. - Using random UUIDs instead of deterministic IDs: Assigning
uuid4()per chunk turns every pipeline retry into duplicate vectors that filltop_kresults with copies of the same article. - Filtering categories after
vector_db.query: Fetching the globaltop_kfirst and filtering in Python returns[]whenever popular items from other categories take alltop_kslots. - Returning raw chunks instead of distinct documents: Without over-fetching (
top_k * CHUNK_OVERFETCH) and grouping bydoc_id, one 2,000-word article can monopolize all 5 search slots. - Swallowing query embedding exceptions into
return []: Returning an empty list when the embedding service times out hides outages behind "No results found" pages instead of triggering alerts or fallback keyword search. - Upgrading the embedding model without re-indexing: Vectors from Model v2 live in a rotated coordinate space incompatible with Model v1 vectors; query and index models must always match.
Alternative approaches
- Vectorized NumPy normalization: When
embed_model.encodereturns a 2Dnumpy.ndarrayof shape(B, d), normalize an entire batch in C without Python loops (checking zero norms per row so one bad row can still be isolated):
import numpy as np
def l2_normalize_batch(matrix: np.ndarray) -> np.ndarray:
norms = np.linalg.norm(matrix, axis=1, keepdims=True)
if np.any((norms == 0.0) | ~np.isfinite(norms)):
raise ValueError("batch contains a zero or non-finite vector")
return matrix / norms
- Binary-splitting poison batches: If a batch of 32 chunks fails permanently because a single malformed text crashes the model, recursively split the failed batch into two halves of 16, 8, ..., 1 to isolate the single bad chunk in
log2(32) = 5extra calls while rescuing the other 31 chunks. - Hybrid lexical + vector search: Combine dense cosine similarity with BM25 (a classic keyword-matching score based on term frequency and word rarity) via Reciprocal Rank Fusion so exact error codes like
"ERR_OAUTH_401"match precisely alongside semantic queries like"rotate expired credentials".
Follow-up questions
-
When source articles are edited or shortened over time, how do you keep the vector store synchronized without leaving orphaned chunks behind? Store a
content_hash = sha256(model_version + "\n" + text)andchunk_countalongside each document so unchanged items skip re-embedding completely. When an article's text changes, upsert the new chunks first and then delete stale tail chunks: for example, if"kb1"shrinks from 4 chunks (kb1#0..kb1#3) to 2 chunks (kb1#0..kb1#1), explicitly deletekb1#2andkb1#3so old paragraphs stop matching searches. Stream updates from a transactional outbox with a monotonicversionnumber perdoc_id(ignoring out-of-order older versions), run a nightly reconciliation sweep comparing source hashes against indexed hashes, and handle embedding-model upgrades via blue-green indexing (build a complete second index with the new model, then atomically swap the read alias). -
Once the vector collection outgrows a single machine's RAM, how would you compress, tier, and shard the index across nodes? First size the footprint:
50 millionchunks at768float32 dimensions (4bytes each) takes50M * 768 * 4 ≈ 153.6 GBof raw vectors before graph overhead. You can first shrink RAM per node by2xwithfloat16or by32x(~4.8 GB) using product quantization (splitting each 768D vector into 96 sub-vectors and replacing each sub-vector with a 1-byte nearest-centroid ID), keeping full float32 vectors on NVMe SSDs (or disk-backed indexes like DiskANN / IVF, Inverted File indexes that cluster vectors into Voronoi cells on disk) to re-score the top 100 candidates accurately. Beyond one machine, shard byhash(doc_id)for uniform storage and query load: a coordinator fans each query out to allSshards in parallel, fetches each shard's filteredtop_k, and merges theS * top_kcandidates inO(S * top_k). (Sharding bycategoryavoids fan-out on category-filtered queries, but creates hot shards for popular categories like"security"and still requires full fan-out whencategory_filterisNone.) -
What offline benchmarks, live user signals, and score-distribution checks would you track to detect retrieval quality degradation as content and queries evolve? Monitor four complementary signals across offline quality, online user behavior, vector geometry, and pipeline health. First, run an automated golden evaluation set (hundreds of real queries paired with human-judged relevant articles) every day and alert if recall@5 (the fraction of relevant items appearing in the top 5) or nDCG@10 (Normalized Discounted Cumulative Gain, a ranking score that rewards placing stronger matches closer to rank 1) drops. Second, track online behavioral metrics: top-3 click-through rate, resolution/conversion rate from search, query reformulation rate, and zero-result rate. Third, monitor score and embedding drift by tracking the daily distribution of top-1 cosine similarity scores (using a Kolmogorov-Smirnov test or Population Stability Index against a baseline week — a sudden drop flags new terminology or thin descriptions the model does not understand) alongside ingestion lag and failed-document rates.
Follow-up questions
- When source articles are edited or shortened over time, how do you keep the vector store synchronized without leaving orphaned chunks behind?
- Once the vector collection outgrows a single machine's RAM, how would you compress, tier, and shard the index across nodes?
- What offline benchmarks, live user signals, and score-distribution checks would you track to detect retrieval quality degradation as content and queries evolve?
Similar questions
- Selecting Sorting Algorithms Under Production Constraints
- Scalable PDF Parsing and Cited RAG Service
- Low-Latency Tree Ensemble Inference
- Select Score Cutoff for Target Precision
- Payment Fraud Detection Under Class Imbalance and Drift
- Diagnosing and Fixing Overfitting in Supervised Learning