Back to Cloudflare

Build Grounded Retrieval With Vectorize and AI Search

November 5, 2026 Wasil Zafar 31 min read

Compare a custom retrieval pipeline with managed search

Table of Contents

  1. Retrieval Starts With Content and Access Boundaries
  2. Vectorize Supports a Custom Embedding Search Path
  3. AI Search and Web Search Serve Different Sources
  4. Grounding, Freshness, and Retrieval Evaluation
  5. Design a Search Assistant Over a Small Document Set
  6. Measure Retrieval Quality and Test Cross-Tenant Exclusion

Retrieval Starts With Content and Access Boundaries

A support lead types "why was I charged a proration credit?" into an internal search box. The help centre has the answer, but the page is titled "Mid-cycle plan changes and billing adjustments." Keyword search returns nothing; a human would have found it instantly. This gap between the words a user types and the words a document uses is the problem embeddings exist to close.

An embedding is a fixed-length list of floating-point numbers produced by a model. With @cf/baai/bge-base-en-v1.5, the list has 768 values (model card). The values are not a summary, a hash, or a reversible encoding. They are coordinates, and the model places texts with similar meaning near each other.

A chunk is the unit you embed: usually a few hundred tokens of a document, with a little overlap so a sentence split across a boundary still appears whole somewhere. An index is the structure that answers "which stored vectors are nearest this query vector?" quickly. Top-K is how many candidates you ask for. Reranking is a second, slower model that scores each query-and-chunk pair and reorders the shortlist. Grounding means the generated answer is built from those chunks rather than from the model's memory.

The useful analogy is a library with a meaning shelf. Instead of looking up a title, you hand the librarian your question, they walk to the coordinate your question maps to, and they bring back the nearby paragraphs. That works only if the library has two properties: the books were shelved with the same coordinate system you are using now, and the librarian checks which reading room you are allowed to enter before fetching anything.

That second property is the part teams underestimate. A retrieval system has two boundaries. The data boundary decides which documents a caller may see: tenant, role, workspace, region. The context boundary decides how much text reaches the model: Top-K times chunk size, plus the question and the answer budget. Figure 1 traces both, and shows where each can fail.

