mastra-ai/mastra · error

Vectors must not be null or undefined

Error message

Vectors must not be null or undefined

What it means

cosineSimilarity(vec1, vec2) throws when either vector is null or undefined. It is private but reachable because query() passes node.embedding! into it, and createGraph() passes embeddings[i]?.vector into it, so missing embeddings surface here at runtime despite TypeScript typing.

Source

Thrown at packages/rag/src/graph-rag/index.ts:195

    }
    node.content = newContent;
  }

  // Get neighbors of a node
  private getNeighbors(nodeId: string, edgeType?: string): { id: string; weight: number }[] {
    return this.edges
      .filter(edge => edge.source === nodeId && (!edgeType || edge.type === edgeType))
      .map(edge => ({
        id: edge.target,
        weight: edge.weight,
      }))
      .filter(node => node !== undefined);
  }

  // Calculate cosine similarity between two vectors
  private cosineSimilarity(vec1: number[], vec2: number[]): number {
    if (!vec1 || !vec2) {
      throw new Error('Vectors must not be null or undefined');
    }
    const vectorLength = vec1.length;

    if (vectorLength !== vec2.length) {
      throw new Error(`Vector dimensions must match: vec1(${vec1.length}) !== vec2(${vec2.length})`);
    }

    let dotProduct = 0;
    let normVec1 = 0;
    let normVec2 = 0;

    for (let i = 0; i < vectorLength; i++) {
      const a = vec1[i]!; // Non-null assertion operator
      const b = vec2[i]!;

      dotProduct += a * b;
      normVec1 += a * a;
      normVec2 += b * b;

View on GitHub (pinned to 75dd419e61)

Solutions

  1. Ensure every node added to the graph has a valid embedding array (addNode enforces this — route all inserts through it).
  2. When building embeddings, assert each GraphEmbedding has a non-empty vector before createGraph().
  3. Re-embed any nodes whose embeddings are missing instead of adding them bare.
  4. Guard the query path by filtering out nodes without embeddings before query(), or validate snapshot.nodes all carry embeddings.

Example fix

// before
await graph.createGraph(chunks, embeddings);
// after
if (embeddings.some(e => !Array.isArray(e.vector) || e.vector.length === 0)) {
  throw new Error('Every embedding must have a non-empty vector');
}
await graph.createGraph(chunks, embeddings);
Defensive patterns

Strategy: validation

Validate before calling

const hasVectors = embeddings.every(e => Array.isArray(e.vector) && e.vector.length > 0);
if (!hasVectors) throw new Error('All embeddings must contain a vector array before createGraph');

Type guard

const hasEmbedding = (n: GraphNode): n is GraphNode & { embedding: number[] } =>
  Array.isArray(n.embedding) && n.embedding.length > 0;

Try / catch

try {
  const results = graph.query({ query });
} catch (e) {
  if ((e as Error).message === 'Vectors must not be null or undefined') {
    // a graph node is missing its embedding; re-index or re-embed that node
  } else throw e;
}

Prevention

When it happens

Trigger: query({query, ...}) on a graph containing a node added without an embedding, or a node whose embedding was set to null/undefined; createGraph() where the embeddings array contains an entry without a vector property.

Common situations: Adding nodes via a code path that skips addNode's embedding check, then querying; embedding generation failing silently for some chunks leaving {vector: undefined}; mutating snapshot nodes and dropping the embedding field.

Related errors


AI-assisted analysis of mastra-ai/mastra@75dd419e61 (2026-08-30). Data as JSON: /api/errors/fc72ef7de47682a2. Report an issue: GitHub.