AI-native knowledge base & Evernote/Obsidian alternative with instant sync & native MCP. Free on Cloudflare or self-hosted via Docker.
HTML ai-agentcloudflarecloudflare-d1cloudflare-r2cloudflare-workersdockerelectronevernoteevernote-alternativeknowledge-basemcpnote-takingobsidian-alternativeoffline-firstpersonal-knowledge-basepwaself-hostedsqlitetiptapweb-clipper
fix(sync): batch large change detail queries
tianma-ifdd0c1d3566ea
diff --git a/apps/api/src/sync-routes.test.mjs b/apps/api/src/sync-routes.test.mjsindex 78e335f9..926841b3 100644--- a/apps/api/src/sync-routes.test.mjs+++ b/apps/api/src/sync-routes.test.mjs@@ -200,4 +200,50 @@ describe("sync route contracts", () => {serverCursor: 22,});});++ test("batches detail queries below Cloudflare D1's bound-parameter limit", async () => {+ const changes = Array.from({ length: 200 }, (_, index) => ({+ id: index + 1,+ entity_type: "memo",+ entity_id: `memo_${String(index + 1).padStart(3, "0")}`,+ operation: "upsert",+ server_cursor: 200,+ sync_identity: "workspace-created-at",+ }));+ const detailQueryBindingCounts = [];+ const database = {+ prepare: (sql) => ({+ bind: (...bindings) => {+ if (bindings.length > 100) {+ throw new Error(`D1_ERROR: too many SQL variables (${bindings.length})`);+ }+ return {+ all: async () => {+ if (sql.includes("WITH workspace_state")) return { results: changes };+ if (sql.includes("FROM memos m")) {+ detailQueryBindingCounts.push(bindings.length);+ return {+ results: bindings.slice(1).map((id) => ({ id, title: `Title ${id}` })),+ };+ }+ return { results: [] };+ },+ first: async () => null,+ };+ },+ }),+ };+ const response = await createApp().request(+ "/api/v1/sync/changes?cursor=0&limit=200",+ {},+ { storage: { db: database, resources: {} } },+ );++ expect(response.status).toBe(200);+ const body = await response.json();+ expect(body.changes).toHaveLength(200);+ expect(body.changes[0]).toMatchObject({ entityId: "memo_001", operation: "upsert" });+ expect(body.changes.at(-1)).toMatchObject({ entityId: "memo_200", operation: "upsert" });+ expect(detailQueryBindingCounts).toEqual([91, 91, 21]);+ });});diff --git a/apps/api/src/sync-routes.ts b/apps/api/src/sync-routes.tsindex ab17d509..6633f8f5 100644--- a/apps/api/src/sync-routes.ts+++ b/apps/api/src/sync-routes.ts@@ -40,6 +40,20 @@ type SyncRouteDependencies = {mapMemoDetail: (row: SyncMemoDetailRow) => MemoDetail;};+// Cloudflare D1 accepts at most 100 bound parameters per query. Each detail+// query also binds the workspace id, so keep entity batches comfortably below+// that ceiling. A large import can place 200 distinct entities in one change+// page; querying all of them in one IN clause would make sync return HTTP 500.+const SYNC_DETAIL_ID_BATCH_SIZE = 90;++const splitSyncDetailIds = (ids: string[]) => {+ const batches: string[][] = [];+ for (let index = 0; index < ids.length; index += SYNC_DETAIL_ID_BATCH_SIZE) {+ batches.push(ids.slice(index, index + SYNC_DETAIL_ID_BATCH_SIZE));+ }+ return batches;+};+export const registerSyncRoutes = (app: Hono<AppEnv>,dependencies: SyncRouteDependencies,@@ -150,33 +164,37 @@ export const registerSyncRoutes = (const notebookIds = Array.from(new Set(compactedPage.filter((change) => change.entity_type === "notebook" && change.operation === "upsert").map((change) => change.entity_id)));- const memoPlaceholders = memoIds.map(() => "?").join(", ");- const notebookPlaceholders = notebookIds.map(() => "?").join(", ");- const [memoRows, notebookRows] = await Promise.all([- memoIds.length > 0- ? context.env.storage.db.prepare(+ const [memoRowBatches, notebookRowBatches] = await Promise.all([+ Promise.all(splitSyncDetailIds(memoIds).map((batch) => {+ const placeholders = batch.map(() => "?").join(", ");+ return context.env.storage.db.prepare(`SELECT m.id, m.notebook_id, m.title, m.excerpt, m.tags_json, m.is_pinned,m.is_archived, m.is_deleted, m.created_at, m.updated_at, m.deleted_at, mc.revision,mc.content_json, mc.content_markdown, mc.content_text, mc.content_hash,m.source_memo_ids, m.merge_source_count, m.merged_into_memo_idFROM memos mINNER JOIN memo_contents mc ON mc.memo_id = m.id- WHERE m.workspace_id = ? AND m.id IN (${memoPlaceholders})`,- ).bind(workspaceId, ...memoIds).all<SyncMemoDetailRow>()- : Promise.resolve({ results: [] as SyncMemoDetailRow[] }),- notebookIds.length > 0- ? context.env.storage.db.prepare(+ WHERE m.workspace_id = ? AND m.id IN (${placeholders})`,+ ).bind(workspaceId, ...batch).all<SyncMemoDetailRow>();+ })),+ Promise.all(splitSyncDetailIds(notebookIds).map((batch) => {+ const placeholders = batch.map(() => "?").join(", ");+ return context.env.storage.db.prepare(`SELECT n.id, n.parent_id, n.name, n.slug, n.icon, n.color, n.sort_order,n.created_at, n.updated_at, COUNT(m.id) AS memo_count, MAX(m.updated_at) AS last_memo_updated_atFROM notebooks nLEFT JOIN memos m ON m.notebook_id = n.id AND m.workspace_id = n.workspace_id AND m.is_deleted = 0- WHERE n.workspace_id = ? AND n.is_deleted = 0 AND n.id IN (${notebookPlaceholders})+ WHERE n.workspace_id = ? AND n.is_deleted = 0 AND n.id IN (${placeholders})GROUP BY n.id, n.parent_id, n.name, n.slug, n.icon, n.color, n.sort_order, n.created_at, n.updated_at`,- ).bind(workspaceId, ...notebookIds).all<NotebookRow>()- : Promise.resolve({ results: [] as NotebookRow[] }),+ ).bind(workspaceId, ...batch).all<NotebookRow>();+ })),]);- const memosById = new Map(memoRows.results.map((row) => [row.id, dependencies.mapMemoDetail(row)]));- const notebooksById = new Map(notebookRows.results.map((row) => [row.id, mapNotebook(row)]));+ const memosById = new Map(memoRowBatches+ .flatMap((batch) => batch.results)+ .map((row) => [row.id, dependencies.mapMemoDetail(row)]));+ const notebooksById = new Map(notebookRowBatches+ .flatMap((batch) => batch.results)+ .map((row) => [row.id, mapNotebook(row)]));const changes = compactedPage.map((change) => {if (change.entity_type === "memo") {const memo = change.operation === "upsert" ? memosById.get(change.entity_id) ?? null : null;diff --git a/tests/e2e/bulk-import-sync.spec.ts b/tests/e2e/bulk-import-sync.spec.tsnew file mode 100644index 00000000..418cc5f9--- /dev/null+++ b/tests/e2e/bulk-import-sync.spec.ts@@ -0,0 +1,171 @@+import { expect, test, type APIRequestContext, type Page } from "@playwright/test";++type SyncMetaRow = { key?: string; value?: string };++const readLocalSyncCursor = (page: Page) => page.evaluate(async () => {+ const modulePath = "/src/lib/local-db.ts";+ const { localDb } = await import(/* @vite-ignore */ modulePath) as {+ localDb: { syncMeta: { toArray: () => Promise<SyncMetaRow[]> } };+ };+ const cursor = (await localDb.syncMeta.toArray()).find((row) => row.key === "cursor")?.value;+ return cursor === undefined ? null : Number(cursor);+});++const countLocalMemosWithMarker = (page: Page, marker: string) => page.evaluate(async (searchMarker) => {+ const modulePath = "/src/lib/local-db.ts";+ const { localDb } = await import(/* @vite-ignore */ modulePath) as {+ localDb: { memos: { toArray: () => Promise<Array<{ title?: string | null }>> } };+ };+ return (await localDb.memos.toArray()).filter((memo) => memo.title?.includes(searchMarker)).length;+}, marker);++const importMemoBatch = async (+ request: APIRequestContext,+ input: { token: string; source: string; notebookId: string; marker: string; offset: number; count: number },+) => {+ const response = await request.post("/mcp", {+ headers: {+ Accept: "application/json, text/event-stream",+ Authorization: `Bearer ${input.token}`,+ },+ data: {+ jsonrpc: "2.0",+ id: input.offset + 1,+ method: "tools/call",+ params: {+ name: "import_memos",+ arguments: {+ source: input.source,+ notebookId: input.notebookId,+ items: Array.from({ length: input.count }, (_, index) => {+ const itemNumber = input.offset + index;+ return {+ externalId: `${input.source}-${itemNumber}`,+ title: `${input.marker} ${itemNumber}`,+ contentMarkdown: `Bulk incremental sync fixture ${input.marker} ${itemNumber}`,+ };+ }),+ },+ },+ },+ });+ expect(response.status()).toBe(200);+ const body = await response.json() as { error?: unknown; result?: { isError?: boolean } };+ expect(body.error).toBeUndefined();+ expect(body.result?.isError).toBe(false);+};++const listMemoIdsWithMarker = async (request: APIRequestContext, marker: string) => {+ const ids: string[] = [];+ let cursor: string | null = null;+ do {+ const search = new URLSearchParams({ q: marker, limit: "100" });+ if (cursor) search.set("cursor", cursor);+ const response = await request.get(`/api/v1/memos?${search.toString()}`);+ expect(response.ok()).toBe(true);+ const page = await response.json() as {+ memos: Array<{ id: string }>;+ nextCursor: string | null;+ };+ ids.push(...page.memos.map((memo) => memo.id));+ cursor = page.nextCursor;+ } while (cursor);+ return ids;+};++const deleteMemoFixtures = async (request: APIRequestContext, memoIds: string[]) => {+ for (let offset = 0; offset < memoIds.length; offset += 50) {+ const memoIdBatch = memoIds.slice(offset, offset + 50);+ const trashResponse = await request.post("/api/v1/memos/batch/delete", {+ data: { memoIds: memoIdBatch },+ });+ expect(trashResponse.ok()).toBe(true);+ const deleteResponse = await request.post("/api/v1/memos/batch/delete", {+ data: { memoIds: memoIdBatch, permanent: true },+ });+ expect(deleteResponse.ok()).toBe(true);+ }+};++test("an existing browser mirror catches up after an import larger than one sync page", async ({ page }) => {+ test.setTimeout(120_000);+ const importedMemoCount = 205;+ const marker = `bulk-sync-${Date.now()}`;+ const source = `e2e-${marker}`;+ let createdMemoIds: string[] = [];+ let apiTokenId: string | null = null;++ const notebooksResponse = await page.request.get("/api/v1/notebooks");+ expect(notebooksResponse.ok()).toBe(true);+ const notebooks = await notebooksResponse.json() as { notebooks: Array<{ id: string }> };+ const notebookId = notebooks.notebooks[0]?.id;+ expect(notebookId).toBeTruthy();++ try {+ await page.goto("/");+ await expect(page.getByRole("button", { name: "正在同步笔记", exact: true })).toHaveCount(0, { timeout: 20_000 });+ await expect.poll(() => readLocalSyncCursor(page), { timeout: 20_000 }).not.toBeNull();+ const cursorBeforeImport = await readLocalSyncCursor(page);+ expect(cursorBeforeImport).not.toBeNull();++ const tokenResponse = await page.request.post("/api/v1/api-tokens", {+ data: {+ name: `E2E bulk sync ${Date.now()}`,+ scopes: ["read:notebooks", "read:memos", "write:memos"],+ },+ });+ expect(tokenResponse.status()).toBe(201);+ const tokenBody = await tokenResponse.json() as { token: string; apiToken: { id: string } };+ apiTokenId = tokenBody.apiToken.id;++ // Stop the workspace lifecycle so all imported changes accumulate after+ // the browser's saved cursor, matching an existing client that was closed+ // while a large MCP migration ran.+ await page.goto("about:blank");++ for (let offset = 0; offset < importedMemoCount; offset += 25) {+ await importMemoBatch(page.request, {+ token: tokenBody.token,+ source,+ notebookId,+ marker,+ offset,+ count: Math.min(25, importedMemoCount - offset),+ });+ }+ createdMemoIds = await listMemoIdsWithMarker(page.request, marker);+ expect(createdMemoIds).toHaveLength(importedMemoCount);++ const firstIncrementalPage = page.waitForResponse((response) => {+ const url = new URL(response.url());+ return url.pathname === "/api/v1/sync/changes" &&+ url.searchParams.get("cursor") === String(cursorBeforeImport) &&+ url.searchParams.get("limit") === "200";+ });+ await page.goto("/");++ const firstPageResponse = await firstIncrementalPage;+ expect(firstPageResponse.ok()).toBe(true);+ const firstPageBody = await firstPageResponse.json() as { changes: unknown[]; hasMore: boolean };+ expect(firstPageBody.changes).toHaveLength(200);+ expect(firstPageBody.hasMore).toBe(true);++ await expect.poll(+ () => countLocalMemosWithMarker(page, marker),+ { timeout: 30_000 },+ ).toBe(importedMemoCount);++ await page.getByRole("button", { name: "全部笔记", exact: true }).click();+ await page.getByPlaceholder("搜索笔记").fill(marker);+ await expect(page.getByText(`${importedMemoCount} 条结果`, { exact: true })).toBeVisible();+ } finally {+ if (createdMemoIds.length === 0) {+ createdMemoIds = await listMemoIdsWithMarker(page.request, marker);+ }+ await deleteMemoFixtures(page.request, createdMemoIds);+ if (apiTokenId) {+ const tokenDeleteResponse = await page.request.delete(`/api/v1/api-tokens/${apiTokenId}`);+ expect(tokenDeleteResponse.ok()).toBe(true);+ }+ }+});