diff --git a/docs/data-model.md b/docs/data-model.md index feced5dd8f..d745008077 100644 --- a/docs/data-model.md +++ b/docs/data-model.md @@ -197,6 +197,9 @@ Terminal activity contributes to the workspace status bucket **per `workspaceId` 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. +- **Access.** The file holds every prompt and reply, so the daemon sets it and its `-wal` and `-shm` + files to mode `0600` on every open. SQLite gives the WAL files it creates the mode of the database + 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 diff --git a/docs/timeline-sync.md b/docs/timeline-sync.md index 056b0c9181..0a7f758c54 100644 --- a/docs/timeline-sync.md +++ b/docs/timeline-sync.md @@ -58,7 +58,9 @@ open rewind, and the children. The backend contract suite is `agent-timeline.tes [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. +and starts no provider. An internal agent, such as the one that writes a commit message, keeps its +history in a memory backend instead, so it leaves nothing on disk. The memory backend also 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/packages/server/src/server/agent/agent-manager.test.ts b/packages/server/src/server/agent/agent-manager.test.ts index 83a6b5a16c..ef9448538e 100644 --- a/packages/server/src/server/agent/agent-manager.test.ts +++ b/packages/server/src/server/agent/agent-manager.test.ts @@ -21,8 +21,8 @@ import { type ManagedAgent, } from "./agent-manager.js"; import { AgentStorage, parseStoredAgentRecord } from "./agent-storage.js"; -import { AgentTimeline } from "./timeline/index.js"; -import { DeferredTimelineBackend } from "./timeline/testing.js"; +import { AgentTimeline, createStoredAgentTimeline } from "./timeline/index.js"; +import { DeferredTimelineBackend, openTestTimelineDatabase } from "./timeline/testing.js"; import { AgentTurnStartCanceledError } from "./agent-sdk-types.js"; import { ForegroundPromptStart } from "./agent-run-state.js"; import { CodexAppServerAgentSession } from "./providers/codex-app-server-agent.js"; @@ -6971,6 +6971,76 @@ test("a run's caller hears how its turn ended even when the timeline fails to re await failed; }); +test("a turn the provider started ends even when the timeline fails to record its metrics", async () => { + const workdir = mkdtempSync(join(tmpdir(), "agent-manager-metrics-record-failure-")); + const session = new TestAgentSession({ provider: "codex", cwd: workdir }); + const client = new (class extends TestAgentClient { + override async createSession(): Promise { + return session; + } + })(); + 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, model: "gpt-5.2-codex" }, + undefined, + { workspaceId: undefined }, + ); + const running = waitForAgentLifecycle(manager, agent.id, "running"); + session.pushEvent({ type: "turn_started", provider: "codex", turnId: "provider-turn" }); + await running; + const idle = waitForAgentLifecycle(manager, agent.id, "idle"); + backend.failNextStampTurnMetrics = true; + session.pushEvent({ type: "turn_completed", provider: "codex", turnId: "provider-turn" }); + await idle; + expect(backend.failNextStampTurnMetrics).toBe(false); +}); + +test("an internal agent's history stays out of the daemon database", async () => { + const workdir = mkdtempSync(join(tmpdir(), "agent-manager-internal-timeline-")); + const database = openTestTimelineDatabase(); + const manager = new AgentManager({ + clients: { codex: new TestAgentClient() }, + timeline: createStoredAgentTimeline(database), + logger, + }); + onTestFinished(async () => { + await manager.closeAgent(internal.id); + await manager.closeAgent(visible.id); + await manager.flush(); + rmSync(workdir, { recursive: true, force: true }); + }); + const internal = await manager.createAgent( + { provider: "codex", cwd: workdir, internal: true }, + undefined, + { workspaceId: undefined }, + ); + const visible = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, { + workspaceId: undefined, + }); + const reply: AgentTimelineItem = { type: "assistant_message", text: "a commit message" }; + await manager.appendTimelineItem(internal.id, reply); + await manager.appendTimelineItem(visible.id, reply); + await manager.flush(); + + expect(await manager.getTimeline(internal.id)).toEqual([reply]); + const storedAgents = database.read((sql) => + sql + .all<{ agent_id: string }>("SELECT agent_id FROM timeline_scopes") + .map((row) => row.agent_id), + ); + expect(storedAgents).toEqual([visible.id]); +}); + 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 82cbe703d3..34909f638f 100644 --- a/packages/server/src/server/agent/agent-manager.ts +++ b/packages/server/src/server/agent/agent-manager.ts @@ -4794,6 +4794,8 @@ export class AgentManager { agentId: resolvedAgentId, session, now, + // Nothing about an internal agent is on disk, its history included. + inMemory: config.internal === true, options, }); @@ -4917,6 +4919,7 @@ export class AgentManager { agentId: string; session: AgentSession; now: Date; + inMemory: boolean; options: | { providerHistory?: readonly TimelineEntry[]; @@ -4931,22 +4934,24 @@ export class AgentManager { | { kind: "kept" } | { kind: "imported"; subagents: ProviderSubagentStreamEvent[]; sessionMetrics?: AgentMetric[] } > { - const { agentId, session, now, options } = params; + const { agentId, session, now, inMemory, options } = params; const scope: TimelineScope = { agentId }; if (options?.providerHistory) { const result = await this.timeline.importHistory(scope, options.providerHistory, { timestamp: (options.updatedAt ?? options.createdAt ?? now).toISOString(), + inMemory, }); return result.kind === "imported" ? { kind: "imported", subagents: [] } : { kind: "kept" }; } if (await this.timeline.describe(scope)) return { kind: "kept" }; if (!options?.importMissingHistory) { - await this.timeline.create(scope, { timestamp: now.toISOString() }); + await this.timeline.create(scope, { timestamp: now.toISOString() }, { inMemory }); return { kind: "created" }; } const history = await this.readProviderHistory(session.streamHistory()); const result = await this.timeline.importHistory(scope, history.entries, { timestamp: now.toISOString(), + inMemory, }); return result.kind === "imported" ? { @@ -5576,16 +5581,22 @@ export class AgentManager { this.emitState(agent); } - /** Stamps the turn's metrics and applies the event by type, returning the event as stamped. */ + /** + * Applies the event by type, then stamps a completed turn's metrics, returning the event as + * stamped. Handlers change the agent's state before they write, so a terminal event whose + * record fails to write still ends the turn; the failure is logged. + */ private async recordStreamEvent(params: StreamEventDispatch): Promise { - const { agent, options, eventTurnId } = params; - let { event } = params; + const { agent, options, eventTurnId, terminalDisposition } = params; + const event = withTurnMetrics(params); try { - event = await this.settleTurnMetrics({ ...params, event }); await this.dispatchStreamEventByType({ ...params, event }); + if (event.type === "turn_completed" && event.metrics && terminalDisposition !== "stale") { + await this.timeline.stampTurnMetrics({ agentId: agent.id }, event.metrics, { + turnId: event.turnId, + }); + } } 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 }, @@ -5735,29 +5746,6 @@ export class AgentManager { * Decides what a completed turn shows and records it on the turn's footer row, so * the live event and a later timeline fetch agree. */ - private async settleTurnMetrics(params: { - agent: ActiveManagedAgent; - event: AgentStreamEvent; - options: HandleStreamEventOptions | undefined; - terminalDisposition: ActiveTurnTerminalDisposition; - }): Promise { - if (params.event.type !== "turn_completed") return params.event; - const { agent } = params; - const { metrics: reported, ...event } = params.event; - // A replayed turn may have run on another model than the agent has now. - const model = params.options?.fromHistory - ? null - : (agent.runtimeInfo?.model ?? agent.config.model); - const metrics = withModelMetric(sanitizeAgentMetrics(reported), model); - if (metrics.length === 0) return event; - if (params.terminalDisposition !== "stale") { - await this.timeline.stampTurnMetrics({ agentId: agent.id }, metrics, { - turnId: event.turnId, - }); - } - return { ...event, metrics }; - } - private onStreamTurnCompleted(params: { agent: ActiveManagedAgent; event: Extract; @@ -5825,13 +5813,13 @@ export class AgentManager { agent.lifecycle = "error"; } agent.lastError = event.error; + this.resolvePendingPermissionsForAgent(agent, event.provider, options, "Turn failed"); await this.appendSystemErrorTimelineMessage( agent, event.provider, this.formatTurnFailedMessage(event), options, ); - this.resolvePendingPermissionsForAgent(agent, event.provider, options, "Turn failed"); } private onStreamTurnCanceled(params: { @@ -6860,3 +6848,22 @@ function pluginPromptContext( ): Pick { return appendSystemPrompt?.length ? { appendSystemPrompt } : {}; } + +/** + * A completed turn with its metrics sanitized and the model added; a replayed turn may have run + * on another model than the agent has now, so it gets none. + */ +function withTurnMetrics(params: { + agent: ActiveManagedAgent; + event: AgentStreamEvent; + options: HandleStreamEventOptions | undefined; +}): AgentStreamEvent { + if (params.event.type !== "turn_completed") return params.event; + const { agent } = params; + const { metrics: reported, ...event } = params.event; + const model = params.options?.fromHistory + ? null + : (agent.runtimeInfo?.model ?? agent.config.model); + const metrics = withModelMetric(sanitizeAgentMetrics(reported), model); + return metrics.length === 0 ? event : { ...event, metrics }; +} 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 03d5ecdaf1..cac43a44b2 100644 --- a/packages/server/src/server/agent/timeline/internal/agent-timeline.ts +++ b/packages/server/src/server/agent/timeline/internal/agent-timeline.ts @@ -151,6 +151,14 @@ export interface TimelineAppendOptions { publish?: (commits: TimelineCommit[]) => void; } +/** + * Where a new history lives. `inMemory` keeps an agent's history, its children included, in + * process memory only, for agents that must leave nothing on disk; it ends with the process. + */ +export interface TimelineRetention { + inMemory?: boolean; +} + /** * Owner of agent timeline history: item identity, sequence numbers, projection, and reads. * @@ -163,22 +171,35 @@ export class AgentTimeline { private readonly sizes = new Map(); private closed = false; - constructor(private readonly backend: AgentTimelineBackend = new MemoryTimelineBackend()) {} + /** Agents whose history lives only in `memory`; see `TimelineRetention`. */ + private readonly memoryAgents = new Set(); + + constructor( + private readonly backend: AgentTimelineBackend = new MemoryTimelineBackend(), + private readonly memory: AgentTimelineBackend = new MemoryTimelineBackend(), + ) {} describe(scope: TimelineScope): Promise { - return this.run(scope, () => this.backend.head(scope)); + return this.run(scope, () => this.backendFor(scope).head(scope)); } /** Creates the scope's history with a new identity, replacing any existing history. */ - create(scope: TimelineScope, seed: TimelineSeed = {}): Promise { - return this.run(scope, async () => this.track(scope, await this.backend.create(scope, seed))); + create( + scope: TimelineScope, + seed: TimelineSeed = {}, + options: TimelineRetention = {}, + ): Promise { + return this.run(scope, async () => { + this.retain(scope, options); + return this.track(scope, await this.backendFor(scope).create(scope, seed)); + }); } /** Returns the existing history, or creates an empty one. */ open(scope: TimelineScope): Promise { return this.run(scope, async () => { - const existing = await this.backend.head(scope); - return existing ?? this.track(scope, await this.backend.create(scope, {})); + const existing = await this.backendFor(scope).head(scope); + return existing ?? this.track(scope, await this.backendFor(scope).create(scope, {})); }); } @@ -189,12 +210,13 @@ export class AgentTimeline { importHistory( scope: TimelineScope, entries: readonly TimelineEntry[], - options: { timestamp?: string } = {}, + options: { timestamp?: string } & TimelineRetention = {}, ): Promise { return this.run(scope, async () => { - const existing = await this.backend.head(scope); + this.retain(scope, options); + const existing = await this.backendFor(scope).head(scope); if (existing) return { kind: "present", head: existing }; - const head = await this.backend.create(scope, { + const head = await this.backendFor(scope).create(scope, { entries: entries.map(providerHistoryEntry), timestamp: options.timestamp, }); @@ -216,8 +238,8 @@ export class AgentTimeline { const head = await this.requireHead(scope); if (head.rewind) return { kind: "rewind_open" }; const plan = planProviderHistory({ - rows: await this.backend.readRows(scope), - prompts: await this.backend.prompts(scope), + rows: await this.backendFor(scope).readRows(scope), + prompts: await this.backendFor(scope).prompts(scope), provider: entries.map(providerHistoryEntry), }); if (plan.kind !== "append") return plan; @@ -231,7 +253,7 @@ export class AgentTimeline { /** The agent's provider children, retired ones included. */ listChildren(agentId: string): Promise { - return this.run({ agentId }, () => this.backend.children(agentId)); + return this.run({ agentId }, () => this.backendFor({ agentId }).children(agentId)); } /** @@ -243,10 +265,10 @@ export class AgentTimeline { update: (previous: ProviderSubagentDescriptor | null) => ProviderSubagentDescriptor, ): Promise { return this.run(scope, async () => { - const child = await this.backend.child(scope); + const child = await this.backendFor(scope).child(scope); if (child?.retired) return null; const descriptor = update(child?.descriptor ?? null); - await this.backend.setChild(scope, descriptor); + await this.backendFor(scope).setChild(scope, descriptor); return descriptor; }); } @@ -257,9 +279,9 @@ export class AgentTimeline { entries: readonly TimelineEntry[], ): Promise { return this.run(scope, async () => { - const child = await this.backend.child(scope); + const child = await this.backendFor(scope).child(scope); if (child?.retired) return null; - if (!child) this.track(scope, await this.backend.create(scope, {})); + if (!child) this.track(scope, await this.backendFor(scope).create(scope, {})); return entries.length === 0 ? [] : await this.commit(scope, entries); }); } @@ -267,9 +289,9 @@ export class AgentTimeline { /** Deletes a child's history. A retired child stays stored and resolves false. */ removeChild(scope: TimelineScope): Promise { return this.run(scope, async () => { - const child = await this.backend.child(scope); + const child = await this.backendFor(scope).child(scope); if (child?.retired) return false; - await this.backend.delete(scope); + await this.backendFor(scope).delete(scope); this.sizes.delete(sizeKey(scope)); return true; }); @@ -278,9 +300,10 @@ export class AgentTimeline { /** Deleting an agent's root history deletes all of its children's too. */ delete(scope: TimelineScope): Promise { return this.run(scope, async () => { - await this.backend.delete(scope); + await this.backendFor(scope).delete(scope); this.sizes.delete(sizeKey(scope)); if (scope.subagentId !== undefined) return; + this.memoryAgents.delete(scope.agentId); const childPrefix = sizeKey({ agentId: scope.agentId, subagentId: "" }); for (const key of this.sizes.keys()) { if (key.startsWith(childPrefix)) this.sizes.delete(key); @@ -296,7 +319,7 @@ export class AgentTimeline { return this.run(scope, async () => { const clientMessageId = submittedPromptId(entry.item); if (clientMessageId) { - const existing = await this.backend.findSubmittedPrompt(scope, clientMessageId); + const existing = await this.backendFor(scope).findSubmittedPrompt(scope, clientMessageId); if (existing) { const head = await this.requireHead(scope); return { @@ -307,7 +330,7 @@ export class AgentTimeline { }; } } - if (await this.backend.isRetired(scope, entry)) return { kind: "dropped" }; + if (await this.backendFor(scope).isRetired(scope, entry)) return { kind: "dropped" }; const [commit] = await this.commit(scope, [entry]); const failure = publishCommitted(options?.publish, commit); return failure @@ -338,7 +361,7 @@ export class AgentTimeline { providerMessageId: string, ): Promise { return this.run(scope, () => - this.backend.attachProviderMessageId(scope, clientMessageId, providerMessageId), + this.backendFor(scope).attachProviderMessageId(scope, clientMessageId, providerMessageId), ); } @@ -348,29 +371,31 @@ export class AgentTimeline { metrics: AgentMetric[], options?: { turnId?: string }, ): Promise { - return this.run(scope, () => this.backend.stampTurnMetrics(scope, metrics, options)); + return this.run(scope, () => this.backendFor(scope).stampTurnMetrics(scope, metrics, options)); } findSubmittedPrompt( scope: TimelineScope, clientMessageId: string, ): Promise { - return this.run(scope, () => this.backend.findSubmittedPrompt(scope, clientMessageId)); + return this.run(scope, () => + this.backendFor(scope).findSubmittedPrompt(scope, clientMessageId), + ); } fetch( scope: TimelineScope, options: AgentTimelineFetchOptions = {}, ): Promise { - return this.run(scope, () => this.backend.fetch(scope, options)); + return this.run(scope, () => this.backendFor(scope).fetch(scope, options)); } readRows(scope: TimelineScope): Promise { - return this.run(scope, () => this.backend.readRows(scope)); + return this.run(scope, () => this.backendFor(scope).readRows(scope)); } lastItem(scope: TimelineScope): Promise { - return this.run(scope, () => this.backend.lastItem(scope)); + return this.run(scope, () => this.backendFor(scope).lastItem(scope)); } /** @@ -379,7 +404,7 @@ export class AgentTimeline { * before it ends the run. Null when the history has no assistant message. */ lastAssistantMessage(scope: TimelineScope): Promise { - return this.run(scope, () => this.backend.lastAssistantMessage(scope)); + return this.run(scope, () => this.backendFor(scope).lastAssistantMessage(scope)); } /** @@ -390,7 +415,7 @@ export class AgentTimeline { return this.run(scope, async () => { const head = await this.requireHead(scope); if (head.rewind) throw new TimelineRewindPendingError(head.rewind); - const target = (await this.backend.prompts(scope)).find( + const target = (await this.backendFor(scope).prompts(scope)).find( (prompt) => prompt.messageId === messageId, ); if (!target) throw new TimelineRewindTargetError(messageId); @@ -399,7 +424,7 @@ export class AgentTimeline { messageId, targetSeq: target.seqStart, }; - await this.backend.setRewind(scope, intent); + await this.backendFor(scope).setRewind(scope, intent); return intent; }); } @@ -414,7 +439,7 @@ export class AgentTimeline { const head = await this.requireHead(scope); if (head.rewind?.id !== intentId) return null; const intent = { ...head.rewind, cut }; - await this.backend.setRewind(scope, intent); + await this.backendFor(scope).setRewind(scope, intent); return intent; }); } @@ -423,7 +448,7 @@ export class AgentTimeline { abandonRewind(scope: TimelineScope, intentId: string): Promise { return this.run(scope, async () => { const head = await this.requireHead(scope); - if (head.rewind?.id === intentId) await this.backend.setRewind(scope, null); + if (head.rewind?.id === intentId) await this.backendFor(scope).setRewind(scope, null); }); } @@ -439,7 +464,11 @@ export class AgentTimeline { return this.run(scope, async () => { const intent = (await this.requireHead(scope)).rewind; if (intent?.id !== intentId) return { kind: "absent" }; - return judgeRewindEvidence(intent, await this.backend.prompts(scope), providerPromptIds); + return judgeRewindEvidence( + intent, + await this.backendFor(scope).prompts(scope), + providerPromptIds, + ); }); } @@ -457,9 +486,12 @@ export class AgentTimeline { const intent = head.rewind; if (intent?.id !== intentId) return { kind: "absent" }; if (!intent.cut) throw new Error("Cannot complete a rewind before its provider outcome"); - const retireFromSeq = resolveRetireFromSeq(intent, await this.backend.prompts(scope)); + const retireFromSeq = resolveRetireFromSeq( + intent, + await this.backendFor(scope).prompts(scope), + ); if (retireFromSeq === null) throw new TimelineRewindBoundaryError(intent); - const result = await this.backend.retire(scope, { + const result = await this.backendFor(scope).retire(scope, { retireFromSeq, selectChildren: childrenSpawnedBy, }); @@ -506,7 +538,7 @@ export class AgentTimeline { scope: TimelineScope, entries: readonly TimelineEntry[], ): Promise { - const { rows, head } = await this.backend.append(scope, entries.map(boundEntry)); + const { rows, head } = await this.backendFor(scope).append(scope, entries.map(boundEntry)); this.track(scope, head); return rows.map((row) => ({ row, @@ -516,11 +548,20 @@ export class AgentTimeline { } private async requireHead(scope: TimelineScope): Promise { - const head = await this.backend.head(scope); + const head = await this.backendFor(scope).head(scope); if (!head) throw new UnknownTimelineError(scope); return head; } + private backendFor(scope: TimelineScope): AgentTimelineBackend { + return this.memoryAgents.has(scope.agentId) ? this.memory : this.backend; + } + + /** An agent stays in memory until its history is deleted. */ + private retain(scope: TimelineScope, options: TimelineRetention): void { + if (options.inMemory && scope.subagentId === undefined) this.memoryAgents.add(scope.agentId); + } + private track(scope: TimelineScope, head: TimelineHead): TimelineHead { this.sizes.set(sizeKey(scope), head.size); return head; diff --git a/packages/server/src/server/agent/timeline/internal/sqlite-backend.ts b/packages/server/src/server/agent/timeline/internal/sqlite-backend.ts index deaba6c771..1e5fa2edba 100644 --- a/packages/server/src/server/agent/timeline/internal/sqlite-backend.ts +++ b/packages/server/src/server/agent/timeline/internal/sqlite-backend.ts @@ -41,7 +41,9 @@ 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 + * chunk per source row, so a streamed chunk never rewrites the message. A chunk is stored as a JSON + * string: node:sqlite reads a TEXT value only up to its first NUL, and a chunk can end inside a + * surrogate pair, which UTF-8 cannot hold. `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 @@ -99,7 +101,7 @@ 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, + text_json TEXT NOT NULL, PRIMARY KEY (scope_id, seq_start, seq) ); @@ -768,11 +770,11 @@ function insertText( row: ProjectedTimelineRow, ): void { sql.run( - "INSERT INTO timeline_text (scope_id, seq_start, seq, text) VALUES (?, ?, ?, ?)", + "INSERT INTO timeline_text (scope_id, seq_start, seq, text_json) VALUES (?, ?, ?, ?)", scopeId, seqStart, seq, - itemText(row.item), + JSON.stringify(itemText(row.item)), ); } @@ -784,12 +786,12 @@ function parseRow(record: Pick): ProjectedTimelineRow { 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", + .all<{ text_json: string }>( + "SELECT text_json FROM timeline_text WHERE scope_id = ? AND seq_start = ? ORDER BY seq", scopeId, row.seqStart, ) - .map((chunk) => chunk.text) + .map((chunk) => JSON.parse(chunk.text_json) as string) .join(""); return { ...row, item: { ...row.item, text } }; } diff --git a/packages/server/src/server/agent/timeline/sqlite-backend.test.ts b/packages/server/src/server/agent/timeline/sqlite-backend.test.ts index db8cdd32a9..0ba088cafb 100644 --- a/packages/server/src/server/agent/timeline/sqlite-backend.test.ts +++ b/packages/server/src/server/agent/timeline/sqlite-backend.test.ts @@ -451,4 +451,21 @@ describe("SQLite timeline reads", () => { expect(backend.lastAssistantMessage(scope)).toHaveLength(100_000); database.close(); }); + + it("reads back streamed text exactly, including a NUL and a pair split across chunks", () => { + const file = nextTestDatabasePath(); + const chunks = ["before\0after ", "\ud83d", "\ude00 end"]; + const writer = openTestTimelineDatabase(file); + const written = new SqliteTimelineBackend(writer); + written.create(scope, { epoch: "e" }); + for (const text of chunks) { + written.append(scope, [entry({ type: "assistant_message", text })]); + } + writer.close(); + + const reopened = new SqliteTimelineBackend(openTestTimelineDatabase(file)); + expect(reopened.readRows(scope).map((row) => row.item)).toEqual([ + { type: "assistant_message", text: chunks.join("") }, + ]); + }); }); diff --git a/packages/server/src/server/agent/timeline/testing.ts b/packages/server/src/server/agent/timeline/testing.ts index d586e1c9c5..ae049d44ff 100644 --- a/packages/server/src/server/agent/timeline/testing.ts +++ b/packages/server/src/server/agent/timeline/testing.ts @@ -66,14 +66,15 @@ export function openTestTimelineDatabase(file?: string): DaemonDatabase { /** * Wraps a backend: defers every call by a turn of the event loop, the shape of an I/O-backed - * store, records the committed appends and whole-history reads, and fails the next append or - * retirement on request. + * store, records the committed appends and whole-history reads, and fails the next append, + * retirement, or metrics stamp on request. */ export class DeferredTimelineBackend implements AgentTimelineBackend { readonly appends: TimelineEntry[][] = []; readRowsCalls = 0; failNextAppend = false; failNextRetire = false; + failNextStampTurnMetrics = false; constructor(private readonly inner: InspectableTimelineBackend = new MemoryTimelineBackend()) {} @@ -153,7 +154,13 @@ export class DeferredTimelineBackend implements AgentTimelineBackend { metrics: AgentMetric[], options?: { turnId?: string }, ): Promise { - return this.defer(() => this.inner.stampTurnMetrics(scope, metrics, options)); + return this.defer(() => { + if (this.failNextStampTurnMetrics) { + this.failNextStampTurnMetrics = false; + throw new Error("disk full"); + } + return this.inner.stampTurnMetrics(scope, metrics, options); + }); } findSubmittedPrompt( scope: TimelineScope, diff --git a/packages/server/src/server/database/daemon-database.test.ts b/packages/server/src/server/database/daemon-database.test.ts index 2e12f560ea..c409263337 100644 --- a/packages/server/src/server/database/daemon-database.test.ts +++ b/packages/server/src/server/database/daemon-database.test.ts @@ -219,6 +219,23 @@ function texts(database: DaemonDatabase): string[] { ); } +it.skipIf(process.platform === "win32")( + "keeps the database and its WAL files private to the user, including a file created readable", + () => { + const umask = process.umask(0o022); + try { + writeFileSync(databasePath, "", { mode: 0o644 }); + const database = open([notes]); + database.write((sql) => insert(sql, "secret")); + for (const file of [databasePath, `${databasePath}-wal`, `${databasePath}-shm`]) { + expect({ file, mode: statSync(file).mode & 0o777 }).toEqual({ file, mode: 0o600 }); + } + } finally { + process.umask(umask); + } + }, +); + it("rolls a write back when its callback throws", () => { const database = open([notes]); expect(() => database.write((sql) => insertThenThrow(sql, "lost"))).toThrow("failed after lost"); diff --git a/packages/server/src/server/database/internal/daemon-database.ts b/packages/server/src/server/database/internal/daemon-database.ts index 985e45a8bb..abba931184 100644 --- a/packages/server/src/server/database/internal/daemon-database.ts +++ b/packages/server/src/server/database/internal/daemon-database.ts @@ -1,5 +1,6 @@ import type { DatabaseSync, SQLInputValue, StatementSync } from "node:sqlite"; import type { Logger } from "pino"; +import { ensurePrivateFile } from "../../private-files.js"; import { WalCheckpointer } from "./wal-checkpointer.js"; export type SqlValue = SQLInputValue; @@ -100,6 +101,14 @@ export function openDaemonDatabase(input: { try { const sqlite = loadSqlite(); connection = new sqlite.DatabaseSync(input.path, { timeout: BUSY_TIMEOUT_MS }); + assertSupported(connection); + // The file holds every prompt and reply. SQLite gives the WAL and shared-memory files it + // creates the database file's mode; files left by an earlier open are fixed here. + if (input.path !== ":memory:") { + for (const file of [input.path, `${input.path}-wal`, `${input.path}-shm`]) { + ensurePrivateFile(file); + } + } connection.exec( [ "PRAGMA journal_mode = WAL", @@ -133,6 +142,13 @@ function loadSqlite(): typeof import("node:sqlite") { return sqlite; } +/** Node 22.13 has node:sqlite without `isTransaction`, which rollback needs. */ +function assertSupported(connection: DatabaseSync): void { + if (typeof connection.isTransaction !== "boolean") { + throw new Error(`node:sqlite in Node ${process.versions.node} is too old; use >= 22.16`); + } +} + function migrate(database: DaemonDatabase, file: string, modules: readonly SchemaModule[]): void { database.write((sql) => { sql.exec( @@ -359,14 +375,20 @@ class SqliteDaemonDatabase implements DaemonDatabase { return { [Symbol.iterator]: () => iterator }; } + /** Runs after a write commits, so it never throws: the write has already happened. */ 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 }; + try { + const worker = new WalCheckpointer({ + path: this.checkpointer.path, + logger: this.logger, + onExit: () => this.checkpointOnThread(), + }); + this.checkpointer = { kind: "worker", worker }; + } catch (error) { + this.logger.warn({ err: error }, "Database WAL checkpointer did not start"); + this.checkpointOnThread(); + } } /** The worker ended on its own: let SQLite checkpoint again, so the WAL stays bounded. */