Retrieval Starts With Content and Access Boundaries
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','titleColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
    S["Sources: R2 objects, D1 rows, CMS pages"] --> P["Parse to plain text"]
    P --> C["Chunk: 300-600 tokens
10-15 percent overlap"] C --> E["Embed with one pinned model"] E --> I["Vectorize index
fixed width, fixed metric"] I --> M["Metadata: tenant_id, doc_id, version, url"] Q["User question"] --> QE["Embed with the same model"] QE --> F{"Tenant resolved from
verified session?"} F -->|"no"| X["Fail closed
never query"] F -->|"yes"| R["Query: namespace + filter
applied before topK"] M --> R R --> RR["Optional rerank"] RR --> CTX["Context budget
topK x chunk tokens"] CTX --> G["Generate from chunks only"] G --> CIT["Citations to chunk ids"] R -->|"empty filtered set"| N["Refuse or ask a
clarifying question"] classDef primary fill:#132440,color:#ffffff,stroke:#0b172b; classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a; classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f; classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420; classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f; class C,CTX primary; class S,P,E,I,M,Q,QE,R,RR,G,CIT,N secondary; class F ok; class X danger;
Content, index, and access layers in a retrieval pipeline Documents are parsed and chunked, each chunk is embedded, and vectors are stored in a Vectorize index partitioned by namespace and metadata. A query is embedded with the same model. The tenant boundary is enforced by a namespace and metadata filter before Top-K selection, and a separate context boundary limits how many chunks reach the generation model. Content layer R2 objects D1 rows Website pages Uploaded files Chunk store chunk_id = doc#n text, url, version 300-600 tokens each Embedding model, pinned bge-base-en-v1.5, 768 values changing it invalidates every vector model + chunker form one version Index layer Vectorize index: fixed dimensions, fixed metric namespace tenant-a tenant_id = a metadata: url, version namespace tenant-b tenant_id = b same index, separate rows Query path 1. embed the question with the same model 2. apply namespace, then metadata filter 3. take topK from the filtered set 4. hydrate text, rerank, then generate Two boundaries that must not move Access: namespace and tenant filter run before Top-K, not after generation. Context: Top-K x chunk tokens plus question plus answer must fit the model window.

Figure 2 separates the layers that teams blur together. The content layer owns parsing and chunking; the index layer owns distance and filtering; the query path owns ordering. A change in any layer invalidates assumptions in the next one, which is why "we changed the embedding model" is a migration, not a deploy.

The first design decision is therefore not which vector database to use. It is what a citable unit of content is, and who is allowed to see it.

Vectorize Supports a Custom Embedding Search Path

Vectorize is a vector database. You create an index with a fixed dimension count and distance metric, insert vectors with ids, optional namespaces, and up to 10 KiB of metadata, then query with a vector and get scored ids back (Vectorize API). It does not parse PDFs, choose chunk boundaries, call a generation model, produce citations, or notice that a source document changed. Those are your jobs.

AI Search is the managed path. You connect a website, an R2 bucket, or uploaded files; it converts content to Markdown, chunks recursively, embeds each chunk, optionally builds a BM25 keyword index, syncs changes, and serves search or chat with the source chunks attached (How AI Search works). It uses Vectorize for its vector index, but the boundary you interact with is an instance, not an index.

Web Search API is a different product category. It does not index your content at all. It sends a query to a third-party web index through AI Gateway and returns titles, URLs, and descriptions you can place in a model's context (Web Search API). It is in open beta and currently offers Ceramic.ai, Exa, and Linkup as providers (providers).

A worked comparison makes the choice concrete. A team has 4,200 help-centre articles across three customer tenants. Answers must cite the article version that was current when the ticket was written, code blocks must survive chunking intact, and tenant A must never see tenant B.

What changes for this teamAI Search pathVectorize path
IsolationOne instance per tenant, with an R2 bucket eachOne index, namespace plus a short tenant filter
Chunk integrityService chunk size and overlap; a fence is not guaranteed wholeA Markdown-aware chunker keeps fences and tables whole
CitationsReturned chunks rendered as-isDeterministic ids mapped to source rows
Time to first answerRoughly a day, plus an evaluation passOne to two weeks, including evaluation

Web Search is the wrong tool for this corpus. It fits questions such as "what changed in this vendor's API this week?", not internal policy documents.

DecisionVectorizeAI SearchWeb Search API
What it isVector index with nearest-neighbour query, namespaces, and metadata filtersManaged indexing and retrieval service with search and chat endpointsQuery API over third-party public web indexes
Content you can searchAnything you chunk and embed yourselfWebsites you own, R2 buckets, or files uploaded to built-in storageThe public web, as indexed by the chosen provider
Who chunks and embedsYou, with full control over boundaries and overlapThe service, with configurable chunk size and overlapNobody; there is no index of yours
Retrieval controlstopK, namespace, metadata filter, optional rerank you implementVector, keyword, or hybrid; match_threshold; max_num_results; reranking; query rewritingQuery text, provider, and limit from 1 to 10
Tenant isolationNamespace plus metadata filter, or separate indexesSeparate instance per tenant, or shared instance with filtersNot applicable; results are public web pages
Freshness clockYour ingestion pipeline, then asynchronous index writesSync interval from 15 minutes to 24 hours, or immediate for built-in storageProvider crawl freshness, outside your control
CitationsYou map ids to source rows and render themChunks include item.key, timestamp, metadata, and scoreResult URLs and descriptions only
Operational burdenHighest: ingestion, backfill, deletion, evaluationLowest: connect a source, tune retrieval, evaluateLowest: one API call, but no control over corpus
Availability and cost shapeGenerally available; billed on stored and queried vector dimensionsAvailable on all plans; plan-based limits; usage billing starts 2026-12-01Open beta; billed per search at provider list price

The table's cost row is deliberately a shape, not a number, because all three products changed pricing or billing status in 2026. Read the current pages before committing.

Figure 3 shows the custom path as a sequence, including the three failures that account for most incidents: a model mismatch, a filter the index cannot serve, and a filter that matches nothing.

Vectorize Supports a Custom Embedding Search Path
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
sequenceDiagram
    autonumber
    participant U as User
    participant W as Worker
    participant AI as Workers AI
    participant V as Vectorize
    participant G as Generation model
    U->>W: question plus session cookie
    W->>W: resolve tenant_id from session
    W->>AI: embed question
    alt index expects 768 values, model returns another width
        AI-->>W: vector of the wrong size
        W-->>U: 500 embedding dimension mismatch
    else model matches the index
        AI-->>W: 768-value vector
        W->>V: query topK, namespace, filter tenant_id
        alt metadata index was never created
            V-->>W: filter error
            W-->>U: 500 filter not indexed
        else filter matches no vectors
            V-->>W: empty matches
            W-->>U: no sources found, ask a narrower question
        else matches returned
            V-->>W: scored ids and metadata
            W->>G: chunks plus question
            G-->>W: answer with chunk citations
            W-->>U: answer plus source links
        end
    end

Debug in this order

Figure 3 is also a debugging order. Check the vector width first, then whether the filter field has a metadata index, then whether the filter is too narrow. Those three checks explain most "the vector database is broken" reports before anyone looks at the model.

Two surfaces make the path runnable. The bindings live in Wrangler config, and the index plus its metadata fields must exist before the first upsert. Neither binding can run against a local simulation, so both declare remote.

{
  "$schema": "node_modules/wrangler/config-schema.json",
  "name": "grounded-retrieval",
  "main": "src/index.ts",
  "compatibility_date": "2026-11-05",
  "ai": {
    "binding": "AI",
    "remote": true
  },
  "vectorize": [
    {
      "binding": "DOCS",
      "index_name": "docs-lab-<initials>",
      "remote": true
    }
  ]
}

The Worker itself does four things. It resolves the tenant, chunks on a boundary it controls, embeds with one pinned model, and queries with namespace and filter applied before Top-K.

interface Env {
  AI: Ai;
  DOCS: VectorizeIndex;
}

interface Doc {
  id: string;
  url: string;
  text: string;
}

const MODEL = "@cf/baai/bge-base-en-v1.5";
const EMBED_BATCH = 16;

// Character-based chunking keeps the example dependency-free. Production code
// should chunk on token counts and respect headings, tables, and code fences.
function chunkText(text: string, size = 1200, overlap = 180): string[] {
  const clean = text.replace(/\s+/g, " ").trim();
  if (clean.length <= size) return clean ? [clean] : [];
  const chunks: string[] = [];
  let start = 0;
  while (start < clean.length) {
    const end = Math.min(start + size, clean.length);
    chunks.push(clean.slice(start, end));
    if (end === clean.length) break;
    start = end - overlap;
  }
  return chunks;
}

async function embed(env: Env, texts: string[]): Promise<number[][]> {
  const vectors: number[][] = [];
  for (let i = 0; i < texts.length; i += EMBED_BATCH) {
    const batch = texts.slice(i, i + EMBED_BATCH);
    const response = await env.AI.run(MODEL, { text: batch });
    vectors.push(...response.data);
  }
  return vectors;
}

export default {
  async fetch(request: Request, env: Env): Promise<Response> {
    const url = new URL(request.url);

    if (request.method === "POST" && url.pathname === "/reindex") {
      // Replace this with your real session check. Never trust a tenant
      // identifier supplied in the request body in production.
      const tenant = request.headers.get("x-tenant-id") ?? "";
      if (!/^[a-z0-9-]{1,32}$/.test(tenant)) {
        return Response.json({ error: "invalid tenant" }, { status: 401 });
      }

      const body = (await request.json()) as { docs: Doc[] };
      const chunks = body.docs.flatMap((doc) =>
        chunkText(doc.text).map((text, index) => ({
          id: `${doc.id}#${index}`,
          tenant,
          docId: doc.id,
          url: doc.url,
          version: Date.now(),
          text,
        })),
      );

      const vectors = await embed(env, chunks.map((chunk) => chunk.text));
      const records = chunks.map((chunk, index) => ({
        id: chunk.id,
        values: vectors[index],
        namespace: chunk.tenant,
        metadata: {
          tenant_id: chunk.tenant,
          doc_id: chunk.docId,
          url: chunk.url,
          version: chunk.version,
          text: chunk.text,
        },
      }));

      // Upsert replaces a vector with the same id in full. It does not remove
      // ids that no longer exist, so delete the old id range before reindexing
      // a document whose chunk count can shrink.
      await env.DOCS.upsert(records);
      return Response.json({ tenant, chunks: records.length });
    }

    if (request.method === "GET" && url.pathname === "/search") {
      const tenant = request.headers.get("x-tenant-id") ?? "";
      const question = url.searchParams.get("q") ?? "";
      if (!tenant || !question) {
        return Response.json({ error: "tenant and q are required" }, { status: 400 });
      }

      const [queryVector] = await embed(env, [question]);
      const result = await env.DOCS.query(queryVector, {
        topK: 5,
        namespace: tenant,
        returnMetadata: "all",
        filter: { tenant_id: tenant },
      });

      return Response.json({
        matches: result.matches.map((match) => ({
          id: match.id,
          score: match.score,
          url: match.metadata?.url,
          text: match.metadata?.text,
        })),
      });
    }

    return new Response("Not found", { status: 404 });
  },
};

The TypeScript panel is the smallest complete custom path: tenant from a header, deterministic chunk ids, one pinned embedding model, namespace plus metadata filter, and returnMetadata: "all" so the caller can render a citation without a second lookup. Storing chunk text in metadata is convenient here and acceptable at 1,200 characters; at production scale it consumes the 10 KiB per-vector budget, so store the text in D1 or R2 and keep only the pointer in metadata. The two comments about authentication and stale ids are the parts readers most often delete.

Vectorize is generally available, but the plan surface still matters. As of 2026-11-05, the Free plan includes 100 indexes, 30 million queried dimensions per month, and 5 million stored dimensions, with 1,000 namespaces per index; the Paid plan raises indexes to a default of 50,000 and namespaces to 50,000, includes 50 million queried dimensions, and charges $0.01 per million queried dimensions and $0.05 per 100 million stored dimensions (limits, pricing). A single index holds up to 20 million vectors at up to 1,536 dimensions. Do not read those numbers as a capacity promise for your workload; read them as the point where you need a second index or a smaller embedding.

AI Search and Web Search Serve Different Sources

The distinction that matters is where the bytes come from. AI Search searches a corpus you connected: a website you own, an R2 bucket, or files you uploaded. Web Search searches the public internet through a provider. Neither is a superset of the other, and a grounded assistant over internal policy should not be pointed at the open web without a clear product reason.

Tenant isolation in AI Search has two documented shapes (Multitenancy). An instance per tenant gives each tenant separate storage and a separate index. It is the recommended shape when isolation is a hard requirement or tenants are created at runtime, and it is bounded by the instances-per-account limit: 100 on Workers Free, 5,000 by default on Paid. A shared instance with metadata filtering is simpler for many small tenants, but every write must carry the tenant attribute and every query must filter on it. The filter is applied before retrieval, so it reduces the candidate set rather than trimming results afterward (Filtering).

A filter is not an access control

Filters match only the first 64 UTF-8 bytes of an indexed string, in both AI Search and Vectorize, so use a short opaque tenant id rather than a signed ACL blob; AI Search also caps custom metadata at five fields per instance and re-indexes when that schema changes (Metadata attributes). A filter is not an authorization system: it can only be trusted if the tenant id came from a verified session, and applying it after Top-K means you paid to search data you should never have touched.

Deletion has a clock. items.delete() removes an item and its indexed chunks immediately from the API's perspective (Items API). For external sources, a sync job processes new, modified, and deleted files, and the default interval is 24 hours; you can lower it to 15 minutes or trigger a job from a publish hook, at most once every 30 seconds (Syncing). Built-in storage has no sync jobs and indexes files as they are uploaded. If a deleted document must disappear within seconds, delete the item explicitly and keep a tombstone in D1 that the Worker checks before generation.

A citation must resolve to a chunk

AI Search returns chunks[], each with an item key, a timestamp, custom metadata, and a score; grouping repeated chunk ids by item key yields one citation per document (Chunk citations). Cite the retrieved version, not whatever the URL serves today, because a page can change between retrieval and the user clicking the link. A citation that cannot be resolved back to a chunk id in the response is decoration.

Web Search returns result URLs and descriptions, with a limit between 1 and 10 and a query capped at 1,024 characters (How to use). Its freshness is the provider's crawl freshness, and its retention terms vary by provider: Ceramic.ai and Linkup state zero data retention, Exa does not (providers). That difference is a procurement question, not a footnote.

Grounding, Freshness, and Retrieval Evaluation

Grounding is an invariant, not a prompt instruction. Every factual sentence in the answer must map to a chunk id that was in the retrieved set, and the response must expose that mapping.

Check grounding mechanically

A model asked to "only use the context" will still occasionally blend in priors, especially when the retrieved chunks are thin. Parse the answer's citation markers, verify each id exists in the response's returned chunks, and reject or regenerate answers with unsupported claims.

A second grounding failure is quieter: the right chunk is retrieved, then crowded out of the model's window.

The context window is a budget

AI Search defaults to 10 results, accepts 1 to 50, and can expand each hit with 0 to 3 neighbouring chunks (Workers binding). Ten chunks of 600 tokens plus three neighbours each is already 24,000 tokens before the question and the answer, which does not fit an 8K model, and the failure looks like truncated or ignored context rather than an error. Either raise the model's window, lower max_num_results, or lower chunk size; choose deliberately and record the arithmetic.

Freshness is three separate clocks. The source clock is how long after a document changes the pipeline notices. The index clock is how long after a write the vector is queryable. The model clock is how long your embeddings remain comparable to the query model.

AI Search handles the first two with sync jobs and, for built-in storage, immediate indexing. Vectorize handles the second asynchronously: the API documents inserts and deletes as eventually visible within seconds, and a June 2026 changelog reports median end-to-end visibility under 30 seconds and p99 under 2 minutes after a write-ahead-log improvement (changelog). Those are vendor-reported figures, not a guarantee for your index size.

The model clock is the one teams forget. If you change the embedding model, or move chunk boundaries enough that old and new chunks no longer align, old vectors and new query vectors stop sharing a coordinate system. Cosine similarity between vectors from two different models is a number, but it is not meaning, and dimensions may differ too: 768 for the base model, 1,024 for the large one. Because dimension and metric are fixed at index creation, re-embedding is a new index, not an update (Create indexes).

Treat the swap as a release:

  1. Create docs-v2 with the new model's dimension count and metric.
  2. Dual-write new chunks, then backfill the corpus.
  3. Evaluate against the golden set.
  4. Switch the binding and keep docs-v1 for rollback.
  5. Delete the old index after the retention window.
Stale index and versioned index failure paths In the stale path, a document is edited but the index still holds old vectors, so retrieval returns the old chunk and the model answers confidently with a citation to superseded content. In the versioned path, the new index is built and evaluated before the binding switches, and the answer either cites the current version or refuses when no current chunk clears the threshold. Stale index: no version boundary Doc edited v2 published Index still holds v1 vectors Answer cites v1 with a high score Confident, plausible, superseded Versioned index: explicit boundary and gate Doc edited v2 published Reindex into docs-v2 backfill, then evaluate Eval gate recall and citations Switch binding keep v1 for rollback What the gate checks Recall@5 on the golden set, citation ids that resolve to returned chunks, and a refusal path when no current chunk clears the threshold. A recall drop or a citation to a superseded document blocks the switch. Freshness is source-to-queryable time, not a sync job in a dashboard.

Figure 4 contrasts the two postures. The upper lane is the common failure: the document changed, the index did not, and the system confidently cites a superseded version. The lower lane treats reindexing as a release with a gate. The gate is not ceremonial; it is the only place where a retrieval regression is visible before users see it.

Evaluation needs a held-out golden set. Fifty to one hundred questions is enough to start, and each row should contain the question, the tenant, the expected document ids, and an acceptable-answer note.

Measure retrieval and generation separately. Recall@k asks whether the right document was in the top k; MRR asks how high it ranked; citation precision asks whether cited ids match retrieved chunks; refusal accuracy asks whether the system declines when nothing supports an answer; and cross-tenant leak rate asks how often another tenant's chunk appears. A single end-to-end "looks good" judgement cannot tell you whether to change the chunker or the prompt.

Design a Search Assistant Over a Small Document Set

The exercise builds the custom path from Figure 3 over twelve short Markdown documents across three tenants. It is deliberately small enough to reason about every chunk by hand, which is what makes retrieval failures visible.

Create the index and its metadata fields before the first upsert. Dimensions and metric are fixed at creation, and the three metadata fields are what the tenant, document, and version filters read. The last two commands run the Worker against remote bindings and remove the index when the exercise ends.

npx wrangler vectorize create docs-lab-<initials> --dimensions=768 --metric=cosine

npx wrangler vectorize create-metadata-index docs-lab-<initials> --property-name=tenant_id --type=string
npx wrangler vectorize create-metadata-index docs-lab-<initials> --property-name=doc_id --type=string
npx wrangler vectorize create-metadata-index docs-lab-<initials> --property-name=version --type=string

npx wrangler dev

npx wrangler vectorize delete docs-lab-<initials>
Guided exercise

Design a Search Assistant Over a Small Document Set

Status: design-only. Not executed for this draft. No index was created, no Worker was deployed, and no query was run. Expected observations below are documented behaviour and arithmetic, not measured results.

Prerequisites and plan requirements. A Cloudflare account with Workers and Vectorize enabled, Node.js 20 or later, npm, and Wrangler 4. A Workers Free account is sufficient for the Vectorize volume in this exercise; Vectorize and Workers AI have no local simulation, so their bindings must set remote = true and run under wrangler dev (bindings per environment). AI Search is optional for comparison; its billing begins on 2026-12-01, so check the current pricing page before creating instances.

Inputs. The corpus, the question set, and the index name are chosen so that every failure is visible by hand.

InputValueWhat it exercises
Corpus12 Markdown files, 1 to 3 KB each, four per tenantSmall enough to inspect every chunk
Content shapesOne document with a fenced code block, one with a tableWhether chunking respects structure
Golden set24 questions, eight per tenantRetrieval and refusal measured separately
Question mixFour answerable, four unanswerable per tenantA refusal path, not just a happy path
Index namedocs-lab-<initials>Disposable and unique to the exercise
  1. Create the index and the three metadata fields with the Bash panel above, before any upsert. Vectors written before a metadata index exists are not indexed for filtering until they are written again (metadata filtering).
  2. Add the AI and DOCS bindings from the JSON panel, keep remote set on both, and deploy the Worker from the TypeScript panel. Upload the twelve documents through POST /reindex once per tenant, setting the tenant header explicitly.
  3. Query tenant A with one answerable question. Expect five matches or fewer, each with a score between 0 and 1 for cosine, and every url under tenant A's prefix. Expect the highest score to be visibly higher than the fourth and fifth, which is a signal that the chunker is producing distinguishable units.
  4. Query tenant B with the same question. Expect tenant B's documents, not tenant A's, even though the question text is identical.
  5. Send a query with x-tenant-id: tenant-a but a body or parameter naming tenant B. Expect tenant A results. This is the test that proves the tenant comes from the authenticated context.
  6. Delete one document with deleteByIds for its chunk ids, then query for a phrase unique to it. Expect it to disappear; per the June 2026 changelog, p99 visibility for a write is under two minutes, so poll rather than assuming instant removal.
  7. Reindex one document with a shorter chunk size into a second index docs-lab-v2, then run the same golden set against both. Compare recall@5 and the number of chunks per document. Do not switch the binding until v2 meets or beats v1.

Expected observations. A correctly scoped query returns only the caller's tenant, even when the question is identical across tenants. A filter that matches nothing returns an empty matches array, not an error, and topK can return fewer than five rows because the filter runs before Top-K.

Chunking shows up in the answer. The code-block document should retrieve as a coherent chunk if the chunker respects fences; a naive fixed-width splitter will cut it mid-block, and the answer will cite a fragment.

Failure checks. A VectorizeError about dimensions means the query vector width differs from the index; check the model id, not the query text. A filter error on tenant_id means the metadata index was never created or the vectors predate it. Zero results for a term that exists usually means the filter value was truncated or the tenant id casing differs; filter strings match only the first 64 UTF-8 bytes. A stale hit after deletion means you are inside the asynchronous window, not that deletion failed. A citation that points to a document the user cannot open means the retrieval filter and the application's authorization check disagree.

Cost dimensions. Twelve documents produce on the order of tens of chunks, well inside the Vectorize Free allowance of 5 million stored dimensions and 30 million queried dimensions per month. Embedding cost at bge-base-en-v1.5 list price is $0.0666 per million input tokens as of 2026-11-05, and this corpus is far below one million tokens. If you repeat the comparison with AI Search, its included monthly usage is 5 million ingestion tokens, 10 GB-month of storage, and 1,000 semantic plus 1,000 full-text queries, after which list rates apply (AI Search limits and pricing).

Cleanup. Delete the Workers and both indexes with npx wrangler vectorize delete docs-lab-<initials> and ... docs-lab-v2, remove the local fixtures and golden-set file, and revoke any API token created for the exercise. Confirm the indexes are gone before deleting the R2 bucket or D1 database used as the source of truth.

The exercise is intentionally front-loaded with exclusion tests. Steps 3 and 4 prove retrieval works; step 5 proves it fails closed. A demo that only shows the happy path has not tested tenancy.

Measure Retrieval Quality and Test Cross-Tenant Exclusion

Verification date: 2026-11-05. Basis: official Cloudflare documentation reviewed on that date; planning baseline 2026-11-02. Execution status: design-only. No Wrangler, curl, or Node command was run for this draft. Tested versions: none recorded.

Pass evidence. A correct implementation should produce all of the following:

  • Recall@5 at or above the threshold you set before tuning, measured on the held-out golden set, with the per-question results retained.
  • Zero chunks from another tenant across at least 20 adversarial queries that name a different tenant in the body, query string, or metadata filter.
  • Every cited id resolves to a chunk in the same response, and every cited document is still present at generation time.
  • A question with no supporting chunk returns a refusal or a clarifying question, not a fabricated answer.
  • After reindexing a changed document, queries return the new version and cite it; the old version is no longer retrievable.
  • After deletion and the async visibility window, the deleted document does not appear in results or citations.

Fail signatures. A cross-tenant chunk with a normal-looking score means the filter was applied after retrieval or the tenant id was taken from user input. A citation that 404s means the citation was rendered from a URL rather than from the retrieved chunk's stored version. A confident answer with no citation means grounding was a prompt instruction, not an invariant. A sudden recall drop after a "small" chunker change means the embedding model and the chunk boundaries drifted apart. An empty result set on a broad question usually means the filter is too narrow or match_threshold is above the score distribution.

Self-check. Answer before reading the explanations.

  1. Does a higher topK improve grounding? Not by itself. More candidates can add noise and consume the context budget. Grounding improves when the right chunk is retrieved and the model is required to cite it; past a point, extra chunks dilute attention and increase cost.
  2. Can you change the embedding model without re-embedding the corpus? No. Similarity is only meaningful within one model's coordinate space. A new model means a new index, a backfill, and an evaluation pass, because dimensions and metric are fixed at creation.
  3. Is a metadata filter an authorization control? No. It is a retrieval narrowing mechanism. Authorization must decide the tenant before the query, and the filter value must come from that decision.
  4. Does a 24-hour sync interval mean data is 24 hours stale? Not exactly. It is the default cadence for checking an external source; a change can be picked up sooner if you trigger a job, and built-in storage indexes on upload. The observable freshness is source-change-to-queryable time, which also includes processing and the index write.

Unresolved limitations. This draft did not execute the exercise, so no recall, latency, or cost was measured. The Vectorize visibility figures are vendor-reported from a June 2026 changelog and depend on index size and write volume. AI Search pricing begins on 2026-12-01 and the published rates may change; the free allowances are plan-dependent. Web Search API is in open beta, its provider lineup and retention terms can change, and its results are public-web results, not a private corpus. The chunker in the code widget is character-based and will split tables and code fences; it is a teaching example, not a production chunker. Filterable strings are truncated at 64 UTF-8 bytes in both Vectorize and AI Search, which limits how much tenancy or ACL information a filter can carry.

Authoritative references.

Next in the Series

In Build Agents With Explicit Tools and Durable State, we'll explore Coordinate model decisions, authorization, memory, and human review.