diff --git a/docs/data-model.md b/docs/data-model.md index 5102eb033c..a9a11ff3eb 100644 --- a/docs/data-model.md +++ b/docs/data-model.md @@ -591,6 +591,11 @@ then retry only when a requested row changes during the read. Unrelated agent st invalidate the read. Directory baseline replacements and host removal or renaming still invalidate the affected reads. +On web and Electron, tabs share IndexedDB but hold independent directory snapshots in memory. A +tab can commit directory deltas only while the persisted checkpoint revision matches the one it +read or wrote. If a different tab evicts or rewrites that baseline, the next full directory refresh +can replace it. Timeline writes do not depend on the directory checkpoint. + The cache is capped at 32 MiB and evicts whole hosts in least-recently-written order. After an eviction, only a baseline replacement stores that host's directory again. Mutations queued around the eviction are dropped when they are written, so a checkpoint never outlives its rows. Budget diff --git a/packages/app/e2e/browser/sidebar-workspace.spec.ts b/packages/app/e2e/browser/sidebar-workspace.spec.ts index 068b75e213..aff1e4ffaf 100644 --- a/packages/app/e2e/browser/sidebar-workspace.spec.ts +++ b/packages/app/e2e/browser/sidebar-workspace.spec.ts @@ -210,14 +210,14 @@ async function simulateDamagedLegacyDirectoryCache( return; } const stored = JSON.parse(checkpoint.payload); - // Read the cursors from whichever version wrote them, then store them as version 1: - // the format whose writer could keep a checkpoint after evicting the rows it describes. + // Read the cursors from whichever version wrote them, then store them as version 2: + // the format whose writer could keep a checkpoint after another tab evicted its rows. const cursors = typeof stored.version === "number" ? stored.cursors : stored; if (!cursors?.workspaces?.generation) { transaction.abort(); return; } - store.put({ ...checkpoint, payload: JSON.stringify({ version: 1, cursors }) }); + store.put({ ...checkpoint, payload: JSON.stringify({ version: 2, cursors }) }); for (const row of rows) { if ( row.serverId === serverId && diff --git a/packages/app/src/runtime/replica-cache/index.browser.test.ts b/packages/app/src/runtime/replica-cache/index.browser.test.ts new file mode 100644 index 0000000000..4a000882b1 --- /dev/null +++ b/packages/app/src/runtime/replica-cache/index.browser.test.ts @@ -0,0 +1,90 @@ +import { expect, it } from "vitest"; +import { normalizeProjectDescriptor, normalizeWorkspaceDescriptor } from "@/stores/session-store"; +import { ReplicaCache } from "."; +import { createIndexedDbReplicaRowStore } from "./row-store.web"; + +const SERVER_ID = "shared-host"; +const noLegacyCleanup = { clearLegacyCache: async () => undefined }; + +// Each browser tab opens its own ReplicaCache over the same IndexedDB database. +function openTab(databaseName: string, maxBytes?: number): ReplicaCache { + const store = createIndexedDbReplicaRowStore({ databaseName, schemaVersion: 1 }); + const cache = new ReplicaCache(store, { ...noLegacyCleanup, ...(maxBytes ? { maxBytes } : {}) }); + cache.setHosts([SERVER_ID]); + return cache; +} + +function workspace(name: string) { + return normalizeWorkspaceDescriptor({ + id: "workspace-1", + projectId: "project-1", + projectDisplayName: "Paseo", + projectRootPath: "/repo/paseo", + workspaceDirectory: "/repo/paseo", + projectKind: "git", + workspaceKind: "local_checkout", + name, + status: "running", + statusEnteredAt: "2026-07-18T08:00:00.000Z", + activityAt: null, + archivingAt: null, + diffStat: null, + scripts: [], + }); +} + +const project = normalizeProjectDescriptor({ + projectId: "project-1", + projectDisplayName: "Paseo", + projectRootPath: "/repo/paseo", + projectKind: "git", +}); + +const checkpoint = { + projects: { generation: "g", afterSeq: 31 }, + workspaces: { generation: "g:background", afterSeq: 1494 }, +}; + +// #10206: one tab evicts the host while another tab keeps writing directory deltas. +it("does not store a checkpoint for rows that another tab evicted", async () => { + const databaseName = `replica-cross-tab-${crypto.randomUUID()}`; + const syncingTab = openTab(databaseName); + syncingTab.replaceDirectoryBaseline(SERVER_ID, { + agents: new Map(), + workspaces: new Map([["workspace-1", workspace("main")]]), + projects: new Map([["project-1", project]]), + checkpoint, + }); + await syncingTab.flush(); + + const evictingTab = openTab(databaseName, 8_192); + await evictingTab.readDirectory(SERVER_ID); + evictingTab.commitTimeline(SERVER_ID, "agent-1", { + agentId: "agent-1", + items: [ + { + kind: "assistant_message", + id: "message-1", + text: "x".repeat(16_384), + timestamp: new Date("2026-07-18T08:02:00.000Z"), + timelineCursor: { epoch: "epoch-1", seq: 12 }, + }, + ], + range: { epoch: "epoch-1", startSeq: 1, endSeq: 12 }, + hasOlder: false, + }); + await evictingTab.flush(); + expect((await openTab(databaseName).readDirectory(SERVER_ID)).checkpoint).toBeUndefined(); + + syncingTab.commitDirectoryMutations( + SERVER_ID, + [{ kind: "workspace", type: "upsert", id: "workspace-1", value: workspace("renamed") }], + { ...checkpoint, workspaces: { generation: "g:background", afterSeq: 1495 } }, + ); + await syncingTab.flush(); + + // The second tab wrote over a directory it never saw evicted, so the store rejected the write. + const newTab = await openTab(databaseName).readDirectory(SERVER_ID); + expect(newTab.projects.size).toBe(0); + expect(newTab.checkpoint).toBeUndefined(); +}); diff --git a/packages/app/src/runtime/replica-cache/index.ts b/packages/app/src/runtime/replica-cache/index.ts index dcae145500..ef65721e23 100644 --- a/packages/app/src/runtime/replica-cache/index.ts +++ b/packages/app/src/runtime/replica-cache/index.ts @@ -402,9 +402,9 @@ const DirectoryCheckpointSchema = z.strictObject({ // A checkpoint is trusted only when this version wrote it. Earlier writers could store one for a // directory the cache no longer held: unversioned ones after an overlapping refresh, version 1 -// after an eviction. Rejecting them revalidates directory contents once without evicting cached -// rows or timelines. -const DIRECTORY_CHECKPOINT_VERSION = 2; +// after an eviction, version 2 after another tab evicted the host. Rejecting them revalidates +// directory contents once without evicting cached rows or timelines. +const DIRECTORY_CHECKPOINT_VERSION = 3; const StoredDirectoryCheckpointSchema = z.strictObject({ version: z.literal(DIRECTORY_CHECKPOINT_VERSION), @@ -1180,11 +1180,12 @@ export class ReplicaCache { // A repair is queued behind writes that can evict its host. If one did, the host has no // directory left for the repaired checkpoint to describe, so only the deletes still apply. + // A shared store also rejects the repair when another connection rewrote the directory. private applyRepair(serverId: string, changes: ReplicaRowChanges): Promise { return this.queueOperation(async () => { const applied = this.invalidatedHosts.has(serverId) ? { ...changes, upserts: [] } : changes; - await this.rowStore.apply(applied); - this.applyStoredChanges(applied); + const accepted = await this.rowStore.apply(applied, { directoryBaselines: new Set() }); + this.applyStoredChanges(accepted ?? applied); }); } @@ -1323,12 +1324,21 @@ export class ReplicaCache { await this.ensureStoredIndex(); const changes = this.materializePendingChanges(pending); const { changes: boundedChanges, evicted } = await this.fitChangesToBudget(changes); - if (boundedChanges.upserts.length > 0 || boundedChanges.deletes.length > 0) { - await this.rowStore.apply(boundedChanges); - this.applyStoredChanges(boundedChanges); + const baselines = new Set( + [...pending.baselines].filter((serverId) => !evicted.has(serverId)), + ); + if ( + baselines.size > 0 || + boundedChanges.upserts.length > 0 || + boundedChanges.deletes.length > 0 + ) { + const accepted = await this.rowStore.apply(boundedChanges, { + directoryBaselines: baselines, + }); + this.applyStoredChanges(accepted ?? boundedChanges); } - for (const serverId of pending.baselines) { - if (!evicted.has(serverId)) this.invalidatedHosts.delete(serverId); + for (const serverId of baselines) { + this.invalidatedHosts.delete(serverId); } } catch { this.restorePendingChanges(pending); diff --git a/packages/app/src/runtime/replica-cache/row-store.ts b/packages/app/src/runtime/replica-cache/row-store.ts index b9cd02d99c..8aaacba623 100644 --- a/packages/app/src/runtime/replica-cache/row-store.ts +++ b/packages/app/src/runtime/replica-cache/row-store.ts @@ -17,6 +17,12 @@ export interface ReplicaRowChanges { deletes: ReplicaRowKey[]; } +export interface ReplicaRowApplyOptions { + // Hosts whose whole directory these changes replace. Passing the option, even empty, asks a + // shared store to reject directory changes for hosts another connection rewrote since. + directoryBaselines?: ReadonlySet; +} + export interface ReplicaHostRows { serverId: string; rows: ReplicaRow[]; @@ -30,7 +36,12 @@ export interface ReplicaRowStore { ids?: readonly string[], ): Promise; readAll(): Promise; - apply(changes: ReplicaRowChanges): Promise; + // Shared stores can reject directory deltas that no longer match their baseline. + // Return the accepted changes when they differ from the requested changes. + apply( + changes: ReplicaRowChanges, + options?: ReplicaRowApplyOptions, + ): Promise; deleteHost(serverId: string): Promise; renameHost(oldServerId: string, newServerId: string): Promise; clear(): Promise; diff --git a/packages/app/src/runtime/replica-cache/row-store.web.browser.test.ts b/packages/app/src/runtime/replica-cache/row-store.web.browser.test.ts new file mode 100644 index 0000000000..ea09f84426 --- /dev/null +++ b/packages/app/src/runtime/replica-cache/row-store.web.browser.test.ts @@ -0,0 +1,48 @@ +import { expect, it } from "vitest"; +import { createIndexedDbReplicaRowStore } from "./row-store.web"; +import { REPLICA_SINGLETON_ROW_ID, type ReplicaRow } from "./row-store"; + +it("rejects directory deltas from a connection whose shared baseline was evicted", async () => { + const databaseName = `replica-eviction-${crypto.randomUUID()}`; + const first = createIndexedDbReplicaRowStore({ databaseName, schemaVersion: 1 }); + const second = createIndexedDbReplicaRowStore({ databaseName, schemaVersion: 1 }); + const serverId = "host"; + const kinds = ["agent", "checkpoint", "project", "workspace"] as const; + const checkpoint: ReplicaRow = { + serverId, + kind: "checkpoint", + id: REPLICA_SINGLETON_ROW_ID, + payload: "checkpoint", + }; + const project: ReplicaRow = { serverId, kind: "project", id: "project", payload: "project" }; + const workspace: ReplicaRow = { + serverId, + kind: "workspace", + id: "workspace", + payload: "workspace", + }; + const timeline: ReplicaRow = { serverId, kind: "timeline", id: "agent", payload: "timeline" }; + const replace = { directoryBaselines: new Set([serverId]) }; + const delta = { + upserts: [checkpoint, { ...workspace, payload: "updated workspace" }, timeline], + deletes: [], + }; + + const incremental = { directoryBaselines: new Set() }; + const baseline = { upserts: [checkpoint, project, workspace], deletes: [] }; + await first.open(); + await second.open(); + await first.apply(baseline, replace); + expect(await second.read(serverId, kinds)).toEqual([checkpoint, project, workspace]); + await second.apply(delta, incremental); + expect(await first.read(serverId, kinds)).toEqual([checkpoint, project, delta.upserts[1]]); + + await first.deleteHost(serverId); + await second.apply(delta, incremental); + expect(await first.read(serverId, kinds)).toEqual([]); + expect(await first.read(serverId, ["timeline"])).toEqual([timeline]); + + await first.apply(baseline, replace); + await second.apply(delta, incremental); + expect(await first.read(serverId, kinds)).toEqual([checkpoint, project, workspace]); +}); diff --git a/packages/app/src/runtime/replica-cache/row-store.web.ts b/packages/app/src/runtime/replica-cache/row-store.web.ts index 12f484bd91..9c1299a1e7 100644 --- a/packages/app/src/runtime/replica-cache/row-store.web.ts +++ b/packages/app/src/runtime/replica-cache/row-store.web.ts @@ -1,5 +1,11 @@ -import type { ReplicaHostRows, ReplicaRow, ReplicaRowChanges, ReplicaRowStore } from "./row-store"; -import { REPLICA_ROW_STORE_SCHEMA_VERSION } from "./row-store-schema"; +import type { + ReplicaHostRows, + ReplicaRow, + ReplicaRowApplyOptions, + ReplicaRowChanges, + ReplicaRowStore, +} from "./row-store"; +import { REPLICA_ROW_STORE_SCHEMA_VERSION, REPLICA_SINGLETON_ROW_ID } from "./row-store-schema"; export type { ReplicaHostRows, @@ -16,6 +22,16 @@ const DATABASE_VERSION = 1; const ROWS_STORE = "rows"; const META_STORE = "meta"; const SCHEMA_VERSION_KEY = "schema_version"; +const DIRECTORY_KINDS = ["agent", "checkpoint", "project", "workspace"] as const; + +interface IndexedDbReplicaRow extends ReplicaRow { + directoryRevision?: string; +} + +function withoutDirectoryRevision(row: IndexedDbReplicaRow): ReplicaRow { + if (row.directoryRevision === undefined) return row; + return { serverId: row.serverId, kind: row.kind, id: row.id, payload: row.payload }; +} interface IndexedDbReplicaRowStoreOptions { databaseName: string; @@ -91,6 +107,12 @@ export function createIndexedDbReplicaRowStore( ): ReplicaRowStore { let database: IDBDatabase | null = null; let opening: Promise | null = null; + const observedDirectoryRevisions = new Map(); + + function observeDirectoryRevision(serverId: string, revision: string | undefined): void { + if (revision === undefined) observedDirectoryRevisions.delete(serverId); + else observedDirectoryRevisions.set(serverId, revision); + } function getDatabase(): IDBDatabase { if (!database) throw new Error("Replica row store has not been opened"); @@ -125,12 +147,14 @@ export function createIndexedDbReplicaRowStore( async function readAll(): Promise { const transaction = getDatabase().transaction(ROWS_STORE, "readonly"); const completion = transactionComplete(transaction); - const rows = await requestResult(transaction.objectStore(ROWS_STORE).getAll()); + const rows = await requestResult( + transaction.objectStore(ROWS_STORE).getAll(), + ); await completion; const hosts = new Map(); for (const row of rows) { const hostRows = hosts.get(row.serverId) ?? []; - hostRows.push(row); + hostRows.push(withoutDirectoryRevision(row)); hosts.set(row.serverId, hostRows); } return Array.from(hosts, ([serverId, hostRows]) => ({ serverId, rows: hostRows })); @@ -148,36 +172,127 @@ export function createIndexedDbReplicaRowStore( const requests = ids ? kinds.flatMap((kind) => ids.map(async (id) => { - const row = await requestResult( + const row = await requestResult( store.get([serverId, kind, id]), ); return row ? [row] : []; }), ) : kinds.map((kind) => - requestResult( + requestResult( store.getAll(IDBKeyRange.bound([serverId, kind], [serverId, kind, []])), ), ); const rows = (await Promise.all(requests)).flat(); await completion; - return rows.sort((left, right) => - left.kind === right.kind - ? left.id.localeCompare(right.id) - : left.kind.localeCompare(right.kind), - ); + if (!ids && DIRECTORY_KINDS.every((kind) => kinds.includes(kind))) { + const checkpoint = rows.find( + (row) => row.kind === "checkpoint" && row.id === REPLICA_SINGLETON_ROW_ID, + ); + observeDirectoryRevision(serverId, checkpoint?.directoryRevision); + } + return rows + .map(withoutDirectoryRevision) + .sort((left, right) => + left.kind === right.kind + ? left.id.localeCompare(right.id) + : left.kind.localeCompare(right.kind), + ); } - async function apply(changes: ReplicaRowChanges): Promise { + async function apply( + changes: ReplicaRowChanges, + { directoryBaselines }: ReplicaRowApplyOptions = {}, + ): Promise { + let accepted = changes; + const nextRevisions = new Map(); await runTransaction(getDatabase(), ROWS_STORE, async (transaction) => { const rows = transaction.objectStore(ROWS_STORE); - for (const key of changes.deletes) { + if (directoryBaselines) { + accepted = await prepareDirectoryWrite({ + rows, + changes, + directoryBaselines, + nextRevisions, + }); + } + for (const key of accepted.deletes) { await requestResult(rows.delete([key.serverId, key.kind, key.id])); } - for (const row of changes.upserts) { - await requestResult(rows.put(row)); + for (const row of accepted.upserts) { + const directoryRevision = + row.kind === "checkpoint" ? nextRevisions.get(row.serverId) : undefined; + await requestResult(rows.put(directoryRevision ? { ...row, directoryRevision } : row)); } }); + for (const [serverId, revision] of nextRevisions) observeDirectoryRevision(serverId, revision); + return accepted === changes ? undefined : accepted; + } + + async function prepareDirectoryWrite(input: { + rows: IDBObjectStore; + changes: ReplicaRowChanges; + directoryBaselines: ReadonlySet; + nextRevisions: Map; + }): Promise { + const { rows, changes, directoryBaselines, nextRevisions } = input; + const hosts = new Set(directoryBaselines); + const checkpoints = new Map(); + for (const row of changes.upserts) { + if (row.kind !== "timeline") hosts.add(row.serverId); + if (row.kind === "checkpoint") checkpoints.set(row.serverId, row); + } + for (const row of changes.deletes) { + if (row.kind !== "timeline") hosts.add(row.serverId); + } + + const staleHosts = new Set(); + const unbasedHosts = new Set(); + for (const serverId of hosts) { + const replacingBaseline = directoryBaselines.has(serverId); + const current = replacingBaseline + ? undefined + : await requestResult( + rows.get([serverId, "checkpoint", REPLICA_SINGLETON_ROW_ID]), + ); + if (replacingBaseline) { + // A different tab may have added directory rows since this tab indexed the cache. + for (const kind of DIRECTORY_KINDS) { + await requestResult( + rows.delete(IDBKeyRange.bound([serverId, kind], [serverId, kind, []])), + ); + } + } else if (current?.directoryRevision !== observedDirectoryRevisions.get(serverId)) { + staleHosts.add(serverId); + continue; + } else if (!current?.directoryRevision) { + // Targeted lookups can still use these rows, but they do not form a baseline. + unbasedHosts.add(serverId); + continue; + } + + // Rotate the revision even on row-only writes. A tab that missed those changes + // must not publish a checkpoint over them. + const checkpoint = checkpoints.get(serverId); + const revision = + checkpoint || current ? crypto.getRandomValues(new Uint32Array(4)).join(":") : undefined; + nextRevisions.set(serverId, revision); + if (!checkpoint && current) { + await requestResult(rows.put({ ...current, directoryRevision: revision })); + } + } + if (staleHosts.size === 0 && unbasedHosts.size === 0) return changes; + return { + deletes: changes.deletes.filter( + (row) => row.kind === "timeline" || !staleHosts.has(row.serverId), + ), + upserts: changes.upserts.filter( + (row) => + row.kind === "timeline" || + (!staleHosts.has(row.serverId) && + (row.kind !== "checkpoint" || !unbasedHosts.has(row.serverId))), + ), + }; } async function deleteHost(serverId: string): Promise { @@ -199,6 +314,11 @@ export function createIndexedDbReplicaRowStore( await requestResult(rows.delete([row.serverId, row.kind, row.id])); } }); + const revision = observedDirectoryRevisions.get(oldServerId); + if (revision !== undefined) { + observedDirectoryRevisions.delete(oldServerId); + observeDirectoryRevision(newServerId, revision); + } } async function clear(): Promise {