Validate vectors before cosine similarity

AI assisted the preparation of this article, and its Python example was tested locally with synthetic fixtures.
A cosine calculation needs more than two arrays that happen to have the same length. Empty vectors, non-finite values and zero norms require an explicit policy before a local debugging tool divides by a norm.
Flow: Vectors, then Shape and values, then Norm check, then Score or error.
Validate a deliberately bounded domain
The example accepts lists of finite Python floats, with at most 10,000 components. Every nonzero magnitude must be between 1e-100 and 1e100. Those limits are a fixture policy, not a property of embeddings in general. Each vector must have a nonzero norm.
import math
def cosine(left, right):
if not left or len(left) != len(right) or len(left) > 10000:
raise ValueError("invalid vector dimensions")
for value in (*left, *right):
if type(value) is not float or not math.isfinite(value):
raise ValueError("components must be finite floats")
if value and not 1e-100 <= abs(value) <= 1e100:
raise ValueError("component outside fixture range")
left_norm = math.hypot(*left)
right_norm = math.hypot(*right)
if not left_norm or not right_norm:
raise ValueError("zero vector")
return math.fsum((a / left_norm) * (b / right_norm)
for a, b in zip(left, right))
The calculation normalizes before multiplying, avoiding the most obvious overflow from multiplying two large raw components. math.hypot supplies the norm and math.fsum sums the products. The bounded domain and length are part of the contract; this is not a proof for arbitrary floats or arbitrarily large vectors.
Identical unit vectors produce one, orthogonal vectors produce zero, and opposite unit vectors produce minus one, within a chosen floating-point tolerance. Include values at the declared boundaries and reject a value just beyond them. NaN, infinity, mismatched lengths, empty input and a zero vector should fail before a score is returned.
Separate arithmetic from compatibility
The scikit-learn cosine reference defines cosine similarity as a normalized dot product. Its example returns zero for a zero vector; this fixture deliberately rejects that case instead. The Python math reference describes isfinite, hypot and fsum.
Equal dimensions and finite arithmetic do not establish that vectors came from the same model, revision or preprocessing pipeline. Record those identities separately and route queries to the matching index. A numeric score is not a calibrated probability or proof of relevance, support or tenant authorization.
The checks ran on synthetic arrays with CPython 3.13.5. They do not exercise an embedding provider or a vector database, and their tolerances are not a benchmark for a retrieval system.