AI-Powered Full Stack Tutorial 0/70 lessons ~6 min read Lesson 17

    Embeddings, Similarity Search and Vector Fundamentals

    A learner typed "how do I finish a lesson" into TechLearningPro search.

    Course progress0%
    Focus
    16 guided sections
    Practice signal
    Concept-first lesson
    Career prep
    Foundation builder

    AI-Powered Full Stack Development · Lesson 17 · AI and LLM Application Fundamentals

    Lesson Overview

    A learner typed "how do I finish a lesson" into TechLearningPro search. The catalog row was titled "Recording completion." Keyword lookup required the letters finish or a hand-maintained synonym list, and the row did not appear. A second bug, found the same week, ranked a private draft from another tenant because the scan forgot tenantId. The model was never involved. The failure was how the platform decides that two pieces of text are about the same idea, and who is allowed to see the neighbor.

    An embedding is a list of numbers that stands in for a piece of text. Similarity search ranks stored lists against a query list. Cosine similarity is the measure this lesson uses: it scores the angle between two vectors, so a longer title is not automatically a better match. You will implement that math in TypeScript, back it with a tiny lexicon embedder you can fully explain, and enforce tenant, lesson version, and embedder identity before any score is returned.

    The lexicon is a teaching stand-in. It is not a neural embedding model, and the tests do not pretend that it understands synonyms outside its table. A production embedding model replaces the Embedder port and returns a fixed-length array whose length is part of that model version. Embeddings and Tokens and embeddings name the idea. This lesson makes the ranking rule, the isolation rule, and the "no weak match" rule executable. Vector databases and the later pgvector lesson are where the same records move into PostgreSQL. The math and the filters do not get a holiday when that happens.

    Planning assumptions:

    • The index in this lab holds lesson titles the caller is allowed to know exist, not full copyrighted bodies and not another tenant's drafts.
    • Scores are comparable only when embedderId and dimension count match.
    • A minimum score is a product threshold. The number 0.5 below is a lab default, not a universal "relevant" cutoff.
    • No provider account. The embedder is pure functions.

    Learning Objectives

    By the end of this lesson you will be able to:

    1. Define a vector, a dot product, a magnitude, and cosine similarity in the units this search uses.
    2. Explain why cosine ranking is unchanged if you scale a vector, and why a raw dot product is not.
    3. Implement cosine similarity that rejects dimension mismatches, non-finite components, and zero vectors.
    4. Build a lexicon embedder with named axes so a ranking has an explanation a reviewer can check.
    5. State what the lexicon cannot do, and what an Embedder port must preserve when a trained model replaces it.
    6. Search an in-memory index with tenant, embedder id, and lesson version as hard filters.
    7. Drop neighbors below a minimum score and return an empty set the tutor can abstain on.
    8. Keep vectors from two embedder versions from being compared.
    9. Name the privacy boundary: text sent to a future embedding API is still an export of tenant data.
    10. Test a known ranking, a cross-tenant miss, and a zero-vector rejection without a network call.
    11. Choose keyword search, this cosine index, or a later hybrid design using the failure you are trying to remove.
    12. Write the re-embed rule for the day the model id changes.

    Prerequisites

    • Comfort with TypeScript arrays and number, including Number.isFinite. Lesson 3 is the language reference. /learn/typescript is the primer.
    • You can read the trust boundary from lesson 1. Search results are product data. They are not a model draft, and they still obey tenant isolation.
    • You do not need linear-algebra coursework. The three formulas below are the whole toolkit for this lesson.
    • You do not need a vector database or an API key. PostgreSQL storage comes later; this lesson keeps the index in a Map so the rules are visible.
    • Optional reading before the math: Semantic search for the product picture, then come back and compute a score by hand.

    Detailed Core Concepts

    Why keyword equality fails open

    Exact and substring search are deterministic and cheap. They are the right tool when the learner knows the identifier, such as a lesson slug. They miss a paraphrase because they compare characters, not meaning. A synonym table patches one pair and misses the next. Embeddings exist so "finish a lesson" and "recording completion" can land near each other when the embedding function was built to place related phrases near each other.

    That last clause is the whole honesty rule. Nearness is a property of the embedder, not a property of cosine. Cosine will faithfully report that two lexicon vectors are orthogonal. It will not invent a synonym the lexicon omitted. A trained model makes different mistakes: it can place unrelated text nearby, and it can change its geometry when you change model versions. You store the model id with the vector so you can tell those eras apart.

    Vectors used here

    A vector in this lesson is a readonly number[] of a fixed length. Each index is an axis. The lexicon embedder uses four axes, in order:

    IndexAxisExample words
    0progresscomplete, completion, finish, progress
    1quizquiz, score, grade
    2authsession, auth, login
    3streamstream, token, sse

    A trained model might use hundreds or thousands of axes that do not have English names. You still store the length. You still refuse to compare a length-4 vector with a length-1536 vector. The number 1536 is only an illustration of "models publish a dimension." Read the model card you actually deploy and store that number. Do not copy a dimension from a blog into a schema and call it current.

    Dot product, magnitude, cosine

    For vectors a and b of the same length:

    • Dot product: a · b = a0*b0 + a1*b1 + ...
    • Magnitude: ||a|| = sqrt(a · a)
    • Cosine similarity: (a · b) / (||a|| * ||b||)

    The result is between -1 and 1 when both magnitudes are non-zero. 1 means the same direction. 0 means a right angle. Negative means opposite directions. Text embedders are often trained so related texts land in a region of positive scores. Do not assume every model uses the full range, and do not treat 0.8 as a universal pass mark. Calibrate on your titles.

    Worked example on the progress and quiz axes, with auth and stream left at zero:

    • "finish lesson" maps toward (1, 0, 0, 0) after the lexicon averages known words.
    • "quiz score" maps toward (0, 1, 0, 0).
    • Dot product is 0. Cosine is 0. The quiz title must not rank as a completion lesson.
    • "recording completion" maps toward (1, 0, 0, 0). Cosine with "finish lesson" is 1 in this lexicon, because both point along progress.

    If you multiply the first vector by 10, the dot product grows by 10 and both the formula's numerator and one magnitude grow, so cosine stays the same. A ranking that uses the raw dot product would prefer the scaled vector. That is why this search uses cosine unless you L2-normalize every stored vector and every query and then use the dot product as an equivalent shortcut. The shortcut is only equivalent when both sides are normalized and neither was a zero vector.

    Zero vectors and empty text

    A string with no lexicon hits becomes (0, 0, 0, 0) if you naively sum nothing. Its magnitude is zero. Division by zero is not a similarity. The embedder in this lab returns an error for text that produces no known words, and cosine throws zero_vector if a caller passes one anyway. The product response is "no match," not a NaN sorted to the top. NaN comparisons are unordered and will scramble a sort.

    Filters that are not part of the score

    Cosine does not know what a tenant is. These predicates run before scoring, so another tenant's title never becomes a candidate and never appears in a log of "near misses":

    FilterWhy it is hard
    tenantIdA closer vector in another tenant is still a leak.
    embedderIdDifferent models do not share a geometry.
    dimensionsA shorter vector is not a prefix of a longer one.
    lessonVersionA retitled lesson must not be found under the old vector.

    After scoring, drop candidates below minScore. If none remain, return an empty list with reason no_neighbor. The tutor from lessons 1 and 16 can abstain instead of explaining a random lesson. That empty set is a success case. It is the grounding hook the next lessons and the RAG module build on. What is RAG? shows retrieval feeding a generator. This lesson stops at retrieval of titles.

    Keyword, vector, hybrid

    ApproachFitsBreaks when
    Keyword or slugExact lesson ids, codes, error stringsThe learner paraphrases
    Cosine on an embedderParaphrase over a corpus embedded with one model versionThe embedder never saw the domain, or versions are mixed
    HybridYou need both a rare identifier and a paraphraseThe fusion weights are unmeasured

    Hybrid search is a later lesson. Do not average a keyword score and a cosine score in this lab. They are different units. Shipping an average without a labeled eval set is how a worse ranker gets a confident deploy.

    What you must not send to an embedding API

    When a real Embedder calls a provider, the text leaves your network. Send titles or excerpts the tenant already allows that workflow to process. Do not send another learner's progress notes, raw emails, or secrets "because the vector is irreversible." Vectors can still be inverted or compared by anyone who holds them, and the provider saw the original text regardless. Batch requests need a timeout and a size cap. Store embedderId from your config next to every vector. When that id changes, the old rows are ineligible until a job re-embeds them. The request path must not silently fall back to the old geometry.

    Architecture and Request Flow

    flowchart TB
      subgraph browser [Browser]
        Box[Search box]
      end
    
      subgraph server [TechLearningPro API]
        Auth[Session tenant]
        Query[Embed query]
        Index[In-memory title index]
      end
    
      subgraph embed [Embedder boundary]
        Lex[Lexicon embedder]
      end
    
      Box -->|GET search q| Auth
      Auth --> Query
      Query --> Lex
      Query --> Index
      Index -->|titles in tenant| Box

    The browser sends a query string. It does not send a vector, an embedder id, or a tenant id that the server trusts. The server embeds the query with the current embedder and scans only that tenant's records. A future provider sits behind LexiconEmbedder's interface. The browser still receives titles, never the credential.

    flowchart LR
      Text[Title or query] --> Tokens[Lowercase tokens]
      Tokens --> Axes[Sum lexicon axes]
      Axes --> Vec[Vector plus embedderId]
      Vec --> Cos[Cosine against same embedder]
      Cos --> Cut[Drop below minScore]
      Cut --> Hits[Ordered lesson ids]

    Step-by-step Implementation

    Package path: packages/similarity/. "strict": true. No network.

    Step 1: Cosine, with the failures made explicit

    packages/similarity/src/cosine.ts

    typescript
    export type CosineError = "empty" | "dimension_mismatch" | "non_finite" | "zero_vector";
    export function cosineSimilarity(
    a: readonly number[],
    b: readonly number[],
    ): { ok: true; score: number } | { ok: false; error: CosineError } {
    if (a.length === 0 || b.length === 0) return { ok: false, error: "empty" };
    if (a.length !== b.length) return { ok: false, error: "dimension_mismatch" };
    let dot = 0;
    let normA = 0;
    let normB = 0;
    for (let i = 0; i < a.length; i++) {
    const x = a[i] ?? Number.NaN;
    const y = b[i] ?? Number.NaN;
    if (!Number.isFinite(x) || !Number.isFinite(y)) {
    return { ok: false, error: "non_finite" };
    }
    dot += x * y;
    normA += x * x;
    normB += y * y;
    }
    if (normA === 0 || normB === 0) return { ok: false, error: "zero_vector" };
    const raw = dot / (Math.sqrt(normA) * Math.sqrt(normB));
    // Float arithmetic can land a hair outside the closed interval.
    const score = Math.min(1, Math.max(-1, raw));
    return { ok: true, score };
    }

    Returning a result object keeps NaN from propagating into a sort. Callers match on ok.

    Step 2: A lexicon you can audit

    packages/similarity/src/lexicon.ts

    typescript
    export const AXES = ["progress", "quiz", "auth", "stream"] as const;
    export const EMBEDDER_ID = "lexicon-course-axes-v1";
    const WORD_AXES: Readonly<Record<string, readonly number[]>> = {
    complete: [1, 0, 0, 0],
    completion: [1, 0, 0, 0],
    finish: [1, 0, 0, 0],
    progress: [1, 0, 0, 0],
    recording: [1, 0, 0, 0],
    quiz: [0, 1, 0, 0],
    score: [0, 1, 0, 0],
    grade: [0, 1, 0, 0],
    session: [0, 0, 1, 0],
    auth: [0, 0, 1, 0],
    login: [0, 0, 1, 0],
    stream: [0, 0, 0, 1],
    token: [0, 0, 0, 1],
    sse: [0, 0, 0, 1],
    };
    export interface Embedded {
    embedderId: string;
    values: readonly number[];
    }
    export type EmbedResult =
    | { ok: true; vector: Embedded }
    | { ok: false; error: "empty_text" | "no_known_terms" };
    /** Lowercase tokens. Punctuation is a separator. This is the whole normalizer. */
    export function tokenize(text: string): string[] {
    return text.toLowerCase().split(/[^a-z0-9]+/).filter((word) => word.length > 0);
    }
    /**
    * Average of in-lexicon word vectors.
    * Words outside the table are skipped and do not create synonym magic.
    * Averaging versus summing does not change cosine; it keeps component scale readable.
    */
    export function embedLexicon(text: string): EmbedResult {
    const words = tokenize(text);
    if (words.length === 0) return { ok: false, error: "empty_text" };
    const sums = [0, 0, 0, 0];
    let hits = 0;
    for (const word of words) {
    const axes = WORD_AXES[word];
    if (!axes) continue;
    hits += 1;
    for (let i = 0; i < sums.length; i++) sums[i] = (sums[i] ?? 0) + (axes[i] ?? 0);
    }
    if (hits === 0) return { ok: false, error: "no_known_terms" };
    const values = sums.map((total) => total / hits);
    return { ok: true, vector: { embedderId: EMBEDDER_ID, values } };
    }

    recording is in the table so the Monday story ranks. how, do, i, and a are absent on purpose. A production model would give those function words a small weight or drop them with a documented stop-word list. Write that list down if you add one. An undocumented list changes rank without a diff anyone can review.

    The port a future provider must satisfy:

    typescript
    export interface Embedder {
    readonly id: string;
    readonly dimensions: number;
    embed(text: string): Promise<EmbedResult>;
    }

    embedLexicon is synchronous. The interface is async because a provider call is I/O. The lab adapter wraps the function in Promise.resolve. Timeouts, retries, and credentials live in that adapter, not in cosineSimilarity.

    Step 3: The index

    packages/similarity/src/index.ts

    typescript
    import { cosineSimilarity } from "./cosine.js";
    import type { Embedded } from "./lexicon.js";
    export interface TitleRecord {
    tenantId: string;
    lessonId: string;
    lessonVersion: number;
    title: string;
    vector: Embedded;
    }
    export interface SearchHit {
    lessonId: string;
    lessonVersion: number;
    title: string;
    score: number;
    }
    export interface SearchQuery {
    tenantId: string;
    lessonVersion: number;
    vector: Embedded;
    /** Lab default is a starting gate, not a tuned relevance cutoff. */
    minScore: number;
    limit: number;
    }
    export function searchTitles(
    records: readonly TitleRecord[],
    query: SearchQuery,
    ): { hits: SearchHit[] } | { error: "bad_query" | "bad_vector" } {
    if (query.limit < 1 || query.limit > 20) return { error: "bad_query" };
    if (!Number.isFinite(query.minScore) || query.minScore < -1 || query.minScore > 1) {
    return { error: "bad_query" };
    }
    const hits: SearchHit[] = [];
    for (const record of records) {
    if (record.tenantId !== query.tenantId) continue;
    if (record.lessonVersion !== query.lessonVersion) continue;
    if (record.vector.embedderId !== query.vector.embedderId) continue;
    const scored = cosineSimilarity(record.vector.values, query.vector.values);
    if (!scored.ok) return { error: "bad_vector" };
    if (scored.score < query.minScore) continue;
    hits.push({
    lessonId: record.lessonId,
    lessonVersion: record.lessonVersion,
    title: record.title,
    score: scored.score,
    });
    }
    hits.sort((left, right) => {
    if (right.score !== left.score) return right.score - left.score;
    return left.lessonId < right.lessonId ? -1 : left.lessonId > right.lessonId ? 1 : 0;
    });
    return { hits: hits.slice(0, query.limit) };
    }

    The sort tie-break on lessonId keeps tests stable when two titles share a score. Stable ties matter when a UI says "top result" and two rows are equally on-axis.

    A note on the early bad_vector return: if any eligible record fails cosine, the function fails closed. A zero vector in your own tenant's index is a corrupt row. Do not skip it and keep going in the lab; surface it so the re-embed job can delete it. Ineligible rows are skipped by the filters and never scored.

    Step 4: Query path

    The HTTP handler, shaped like the other lessons:

    1. Read the session. No session yields 401. Take tenantId from the session.
    2. Read q from the query string. Trim. Reject empty and reject length over 200 with 400. Reject a client-supplied tenantId that does not match the session.
    3. Call embedLexicon. On empty_text or no_known_terms, return 200 with hits: [] and reason: "no_neighbor". That is not a 500. The learner sees no suggestions.
    4. searchTitles with the catalog version you are serving, minScore: 0.5, and limit: 5.
    5. Return lesson id, version, title, and a score rounded for display if you want, but keep the full score in logs of returned ids only.

    Do not return vectors to the browser. They are an internal index. Do not echo the raw query into an analytics tool that other tenants' staff can read.

    Step 5: Run

    bash
    npx tsc --noEmit
    node --experimental-strip-types --test src/search.test.ts

    Nothing in the package reads process.env. Cleanup is removing the package. A later adapter that calls a provider must fail tests if an environment variable named like a key is required for the unit run.

    Security

    • Authentication before embed. An anonymous catalog, if you have one, is a separate index of public titles, not a flag that disables the tenant filter on private rows.
    • Authorization is the tenant filter plus the rule that private draft titles are not inserted into the shared index. Insert-time ACL is what makes search-time filtering sufficient. If a draft is inserted, the filter cannot invent a permission it never stored.
    • Least privilege for a future embedding credential: the runtime identity can call the embed endpoint and nothing else. It cannot read the database role that writes completion.
    • Input validation caps query length so a client cannot push a document through the search box into your token bill.
    • Secrets do not belong in titles. The lexicon does not log text. A provider adapter must not log the request body by default.
    • Tenant isolation is a predicate, tested by a record that would otherwise score 1 and must still be absent.

    Vectors of private titles are still private. A backup of the index is a backup of those titles' meaning. Encrypt and authorize it the same way you authorize the lesson table. AI security names the third-party boundary; the filter in searchTitles is the control this lesson actually ships.

    Error Handling

    CaseCaller getsOperator sees
    Empty query400 bad_queryCount of rejected queries, no text
    No lexicon hits200, hits: [], no_neighborCount, not the query string in a shared log
    Dimension or embedder mismatchRow skipped; if the query vector itself is illegal, bad_vectorCorrupt-index counter
    Zero vectorbad_vector on an eligible rowRe-embed job
    All scores under minScore200, empty hitsScore histogram later, on an allowed sample
    Future provider timeout200, empty hits, reason: unavailableTimeout metric, no automatic retry loop

    Empty hits are a normal product outcome. The UI says the catalog had no close title. It does not call the tutor to invent a lesson. Retrying an embedding call is safe only when the request is idempotent and you cap attempts. A timeout may still have been billed. One retry with the same timeout is the ceiling until you have measured otherwise.

    Testing

    packages/similarity/src/search.test.ts

    typescript
    import assert from "node:assert/strict";
    import test from "node:test";
    import { cosineSimilarity } from "./cosine.js";
    import { embedLexicon, EMBEDDER_ID } from "./lexicon.js";
    import { searchTitles, type TitleRecord } from "./index.js";
    function record(tenantId: string, lessonId: string, title: string): TitleRecord {
    const embedded = embedLexicon(title);
    if (!embedded.ok) throw new Error(embedded.error);
    return {
    tenantId,
    lessonId,
    lessonVersion: 1,
    title,
    vector: embedded.vector,
    };
    }
    const catalog = [
    record("ten_a", "les_completion", "Recording completion"),
    record("ten_a", "les_quiz", "Quiz score"),
    record("ten_b", "les_secret", "Recording completion"),
    ];
    test("cosine is 1 along the same axis and 0 across axes", () => {
    const finish = embedLexicon("finish lesson");
    const completion = embedLexicon("recording completion");
    const quiz = embedLexicon("quiz score");
    assert.equal(finish.ok && completion.ok && quiz.ok, true);
    if (!finish.ok || !completion.ok || !quiz.ok) return;
    const same = cosineSimilarity(finish.vector.values, completion.vector.values);
    const cross = cosineSimilarity(finish.vector.values, quiz.vector.values);
    assert.equal(same.ok, true);
    assert.equal(cross.ok, true);
    if (same.ok) assert.equal(same.score, 1);
    if (cross.ok) assert.equal(cross.score, 0);
    });
    test("scaling a vector does not change cosine", () => {
    const base = embedLexicon("finish");
    assert.equal(base.ok, true);
    if (!base.ok) return;
    const scaled = base.vector.values.map((value) => value * 10);
    const score = cosineSimilarity(base.vector.values, scaled);
    assert.equal(score.ok && score.score > 0.999, true);
    });
    test("search stays inside the tenant and ranks completion over quiz", () => {
    const query = embedLexicon("how do I finish a lesson");
    assert.equal(query.ok, true);
    if (!query.ok) return;
    const result = searchTitles(catalog, {
    tenantId: "ten_a",
    lessonVersion: 1,
    vector: query.vector,
    minScore: 0.5,
    limit: 5,
    });
    assert.ok(!("error" in result));
    if ("error" in result) return;
    assert.deepEqual(
    result.hits.map((hit) => hit.lessonId),
    ["les_completion"],
    );
    assert.equal(result.hits.some((hit) => hit.lessonId === "les_secret"), false);
    });
    test("a different embedder id is not a candidate", () => {
    const query = embedLexicon("finish");
    assert.equal(query.ok, true);
    if (!query.ok) return;
    const result = searchTitles(catalog, {
    tenantId: "ten_a",
    lessonVersion: 1,
    vector: { embedderId: "other-model", values: query.vector.values },
    minScore: 0.5,
    limit: 5,
    });
    assert.ok(!("error" in result));
    if ("error" in result) return;
    assert.equal(result.hits.length, 0);
    assert.equal(query.vector.embedderId, EMBEDDER_ID);
    });

    The tenant test is the privacy property: les_secret has the same title as the hit and a perfect geometric match, and it is absent because tenantId differs. Add a test that embedLexicon("???") returns no_known_terms, and a test that cosine on [0,0,0,0] returns zero_vector.

    Performance and Cost

    This index is a linear scan. It is the right shape for a few hundred titles in a unit test and the wrong shape for millions of chunks. The later vector-database lesson replaces the scan with an index structure. It should not replace the filters. An approximate index can miss a true neighbor; it must not be allowed to "miss" the tenant predicate by searching a shared graph and filtering afterward in a way that still loads other tenants' vectors into the process. Prefer a partition or a mandatory WHERE tenant_id = $1 when you reach SQL.

    • Embed the query once per search, not once per row.
    • Cache a query vector for a public, non-personalized string only if the cache key includes embedderId. A personalized note is not a cache key you share across users.
    • Cap query length and batch size. Embedding cost on a provider scales with input tokens and with how often you re-embed the catalog.
    • Re-embed asynchronously when a title changes. The search path reads the latest stored vector for that lessonVersion. It does not call the provider once per keystroke.
    • Do not log full vectors at info level. They are large and they are derived from private text.

    Illustrative ratio: embedding a title once at publish time is far cheaper than embedding the whole catalog on every search. The surprise bill is a migration that re-embeds every tenant on every deploy because the model id was not pinned in config.

    Knowledge Check

    1. What problem does cosine similarity on embeddings solve?

    It ranks texts that point the same direction in a chosen embedder's space, which is how a paraphrase can surface a lesson the keyword index missed. The embedder supplies the meaning. Cosine supplies a scale-stable score and a hard failure on vectors that cannot be compared.

    2. What alternatives exist, and when would you choose each?

    Keyword or slug lookup fits exact identifiers. This cosine index fits paraphrase over one embedder version, with a minimum score and tenant filters. A raw dot product fits only after you normalize, or when magnitude is a feature you intend to rank on. Hybrid search fits after you have an eval set. A vector database fits when a linear scan is too slow, with the same filters.

    3. Which data, identity, and trust boundaries matter?

    The session owns tenantId. Records are inserted only if that tenant may keep the title in the index. The browser does not submit the vector that gets searched. A future embedding provider receives the query text, so the query must already be allowed to leave the trust zone. Scores from another embedder id are not evidence.

    4. What can fail, and how should the system respond?

    Unknown terms and a score under the cutoff return an empty hit list and the UI abstains. Dimension mismatches and zero vectors are corrupt-index failures. A provider timeout returns an empty list with unavailable and does not scan a different model "just in case." Cross-tenant rows are skipped before scoring.

    5. How would you test quality, security, performance, and cost?

    Unit tests lock the worked example, scale invariance, tenant isolation, and embedder mismatch. Quality beyond the lexicon requires a labeled set of paraphrases, which lesson 18's harness pattern can score as hit-or-miss at k. Security review checks insert-time ACL and log redaction. Cost review checks that publish-time embed is the write path and search does not re-embed the catalog.

    Hands-on Assignment

    Lab note. Stay on embedLexicon. Do not call an embedding API.

    Problem. TechLearningPro search should rank "Recording completion" for "how do I finish a lesson" inside tenant A, return nothing from tenant B, and return nothing for a query the lexicon does not know.

    Tasks.

    1. Compute the cosine for the worked example by hand, then confirm it with the test.
    2. Implement cosineSimilarity, embedLexicon, and searchTitles.
    3. Add the no_known_terms test and the zero-vector test.
    4. Document the four axes and the words on each axis in a table a teammate can review. Adding a word is a content change with a test, not a silent edit.
    5. Write the re-embed rule in six lines: what is stored, what makes a row ineligible, who runs the job, what search returns while the job is behind.
    6. State the minScore as an uncalibrated lab default and name the evidence you would need to change it.

    Deliverable. Diagram, source with no secrets, test output, the axis table, and the re-embed note.

    Challenge. Add a second embedder id with the same four numbers and show the search returns no hits. Then describe a backfill that writes new rows without letting a request compare old and new in one ranking.

    Rubric. Conceptual accuracy and architecture 20%. Working implementation 25%. Security and privacy 20%. Tests and failure behavior 20%. Documentation of trade-offs 15%.

    Common Mistakes

    1. Comparing two model versions. Symptom: rankings swing after a deploy, or scores cluster near zero. Cause: vectors from different embedderIds share an array. Fix: store the id and filter it.
    2. Filtering the tenant after taking a global top-k. Symptom: a tenant with few lessons gets empty results, or a shared cache briefly holds another tenant's ids. Cause: the index returned k neighbors from everyone and then dropped some. Fix: constrain the candidate set first.
    3. Treating cosine as understanding. Symptom: a query outside the lexicon 500s, or a team promises semantic search the table cannot do. Cause: the stand-in was described as a model. Fix: return no_neighbor, and describe the lexicon as a lexicon.
    4. Using dot product on unnormalized text vectors. Symptom: long titles full of repeated keywords outrank short exact titles. Cause: magnitude leaked into the score. Fix: cosine, or normalize both sides and document it.
    5. Letting NaN into the sort. Symptom: the order changes between runs or a hit disappears. Cause: a zero vector or a bad component. Fix: the result object in cosineSimilarity.
    6. Sending private notes to an embedding provider. Symptom: a provider log contains learner free text. Cause: "embed everything we store." Fix: an allowlist of fields, the same way prompts have an allowlist.
    7. A universal cutoff copied from a post. Symptom: either no results or noisy results, defended with "0.8 means relevant." Cause: the cutoff was not measured on your titles. Fix: label it uncalibrated and change it with an eval sample.
    8. Re-embedding the catalog on the search request. Symptom: latency and cost track keystrokes. Cause: the port was called inside the scan. Fix: persist vectors at publish time.
    9. Returning vectors to the client. Symptom: a bulky response and a new data export. Cause: debugging fields left in the JSON. Fix: return ids, titles the user may see, and a display score.
    10. Averaging keyword rank and cosine in one number. Symptom: a slug match loses to a vague neighbor. Cause: two scales were added. Fix: wait for the hybrid lesson and a labeled set.

    Summary

    Similarity search ranks embeddings with a measure you can implement and test. Cosine similarity answers "same direction?" and stays still when a vector is scaled. It does not answer "same tenant?" or "same model?" — those are filters, and they run first. The lexicon embedder makes the Monday paraphrase pass for a known word and fail closed for an unknown one. A trained model can replace the port later. It cannot replace the tenant predicate, the stored embedderId, or the empty-result path that keeps a tutor from inventing a lesson.

    Next Lesson Preview

    AI Application Evaluation and Quality Measurement is how you stop arguing from one impressive example. You will build a golden-set harness that scores tutor drafts against the excerpt, blocks a release when a critical case fails, and keeps a model-as-judge advisory until a person has checked it.

    Further Reading

    • MDN: Math.sqrt for the magnitude step. The formula in this lesson is the specification you need.
    • Embeddings, Tokens and embeddings, Semantic search, Embeddings (RAG), and Vector databases.
    • What is RAG? for where a neighbor list goes after this lesson's empty-set rule.
    • This course's TypeScript lesson for strict result types, and lesson 11 for the relational facts a future WHERE tenant_id must match.
    • When you pick a hosted embedding model, read that vendor's current model card for dimension, token limit, and data-retention terms before writing the adapter. Do not code from memory of a field name.
    Ready to mark this lesson complete?Track your journey across the entire course.