spring-projects/spring-ai · error · IllegalArgumentException

Vectors lengths must be equal

Error message

Vectors lengths must be equal

What it means

EmbeddingMath.cosineSimilarity throws IllegalArgumentException 'Vectors lengths must be equal' when the two float[] vectors have different dimensions. Cosine similarity is only defined for vectors of the same embedding dimensionality.

Solutions

  1. Use one embedding model consistently; rebuild/re-embed the store after changing models.
  2. Check vectorX.length == vectorY.length before calling and log/skip mismatches.
  3. Validate dimensionality at ingestion time to catch bad vectors early.

Example fix

// before
double s = EmbeddingMath.cosineSimilarity(newEmbedding, storedVector); // dims may differ

// after
if (newEmbedding.length == storedVector.length) {
    double s = EmbeddingMath.cosineSimilarity(newEmbedding, storedVector);
}
else {
    throw new IllegalStateException("Embedding model changed - re-index the store");
}
Defensive patterns

Strategy: validation

Validate before calling

if (vectorX.length != vectorY.length) {
    throw new IllegalStateException("Embedding dimension mismatch: " + vectorX.length + " vs " + vectorY.length);
}
double s = EmbeddingMath.cosineSimilarity(vectorX, vectorY);

Type guard

static boolean sameDimension(float[] a, float[] b) { return a != null && b != null && a.length == b.length; }

Try / catch

try {
    return EmbeddingMath.cosineSimilarity(x, y);
} catch (IllegalArgumentException e) {
    if (e.getMessage().contains("lengths must be equal")) { logDimensionMismatch(x, y); return 0.0; }
    throw e;
}

Prevention

When it happens

Trigger: Comparing embeddings from two different embedding models (e.g. 384-dim vs 1536-dim), or a corrupted/partially deserialized vector store where stored vectors have a stale dimensionality.

Common situations: Switching embedding models without rebuilding the vector store; mixing documents embedded with different models; manual test fixtures with hand-written vectors.

Understand the failure class

Background: Tensor shape mismatch errors ("must have shape", "expected shape ... got ..."): when tensor dimensions disagree with what an op or layer was told to expect — this error's family across 6 libraries.

Related errors


AI-assisted analysis of spring-projects/spring-ai@98a7beda4f (2026-09-11). Data as JSON: /api/errors/44c69617f3cf66e2. Report an issue: GitHub.

Appendix: source

Thrown at spring-ai-vector-store/src/main/java/org/springframework/ai/vectorstore/SimpleVectorStore.java:275

		return VectorStoreObservationContext.builder(VectorStoreProvider.SIMPLE.value(), operationName)
			.dimensions(this.embeddingModel.dimensions())
			.collectionName("in-memory-map")
			.similarityMetric(VectorStoreSimilarityMetric.COSINE.value());
	}

	public static final class EmbeddingMath {

		private EmbeddingMath() {
			throw new UnsupportedOperationException("This is a utility class and cannot be instantiated");
		}

		public static double cosineSimilarity(float[] vectorX, float[] vectorY) {
			if (vectorX == null || vectorY == null) {
				throw new RuntimeException("Vectors must not be null");
			}
			if (vectorX.length != vectorY.length) {
				throw new IllegalArgumentException("Vectors lengths must be equal");
			}

			float dotProduct = dotProduct(vectorX, vectorY);
			float normX = norm(vectorX);
			float normY = norm(vectorY);

			if (normX == 0 || normY == 0) {
				throw new IllegalArgumentException("Vectors cannot have zero norm");
			}

			return dotProduct / (Math.sqrt(normX) * Math.sqrt(normY));
		}

		public static float dotProduct(float[] vectorX, float[] vectorY) {
			if (vectorX.length != vectorY.length) {
				throw new IllegalArgumentException("Vectors lengths must be equal");
			}

View on GitHub (pinned to 98a7beda4f)