Skip to main content

Switching Embedding Models? Every Vector Needs a Recipe ID

Your vector database only validates length. Here's the schema, guard, and drift check that catch every other embedding mismatch.

Updated 11 min readMarkdown
Switching Embedding Models? Every Vector Needs a Recipe ID

This is the best error your vector search will ever give you:

ERROR:  expected 1536 dimensions, not 3072

It fires the instant you insert a vector of the wrong length into a pgvector vector(1536) column. Qdrant and Pinecone have their own versions. It's loud, it's specific, and it stops bad data before any user sees a strange result.

It's also the only embedding mistake your database can catch. Length is the one property of a vector you can check without knowing where it came from. Everything else about a vector's origin (which model, which prefix, which cleaning steps, which chunker) is invisible to the database. So every change that keeps the length slips straight through, and search keeps returning ten results with confident scores. Just worse ones.

This post covers the six silent mismatches, why they keep happening, and the three pieces of code that turn them into loud failures.

Why vectors from different recipes can't be compared

An embedding is a coordinate on a map of meaning. Each embedding model draws its own map: different training, different orientation, different scale. A coordinate is only meaningful on the map that produced it.

Put two vectors from different maps into a cosine similarity and you still get a number between -1 and 1. The math doesn't know anything is wrong. The number is just meaningless.

The textbook case: text-embedding-ada-002 and text-embedding-3-small both return 1,536 numbers by default. Swap one for the other and the column accepts the new vectors without complaint. They're still not comparable. Users on OpenAI's developer forum have tested this directly, including truncating text-embedding-3-large down to 1,536: no compatibility with ada-002 vectors.

Two-column card comparing changes that fail loudly (dimension count, unknown model name, missing index) with changes that fail silently (same-size model swap, dropped query prefix, changed text cleaning, new chunker, truncation without renormalizing, half-migrated corpus).

The six silent mismatches

# Change Why it's silent
1 Same-size model swap Same length, different map. The dimensions parameter on text-embedding-3 models makes more models fit the old column.
2 Role marker dropped Asymmetric models embed queries and documents differently and must be told which is which.
3 Text preparation changed Same model, different input string, different vector.
4 Chunker changed Same model, but each vector now stands for different text.
5 Shape changed Truncation without renormalizing, or mixing quantized and float vectors, skews scores.
6 Half the corpus re-embedded Query compares meaningfully to one half, randomly to the other.

A few of these deserve specifics.

The role marker

Cohere's v3 embedding models require input_type: search_document for stored content and search_query for searches. The E5 family expects inputs to start with query: or passage: , and the model card says skipping the prefix degrades performance.

Vertex AI is the trap worth memorizing. Its task_type defaults to RETRIEVAL_QUERY when unset. An ingestion job that forgets the parameter doesn't fail. It embeds your entire corpus as if every document were a question.

# Ingestion path (correct)
doc_vec = embed(chunk_text, task_type="RETRIEVAL_DOCUMENT")

# Ingestion path (silent bug: falls back to RETRIEVAL_QUERY)
doc_vec = embed(chunk_text)

The shape

OpenAI returns vectors normalized to length 1, including after shortening with the dimensions parameter. If you slice the array yourself and skip re-normalizing, dot-product search starts rewarding vector length instead of closeness.

import numpy as np

v = np.array(full_vector[:512])
v = v / np.linalg.norm(v)   # skip this line and dot product != cosine

The half-migrated index

"We'll re-embed gradually" produces the worst state of all. A new-model query scores the old-model half at random, and random scores aren't reliably low. Some irrelevant old chunks rank in the top ten; the relevant old chunks never surface. The results look like a normal mix of good and odd.

A half-migrated index isn't halfway better. It's two maps stapled together.

Why it keeps happening: two copies of one recipe

Documents are embedded by an ingestion path, usually a batch worker. Queries are embedded by the search path, live, per request. Often different services, sometimes different languages, written months apart. Each one builds its own request to the embedding API, so each one holds its own copy of the recipe.

