32. Embeddings and exact search

Why this layer exists

Chapter 2 promised this layer in one sentence: retrieval embeds a query with dixie’s honcho-embed, compares it against every stored vector by cosine, and then replaces the exhaustive comparison with an index that approximates it. This chapter is the exhaustive comparison and the embedder in front of it; chapter 33 is the approximation, and every number chapter 33 reports is a distance from what this chapter computes. Chapter 15 said that this chapter searches over embeddings, and chapter 21 built the guard around the embedder and met the pooling incident, in which the vectors were wrong and nothing else was. Chapter 35’s memory service is built on the index these three chapters make.

The layer exists because an agent’s memory is text it must find again by meaning and not by key. “By meaning” costs one forward pass per text, to turn it into a point, and one dot product per comparison. Exact search is the baseline: score every stored point, keep the best $k$. Its answer is the definition of correct for everything that follows, and recall@k, the share of that answer an approximate index also returns, is the metric.

The case against vectors, before the chapter builds them. Barbaste, Darrigol, Vu and Wiltberger read the source of eleven production coding harnesses (arXiv 2609.00006, July 2026) and report that none of them retrieves code with vector embeddings: “the field runs on hand-rolled async loops and deterministic retrieval (ripgrep, tree-sitter, glob, auto-discovered Markdown context files)” (abstract; §13.2, “The Twin Absences: No Agentic Frameworks, No Code RAG”; Observation 9, p. 56). Its Recommendation 8 reads “Do not build RAG over code”, on the evidence that code “has rich deterministic structure (paths, language servers, tree-sitter parses) that semantic similarity cannot replicate” (p. 69), and Recommendation 16 reads “Do not build a vector-embedding retrieval layer for code” (p. 70); the discussion adds that code “changes minute to minute, so pre-indexed embeddings are stale almost by construction” (p. 56). The reasons are sound for code, and this book follows them: its agent reads code with chapter 27’s tools and the file system, and nothing in this chapter indexes a source tree.

The study does not stop at code, and the rest of it cuts against using embeddings for conversation memory, which is what this chapter builds them for. Recommendation 16 continues: “The embeddings that do appear serve conversation memory (OpenClaw’s default hybrid search; Hermes’s opt-in plugins), and Hermes shows lexical SQLite FTS5 sufficing for that role at 642K-line scale” (p. 70). Section 9.6 says “none of the eleven uses embedding-based retrieval as its primary memory substrate—the deterministic-retrieval finding of Observation 9 extends from code to memory, with SQLite full-text search (Hermes) as the production ceiling” (p. 34). And §13.2 places OpenClaw’s default embeddings “for chat recall, never for reading the source tree”, while Hermes’s “core past-conversation search is deliberately lexical (trigger-maintained SQLite FTS5, BM25 plus trigram tokenization for CJK, ‘no LLM calls anywhere’), with embeddings confined to opt-in memory plugins” (p. 54). So the evidence from eleven harnesses is that lexical search is enough for conversation memory in the one system that runs it at scale, and that embeddings there are optional.

This book builds vectors for memory anyway, and that is its own decision, not the study’s. Chapter 35’s recall is asked in the user’s words about things said in other words, and a lexical index matches the words that are there: BM25 over “what did we decide about the database” finds the sentences containing those words, and misses the one that says “we’re going with Postgres”. Lexical search does handle the cases where the words repeat, costs no forward pass per message, and has no embedding space to drift. The study gives no measurement of recall on paraphrased questions, for either method. Whether vectors beat lexical recall on this book’s memory is a question for the memory service of chapter 35, not for this chapter; the vector index (chapters 33 and 34) is built because it is a subject of the book in its own right, and exact search, this chapter’s baseline, is what any claim about the approximate index is measured against. The study is cited for what it measured, which is what eleven harnesses do and not whether they are right.

Mechanism

The embedder as a component

honcho-embed is Qwen3-Embedding-0.6B at Q8_0, served by llama.cpp’s llama-server on dixie with --embeddings --pooling last --ctx-size 4096 --batch-size 2048 --ubatch-size 2048 --parallel 2 --kv-unified (the arguments GET /v1/models lists for the preset, read on 2026-10-04). The server’s POST /v1/embeddings “requires that the model uses a pooling different than type none” and returns vectors “normalized using the Eucledian norm” (the server README at b29c606, line 1506; the misspelling is the README’s). The model card says the embedding dimension is “up to 1024” with user-defined sizes “ranging from 32 to 1024”, which is Matryoshka representation learning: the leading coordinates of the vector are trained to be a usable embedding on their own. This book uses all 1,024.

The embedder is internal/embedding, a leaf package, and not decide.HTTPEmbedder from chapter 28. The vector store must not import the decision-model runtime, and a store that fails to open needs an error type (ErrMismatch, ErrNotLoaded) that its callers can test without knowing which embedder produced it. The two interfaces are method-identical, and embedding_test.go asserts it, so one HTTP embedder serves chapter 28’s router gate and the store:

// Embedder is one /v1/embeddings batch: texts in, one vector per text in the
// same order. It is method-identical to decide.Embedder (chapter 28), so one
// HTTP embedder serves the router's gate and the vector store.
type Embedder interface {
    Embed(ctx context.Context, texts []string) ([][]float32, error)
}

// HTTP is the fleet embedder: OpenAI /v1/embeddings on a llama.cpp router,
// guarded with no switch. Immediately before every batch it reads
// GET /v1/models on the same server and refuses (ErrNotLoaded) unless
// Model's status.value is exactly "loaded"; a sleeping model is not loaded.
// The batch is sent with ?autoload=false, proxies are ignored and redirects
// are refused, so a request reaches the host its URL names and no other.
// An input longer than MaxBatch is split into several requests, each guarded
// on its own.
type HTTP struct {
    BaseURL  string // server root: http://dixie:11434 (the router) or http://dixie:11435 (tether)
    Model    string // honcho-embed
    HTTP     *http.Client
    MaxBatch int // texts per request; 0 means DefaultMaxBatch
}

// DefaultMaxBatch is the texts per request when MaxBatch is 0. Chapter 32
// measured dixie: one request of 128 paragraphs completed, and the cost per
// kilobyte of text stopped falling at about 32 texts per request, so the
// slot does not force 32 and a larger batch buys nothing measurable; the
// number bounds how much one failed request or one guard check covers.
const DefaultMaxBatch = 32

// ErrNotLoaded is the guard's refusal. Loaded wraps it with the status seen.
var ErrNotLoaded = errors.New("embed: model is not loaded; this client never loads a model")

// fleetTransport ignores the environment's proxy settings. A caller's client
// that brings no Transport of its own gets it too.
var fleetTransport = func() *http.Transport {
    t := http.DefaultTransport.(*http.Transport).Clone()
    t.Proxy = nil
    return t
}()

// noRedirect makes a 3xx the response, so a POST body is never resent to
// another host.
func noRedirect(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }

func (h *HTTP) client() *http.Client {
    if h.HTTP != nil {
        c := *h.HTTP
        c.CheckRedirect = noRedirect
        if c.Transport == nil {
            c.Transport = fleetTransport
        }
        return &c
    }
    return &http.Client{Timeout: 60 * time.Second, Transport: fleetTransport, CheckRedirect: noRedirect}
}

// Loaded is the guard: it reads /v1/models and returns nil only when Model
// is listed with status.value "loaded".
func (h *HTTP) Loaded(ctx context.Context) error {
    req, err := http.NewRequestWithContext(ctx, http.MethodGet, h.BaseURL+"/v1/models", nil)
    if err != nil {
        return fmt.Errorf("embed: %w", err)
    }
    resp, err := h.client().Do(req)
    if err != nil {
        return fmt.Errorf("embed: GET /v1/models: %w", err)
    }
    defer resp.Body.Close()
    if resp.StatusCode != http.StatusOK {
        return fmt.Errorf("embed: GET /v1/models: %s", resp.Status)
    }
    var list struct {
        Data []struct {
            ID     string `json:"id"`
            Status struct {
                Value string `json:"value"`
            } `json:"status"`
        } `json:"data"`
    }
    if err := json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(&list); err != nil {
        return fmt.Errorf("embed: GET /v1/models: %w", err)
    }
    for _, m := range list.Data {
        if m.ID == h.Model {
            if m.Status.Value != "loaded" {
                return fmt.Errorf("%w (%s is %q)", ErrNotLoaded, h.Model, m.Status.Value)
            }
            return nil
        }
    }
    return fmt.Errorf("%w (%s is not in /v1/models)", ErrNotLoaded, h.Model)
}

// Embed sends texts in batches of at most MaxBatch, re-running the guard
// before each. The vectors come back in the order of texts.
func (h *HTTP) Embed(ctx context.Context, texts []string) ([][]float32, error) {
    n := h.MaxBatch
    if n <= 0 {
        n = DefaultMaxBatch
    }
    out := make([][]float32, 0, len(texts))
    for start := 0; start < len(texts); start += n {
        end := min(start+n, len(texts))
        vecs, err := h.batch(ctx, texts[start:end])
        if err != nil {
            return nil, err
        }
        out = append(out, vecs...)
    }
    // One nonzero width for the whole call, so a store or a fingerprint never
    // sees an empty or ragged vector.
    for i, v := range out {
        if len(v) == 0 || len(v) != len(out[0]) {
            return nil, fmt.Errorf("embed: vector %d has %d values, vector 0 has %d (one nonzero width is required)", i, len(v), len(out[0]))
        }
    }
    return out, nil
}

