AI Data Engineering · By Divya Madhavan
PySpark Vector Ingestion for RAG: Token-Aware Chunking, Embedding Retries and Index Versions
Build repeatable RAG ingestion with token-aware PySpark preparation, bounded embedding workers and versioned vector records that support replay and deletion.
Design ingestion around a recoverable document version
A RAG index is a derived representation of approved source material. Retain the source URI, document identity, source version, tenant and access policy before producing chunks. Separate extraction, text normalization, chunk preparation, embedding computation and index publication so each stage can be retried and inspected. Keep a manifest of expected chunk IDs and processing states. Preparing context for retrieval does not train or fine-tune an LLM. This is a reference design, not a claim about an employer’s AI system or a production benchmark.
Token-aware text chunking without breaking Unicode
Character counts are not token counts. Select the tokenizer that matches the embedding model and leave room for provider-specific input constraints. The helper below counts tokens in original Unicode character slices rather than decoding arbitrary token windows that might split a multi-byte character. Its binary search returns a fitting slice, not necessarily the largest possible slice, because token counts are not guaranteed to grow monotonically with character length. Overlap is measured in characters and is deliberately a separate setting. This transparent teaching algorithm may make many tokenizer calls: profile it before large-scale use and prefer a tested semantic splitter when paragraph or code boundaries matter.
import hashlib
import json
def chunk_text(text, encode, max_tokens=256, overlap_chars=40):
"""Keep original Unicode text; token limit uses the supplied tokenizer."""
if max_tokens < 1 or overlap_chars < 0:
raise ValueError("Invalid chunk settings")
start = 0
while start < len(text):
# Binary search for a fitting character slice. Token counts need
# not be monotonic: this finds a valid slice, not a maximal one.
low, high = start, len(text)
while low < high:
mid = (low + high + 1) // 2
if len(encode(text[start:mid])) <= max_tokens:
low = mid
else:
high = mid - 1
end = low
if end == start:
raise ValueError("Token budget cannot fit the next character")
piece = text[start:end]
assert len(encode(piece)) <= max_tokens
yield piece
if end == len(text):
break
start = max(start + 1, end - overlap_chars)
def chunk_id(doc_id, source_version, config_version, ordinal, text):
identity = [doc_id, source_version, config_version, ordinal, text]
return hashlib.sha256(
json.dumps(identity, ensure_ascii=False).encode("utf-8")
).hexdigest()
# Example tokenizer only: match the tokenizer to your embedding model.
# Install tiktoken on every Python worker before using the Spark UDF.
# import tiktoken
# encode = tiktoken.get_encoding("cl100k_base").encode_ordinary
# chunks = list(chunk_text("Your approved source text", encode))
Apply chunking in PySpark on Dataproc or Databricks
Install the same tokenizer and transformation code on every worker, pin dependencies, and record the tokenizer name alongside the chunk configuration. The UDF below produces a simple array of chunks, then posexplode preserves the ordinal. It assumes a prevalidated documents DataFrame and a unique output path for the run. Filter or quarantine oversized documents before the UDF, since one document’s entire chunk array lives in a Python worker. Preserve access labels and source links in your real schema; the short projection omits them only to focus on chunk preparation. This integration snippet was syntax-checked, not run on a Spark cluster.
from functools import lru_cache
from pyspark.sql import functions as F, types as T
@lru_cache(maxsize=1)
def tokenizer():
import tiktoken
return tiktoken.get_encoding("cl100k_base")
# Include chunk_text from the previous block in this module.
@F.udf(T.ArrayType(T.StringType()))
def split_document(text):
if text is None:
return []
return list(chunk_text(text, tokenizer().encode_ordinary))
# docs must contain doc_id, source_version and approved text columns.
# Keep tenant and access metadata in the real input schema.
# Reject/quarantine oversized source documents before this step:
# the UDF materializes all chunks for one document in worker memory.
chunked = (
docs.withColumn("chunks", split_document(F.col("text")))
.select("doc_id", "source_version",
F.posexplode("chunks").alias("ordinal", "chunk_text"))
)
# Persist the deterministic preparation result before paid API calls.
chunked.write.mode("errorifexists").parquet("gs://YOUR_BUCKET/chunks/RUN_ID")
Separate parallel embedding generation from pure Spark transformations
Do not hide paid network calls inside a UDF and assume each row is processed once. Failed tasks, speculative execution and repeated actions can repeat those calls. A practical design materializes chunks first, then dispatches bounded work to embedding workers that record durable results keyed by chunk ID plus embedding-model version. An embedding cache reduces repeat billing, but check-and-write alone is not a concurrency lock; coordinate claims or tolerate duplicate computation explicitly. If you use mapInPandas for self-hosted batch inference, initialize the model per worker/partition, bound batch memory and account for worker CPU or GPU placement. Spark ML is not itself an external embedding service.
Handle partial embedding failures before publishing an index
Batch only within the model provider’s input, token and request limits. Limit concurrency across the whole job, rather than multiplying an arbitrary thread count by every Spark partition. Use bounded exponential backoff with jitter for retryable failures and honor provider retry guidance. Persist successes so one rejected input does not force a complete batch to be billed again. Validate result cardinality, expected dimensions and finite vector values; record failures for quarantine. A generic mock vector is not a semantic embedding and should never be presented as a working retrieval example.
Use deterministic chunk IDs and explicit index generations
The chunk_id helper includes the document version, transformation/model configuration, ordinal and content. Reprocessing identical inputs yields identical identities, while changing the embedding model produces a distinct generation when the configuration version changes. Make configuration versions immutable and include the actual model revision when available. Upserting an existing ID may replace its record, but changing a document from ten chunks to six still leaves four old records unless you delete them. Use the manifest to reconcile expected IDs and deletions; keep serving on the previous verified generation until the new one passes checks.
Pinecone upserts: select the API for your index type
Match the client and request shape to the index you actually provisioned. Pinecone distinguishes document indexes from legacy vector indexes; an example for one API should not be pasted into the other. When supplying your own vectors, verify dimension and similarity settings against the embedding model. Use deterministic record identities within the intended namespace and replay the same immutable record after an ambiguous write result. Batch within the active API’s payload limits, and test visibility before switching consumers. No ingestion or query latency guarantee follows from using a vector database; measure both under the intended workload.
Protect access and deletion paths as carefully as retrieval quality
Attach tenant and permission metadata to each record, apply authorization filters during retrieval, and test cross-tenant isolation using denied-access cases. A namespace name by itself is not an application authorization check. Source deletion or access revocation needs to propagate to chunks, stored embeddings, vector records and caches, with an observable completion target. Avoid sending restricted text to an external model unless that processing is approved. Do not embed secrets into notebooks, Spark configuration dumps or downloadable examples.
Validate relevance, replay and operating cost
Build a small labeled set of questions with relevant source documents and track retrieval recall at a chosen k, citation support and stale-result rate. Test empty text, multilingual content, duplicate document IDs, model-version changes, partial embedding failure and source deletion. Re-run an identical batch and confirm the manifest converges without increasing the intended record count; inspect whether repeated external calls still incurred cost. Track tokens embedded, retries, failed chunks, index freshness and end-to-end latency. The chunker’s bounds, Unicode preservation and deterministic IDs were checked locally; external model and vector-store calls were not executed.