Edit one copy and nothing notices. The model name also looks like a config value, so it gets reviewed like one. (More on that failure class in Nobody Deployed Anything. Production Broke Anyway.)

Flow diagram: an ingestion worker embeds documents with recipe A, a search API embeds questions with recipe B and compares them against the index with no error. The fix routes both paths through one embed function that stamps a recipe_id, checked by an index guard.

Fix 1: The Legend and a recipe_id

Six fields fully describe how a vector was made. I call them the Legend, because they're what tells you which map a coordinate belongs to.

The Legend: six numbered fields every vector needs. Model, Role, Preparation, Chunking, Shape, Distance.

Put them in one module that both paths import:

# embedding_recipe.py  (the ONLY module that talks to the embedding API)
import hashlib, json

LEGEND = {
    "model": "text-embedding-3-small",
    "role": {"query": None, "document": None},   # input_type / task_type / prefix
    "prep": "strip_html_v2|collapse_whitespace",
    "chunker": "headings_v3|size=400|overlap=60",
    "shape": {"dims": 1536, "normalized": True, "dtype": "float32"},
    "distance": "cosine",
}
RECIPE_ID = hashlib.sha256(
    json.dumps(LEGEND, sort_keys=True).encode()
).hexdigest()[:12]

def embed(text: str, role: str) -> list[float]:
    prepared = prepare(text)                    # the one prep function
    return client.embed(prepared, **role_args(role))

Store the id, and the exact text you embedded, on every row:

ALTER TABLE chunks
  ADD COLUMN recipe_id     text NOT NULL,
  ADD COLUMN embedded_text text NOT NULL;   -- you can't re-embed what you didn't keep

CREATE INDEX ON chunks (recipe_id);

Fix 2: The query guard

The guard is the dimension check, extended to everything the dimension check can't see.

class RecipeMismatch(RuntimeError):
    pass

def search(question: str, k: int = 10):
    active = index_registry.active_recipe("chunks")
    if active != RECIPE_ID:
        raise RecipeMismatch(f"index={active} query={RECIPE_ID}")
    vec = embed(question, role="query")
    return db.fetch(
        """SELECT id, embedded_text
           FROM chunks
           WHERE recipe_id = %s
           ORDER BY embedding <=> %s::vector
           LIMIT %s""",
        (RECIPE_ID, vec, k),
    )

Deploy a search service with a different Legend and it fails on the first request instead of serving bad results for three weeks.

Fix 3: The Landmark Check

The Legend catches your changes. It can't catch a dependency bump that changes tokenization or a hosted model that behaves differently than last month. For that, re-survey fixed landmarks.

LANDMARKS = load_landmarks()   # 20-50 real queries + chunks, with stored vectors

def landmark_check(floor: float) -> list[str]:
    drifted = []
    for lm in LANDMARKS:
        live = embed(lm.text, role=lm.role)    # through the LIVE code path
        sim = cosine(live, lm.stored_vector)
        if sim < floor:
            drifted.append(f"{lm.id}: {sim:.5f}")
    return drifted

Set floor from data: embed the landmarks twice back-to-back and look at the lowest similarity. Hosted APIs aren't always bit-for-bit identical, though forum tests of the same model on the same text report similarities above 0.9999. Run the check in CI on every deploy of either path, plus a daily cron. Add ten labeled questions whose correct document must stay in the top five, so you also see when drift starts to hurt ranking.

Migrating to a new embedding model safely

A new recipe means a new index. The order:

  1. Keep the source. embedded_text on every row. Re-chunking "from the original files" breaks the day a file changes.
  2. Create the new index (new collection or new column) under the new recipe_id.
  3. Dual-write new documents to both. Dual writes have an ordering trap; see There's No Safe Order for Two Writes. Let the backfill reconcile what the dual write misses.
  4. Backfill with keyset pagination, not OFFSET, or rows inserted mid-run get skipped:
SELECT id, embedded_text
FROM chunks
WHERE recipe_id = :old_recipe AND id > :last_id
ORDER BY id
LIMIT 500;