func (h *HTTP) batch(ctx context.Context, texts []string) ([][]float32, error) {
    if err := h.Loaded(ctx); err != nil {
        return nil, err
    }
    body, _ := json.Marshal(map[string]any{"model": h.Model, "input": texts})
    req, err := http.NewRequestWithContext(ctx, http.MethodPost, h.BaseURL+"/v1/embeddings?autoload=false", bytes.NewReader(body))
    if err != nil {
        return nil, fmt.Errorf("embed: %w", err)
    }
    req.Header.Set("Content-Type", "application/json")
    resp, err := h.client().Do(req)
    if err != nil {
        return nil, fmt.Errorf("embed: POST /v1/embeddings: %w", err)
    }
    defer resp.Body.Close()
    if resp.StatusCode != http.StatusOK {
        return nil, fmt.Errorf("embed: POST /v1/embeddings: %s", resp.Status)
    }
    var out struct {
        Data []struct {
            Index     int        `json:"index"`
            Embedding []*float64 `json:"embedding"`
        } `json:"data"`
    }
    if err := json.NewDecoder(io.LimitReader(resp.Body, 64<<20)).Decode(&out); err != nil {
        return nil, fmt.Errorf("embed: POST /v1/embeddings: %w", err)
    }
    if len(out.Data) != len(texts) {
        return nil, fmt.Errorf("embed: %d vectors for %d texts", len(out.Data), len(texts))
    }
    vecs := make([][]float32, len(texts))
    for _, d := range out.Data {
        if d.Index < 0 || d.Index >= len(texts) || vecs[d.Index] != nil {
            return nil, fmt.Errorf("embed: index %d: indices must be 0..%d, each once", d.Index, len(texts)-1)
        }
        row := make([]float32, len(d.Embedding))
        for j, x := range d.Embedding {
            if x == nil || math.IsNaN(*x) || math.Abs(*x) > math.MaxFloat32 {
                return nil, fmt.Errorf("embed: a value that is not a float32 at [%d][%d]", d.Index, j)
            }
            row[j] = float32(*x)
        }
        vecs[d.Index] = row
    }
    return vecs, nil
}

The guard is chapter 21’s, restated with the three facts it rests on. ?autoload=true|false in the query string “control[s] this behavior per-request” (README line 1795). A model’s status is one of loading, unloaded, loaded or sleeping (lines 1840 to 1863). And chapter 21 found, in the router’s source, that at this llama.cpp build the router counts a sleeping model as running, so ?autoload=false does not stop a request from waking it. Loaded therefore requires status.value == "loaded" and nothing weaker, and batch calls it immediately before each POST. The rule this chapter adds is in Embed: a call with more than MaxBatch texts is split, and the guard runs before every piece, because a model can be evicted between two requests of one call. TestGuardBeforeEveryBatch sends seven texts at MaxBatch 3 and requires three batches, three reads of /v1/models, and autoload=false on every batch.

Two templates

Qwen3-Embedding is trained to embed a retrieval query under an instruction and a document as it is. The model card’s reference code builds the query as f'Instruct: {task_description}\nQuery:{query}' and says, above the documents, “No need to add instruction for retrieval documents”. The card’s own TEI example writes Query: with a space. One byte changes the tokens and therefore the vector, so the book picks one and uses it everywhere: the Python reference’s, which has no space, and which chapters 21 and 28 already use.

// Query renders a query under Qwen3-Embedding's instruction format, exactly
// as chapters 21 and 28 do: "Instruct: " + instruction + "\nQuery:" + text,
// with no space after the colon (the model card's get_detailed_instruct).
func Query(instruction, text string) string {
    return "Instruct: " + instruction + "\nQuery:" + text
}

// Document is a stored text: embedded as it is, with no instruction ("No
// need to add instruction for retrieval documents", the model card).
func Document(text string) string { return text }

The card claims that using instructions “typically yields an improvement of 1% to 5%” on downstream tasks. That is the vendor’s number for its own benchmarks. This chapter does not measure it, and it matters here only in one way: queries and documents are embedded differently, so a stored document and the same text asked as a query do not land on the same point.

Pooling, once more

The transformer returns one hidden state per position, and an embedding is one vector per text. Chapter 15 gave the two pooling rules for an encoder, mean and CLS, and said that a decoder’s last pooling is the causal counterpart: only the last position has read the whole text. Chapter 21’s “Pooling a decoder into one vector” proves it and shows what cls pooling does to a decoder. The incident there is the reason the next subsections exist: on 2026-09-29 the preset on dixie changed to --pooling cls, every text was embedded as its first token, the alias, the GGUF and the width were unchanged, every request returned 200 with 1,024 finite numbers, and only the vectors were wrong. A store of such vectors retrieves by first token. Nothing in this chapter re-derives that; “The fingerprint” below says what the store does about it.

Three metrics, and when they agree

Take a query q∈Rdq \in \mathbb{R}^d and nn stored vectors collected as the rows of V∈Rn×dV \in \mathbb{R}^{n \times d}. Search scores all of them at once, s=Vq∈Rns = Vq \in \mathbb{R}^{n} for unit vectors, and keeps the largest kk entries of ss. Three scores are in use:

cos(q,v)=q⋅v∥q∥∥v∥,q⋅v,−∥q−v∥. \cos(q, v) = \frac{q \cdot v}{\lVert q \rVert \, \lVert v \rVert}, \qquad q \cdot v, \qquad -\lVert q - v \rVert.

On unit vectors, ∥q∥=∥v∥=1\lVert q \rVert = \lVert v \rVert = 1, the cosine is the dot product. The Euclidean distance is a function of it. Expanding the square term by term,

∥q−v∥2=∥q∥2−2q⋅v+∥v∥2=2−2q⋅v, \lVert q - v \rVert^2 = \lVert q \rVert^2 - 2\, q \cdot v + \lVert v \rVert^2 = 2 - 2\, q \cdot v,

so ∥q−v∥=2−2q⋅v\lVert q - v \rVert = \sqrt{2 - 2\, q \cdot v}, which decreases strictly as q⋅vq \cdot v grows. Ranking by smallest distance and ranking by largest cosine produce the same order, and so does the dot product. For the fleet’s embedder all three are the same search.

They differ when a caller’s vectors are not unit length. The package’s rule: a Hit’s Score is a similarity, higher is closer, and L2L_2’s score is the negated distance, so one comparator serves every metric (the Metric type is in the listing below). On the fixture below, the norms after float16 rounding lie in [0.999960, 1.000045][0.999960,\ 1.000045] (a script over the committed files, talos), and the top-10 lists of all 32 queries are identical under cosine, dot and L2L_2. That is a measurement of one fixture, not a proof: two scores closer than the norms’ spread of about 10−410^{-4} could swap under a different metric, and none did.

// Metric is how two vectors are compared. Cosine on L2-normalised vectors
// equals Dot; llama-server's /v1/embeddings returns unit vectors, so the
// two agree on everything the fleet embeds and differ on vectors a caller
// scaled.
type Metric int

const (
    Cosine Metric = iota
    Dot
    L2
)

func (m Metric) String() string {
    switch m {
    case Cosine:
        return "cosine"
    case Dot:
        return "dot"
    case L2:
        return "l2"
    }
    return "metric?"
}

// Record is one stored vector. Text is optional and is what a Rebuild
// re-embeds; a store whose records have no Text cannot Rebuild. Meta is
// what a Filter reads.
type Record struct {
    ID     string
    Vector []float32
    Meta   map[string]string
    Text   string
}

// Hit is one search result. Score is the metric's similarity, higher is
// closer (L2 is the negated distance), so every Metric ranks the same way
// and ties are broken by ID in every index.
type Hit struct {
    ID    string
    Score float32
    Meta  map[string]string
}

// Filter accepts a record by its metadata; nil accepts all. Flat applies it
// before scoring. HNSW applies it on layer 0 during traversal: a rejected
// node is still expanded, so a selective filter does not disconnect the
// search; the upper layers route and ignore it.
type Filter func(meta map[string]string) bool

// Match is the filter that requires every key of kv to be present with the
// given value.
func Match(kv map[string]string) Filter {
    return func(meta map[string]string) bool {
        for k, v := range kv {
            if got, ok := meta[k]; !ok || got != v {
                return false
            }
        }
        return true
    }
}

// Index is what Flat, HNSW and Store share and what memsvc programs against.
// Add replaces a record whose ID is already present. Delete of an unknown ID
// is ErrNotFound. Search returns at most k hits, best first.
type Index interface {
    Add(r Record) error
    Delete(id string) error
    Search(q []float32, k int, f Filter) ([]Hit, error)
    Len() int
    Dim() int
}

// Errors every index shares.
var (
    ErrDim      = errors.New("vecdb: vector width differs from the index's")
    ErrNotFound = errors.New("vecdb: no record with that id")
    ErrEmptyID  = errors.New("vecdb: a record needs a non-empty id")
    // ErrNonFinite refuses a vector with a NaN or infinite component, stored
    // or queried: no order exists on NaN scores, and the exact index is the
    // ground truth recall is measured against.
    ErrNonFinite = errors.New("vecdb: a vector component is NaN or infinite")
)

Exact search and its cost

