GPT-4o vector index corruption after batch embedding update in Kubernetes

Problem: Vector Index Corruption After Batch Embedding Update

In a multi‑tenant OpenAI GPT‑4o service running on Kubernetes, a nightly batch job that recomputes embeddings for a tenant’s document corpus occasionally leaves the persistent FAISS (or HNSW) index in a corrupted state. The symptoms observed by downstream retrieval services are:

  • Missing entries for newly added documents.
  • Duplicate vectors for existing documents, causing inflated similarity scores.
  • FAISS load failures with faiss::Index::deserialize: corrupted index file errors.
  • Intermittent HTTP 500 responses from the /search endpoint.

Because the index is stored on a shared PersistentVolumeClaim (PVC) that is mounted by all autoscaling compute pods, a corrupted index propagates to every replica, leading to a service‑wide outage.

Root Cause Analysis

The batch embedding pipeline performs the following steps:

  1. Pull the latest document set from the tenant’s object store.
  2. Generate embeddings using the openai.ChatCompletion API with the gpt-4o model.
  3. Append the new vectors to the existing FAISS index file stored on the PVC.
  4. Replace the old index file with the newly written file using a mv operation.

Two intertwined issues cause corruption:

  • Concurrent Index Writes: The batch job runs as a Kubernetes Job while the serving pods may still be reading the index. The mv replace is not atomic across NFS‑based PVCs, leading to a race where a pod opens the file while it is partially overwritten.
  • Partial Write on Out‑of‑Memory (OOM) Events: The embedding generation step streams vectors into memory. When the node hits memory pressure, the Python process is killed, leaving the temporary index file truncated. The subsequent mv replaces the good index with this truncated file.

Both conditions result in a corrupted binary index that FAISS cannot deserialize correctly, manifesting as missing or duplicated entries.

Debug: Investigation Steps

1. Log Inspection

Search the pod logs for the batch job and serving pods around the failure window.

kubectl logs -l job-name=gpt4o-embed-batch -n gpt4o -c embedder --since=2h
kubectl logs -l app=gpt4o-search -n gpt4o -c searcher --since=2h | grep -i "faiss"

Typical error snippets:

2026-11-22T03:14:12Z ERROR faiss.index - faiss::Index::deserialize: corrupted index file (size=0)
2026-11-22T03:14:13Z WARN searcher - Failed to load vector index, falling back to empty index

2. File System State

Inspect the index file size before and after the batch job.

# On a pod that has the PVC mounted
ls -lh /data/vector_indexes/tenant-123.idx
# Example output before batch
-rw-r--r-- 1 root root 1.2G Nov 21 22:00 tenant-123.idx
# After batch (corrupted)
-rw-r--r-- 1 root root 0 Nov 22 03:14 tenant-123.idx

3. Resource Metrics

Check node memory pressure during the batch run.

kubectl top pod -l job-name=gpt4o-embed-batch -n gpt4o
NAME                                 CPU(cores)   MEMORY(bytes)
gpt4o-embed-batch-5f9c7d9f9-abcde    2.5          7.8Gi

If MEMORY(bytes) approaches the node limit, OOM kills are likely.

4. Concurrency Check

Verify that no serving pod holds an open file descriptor on the index during the replace.

kubectl exec -it $(kubectl get pod -l app=gpt4o-search -n gpt4o -o jsonpath="{.items[0].metadata.name}") -c searcher -- lsof | grep tenant-123.idx
# No output indicates no open descriptor, but race windows still exist.

Solution: Atomic Index Replacement and Memory Guardrails

1. Write‑Ahead Temporary Index

Modify the batch job to write the new index to a temporary file and then atomically replace the live index using renameat2 with the RENAME_EXCHANGE flag, which is supported on most Linux kernels and works correctly on ext4 and xfs backing the PVC.

# embed_batch.py (excerpt)
import os
import faiss
import shutil

tmp_path = "/data/vector_indexes/tenant-123.idx.tmp"
final_path = "/data/vector_indexes/tenant-123.idx"

# Build new index
index = faiss.IndexFlatL2(1536)
for vec in new_embeddings:
    index.add(vec)

faiss.write_index(index, tmp_path)

# Atomic replace
os.rename(tmp_path, final_path)  # rename is atomic on same filesystem