Background: Offset vs Cursor Pagination: Why Your Pages Skip and Repeat Rows.

  1. Evaluate on labeled questions, not result overlap. Overlap measures difference, not quality.
  2. Flip the active recipe in one move, keep the old index for a rollback window, then flush anything that cached query vectors (semantic caches included).

Cost is rarely the blocker. As an illustration, 2 million chunks × ~400 tokens = 800M tokens; at text-embedding-3-small's $0.02 per million tokens that's about $16. The expensive parts are double storage, evaluation, and lost source text. For very large corpora, the Drift-Adapter paper (2025) reports that a learned mapping recovers 95 to 99% of full re-embedding recall: useful as a bridge, not a destination.

Key Takeaways

  • Your vector database validates length only. A length change is the only embedding mistake that errors.
  • Same-size model swaps, missing input_type/task_type/prefixes, new cleaning steps, new chunkers, unnormalized truncation, and half-migrated indexes all fail silently.
  • The root cause is structural: ingestion and search each hold a copy of the recipe.
  • Put the recipe (the Legend) in one module, hash it into a recipe_id, store it per row, and refuse cross-recipe queries.
  • Watch for drift you didn't cause with a Landmark Check against a measured noise floor.
  • New recipe = new index. Never write new-recipe vectors into an old-recipe index.

FAQ

Do I need to re-embed my documents when switching embedding models?

Yes. Vectors from different models live in different spaces, so query vectors from the new model can't be meaningfully compared with document vectors from the old one. Re-embed the full corpus into a new index, then switch the search path over.

Can I mix embeddings from two models if they have the same dimensions?

No. Matching dimensions only means the database will accept both. text-embedding-ada-002 and text-embedding-3-small both default to 1,536 dimensions and are still not comparable.

Why did my vector search get worse after a deploy with no errors?

Look for a recipe change in only one path: a new model name, a missing input_type or task_type, a dropped query:/passage: prefix, a new text-cleaning step, a new chunker, or a partial re-embed. None of these change vector length, so none of them raise errors.

What is input_type or task_type in an embedding API?

It tells an asymmetric embedding model whether the text is a search query or a document to be stored, and the model embeds them differently. Cohere v3 requires input_type; Vertex AI uses task_type and defaults to RETRIEVAL_QUERY if you leave it out.

How do I detect embedding drift in production?

Keep 20 to 50 fixed landmark texts with stored vectors. Re-embed them through the live ingestion and search paths on every deploy and daily, and alert when similarity drops below the noise floor you measured by embedding them twice.

How do I migrate to a new embedding model with zero downtime?

Build a new index under a new recipe ID beside the old one, dual-write new documents, backfill old ones with keyset pagination, evaluate on labeled queries, flip the search path in one step, and keep the old index for rollback.

The bottom line

The dimension error is the only time your vector database tells you anything about where a vector came from. Give every vector a recipe ID, give your search path a guard, and survey your landmarks. The quiet failures start making noise.

The dimension check guards the length. Your job is to guard the meaning.

Adam Jaber is a software engineer who writes Simply Explained: complex topics, made simple. No jargon, no hype.


Keep reading: New here? Start Here: A Plain-English Map to Understanding AI 📬 Get one of these in your inbox each week → Simply Explained newsletter

About the author

  • I'm a senior software engineer. I write Simply Explained, a plain-English breakdown of how AI and software actually work, and the quiet ways they break: AI fixes that hide bugs, agents that pick the wrong tool, health checks that take down healthy servers. One symptom, one analogy, one fix per piece. New here? Start with the pinned Start Here guide, or get one breakdown a week by email.

Database column constraints only validate vector length and silently accept incompatible spaces, which is why swapping ada-002 for text-embedding-3-small—or dropping an asymmetric query/document prefix—produces confident-looking garbage instead of an error. Attaching an explicit recipe ID covering model, prefix, normalization, and chunker version turns all six silent mismatches into loud, enforceable checks.

Keeping the recipe ID on both the stored vectors and the query path also makes blue-green re-embedding migrations straightforward, since queries can filter strictly to the active recipe generation until backfill finishes.