From a text to a ranked list by exact search Four stages from top to bottom. First, the text: a stored paragraph is embedded as it is, and a question is rendered under the instruction format, Instruct, the task, a newline, Query, a colon and the question with no space. Second, the embedder: honcho-embed on dixie behind the guard, which reads the model list and refuses unless the model is loaded, then posts the batch with autoload false; one unit vector of 1,024 floats comes back per text. Third, the exact scan: every stored row is scored by cosine, the k best are kept in a min-heap whose root is the worst kept, and equal scores order by ID. Fourth, the hits, best first, with rank, id, book and score; this list is the ground truth chapter 33 approximates. Text Document(text)the paragraph, as it is, no instruction Query(instruction, text)"Instruct: " + instruction + "\nQuery:" + text Embedderhoncho-embed on dixie, behind the guard GET /v1/modelsbefore every batch; refuse unlessstatus.value == "loaded" POST /v1/embeddings?autoload=falseno proxy, no redirect one unit vector of 1,024 floats per text: last-token pooling, L2-normalised by the server Exact scann rows of d floats: n·d multiplications per query score every row the filter accepts: cos(q, v) = q·v / (|q| |v|), equal to q·v on unit vectors keep the k best in a min-heap whose root is the worst kept: O(n log k) comparisons equal scores order by ID, so the list is a function of the data and the query the committed fixture: 1,018 rows × 1,024 floats, 2,084,864 bytes as float16 Hits, best first rank id book score 1 … kscore descending, then ID ascending recall@k of this list against itself is 1: it is the ground truth chapter 33 approximates

Flat scores every row and keeps the best kk. Scoring one row is dd multiplications and additions, so one query costs ndn d of them. For the fixture, n=1018n = 1018 and d=1024d = 1024 give 1,042,432. The lab’s benchmarks (go test -run XXX -bench FlatSearch -benchtime 2000x -count 3 ./labs/ch32, run on straylight) print:

cpu: AMD RYZEN AI MAX+ 395 w/ Radeon 8060S          
BenchmarkFlatSearchFixture-32                 2000        417655 ns/op
BenchmarkFlatSearchFixture-32                 2000        430191 ns/op
BenchmarkFlatSearchFixture-32                 2000        418142 ns/op
BenchmarkFlatSearchFilteredBook-32            2000         46595 ns/op
BenchmarkFlatSearchFilteredBook-32            2000         45019 ns/op
BenchmarkFlatSearchFilteredBook-32            2000         46265 ns/op

So Flat.Search with k=10k = 10 over the fixture takes 418,142 ns at the median of the three runs, about 0.40 ns per multiply-add.

The cost is linear in nn, and that linearity is the reason chapter 33 exists: a memory of a million vectors costs a thousand times more per query.

The kk best are kept in a bounded min-heap whose root is the worst kept hit. A row’s cost depends on what it scores. It is compared once with the root; if it is not better it is dropped. If it is better, it replaces the root and sinks to its place, which takes at most two comparisons per level of a heap of kk entries, 2⌊log2k⌋2 \lfloor \log_2 k \rfloor. In the worst case, scores that rise with the row index, every row is kept, and the total is O(nlogk)O(n \log k). In the usual case far fewer rows enter. If the rows come in random order with distinct scores, the rank of row ii among the first ii rows is uniform over the ii places, so it is among the best kk of them with probability k/ik/i, and it replaces the root exactly when it is. The expected number of replacements after the heap fills is

∑i=k+1nki=k(Hn−Hk)≈klnnk, \sum_{i=k+1}^{n} \frac{k}{i} = k\,(H_n - H_k) \approx k \ln \frac{n}{k},

with Hm=∑j=1m1/jH_m = \sum_{j=1}^{m} 1/j. For k=5k = 5 and n=1018n = 1018 this is 26.10; counting the replacements over the 32 queries’ scans in file order gives a mean of 27.41 (range 10 to 46), and over one random permutation per query 25.28, 32 samples (a numpy script on talos). The scan, not the heap, is the cost: about one comparison with the root per row, and a few dozen sifts per query.

Two rules are part of the behaviour, not the speed. The filter is applied before scoring: a row the filter rejects costs one call of the filter and no multiply-adds. That still visits nn rows. Filtering the fixture to book 6, which holds 33 of the 1,018 paragraphs, took 46,265 ns at the median of the three runs above, 9.0 times faster than the unfiltered search and 3.2% of its scoring, because the scan and the 1,018 filter calls remain (exercise (c)). And ties are broken by ID. Equal float32 scores happen, with duplicate texts, symmetric vectors, or a Dot on integer data. Recall@k is a function of the data only if the kk-th place is decided by something other than iteration order, so every heap and every sort in the package orders by (score, ID), through better. A NaN or infinite component is refused with ErrNonFinite on Add and Search, since no order exists on NaN scores and the exact index is the ground truth; a finite row that overflows to a NaN score ranks after every number.

// Flat is the exact index: every stored vector is scored and the top k are
// kept in a bounded heap. It is chapter 32's lab and chapter 33's ground
// truth. Rows are stored densely; Delete swaps the last row into the hole,
// so Len is the row count and iteration order is not insertion order.
type Flat struct {
    metric Metric
    dim    int
    ids    []string
    rows   [][]float32
    norms  []float32
    metas  []map[string]string
    texts  []string
    where  map[string]int // id -> row
}

// NewFlat makes an empty exact index of width dim.
func NewFlat(dim int, m Metric) *Flat {
    return &Flat{metric: m, dim: dim, where: map[string]int{}}
}

var _ Index = (*Flat)(nil)

func (f *Flat) Len() int { return len(f.ids) }
func (f *Flat) Dim() int { return f.dim }

// Add stores r, replacing a record with the same ID. The vector is copied.
func (f *Flat) Add(r Record) error {
    if r.ID == "" {
        return ErrEmptyID
    }
    if len(r.Vector) != f.dim {
        return ErrDim
    }
    if !finite(r.Vector) {
        return ErrNonFinite
    }
    v := append([]float32(nil), r.Vector...)
    if i, ok := f.where[r.ID]; ok {
        f.rows[i], f.norms[i], f.metas[i], f.texts[i] = v, norm(v), copyMeta(r.Meta), r.Text
        return nil
    }
    f.where[r.ID] = len(f.ids)
    f.ids = append(f.ids, r.ID)
    f.rows = append(f.rows, v)
    f.norms = append(f.norms, norm(v))
    f.metas = append(f.metas, copyMeta(r.Meta))
    f.texts = append(f.texts, r.Text)
    return nil
}

// Delete removes id; the last row takes its place.
func (f *Flat) Delete(id string) error {
    i, ok := f.where[id]
    if !ok {
        return ErrNotFound
    }
    last := len(f.ids) - 1
    if i != last {
        f.ids[i], f.rows[i], f.norms[i], f.metas[i], f.texts[i] = f.ids[last], f.rows[last], f.norms[last], f.metas[last], f.texts[last]
        f.where[f.ids[i]] = i
    }
    f.ids, f.rows, f.norms, f.metas, f.texts = f.ids[:last], f.rows[:last], f.norms[:last], f.metas[:last], f.texts[:last]
    delete(f.where, id)
    return nil
}

// Search scores every row that fl accepts and keeps the k best in a
// min-heap whose root is the worst kept hit: a new score replaces the root
// when it is better (by better: higher score, then lower ID). The cost is
// n distance computations and at most n log k heap operations.
func (f *Flat) Search(q []float32, k int, fl Filter) ([]Hit, error) {
    if len(q) != f.dim {
        return nil, ErrDim
    }
    if !finite(q) {
        return nil, ErrNonFinite
    }
    if k <= 0 {
        return nil, nil
    }
    qn := norm(q)
    h := &hitHeap{}
    for i, v := range f.rows {
        if fl != nil && !fl(f.metas[i]) {
            continue
        }
        s := score(f.metric, q, qn, v, f.norms[i])
        if h.Len() < k {
            heap.Push(h, Hit{ID: f.ids[i], Score: s})
        } else if better(s, f.ids[i], (*h)[0].Score, (*h)[0].ID) {
            (*h)[0] = Hit{ID: f.ids[i], Score: s}
            heap.Fix(h, 0)
        }
    }
    hits := make([]Hit, h.Len())
    for i := len(hits) - 1; i >= 0; i-- {
        hits[i] = heap.Pop(h).(Hit)
    }
    for i := range hits {
        hits[i].Meta = copyMeta(f.metas[f.where[hits[i].ID]])
    }
    return hits, nil
}

// hitHeap is a min-heap by better: the root is the worst hit kept.
type hitHeap []Hit

func (h hitHeap) Len() int           { return len(h) }
func (h hitHeap) Less(i, j int) bool { return better(h[j].Score, h[j].ID, h[i].Score, h[i].ID) }
func (h hitHeap) Swap(i, j int)      { h[i], h[j] = h[j], h[i] }
func (h *hitHeap) Push(x any)        { *h = append(*h, x.(Hit)) }
func (h *hitHeap) Pop() any          { old := *h; x := old[len(old)-1]; *h = old[:len(old)-1]; return x }

One host reproduces its own float32 sums exactly, since the order of the additions is fixed. Two hosts need not: summation order differs with the CPU’s vector kernels, and this book never claims bit-exact results across machines. Chapter 33 therefore states a tolerance of ±0.01\pm 0.01 for recall compared across hosts. The fixture search below was run on talos and straylight, and the ids and four-digit scores of the first three queries’ top five agree on both. That is a check on two hosts, not a guarantee for a third.

Recall as the metric

Let EkE_k be the exact top-kk ids and AkA_k the approximate index’s list cut to ∣Ek∣\lvert E_k \rvert. Then

recall@k=∣Ek∩Ak∣∣Ek∣. \text{recall@}k = \frac{\lvert E_k \cap A_k \rvert}{\lvert E_k \rvert}.

An empty EkE_k is recall 1, since nothing was missed. The cut matters: an approximate index that returns k+1k+1 ids does not get credit for the extra one. If both lists have kk entries, precision@k is the same number: the intersection is the same set, and the two denominators are both kk. Order inside the top kk is not scored, because chapter 33’s graph returns its kept set sorted by true distance, so order is never the approximation’s error. The mean over queries is the number chapter 33 reports.