2. Use a Sidecar Lock Service

Introduce a lightweight lock sidecar (e.g., etcd lease) that the batch job acquires before starting the replace. Serving pods check the lock before loading the index; if the lock is held, they continue using the previous index until the new one is ready.

# lock_client.py (simplified)
import etcd3

client = etcd3.client()
lock = client.lock("tenant-123-index-lock", ttl=300)

if lock.acquire():
    try:
        # perform index write and atomic rename
        ...
    finally:
        lock.release()

3. Memory Guardrails

Configure the batch job’s pod with a memory request/limit that provides a safety margin and enable the OOM killer to send a SIGTERM to the process, allowing graceful cleanup.

# deployment.yaml snippet
resources:
  requests:
    memory: "8Gi"
    cpu: "2"
  limits:
    memory: "10Gi"
    cpu: "4"
terminationGracePeriodSeconds: 120

4. PVC Snapshot Backup

Before each batch run, create a snapshot of the index PVC. If corruption is detected, roll back instantly.

# Using Velero or CSI snapshot
kubectl snapshot create tenant-123-idx-snap-$(date +%s) \
  --namespace gpt4o \
  --volume-snapshot-class=csi-hostpath-snapclass \
  --source-pvc=tenant-123-idx-pvc

Verification: Confirming a Healthy Index

1. Post‑Deployment Health Check

curl -s -o /dev/null -w "%{http_code}" http://search-service.gpt4o.svc.cluster.local/v1/search?query=test
# Expected output: 200

2. Index Integrity Test

Run a small sanity query against the newly loaded index.

# sanity_check.py
import faiss, numpy as np, requests, json

index_path = "/data/vector_indexes/tenant-123.idx"
index = faiss.read_index(index_path)

# Verify number of vectors matches expected count
expected = 124567
actual = index.ntotal
assert actual == expected, f"Vector count mismatch: {actual} vs {expected}"

# Perform a nearest‑neighbor lookup
query = np.random.rand(1, 1536).astype('float32')
D, I = index.search(query, k=5)
print("Top distances:", D)

3. Monitoring Metrics

Ensure the following Prometheus alerts are green:

Alert Condition
VectorIndexLoadFailure rate(search_index_load_errors[5m]) > 0
EmbeddingBatchOOM kube_pod_container_status_last_termination_reason{reason=”OOMKilled”} > 0

Prevention: Operational Guardrails

  • Atomic Writes: Always write to a temporary file and rename.
  • Lock Coordination: Use a distributed lock (etcd, Consul) to serialize index updates with reads.
  • Resource Sizing: Allocate at least 20 % headroom above peak memory usage of the embedding pipeline.
  • Snapshot & Rollback: Automate PVC snapshots before each batch run and retain at least two recent snapshots.
  • Canary Deployment: Deploy the new index to a single replica first; verify health before scaling out.
  • Observability: Emit a custom metric gpt4o_index_update_success{tenant="123"} and alert on missing success events.

Related Topic Hub: LLM Systems Troubleshooting Hub

FAQ

  1. Why does the index sometimes load successfully after a failure?
    Because some serving pods may have cached the previous in‑memory index while others attempt to reload the corrupted file. The pod that succeeds continues serving, masking the failure until a rollout forces all pods to reload.
  2. Can I use a cloud‑native vector store (e.g., Pinecone) to avoid this issue?
    External managed stores eliminate local file‑system races, but they introduce network latency and cost considerations. The same concurrency principles apply if you perform bulk upserts.
  3. How do I detect a partially written index before the rename?
    Check the temporary file size against an expected threshold (e.g., stat -c %s /data/...tmp) and verify that faiss.read_index succeeds in a dry‑run container.
  4. Is the rename operation truly atomic on NFS‑backed PVCs?
    On most Kubernetes CSI drivers backed by block storage (e.g., EBS, GCE PD) the rename is atomic within the same volume. For NFS‑based PVCs, enable nfs4 with no_subtree_check to preserve atomicity.
  5. What should I do if the OOM killer still terminates the job despite higher limits?
    Profile memory usage of the embedding loop (e.g., using tracemalloc) and batch the embeddings into smaller chunks, flushing to disk after each chunk to keep the resident set low.