Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

Implement turbopuffer

Rafi94917d1b1641
diff --git a/apps/web/.env.example b/apps/web/.env.example
index 486c67880a..71c7d9f6c0 100644
--- a/apps/web/.env.example
+++ b/apps/web/.env.example
@@ -24,7 +24,7 @@ UPSTASH_REDIS_REST_URL=
UPSTASH_REDIS_REST_TOKEN=
# Full-text partner search
-# Supported values: upstash-redis, upstash-search
+# Supported values: upstash-redis, upstash-search, turbopuffer
PARTNER_SEARCH_PROVIDER=
PARTNER_SEARCH_INDEX_NAME=partner-search-v1
PARTNER_UPSTASH_SEARCH_INDEX_NAME=partner-search-v1
@@ -34,6 +34,10 @@ PARTNER_SEARCH_DEBUG=false
UPSTASH_SEARCH_REST_URL=
UPSTASH_SEARCH_REST_TOKEN=
+# Required when PARTNER_SEARCH_PROVIDER=turbopuffer
+TURBOPUFFER_API_KEY=
+TURBOPUFFER_REGION=aws-us-east-1
+
# Upstash QStash – required for queues and background jobs
# Get your QStash Token here: https://upstash.com/docs/qstash/overall/getstarted
QSTASH_URL="https://qstash-us-east-1.upstash.io"
diff --git a/apps/web/lib/api/partners/search/provider.ts b/apps/web/lib/api/partners/search/provider.ts
index 47a2bd01f1..0b71af6bb1 100644
--- a/apps/web/lib/api/partners/search/provider.ts
+++ b/apps/web/lib/api/partners/search/provider.ts
@@ -1,11 +1,30 @@
+import { createTurbopufferPartnerSearchProvider } from "./providers/turbopuffer";
import { createUpstashRedisPartnerSearchProvider } from "./providers/upstash-redis";
import { createUpstashSearchPartnerSearchProvider } from "./providers/upstash-search";
import type { PartnerSearchProvider } from "./types";
-let upstashRedisProvider: PartnerSearchProvider | null = null;
-let upstashSearchProvider: PartnerSearchProvider | null = null;
-
-export type PartnerSearchProviderName = "upstash-redis" | "upstash-search";
+const PARTNER_SEARCH_PROVIDER_NAMES = [
+ "upstash-redis",
+ "upstash-search",
+ "turbopuffer",
+] as const;
+
+export type PartnerSearchProviderName =
+ (typeof PARTNER_SEARCH_PROVIDER_NAMES)[number];
+
+const providerFactories: Record<
+ PartnerSearchProviderName,
+ () => PartnerSearchProvider
+> = {
+ "upstash-redis": createUpstashRedisPartnerSearchProvider,
+ "upstash-search": createUpstashSearchPartnerSearchProvider,
+ turbopuffer: createTurbopufferPartnerSearchProvider,
+};
+
+const providerCache = new Map<
+ PartnerSearchProviderName,
+ PartnerSearchProvider
+>();
export function getPartnerSearchProviderName(): PartnerSearchProviderName | null {
const provider = process.env.PARTNER_SEARCH_PROVIDER?.trim();
@@ -14,11 +33,13 @@ export function getPartnerSearchProviderName(): PartnerSearchProviderName | null
return null;
}
- if (provider === "upstash-redis" || provider === "upstash-search") {
- return provider;
+ if ((PARTNER_SEARCH_PROVIDER_NAMES as readonly string[]).includes(provider)) {
+ return provider as PartnerSearchProviderName;
}
- throw new Error(`Unsupported partner search provider: ${provider}`);
+ throw new Error(
+ `Unsupported partner search provider: ${provider}. Expected one of ${PARTNER_SEARCH_PROVIDER_NAMES.join(", ")}.`,
+ );
}
export function getPartnerSearchProvider(): PartnerSearchProvider | null {
@@ -28,19 +49,12 @@ export function getPartnerSearchProvider(): PartnerSearchProvider | null {
return null;
}
- if (provider === "upstash-redis") {
- if (!upstashRedisProvider) {
- upstashRedisProvider = createUpstashRedisPartnerSearchProvider();
- }
- return upstashRedisProvider;
- }
+ let instance = providerCache.get(provider);
- if (provider === "upstash-search") {
- if (!upstashSearchProvider) {
- upstashSearchProvider = createUpstashSearchPartnerSearchProvider();
- }
- return upstashSearchProvider;
+ if (!instance) {
+ instance = providerFactories[provider]();
+ providerCache.set(provider, instance);
}
- throw new Error(`Unsupported partner search provider: ${provider}`);
+ return instance;
}
diff --git a/apps/web/lib/api/partners/search/providers/turbopuffer.ts b/apps/web/lib/api/partners/search/providers/turbopuffer.ts
new file mode 100644
index 0000000000..933744c97f
--- /dev/null
+++ b/apps/web/lib/api/partners/search/providers/turbopuffer.ts
@@ -0,0 +1,274 @@
+import { chunk } from "@dub/utils";
+import { Turbopuffer } from "@turbopuffer/turbopuffer";
+import {
+ getPartnerSearchableValues,
+ normalizePartnerSearchQuery,
+} from "../searchable-values";
+import type { PartnerSearchDocument, PartnerSearchProvider } from "../types";
+import { validatePartnerSearchCandidateLimit } from "../types";
+import { withQueryDeadline, withTransientRetry } from "./resilience";
+import {
+ getEmailNgrams,
+ getQueryNgrams,
+ logPartnerSearchDebug,
+ resolveIndexName,
+} from "./shared";
+
+const DEFAULT_NAMESPACE = "partner-search-v1";
+const DEFAULT_REGION = "aws-us-east-1";
+const WRITE_BATCH_SIZE = 500;
+const QUERY_OPERATION_TIMEOUT_MS = 1_000;
+
+/**
+ * One namespace holding every program, scoped per query by a `programId` filter.
+ *
+ * Turbopuffer's idiomatic multi-tenancy is a namespace per tenant, which would
+ * make program isolation structural rather than filter-enforced. It is not used
+ * here because `PartnerSearchProvider.delete` receives only document IDs — with
+ * no program in hand there is no way to pick the namespace to delete from.
+ * Switching would mean widening the interface to carry the program.
+ */
+interface TurbopufferPartnerSearchRow extends Record<string, unknown> {
+ id: string;
+ programId: string;
+ searchText: string;
+ emailNgrams: string;
+}
+
+/**
+ * Pinned rather than left to default. Turbopuffer's newer tokenizers keep a URL
+ * as a single token, so `scottdigital` cannot match
+ * `https://www.scottdigital-42.techcorp.io` — and partner websites, short
+ * links, and destination URLs are all searchable fields here. word_v2 splits
+ * URLs into their components while handling emails, handles, and hyphenated
+ * keys the same way the newer ones do.
+ *
+ * Changing this requires a full re-backfill: it changes how documents are
+ * tokenized at write time, so existing rows keep their old indexing.
+ */
+const SEARCH_TEXT_TOKENIZER = "word_v2";
+
+// `searchText` and `emailNgrams` are BM25-indexed. BM25 attributes are not
+// filterable by default, but `emailNgrams` needs to be: the n-gram branch uses
+// a ContainsAllTokens filter to require every trigram.
+const TURBOPUFFER_SCHEMA = {
+ programId: { type: "string", filterable: true },
+ searchText: {
+ type: "string",
+ full_text_search: { tokenizer: SEARCH_TEXT_TOKENIZER },
+ },
+ emailNgrams: {
+ type: "string",
+ full_text_search: { tokenizer: SEARCH_TEXT_TOKENIZER },
+ filterable: true,
+ },
+} as const;
+
+interface CreateTurbopufferPartnerSearchProviderOptions {
+ namespace?: TurbopufferNamespace;
+ namespaceName?: string;
+}
+
+/** The subset of the SDK namespace this provider uses, so tests can fake it. */
+export interface TurbopufferNamespace {
+ write(params: Record<string, unknown>): Promise<{ rows_affected: number }>;
+ query(params: Record<string, unknown>): Promise<{
+ rows?: { id: string | number; $dist?: number }[];
+ }>;
+ multiQuery(params: Record<string, unknown>): Promise<{
+ results?: { rows?: { id: string | number; $dist?: number }[] }[];
+ }>;
+ deleteAll(): Promise<unknown>;
+}
+
+function getNamespaceName(namespaceName?: string): string {
+ return resolveIndexName(
+ [namespaceName, process.env.PARTNER_SEARCH_INDEX_NAME],
+ DEFAULT_NAMESPACE,
+ );
+}
+
+function createNamespace(namespaceName: string): TurbopufferNamespace {
+ const apiKey = process.env.TURBOPUFFER_API_KEY;
+
+ if (!apiKey) {
+ throw new Error("TURBOPUFFER_API_KEY is required for partner search.");
+ }
+
+ const client = new Turbopuffer({
+ apiKey,
+ region: process.env.TURBOPUFFER_REGION?.trim() || DEFAULT_REGION,
+ });
+
+ return client.namespace(namespaceName) as unknown as TurbopufferNamespace;
+}
+
+function serializeTurbopufferRow(
+ document: PartnerSearchDocument,
+): TurbopufferPartnerSearchRow {
+ return {
+ id: document.id,
+ programId: document.programId,
+ searchText: getPartnerSearchableValues(document)
+ .map(normalizePartnerSearchQuery)
+ .join(" "),
+ emailNgrams: getEmailNgrams(document.email),
+ };
+}
+
+/**
+ * Two ranked branches, unioned by the caller.
+ *
+ * The text branch treats the last token as a prefix so "john" reaches
+ * "johnson", matching how the Redis provider's $smart behaves. The n-gram
+ * branch carries a ContainsAllTokens filter so every trigram must be present —
+ * BM25 alone would score a document that shares just one, which is how an
+ * unrelated address ends up looking like a partial-email match.
+ */
+function buildQueryBranches(programId: string, query: string) {
+ const programFilter = ["programId", "Eq", programId];
+ const branches: Record<string, unknown>[] = [
+ {
+ rank_by: ["searchText", "BM25", query, { last_as_prefix: true }],
+ filters: programFilter,
+ },
+ ];
+
+ const ngrams = getQueryNgrams(query).join(" ");
+ if (ngrams) {
+ branches.push({
+ rank_by: ["emailNgrams", "BM25", ngrams],
+ filters: [
+ "And",
+ [programFilter, ["emailNgrams", "ContainsAllTokens", ngrams]],
+ ],
+ });
+ }
+
+ return branches;
+}
+
+function mergeBranchRows(
+ branches: { rows?: { id: string | number; $dist?: number }[] }[],
+ limit: number,
+) {
+ const bestById = new Map<string, number>();
+
+ for (const branch of branches) {
+ for (const row of branch.rows ?? []) {
+ const id = String(row.id);
+ const score = row.$dist ?? 0;
+ // Scores come from different BM25 clauses and are not directly
+ // comparable; the higher one only decides ordering within the union.
+ if (!bestById.has(id) || score > bestById.get(id)!) {
+ bestById.set(id, score);
+ }
+ }
+ }
+
+ return Array.from(bestById, ([id, score]) => ({ id, score }))
+ .sort(
+ (left, right) =>
+ right.score - left.score || left.id.localeCompare(right.id),
+ )
+ .slice(0, limit);
+}
+
+export async function deleteTurbopufferPartnerSearchNamespace({
+ namespace,
+ namespaceName,
+}: CreateTurbopufferPartnerSearchProviderOptions = {}) {
+ const resolvedNamespaceName = getNamespaceName(namespaceName);
+ const resolvedNamespace = namespace ?? createNamespace(resolvedNamespaceName);
+
+ await withTransientRetry(() => resolvedNamespace.deleteAll());
+
+ return { namespaceName: resolvedNamespaceName };
+}
+
+export function createTurbopufferPartnerSearchProvider({
+ namespace,
+ namespaceName,
+}: CreateTurbopufferPartnerSearchProviderOptions = {}): PartnerSearchProvider {
+ const resolvedNamespaceName = getNamespaceName(namespaceName);
+ const resolvedNamespace = namespace ?? createNamespace(resolvedNamespaceName);
+
+ return {
+ async searchCandidates({ programId, query, limit }) {
+ validatePartnerSearchCandidateLimit(limit);
+
+ const normalizedQuery = normalizePartnerSearchQuery(query);
+ const branches = buildQueryBranches(programId, normalizedQuery).map(
+ (branch) => ({ ...branch, top_k: limit, include_attributes: false }),
+ );
+
+ // One round trip regardless of branch count.
+ const { results } = await withQueryDeadline(
+ () => resolvedNamespace.multiQuery({ queries: branches }),
+ QUERY_OPERATION_TIMEOUT_MS,
+ );
+
+ const hits = mergeBranchRows(results ?? [], limit);
+
+ logPartnerSearchDebug("Turbopuffer", {
+ namespace: resolvedNamespaceName,
+ operation: "searchCandidates",
+ query: { programId, query, limit },
+ branches: branches.length,
+ resultCount: hits.length,
+ hits,
+ });
+
+ return { hits };
+ },
+
+ async waitForIndexing() {
+ // Turbopuffer writes are read-after-write consistent — a committed write
+ // is immediately queryable, so there is no indexing lag to wait on.
+ },
+
+ async upsert(documents) {
+ for (const documentBatch of chunk(documents, WRITE_BATCH_SIZE)) {
+ await withTransientRetry(() =>
+ resolvedNamespace.write({
+ upsert_rows: documentBatch.map(serializeTurbopufferRow),
+ schema: TURBOPUFFER_SCHEMA,
+ }),
+ );
+ }
+ },
+
+ async delete(documentIds) {
+ for (const documentIdBatch of chunk(documentIds, WRITE_BATCH_SIZE)) {
+ await withTransientRetry(() =>
+ resolvedNamespace.write({ deletes: documentIdBatch }),
+ );
+ }
+ },
+
+ async listDocumentIds({ cursor, limit }) {
+ // Keyset pagination over the ID order, the same shape the backfill uses
+ // against the database. Turbopuffer has no scan cursor of its own.
+ const { rows } = await withTransientRetry(() =>
+ resolvedNamespace.query({
+ rank_by: ["id", "asc"],
+ top_k: limit,
+ include_attributes: false,
+ ...(cursor ? { filters: ["id", "Gt", cursor] } : {}),
+ }),
+ );
+
+ const documentIds = (rows ?? []).map(({ id }) => String(id));
+
+ return {
+ documentIds,
+ // A short page means the namespace is exhausted; otherwise resume from
+ // the last ID.
+ cursor:
+ documentIds.length < limit
+ ? null
+ : documentIds[documentIds.length - 1],
+ };
+ },
+ };
+}
diff --git a/apps/web/package.json b/apps/web/package.json
index f6028eacd7..a8bef1d60f 100644
--- a/apps/web/package.json
+++ b/apps/web/package.json
@@ -54,6 +54,7 @@
"@tiptap/html": "^3.15.3",
"@tiptap/starter-kit": "^3.15.3",
"@tiptap/static-renderer": "^3.15.3",
+ "@turbopuffer/turbopuffer": "^2.8.0",
"@types/base-x": "^3.0.10",
"@types/bcryptjs": "^2.4.6",
"@types/buffer-crc32": "0.2.0",
diff --git a/apps/web/scripts/partners/create-partner-search-index.ts b/apps/web/scripts/partners/create-partner-search-index.ts
index 3a581423bf..d68a3e6c74 100644
--- a/apps/web/scripts/partners/create-partner-search-index.ts
+++ b/apps/web/scripts/partners/create-partner-search-index.ts
@@ -8,9 +8,13 @@ async function main() {
throw new Error("PARTNER_SEARCH_PROVIDER is not configured.");
}
- if (providerName === "upstash-search") {
+ // Only Redis Search needs an index declared up front. The others infer their
+ // schema from the first write, so this is a no-op for them — spelled out per
+ // provider rather than falling through, so a new provider cannot silently
+ // land on the Redis path.
+ if (providerName === "upstash-search" || providerName === "turbopuffer") {
console.log(
- "Upstash Search creates the partner search index on the first backfill upsert.",
+ `${providerName} creates the partner search index on the first backfill upsert.`,
);
return;
}
diff --git a/apps/web/scripts/partners/delete-partner-search-index.ts b/apps/web/scripts/partners/delete-partner-search-index.ts
index 9c9053b6aa..069985187a 100644
--- a/apps/web/scripts/partners/delete-partner-search-index.ts
+++ b/apps/web/scripts/partners/delete-partner-search-index.ts
@@ -1,4 +1,5 @@
import { getPartnerSearchProviderName } from "@/lib/api/partners/search";
+import { deleteTurbopufferPartnerSearchNamespace } from "@/lib/api/partners/search/providers/turbopuffer";
import { deleteUpstashSearchPartnerSearchIndex } from "@/lib/api/partners/search/providers/upstash-search";
import { chunk } from "@dub/utils";
import { Redis } from "@upstash/redis";
@@ -112,6 +113,12 @@ async function main() {
return;
}
+ if (providerName === "turbopuffer") {
+ await deleteTurbopufferPartnerSearchNamespace({ namespaceName: indexName });
+ console.log(`Partner search cleanup complete: emptied ${indexName}.`);
+ return;
+ }
+
const redis = createRedisClient();
const index = redis.search.index({ name: indexName });
const description = await index.describe();
diff --git a/apps/web/tests/partners/turbopuffer-partner-search-provider.test.ts b/apps/web/tests/partners/turbopuffer-partner-search-provider.test.ts
new file mode 100644
index 0000000000..475f71abef
--- /dev/null
+++ b/apps/web/tests/partners/turbopuffer-partner-search-provider.test.ts
@@ -0,0 +1,283 @@
+import {
+ PARTNER_SEARCH_CANDIDATE_LIMIT,
+ type PartnerSearchDocument,
+} from "@/lib/api/partners/search";
+import {
+ createTurbopufferPartnerSearchProvider,
+ deleteTurbopufferPartnerSearchNamespace,
+ type TurbopufferNamespace,
+} from "@/lib/api/partners/search/providers/turbopuffer";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const document: PartnerSearchDocument = {
+ id: "pge_test",
+ programId: "prog_test",
+ partnerId: "pn_test",
+ name: "Rafi Hasan",
+ email: "[email protected]",
+ companyName: "Hasan Labs",
+ description: "Affiliate marketer",
+ platformTypes: ["youtube"],
+ platformIdentifiers: ["@rafi"],
+ linkDomains: ["dub.sh"],
+ linkKeys: ["rafi"],
+ shortLinks: ["https://dub.sh/rafi"],
+ destinationUrls: ["https://example.com/referrals/rafi"],
+};
+
+const mocks = vi.hoisted(() => ({
+ write: vi.fn(),
+ query: vi.fn(),
+ multiQuery: vi.fn(),
+ deleteAll: vi.fn(),
+}));
+
+function createNamespaceMock(): TurbopufferNamespace {
+ return {
+ write: mocks.write,
+ query: mocks.query,
+ multiQuery: mocks.multiQuery,
+ deleteAll: mocks.deleteAll,
+ } as unknown as TurbopufferNamespace;
+}
+
+function createProvider() {
+ return createTurbopufferPartnerSearchProvider({
+ namespace: createNamespaceMock(),
+ namespaceName: "test-namespace",
+ });
+}
+
+describe("Turbopuffer partner search provider", () => {
+ beforeEach(() => {
+ for (const mock of Object.values(mocks)) {
+ mock.mockReset();
+ }
+ mocks.write.mockResolvedValue({ rows_affected: 1 });
+ mocks.multiQuery.mockResolvedValue({ results: [] });
+ mocks.query.mockResolvedValue({ rows: [] });
+ });
+
+ it("flattens every searchable field into one BM25 attribute", async () => {
+ await createProvider().upsert([document]);
+
+ const [{ upsert_rows, schema }] = mocks.write.mock.calls[0];
+ expect(upsert_rows).toHaveLength(1);
+
+ const [row] = upsert_rows;
+ expect(row.id).toBe("pge_test");
+ expect(row.programId).toBe("prog_test");
+ for (const value of [
+ "rafi hasan",
+ "hasan labs",
+ "affiliate marketer",
+ "youtube",
+ "@rafi",
+ "dub.sh",
+ "https://dub.sh/rafi",
+ "https://example.com/referrals/rafi",
+ ]) {
+ expect(row.searchText).toContain(value);
+ }
+
+ // BM25 attributes are not filterable by default, but the n-gram branch
+ // filters on emailNgrams.
+ expect(schema.emailNgrams).toMatchObject({ filterable: true });
+ expect(schema.programId).toMatchObject({ filterable: true });
+ });
+
+ it("pins a tokenizer that splits URLs into their components", async () => {
+ // The default tokenizer keeps a URL as one token, so "scottdigital" cannot
+ // match "https://www.scottdigital-42.techcorp.io" — and websites, short
+ // links, and destination URLs are all searchable here.
+ await createProvider().upsert([document]);
+
+ const [{ schema }] = mocks.write.mock.calls[0];
+ expect(schema.searchText.full_text_search).toEqual({
+ tokenizer: "word_v2",
+ });
+ expect(schema.emailNgrams.full_text_search).toEqual({
+ tokenizer: "word_v2",
+ });
+ });
+
+ it("scopes both branches to the program and matches prefixes", async () => {
+ await createProvider().searchCandidates({
+ programId: "prog_test",
+ query: "rafi",
+ limit: 10,
+ });
+
+ const [{ queries }] = mocks.multiQuery.mock.calls[0];
+ const [textBranch] = queries;
+
+ expect(textBranch.rank_by).toEqual([
+ "searchText",
+ "BM25",
+ "rafi",
+ { last_as_prefix: true },
+ ]);
+ expect(textBranch.filters).toEqual(["programId", "Eq", "prog_test"]);
+
+ for (const branch of queries) {
+ expect(JSON.stringify(branch.filters)).toContain("prog_test");
+ expect(branch.top_k).toBe(10);
+ }
+ });
+
+ it("requires every trigram on the n-gram branch", async () => {
+ // BM25 alone would score a document sharing a single trigram, which is how
+ // an unrelated address looks like a partial-email match.
+ await createProvider().searchCandidates({
+ programId: "prog_test",
+ query: "examp",
+ limit: 10,
+ });
+
+ const [{ queries }] = mocks.multiQuery.mock.calls[0];
+ expect(queries).toHaveLength(2);
+
+ const [, ngramBranch] = queries;
+ expect(ngramBranch.rank_by).toEqual(["emailNgrams", "BM25", "exa xam amp"]);
+ expect(ngramBranch.filters).toEqual([
+ "And",
+ [
+ ["programId", "Eq", "prog_test"],
+ ["emailNgrams", "ContainsAllTokens", "exa xam amp"],
+ ],
+ ]);
+ });
+
+ it("skips the n-gram branch when the query cannot produce trigrams", async () => {
+ await createProvider().searchCandidates({
+ programId: "prog_test",
+ query: "hi",
+ limit: 10,
+ });
+
+ const [{ queries }] = mocks.multiQuery.mock.calls[0];
+ expect(queries).toHaveLength(1);
+ });
+
+ it("unions branches, keeping the better score for a shared document", async () => {
+ mocks.multiQuery.mockResolvedValue({
+ results: [
+ { rows: [{ id: "pge_1", $dist: 0.4 }] },
+ {
+ rows: [
+ { id: "pge_1", $dist: 0.9 },
+ { id: "pge_2", $dist: 0.6 },
+ ],
+ },
+ ],
+ });
+
+ const { hits } = await createProvider().searchCandidates({
+ programId: "prog_test",
+ query: "examp",
+ limit: 10,
+ });
+
+ expect(hits).toEqual([
+ { id: "pge_1", score: 0.9 },
+ { id: "pge_2", score: 0.6 },
+ ]);
+ });
+
+ it("never returns more than the requested limit", async () => {
+ mocks.multiQuery.mockResolvedValue({
+ results: [
+ { rows: [{ id: "pge_1", $dist: 0.5 }] },
+ { rows: [{ id: "pge_2", $dist: 0.4 }] },
+ ],
+ });
+
+ const { hits } = await createProvider().searchCandidates({
+ programId: "prog_test",
+ query: "examp",
+ limit: 1,
+ });
+
+ expect(hits).toHaveLength(1);
+ });
+
+ it("rejects a limit above the candidate ceiling", async () => {
+ await expect(
+ createProvider().searchCandidates({
+ programId: "prog_test",
+ query: "rafi",
+ limit: PARTNER_SEARCH_CANDIDATE_LIMIT + 1,
+ }),
+ ).rejects.toThrow("Partner search candidate limit");
+ });
+
+ it("deletes by document ID", async () => {
+ await createProvider().delete(["pge_1", "pge_2"]);
+
+ expect(mocks.write).toHaveBeenCalledWith({
+ deletes: ["pge_1", "pge_2"],
+ });
+ });
+
+ it("enumerates document IDs by keyset over the ID order", async () => {
+ mocks.query.mockResolvedValue({
+ rows: [{ id: "pge_1" }, { id: "pge_2" }],
+ });
+
+ const page = await createProvider().listDocumentIds({ limit: 2 });
+
+ expect(mocks.query).toHaveBeenCalledWith(
+ expect.objectContaining({ rank_by: ["id", "asc"], top_k: 2 }),
+ );
+ // A full page means there may be more, so the cursor is the last ID.
+ expect(page).toEqual({
+ documentIds: ["pge_1", "pge_2"],
+ cursor: "pge_2",
+ });
+ });
+
+ it("resumes after the cursor and reports exhaustion on a short page", async () => {
+ mocks.query.mockResolvedValue({ rows: [{ id: "pge_9" }] });
+
+ const page = await createProvider().listDocumentIds({
+ cursor: "pge_8",
+ limit: 2,
+ });
+
+ expect(mocks.query).toHaveBeenCalledWith(
+ expect.objectContaining({ filters: ["id", "Gt", "pge_8"] }),
+ );
+ expect(page).toEqual({ documentIds: ["pge_9"], cursor: null });
+ });
+
+ it("does not wait for indexing, which turbopuffer does not need", async () => {
+ await expect(createProvider().waitForIndexing()).resolves.toBeUndefined();
+ expect(mocks.query).not.toHaveBeenCalled();
+ expect(mocks.write).not.toHaveBeenCalled();
+ });
+
+ it("empties the namespace", async () => {
+ mocks.deleteAll.mockResolvedValue({});
+
+ const result = await deleteTurbopufferPartnerSearchNamespace({
+ namespace: createNamespaceMock(),
+ namespaceName: "test-namespace",
+ });
+
+ expect(mocks.deleteAll).toHaveBeenCalledOnce();
+ expect(result).toEqual({ namespaceName: "test-namespace" });
+ });
+
+ it("falls back to the default namespace when the env var is blank", async () => {
+ vi.stubEnv("PARTNER_SEARCH_INDEX_NAME", "");
+ mocks.deleteAll.mockResolvedValue({});
+
+ const { namespaceName } = await deleteTurbopufferPartnerSearchNamespace({
+ namespace: createNamespaceMock(),
+ });
+
+ expect(namespaceName).toBe("partner-search-v1");
+ vi.unstubAllEnvs();
+ });
+});
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index d808ee13eb..10d7b33b80 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -140,6 +140,9 @@ importers:
'@tiptap/static-renderer':
specifier: ^3.15.3
+ '@turbopuffer/turbopuffer':
+ specifier: ^2.8.0
+ version: 2.8.0
'@types/base-x':
specifier: ^3.0.10
version: 3.0.10
@@ -675,7 +678,7 @@ importers:
dependencies:
'@hubspot/cli':
specifier: ^7.6.2
devDependencies:
'@types/node':
specifier: 18.11.9
@@ -5666,6 +5669,9 @@ packages:
'@tsconfig/[email protected]':
resolution: {integrity: sha512-vxhUy4J8lyeyinH7Azl1pdd43GJhZH/tP2weN8TntQblOY+A0XbT8DJk1/oCPuOOyg/Ja757rG0CgHcWC8OfMA==}
+ '@turbopuffer/[email protected]':
+ resolution: {integrity: sha512-lurmVByLynuWtPtVl7SBEJ0bNakb8bs4KsafKzeLWnXA6BsQiGS9obT/7ExQVb9/yecyRn/grj8VgwUzi2xMyg==}
+
resolution: {integrity: sha512-rfT93uj5s0PRL7EzccGMs3brplhcrghnDoV26NqKhCAS1hVo+WdNsPvE/yb6ilfr5hi2MEk6d5EWJTKdxg8jVw==}
@@ -10744,6 +10750,9 @@ packages:
resolution: {integrity: sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw==}
+ resolution: {integrity: sha512-zJq6RP/5q+TO2OpFV3FHzlPnFjmkb7Nc99a5SNjJE+uu/PkpChs+NIZSSzbBoD+6kjiISXjfYdwj1ZRQ81dz/w==}
+
resolution: {integrity: sha512-HipMsgJkZu8br23pW15uvo6sib6wne/4woLZPlFf3rpDyMe9ywEXUsuD7+6K9PRkJlVT51j/sCOYDKGGS3ZJrw==}
@@ -12924,6 +12933,10 @@ packages:
resolution: {integrity: sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==}
+ resolution: {integrity: sha512-IDxfleLmmbSskfWSUATiN1nfn2rDuvnMOqb5CWR92iIfojA0Ud+ulOAAEQ57LPr9rWmsreUyf5lwyao+7GNNVw==}
+ engines: {node: '>=20.18.1'}
+
resolution: {integrity: sha512-CLjCCLQ6UuMxWnbIylkisbRj31qxHPAurvena/0iwSVbQ2G1VY5/HjV0IRabOEbDHlzZlRdCrD4NhB0JtU40Pg==}
@@ -14541,9 +14554,9 @@ snapshots:
'@babel/core': 7.24.5
'@babel/helper-plugin-utils': 7.25.9
dependencies:
- '@babel/core': 7.28.4
+ '@babel/core': 7.24.5
'@babel/helper-plugin-utils': 7.27.1
optional: true
@@ -15373,7 +15386,7 @@ snapshots:
- encoding
- supports-color
dependencies:
'@hubspot/local-dev-lib': 3.19.1
'@hubspot/project-parsing-lib': 0.8.6(@hubspot/[email protected])
@@ -15404,7 +15417,7 @@ snapshots:
yargs: 17.7.2
yargs-parser: 21.1.1
optionalDependencies:
'@modelcontextprotocol/sdk': 1.13.3
transitivePeerDependencies:
- '@babel/core'
@@ -15442,7 +15455,7 @@ snapshots:
react-dom: 18.3.1([email protected])
optional: true
dependencies:
'@babel/code-frame': 7.26.2
'@babel/parser': 7.26.2
@@ -15469,7 +15482,7 @@ snapshots:
'@vitejs/plugin-react': 4.7.0([email protected](@types/[email protected])([email protected]))
ansi-to-html: 0.7.2
babel-plugin-macros: 3.1.0
chalk: 5.4.1
class-variance-authority: 0.7.0
cli-progress: 3.12.0
@@ -15488,7 +15501,7 @@ snapshots:
react-dom: 18.3.1([email protected])
request: 2.88.2
storybook: 8.6.14([email protected])
tailwind-merge: 2.6.0
tailwindcss-animate: 1.0.7
typescript: 4.7.4
@@ -19355,6 +19368,11 @@ snapshots:
'@tsconfig/[email protected]': {}
+ '@turbopuffer/[email protected]':
+ dependencies:
+ pako: 2.2.0
+ undici: 7.29.0
+
optional: true
@@ -20521,11 +20539,11 @@ snapshots:
resolve: 1.22.6
optional: true
dependencies:
'@babel/helper-annotate-as-pure': 7.27.3
'@babel/helper-module-imports': 7.25.9
- '@babel/plugin-syntax-jsx': 7.27.1(@babel/[email protected])
+ '@babel/plugin-syntax-jsx': 7.27.1(@babel/[email protected])
lodash: 4.17.21
picomatch: 2.3.1
@@ -25707,6 +25725,8 @@ snapshots:
+
@@ -27614,12 +27634,12 @@ snapshots:
tslib: 2.6.2
optional: true
dependencies:
client-only: 0.0.1
react: 18.3.1
optionalDependencies:
- '@babel/core': 7.28.4
+ '@babel/core': 7.24.5
babel-plugin-macros: 3.1.0
optional: true
@@ -28531,6 +28551,8 @@ snapshots:
+
dependencies:
base64-js: 1.5.1