What recall does not see: a hit at rank k+1k+1 is as absent as a random one, and a list that swaps rank kk with rank k+1k+1 in a region where all scores are within 10−410^{-4} loses a full 1/k1/k. Chapter 33 reports recall over several kk and search-width values for that reason.

// Recall is recall@k: the share of exact's ids that approx also returned,
// with approx cut to len(exact). Both indexes break ties at the k-th score
// by ID, so on one host the number is reproducible; two hosts whose
// float32 sums differ can still disagree on a near-tie, so cross-host
// comparisons use a tolerance, never equality. An empty exact is recall 1.
func Recall(exact, approx []Hit) float64 {
    if len(exact) == 0 {
        return 1
    }
    if len(approx) > len(exact) {
        approx = approx[:len(exact)]
    }
    got := make(map[string]bool, len(approx))
    for _, h := range approx {
        got[h.ID] = true
    }
    n := 0
    for _, h := range exact {
        if got[h.ID] {
            n++
        }
    }
    return float64(n) / float64(len(exact))
}

The fingerprint

What names an embedding space? Name (the id /v1/models lists), Model, Dim, Pooling and Normalize. What the incident showed is that none of those names can see a server flag. The fingerprint therefore also carries probes: six texts and the vectors the space gave them when it was captured. They are this fingerprint’s own capture, not borrowed from the probe file chapter 21’s student carries.

Capture embeds the probes, embeds them again as a second batch, and embeds a third batch with every probe doubled, which is chapter 21’s in-batch duplicate, the case that moved a vector most on dixie (0.998618 on 2026-09-30, DECISIONS). It takes the worst cosine between any repeat and its probe, cworstc_{\text{worst}}, and sets

Threshold=min(0.999, cworst−0.0005). \text{Threshold} = \min\bigl(0.999,\ c_{\text{worst}} - 0.0005\bigr).

The 0.0005 is margin below the worst repeat the embedder produced, and the 0.999 cap keeps the check an inequality with room in it for an embedder that repeats exactly: a float comparison is never an equality test. Capture enforces no floor on cworstc_{\text{worst}}. An embedder that repeats itself badly gets a low threshold, and the caller decides whether that space is worth fingerprinting; its doc comment says so.

Two methods use the fingerprint. Equal compares identity, Name, Model, Dim, Pooling, Normalize and the probe texts, and not the threshold: the threshold is a measured property of one capture, so recapturing the same space must still be Equal, or Open would answer a schema error for a space that had not changed. Check re-embeds the probes as one batch and requires every cosine with the stored vector to be at least Threshold. It is written as a pass (!(c >= f.Threshold) is the failure), so a wrong width, a NaN or a zero vector never passes, and it refuses a fingerprint with no probes or a threshold outside (0,1](0, 1], since a hand-edited file must not turn the check into a pass. Chapter 34 uses both: Equal for the schema at open, Check for the drift no name shows.

// Fingerprint identifies an embedding space. A vecdb store records it at
// creation and checks it at open: a different Name, Model, Dim, Pooling or
// Normalize is a schema change outright, and a probe whose fresh cosine
// falls below Threshold is the change no name check sees (chapter 21's
// pooling incident: same alias, same GGUF, same dimension, different
// vectors). Probes are the fingerprint's own capture, never jev-lite's file.
type Fingerprint struct {
    Name      string  `json:"name"`      // the id /v1/models lists: honcho-embed
    Model     string  `json:"model"`     // Qwen3-Embedding-0.6B
    Dim       int     `json:"dim"`       // 1024
    Pooling   string  `json:"pooling"`   // last
    Normalize string  `json:"normalize"` // l2
    Threshold float64 `json:"threshold"` // at most 0.999, never equality (plan ruling 19)
    Probes    []Probe `json:"probes"`
}

// Probe is one text and the vector the space gave it when the fingerprint
// was captured.
type Probe struct {
    Text   string    `json:"text"`
    Vector []float32 `json:"vector"`
}

// ErrMismatch is a failed Check: the embedder does not reproduce the probes.
var ErrMismatch = errors.New("embed: fingerprint mismatch")

// MaxThreshold caps Threshold: an embedder that repeats exactly still gets a
// check with a margin, never an equality test on floats.
const MaxThreshold = 0.999

// Check re-embeds the probes as one batch and requires every cosine with the
// stored vector to be at least Threshold. It is written as a pass, so a wrong
// width, a NaN or a zero vector never passes. A fingerprint with no probes
// cannot be checked and fails, and so does one whose Threshold is outside
// (0, 1]: a hand-edited file must not turn the check into a pass for any
// embedder of the right width.
func (f *Fingerprint) Check(ctx context.Context, e Embedder) error {
    if len(f.Probes) == 0 {
        return fmt.Errorf("%w: the fingerprint has no probes", ErrMismatch)
    }
    if !(f.Threshold > 0 && f.Threshold <= 1) { // written as a pass: NaN fails it
        return fmt.Errorf("%w: threshold %g is outside (0, 1]", ErrMismatch, f.Threshold)
    }
    texts := make([]string, len(f.Probes))
    for i, p := range f.Probes {
        texts[i] = p.Text
    }
    live, err := e.Embed(ctx, texts)
    if err != nil {
        return err
    }
    if len(live) != len(texts) {
        return fmt.Errorf("%w: %d vectors for %d probes", ErrMismatch, len(live), len(texts))
    }
    for i, v := range live {
        if len(v) != f.Dim || len(f.Probes[i].Vector) != f.Dim {
            return fmt.Errorf("%w: probe %d has %d values, the space has %d", ErrMismatch, i, len(v), f.Dim)
        }
        c := Cosine(v, f.Probes[i].Vector)
        if !(c >= f.Threshold) { // a NaN fails this comparison, as it should
            return fmt.Errorf("%w: probe %d cosine %.6f below %g", ErrMismatch, i, c, f.Threshold)
        }
    }
    return nil
}

// Equal is true when the identity fields agree: Name, Model, Dim, Pooling,
// Normalize and the probe texts, so two fingerprints of one space captured
// with different probes are not Equal. Threshold is a measured property of
// one capture (it moves with batch noise), not identity, so recapturing the
// same space is Equal. Vectors are compared by Check, not by Equal.
func (f *Fingerprint) Equal(g *Fingerprint) bool {
    if f == nil || g == nil {
        return f == g
    }
    if f.Name != g.Name || f.Model != g.Model || f.Dim != g.Dim || f.Pooling != g.Pooling ||
        f.Normalize != g.Normalize || len(f.Probes) != len(g.Probes) {
        return false
    }
    for i := range f.Probes {
        if f.Probes[i].Text != g.Probes[i].Text {
            return false
        }
    }
    return true
}

// Capture builds a Fingerprint from e. It embeds texts once (these become
// the probes), again as a second batch, and a third time with every text
// doubled in one batch (chapter 21's in-batch duplicate, the case that moved
// a vector most on dixie), takes the worst cosine between any repeat and its
// probe, and sets Threshold to min(MaxThreshold, worst - 0.0005). It enforces
// no floor on that worst cosine: an embedder that repeats itself badly gets a
// low Threshold, and the caller decides whether that space is worth
// fingerprinting (a Threshold of 0 or less fails every Check). It is an
// implementer step behind the guard, never a test.
func Capture(ctx context.Context, e Embedder, name, model, pooling, normalize string, texts []string) (*Fingerprint, error) {
    if len(texts) == 0 {
        return nil, errors.New("embed: capture needs at least one probe text")
    }
    first, err := e.Embed(ctx, texts)
    if err != nil {
        return nil, err
    }
    second, err := e.Embed(ctx, texts)
    if err != nil {
        return nil, err
    }
    doubled := make([]string, 0, 2*len(texts))
    for _, t := range texts {
        doubled = append(doubled, t, t)
    }
    third, err := e.Embed(ctx, doubled)
    if err != nil {
        return nil, err
    }
    if len(first) != len(texts) || len(second) != len(texts) || len(third) != 2*len(texts) {
        return nil, errors.New("embed: capture: the embedder returned the wrong number of vectors")
    }
    dim := len(first[0])
    if dim == 0 {
        return nil, errors.New("embed: capture: empty vectors")
    }
    worst := 1.0
    f := &Fingerprint{Name: name, Model: model, Dim: dim, Pooling: pooling, Normalize: normalize}
    for i, t := range texts {
        if len(first[i]) != dim {
            return nil, fmt.Errorf("embed: capture: vector %d has %d values, vector 0 has %d", i, len(first[i]), dim)
        }
        for _, rep := range [][]float32{second[i], third[2*i], third[2*i+1]} {
            c := Cosine(first[i], rep)
            if math.IsNaN(c) {
                return nil, fmt.Errorf("embed: capture: a NaN cosine for probe %d", i)
            }
            worst = math.Min(worst, c)
        }
        f.Probes = append(f.Probes, Probe{Text: t, Vector: first[i]})
    }
    f.Threshold = math.Min(MaxThreshold, worst-0.0005)
    return f, nil
}

// Cosine is a·b / (|a||b|) in float64; it is NaN when either vector is zero
// or the lengths differ, so a caller's ">=" comparison fails.
func Cosine(a, b []float32) float64 {
    if len(a) != len(b) || len(a) == 0 {
        return math.NaN()
    }
    var dot, na, nb float64
    for i := range a {
        x, y := float64(a[i]), float64(b[i])
        dot += x * y
        na += x * x
        nb += y * y
    }
    if na == 0 || nb == 0 {
        return math.NaN()
    }
    return dot / (math.Sqrt(na) * math.Sqrt(nb))
}

float16 for the fixture

