diff --git a/docs/architecture.md b/docs/architecture.md index 05ddef9064..2411a0303a 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -403,7 +403,7 @@ initializing → idle ⇄ running client-side dedup; the default fetch page is 200 items. - Timeline row `timestamp` values are canonical daemon-owned timestamps. Providers may supply original replay timestamps, but clients must not guess timestamp trust or hide time UI based on local clock heuristics. - Events stream to connected clients in real time; correctness is backed by authoritative timeline fetches and paged-to-completion catch-up. -- Agent state persists to `$PASEO_HOME/agents/{cwd-with-dashes}/{agent-id}.json`. Timeline rows are runtime memory; provider history is the durable transcript authority and resumed agents rebuild from it. That storage path is derived from `cwd`, not from workspace id. +- Agent state persists to `$PASEO_HOME/agents/{cwd-with-dashes}/{agent-id}.json`. That storage path is derived from `cwd`, not from workspace id. Timeline rows persist in the daemon database, `$PASEO_HOME/paseo.db`. They are the transcript authority after the first import of provider history. See [owned history](timeline-sync.md#owned-history). ## Right-sidebar boundary: directory-backed vs workspace-owned @@ -479,6 +479,7 @@ Providers that can accept native tool definitions should set `supportsNativePase ``` $PASEO_HOME/ ├── agents/{cwd-with-dashes}/{agent-id}.json # Agent record +├── paseo.db # Daemon database (SQLite): agent timelines ├── projects/projects.json # Project registry ├── projects/workspaces.json # Workspace registry ├── projects/icons/ # Custom project icon images diff --git a/docs/data-model.md b/docs/data-model.md index 14c8d3941f..feced5dd8f 100644 --- a/docs/data-model.md +++ b/docs/data-model.md @@ -34,7 +34,7 @@ Workspace archive runs lifecycle teardown from the exact `cwd` but removes only `worktreeRoot` after its last active reference disappears. Worktree recovery recreates that backing checkout from `mainRepoRoot`, then restores the relative path from `worktreeRoot` to `cwd`. -Paseo uses **file-based JSON persistence** instead of a traditional database. All data is validated at runtime with Zod schemas. Most stores write atomically (write to temp file, then rename); a few still use plain `writeFile` — see each section. There is no schema-versioning/migration framework — schemas rely on optional fields with defaults for forward compatibility, with a small amount of inline normalization in `persisted-config.ts` for legacy provider/speech entries. +Paseo persists most stores as JSON files, and agent timelines in the [daemon database](#daemon-database). JSON data is validated at runtime with Zod schemas. Most JSON stores write atomically (write to temp file, then rename); a few still use plain `writeFile` — see each section. JSON stores have no schema-versioning/migration framework — schemas rely on optional fields with defaults for forward compatibility, with a small amount of inline normalization in `persisted-config.ts` for legacy provider/speech entries. All server-side stores live under `$PASEO_HOME` (defaults to `~/.paseo`). @@ -53,6 +53,7 @@ $PASEO_HOME/ ├── daemon-keypair.json # E2EE keypair for relay (mode 0600) ├── paseo.pid # Daemon PID lock file ├── local-credential # Per-run local client credential (mode 0600) +├── paseo.db # Daemon database (SQLite, with -wal and -shm files) ├── daemon.log # Default log file (path configurable) ├── agents/ │ └── {sanitized-cwd}/ @@ -181,11 +182,39 @@ Terminal activity contributes to the workspace status bucket **per `workspaceId` --- -## Runtime-only Agent Timelines +## Daemon database -Agent timelines are not written to `$PASEO_HOME`. `AgentTimeline` owns each agent's history behind -a backend, and the only backend is in memory, so a daemon restart loses it and the next resume -imports provider history. See [owned history](timeline-sync.md#owned-history). +`$PASEO_HOME/paseo.db` is one SQLite file that the daemon opens at startup with `node:sqlite` +(`packages/server/src/server/database/`). Agent timelines are its only store today. Each store is a +`SchemaModule`: its own table-name prefix and an append-only list of migrations. + +- **Migrations.** Startup runs every module's pending migrations in one transaction, so a failed + migration leaves the file as it was. `schema_versions` records each module's version and + `min_reader_version`. Mark a migration `breaking` when an older daemon cannot read the result, + for example a dropped or renamed column. An older daemon then refuses to start with + `DatabaseSchemaTooNewError`. Additive migrations leave older daemons working, and they ignore + modules they do not know. This matters because the app and the daemon update separately, and a + user can run an older daemon on the same `$PASEO_HOME`. +- **Failure.** A file that SQLite cannot open stops the daemon with `DatabaseOpenError`, which + names the path. The daemon does not delete or recreate the file. +- **Durability.** The database uses WAL with `synchronous = NORMAL`. A power loss can drop the + last commits but does not corrupt the file. +- **Checkpoints.** A checkpoint syncs the file to disk and takes up to 100 ms. SQLite's + auto-checkpoint runs it on the committing thread, which stalled the event loop during streaming. + The daemon turns it off and checkpoints from a worker thread with its own connection. If the + worker exits, the daemon turns auto-checkpoint back on. +- **Transactions.** `write` and `read` callbacks are synchronous, so a transaction never spans an + `await` and transactions never interleave. +- **Node.** `node:sqlite` needs Node 22.16 or later. Node 22 prints an experimental warning once, + when the daemon opens the database. + +### Agent timelines + +`AgentTimeline` owns each agent's history, and its SQLite backend stores the projected rows, the +source ranges, retirements, the open rewind, and provider children in `timeline_*` tables. The text +of a streamed assistant or reasoning message is stored as one chunk per source event, beside its +row, so a chunk never rewrites the message. An earlier file store rewrote the whole transcript on +every update. See [owned history](timeline-sync.md#owned-history). --- diff --git a/docs/timeline-sync.md b/docs/timeline-sync.md index eef0ed1287..056b0c9181 100644 --- a/docs/timeline-sync.md +++ b/docs/timeline-sync.md @@ -54,11 +54,11 @@ deleting the agent, or a provider removing one of its own children, deletes hist `AgentTimeline` serializes every operation of one agent, child scopes included, and keeps its state in an `AgentTimelineBackend`: the sequence, the rows and retirements, prompt identities, the open rewind, and the children. The backend contract suite is `agent-timeline.test.ts`, run over -`TIMELINE_CONTRACT_BACKENDS` in `timeline/testing.ts`. The only backend keeps everything in -memory, so a daemon restart loses the owned history: the next resume imports provider history into -a new epoch, and clients take the destructive reset below. Rewinds retired before the restart come -back if the provider history still holds them. Retained history costs memory for every loaded, -closed or archived agent until the daemon exits or the agent is deleted. +`TIMELINE_CONTRACT_BACKENDS` in `timeline/testing.ts`. The daemon uses the SQLite backend in the +[daemon database](data-model.md#daemon-database). History, retirements, the open rewind, and +provider children survive a daemon restart in the same epoch, so clients keep their cursors. A +closed or archived agent holds no history in memory. Each fetch reads the page from the database +and starts no provider. The memory backend serves tests. An open rewind is stored with the history. Resuming an agent whose history holds one settles it before the agent takes prompts: a recorded provider cut is committed, and an unknown outcome is diff --git a/package-lock.json b/package-lock.json index 51a812463e..c2fdcf6eee 100644 --- a/package-lock.json +++ b/package-lock.json @@ -45,6 +45,9 @@ "react-dom": "19.2.3", "typescript": "^5.9.3", "ws": "^8.20.0" + }, + "engines": { + "node": ">=22.16.0" } }, "node_modules/@0no-co/graphql.web": { @@ -39719,6 +39722,9 @@ "typescript": "^5.2.2", "vitest": "^4.1.6", "zx": "^8.8.5" + }, + "engines": { + "node": ">=22.16.0" } }, "packages/cli/node_modules/@vitest/expect": { @@ -40646,7 +40652,7 @@ "@playwright/test": "^1.56.1", "@types/express": "^4.17.20", "@types/markdown-it": "^14.2.0", - "@types/node": "^20.9.0", + "@types/node": "^22.16.0", "@types/qrcode": "^1.5.6", "@types/uuid": "^9.0.7", "@types/ws": "^8.5.8", @@ -40654,6 +40660,9 @@ "cross-env": "^10.1.0", "tsx": "^4.6.0", "vitest": "^4.1.6" + }, + "engines": { + "node": ">=22.16.0" } }, "packages/server/node_modules/@esbuild/aix-ppc64": { @@ -41101,6 +41110,16 @@ "@types/mdurl": "^2" } }, + "packages/server/node_modules/@types/node": { + "version": "22.20.5", + "resolved": "https://registry.npmjs.org/@types/node/-/node-22.20.5.tgz", + "integrity": "sha512-U2+DNr+wSjpsTS/wZGYHq7GcwfuSmKiKvoPvK22zwTlRhU91yOniN4qRR5KhIjvif7ysw/dz/hKmfDH0Ris4aA==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~6.21.0" + } + }, "packages/server/node_modules/@vitest/expect": { "version": "4.1.6", "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.1.6.tgz", diff --git a/package.json b/package.json index 52be558ceb..f18e2723d5 100644 --- a/package.json +++ b/package.json @@ -169,5 +169,8 @@ "tiny-async-pool": { "semver@^5": "5.7.2" } + }, + "engines": { + "node": ">=22.16.0" } } diff --git a/packages/cli/package.json b/packages/cli/package.json index 825f650e49..36aca6de12 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -47,5 +47,8 @@ "typescript": "^5.2.2", "vitest": "^4.1.6", "zx": "^8.8.5" + }, + "engines": { + "node": ">=22.16.0" } } diff --git a/packages/server/package.json b/packages/server/package.json index 99b228d1a3..6d137f1701 100644 --- a/packages/server/package.json +++ b/packages/server/package.json @@ -160,7 +160,7 @@ "@playwright/test": "^1.56.1", "@types/express": "^4.17.20", "@types/markdown-it": "^14.2.0", - "@types/node": "^20.9.0", + "@types/node": "^22.16.0", "@types/qrcode": "^1.5.6", "@types/uuid": "^9.0.7", "@types/ws": "^8.5.8", @@ -171,5 +171,8 @@ }, "overrides": { "lightningcss": "1.30.1" + }, + "engines": { + "node": ">=22.16.0" } } diff --git a/packages/server/src/server/agent/agent-manager.test.ts b/packages/server/src/server/agent/agent-manager.test.ts index 250747b058..58a9bebec9 100644 --- a/packages/server/src/server/agent/agent-manager.test.ts +++ b/packages/server/src/server/agent/agent-manager.test.ts @@ -6881,6 +6881,50 @@ test("archiveSnapshot restoring an earlier archive time on a loaded agent keeps expect(events.at(-1)?.updatedAt.getTime()).toBeGreaterThanOrEqual(unarchivedAt); }); +test("a turn ends even when the timeline fails to record how it ended", async () => { + const workdir = mkdtempSync(join(tmpdir(), "agent-manager-terminal-record-failure-")); + class FailingTurnClient extends TestAgentClient { + readonly session = new TestAgentSession({ provider: "codex", cwd: workdir }); + + override async createSession(): Promise { + return this.session; + } + } + const client = new FailingTurnClient(); + const backend = new DeferredTimelineBackend(); + const manager = new AgentManager({ + clients: { codex: client }, + timeline: new AgentTimeline(backend), + logger, + }); + onTestFinished(async () => { + await manager.closeAgent(agent.id); + await manager.flush(); + rmSync(workdir, { recursive: true, force: true }); + }); + const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, { + workspaceId: undefined, + }); + const running = waitForAgentLifecycle(manager, agent.id, "running"); + client.session.pushEvent({ type: "turn_started", provider: "codex", turnId: "failed-turn" }); + await running; + const failed = waitForAgentLifecycle(manager, agent.id, "error"); + // The turn's error message is the write that fails. + backend.failNextAppend = true; + client.session.pushEvent({ + type: "turn_failed", + provider: "codex", + turnId: "failed-turn", + error: "Selected model is at capacity.", + }); + await failed; + expect(manager.getAgent(agent.id)?.lifecycle).toBe("error"); + // The failed turn no longer holds the agent: its next turn runs and records. + const runningAgain = waitForAgentLifecycle(manager, agent.id, "running"); + client.session.pushEvent({ type: "turn_started", provider: "codex", turnId: "next-turn" }); + await runningAgain; +}); + test("markAgentUnread restores error attention on a read errored agent", async () => { const workdir = mkdtempSync(join(tmpdir(), "agent-manager-mark-unread-error-")); const storage = new AgentStorage(join(workdir, "agents"), logger); diff --git a/packages/server/src/server/agent/agent-manager.ts b/packages/server/src/server/agent/agent-manager.ts index 9dc92c8a06..580e5358ad 100644 --- a/packages/server/src/server/agent/agent-manager.ts +++ b/packages/server/src/server/agent/agent-manager.ts @@ -511,6 +511,16 @@ interface HandleStreamEventOptions { fromHistory?: boolean; } +interface StreamEventDispatch { + agent: ActiveManagedAgent; + event: AgentStreamEvent; + options: HandleStreamEventOptions | undefined; + isForegroundEvent: boolean; + eventTurnId: string | undefined; + terminalDisposition: ActiveTurnTerminalDisposition; + flags: StreamEventFlags; +} + interface ManagedAgentBase { id: string; provider: AgentProvider; @@ -5447,11 +5457,9 @@ export class AgentManager { ); } - event = await this.settleTurnMetrics({ agent, event, options, terminalDisposition }); - const flags: StreamEventFlags = { shouldDispatchEvent: true, shouldNotifyWaiters: true }; - const dispatchPromise = this.dispatchStreamEventByType({ + event = await this.recordStreamEvent({ agent, event, options, @@ -5460,9 +5468,6 @@ export class AgentManager { terminalDisposition, flags, }); - if (dispatchPromise) { - await dispatchPromise; - } if (!options?.fromHistory) { if (isTurnTerminalEvent(event)) { @@ -5574,15 +5579,26 @@ export class AgentManager { this.emitState(agent); } - private dispatchStreamEventByType(params: { - agent: ActiveManagedAgent; - event: AgentStreamEvent; - options: HandleStreamEventOptions | undefined; - isForegroundEvent: boolean; - eventTurnId: string | undefined; - terminalDisposition: ActiveTurnTerminalDisposition; - flags: StreamEventFlags; - }): Promise | undefined { + /** Stamps the turn's metrics and applies the event by type, returning the event as stamped. */ + private async recordStreamEvent(params: StreamEventDispatch): Promise { + const { agent, options, eventTurnId } = params; + let { event } = params; + try { + event = await this.settleTurnMetrics({ ...params, event }); + await this.dispatchStreamEventByType({ ...params, event }); + } catch (error) { + // A turn that ended must stop holding the agent and its waiters, even when its record + // failed to write; otherwise the agent stays running until the daemon restarts. + if (options?.fromHistory || !isTurnTerminalEvent(event)) throw error; + this.logger.error( + { err: error, agentId: agent.id, turnId: eventTurnId, eventType: event.type }, + "Failed to record how the turn ended", + ); + } + return event; + } + + private dispatchStreamEventByType(params: StreamEventDispatch): Promise | undefined { const { agent, event, options, isForegroundEvent, eventTurnId, terminalDisposition, flags } = params; switch (event.type) { diff --git a/packages/server/src/server/agent/timeline-projection.ts b/packages/server/src/server/agent/timeline-projection.ts index b698f934ae..2a0c97f398 100644 --- a/packages/server/src/server/agent/timeline-projection.ts +++ b/packages/server/src/server/agent/timeline-projection.ts @@ -332,7 +332,7 @@ function mergeAssistantChunks(entries: readonly WorkingEntry[]): WorkingEntry[] /** A retained item. `seq` is its latest source event, not its display anchor. */ export type ProjectedTimelineRow = AgentTimelineRow & TimelineProjectionEntry; -interface ProjectedTimelinePageOptions { +export interface ProjectedTimelinePageOptions { wholeTurns?: boolean; bounds: { minSeq: number; maxSeq: number }; direction: TimelineLimitDirection; @@ -340,6 +340,61 @@ interface ProjectedTimelinePageOptions { limit?: number; } +/** + * How a new source row lands in a projection: + * - `identity`: it updates `identityRow`, the active row with the same item identity; + * - `adjacent`: it continues `lastRow`, the last active row (streamed assistant or reasoning text); + * - `new`: it becomes a new last row. + * The result is the whole projected row. For `adjacent`, a merged text is `lastRow`'s text followed + * by the new chunk, so a `lastRow` passed with empty text yields the chunk alone. + */ +export type TimelineRowFold = + | { kind: "identity"; row: ProjectedTimelineRow } + | { kind: "adjacent"; row: ProjectedTimelineRow } + | { kind: "new"; row: ProjectedTimelineRow }; + +export function foldTimelineRow(input: { + row: AgentTimelineRow; + /** The row the projection holds for `timelineItemIdentity(row.item)`, if any. */ + identityRow: ProjectedTimelineRow | undefined; + lastRow: ProjectedTimelineRow | undefined; +}): TimelineRowFold { + const entry = makeCanonicalEntries([input.row])[0]; + const merged = input.identityRow ? mergeIdentityEntries(input.identityRow, entry) : null; + if (merged) return { kind: "identity", row: { ...merged, seq: merged.seqEnd } }; + const previous = input.lastRow; + const adjacent = previous + ? mergeReasoningChunks(mergeAssistantChunks([previous, entry])) + : [entry]; + if (previous && adjacent.length === 1) { + return { kind: "adjacent", row: { ...adjacent[0], seq: adjacent[0].seqEnd } }; + } + return { kind: "new", row: { ...entry, seq: entry.seqEnd } }; +} + +/** + * Merges neighbouring retirements that no active row separates. Merging keeps the meaning (drop + * rows anchored in `[retireFromSeq, seq)`) and bounds the count by the active rows in the span. + */ +export function coalesceTimelineRetirements( + retirements: readonly TimelineRetirement[], + hasActiveAnchorIn: (startSeq: number, endSeq: number) => boolean, +): TimelineRetirement[] { + const coalesced: TimelineRetirement[] = []; + for (const retirement of retirements) { + const previous = coalesced.at(-1); + if (previous && !hasActiveAnchorIn(previous.seq, retirement.retireFromSeq)) { + coalesced[coalesced.length - 1] = { + seq: retirement.seq, + retireFromSeq: Math.min(previous.retireFromSeq, retirement.retireFromSeq), + }; + continue; + } + coalesced.push({ ...retirement }); + } + return coalesced; +} + /** Owns projected state; source events are consumed, never retained. */ export class TimelineProjection { private readonly rows: ProjectedTimelineRow[] = []; @@ -375,28 +430,26 @@ export class TimelineProjection { } private appendProjected(row: AgentTimelineRow): number { - const entry = makeCanonicalEntries([row])[0]; const identity = timelineItemIdentity(row.item); const index = identity === null ? undefined : this.identities.get(identity); - const existing = index === undefined ? undefined : this.rows[index]; - const merged = existing ? mergeIdentityEntries(existing, entry) : null; - if (merged && index !== undefined) { - this.rows[index] = { ...merged, seq: merged.seqEnd }; + const fold = foldTimelineRow({ + row, + identityRow: index === undefined ? undefined : this.rows[index], + lastRow: this.rows.at(-1), + }); + if (fold.kind === "identity" && index !== undefined) { + this.rows[index] = fold.row; this.extendSpan(index); return index; } - const previous = this.rows.at(-1); - const adjacent = previous - ? mergeReasoningChunks(mergeAssistantChunks([previous, entry])) - : [entry]; - if (previous && adjacent.length === 1) { - const mergedText = adjacent[0]; - this.rows[this.rows.length - 1] = { ...mergedText, seq: mergedText.seqEnd }; + if (fold.kind === "adjacent") { + this.rows[this.rows.length - 1] = fold.row; this.extendSpan(this.rows.length - 1); return this.rows.length - 1; } + const entry = fold.row; if (identity !== null) this.identities.set(identity, this.rows.length); - this.rows.push({ ...entry, seq: entry.seqEnd }); + this.rows.push(entry); const last = this.spans.at(-1); if (last && last.endSeq >= entry.seqStart) { last.endSeq = Math.max(last.endSeq, entry.seqEnd); @@ -516,19 +569,9 @@ export class TimelineProjection { } private coalesceRetirements(retirements: readonly TimelineRetirement[]): TimelineRetirement[] { - const coalesced: TimelineRetirement[] = []; - for (const retirement of retirements) { - const previous = coalesced.at(-1); - if (previous && !this.hasActiveAnchorIn(previous.seq, retirement.retireFromSeq)) { - coalesced[coalesced.length - 1] = { - seq: retirement.seq, - retireFromSeq: Math.min(previous.retireFromSeq, retirement.retireFromSeq), - }; - continue; - } - coalesced.push({ ...retirement }); - } - return coalesced; + return coalesceTimelineRetirements(retirements, (startSeq, endSeq) => + this.hasActiveAnchorIn(startSeq, endSeq), + ); } private hasActiveAnchorIn(startSeq: number, endSeq: number): boolean { @@ -693,7 +736,7 @@ export class TimelineProjection { const start = input.wholeTurns ? this.wholeTurnWindowStart(requestedStart) : requestedStart; // Choose the window before extending the right edge, so a prompt jump // cannot lose its target when the next turn is arbitrarily large. - if (input.wholeTurns) { + if (input.wholeTurns && low > 0) { while (low < this.rows.length && continuesProjectedTurn(this.rows[low - 1], this.rows[low])) low++; } @@ -898,7 +941,7 @@ interface ProjectedEntryCandidate { firstSourceSeq: number; } -function selectProjectedEntriesAfter(input: { +export function selectProjectedEntriesAfter(input: { entries: readonly TimelineProjectionEntry[]; /** Seqs covered without an active row; they advance the cursor but add no entry. */ covered?: readonly TimelineSeqRange[]; @@ -940,7 +983,7 @@ function selectProjectedEntriesAfter(input: { }; } -function continuesProjectedTurn( +export function continuesProjectedTurn( previous: TimelineProjectionEntry, next: TimelineProjectionEntry, ): boolean { diff --git a/packages/server/src/server/agent/timeline/index.ts b/packages/server/src/server/agent/timeline/index.ts index 4b6bcb1ed3..a0e9e8d888 100644 --- a/packages/server/src/server/agent/timeline/index.ts +++ b/packages/server/src/server/agent/timeline/index.ts @@ -1,5 +1,10 @@ +import type { DaemonDatabase } from "../../database/index.js"; +import { AgentTimeline } from "./internal/agent-timeline.js"; +import { SqliteTimelineBackend } from "./internal/sqlite-backend.js"; + export { AgentTimeline, + TimelineClosedError, TimelineRewindBoundaryError, TimelineRewindPendingError, TimelineRewindTargetError, @@ -19,3 +24,9 @@ export { type TimelineScope, type TimelineSeed, } from "./internal/agent-timeline.js"; +export { timelineSchema } from "./internal/sqlite-backend.js"; + +/** The daemon's timeline, stored in the daemon database. Open the database with `timelineSchema`. */ +export function createStoredAgentTimeline(database: DaemonDatabase): AgentTimeline { + return new AgentTimeline(new SqliteTimelineBackend(database)); +} diff --git a/packages/server/src/server/agent/timeline/internal/agent-timeline.ts b/packages/server/src/server/agent/timeline/internal/agent-timeline.ts index 5c052c80c6..03d5ecdaf1 100644 --- a/packages/server/src/server/agent/timeline/internal/agent-timeline.ts +++ b/packages/server/src/server/agent/timeline/internal/agent-timeline.ts @@ -72,6 +72,14 @@ export type TimelineRewindVerdict = | { kind: "absent" }; /** Another rewind is open on the history; it must settle first. */ +/** The timeline was closed for shutdown; it takes no more operations. */ +export class TimelineClosedError extends Error { + constructor() { + super("The agent timeline is closed"); + this.name = "TimelineClosedError"; + } +} + export class TimelineRewindPendingError extends Error { constructor(readonly intent: TimelineRewindIntent) { super("Another rewind of this conversation has not settled"); @@ -153,6 +161,7 @@ export interface TimelineAppendOptions { export class AgentTimeline { private readonly tails = new Map>(); private readonly sizes = new Map(); + private closed = false; constructor(private readonly backend: AgentTimelineBackend = new MemoryTimelineBackend()) {} @@ -474,9 +483,20 @@ export class AgentTimeline { * Callers use it so an event published outside the timeline cannot overtake queued writes. */ settled(scope: TimelineScope): Promise { + // A closed timeline takes no operations, so the ones already queued are all there is. + if (this.closed) return this.tails.get(scope.agentId) ?? Promise.resolve(); return this.run(scope, settledOperation); } + /** + * Refuses new operations with `TimelineClosedError` and resolves once every operation called + * before it has finished. The daemon calls it before closing the store. + */ + async close(): Promise { + this.closed = true; + await Promise.all(this.tails.values()); + } + /** Projected row count as of the last committed write, for diagnostics. */ residentSize(scope: TimelineScope): number | null { return this.sizes.get(sizeKey(scope)) ?? null; @@ -507,6 +527,7 @@ export class AgentTimeline { } private run(scope: TimelineScope, operation: () => T | Promise): Promise { + if (this.closed) return Promise.reject(new TimelineClosedError()); const key = scope.agentId; const previous = this.tails.get(key) ?? Promise.resolve(); const result = previous.then(operation); diff --git a/packages/server/src/server/agent/timeline/internal/fetch-page.ts b/packages/server/src/server/agent/timeline/internal/fetch-page.ts new file mode 100644 index 0000000000..55851a0af3 --- /dev/null +++ b/packages/server/src/server/agent/timeline/internal/fetch-page.ts @@ -0,0 +1,77 @@ +import { limitAgentTimelineItemContent } from "../../agent-timeline-content.js"; +import type { + AgentTimelineFetchOptions, + AgentTimelineFetchResult, +} from "../../agent-timeline-store-types.js"; +import type { + ProjectedTimelinePageOptions, + ProjectedTimelinePageSelection, +} from "../../timeline-projection.js"; + +const DEFAULT_TIMELINE_FETCH_LIMIT = 200; + +export interface TimelinePageHistory { + epoch: string; + /** 0 before any commit. */ + minSeq: number; + nextSeq: number; + retirementCount: number; +} + +/** + * The fetch contract every backend shares: cursor validation, gap and stale-cursor resets, and the + * served item budget. `selectPage` is the backend's projected page selection. + */ +export function fetchTimelinePage(input: { + history: TimelinePageHistory; + options: AgentTimelineFetchOptions; + selectPage: (options: ProjectedTimelinePageOptions) => ProjectedTimelinePageSelection; +}): AgentTimelineFetchResult { + const { history, options } = input; + const direction = options.direction ?? "tail"; + const cursor = options.cursor; + const hasRows = history.minSeq !== 0; + const window = { + minSeq: history.minSeq, + maxSeq: history.nextSeq - 1, + nextSeq: history.nextSeq, + }; + const staleCursor = + cursor !== undefined && + (cursor.epoch !== history.epoch || + (cursor.retirementCount !== undefined && cursor.retirementCount !== history.retirementCount)); + const gap = + !staleCursor && + direction === "after" && + cursor !== undefined && + hasRows && + cursor.seq < history.minSeq - 1; + const reset = staleCursor || gap; + const page = input.selectPage({ + bounds: window, + direction: reset ? "tail" : direction, + cursorSeq: cursor?.seq, + limit: options.limit ?? DEFAULT_TIMELINE_FETCH_LIMIT, + wholeTurns: options.wholeTurns, + }); + return { + epoch: history.epoch, + direction, + reset, + staleCursor, + gap, + window, + hasOlder: page.hasOlder, + hasNewer: page.hasNewer, + startSeq: page.startSeq, + endSeq: page.endSeq, + // Stored rows are already within budget; this bounds assistant and reasoning merges. + rows: page.entries.map((entry) => + Object.assign({ seq: entry.seqEnd }, entry, { + item: limitAgentTimelineItemContent(entry.item), + }), + ), + retirements: page.retirements, + retirementCount: history.retirementCount, + }; +} diff --git a/packages/server/src/server/agent/timeline/internal/memory-backend.ts b/packages/server/src/server/agent/timeline/internal/memory-backend.ts index 4c0df6d314..adc1340a7f 100644 --- a/packages/server/src/server/agent/timeline/internal/memory-backend.ts +++ b/packages/server/src/server/agent/timeline/internal/memory-backend.ts @@ -1,5 +1,4 @@ import { randomUUID } from "node:crypto"; -import { limitAgentTimelineItemContent } from "../../agent-timeline-content.js"; import type { AgentMetric, AgentTimelineItem } from "../../agent-sdk-types.js"; import type { AgentTimelineFetchOptions, @@ -22,6 +21,8 @@ import type { TimelineSeed, } from "./backend.js"; import { UnknownTimelineError } from "./backend.js"; +import { fetchTimelinePage } from "./fetch-page.js"; +import { buildSourceRow } from "./source-row.js"; interface MemoryTimelineState { epoch: string; @@ -37,8 +38,6 @@ interface MemoryTimelineState { childRetired: boolean; } -const DEFAULT_TIMELINE_FETCH_LIMIT = 200; - function scopeKey(scope: TimelineScope): string { return scope.subagentId === undefined ? scope.agentId @@ -53,17 +52,6 @@ function cloneRow(row: T): T { return { ...row }; } -function buildRow(entry: TimelineEntry, seq: number, timestamp: string): AgentTimelineRow { - return { - seq, - timestamp: entry.timestamp ?? timestamp, - item: entry.item, - ...(entry.turnId ? { turnId: entry.turnId } : {}), - ...(entry.providerMessageId ? { providerMessageId: entry.providerMessageId } : {}), - ...(entry.turnMetrics ? { turnMetrics: entry.turnMetrics } : {}), - }; -} - /** Volatile backend: history lives in process memory and is lost when the daemon exits. */ export class MemoryTimelineBackend implements AgentTimelineBackend { private readonly states = new Map(); @@ -73,7 +61,9 @@ export class MemoryTimelineBackend implements AgentTimelineBackend { const startSeq = seed.nextSeq ?? 1; const rows = seed.rows?.length ? seed.rows.map(cloneRow) - : (seed.entries ?? []).map((entry, index) => buildRow(entry, startSeq + index, timestamp)); + : (seed.entries ?? []).map((entry, index) => + buildSourceRow(entry, startSeq + index, timestamp), + ); const nextSeq = rows.reduce((next, row) => Math.max(next, row.seq + 1), startSeq); const projection = new TimelineProjection(rows); const state: MemoryTimelineState = { @@ -137,7 +127,9 @@ export class MemoryTimelineBackend implements AgentTimelineBackend { append(scope: TimelineScope, entries: readonly TimelineEntry[]): TimelineBackendAppendResult { const state = this.requireState(scope); const timestamp = new Date().toISOString(); - const rows = entries.map((entry, index) => buildRow(entry, state.nextSeq + index, timestamp)); + const rows = entries.map((entry, index) => + buildSourceRow(entry, state.nextSeq + index, timestamp), + ); for (const row of rows) { state.projection.append(row); state.nextSeq = row.seq + 1; @@ -233,48 +225,11 @@ export class MemoryTimelineBackend implements AgentTimelineBackend { fetch(scope: TimelineScope, options: AgentTimelineFetchOptions): AgentTimelineFetchResult { const state = this.requireState(scope); - const direction = options.direction ?? "tail"; - const cursor = options.cursor; - const hasRows = state.minSeq !== 0; - const window = { minSeq: state.minSeq, maxSeq: state.nextSeq - 1, nextSeq: state.nextSeq }; - const staleCursor = - cursor !== undefined && - (cursor.epoch !== state.epoch || - (cursor.retirementCount !== undefined && cursor.retirementCount !== state.retirementCount)); - const gap = - !staleCursor && - direction === "after" && - cursor !== undefined && - hasRows && - cursor.seq < state.minSeq - 1; - const reset = staleCursor || gap; - const page = state.projection.selectPage({ - bounds: window, - direction: reset ? "tail" : direction, - cursorSeq: cursor?.seq, - limit: options.limit ?? DEFAULT_TIMELINE_FETCH_LIMIT, - wholeTurns: options.wholeTurns, + return fetchTimelinePage({ + history: state, + options, + selectPage: (page) => state.projection.selectPage(page), }); - return { - epoch: state.epoch, - direction, - reset, - staleCursor, - gap, - window, - hasOlder: page.hasOlder, - hasNewer: page.hasNewer, - startSeq: page.startSeq, - endSeq: page.endSeq, - // Stored rows are already within budget; this bounds assistant and reasoning merges. - rows: page.entries.map((entry) => - Object.assign({ seq: entry.seqEnd }, entry, { - item: limitAgentTimelineItemContent(entry.item), - }), - ), - retirements: page.retirements, - retirementCount: state.retirementCount, - }; } readRows(scope: TimelineScope): ProjectedTimelineRow[] { diff --git a/packages/server/src/server/agent/timeline/internal/source-row.ts b/packages/server/src/server/agent/timeline/internal/source-row.ts new file mode 100644 index 0000000000..2cf818767c --- /dev/null +++ b/packages/server/src/server/agent/timeline/internal/source-row.ts @@ -0,0 +1,18 @@ +import type { AgentTimelineRow } from "../../agent-timeline-store-types.js"; +import type { TimelineEntry } from "./backend.js"; + +/** The source row an entry commits as, at `seq`. */ +export function buildSourceRow( + entry: TimelineEntry, + seq: number, + timestamp: string, +): AgentTimelineRow { + return { + seq, + timestamp: entry.timestamp ?? timestamp, + item: entry.item, + ...(entry.turnId ? { turnId: entry.turnId } : {}), + ...(entry.providerMessageId ? { providerMessageId: entry.providerMessageId } : {}), + ...(entry.turnMetrics ? { turnMetrics: entry.turnMetrics } : {}), + }; +} diff --git a/packages/server/src/server/agent/timeline/internal/sqlite-backend.ts b/packages/server/src/server/agent/timeline/internal/sqlite-backend.ts new file mode 100644 index 0000000000..deaba6c771 --- /dev/null +++ b/packages/server/src/server/agent/timeline/internal/sqlite-backend.ts @@ -0,0 +1,1220 @@ +import { randomUUID } from "node:crypto"; +import { timelineItemIdentity } from "@getpaseo/protocol/timeline-identity"; +import { continuesTimelineTurn, isTimelineTurnTrigger } from "@getpaseo/protocol/timeline-turn"; +import type { AgentMetric, AgentTimelineItem } from "../../agent-sdk-types.js"; +import type { + AgentTimelineFetchOptions, + AgentTimelineFetchResult, + AgentTimelineRow, +} from "../../agent-timeline-store-types.js"; +import { + TimelineProjection, + coalesceTimelineRetirements, + continuesAssistantMessage, + foldTimelineRow, + selectProjectedEntriesAfter, + type ProjectedTimelinePageOptions, + type ProjectedTimelinePageSelection, + type ProjectedTimelineRow, + type TimelineRetirement, + type TimelineSeqRange, +} from "../../timeline-projection.js"; +import type { ProviderSubagentDescriptor } from "../../provider-subagents/store.js"; +import type { DaemonDatabase, ReadSql, SchemaModule, WriteSql } from "../../../database/index.js"; +import type { + AgentTimelineBackend, + RetiredChildSelector, + TimelineBackendAppendResult, + TimelineBackendRetireResult, + TimelineChild, + TimelineEntry, + TimelineHead, + TimelinePrompt, + TimelineRewindIntent, + TimelineScope, + TimelineSeed, +} from "./backend.js"; +import { UnknownTimelineError } from "./backend.js"; +import { fetchTimelinePage } from "./fetch-page.js"; +import { buildSourceRow } from "./source-row.js"; + +/** + * Tables of the timeline store. `timeline_rows` holds projected rows: `row` is the row's JSON, + * with the text of streamed assistant and reasoning rows kept in `timeline_text` instead, one + * chunk per source row, so a streamed chunk never rewrites the message. `retired_by` is the seq of + * the retirement that took the row out of the conversation. `span_start` marks rows that start a + * source-coverage span (no earlier active row's `seq_end` reaches them). `identity_live` marks the + * row an item identity's next update merges into. `timeline_source_ranges` maps every source seq + * to its active row, or to none for retired rows and retirements. `timeline_retired_keys` holds the + * turn ids and tool call ids late output is dropped for. + */ +const SCHEMA_V1 = ` +CREATE TABLE timeline_scopes ( + id INTEGER PRIMARY KEY, + agent_id TEXT NOT NULL, + subagent_id TEXT, + epoch TEXT NOT NULL, + next_seq INTEGER NOT NULL, + min_seq INTEGER NOT NULL, + active_count INTEGER NOT NULL, + active_max_seq_end INTEGER NOT NULL, + retirement_count INTEGER NOT NULL, + rewind TEXT, + descriptor TEXT, + child_retired INTEGER NOT NULL DEFAULT 0 +); +CREATE UNIQUE INDEX timeline_scopes_root ON timeline_scopes (agent_id) WHERE subagent_id IS NULL; +CREATE UNIQUE INDEX timeline_scopes_child ON timeline_scopes (agent_id, subagent_id) + WHERE subagent_id IS NOT NULL; + +CREATE TABLE timeline_rows ( + scope_id INTEGER NOT NULL REFERENCES timeline_scopes (id) ON DELETE CASCADE, + seq_start INTEGER NOT NULL, + seq_end INTEGER NOT NULL, + retired_by INTEGER, + span_start INTEGER NOT NULL, + identity TEXT, + identity_live INTEGER NOT NULL, + turn_id TEXT, + turn_trigger INTEGER NOT NULL, + item_type TEXT NOT NULL, + client_message_id TEXT, + row TEXT NOT NULL, + PRIMARY KEY (scope_id, seq_start) +); +CREATE INDEX timeline_rows_active ON timeline_rows (scope_id, seq_start) WHERE retired_by IS NULL; +CREATE INDEX timeline_rows_span ON timeline_rows (scope_id, seq_start) + WHERE retired_by IS NULL AND span_start = 1; +CREATE INDEX timeline_rows_identity ON timeline_rows (scope_id, identity) WHERE identity_live = 1; +CREATE INDEX timeline_rows_turn ON timeline_rows (scope_id, turn_id, seq_start) + WHERE retired_by IS NULL AND turn_id IS NOT NULL; +CREATE INDEX timeline_rows_type ON timeline_rows (scope_id, item_type, seq_start) + WHERE retired_by IS NULL; +CREATE INDEX timeline_rows_client_message ON timeline_rows (scope_id, client_message_id) + WHERE client_message_id IS NOT NULL; +CREATE INDEX timeline_rows_retired ON timeline_rows (scope_id, retired_by, seq_start) + WHERE retired_by IS NOT NULL; + +CREATE TABLE timeline_text ( + scope_id INTEGER NOT NULL REFERENCES timeline_scopes (id) ON DELETE CASCADE, + seq_start INTEGER NOT NULL, + seq INTEGER NOT NULL, + text TEXT NOT NULL, + PRIMARY KEY (scope_id, seq_start, seq) +); + +CREATE TABLE timeline_source_ranges ( + scope_id INTEGER NOT NULL REFERENCES timeline_scopes (id) ON DELETE CASCADE, + start_seq INTEGER NOT NULL, + end_seq INTEGER NOT NULL, + row_seq_start INTEGER, + PRIMARY KEY (scope_id, start_seq) +); + +CREATE TABLE timeline_retirements ( + scope_id INTEGER NOT NULL REFERENCES timeline_scopes (id) ON DELETE CASCADE, + seq INTEGER NOT NULL, + retire_from_seq INTEGER NOT NULL, + PRIMARY KEY (scope_id, seq) +); + +CREATE TABLE timeline_retired_keys ( + scope_id INTEGER NOT NULL REFERENCES timeline_scopes (id) ON DELETE CASCADE, + kind TEXT NOT NULL, + key TEXT NOT NULL, + PRIMARY KEY (scope_id, kind, key) +); +`; + +/** The timeline store's schema in the daemon database. */ +export const timelineSchema: SchemaModule = { + name: "timeline", + migrations: [{ up: (sql) => sql.exec(SCHEMA_V1) }], +}; + +interface ScopeRecord { + id: number; + epoch: string; + next_seq: number; + min_seq: number; + active_count: number; + active_max_seq_end: number; + retirement_count: number; + rewind: string | null; + descriptor: string | null; + child_retired: number; +} + +interface RowRecord { + seq_start: number; + item_type: string; + row: string; +} + +/** The columns turn and message boundaries are decided on, without the row's payload. */ +interface RowShape { + seq_start: number; + turn_id: string | null; + turn_trigger: number; + item_type: string; +} + +interface SourceRangeRecord { + start_seq: number; + end_seq: number; + row_seq_start: number | null; +} + +interface RetirementRecord { + seq: number; + retire_from_seq: number; +} + +const SCOPE_COLUMNS = + "id, epoch, next_seq, min_seq, active_count, active_max_seq_end, retirement_count, rewind, " + + "descriptor, child_retired"; +const SHAPE_COLUMNS = "seq_start, turn_id, turn_trigger, item_type"; +const ACTIVE = "scope_id = ? AND retired_by IS NULL"; + +type TextItemType = "assistant_message" | "reasoning"; + +function isTextItemType(type: string): type is TextItemType { + return type === "assistant_message" || type === "reasoning"; +} + +/** Durable backend: history lives in the daemon database and survives restarts. */ +export class SqliteTimelineBackend implements AgentTimelineBackend { + constructor(private readonly database: DaemonDatabase) {} + + create(scope: TimelineScope, seed: TimelineSeed): TimelineHead { + return this.database.write((sql) => describe(createScope(sql, scope, seed))); + } + + delete(scope: TimelineScope): void { + this.database.write((sql) => { + if (scope.subagentId === undefined) { + sql.run("DELETE FROM timeline_scopes WHERE agent_id = ?", scope.agentId); + } else { + sql.run( + "DELETE FROM timeline_scopes WHERE agent_id = ? AND subagent_id = ?", + scope.agentId, + scope.subagentId, + ); + } + }); + } + + head(scope: TimelineScope): TimelineHead | null { + return this.database.read((sql) => { + const record = findScope(sql, scope); + return record ? describe(record) : null; + }); + } + + append(scope: TimelineScope, entries: readonly TimelineEntry[]): TimelineBackendAppendResult { + return this.database.write((sql) => { + const record = requireScope(sql, scope); + const timestamp = new Date().toISOString(); + const rows = entries.map((entry) => { + const row = buildSourceRow(entry, record.next_seq, timestamp); + foldSourceRow(sql, record, row); + record.next_seq = row.seq + 1; + if (record.min_seq === 0) record.min_seq = row.seq; + return row; + }); + saveScopeCounters(sql, record); + // The rows are built for this call, so the caller can own them. + return { rows, head: describe(record) }; + }); + } + + isRetired(scope: TimelineScope, entry: TimelineEntry): boolean { + return this.database.read((sql) => { + const { id } = requireScope(sql, scope); + if (entry.turnId !== undefined && hasRetiredKey(sql, id, "turn", entry.turnId)) return true; + const identity = timelineItemIdentity(entry.item); + if (identity === null || findIdentityRow(sql, id, identity)) return false; + return hasRetiredKey(sql, id, "identity", identity); + }); + } + + prompts(scope: TimelineScope): TimelinePrompt[] { + return this.database.read((sql) => { + const { id } = requireScope(sql, scope); + return sql + .all( + `SELECT seq_start, item_type, row FROM timeline_rows WHERE ${ACTIVE} ` + + "AND item_type = 'user_message' ORDER BY seq_start", + id, + ) + .map((record) => { + const row = parseRow(record); + const item = row.item as Extract; + return { + seqStart: row.seqStart, + messageId: item.messageId, + providerMessageId: row.providerMessageId, + submitted: item.clientMessageId !== undefined, + }; + }); + }); + } + + setRewind(scope: TimelineScope, rewind: TimelineRewindIntent | null): TimelineHead { + return this.database.write((sql) => { + const record = requireScope(sql, scope); + record.rewind = rewind ? JSON.stringify(rewind) : null; + sql.run("UPDATE timeline_scopes SET rewind = ? WHERE id = ?", record.rewind, record.id); + return describe(record); + }); + } + + retire( + scope: TimelineScope, + input: { retireFromSeq: number; selectChildren: RetiredChildSelector }, + ): TimelineBackendRetireResult { + return this.database.write((sql) => { + const record = requireScope(sql, scope); + const retirement: TimelineRetirement = { + seq: record.next_seq, + retireFromSeq: input.retireFromSeq, + }; + const retiredRows = readActiveRows(sql, record.id, { fromSeq: input.retireFromSeq }); + sql.run( + "UPDATE timeline_rows SET retired_by = ?, identity_live = 0 " + + `WHERE ${ACTIVE} AND seq_start >= ?`, + retirement.seq, + record.id, + input.retireFromSeq, + ); + for (const row of retiredRows) { + if (row.item.type === "tool_call") { + addRetiredKey(sql, record.id, "identity", row.item.callId); + } + if (row.turnId !== undefined && !hasActiveTurn(sql, record.id, row.turnId)) { + addRetiredKey(sql, record.id, "turn", row.turnId); + } + } + // Ranges of the retired rows stay covered, without a row. They start at or after their row. + sql.run( + "UPDATE timeline_source_ranges SET row_seq_start = NULL " + + "WHERE scope_id = ? AND start_seq >= ? AND row_seq_start >= ?", + record.id, + input.retireFromSeq, + input.retireFromSeq, + ); + sql.run( + "INSERT INTO timeline_source_ranges (scope_id, start_seq, end_seq, row_seq_start) " + + "VALUES (?, ?, ?, NULL)", + record.id, + retirement.seq, + retirement.seq, + ); + sql.run( + "INSERT INTO timeline_retirements (scope_id, seq, retire_from_seq) VALUES (?, ?, ?)", + record.id, + retirement.seq, + retirement.retireFromSeq, + ); + const retiredChildIds = [ + ...input.selectChildren(retiredRows, listChildren(sql, scope.agentId)), + ]; + for (const subagentId of retiredChildIds) { + sql.run( + "UPDATE timeline_scopes SET child_retired = 1 WHERE agent_id = ? AND subagent_id = ?", + scope.agentId, + subagentId, + ); + } + record.next_seq = retirement.seq + 1; + if (record.min_seq === 0) record.min_seq = retirement.seq; + record.retirement_count += 1; + record.active_count -= retiredRows.length; + record.active_max_seq_end = activeMaxSeqEnd(sql, record.id); + record.rewind = null; + saveScopeCounters(sql, record); + sql.run("UPDATE timeline_scopes SET rewind = NULL WHERE id = ?", record.id); + return { retirement, retiredRows, retiredChildIds, head: describe(record) }; + }); + } + + children(agentId: string): TimelineChild[] { + return this.database.read((sql) => listChildren(sql, agentId)); + } + + child(scope: TimelineScope): TimelineChild | null { + if (scope.subagentId === undefined) return null; + const subagentId = scope.subagentId; + return this.database.read((sql) => { + const record = findScope(sql, scope); + return record ? toChild(subagentId, record) : null; + }); + } + + setChild(scope: TimelineScope, descriptor: ProviderSubagentDescriptor): void { + this.database.write((sql) => { + const record = findScope(sql, scope) ?? createScope(sql, scope, {}); + sql.run( + "UPDATE timeline_scopes SET descriptor = ? WHERE id = ?", + JSON.stringify(descriptor), + record.id, + ); + }); + } + + attachProviderMessageId( + scope: TimelineScope, + clientMessageId: string, + providerMessageId: string, + ): AgentTimelineRow | null { + return this.database.write((sql) => { + const { id } = requireScope(sql, scope); + const record = findSubmittedPromptRecord(sql, id, clientMessageId); + if (!record) return null; + const row = { ...parseRow(record), providerMessageId }; + saveRow(sql, id, row); + return row; + }); + } + + stampTurnMetrics( + scope: TimelineScope, + metrics: AgentMetric[], + options?: { turnId?: string }, + ): ProjectedTimelineRow | null { + return this.database.write((sql) => { + const { id } = requireScope(sql, scope); + const footer = turnFooterSeq(sql, id, options?.turnId); + if (footer === null) return null; + const record = sql.get( + "SELECT seq_start, item_type, row FROM timeline_rows WHERE scope_id = ? AND seq_start = ?", + id, + footer, + )!; + const row = { ...parseRow(record), turnMetrics: metrics }; + saveRow(sql, id, row); + return withText(sql, id, row); + }); + } + + findSubmittedPrompt(scope: TimelineScope, clientMessageId: string): AgentTimelineRow | null { + return this.database.read((sql) => { + const { id } = requireScope(sql, scope); + const record = findSubmittedPromptRecord(sql, id, clientMessageId); + return record ? parseRow(record) : null; + }); + } + + fetch(scope: TimelineScope, options: AgentTimelineFetchOptions): AgentTimelineFetchResult { + return this.database.read((sql) => { + const record = requireScope(sql, scope); + return fetchTimelinePage({ + history: { + epoch: record.epoch, + minSeq: record.min_seq, + nextSeq: record.next_seq, + retirementCount: record.retirement_count, + }, + options, + selectPage: (page) => new StoredPageSelection(sql, record).select(page), + }); + }); + } + + readRows(scope: TimelineScope): ProjectedTimelineRow[] { + return this.database.read((sql) => readActiveRows(sql, requireScope(sql, scope).id, {})); + } + + lastItem(scope: TimelineScope): AgentTimelineItem | null { + return this.database.read((sql) => { + const record = requireScope(sql, scope); + const last = lastSourceRange(sql, record.id); + if (!last || last.end_seq !== record.next_seq - 1 || last.row_seq_start === null) return null; + return readRow(sql, record.id, last.row_seq_start).item; + }); + } + + lastAssistantMessage(scope: TimelineScope): string | null { + return this.database.read((sql) => { + const { id } = requireScope(sql, scope); + const last = sql.get<{ seq_start: number }>( + `SELECT seq_start FROM timeline_rows WHERE ${ACTIVE} ` + + "AND item_type = 'assistant_message' ORDER BY seq_start DESC LIMIT 1", + id, + ); + if (!last) return null; + let next = readRow(sql, id, last.seq_start); + const chunks = [itemText(next.item)]; + for (const record of sql.iterate( + `SELECT seq_start, item_type, row FROM timeline_rows WHERE ${ACTIVE} ` + + "AND seq_start < ? ORDER BY seq_start DESC", + id, + last.seq_start, + )) { + if (record.item_type !== "assistant_message") break; + const row = withText(sql, id, parseRow(record)); + if (!continuesAssistantMessage(row, next)) break; + chunks.push(itemText(row.item)); + next = row; + } + return chunks.toReversed().join(""); + }); + } + + /** Retired rows, oldest retirement first. Not part of the backend contract; tests read it. */ + retiredRows(scope: TimelineScope): ProjectedTimelineRow[] { + return this.database.read((sql) => { + const { id } = requireScope(sql, scope); + return sql + .all( + "SELECT seq_start, item_type, row FROM timeline_rows " + + "WHERE scope_id = ? AND retired_by IS NOT NULL ORDER BY retired_by, seq_start", + id, + ) + .map((record) => withText(sql, id, parseRow(record))); + }); + } +} + +function describe(record: ScopeRecord): TimelineHead { + return { + epoch: record.epoch, + seq: record.next_seq - 1, + size: record.active_count, + retirementCount: record.retirement_count, + rewind: record.rewind ? (JSON.parse(record.rewind) as TimelineRewindIntent) : null, + }; +} + +function toChild(subagentId: string, record: ScopeRecord): TimelineChild { + return { + subagentId, + descriptor: record.descriptor + ? (JSON.parse(record.descriptor) as ProviderSubagentDescriptor) + : null, + retired: record.child_retired === 1, + }; +} + +function findScope(sql: ReadSql, scope: TimelineScope): ScopeRecord | undefined { + return scope.subagentId === undefined + ? sql.get( + `SELECT ${SCOPE_COLUMNS} FROM timeline_scopes WHERE agent_id = ? AND subagent_id IS NULL`, + scope.agentId, + ) + : sql.get( + `SELECT ${SCOPE_COLUMNS} FROM timeline_scopes WHERE agent_id = ? AND subagent_id = ?`, + scope.agentId, + scope.subagentId, + ); +} + +function requireScope(sql: ReadSql, scope: TimelineScope): ScopeRecord { + const record = findScope(sql, scope); + if (!record) throw new UnknownTimelineError(scope); + return record; +} + +function listChildren(sql: ReadSql, agentId: string): TimelineChild[] { + return sql + .all( + `SELECT ${SCOPE_COLUMNS}, subagent_id FROM timeline_scopes ` + + "WHERE agent_id = ? AND subagent_id IS NOT NULL", + agentId, + ) + .map((record) => toChild(record.subagent_id, record)); +} + +/** Replaces the scope's history, leaving a root's children as they are. */ +function createScope(sql: WriteSql, scope: TimelineScope, seed: TimelineSeed): ScopeRecord { + const existing = findScope(sql, scope); + if (existing) sql.run("DELETE FROM timeline_scopes WHERE id = ?", existing.id); + const timestamp = seed.timestamp ?? new Date().toISOString(); + const startSeq = seed.nextSeq ?? 1; + const sourceRows = seed.rows?.length + ? seed.rows.map((row) => ({ ...row })) + : (seed.entries ?? []).map((entry, index) => + buildSourceRow(entry, startSeq + index, timestamp), + ); + const nextSeq = sourceRows.reduce((next, row) => Math.max(next, row.seq + 1), startSeq); + // A seed is already in memory; projecting it there reuses the projection's seeding rules. + const rows = new TimelineProjection(sourceRows).getRows(); + const record: ScopeRecord = { + id: 0, + epoch: seed.epoch ?? randomUUID(), + next_seq: nextSeq, + min_seq: rows[0]?.seqStart ?? 0, + active_count: rows.length, + active_max_seq_end: 0, + retirement_count: 0, + rewind: null, + descriptor: null, + child_retired: 0, + }; + record.id = sql.get<{ id: number }>( + "INSERT INTO timeline_scopes (agent_id, subagent_id, epoch, next_seq, min_seq, " + + "active_count, active_max_seq_end, retirement_count) VALUES (?, ?, ?, ?, ?, ?, 0, 0) " + + "RETURNING id", + scope.agentId, + scope.subagentId ?? null, + record.epoch, + record.next_seq, + record.min_seq, + record.active_count, + )!.id; + const liveIdentityAt = new Map(); + for (const row of rows) { + const identity = timelineItemIdentity(row.item); + if (identity !== null) liveIdentityAt.set(identity, row.seqStart); + } + const ranges: (TimelineSeqRange & { rowSeqStart: number })[] = []; + for (const row of rows) { + const identity = timelineItemIdentity(row.item); + insertRow(sql, record.id, row, { + spanStart: record.active_max_seq_end < row.seqStart, + identityLive: identity !== null && liveIdentityAt.get(identity) === row.seqStart, + }); + if (isTextItemType(row.item.type)) insertText(sql, record.id, row.seqStart, row.seqStart, row); + record.active_max_seq_end = Math.max(record.active_max_seq_end, row.seqEnd); + for (const range of row.sourceSeqRanges) ranges.push({ ...range, rowSeqStart: row.seqStart }); + } + ranges.sort((left, right) => left.startSeq - right.startSeq); + for (const range of ranges) { + insertSourceRange(sql, record.id, range.startSeq, range.endSeq, range.rowSeqStart); + } + saveScopeCounters(sql, record); + return record; +} + +/** Folds one source row into the stored projection, mirroring `TimelineProjection.append`. */ +function foldSourceRow(sql: WriteSql, record: ScopeRecord, row: AgentTimelineRow): void { + const identity = timelineItemIdentity(row.item); + const identityRecord = identity === null ? undefined : findIdentityRow(sql, record.id, identity); + if (identityRecord) { + const fold = foldTimelineRow({ + row, + identityRow: parseRow(identityRecord), + lastRow: undefined, + }); + if (fold.kind === "identity") { + saveRow(sql, record.id, fold.row); + // Rows the longer coverage now reaches no longer start a span. + sql.run( + `UPDATE timeline_rows SET span_start = 0 WHERE ${ACTIVE} AND span_start = 1 ` + + "AND seq_start > ? AND seq_start <= ?", + record.id, + fold.row.seqStart, + fold.row.seqEnd, + ); + coverSourceSeq(sql, record, row.seq, fold.row); + return; + } + } + const lastRow = isTextItemType(row.item.type) ? lastActiveTextRow(sql, record.id) : undefined; + const fold = foldTimelineRow({ row, identityRow: undefined, lastRow }); + if (fold.kind === "adjacent") { + // `lastRow` has no text, so the merged text is this chunk alone. + insertText(sql, record.id, fold.row.seqStart, row.seq, fold.row); + saveRow(sql, record.id, fold.row); + coverSourceSeq(sql, record, row.seq, fold.row); + return; + } + if (identity !== null) { + sql.run( + "UPDATE timeline_rows SET identity_live = 0 " + + "WHERE scope_id = ? AND identity = ? AND identity_live = 1", + record.id, + identity, + ); + } + insertRow(sql, record.id, fold.row, { + spanStart: record.active_max_seq_end < fold.row.seqStart, + identityLive: identity !== null, + }); + if (isTextItemType(fold.row.item.type)) { + insertText(sql, record.id, fold.row.seqStart, row.seq, fold.row); + } + record.active_count += 1; + coverSourceSeq(sql, record, row.seq, fold.row); +} + +/** Records that `seq` is covered by `row`, extending the last source range when contiguous. */ +function coverSourceSeq( + sql: WriteSql, + record: ScopeRecord, + seq: number, + row: ProjectedTimelineRow, +): void { + record.active_max_seq_end = Math.max(record.active_max_seq_end, row.seqEnd); + const last = lastSourceRange(sql, record.id); + if (last && last.row_seq_start === row.seqStart && last.end_seq + 1 === seq) { + sql.run( + "UPDATE timeline_source_ranges SET end_seq = ? WHERE scope_id = ? AND start_seq = ?", + seq, + record.id, + last.start_seq, + ); + return; + } + insertSourceRange(sql, record.id, seq, seq, row.seqStart); +} + +function lastSourceRange(sql: ReadSql, scopeId: number): SourceRangeRecord | undefined { + return sql.get( + "SELECT start_seq, end_seq, row_seq_start FROM timeline_source_ranges " + + "WHERE scope_id = ? ORDER BY start_seq DESC LIMIT 1", + scopeId, + ); +} + +function insertSourceRange( + sql: WriteSql, + scopeId: number, + startSeq: number, + endSeq: number, + rowSeqStart: number | null, +): void { + sql.run( + "INSERT INTO timeline_source_ranges (scope_id, start_seq, end_seq, row_seq_start) " + + "VALUES (?, ?, ?, ?)", + scopeId, + startSeq, + endSeq, + rowSeqStart, + ); +} + +function saveScopeCounters(sql: WriteSql, record: ScopeRecord): void { + sql.run( + "UPDATE timeline_scopes SET next_seq = ?, min_seq = ?, active_count = ?, " + + "active_max_seq_end = ?, retirement_count = ? WHERE id = ?", + record.next_seq, + record.min_seq, + record.active_count, + record.active_max_seq_end, + record.retirement_count, + record.id, + ); +} + +/** The highest `seq_end` of the active rows: the end of the last span. */ +function activeMaxSeqEnd(sql: ReadSql, scopeId: number): number { + const lastSpan = sql.get<{ seq_start: number }>( + `SELECT seq_start FROM timeline_rows WHERE ${ACTIVE} AND span_start = 1 ` + + "ORDER BY seq_start DESC LIMIT 1", + scopeId, + ); + if (!lastSpan) return 0; + return sql.get<{ max: number }>( + `SELECT MAX(seq_end) AS max FROM timeline_rows WHERE ${ACTIVE} AND seq_start >= ?`, + scopeId, + lastSpan.seq_start, + )!.max; +} + +/** The row JSON, with a streamed text row's text left out; the text lives in `timeline_text`. */ +function encodeRow(row: ProjectedTimelineRow): string { + if (!isTextItemType(row.item.type)) return JSON.stringify(row); + return JSON.stringify({ ...row, item: { ...row.item, text: "" } }); +} + +function itemText(item: AgentTimelineItem): string { + return item.type === "assistant_message" || item.type === "reasoning" ? item.text : ""; +} + +function insertRow( + sql: WriteSql, + scopeId: number, + row: ProjectedTimelineRow, + flags: { spanStart: boolean; identityLive: boolean }, +): void { + sql.run( + "INSERT INTO timeline_rows (scope_id, seq_start, seq_end, retired_by, span_start, identity, " + + "identity_live, turn_id, turn_trigger, item_type, client_message_id, row) " + + "VALUES (?, ?, ?, NULL, ?, ?, ?, ?, ?, ?, ?, ?)", + scopeId, + row.seqStart, + row.seqEnd, + flags.spanStart ? 1 : 0, + timelineItemIdentity(row.item), + flags.identityLive ? 1 : 0, + row.turnId ?? null, + isTimelineTurnTrigger(row.item) ? 1 : 0, + row.item.type, + row.item.type === "user_message" ? (row.item.clientMessageId ?? null) : null, + encodeRow(row), + ); +} + +/** Rewrites an existing row's payload and the columns an update can change. */ +function saveRow(sql: WriteSql, scopeId: number, row: ProjectedTimelineRow): void { + sql.run( + "UPDATE timeline_rows SET seq_end = ?, turn_id = ?, turn_trigger = ?, row = ? " + + "WHERE scope_id = ? AND seq_start = ?", + row.seqEnd, + row.turnId ?? null, + isTimelineTurnTrigger(row.item) ? 1 : 0, + encodeRow(row), + scopeId, + row.seqStart, + ); +} + +function insertText( + sql: WriteSql, + scopeId: number, + seqStart: number, + seq: number, + row: ProjectedTimelineRow, +): void { + sql.run( + "INSERT INTO timeline_text (scope_id, seq_start, seq, text) VALUES (?, ?, ?, ?)", + scopeId, + seqStart, + seq, + itemText(row.item), + ); +} + +function parseRow(record: Pick): ProjectedTimelineRow { + return JSON.parse(record.row) as ProjectedTimelineRow; +} + +/** Fills a parsed text row's text from its chunks. */ +function withText(sql: ReadSql, scopeId: number, row: ProjectedTimelineRow): ProjectedTimelineRow { + if (row.item.type !== "assistant_message" && row.item.type !== "reasoning") return row; + const text = sql + .all<{ text: string }>( + "SELECT text FROM timeline_text WHERE scope_id = ? AND seq_start = ? ORDER BY seq", + scopeId, + row.seqStart, + ) + .map((chunk) => chunk.text) + .join(""); + return { ...row, item: { ...row.item, text } }; +} + +function readRow(sql: ReadSql, scopeId: number, seqStart: number): ProjectedTimelineRow { + const record = sql.get( + "SELECT seq_start, item_type, row FROM timeline_rows WHERE scope_id = ? AND seq_start = ?", + scopeId, + seqStart, + )!; + return withText(sql, scopeId, parseRow(record)); +} + +/** Active rows anchored in `[fromSeq, beforeSeq)`, in display order. */ +function readActiveRows( + sql: ReadSql, + scopeId: number, + range: { fromSeq?: number; beforeSeq?: number }, +): ProjectedTimelineRow[] { + return sql + .all( + `SELECT seq_start, item_type, row FROM timeline_rows WHERE ${ACTIVE} ` + + "AND seq_start >= ? AND seq_start < ? ORDER BY seq_start", + scopeId, + range.fromSeq ?? Number.MIN_SAFE_INTEGER, + range.beforeSeq ?? Number.MAX_SAFE_INTEGER, + ) + .map((record) => withText(sql, scopeId, parseRow(record))); +} + +/** The last active row when it is a streamed text row, without its text. */ +function lastActiveTextRow(sql: ReadSql, scopeId: number): ProjectedTimelineRow | undefined { + // The payload of any other row type is not read. + const last = sql.get<{ row: string | null }>( + "SELECT CASE WHEN item_type IN ('assistant_message', 'reasoning') THEN row END AS row " + + `FROM timeline_rows WHERE ${ACTIVE} ORDER BY seq_start DESC LIMIT 1`, + scopeId, + ); + return last?.row ? parseRow({ row: last.row }) : undefined; +} + +function findIdentityRow(sql: ReadSql, scopeId: number, identity: string): RowRecord | undefined { + return sql.get( + "SELECT seq_start, item_type, row FROM timeline_rows " + + "WHERE scope_id = ? AND identity = ? AND identity_live = 1", + scopeId, + identity, + ); +} + +function findSubmittedPromptRecord( + sql: ReadSql, + scopeId: number, + clientMessageId: string, +): RowRecord | undefined { + return sql.get( + "SELECT seq_start, item_type, row FROM timeline_rows " + + "WHERE scope_id = ? AND client_message_id = ? AND retired_by IS NULL " + + "ORDER BY seq_start LIMIT 1", + scopeId, + clientMessageId, + ); +} + +function hasActiveTurn(sql: ReadSql, scopeId: number, turnId: string): boolean { + return ( + sql.get( + `SELECT 1 FROM timeline_rows WHERE ${ACTIVE} AND turn_id = ? LIMIT 1`, + scopeId, + turnId, + ) !== undefined + ); +} + +function hasRetiredKey(sql: ReadSql, scopeId: number, kind: string, key: string): boolean { + return ( + sql.get( + "SELECT 1 FROM timeline_retired_keys WHERE scope_id = ? AND kind = ? AND key = ?", + scopeId, + kind, + key, + ) !== undefined + ); +} + +function addRetiredKey(sql: WriteSql, scopeId: number, kind: string, key: string): void { + sql.run( + "INSERT OR IGNORE INTO timeline_retired_keys (scope_id, kind, key) VALUES (?, ?, ?)", + scopeId, + kind, + key, + ); +} + +function continuesShape(previous: RowShape, next: RowShape): boolean { + return continuesTimelineTurn( + previous.turn_id ?? undefined, + next.turn_id ?? undefined, + next.turn_trigger === 1, + ); +} + +/** + * The row a completed turn's metrics go on: the turn's last assistant message, else its last row + * when that row is a tool call. Mirrors `TimelineProjection.stampTurnMetrics`. + */ +function turnFooterSeq(sql: ReadSql, scopeId: number, turnId: string | undefined): number | null { + const tail = sql.get( + `SELECT ${SHAPE_COLUMNS} FROM timeline_rows WHERE ${ACTIVE} ORDER BY seq_start DESC LIMIT 1`, + scopeId, + ); + if (!tail) return null; + let last: RowShape | undefined = tail; + if (turnId !== undefined) { + last = + sql.get( + `SELECT ${SHAPE_COLUMNS} FROM timeline_rows WHERE ${ACTIVE} AND turn_id = ? ` + + "ORDER BY seq_start DESC LIMIT 1", + scopeId, + turnId, + ) ?? (tail.turn_id === null ? tail : undefined); + } + if (!last) return null; + let next: RowShape | undefined; + for (const row of sql.iterate( + `SELECT ${SHAPE_COLUMNS} FROM timeline_rows WHERE ${ACTIVE} AND seq_start <= ? ` + + "ORDER BY seq_start DESC", + scopeId, + last.seq_start, + )) { + if (next && !continuesShape(row, next)) break; + if (row.item_type === "assistant_message") return row.seq_start; + next = row; + } + return last.item_type === "tool_call" ? last.seq_start : null; +} + +/** + * Page selection over the stored projection. It mirrors `TimelineProjection.selectPage` with + * row anchors in place of row indexes, and reads only the rows the page returns plus the bounded + * walks the page rules need. + */ +class StoredPageSelection { + private readonly scopeId: number; + + constructor( + private readonly sql: ReadSql, + private readonly record: ScopeRecord, + ) { + this.scopeId = record.id; + } + + select(input: ProjectedTimelinePageOptions): ProjectedTimelinePageSelection { + const hasRows = this.record.active_count > 0; + if (!hasRows && lastSourceRange(this.sql, this.scopeId)) { + // Every row is retired. Forward pages still advance; a tail covers the whole window. + if (input.direction === "after") return this.selectAfter(input); + if (input.direction === "tail") { + return { + entries: [], + startSeq: input.bounds.minSeq, + endSeq: input.bounds.maxSeq, + hasOlder: false, + hasNewer: false, + retirements: this.retirementsInSpan(input.bounds.minSeq, input.bounds.maxSeq), + }; + } + } + if (!hasRows) { + const cursor = + input.cursorSeq ?? + (input.direction === "before" ? input.bounds.maxSeq + 1 : input.bounds.minSeq - 1); + return { + entries: [], + startSeq: null, + endSeq: null, + hasOlder: + input.direction === "after" + ? cursor >= input.bounds.minSeq + : input.direction === "before" && cursor > input.bounds.minSeq, + hasNewer: + input.direction === "after" + ? cursor < input.bounds.maxSeq + : input.direction === "before" && cursor <= input.bounds.maxSeq, + retirements: [], + }; + } + switch (input.direction) { + case "tail": + return this.selectTail(input); + case "after": + return this.selectAfter(input); + case "before": + return this.selectBefore(input); + } + } + + private selectTail(input: ProjectedTimelinePageOptions): ProjectedTimelinePageSelection { + const limit = Math.max(0, Math.floor(input.limit ?? 0)); + const requested = (limit > 0 && this.nthActiveFromEnd(limit)) || this.firstActive(); + const covered = this.spanStartAtOrBefore(requested); + const start = input.wholeTurns ? this.wholeTurnWindowStart(covered) : covered; + return { + entries: readActiveRows(this.sql, this.scopeId, { fromSeq: start }), + startSeq: start, + endSeq: input.bounds.maxSeq, + hasOlder: this.hasActiveAnchorIn(Number.MIN_SAFE_INTEGER, start), + hasNewer: false, + retirements: this.retirementsInSpan(start, input.bounds.maxSeq), + }; + } + + private selectAfter(input: ProjectedTimelinePageOptions): ProjectedTimelinePageSelection { + const startSeq = Math.max( + input.bounds.minSeq, + (input.cursorSeq ?? input.bounds.minSeq - 1) + 1, + ); + const limit = Math.max(0, Math.floor(input.limit ?? 0)); + const anchors = new Set(); + const covered: TimelineSeqRange[] = []; + const retirements: TimelineRetirement[] = []; + // Ranges are disjoint and ordered: start from the one that may contain `startSeq`. + const first = + this.sql.get<{ start_seq: number }>( + "SELECT start_seq FROM timeline_source_ranges WHERE scope_id = ? AND start_seq <= ? " + + "ORDER BY start_seq DESC LIMIT 1", + this.scopeId, + startSeq, + )?.start_seq ?? Number.MIN_SAFE_INTEGER; + for (const range of this.sql.iterate( + "SELECT start_seq, end_seq, row_seq_start FROM timeline_source_ranges " + + "WHERE scope_id = ? AND start_seq >= ? ORDER BY start_seq", + this.scopeId, + first, + )) { + if (range.end_seq < startSeq) continue; + if (range.start_seq > input.bounds.maxSeq) break; + if (range.row_seq_start !== null) { + anchors.add(range.row_seq_start); + } else { + covered.push({ startSeq: Math.max(range.start_seq, startSeq), endSeq: range.end_seq }); + const retirement = this.sql.get( + "SELECT seq, retire_from_seq FROM timeline_retirements WHERE scope_id = ? AND seq = ?", + this.scopeId, + range.start_seq, + ); + if (retirement) { + retirements.push({ seq: retirement.seq, retireFromSeq: retirement.retire_from_seq }); + } + } + // Each retirement counts toward the limit, so a page stays bounded however many it crosses. + if (limit > 0 && anchors.size + retirements.length >= limit) break; + } + const entries = [...anchors] + .sort((left, right) => left - right) + .map((anchor) => readRow(this.sql, this.scopeId, anchor)); + const selected = selectProjectedEntriesAfter({ + entries, + covered, + startSeq, + maxSeq: input.bounds.maxSeq, + limit, + }); + const endSeq = selected.endSeq; + return { + entries: selected.entries.map((entry) => entry as ProjectedTimelineRow), + startSeq: endSeq === null ? null : startSeq, + endSeq, + hasOlder: startSeq > input.bounds.minSeq, + hasNewer: endSeq !== null && endSeq < input.bounds.maxSeq, + retirements: + endSeq === null + ? [] + : this.coalesce(retirements.filter((retirement) => retirement.seq <= endSeq)), + }; + } + + private selectBefore(input: ProjectedTimelinePageOptions): ProjectedTimelinePageSelection { + const endSeq = Math.min(input.bounds.maxSeq, (input.cursorSeq ?? input.bounds.maxSeq + 1) - 1); + if (endSeq < input.bounds.minSeq) { + return { + entries: [], + startSeq: null, + endSeq: null, + hasOlder: false, + hasNewer: true, + retirements: [], + }; + } + const limit = Math.max(0, Math.floor(input.limit ?? 0)); + const requested = (limit > 0 && this.nthActiveFromEnd(limit, endSeq)) || this.firstActive(); + const start = input.wholeTurns ? this.wholeTurnWindowStart(requested) : requested; + // The first active row after the page; undefined when the page reaches the end. + let after = this.sql.get( + `SELECT ${SHAPE_COLUMNS} FROM timeline_rows WHERE ${ACTIVE} AND seq_start > ? ` + + "ORDER BY seq_start LIMIT 1", + this.scopeId, + endSeq, + ); + const lastInPage = this.sql.get( + `SELECT ${SHAPE_COLUMNS} FROM timeline_rows WHERE ${ACTIVE} AND seq_start <= ? ` + + "ORDER BY seq_start DESC LIMIT 1", + this.scopeId, + endSeq, + ); + if (input.wholeTurns && after && lastInPage) { + // Choose the window before extending the right edge, so a prompt jump cannot lose its + // target when the next turn is arbitrarily large. + let previous = lastInPage; + after = undefined; + for (const row of this.sql.iterate( + `SELECT ${SHAPE_COLUMNS} FROM timeline_rows WHERE ${ACTIVE} AND seq_start > ? ` + + "ORDER BY seq_start", + this.scopeId, + endSeq, + )) { + if (!continuesShape(previous, row)) { + after = row; + break; + } + previous = row; + } + } + let selectedEnd = endSeq; + if (input.wholeTurns) { + selectedEnd = after ? after.seq_start - 1 : input.bounds.maxSeq; + } + return { + entries: readActiveRows(this.sql, this.scopeId, { + fromSeq: start, + beforeSeq: after?.seq_start, + }), + startSeq: start, + endSeq: selectedEnd, + hasOlder: this.hasActiveAnchorIn(Number.MIN_SAFE_INTEGER, start), + hasNewer: selectedEnd < input.bounds.maxSeq, + retirements: this.retirementsInSpan(start, selectedEnd), + }; + } + + /** Extends a window start back to whole turns and whole coverage spans. */ + private wholeTurnWindowStart(requested: number): number { + let start = requested; + for (;;) { + let next = this.shape(start); + for (const row of this.sql.iterate( + `SELECT ${SHAPE_COLUMNS} FROM timeline_rows WHERE ${ACTIVE} AND seq_start < ? ` + + "ORDER BY seq_start DESC", + this.scopeId, + start, + )) { + if (!continuesShape(row, next)) break; + start = row.seq_start; + next = row; + } + // Source coverage can pull in an earlier tool and therefore its entire run. + const covered = this.spanStartAtOrBefore(start); + if (covered === start) return start; + start = covered; + } + } + + private shape(seqStart: number): RowShape { + return this.sql.get( + `SELECT ${SHAPE_COLUMNS} FROM timeline_rows WHERE scope_id = ? AND seq_start = ?`, + this.scopeId, + seqStart, + )!; + } + + private firstActive(): number { + return this.sql.get<{ seq_start: number }>( + `SELECT seq_start FROM timeline_rows WHERE ${ACTIVE} ORDER BY seq_start LIMIT 1`, + this.scopeId, + )!.seq_start; + } + + /** The anchor of the `n`th active row from the end, among rows anchored at or before `atOrBefore`. */ + private nthActiveFromEnd(n: number, atOrBefore = Number.MAX_SAFE_INTEGER): number | undefined { + return this.sql.get<{ seq_start: number }>( + `SELECT seq_start FROM timeline_rows WHERE ${ACTIVE} AND seq_start <= ? ` + + "ORDER BY seq_start DESC LIMIT 1 OFFSET ?", + this.scopeId, + atOrBefore, + n - 1, + )?.seq_start; + } + + private spanStartAtOrBefore(seqStart: number): number { + return this.sql.get<{ seq_start: number }>( + `SELECT seq_start FROM timeline_rows WHERE ${ACTIVE} AND span_start = 1 ` + + "AND seq_start <= ? ORDER BY seq_start DESC LIMIT 1", + this.scopeId, + seqStart, + )!.seq_start; + } + + private hasActiveAnchorIn(startSeq: number, endSeq: number): boolean { + return ( + this.sql.get( + `SELECT 1 FROM timeline_rows WHERE ${ACTIVE} AND seq_start >= ? AND seq_start < ? LIMIT 1`, + this.scopeId, + startSeq, + endSeq, + ) !== undefined + ); + } + + private retirementsInSpan(startSeq: number, endSeq: number): TimelineRetirement[] { + return this.coalesce( + this.sql + .all( + "SELECT seq, retire_from_seq FROM timeline_retirements " + + "WHERE scope_id = ? AND seq >= ? AND seq <= ? ORDER BY seq", + this.scopeId, + startSeq, + endSeq, + ) + .map((record) => ({ seq: record.seq, retireFromSeq: record.retire_from_seq })), + ); + } + + private coalesce(retirements: readonly TimelineRetirement[]): TimelineRetirement[] { + return coalesceTimelineRetirements(retirements, (startSeq, endSeq) => + this.hasActiveAnchorIn(startSeq, endSeq), + ); + } +} diff --git a/packages/server/src/server/agent/timeline/sqlite-backend.test.ts b/packages/server/src/server/agent/timeline/sqlite-backend.test.ts new file mode 100644 index 0000000000..db8cdd32a9 --- /dev/null +++ b/packages/server/src/server/agent/timeline/sqlite-backend.test.ts @@ -0,0 +1,454 @@ +import { describe, expect, it } from "vitest"; +import type { AgentTimelineItem } from "../agent-sdk-types.js"; +import type { AgentTimelineFetchOptions } from "../agent-timeline-store-types.js"; +import type { ProviderSubagentDescriptor } from "../provider-subagents/store.js"; +import type { DaemonDatabase, ReadSql, WriteSql } from "../../database/index.js"; +import { MemoryTimelineBackend } from "./internal/memory-backend.js"; +import { SqliteTimelineBackend } from "./internal/sqlite-backend.js"; +import { nextTestDatabasePath } from "../../test-utils/test-database-path.js"; +import { DeferredTimelineBackend, openTestTimelineDatabase } from "./testing.js"; +import { + AgentTimeline, + TimelineClosedError, + type TimelineEntry, + type TimelineScope, +} from "./index.js"; + +const scope: TimelineScope = { agentId: "agent" }; +const TIMESTAMP = "2026-11-25T10:00:00.000Z"; + +function entry(item: AgentTimelineItem, fields: Omit = {}): TimelineEntry { + return { item, timestamp: TIMESTAMP, ...fields }; +} + +function tool(callId: string, status: "running" | "completed", label = callId): AgentTimelineItem { + return { + type: "tool_call", + callId, + name: "shell", + status, + error: null, + detail: { type: "plain_text", label }, + }; +} + +function descriptor(id: string, toolCallId: string | null): ProviderSubagentDescriptor { + return { + id, + parentAgentId: "agent", + parentSubagentId: null, + provider: "claude", + title: null, + description: null, + status: "running", + createdAt: TIMESTAMP, + updatedAt: TIMESTAMP, + toolCallId, + cwd: null, + subtitle: null, + }; +} + +function seededRandom(seed: number): (bound: number) => number { + let state = seed; + return (bound) => { + state = (Math.imul(state, 1664525) + 1013904223) >>> 0; + return Math.floor((state / 0x1_0000_0000) * bound); + }; +} + +/** Every row of every timeline table, to compare stored state before and after a failed write. */ +function dumpTables(database: DaemonDatabase): Record { + return database.read((sql) => { + const tables = sql + .all<{ name: string }>( + "SELECT name FROM sqlite_master WHERE type = 'table' AND name LIKE 'timeline_%' ORDER BY name", + ) + .map((table) => table.name); + return Object.fromEntries(tables.map((table) => [table, sql.all(`SELECT * FROM ${table}`)])); + }); +} + +/** Counts the rows the backend's queries return, to prove a read touches a bounded slice. */ +class CountingDatabase implements DaemonDatabase { + rowsRead = 0; + + constructor(private readonly inner: DaemonDatabase) {} + + write(fn: (sql: WriteSql) => T): T { + return this.inner.write((sql) => fn({ ...this.counting(sql), run: sql.run, exec: sql.exec })); + } + + read(fn: (sql: ReadSql) => T): T { + return this.inner.read((sql) => fn(this.counting(sql))); + } + + close(): void { + this.inner.close(); + } + + private counting(sql: ReadSql): ReadSql { + return { + get: (query, ...params) => { + const row = sql.get(query, ...params); + if (row !== undefined) this.rowsRead += 1; + return row as never; + }, + all: (query, ...params) => { + const rows = sql.all(query, ...params); + this.rowsRead += rows.length; + return rows as never; + }, + iterate: (query: string, ...params: Parameters[1][]) => { + const rows = sql.iterate(query, ...params); + const count = () => (this.rowsRead += 1); + return { + *[Symbol.iterator]() { + for (const row of rows) { + count(); + yield row; + } + }, + }; + }, + }; + } +} + +describe("SQLite timeline backend against the memory backend", () => { + it("stores the same history and serves the same pages on seeded randomized timelines", () => { + const random = seededRandom(0x5eed_0001); + for (let scenario = 0; scenario < 40; scenario++) { + const memory = new MemoryTimelineBackend(); + const sqlite = new SqliteTimelineBackend(openTestTimelineDatabase()); + const backends = [memory, sqlite] as const; + for (const backend of backends) backend.create(scope, { epoch: "e" }); + let turn = 0; + for (let step = 0; step < 120; step++) { + const roll = random(20); + const identity = String(random(6)); + const text = `${scenario}-${step}`; + if (roll === 0) { + const prompts = memory.prompts(scope); + if (prompts.length > 0) { + const retireFromSeq = prompts[random(prompts.length)].seqStart; + const results = backends.map((backend) => + backend.retire(scope, { retireFromSeq, selectChildren: () => [] }), + ); + expect(results[1]).toEqual(results[0]); + } + continue; + } + if (roll === 1) { + const turnId = random(2) === 0 ? String(turn) : undefined; + const metrics = [{ name: "tokens", value: step }] as never; + const results = backends.map((backend) => + backend.stampTurnMetrics(scope, metrics, turnId === undefined ? {} : { turnId }), + ); + expect(results[1]).toEqual(results[0]); + continue; + } + if (roll === 2) { + const clientMessageId = `client-${random(step + 1)}`; + const results = backends.map((backend) => + backend.attachProviderMessageId(scope, clientMessageId, `provider-${step}`), + ); + expect(results[1]).toEqual(results[0]); + continue; + } + if (random(8) === 0) turn += 1; + const items: AgentTimelineItem[] = [ + { type: "user_message", text, messageId: `m-${step}`, clientMessageId: `client-${step}` }, + { type: "user_message", text, messageId: `m-${step}` }, + { type: "assistant_message", text }, + { type: "assistant_message", text, messageId: identity }, + { type: "reasoning", text }, + tool(identity, random(2) === 0 ? "running" : "completed", text), + { + type: "plugin", + id: identity, + pluginId: "test", + kind: "state", + version: 1, + data: { text }, + }, + ]; + const next = entry(items[random(items.length)], { turnId: String(turn) }); + const retired = backends.map((backend) => backend.isRetired(scope, next)); + expect(retired[1]).toBe(retired[0]); + const results = backends.map((backend) => backend.append(scope, [next])); + expect(results[1]).toEqual(results[0]); + } + expectSameHistory(memory, sqlite); + // Seeding from projected rows, as an import does, keeps both in step too. + const rows = memory.readRows(scope); + for (const backend of backends) backend.create({ agentId: "seeded" }, { rows, epoch: "e" }); + expectSameHistory(memory, sqlite, { agentId: "seeded" }); + } + }); +}); + +function expectSameHistory( + memory: MemoryTimelineBackend, + sqlite: SqliteTimelineBackend, + target: TimelineScope = scope, +): void { + expect(sqlite.head(target)).toEqual(memory.head(target)); + expect(sqlite.readRows(target)).toEqual(memory.readRows(target)); + expect(sqlite.retiredRows(target)).toEqual(memory.retiredRows(target)); + expect(sqlite.prompts(target)).toEqual(memory.prompts(target)); + expect(sqlite.lastItem(target)).toEqual(memory.lastItem(target)); + expect(sqlite.lastAssistantMessage(target)).toEqual(memory.lastAssistantMessage(target)); + const maxSeq = memory.head(target)!.seq; + for (const direction of ["tail", "before", "after"] as const) { + for (const wholeTurns of [false, true]) { + for (const limit of [0, 1, 3, 10]) { + for (const cursorSeq of [0, 1, Math.floor(maxSeq / 3), Math.floor(maxSeq / 2), maxSeq]) { + const options: AgentTimelineFetchOptions = { + direction, + wholeTurns, + limit, + cursor: { epoch: "e", seq: cursorSeq }, + }; + expect({ options, page: sqlite.fetch(target, options) }).toEqual({ + options, + page: memory.fetch(target, options), + }); + } + } + } + } +} + +describe("SQLite timeline durability", () => { + it("keeps rows, turns, metrics, provider ids, rewinds, and children across a restart", async () => { + const file = nextTestDatabasePath(); + let database = openTestTimelineDatabase(file); + let timeline = new AgentTimeline(new SqliteTimelineBackend(database)); + await timeline.create(scope, { epoch: "e" }); + await timeline.ingest( + scope, + entry( + { type: "user_message", text: "first", messageId: "m1", clientMessageId: "c1" }, + { turnId: "t1" }, + ), + ); + await timeline.attachProviderMessageId(scope, "c1", "p1"); + await timeline.append(scope, [ + entry({ type: "assistant_message", text: "Hel" }, { turnId: "t1" }), + entry({ type: "assistant_message", text: "lo" }, { turnId: "t1" }), + entry(tool("spawn", "running"), { turnId: "t1" }), + ]); + await timeline.stampTurnMetrics(scope, [{ name: "tokens", value: 3 }] as never, { + turnId: "t1", + }); + await timeline.append(scope, [ + entry({ type: "user_message", text: "second", messageId: "m2" }, { turnId: "t2" }), + entry({ type: "assistant_message", text: "Done" }, { turnId: "t2" }), + ]); + const child: TimelineScope = { agentId: "agent", subagentId: "child" }; + await timeline.recordChild(child, () => descriptor("child", "spawn")); + await timeline.recordChildEntries(child, [entry({ type: "assistant_message", text: "kid" })]); + const intent = await timeline.beginRewind(scope, "m1"); + await timeline.recordRewindCut(scope, intent.id, { kind: "at_target" }); + const rowsBefore = await timeline.readRows(scope); + const headBefore = await timeline.describe(scope); + await timeline.close(); + database.close(); + + database = openTestTimelineDatabase(file); + timeline = new AgentTimeline(new SqliteTimelineBackend(database)); + expect(await timeline.describe(scope)).toEqual(headBefore); + expect(headBefore?.rewind).toMatchObject({ id: intent.id, cut: { kind: "at_target" } }); + const rowsAfter = await timeline.readRows(scope); + expect(rowsAfter).toEqual(rowsBefore); + expect(rowsAfter.map((row) => row.turnId)).toEqual(["t1", "t1", "t1", "t2", "t2"]); + expect(rowsAfter[0].providerMessageId).toBe("p1"); + expect(rowsAfter[1]).toMatchObject({ + item: { text: "Hello" }, + turnMetrics: [{ name: "tokens", value: 3 }], + }); + // Turn ids survive, so a whole-turns tail still stops at the last turn (#10030). + const lastTurn = await timeline.fetch(scope, { direction: "tail", limit: 1, wholeTurns: true }); + expect(lastTurn.rows.map((row) => row.turnId)).toEqual(["t2", "t2"]); + expect(await timeline.listChildren("agent")).toEqual([ + { subagentId: "child", descriptor: descriptor("child", "spawn"), retired: false }, + ]); + expect((await timeline.readRows(child)).map((row) => row.item)).toEqual([ + { type: "assistant_message", text: "kid" }, + ]); + + // The rewind opened before the restart completes after it. + const completion = await timeline.completeRewind(scope, intent.id); + expect(completion).toMatchObject({ kind: "retired", retiredChildIds: ["child"] }); + await timeline.close(); + database.close(); + + database = openTestTimelineDatabase(file); + const backend = new SqliteTimelineBackend(database); + timeline = new AgentTimeline(backend); + expect(await timeline.readRows(scope)).toEqual([]); + expect(backend.retiredRows(scope)).toEqual(rowsBefore); + expect(await timeline.describe(scope)).toMatchObject({ retirementCount: 1, rewind: null }); + expect(await timeline.listChildren("agent")).toMatchObject([ + { subagentId: "child", retired: true }, + ]); + // Late output of a retired tool call is still dropped. + expect(await timeline.ingest(scope, entry(tool("spawn", "completed")))).toEqual({ + kind: "dropped", + }); + const tail = await timeline.fetch(scope, { direction: "tail" }); + expect(tail.retirements).toEqual([{ seq: 7, retireFromSeq: 1 }]); + await timeline.close(); + database.close(); + }); + + it("finishes queued writes on close, then refuses new ones", async () => { + const file = nextTestDatabasePath(); + let database = openTestTimelineDatabase(file); + const timeline = new AgentTimeline( + new DeferredTimelineBackend(new SqliteTimelineBackend(database)), + ); + await timeline.create(scope, { epoch: "e" }); + const writes = ["a", "b", "c"].map((text) => + timeline.append(scope, [entry({ type: "user_message", text })]), + ); + await timeline.close(); + await expect( + timeline.append(scope, [entry({ type: "user_message", text: "late" })]), + ).rejects.toBeInstanceOf(TimelineClosedError); + // Nothing is left to wait for, so code that orders itself behind the timeline still runs. + await expect(timeline.settled(scope)).resolves.toBeUndefined(); + await Promise.all(writes); + database.close(); + + database = openTestTimelineDatabase(file); + const rows = new SqliteTimelineBackend(database).readRows(scope); + expect(rows.map((row) => row.item)).toMatchObject([ + { text: "a" }, + { text: "b" }, + { text: "c" }, + ]); + database.close(); + }); +}); + +describe("SQLite timeline write failures", () => { + function failOn(database: DaemonDatabase, table: string): void { + database.write((sql) => + sql.exec( + `CREATE TRIGGER fail_${table} BEFORE INSERT ON ${table} ` + + "BEGIN SELECT RAISE(ABORT, 'disk full'); END", + ), + ); + } + + it("leaves no part of a failed append", () => { + const database = openTestTimelineDatabase(); + const backend = new SqliteTimelineBackend(database); + backend.create(scope, { epoch: "e" }); + backend.append(scope, [entry({ type: "user_message", text: "kept" })]); + const before = dumpTables(database); + failOn(database, "timeline_text"); + // The prompt is written before the reply's text fails. + expect(() => + backend.append(scope, [ + entry({ type: "user_message", text: "lost" }), + entry({ type: "assistant_message", text: "lost" }), + ]), + ).toThrow(/disk full/); + expect(dumpTables(database)).toEqual(before); + expect(backend.head(scope)).toMatchObject({ seq: 1, size: 1 }); + database.close(); + }); + + it("leaves no part of a failed retirement", () => { + const database = openTestTimelineDatabase(); + const backend = new SqliteTimelineBackend(database); + backend.create(scope, { epoch: "e" }); + backend.append(scope, [ + entry({ type: "user_message", text: "one", messageId: "m1" }, { turnId: "t1" }), + entry(tool("call", "running"), { turnId: "t1" }), + ]); + backend.setChild({ agentId: "agent", subagentId: "child" }, descriptor("child", "call")); + backend.setRewind(scope, { id: "r", messageId: "m1", targetSeq: 1 }); + const before = dumpTables(database); + failOn(database, "timeline_retirements"); + // Rows, keys, ranges, and the child are written before the retirement fails. + expect(() => + backend.retire(scope, { retireFromSeq: 1, selectChildren: () => ["child"] }), + ).toThrow(/disk full/); + expect(dumpTables(database)).toEqual(before); + expect(backend.isRetired(scope, entry(tool("call", "completed")))).toBe(false); + database.close(); + }); +}); + +describe("SQLite timeline reads", () => { + function longHistory(): { database: CountingDatabase; backend: SqliteTimelineBackend } { + const database = new CountingDatabase(openTestTimelineDatabase()); + const backend = new SqliteTimelineBackend(database); + backend.create(scope, { epoch: "e" }); + for (let batch = 0; batch < 50; batch++) { + const entries: TimelineEntry[] = []; + for (let index = 0; index < 10; index++) { + const turnId = `t${batch * 10 + index}`; + entries.push( + entry({ type: "user_message", text: turnId, messageId: turnId }, { turnId }), + entry(tool(`${turnId}-call`, "completed"), { turnId }), + entry({ type: "assistant_message", text: "a" }, { turnId }), + entry({ type: "assistant_message", text: "b" }, { turnId }), + ); + } + backend.append(scope, entries); + } + return { database, backend }; + } + + it("reads a bounded slice of a long history for a page", () => { + const { database, backend } = longHistory(); + expect(backend.head(scope)).toMatchObject({ seq: 2000, size: 1500 }); + const pages: AgentTimelineFetchOptions[] = [ + { direction: "tail", limit: 20 }, + { direction: "tail", limit: 20, wholeTurns: true }, + { direction: "before", limit: 20, cursor: { epoch: "e", seq: 1000 } }, + { direction: "before", limit: 20, cursor: { epoch: "e", seq: 1000 }, wholeTurns: true }, + { direction: "after", limit: 20, cursor: { epoch: "e", seq: 1000 } }, + ]; + for (const options of pages) { + database.rowsRead = 0; + expect(backend.fetch(scope, options).rows.length).toBeGreaterThanOrEqual(20); + expect(database.rowsRead, JSON.stringify(options)).toBeLessThan(150); + } + for (const read of [ + () => backend.head(scope), + () => backend.lastItem(scope), + () => backend.lastAssistantMessage(scope), + () => backend.isRetired(scope, entry(tool("t3-call", "completed"))), + () => backend.findSubmittedPrompt(scope, "absent"), + () => backend.stampTurnMetrics(scope, [], { turnId: "t499" }), + ]) { + database.rowsRead = 0; + read(); + expect(database.rowsRead).toBeLessThan(20); + } + database.close(); + }); + + it("writes a streamed chunk without rewriting the message's earlier text", () => { + const database = openTestTimelineDatabase(); + const backend = new SqliteTimelineBackend(database); + backend.create(scope, { epoch: "e" }); + const storedRowSize = () => + database.read( + (sql) => sql.get<{ size: number }>("SELECT length(row) AS size FROM timeline_rows")!.size, + ); + for (let chunk = 0; chunk < 100; chunk++) { + backend.append(scope, [entry({ type: "assistant_message", text: "x".repeat(1000) })]); + } + // The row holds only its metadata; the 100,000 characters of text are chunks beside it. + expect(storedRowSize()).toBeLessThan(300); + expect(backend.lastAssistantMessage(scope)).toHaveLength(100_000); + database.close(); + }); +}); diff --git a/packages/server/src/server/agent/timeline/testing.ts b/packages/server/src/server/agent/timeline/testing.ts index 7e18b8284b..d586e1c9c5 100644 --- a/packages/server/src/server/agent/timeline/testing.ts +++ b/packages/server/src/server/agent/timeline/testing.ts @@ -1,4 +1,8 @@ import { setImmediate as nextTurn } from "node:timers/promises"; +import { onTestFinished } from "vitest"; +import { createTestLogger } from "../../../test-utils/test-logger.js"; +import { nextTestDatabasePath } from "../../test-utils/test-database-path.js"; +import { openDaemonDatabase, type DaemonDatabase } from "../../database/index.js"; import type { AgentMetric, AgentTimelineItem } from "../agent-sdk-types.js"; import type { AgentTimelineFetchOptions, @@ -22,6 +26,7 @@ import type { TimelineSeed, } from "./internal/backend.js"; import { MemoryTimelineBackend } from "./internal/memory-backend.js"; +import { SqliteTimelineBackend, timelineSchema } from "./internal/sqlite-backend.js"; /** * Testing entry point of the timeline module. Production code imports `./index.js`. @@ -39,7 +44,25 @@ export interface InspectableTimelineBackend extends AgentTimelineBackend { export const TIMELINE_CONTRACT_BACKENDS: ReadonlyArray<{ name: string; create: () => InspectableTimelineBackend; -}> = [{ name: "memory", create: () => new MemoryTimelineBackend() }]; +}> = [ + { name: "memory", create: () => new MemoryTimelineBackend() }, + { name: "sqlite", create: () => new SqliteTimelineBackend(openTestTimelineDatabase()) }, +]; + +/** + * Opens a fresh file-backed timeline database, closed when the calling test finishes, in a + * directory removed when the process exits. Pass the path of an earlier database to reopen it, as + * a daemon restart does. + */ +export function openTestTimelineDatabase(file?: string): DaemonDatabase { + const database = openDaemonDatabase({ + path: file ?? nextTestDatabasePath(), + modules: [timelineSchema], + logger: createTestLogger(), + }); + onTestFinished(() => database.close()); + return database; +} /** * Wraps a backend: defers every call by a turn of the event loop, the shape of an I/O-backed diff --git a/packages/server/src/server/bootstrap.smoke.test.ts b/packages/server/src/server/bootstrap.smoke.test.ts index a935036459..a7ce43cbbf 100644 --- a/packages/server/src/server/bootstrap.smoke.test.ts +++ b/packages/server/src/server/bootstrap.smoke.test.ts @@ -22,7 +22,7 @@ import { createPersistedWorkspaceRecord, } from "./workspace-registry.js"; import { AgentStorage, type StoredAgentRecord } from "./agent/agent-storage.js"; -import { ensureAgentLoaded } from "./agent/agent-loading.js"; +import { ensureAgentLoaded, loadAgentHistory } from "./agent/agent-loading.js"; import { AgentManagerShuttingDownError } from "./agent/agent-manager.js"; import { hashDaemonPassword } from "./auth.js"; import { generateLocalPairingOffer } from "./pairing-offer.js"; @@ -94,59 +94,54 @@ describe("paseo daemon bootstrap", () => { } }); - test("keeps timeline activity in memory and removes obsolete timeline files at startup", async () => { - const paseoHomeRoot = await mkdtemp(path.join(os.tmpdir(), "paseo-timeline-cleanup-")); + test("stores timelines in paseo.db and serves them after a restart without loading the agent", async () => { + const paseoHomeRoot = await mkdtemp(path.join(os.tmpdir(), "paseo-timeline-restart-")); const paseoHome = path.join(paseoHomeRoot, ".paseo"); const obsoleteTimelineDirectory = path.join(paseoHome, "agent-timelines"); const agentCwd = await mkdtemp(path.join(os.tmpdir(), "paseo-timeline-agent-")); await mkdir(obsoleteTimelineDirectory, { recursive: true }); await writeFile(path.join(obsoleteTimelineDirectory, "obsolete.json"), "{}\n", "utf-8"); - - const daemonHandle = await createTestPaseoDaemon({ paseoHomeRoot, cleanup: false }); try { - await expect(access(obsoleteTimelineDirectory)).rejects.toMatchObject({ code: "ENOENT" }); + const first = await createTestPaseoDaemon({ paseoHomeRoot, cleanup: false }); + let agentId: string; + try { + await expect(access(obsoleteTimelineDirectory)).rejects.toMatchObject({ code: "ENOENT" }); + const agent = await first.daemon.agentManager.createAgent( + { provider: "codex", cwd: agentCwd }, + undefined, + { workspaceId: undefined }, + ); + agentId = agent.id; + await first.daemon.agentManager.appendTimelineItem(agent.id, { + type: "assistant_message", + text: "kept across the restart", + }); + await first.daemon.agentManager.flush(); + } finally { + await first.close(); + } + await access(path.join(paseoHome, "paseo.db")); - const agent = await daemonHandle.daemon.agentManager.createAgent( - { provider: "codex", cwd: agentCwd }, - undefined, - { workspaceId: undefined }, - ); - await daemonHandle.daemon.agentManager.appendTimelineItem(agent.id, { - type: "assistant_message", - text: "timeline stays in memory", - }); - await daemonHandle.daemon.agentManager.flush(); - - await expect(access(obsoleteTimelineDirectory)).rejects.toMatchObject({ code: "ENOENT" }); + const second = await createTestPaseoDaemon({ paseoHomeRoot, cleanup: false }); + try { + const { agentManager, agentStorage } = second.daemon; + const source = await loadAgentHistory(agentId, { + agentManager, + agentStorage, + logger: pino({ level: "silent" }), + purpose: "history", + }); + expect(source.kind).toBe("stored"); + const page = await agentManager.fetchTimeline(agentId, { direction: "tail" }); + expect(page.rows.map((row) => row.item)).toContainEqual({ + type: "assistant_message", + text: "kept across the restart", + }); + expect(agentManager.getAgent(agentId)).toBeNull(); + } finally { + await second.close(); + } } finally { - await daemonHandle.close(); - await Promise.all([ - rm(paseoHomeRoot, { recursive: true, force: true }), - rm(agentCwd, { recursive: true, force: true }), - ]); - } - }); - - test("does not create a timeline directory for live timeline activity", async () => { - const paseoHomeRoot = await mkdtemp(path.join(os.tmpdir(), "paseo-timeline-memory-")); - const agentCwd = await mkdtemp(path.join(os.tmpdir(), "paseo-timeline-agent-")); - const daemonHandle = await createTestPaseoDaemon({ paseoHomeRoot, cleanup: false }); - const timelineDirectory = path.join(daemonHandle.paseoHome, "agent-timelines"); - try { - const agent = await daemonHandle.daemon.agentManager.createAgent( - { provider: "codex", cwd: agentCwd }, - undefined, - { workspaceId: undefined }, - ); - await daemonHandle.daemon.agentManager.appendTimelineItem(agent.id, { - type: "assistant_message", - text: "timeline stays in memory", - }); - await daemonHandle.daemon.agentManager.flush(); - - await expect(access(timelineDirectory)).rejects.toMatchObject({ code: "ENOENT" }); - } finally { - await daemonHandle.close(); await Promise.all([ rm(paseoHomeRoot, { recursive: true, force: true }), rm(agentCwd, { recursive: true, force: true }), diff --git a/packages/server/src/server/bootstrap.ts b/packages/server/src/server/bootstrap.ts index d4eead0aed..16f1c7f3e0 100644 --- a/packages/server/src/server/bootstrap.ts +++ b/packages/server/src/server/bootstrap.ts @@ -14,7 +14,7 @@ import { describeHookWorkspace } from "./plugins/lifecycle/index.js"; import express from "express"; import { createServer as createHTTPServer, type IncomingMessage, type ServerResponse } from "http"; import { constants, existsSync, unlinkSync } from "fs"; -import { open, rm, stat } from "fs/promises"; +import { mkdir, open, rm, stat } from "fs/promises"; import { randomUUID } from "node:crypto"; import { getCachedHostMachineKind, primeHostMachineKind } from "./host-machine-kind.js"; import { getHostName } from "./host-name.js"; @@ -149,6 +149,8 @@ import type { RequestedSpeechProviders } from "./speech/speech-types.js"; import { createSpeechService } from "./speech/speech-runtime.js"; import { createSpeechSettingsOwner } from "./speech/speech-settings.js"; import { AgentManager } from "./agent/agent-manager.js"; +import { createStoredAgentTimeline, timelineSchema } from "./agent/timeline/index.js"; +import { openDaemonDatabase } from "./database/index.js"; import { AgentStorage } from "./agent/agent-storage.js"; import { attachAgentStoragePersistence } from "./persistence-hooks.js"; import { createAgentMcpServer } from "./agent/mcp-server.js"; @@ -649,6 +651,13 @@ export async function createPaseoDaemon( "Failed to remove obsolete agent timeline data", ); }); + await mkdir(config.paseoHome, { recursive: true }); + const database = openDaemonDatabase({ + path: path.join(config.paseoHome, "paseo.db"), + modules: [timelineSchema], + logger: rootLogger.child({ module: "database" }), + }); + const timeline = createStoredAgentTimeline(database); const bootstrapStart = performance.now(); const elapsed = () => `${(performance.now() - bootstrapStart).toFixed(0)}ms`; const daemonVersion = config.daemonVersion ?? resolveDaemonVersion(import.meta.url); @@ -1051,6 +1060,7 @@ export async function createPaseoDaemon( clients: initialAgentManagerState.clients, providerDefinitions: initialAgentManagerState.providerDefinitions, registry: agentStorage, + timeline, appendSystemPrompt: config.appendSystemPrompt, onWorkspaceStateMayHaveChanged: ({ cwd }) => { workspaceGitService.onWorkspaceStateMayHaveChanged(cwd); @@ -2053,6 +2063,8 @@ export async function createPaseoDaemon( httpServer.closeAllConnections(); await new Promise((resolve) => httpServer.close(() => resolve())); } + await timeline.close(); + database.close(); throw error; } }; @@ -2128,6 +2140,8 @@ export async function createPaseoDaemon( if (wsServer) { await wsServer.close(); } + await timeline.close(); + database.close(); forgeResolver.dispose(); await serviceProxy.stopStandalone(); // Force-drop remaining sockets so httpServer.close() resolves promptly. diff --git a/packages/server/src/server/database/daemon-database.test.ts b/packages/server/src/server/database/daemon-database.test.ts new file mode 100644 index 0000000000..2e12f560ea --- /dev/null +++ b/packages/server/src/server/database/daemon-database.test.ts @@ -0,0 +1,351 @@ +import { mkdtempSync, rmSync, statSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { createTestLogger } from "../../test-utils/test-logger.js"; +import { + DatabaseClosedError, + DatabaseOpenError, + DatabaseSchemaTooNewError, + openDaemonDatabase, + type DaemonDatabase, + type ReadSql, + type SchemaModule, + type WriteSql, +} from "./index.js"; +import { WalCheckpointer } from "./internal/wal-checkpointer.js"; + +let directory: string; +let databasePath: string; +const opened: DaemonDatabase[] = []; + +beforeEach(() => { + directory = mkdtempSync(path.join(tmpdir(), "paseo-database-")); + databasePath = path.join(directory, "paseo.db"); +}); + +afterEach(() => { + for (const database of opened.splice(0)) database.close(); + rmSync(directory, { recursive: true, force: true }); +}); + +function open(modules: readonly SchemaModule[]): DaemonDatabase { + const database = openDaemonDatabase({ path: databasePath, modules, logger: createTestLogger() }); + opened.push(database); + return database; +} + +function reopen(database: DaemonDatabase, modules: readonly SchemaModule[]): DaemonDatabase { + database.close(); + return open(modules); +} + +const notes: SchemaModule = { + name: "notes", + migrations: [ + { + up: (sql) => + sql.exec("CREATE TABLE notes_items (id INTEGER PRIMARY KEY, text TEXT NOT NULL)"), + }, + ], +}; + +function count(database: DaemonDatabase, table: string): number { + return database.read((sql) => sql.get<{ n: number }>(`SELECT count(*) AS n FROM ${table}`)!.n); +} + +function tableNames(database: DaemonDatabase): string[] { + return database.read((sql) => + sql + .all<{ name: string }>("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name") + .map((row) => row.name), + ); +} + +function versions(database: DaemonDatabase) { + return database.read((sql) => + sql.all<{ module: string; version: number; min_reader_version: number }>( + "SELECT module, version, min_reader_version FROM schema_versions ORDER BY module", + ), + ); +} + +describe("opening the daemon database", () => { + it("creates the file in WAL mode with foreign keys on", () => { + const database = open([notes]); + expect( + database.read((sql) => ({ + journal: sql.get<{ journal_mode: string }>("PRAGMA journal_mode")!.journal_mode, + foreignKeys: sql.get<{ foreign_keys: number }>("PRAGMA foreign_keys")!.foreign_keys, + synchronous: sql.get<{ synchronous: number }>("PRAGMA synchronous")!.synchronous, + })), + ).toEqual({ journal: "wal", foreignKeys: 1, synchronous: 1 }); + expect(versions(database)).toEqual([{ module: "notes", version: 1, min_reader_version: 1 }]); + }); + + it("keeps committed rows across a reopen and runs no migration twice", () => { + let database = open([notes]); + database.write((sql) => sql.run("INSERT INTO notes_items (text) VALUES (?)", "kept")); + database = reopen(database, [notes]); + expect(database.read((sql) => sql.all("SELECT text FROM notes_items"))).toEqual([ + { text: "kept" }, + ]); + expect(versions(database)).toEqual([{ module: "notes", version: 1, min_reader_version: 1 }]); + }); + + it("runs only the pending migrations of a module that gained some", () => { + let database = open([notes]); + database.write((sql) => sql.run("INSERT INTO notes_items (text) VALUES ('a')")); + database = reopen(database, [ + { + name: "notes", + migrations: [ + ...notes.migrations, + { up: (sql) => sql.exec("ALTER TABLE notes_items ADD COLUMN pinned INTEGER") }, + ], + }, + ]); + expect(database.read((sql) => sql.all("SELECT text, pinned FROM notes_items"))).toEqual([ + { text: "a", pinned: null }, + ]); + expect(versions(database)).toEqual([{ module: "notes", version: 2, min_reader_version: 1 }]); + }); + + it("migrates several modules independently", () => { + const tags: SchemaModule = { + name: "tags", + migrations: [{ up: (sql) => sql.exec("CREATE TABLE tags_items (name TEXT)") }], + }; + let database = open([notes]); + database = reopen(database, [notes, tags]); + expect(tableNames(database)).toEqual(["notes_items", "schema_versions", "tags_items"]); + expect(versions(database).map((row) => [row.module, row.version])).toEqual([ + ["notes", 1], + ["tags", 1], + ]); + }); + + it("rolls every migration back when one fails, so the next open retries from the same state", () => { + const failing: SchemaModule = { + name: "notes", + migrations: [ + ...notes.migrations, + { + up: (sql) => { + sql.exec("CREATE TABLE notes_extra (id INTEGER)"); + throw new Error("migration bug"); + }, + }, + ], + }; + expect(() => + openDaemonDatabase({ path: databasePath, modules: [failing], logger: createTestLogger() }), + ).toThrow(DatabaseOpenError); + const database = open([]); + expect(tableNames(database)).toEqual(["schema_versions"]); + }); + + it("opens a database a newer daemon changed additively, and ignores stores it does not know", () => { + const newer: SchemaModule = { + name: "notes", + migrations: [ + ...notes.migrations, + { up: (sql) => sql.exec("ALTER TABLE notes_items ADD COLUMN pinned INTEGER") }, + ], + }; + const unknownStore: SchemaModule = { + name: "future", + migrations: [{ up: (sql) => sql.exec("CREATE TABLE future_items (id INTEGER)") }], + }; + let database = open([newer, unknownStore]); + database.write((sql) => sql.run("INSERT INTO notes_items (text, pinned) VALUES ('a', 1)")); + database = reopen(database, [notes]); + expect(database.read((sql) => sql.all("SELECT text FROM notes_items"))).toEqual([ + { text: "a" }, + ]); + expect(versions(database)).toEqual([ + { module: "future", version: 1, min_reader_version: 1 }, + { module: "notes", version: 2, min_reader_version: 1 }, + ]); + }); + + it("refuses a database a newer daemon changed in a way this daemon cannot read", () => { + const breaking: SchemaModule = { + name: "notes", + migrations: [ + ...notes.migrations, + { up: (sql) => sql.exec("DROP TABLE notes_items"), breaking: true }, + ], + }; + open([breaking]).close(); + opened.length = 0; + let error: unknown; + try { + openDaemonDatabase({ path: databasePath, modules: [notes], logger: createTestLogger() }); + } catch (thrown) { + error = thrown; + } + expect(error).toBeInstanceOf(DatabaseSchemaTooNewError); + expect(error).toMatchObject({ module: "notes", minReaderVersion: 2, knownVersion: 1 }); + expect((error as Error).message).toContain(databasePath); + }); + + it("fails with the path when the file is not a database", () => { + const corrupt = path.join(directory, "corrupt.db"); + writeFileSync(corrupt, "this is not a sqlite file, it is some text long enough to be read"); + let error: unknown; + try { + openDaemonDatabase({ path: corrupt, modules: [notes], logger: createTestLogger() }); + } catch (thrown) { + error = thrown; + } + expect(error).toBeInstanceOf(DatabaseOpenError); + expect((error as Error).message).toContain(corrupt); + }); +}); + +function insert(sql: WriteSql, text: string): void { + sql.run("INSERT INTO notes_items (text) VALUES (?)", text); +} + +function insertThenThrow(sql: WriteSql, text: string): never { + insert(sql, text); + throw new Error(`failed after ${text}`); +} + +function texts(database: DaemonDatabase): string[] { + return database.read((sql) => + sql.all<{ text: string }>("SELECT text FROM notes_items ORDER BY id").map((row) => row.text), + ); +} + +it("rolls a write back when its callback throws", () => { + const database = open([notes]); + expect(() => database.write((sql) => insertThenThrow(sql, "lost"))).toThrow("failed after lost"); + expect(count(database, "notes_items")).toBe(0); +}); + +it("rolls back only a nested write that throws", () => { + const database = open([notes]); + const writeOuter = (sql: WriteSql) => { + insert(sql, "outer"); + expect(() => database.write((inner) => insertThenThrow(inner, "inner"))).toThrow( + "failed after inner", + ); + database.write((inner) => insert(inner, "second")); + }; + database.write(writeOuter); + expect(texts(database)).toEqual(["outer", "second"]); +}); + +it("joins a read nested in a write, which sees the write's uncommitted rows", () => { + const database = open([notes]); + database.write((sql) => { + insert(sql, "pending"); + expect(count(database, "notes_items")).toBe(1); + }); +}); + +it("refuses a write inside a read", () => { + const database = open([notes]); + const writeInsideRead = () => database.write((sql) => insert(sql, "late")); + expect(() => database.read(writeInsideRead)).toThrow(/inside a read/); +}); + +it("refuses an asynchronous callback and rolls its work back", () => { + const database = open([notes]); + const writeAsync = async (sql: WriteSql) => insert(sql, "async"); + expect(() => database.write(writeAsync)).toThrow(/synchronous/); + expect(count(database, "notes_items")).toBe(0); +}); + +it("invalidates a handle once its callback returns", () => { + const database = open([notes]); + let leaked: WriteSql | undefined; + database.write((sql) => { + leaked = sql; + }); + expect(() => insert(leaked!, "late")).toThrow(/after its transaction/); + expect(count(database, "notes_items")).toBe(0); +}); + +it("closes an unfinished iterator before the transaction ends", () => { + const database = open([notes]); + database.write((sql) => ["a", "b", "c"].forEach((text) => insert(sql, text))); + let rest: Iterator | undefined; + const first = database.read((sql) => { + const iterator = sql.iterate("SELECT text FROM notes_items ORDER BY id")[Symbol.iterator](); + rest = iterator; + return iterator.next().value; + }); + expect(first).toEqual({ text: "a" }); + expect(() => rest!.next()).toThrow(/after its transaction/); + // A statement left open makes schema changes fail with "database table is locked". + database.write((sql) => sql.exec("DROP TABLE notes_items")); + expect(tableNames(database)).toEqual(["schema_versions"]); +}); + +it("refuses to reuse a statement that an unfinished iterator holds", () => { + const database = open([notes]); + database.write((sql) => insert(sql, "a")); + const query = "SELECT text FROM notes_items"; + const reuse = (sql: ReadSql) => { + sql.iterate(query)[Symbol.iterator]().next(); + expect(() => sql.all(query)).toThrow(/already iterating/); + }; + database.read(reuse); +}); + +it("checkpoints the WAL off the daemon thread, never during a write", async () => { + const database = open([notes]); + expect( + database.read((sql) => sql.get<{ wal_autocheckpoint: number }>("PRAGMA wal_autocheckpoint")), + ).toEqual({ wal_autocheckpoint: 0 }); + const fileSize = () => statSync(databasePath).size; + const before = fileSize(); + const writeBatch = (sql: WriteSql) => { + for (let row = 0; row < 50; row++) insert(sql, "x".repeat(1000)); + }; + for (let batch = 0; batch < 20; batch++) database.write(writeBatch); + // Writes go to the WAL. Only a checkpoint copies them into the database file. + await vi.waitFor(() => expect(fileSize()).toBeGreaterThan(before + 500_000), { + timeout: 10_000, + interval: 50, + }); +}); + +it("rejects every call after close", () => { + const database = open([notes]); + database.close(); + expect(() => database.read((sql) => sql.all("SELECT 1"))).toThrow(DatabaseClosedError); + expect(() => database.close()).not.toThrow(); +}); + +describe("the WAL checkpointer", () => { + it("stops and closes its connection when asked, without reporting an exit", () => { + open([notes]).write((sql) => insert(sql, "a")); + let exited = false; + const checkpointer = new WalCheckpointer({ + path: databasePath, + logger: createTestLogger(), + onExit: () => { + exited = true; + }, + }); + expect(checkpointer.stop()).toBe(true); + expect(exited).toBe(false); + }); + + it("reports a worker that ends on its own, so the database can checkpoint itself again", async () => { + let exited = false; + const checkpointer = new WalCheckpointer({ + path: path.join(directory, "missing", "paseo.db"), + logger: createTestLogger(), + onExit: () => { + exited = true; + }, + }); + await vi.waitFor(() => expect(exited).toBe(true), { timeout: 10_000, interval: 20 }); + expect(checkpointer.stop()).toBe(true); + }); +}); diff --git a/packages/server/src/server/database/index.ts b/packages/server/src/server/database/index.ts new file mode 100644 index 0000000000..db6756d410 --- /dev/null +++ b/packages/server/src/server/database/index.ts @@ -0,0 +1,12 @@ +export { + DatabaseClosedError, + DatabaseOpenError, + DatabaseSchemaTooNewError, + openDaemonDatabase, + type DaemonDatabase, + type Migration, + type ReadSql, + type SchemaModule, + type SqlValue, + type WriteSql, +} from "./internal/daemon-database.js"; diff --git a/packages/server/src/server/database/internal/daemon-database.ts b/packages/server/src/server/database/internal/daemon-database.ts new file mode 100644 index 0000000000..985e45a8bb --- /dev/null +++ b/packages/server/src/server/database/internal/daemon-database.ts @@ -0,0 +1,404 @@ +import type { DatabaseSync, SQLInputValue, StatementSync } from "node:sqlite"; +import type { Logger } from "pino"; +import { WalCheckpointer } from "./wal-checkpointer.js"; + +export type SqlValue = SQLInputValue; + +/** Queries available inside `DaemonDatabase.read`. A handle is valid only inside its callback. */ +export interface ReadSql { + get(sql: string, ...params: SqlValue[]): T | undefined; + all(sql: string, ...params: SqlValue[]): T[]; + /** Lazy rows. An unfinished iteration is closed when the callback returns. */ + iterate(sql: string, ...params: SqlValue[]): Iterable; +} + +/** Queries available inside `DaemonDatabase.write`. */ +export interface WriteSql extends ReadSql { + run(sql: string, ...params: SqlValue[]): { changes: number }; + /** Runs one or more statements without caching them, for schema changes. */ + exec(sql: string): void; +} + +export interface Migration { + up(sql: WriteSql): void; + /** + * The change leaves the schema unreadable for a daemon that knows only the earlier migrations, + * for example a dropped or renamed column. Additive changes leave this unset. + */ + breaking?: boolean; +} + +/** A store's schema: its tables, named with the store's prefix, and their migrations in order. */ +export interface SchemaModule { + name: string; + /** Append-only. The module's version is the number of migrations applied. */ + migrations: readonly Migration[]; +} + +/** + * The daemon's SQLite database. Calls are synchronous and run on the caller's thread, so + * transactions never interleave. A callback must not be asynchronous: a transaction never spans + * an `await`. + */ +export interface DaemonDatabase { + /** One write transaction. A throw rolls it back. Nested in a write, it is a savepoint. */ + write(fn: (sql: WriteSql) => T): T; + /** One consistent read. Nested in a read or write, it joins the outer transaction. */ + read(fn: (sql: ReadSql) => T): T; + /** Checkpoints the WAL and closes the file. Later calls throw `DatabaseClosedError`. */ + close(): void; +} + +export class DatabaseClosedError extends Error { + constructor() { + super("The daemon database is closed"); + this.name = "DatabaseClosedError"; + } +} + +/** The database cannot be used: `node:sqlite` is missing, or the file cannot be opened or migrated. */ +export class DatabaseOpenError extends Error { + constructor( + readonly path: string, + cause: unknown, + ) { + super(`Cannot open the Paseo database at ${path}: ${describeError(cause)}`, { cause }); + this.name = "DatabaseOpenError"; + } +} + +/** A newer daemon changed a store's schema in a way this daemon cannot read. */ +export class DatabaseSchemaTooNewError extends Error { + constructor( + readonly path: string, + readonly module: string, + readonly minReaderVersion: number, + readonly knownVersion: number, + ) { + super( + `The Paseo database at ${path} was changed by a newer Paseo: store '${module}' needs ` + + `schema version ${minReaderVersion}, this daemon knows version ${knownVersion}. ` + + "Update Paseo to use it.", + ); + this.name = "DatabaseSchemaTooNewError"; + } +} + +const BUSY_TIMEOUT_MS = 1000; +const JOURNAL_SIZE_LIMIT_BYTES = 64 * 1024 * 1024; + +/** + * Opens the database at `path`, creating the file when absent in a directory that must exist, and + * brings every module's schema up to date in one transaction. Throws `DatabaseOpenError` or `DatabaseSchemaTooNewError`. + */ +export function openDaemonDatabase(input: { + path: string; + modules: readonly SchemaModule[]; + logger: Logger; +}): DaemonDatabase { + let connection: DatabaseSync | undefined; + try { + const sqlite = loadSqlite(); + connection = new sqlite.DatabaseSync(input.path, { timeout: BUSY_TIMEOUT_MS }); + connection.exec( + [ + "PRAGMA journal_mode = WAL", + "PRAGMA synchronous = NORMAL", + "PRAGMA foreign_keys = ON", + `PRAGMA journal_size_limit = ${JOURNAL_SIZE_LIMIT_BYTES}`, + ].join(";"), + ); + const database = new SqliteDaemonDatabase(connection, input.logger); + migrate(database, input.path, input.modules); + if (input.path !== ":memory:") database.checkpointOffThread(input.path); + return database; + } catch (error) { + connection?.close(); + if (error instanceof DatabaseSchemaTooNewError) throw error; + throw new DatabaseOpenError(input.path, error); + } +} + +function loadSqlite(): typeof import("node:sqlite") { + // Loaded on open, not imported: Node 22 warns that the module is experimental when it loads, and + // CLI commands import this package without opening a database. + // Node before 20.16 has no getBuiltinModule; the engines field does not stop a global install. + const sqlite = + typeof process.getBuiltinModule === "function" + ? process.getBuiltinModule("node:sqlite") + : undefined; + if (!sqlite) { + throw new Error(`node:sqlite is unavailable in Node ${process.versions.node}; use >= 22.16`); + } + return sqlite; +} + +function migrate(database: DaemonDatabase, file: string, modules: readonly SchemaModule[]): void { + database.write((sql) => { + sql.exec( + "CREATE TABLE IF NOT EXISTS schema_versions (" + + "module TEXT PRIMARY KEY, version INTEGER NOT NULL, min_reader_version INTEGER NOT NULL)", + ); + const names = new Set(); + for (const module of modules) { + if (names.has(module.name)) throw new Error(`Schema module '${module.name}' is listed twice`); + names.add(module.name); + migrateModule(sql, file, module); + } + }); +} + +interface StoredVersion { + version: number; + min_reader_version: number; +} + +function migrateModule(sql: WriteSql, file: string, module: SchemaModule): void { + const known = module.migrations.length; + const stored = sql.get( + "SELECT version, min_reader_version FROM schema_versions WHERE module = ?", + module.name, + ); + if (stored && stored.min_reader_version > known) { + throw new DatabaseSchemaTooNewError(file, module.name, stored.min_reader_version, known); + } + const from = stored?.version ?? 0; + if (from >= known) return; + // The first migration creates the store, so no daemon that predates it can read the store. + let minReaderVersion = Math.max(stored?.min_reader_version ?? 0, 1); + for (let index = from; index < known; index++) { + const migration = module.migrations[index]; + migration.up(sql); + if (migration.breaking) minReaderVersion = index + 1; + } + sql.run( + "INSERT INTO schema_versions (module, version, min_reader_version) VALUES (?, ?, ?) " + + "ON CONFLICT (module) DO UPDATE SET version = excluded.version, " + + "min_reader_version = excluded.min_reader_version", + module.name, + known, + minReaderVersion, + ); +} + +type TransactionState = "none" | "read" | "write"; + +/** Who checkpoints the WAL: SQLite on each commit, a worker not yet started, or the worker. */ +type CheckpointerState = + | { kind: "on_thread" } + | { kind: "pending"; path: string } + | { kind: "worker"; worker: WalCheckpointer }; + +const SQLITE_DEFAULT_AUTOCHECKPOINT_PAGES = 1000; + +interface OpenIteration { + close(): void; +} + +class SqliteDaemonDatabase implements DaemonDatabase { + private state: TransactionState = "none"; + private savepoints = 0; + private closed = false; + private readonly statements = new Map(); + private readonly iterating = new Set(); + private checkpointer: CheckpointerState = { kind: "on_thread" }; + + constructor( + private readonly connection: DatabaseSync, + private readonly logger: Logger, + ) {} + + write(fn: (sql: WriteSql) => T): T { + this.assertOpen(); + if (this.state === "read") throw new Error("Cannot write inside a read transaction"); + if (this.state === "write") return this.savepoint(fn); + return this.transaction("write", "BEGIN IMMEDIATE", fn); + } + + read(fn: (sql: ReadSql) => T): T { + this.assertOpen(); + if (this.state !== "none") return this.scoped(fn); + return this.transaction("read", "BEGIN", fn); + } + + /** + * Moves WAL checkpoints to a worker thread, started by the first committed write, so a + * read-only open starts no thread. Until then SQLite's auto-checkpoint stays off. + */ + checkpointOffThread(file: string): void { + this.connection.exec("PRAGMA wal_autocheckpoint = 0"); + this.checkpointer = { kind: "pending", path: file }; + } + + close(): void { + if (this.closed) return; + if (this.state !== "none") throw new Error("Cannot close the database inside a transaction"); + this.closed = true; + if (this.checkpointer.kind === "worker" && !this.checkpointer.worker.stop()) { + this.logger.warn("Database WAL checkpointer did not stop before close"); + } + try { + const result = this.connection.prepare("PRAGMA wal_checkpoint(TRUNCATE)").get() as + | { busy: number } + | undefined; + if (result?.busy) this.logger.warn("Database WAL checkpoint was blocked by another reader"); + } catch (error) { + this.logger.warn({ err: error }, "Database WAL checkpoint failed before close"); + } + this.statements.clear(); + this.connection.close(); + } + + private transaction(state: TransactionState, begin: string, fn: (sql: WriteSql) => T): T { + this.connection.exec(begin); + this.state = state; + try { + const result = this.scoped(fn); + this.connection.exec("COMMIT"); + if (state === "write") this.startPendingCheckpointer(); + return result; + } catch (error) { + if (this.connection.isTransaction) this.connection.exec("ROLLBACK"); + throw error; + } finally { + this.state = "none"; + } + } + + private savepoint(fn: (sql: WriteSql) => T): T { + const name = `paseo_${++this.savepoints}`; + this.connection.exec(`SAVEPOINT ${name}`); + try { + const result = this.scoped(fn); + this.connection.exec(`RELEASE ${name}`); + return result; + } catch (error) { + this.connection.exec(`ROLLBACK TO ${name}`); + this.connection.exec(`RELEASE ${name}`); + throw error; + } finally { + this.savepoints--; + } + } + + /** Runs `fn` with a handle that stops working, and closes its iterations, when `fn` returns. */ + private scoped(fn: (sql: WriteSql) => T): T { + let valid = true; + const iterations = new Set(); + const assertValid = () => { + if (!valid) throw new Error("A database handle was used after its transaction ended"); + }; + const statement = (sql: string) => { + assertValid(); + const prepared = this.statement(sql); + if (this.iterating.has(prepared)) { + throw new Error(`A statement is already iterating: ${sql}`); + } + return prepared; + }; + const handle: WriteSql = { + get: (sql: string, ...params: SqlValue[]) => + statement(sql).get(...params) as R | undefined, + all: (sql: string, ...params: SqlValue[]) => statement(sql).all(...params) as R[], + iterate: (sql: string, ...params: SqlValue[]) => + this.iterate(statement(sql), params, iterations, assertValid), + run: (sql: string, ...params: SqlValue[]) => ({ + changes: Number(statement(sql).run(...params).changes), + }), + exec: (sql: string) => { + assertValid(); + this.connection.exec(sql); + }, + }; + try { + const result = fn(handle); + if (isThenable(result)) { + throw new Error("A database transaction callback must be synchronous"); + } + return result; + } finally { + valid = false; + for (const iteration of iterations) iteration.close(); + } + } + + private iterate( + prepared: StatementSync, + params: SqlValue[], + iterations: Set, + assertValid: () => void, + ): Iterable { + const rows = prepared.iterate(...params); + let done = false; + const iteration: OpenIteration = { + close: () => { + if (done) return; + done = true; + this.iterating.delete(prepared); + iterations.delete(iteration); + rows.return?.(); + }, + }; + this.iterating.add(prepared); + iterations.add(iteration); + const iterator: Iterator = { + next: () => { + assertValid(); + if (done) return { done: true, value: undefined }; + const next = rows.next(); + if (next.done) iteration.close(); + return next.done + ? { done: true, value: undefined } + : { done: false, value: next.value as R }; + }, + return: () => { + iteration.close(); + return { done: true, value: undefined }; + }, + }; + return { [Symbol.iterator]: () => iterator }; + } + + private startPendingCheckpointer(): void { + if (this.checkpointer.kind !== "pending") return; + const worker = new WalCheckpointer({ + path: this.checkpointer.path, + logger: this.logger, + onExit: () => this.checkpointOnThread(), + }); + this.checkpointer = { kind: "worker", worker }; + } + + /** The worker ended on its own: let SQLite checkpoint again, so the WAL stays bounded. */ + private checkpointOnThread(): void { + if (this.closed) return; + this.logger.warn("Database WAL checkpointer exited; checkpointing on the daemon thread"); + this.checkpointer = { kind: "on_thread" }; + this.connection.exec(`PRAGMA wal_autocheckpoint = ${SQLITE_DEFAULT_AUTOCHECKPOINT_PAGES}`); + } + + private statement(sql: string): StatementSync { + let prepared = this.statements.get(sql); + if (!prepared) { + prepared = this.connection.prepare(sql); + this.statements.set(sql, prepared); + } + return prepared; + } + + private assertOpen(): void { + if (this.closed) throw new DatabaseClosedError(); + } +} + +function isThenable(value: unknown): boolean { + return ( + typeof value === "object" && + value !== null && + typeof (value as { then?: unknown }).then === "function" + ); +} + +function describeError(error: unknown): string { + return error instanceof Error ? error.message : String(error); +} diff --git a/packages/server/src/server/database/internal/wal-checkpointer.ts b/packages/server/src/server/database/internal/wal-checkpointer.ts new file mode 100644 index 0000000000..c48f514b48 --- /dev/null +++ b/packages/server/src/server/database/internal/wal-checkpointer.ts @@ -0,0 +1,88 @@ +import { Worker } from "node:worker_threads"; +import type { Logger } from "pino"; + +const CHECKPOINT_INTERVAL_MS = 1000; +const STOP_TIMEOUT_MS = 2000; + +const RUNNING = 0; +const STOPPING = 1; +const STOPPED = 1; + +/** + * Runs in the worker. It sleeps on the shared state, so `stop` wakes it at once, and needs no + * event loop: a checkpoint is one synchronous call. + */ +const WORKER_SOURCE = ` +const { parentPort, workerData } = require("node:worker_threads"); +const state = new Int32Array(workerData.state); +let connection; +try { + connection = new (process.getBuiltinModule("node:sqlite").DatabaseSync)(workerData.path); + while (Atomics.wait(state, 0, ${RUNNING}, workerData.intervalMs) === "timed-out") { + try { + connection.prepare("PRAGMA wal_checkpoint(PASSIVE)").get(); + } catch (error) { + parentPort.postMessage(String(error && error.message ? error.message : error)); + } + } +} catch (error) { + parentPort.postMessage(String(error && error.message ? error.message : error)); +} finally { + try { connection && connection.close(); } catch {} + Atomics.store(state, 1, ${STOPPED}); + Atomics.notify(state, 1); +} +`; + +/** + * Copies committed WAL pages into the database file from a worker thread. A checkpoint syncs the + * file to disk, which takes up to a hundred milliseconds; on the daemon thread it would stall the + * event loop on whichever write crossed SQLite's auto-checkpoint threshold. A passive checkpoint + * takes no lock a writer needs, so it runs alongside the daemon's writes. + */ +export class WalCheckpointer { + private readonly state = new Int32Array(new SharedArrayBuffer(8)); + private readonly worker: Worker; + private stopped = false; + + /** `onExit` runs when the worker ends before `stop`, so checkpoints have stopped. */ + constructor(input: { path: string; logger: Logger; onExit: () => void }) { + const { logger } = input; + this.worker = new Worker(WORKER_SOURCE, { + eval: true, + workerData: { + path: input.path, + state: this.state.buffer, + intervalMs: CHECKPOINT_INTERVAL_MS, + }, + // Node 22 prints an experimental warning when the worker loads node:sqlite; the daemon + // already printed it once. + stderr: true, + }); + this.worker.stderr.resume(); + this.worker.on("message", (message: string) => { + logger.warn({ error: message }, "Database WAL checkpoint failed"); + }); + this.worker.on("error", (error) => { + logger.warn({ err: error }, "Database WAL checkpointer failed"); + }); + this.worker.on("exit", () => { + if (!this.stopped) input.onExit(); + }); + this.worker.unref(); + } + + /** + * Stops the worker, blocking until it has closed its connection, for at most two seconds. False + * when it had not closed by then; it is terminated either way. + */ + stop(): boolean { + if (this.stopped) return true; + this.stopped = true; + Atomics.store(this.state, 0, STOPPING); + Atomics.notify(this.state, 0); + const closed = Atomics.wait(this.state, 1, 0, STOP_TIMEOUT_MS) !== "timed-out"; + void this.worker.terminate(); + return closed; + } +} diff --git a/packages/server/src/server/test-utils/test-database-path.ts b/packages/server/src/server/test-utils/test-database-path.ts new file mode 100644 index 0000000000..ddb58ae4e8 --- /dev/null +++ b/packages/server/src/server/test-utils/test-database-path.ts @@ -0,0 +1,17 @@ +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; + +let directory: string | undefined; +let count = 0; + +/** A path for a test database that no other test uses, in a directory removed at process exit. */ +export function nextTestDatabasePath(): string { + if (!directory) { + const created = mkdtempSync(path.join(tmpdir(), "paseo-database-")); + directory = created; + process.once("exit", () => rmSync(created, { recursive: true, force: true })); + } + count += 1; + return path.join(directory, `test-${count}.db`); +}