Short answer: treat embedding dimension as an immutable data contract, not as a property to discover during an upsert. Read the destination index dimension, compare it with the actual length returned by the embedding stage, and reject the entire bulk batch before any write when they differ. For a logistics page-change watcher, this preserves a clean audit boundary: no alert should depend on a batch whose vectors were only partly accepted.
A dimension mismatch means the vector has a different number of numeric components from the index schema. It is not repaired by padding, truncating, retrying, or changing the bulk size. Generate the vector with the embedding configuration for which the index was created, or create a new index with the new dimension and deliberately re-embed the corpus.
A vector index operates in a fixed-dimensional space. If an index expects 1,536 components and an ingestion worker sends 3,072, the objects do not inhabit the same space, so the write must fail. The reverse mismatch is equally invalid. This check protects the mathematical meaning of distance calculations; silently shaving off coordinates would produce a different representation, while appending zeros would create a representation the embedding model did not produce.
In bulk ingestion, the error often appears after a configuration change rather than after a change to the page parser. One worker may use a different embedding model or model revision, a stale environment value may select another configuration, or stored vectors may be replayed into an index created for another generation. A second failure mode is structural: code accidentally serializes a batch of vectors as one flattened vector. Ten vectors of length 768 then look like one vector of length 7,680.
The logistics workflow makes the boundary concrete. A watcher fetches a carrier status page, extracts stable text, divides it into addressable chunks, embeds those chunks, and stores them for later retrieval. When a new snapshot arrives, retrieval helps determine which prior passages are relevant to the changed text before an alert is composed. Retrieval-augmented generation joins a parametric model with external retrieved material, but it does not relax the index's schema contract.
Stop early.
No partial batch.
An alert pipeline also needs to distinguish content identity from attempt identity. A useful record carries the page URL, snapshot digest, chunk ordinal, normalized-text digest, embedding contract identifier, and ingestion attempt identifier. The vector length alone is insufficient: two embedding configurations can emit vectors of the same length while assigning different meanings to their coordinates. For audit purposes, model/configuration identity and dimension belong together.
The decision is to validate a versioned embedding contract at the batch boundary, then write an idempotent batch only when every record satisfies it. The contract includes the expected dimension and an application-defined identifier for the embedding configuration. It is stored alongside ingestion metadata and deployment configuration; startup validation compares it with destination metadata, while per-batch validation checks the actual output.
The invariants are stricter than "the API call returned success." Every vector in a batch has exactly the declared dimension. Every record can be traced to one page snapshot and one embedding contract. Replaying the same snapshot and contract produces the same application-level record IDs. A batch rejected before the write produces no committed ingestion event. An alert cites a successfully committed snapshot, never an in-flight attempt.
This is an exactly-once mindset implemented over operations that may be delivered more than once. The storage system need not promise magical exactly-once execution; deterministic IDs, explicit attempt states, and reconciliation make repeated delivery observable and harmless. Record an append-only transition such as prepared, committed, or rejected, but do not log the page body or vector by default. Page text can contain personal data, tracking identifiers, or other regulated material, so retention, access, and erasure policies apply to the audit trail as well as the primary store. Data minimization is a useful compliance constraint here, not decoration.
| Option | Retrieval quality | Ingestion latency | Failure boundary | Audit consequence |
|---|---|---|---|---|
| Validate every vector, then write the batch | Preserves the declared embedding space | Adds a linear validation pass | Before the remote write | One clear rejection event |
| Validate one sample per batch | Can miss a malformed or mixed batch | Lower local validation work | During or after the write | Partial outcomes require reconciliation |
| Pad or truncate vectors | Corrupts representation semantics | Appears fast | Hidden until retrieval | Cannot prove semantic equivalence |
| Create a new index and re-embed | Preserves the new representation | Highest migration latency | At an explicit version boundary | Old and new generations remain attributable |
The first option is the default because an O(n) length check is small beside network embedding and indexing work, while its failure boundary is precise. If retrieval quality competes with latency, reduce chunk count or tune batching only after measuring; never trade away dimensional validity.
The trade-off is explicit.
The following Go example models the guard even if the surrounding orchestration happens in Node.js. The important part is language-independent: carry the contract next to each vector, validate all records, derive deterministic IDs, and call the writer only after the batch is known to be homogeneous.
package ingestion
import (
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
)
type Contract struct {
ID string
Dimension int
}
type Chunk struct {
PageURL string
SnapshotSHA string
Ordinal int
ContractID string
Vector []float32
}
type Record struct {
ID string
Vector []float32
Metadata map[string]string
}
type Writer interface {
Upsert(ctx context.Context, records []Record) error
}
func recordID(c Chunk) string {
input := fmt.Sprintf("%s\x00%s\x00%d\x00%s",
c.PageURL, c.SnapshotSHA, c.Ordinal, c.ContractID)
sum := sha256.Sum256([]byte(input))
return hex.EncodeToString(sum[:])
}
func BuildBatch(chunks []Chunk, contract Contract) ([]Record, error) {
if contract.ID == "" || contract.Dimension <= 0 {
return nil, errors.New("invalid embedding contract")
}
records := make([]Record, 0, len(chunks))
for i, chunk := range chunks {
if chunk.ContractID != contract.ID {
return nil, fmt.Errorf("chunk %d: contract %q, expected %q",
i, chunk.ContractID, contract.ID)
}
if len(chunk.Vector) != contract.Dimension {
return nil, fmt.Errorf("chunk %d: dimension %d, expected %d",
i, len(chunk.Vector), contract.Dimension)
}
records = append(records, Record{
ID: recordID(chunk),
Vector: chunk.Vector,
Metadata: map[string]string{
"page_url": chunk.PageURL,
"snapshot_sha": chunk.SnapshotSHA,
"contract_id": chunk.ContractID,
},
})
}
return records, nil
}
func Commit(ctx context.Context, w Writer, chunks []Chunk, contract Contract) error {
records, err := BuildBatch(chunks, contract)
if err != nil {
return fmt.Errorf("reject batch before upsert: %w", err)
}
if err := w.Upsert(ctx, records); err != nil {
return fmt.Errorf("upsert validated batch: %w", err)
}
return nil
}
In production, obtain the expected dimension from controlled index metadata or schema configuration and compare it at process startup. Do not infer it from the first vector in the batch: if the first worker is misconfigured, inference canonizes the error. Do not trust only a configured model name either. Validate returned lengths because configuration and output are separate evidence.
The write adapter should preserve provider-neutral semantics: a list of IDs, vectors, and minimal metadata. Retry only failures classified as transient by that adapter, using bounded backoff, and reuse the deterministic IDs. A dimension error is permanent for that payload. Sending it five more times adds latency and obscures the first cause.
Consider one concrete failure chain in a rolling deployment: worker A still emits 1,536-component vectors under contract carrier-page-v1, worker B emits 3,072-component vectors under carrier-page-v2, and a queue interleaves their chunks in one bulk request; sampling the first item says nothing about the remaining items, retrying merely reshuffles the same invalid work, and accepting a prefix would leave one snapshot represented by two incompatible spaces, so validation must inspect every item and reject the request before the adapter can write even one record. This is why I would choose a full linear pass despite its local latency: the alternative transfers uncertainty into reconciliation and, eventually, into the alert evidence shown to an operator.
Retries cannot fix geometry.
When the desired embedding configuration changes, create a new generation rather than mutating the meaning of an existing index. Backfill it from source snapshots, run retrieval evaluation against a fixed set of logistics changes, then switch reads through a controlled alias or application configuration. Keep the old generation available for rollback according to the system's retention policy. This costs time and temporary capacity, but it makes the semantic transition reviewable.
Retrieval quality should be evaluated with cases that resemble the alert decision: route suspension language, depot-hour changes, delivery-area exclusions, and dates embedded in boilerplate. Measure whether the relevant prior passage appears within the chosen retrieval limit, and separately measure end-to-end latency. A faster index that retrieves the wrong historical passage does not improve the alert. A more accurate configuration whose backfill cannot meet the freshness objective also fails the job. The decision needs both distributions, not one average.
Deployment gates should include a contract probe against each target environment and a small known vector fixture. Unit tests cover empty vectors, off-by-one dimensions, mixed contract IDs, and stable record IDs. Integration tests should prove that a rejected mixed batch causes zero writes in the application adapter, while a replay leaves one logical record per chunk. After deployment, reconcile committed ingestion events against stored record counts and snapshot manifests.
Observe counts, not content: rejected batches by contract ID, observed versus expected dimensions, batch size, embedding duration, write duration, replay count, and reconciliation lag. Keep dimensions as bounded metric labels only if the monitoring system can tolerate that cardinality; URLs and snapshot digests belong in protected logs or trace attributes, not metric labels. Alert on a sustained mismatch count immediately because no amount of downstream retrieval tuning can repair absent records.
The rejected option is to infer the index dimension from the first embedding and create storage on demand. It shortens a prototype's setup path, but it gives the first successful request authority over a durable schema. Concurrent workers can race, a stale worker can win, and a later deployment can appear healthy until it meets the existing index. That is a poor ownership model for an alerting system with audit obligations.
There is a valid use case: an isolated experiment with disposable data, one embedding configuration, no concurrent writers, and no downstream alerts. Label the generated index with the full contract, destroy it after the experiment, and do not promote it in place. Once another service or a human decision depends on retrieval, move schema creation into reviewed deployment work.
Keep that boundary sharp.
The operational rule remains narrow: compare the index contract, embedding configuration, and actual vector length before every bulk write. If they disagree, reject and diagnose. If the embedding configuration has intentionally changed, build a new indexed generation and re-embed from source. This keeps retrieval quality measurable, latency trade-offs explicit, and every logistics alert attributable to a coherent body of evidence.