The committed fixture holds its vectors as IEEE 754 binary16: 1 sign bit, 5 exponent bits and 10 stored mantissa bits, so 11 significant bits with the hidden one. Round-to-nearest-even gives a relative error of at most 2−112^{-11} per component in the normal range, ∣x∣≥2−14\lvert x \rvert \ge 2^{-14}: the spacing at a value in [2e,2e+1)[2^e, 2^{e+1}) is 2e−102^{e-10}, half of it is 2e−112^{e-11}, and that is at most 2−11∣x∣2^{-11}\lvert x \rvert.

What does that do to a cosine? Let vv be a unit vector, v′=v+ev' = v + e its rounding, with ∣ei∣≤2−11∣vi∣\lvert e_i \rvert \le 2^{-11} \lvert v_i \rvert, so that ∥e∥≤2−11∥v∥=2−11\lVert e \rVert \le 2^{-11} \lVert v \rVert = 2^{-11}. Split e=av+e⊥e = a\,v + e_\perp with a=v⋅ea = v \cdot e and e⊥⊥ve_\perp \perp v. Then ∣a∣≤∥e∥≤2−11\lvert a \rvert \le \lVert e \rVert \le 2^{-11}, ∥e∥2=a2+∥e⊥∥2\lVert e \rVert^2 = a^2 + \lVert e_\perp \rVert^2, and

v⋅v′=1+a,∥v′∥2=1+2a+∥e∥2=(1+a)2+∥e⊥∥2, v \cdot v' = 1 + a, \qquad \lVert v' \rVert^2 = 1 + 2a + \lVert e \rVert^2 = (1 + a)^2 + \lVert e_\perp \rVert^2,

so, with x=∥e⊥∥2/(1+a)2x = \lVert e_\perp \rVert^2 / (1+a)^2,

cos(v,v′)=1+a(1+a)2+∥e⊥∥2=(1+x)−1/2. \cos(v, v') = \frac{1 + a}{\sqrt{(1+a)^2 + \lVert e_\perp \rVert^2}} = (1 + x)^{-1/2}.

The function f(x)=(1+x)−1/2f(x) = (1+x)^{-1/2} is convex (f′′(x)=34(1+x)−5/2>0f''(x) = \tfrac34 (1+x)^{-5/2} > 0), so it lies above its tangent at 0, 1−x/21 - x/2. Hence 1−cos≤x/21 - \cos \le x/2, and

1−cos(v,v′)≤∥e⊥∥22(1+a)2≤2−222(1−2−11)2=2−23(1−2−11)−2≈1.193×10−7, 1 - \cos(v, v') \le \frac{\lVert e_\perp \rVert^2}{2\,(1+a)^2} \le \frac{2^{-22}}{2\,(1 - 2^{-11})^2} = 2^{-23}\,(1 - 2^{-11})^{-2} \approx 1.193 \times 10^{-7},

using ∥e⊥∥≤∥e∥≤2−11\lVert e_\perp \rVert \le \lVert e \rVert \le 2^{-11} and 1+a≥1−2−111 + a \ge 1 - 2^{-11}. The factor (1−2−11)−2(1-2^{-11})^{-2} is 1+2−10+O(2−20)1 + 2^{-10} + O(2^{-20}), so the bound is 2−23=1.19×10−72^{-23} = 1.19 \times 10^{-7} to three digits. A component below 2−142^{-14} in magnitude has a fixed absolute error of at most 2−252^{-25} instead of a relative one; at most 1,024 of them add at most 1024⋅2−50=2−401024 \cdot 2^{-50} = 2^{-40} to ∥e∥2\lVert e \rVert^2, which is 2−182^{-18} of the 2−222^{-22} budget. The capture prints the worst self-cosine over the 1,018 document vectors: the measured 1−S1 - S is below.

The norm after rounding is bounded more directly: ∥v′∥2=∑ivi2(1+εi)2\lVert v' \rVert^2 = \sum_i v_i^2 (1 + \varepsilon_i)^2 with ∣εi∣≤2−11\lvert \varepsilon_i \rvert \le 2^{-11}, so ∥v′∥∈[1−2−11, 1+2−11]\lVert v' \rVert \in [1 - 2^{-11},\ 1 + 2^{-11}], within 4.9×10−44.9 \times 10^{-4} of 1 (exercise (f) uses it).

The reason for float16 at all is size: 1,018 vectors of 1,024 components at 2 bytes are 2,084,864 bytes, against 4,169,728 as float32, for a loss the bound above puts under 1.2×10−71.2 \times 10^{-7} in cosine. LoadFixture widens them back to float32 for every index.

// The committed fixture stores vectors as IEEE 754 binary16 (1 sign, 5
// exponent, 10 mantissa bits): at most 1,024 vectors × 1,024 dimensions × 2
// bytes, under 2 MiB where float32 would be twice that. A unit vector's
// components are below 1 in magnitude, and the 11 significant bits give a
// relative error of at most 2^-11 for components of magnitude at least
// 2^-14; smaller ones (rare in a 1,024-wide unit vector) carry an absolute
// error of at most 2^-25. The cosine of a vector with its own float16
// rounding is above 0.99999 in practice; chapter 32 prints the measured
// value. Go has no float16, so the conversion is written out.

// F16Bits rounds a float32 to binary16, round-to-nearest-even, with
// overflow to infinity and subnormals kept.
func F16Bits(f float32) uint16 {
    b := math.Float32bits(f)
    sign := uint16(b>>16) & 0x8000
    exp := int((b>>23)&0xff) - 127
    mant := b & 0x7fffff
    switch {
    case exp == 128: // Inf or NaN
        if mant != 0 {
            return sign | 0x7e00
        }
        return sign | 0x7c00
    case exp > 15: // too large: infinity
        return sign | 0x7c00
    case exp >= -14: // normal
        m := mant >> 13
        rem := mant & 0x1fff
        if rem > 0x1000 || (rem == 0x1000 && m&1 == 1) {
            m++
        }
        h := uint16(exp+15)<<10 + uint16(m) // a mantissa carry rolls into the exponent, which is right
        return sign | h
    case exp >= -25: // subnormal in float16
        shift := uint(-exp - 14 + 13) // 14..24
        full := mant | 0x800000
        m := full >> shift
        rem := full & (1<<shift - 1)
        half := uint32(1) << (shift - 1)
        if rem > half || (rem == half && m&1 == 1) {
            m++
        }
        return sign | uint16(m)
    }
    return sign // underflow to zero
}

// F16Float widens binary16 bits to float32 exactly.
func F16Float(h uint16) float32 {
    sign := uint32(h&0x8000) << 16
    exp := uint32(h>>10) & 0x1f
    mant := uint32(h & 0x3ff)
    switch exp {
    case 0:
        if mant == 0 {
            return math.Float32frombits(sign)
        }
        // subnormal: normalise
        e := uint32(127 - 15 + 1)
        for mant&0x400 == 0 {
            mant <<= 1
            e--
        }
        mant &= 0x3ff
        return math.Float32frombits(sign | e<<23 | mant<<13)
    case 0x1f:
        return math.Float32frombits(sign | 0x7f800000 | mant<<13)
    }
    return math.Float32frombits(sign | (exp+127-15)<<23 | mant<<13)
}

// WriteF16 writes vecs as little-endian binary16, row after row, no header
// (the dimension and count live in the fixture's JSON header).
func WriteF16(w io.Writer, vecs [][]float32) error {
    buf := make([]byte, 0, 2048)
    for _, v := range vecs {
        buf = buf[:0]
        for _, x := range v {
            buf = binary.LittleEndian.AppendUint16(buf, F16Bits(x))
        }
        if _, err := w.Write(buf); err != nil {
            return err
        }
    }
    return nil
}

// ReadF16 reads rows of dim binary16 values until EOF; a trailing partial
// row is an error.
func ReadF16(r io.Reader, dim int) ([][]float32, error) {
    raw, err := io.ReadAll(r)
    if err != nil {
        return nil, err
    }
    if dim <= 0 || len(raw)%(2*dim) != 0 {
        return nil, fmt.Errorf("vecdb: %d bytes is not a whole number of %d-wide float16 rows", len(raw), dim)
    }
    out := make([][]float32, len(raw)/(2*dim))
    for i := range out {
        row := make([]float32, dim)
        for j := range row {
            row[j] = F16Float(binary.LittleEndian.Uint16(raw[2*(i*dim+j):]))
        }
        out[i] = row
    }
    return out, nil
}

The corpus

The corpus is Project Gutenberg eBook #2199, the Iliad in Samuel Butler’s prose translation: public domain, stable, an external text and not this book’s own paragraphs, so a retrieval that works on it is not an artefact of the book’s wording. It is sampled by rules that the committed header pins: the plain-text file’s SHA-256 (the command refuses to write if the file changed), Gutenberg’s header and licence stripped between the *** START and *** END markers, CRLF folded to LF, lines of a paragraph joined with single spaces, paragraphs kept when they are over 200 bytes and at most 2,000, ids p0000, p0001, … counting the eligible paragraphs in text order, and book taken from the BOOK heading each falls under. The 2,000-byte cap exists because a token is at least one byte: no kept text can exceed 2,000 tokens (plus the end-of-sequence token the model appends), which fits both the 2,048-token physical batch and the 4,096-token cache of the embedder’s slot. At most 1,024 paragraphs are kept, by a seeded shuffle (seed 2199) and then sorted back into text order; on this text the cap does not bind, as the walkthrough shows, and the fixture holds every eligible paragraph.

The header pins counts and hashes and leaves out dates and hosts, so the file is a function of the source and the rules. The vectors are not: they came from one capture on one server, and a fresh capture is allowed to differ. Chapter 21 found that a vector moves with the batch it sits in, by up to about 1.2×10−31.2 \times 10^{-3} in cosine (DECISIONS, 2026-09-30). The tests therefore compare against the committed files and never against a recapture.

// The corpus is Project Gutenberg eBook #2199, the Iliad in Samuel Butler's
// prose translation (D4): public domain, stable, and not this book's own
// text. corpus fetches the plain-text file over the tailnet-free default
// transport with proxies ignored and redirects refused, checks its SHA-256
// against the value recorded when the fixture was made, strips Gutenberg's
// header and licence, splits on blank lines, keeps paragraphs between -min
// and -cap bytes, samples -max of them by seed, and writes them as JSON
// lines under a header that pins every rule it applied.
const (
    defaultCorpusURL = "https://www.gutenberg.org/cache/epub/2199/pg2199.txt"
    defaultCorpusSHA = "72673dcefeaa5d302b4ac1cc9ce6fd0b236831e816de41391e5cfe138ab5b077"
    startMarker      = "*** START OF THE PROJECT GUTENBERG EBOOK"
    endMarker        = "*** END OF THE PROJECT GUTENBERG EBOOK"
)

var bookHeading = regexp.MustCompile(`^BOOK ([IVXL]+)\.?$`)

func corpusCmd(args []string) error {
    fs := flag.NewFlagSet("corpus", flag.ExitOnError)
    out := fs.String("out", "", "directory for iliad-paragraphs.jsonl")
    url := fs.String("url", defaultCorpusURL, "the plain-text source")
    sha := fs.String("sha", defaultCorpusSHA, "expected SHA-256 of the source bytes")
    seed := fs.Int("seed", 2199, "sampling seed")
    max := fs.Int("max", 1024, "paragraphs to keep")
    min := fs.Int("min", 200, "a paragraph must be over this many bytes")
    cap := fs.Int("cap", 2000, "and at most this many (the embedder's slot is 4,096 tokens)")
    fs.Parse(args)
    if *out == "" {
        return errors.New("-out is required")
    }
    raw, err := fetch(*url)
    if err != nil {
        return err
    }
    sum := sha256.Sum256(raw)
    got := hex.EncodeToString(sum[:])
    fmt.Printf("source: %d bytes, sha256 %s\n", len(raw), got)
    if *sha != "" && got != *sha {
        return fmt.Errorf("source sha256 %s, expected %s: the file changed; nothing written", got, *sha)
    }
    paras, eligible, err := paragraphs(string(raw), *min, *cap)
    if err != nil {
        return err
    }
    fmt.Printf("eligible paragraphs (%d < bytes <= %d): %d\n", *min, *cap, eligible)
    r := rand.New(rand.NewPCG(uint64(*seed), 2199))
    r.Shuffle(len(paras), func(i, j int) { paras[i], paras[j] = paras[j], paras[i] })
    if len(paras) > *max {
        paras = paras[:*max]
    }
    sort.Slice(paras, func(i, j int) bool { return paras[i].ID < paras[j].ID })
    var body strings.Builder
    for _, p := range paras {
        line, _ := json.Marshal(p)
        body.Write(line)
        body.WriteByte('\n')
    }
    bsum := sha256.Sum256([]byte(body.String()))
    hdr := vecdb.CorpusHeader{Source: "gutenberg-2199", URL: *url, SourceSHA256: got, SourceBytes: len(raw), Translator: "Samuel Butler",
        MinBytes: *min, MaxBytes: *cap, Seed: *seed, Eligible: eligible, Count: len(paras), SHA256: hex.EncodeToString(bsum[:])}
    hline, _ := json.Marshal(hdr)
    if err := os.MkdirAll(*out, 0o755); err != nil {
        return err
    }
    path := filepath.Join(*out, "iliad-paragraphs.jsonl")
    if err := os.WriteFile(path, append(append(hline, '\n'), body.String()...), 0o644); err != nil {
        return err
    }
    fmt.Printf("wrote %s: %d paragraphs, sha256 %s\n", path, len(paras), hdr.SHA256)
    return nil
}

// fetch reads a URL with proxies ignored and redirects refused.
func fetch(url string) ([]byte, error) {
    tr := http.DefaultTransport.(*http.Transport).Clone()
    tr.Proxy = nil
    c := &http.Client{Timeout: 2 * time.Minute, Transport: tr,
        CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
    resp, err := c.Get(url)
    if err != nil {
        return nil, err
    }
    defer resp.Body.Close()
    if resp.StatusCode != http.StatusOK {
        return nil, fmt.Errorf("GET %s: %s", url, resp.Status)
    }
    return io.ReadAll(io.LimitReader(resp.Body, 8<<20))
}

// paragraphs splits the text between Gutenberg's markers into paragraphs.
// Lines are joined with single spaces; a paragraph is kept when
// min < len <= cap bytes; IDs count eligible paragraphs in order.
func paragraphs(text string, min, cap int) ([]vecdb.Paragraph, int, error) {
    text = strings.ReplaceAll(text, "\r\n", "\n")
    start := strings.Index(text, startMarker)
    end := strings.Index(text, endMarker)
    if start < 0 || end < 0 || end < start {
        return nil, 0, errors.New("the Gutenberg START/END markers were not found")
    }
    if nl := strings.IndexByte(text[start:], '\n'); nl >= 0 {
        start += nl + 1
    }
    body := text[start:end]
    var out []vecdb.Paragraph
    book := ""
    sc := bufio.NewScanner(strings.NewReader(body))
    sc.Buffer(make([]byte, 1<<20), 1<<20)
    var lines []string
    flush := func() {
        if len(lines) == 0 {
            return
        }
        p := strings.Join(lines, " ")
        lines = lines[:0]
        if m := bookHeading.FindStringSubmatch(p); m != nil {
            book = fmt.Sprint(roman(m[1]))
            return
        }
        if len(p) > min && len(p) <= cap && book != "" {
            out = append(out, vecdb.Paragraph{ID: fmt.Sprintf("p%04d", len(out)), Book: book, Text: p})
        }
    }
    for sc.Scan() {
        line := strings.TrimSpace(sc.Text())
        if line == "" {
            flush()
            continue
        }
        lines = append(lines, strings.Join(strings.Fields(line), " "))
    }
    flush()
    return out, len(out), sc.Err()
}

func roman(s string) int {
    val := map[byte]int{'I': 1, 'V': 5, 'X': 10, 'L': 50}
    n := 0
    for i := 0; i < len(s); i++ {
        v := val[s[i]]
        if i+1 < len(s) && v < val[s[i+1]] {
            n -= v
        } else {
            n += v
        }
    }
    return n
}

Walkthrough

The listings above are the package; two commands produce the fixture. corpus ran from go/, on talos:

source: 928957 bytes, sha256 72673dcefeaa5d302b4ac1cc9ce6fd0b236831e816de41391e5cfe138ab5b077
eligible paragraphs (200 < bytes <= 2000): 1018
wrote internal/vecdb/testdata/iliad-paragraphs.jsonl: 1018 paragraphs, sha256 5bf7478c024840d3e7798fc95b62db47eecf39e8e85bde215c656636b109c563

Between the markers there are 1,166 blank-line-separated blocks (a count made with the same splitting code, on talos). Of them 24 are BOOK headings, 5 precede the first heading, 94 are at most 200 bytes and 25 are over 2,000, which leaves 1,018. That is below the cap of 1,024, so the shuffle removed nothing, the header says "eligible":1018,"count":1018, and the fixture is the whole eligible set: 737,222 bytes of paragraph text (774,866 as JSON lines), between 201 and 1,985 bytes each, 19 to 73 per book (a script over the committed file). Ten paragraphs chosen at random were checked by eye: all are Butler’s prose, none carries Gutenberg boilerplate or licence text, and the book numbers run 1 to 24.

embed is the one guarded fleet contact of the chapter. It checks the guard once up front, then embedding.HTTP re-checks GET /v1/models before every batch and sends ?autoload=false. It measures one request each at batch sizes 1, 8, 32 and 128 (the median of five), embeds every paragraph as a document and every query under the instruction, and captures the fingerprint from three documents and three queries.

// embed is the one guarded capture of chapter 32: every paragraph as a
// document and every query under the instruction, through embedding.HTTP
// (GET /v1/models before every batch, ?autoload=false, no proxy, no
// redirect), written as float16; the fingerprint from six probes; and the
// latency of one request at batch sizes 1, 8, 32 and 128. It is run by hand
// once; nothing in go test calls it.
func embedCmd(args []string) error {
    fs := flag.NewFlagSet("embed", flag.ExitOnError)
    corpus := fs.String("corpus", "", "iliad-paragraphs.jsonl")
    queries := fs.String("queries", "", "iliad-queries.jsonl")
    out := fs.String("out", "", "directory for the vectors and the fingerprint")
    base := fs.String("base", "", "server root, e.g. http://dixie:11434")
    model := fs.String("model", "honcho-embed", "the id /v1/models lists")
    batch := fs.Int("batch", embedding.DefaultMaxBatch, "texts per request")
    fs.Parse(args)
    if *corpus == "" || *queries == "" || *out == "" || *base == "" {
        return errors.New("-corpus, -queries, -out and -base are required")
    }
    _, paras, err := vecdb.ReadCorpus(*corpus)
    if err != nil {
        return err
    }
    qh, qs, err := vecdb.ReadQueries(*queries)
    if err != nil {
        return err
    }
    e := &embedding.HTTP{BaseURL: *base, Model: *model, MaxBatch: *batch}
    ctx := context.Background()
    if err := e.Loaded(ctx); err != nil {
        return err
    }
    // Latency by batch size, one request each, median of five.
    for _, n := range []int{1, 8, 32, 128} {
        if n > len(paras) {
            break
        }
        texts := make([]string, n)
        for i := range texts {
            texts[i] = embedding.Document(paras[i].Text)
        }
        one := &embedding.HTTP{BaseURL: *base, Model: *model, MaxBatch: n}
        var ds []time.Duration
        var failed error
        for rep := 0; rep < 5; rep++ {
            t0 := time.Now()
            if _, err := one.Embed(ctx, texts); err != nil {
                failed = err
                break
            }
            ds = append(ds, time.Since(t0))
        }
        if failed != nil { // the measurement: this batch size does not fit the slot
            fmt.Printf("latency batch=%d failed: %v\n", n, failed)
            continue
        }
        sort.Slice(ds, func(i, j int) bool { return ds[i] < ds[j] })
        fmt.Printf("latency batch=%d median=%.1fms min=%.1fms max=%.1fms\n", n, ms(ds[2]), ms(ds[0]), ms(ds[4]))
    }
    // Documents.
    texts := make([]string, len(paras))
    for i, p := range paras {
        texts[i] = embedding.Document(p.Text)
    }
    t0 := time.Now()
    vecs, err := e.Embed(ctx, texts)
    if err != nil {
        return err
    }
    fmt.Printf("documents: %d vectors of %d in %s\n", len(vecs), len(vecs[0]), time.Since(t0).Round(time.Millisecond))
    if err := os.MkdirAll(*out, 0o755); err != nil {
        return err
    }
    if err := writeF16(filepath.Join(*out, "iliad-vectors.f16"), vecs); err != nil {
        return err
    }
    // Queries.
    qtexts := make([]string, len(qs))
    for i, q := range qs {
        qtexts[i] = embedding.Query(qh.Instruction, q.Text)
    }
    qvecs, err := e.Embed(ctx, qtexts)
    if err != nil {
        return err
    }
    if err := writeF16(filepath.Join(*out, "iliad-query-vectors.f16"), qvecs); err != nil {
        return err
    }
    fmt.Printf("queries: %d vectors\n", len(qvecs))
    // Fingerprint: three documents and three queries as probes.
    probes := []string{texts[0], texts[1], texts[2], qtexts[0], qtexts[1], qtexts[2]}
    fp, err := embedding.Capture(ctx, e, *model, "Qwen3-Embedding-0.6B", "last", "l2", probes)
    if err != nil {
        return err
    }
    raw, _ := json.MarshalIndent(fp, "", " ")
    if err := os.WriteFile(filepath.Join(*out, "iliad-fingerprint.json"), append(raw, '\n'), 0o644); err != nil {
        return err
    }
    fmt.Printf("fingerprint: dim=%d threshold=%.6f (min(0.999, worst repeat cosine - 0.0005))\n", fp.Dim, fp.Threshold)
    // What float16 cost: the worst self-cosine of a vector with its rounding.
    worst := 1.0
    for _, v := range vecs {
        r := make([]float32, len(v))
        for j, x := range v {
            r[j] = vecdb.F16Float(vecdb.F16Bits(x))
        }
        worst = math.Min(worst, embedding.Cosine(v, r))
    }
    fmt.Printf("float16: worst self-cosine 1 - %.3e\n", 1-worst)
    return nil
}

Its output on 2026-10-04 at 10:22 UTC, run on talos against dixie through the router at port 11434:

latency batch=1 median=31.2ms min=26.9ms max=151.5ms
latency batch=8 median=254.0ms min=227.8ms max=267.2ms
latency batch=32 median=1089.3ms min=1049.9ms max=1152.2ms
latency batch=128 median=4449.1ms min=4270.7ms max=4692.4ms
documents: 1018 vectors of 1024 in 43.678s
queries: 32 vectors
fingerprint: dim=1024 threshold=0.998552 (min(0.999, worst repeat cosine - 0.0005))
float16: worst self-cosine 1 - 2.584e-08

Latency. The batches are the first 1, 8, 32 and 128 paragraphs, which hold 362, 3,513, 18,486 and 73,599 bytes, so the medians per kilobyte of text are 86, 72, 59 and 60 ms (31.2 ms over 0.362 KB and so on). The cost per text of a batch is the wrong measure, since the batches’ texts differ in length. Per kilobyte it falls by about a third from one text to 32, which is a fixed cost per request being shared, and stops falling after that. So a batch of 128 is not faster per byte than 32, and 32 is not at a cliff. A request of 128 paragraphs completed in one request, 73,599 bytes of English, about 18,000 tokens at four bytes a token, four and a half times the slot’s 4,096-token unified cache, so the cache is not a limit on the request size; this chapter does not look inside the server to say why. DefaultMaxBatch = 32 is a choice of how much one failed request or one guard check covers, and the code’s comment says so. The batch-1 maximum, 151.5 ms, is one slow repeat of five. All 1,018 documents took 43.7 s, 42.9 ms per paragraph, or 59 ms per kilobyte. An earlier run of the same command, 99 seconds before, printed medians of 28.9, 237.0, 1068.9 and 4546.4 ms (80, 67, 58 and 62 ms per kilobyte), and every other line of the output above identically.

Two captures. That earlier run wrote its own copy of the three vector and fingerprint files. cmp finds them byte-identical to the committed ones. The batches were the same in both runs (32 texts per request, the same order), and the server returned the same bits for them. That is what was observed, not a property to rely on: chapter 21 measured vectors moving by about 10−310^{-3} when the neighbours in a batch change, and the live check below shows that a query embedded alone differs from its copy in the committed file by 5.6×10−45.6 \times 10^{-4} in cosine.

The threshold. 0.998552=cworst−0.00050.998552 = c_{\text{worst}} - 0.0005 gives cworst=0.999052c_{\text{worst}} = 0.999052 across the three repeat measurements of the six probes, which are paragraphs and instructed queries. Chapter 21’s 0.998618 was measured on short sentences from talos through the tether port and is a different set of probes. The threshold sits 1.4×10−31.4 \times 10^{-3} below 1, and the same margin applies to every Check the store does at open.

float16. The worst of the 1,018 self-cosines is 1−2.584×10−81 - 2.584 \times 10^{-8}. The bound derived above is 1.193×10−71.193 \times 10^{-7}, so the worst measured loss is 4.6 times smaller. The bound assumes every component is wrong by its maximum and the errors point away from vv; real rounding errors are signed and nearly independent, so ∥e⊥∥2\lVert e_\perp \rVert^2 is about the sum of 1,024 squared errors of typical size, not the square of their maximum. The committed vectors’ norms are within [0.999960, 1.000045][0.999960,\ 1.000045], against the bound 4.9×10−44.9 \times 10^{-4}, and 1,753 of the 1,042,432 components (0.17%) are below 2−142^{-14}, the smallest nonzero being 2−242^{-24}, binary16’s smallest subnormal.

The fixture is five files: the paragraphs with their header, the document vectors (2,084,864 bytes, the 1,018 × 1,024 × 2 of the float16 section), the 32 questions with the instruction in the header, their vectors (65,536 bytes), and the fingerprint (109,177 bytes, mostly six 1,024-float probes in decimal text). The queries are written in Butler’s names for the gods, because his text says Jove, Juno, Venus, Vulcan, Neptune and Ulysses, and a question about Zeus would test the embedder’s mythology and not the search.

The search. TestFixtureSearch loads the fixture into Flat with cosine, runs all 32 queries for the top five, and compares each with the reference. It logs the first three. On talos (identical ids and scores on straylight):

=== RUN   TestFixtureSearch
    lab_test.go:311: q01 "Why is Achilles angry with Agamemnon?"
    lab_test.go:317:   1  0.7709  p0748  book 18  Then said Achilles in his great grief, “I would die here and now, in that I could not save my comrade. He has fallen f…
    lab_test.go:317:   2  0.7453  p0014  book 1  Then Agamemnon said, “Achilles, valiant though you be, you shall not thus outwit me. You shall not overreach and you s…
    lab_test.go:317:   3  0.7425  p0076  book 2  And Agamemnon answered, “Nestor, you have again outdone the sons of the Achaeans in counsel. Would, by Father Jove, Mi…
    lab_test.go:317:   4  0.7350  p0069  book 2  “Agamemnon,” he cried, “what ails you now, and what more do you want? Your tents are filled with bronze and with f…
    lab_test.go:317:   5  0.7346  p0022  book 1  “Of a truth,” he said, “a great sorrow has befallen the Achaean land. Surely Priam with his sons would rejoice, an…
    lab_test.go:311: q02 "Who is Chryses and what does he ask of the Achaeans?"
    lab_test.go:317:   1  0.7225  p0031  book 1  Achilles drew a deep sigh and said, “You know it; why tell you what you know well already? We went to Thebe the strong…
    lab_test.go:317:   2  0.7022  p0001  book 1  And which of the gods was it that set them on to quarrel? It was the son of Jove and Leto; for he was angry with the kin…
    lab_test.go:317:   3  0.6631  p0032  book 1  “On this the rest of the Achaeans with one voice were for respecting the priest and taking the ransom that he offered;…
    lab_test.go:317:   4  0.6561  p0036  book 1  So saying he gave the girl over to her father, who received her gladly, and they ranged the holy hecatomb all orderly ro…
    lab_test.go:317:   5  0.6545  p0014  book 1  Then Agamemnon said, “Achilles, valiant though you be, you shall not thus outwit me. You shall not overreach and you s…
    lab_test.go:311: q03 "How does Hector say farewell to Andromache and his son?"
    lab_test.go:317:   1  0.7778  p1013  book 24  On this the people stood asunder, and made a way for the waggon. When they had borne the body within the house they laid…
    lab_test.go:317:   2  0.7676  p0287  book 6  Then Hector left her, and forthwith was at his own house. He did not find Andromache, for she was on the wall with her c…
    lab_test.go:317:   3  0.6723  p0286  book 6  And Hector answered, “Bid me not be seated, Helen, for all the goodwill you bear me. I cannot stay. I am in haste to h…
    lab_test.go:317:   4  0.6632  p0290  book 6  He stretched his arms towards his child, but the boy cried and nestled in his nurse’s bosom, scared at the sight of hi…
    lab_test.go:317:   5  0.6609  p0900  book 22  Then Hector said, as the life ebbed out of him, “I pray you by your life and knees, and by your parents, let not dogs …
--- PASS: TestFixtureSearch (0.13s)

Each hit is judged by reading it.

q01. The top hit is Achilles in Book 18, in grief for Patroclus: “Even so has Agamemnon angered me. And yet—so be it, for it is over”. It names the anger and the king, and it answers a different question: the quarrel is behind him. The cause is in rank 2, p0014, Agamemnon’s reply in Book 1: “Are you to keep your own prize, while I sit tamely under my loss and give up the girl at your bidding? … or I will come and take your own”. Rank 2 is the answer; rank 1 is the passage that best matches the question’s words.

q02. The top hit answers it. p0031 is Achilles telling Thetis the story: “Chryses, priest of Apollo, came to the ships of the Achaeans to free his daughter, and brought with him a great ransom … and he besought the Achaeans”. Rank 2, p0001, is the narrator’s version of the same sentences, so the two highest scores belong to the two tellings of one event.

q03. The top hit does not answer it. p1013 is Andromache’s lament over Hector’s body in Book 24: it matches Hector, Andromache and the child, and it is not a farewell. The farewell is Book 6: p0287 (rank 2) is Hector looking for her, p0290 (rank 4) is Hector taking his son and praying over him, and the speech in which he tells her he must fight, p0289, is at rank 8 with score 0.6405; its neighbour p0288, a servant’s reply, is at rank 303 (a script over the committed vectors). Exact search ranked the question’s topic correctly and the passage that answers it eighth.

That is the property to carry into chapter 35: an embedding finds what a passage is about, not whether it contains the answer, and the top hit is the best-scoring neighbour of the question, not the answer to it. Chapter 33’s index can only match these lists, never improve on them; how good they are is set by this embedder, these texts and this template.

The last step is the live check, AEC_LIVE=dixie go -C go test -count=1 -run TestLive -v ./labs/ch32. It reads /v1/models naming no model, skips unless honcho-embed is loaded, then runs the fixture’s Fingerprint.Check through the guarded client and embeds q01 again. Run on talos against dixie, 2026-10-04 at about 10:59 UTC:

=== RUN   TestLive
    lab_test.go:548: dixie honcho-embed: fingerprint check passed in 243ms (threshold 0.998552)
    lab_test.go:553: q01 re-embedded: cosine with the committed (float16) vector 0.999438
--- PASS: TestLive (0.32s)

The fixture and the live embedder agree. The re-embedded query, alone in its batch, is 5.6×10−45.6 \times 10^{-4} from its committed copy, which sat in a batch of 32 queries and was then rounded to float16 (a loss under 10−710^{-7} by the bound above), inside the 1.4×10−31.4 \times 10^{-3} the threshold allows. A failure here would mean the embedder changed since the capture, which is the schema change chapter 34 is about, and the repair is chapter 34’s, not a recapture.

Exercises

(a) Give three vectors q,a,b∈R2q, a, b \in \mathbb{R}^2 for which cosine and Euclidean distance rank a pair of candidates differently, and say which assumption of the Mechanism they violate.

Answer

Take q=(1,0)q = (1, 0), a=(10,0)a = (10, 0) and b=(0.9,0.1)b = (0.9, 0.1). The cosines are cos(q,a)=1\cos(q, a) = 1 and cos(q,b)=0.9/0.82=0.994\cos(q, b) = 0.9/\sqrt{0.82} = 0.994, so cosine prefers a. The distances are ∥q−a∥=9\lVert q - a \rVert = 9 and ∥q−b∥=0.02=0.141\lVert q - b \rVert = \sqrt{0.02} = 0.141, so Euclidean distance prefers b. The unit-sphere assumption fails: a has norm 10, and ∥q−v∥2=2−2q⋅v\lVert q - v \rVert^2 = 2 - 2\, q \cdot v needs ∥v∥=1\lVert v \rVert = 1.

(b) Why is the heap a min-heap when the search wants the largest scores, and what does Search cost when k=nk = n?

Answer

The element to evict when a better row arrives is the worst one kept, so the worst kept hit must be at the root, where it is read in constant time; a max-heap would put the best there and make eviction a search. With k=nk = n every row is pushed and sifts up at O(logn)O(\log n), and no row replaces the root, so the scan is O(nlogn)O(n \log n) comparisons on top of the ndn d multiply-adds, which is a sort. Search still returns the right order, because it drains the heap from the root: the worst is popped first and written at the end of the result.

(c) A filter accepts one row in a thousand. How much work does Flat.Search save, and what would save more?

Answer

It saves the scoring of 999 rows in 1,000, which is almost all of the multiply-adds, and none of the scan: every row is still visited and its filter called. From the two timings above, an unfiltered search over 1,018 rows took 418,142 ns, about 411 ns per scored row; the book 6 search scored 33 rows (about 13,600 ns) and took 46,265 ns, so the 1,018 filter calls cost about 32,700 ns, about 32 ns each. A 1-in-1,000 filter would therefore cost nearly the same 32,700 ns, about thirteen times faster than the unfiltered search and no better. To go below the scan, the exact index needs a way to find the accepted rows without visiting the rest: a posting list per metadata key. Chapter 33’s HNSW applies the filter during the traversal of layer 0 instead.

(d) Three records tie at the same score and k=2k = 2, with no ID rule. List the valid answers of Search, and the recall an approximate index would score against each.

Answer

Any two of the three: {1,2}\{1,2\}, {1,3}\{1,3\} and {2,3}\{2,3\} are all valid top-2 sets. An approximate index that returned {1,2}\{1,2\} would score recall 1 against an exact index that chose {1,2}\{1,2\} and 0.5 against one that chose {1,3}\{1,3\} or {2,3}\{2,3\}, because it shares exactly one id with those. The same output scores differently depending on a choice the data does not determine. The (score, ID) order picks one set once and for all, so recall becomes a function of the data and the query.

(e) Which of the pooling incident’s symptoms does Equal see, and which does Check see?

Answer

Equal sees none. The alias, the model name, the width, the pooling string and the normalisation in a fingerprint are what the capturer wrote down, and none of them changed when the server’s --pooling flag did. Check sees it, because it compares vectors. Under cls the three instructed query probes begin with the same first token, Instruct, and so come back as one vector uu (chapter 21’s first consequence). If two of them, cic_i and cjc_j, passed against their captured vectors, each would lie within the angle arccos(0.998552)=0.0538\arccos(0.998552) = 0.0538 rad of uu, so by the triangle inequality for angles on the sphere ∠(ci,cj)≤0.1077\angle(c_i, c_j) \le 0.1077 rad and cos(ci,cj)≥0.9942\cos(c_i, c_j) \ge 0.9942. The captured query probes’ pairwise cosines are 0.542, 0.497 and 0.397 (a script over the committed fingerprint, talos), so at most one of the three passes, and Check fails. A store therefore runs both at open: Equal is a free comparison that catches a deliberate change, and Check costs one embedding batch and catches the one that nobody announced.

(f) Derive the 2e-3 tolerance of TestCorpusPinned’s norm check from the float16 bound, and say what a component below 2−142^{-14} does to it.

Answer

The Mechanism’s norm interval is [0.999512, 1.000488][0.999512,\ 1.000488], within 2−11=4.9×10−42^{-11} = 4.9 \times 10^{-4} of 1. The test allows 2e-3, about four times that, so it also absorbs the digits the server prints and any slack in the unit length it returned. The committed vectors lie in [0.999960, 1.000045][0.999960,\ 1.000045], eleven times inside the bound, since 1,024 signed errors average out. A component with ∣xi∣<2−14\lvert x_i \rvert < 2^{-14} has absolute error at most 2−252^{-25} and changes its square by less than 2−38+2−502^{-38} + 2^{-50}; summed over at most 1,024 such components it moves ∥v′∥2\lVert v' \rVert^2 by less than 2−282^{-28}, negligible against the 2−102^{-10} the normal components allow.

Lab

go/labs/ch32 declares Impl{NewFlat, Recall}; you write mine/flat.go, the exact index and recall@k, and run

make lab CH=32 IMPL=mine

Provided: the embedder, the fixture and LoadFixture, vecdb.Match, and the metric arithmetic’s types. The tests pin: hits and scores against an independent brute force under all three metrics; ties by ID; the filter before scoring, including a filter that rejects everything; replace and delete; the recall definition, with the cut; the fixture’s header rules and vector norms; equality of your search with the reference’s over the 32 queries; the fingerprint’s refusals on a stand-in embedder; no secrets in the fixture, and that the scan itself catches each credential shape planted in a copy; and, under AEC_LIVE=dixie, the fixture’s fingerprint against the live embedder. Ten tests run offline, and the reference passes them (ok aec/labs/ch32). Against the starter, six fail: TestExactMatchesBruteForce, TestTiesBrokenByID, TestFilterBeforeScoring, TestDeleteAndReplace, TestRecallDefinition and TestFixtureSearch; TestCorpusPinned, TestFingerprintRefuses, TestNoSecretsInTestdata and TestSecretScanCatchesPlants pass. The tests never contact the fleet.

Further reading

results matching ""

    No results matching ""