mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-26 02:05:31 +00:00
feat(timeline): store agent timelines in paseo.db
Agent history now survives a daemon restart, and closed or archived agents hold no timeline in memory. A history fetch reads paseo.db and starts no provider. The daemon opens one SQLite database at $PASEO_HOME/paseo.db with node:sqlite. Each schema module owns its tables and migrations, and records a min_reader_version, so an older daemon refuses a database it cannot read instead of corrupting it. Node 22.16 is the floor, because DatabaseSync needs it. A worker thread runs the WAL checkpoints. A checkpoint syncs the file, and on the daemon thread it stalled the event loop for up to 119 ms on whichever write crossed the auto-checkpoint threshold. If the worker exits, the daemon returns to SQLite's auto-checkpoint. A turn's final event now ends the run even when the timeline fails to write it. Before this change the error escaped handleStreamEvent before settleTerminalRun, so the agent stayed running and its waiters hung. The durable store makes that write fallible, and shutdown made it fail: settled() rejected after close.
This commit is contained in:
@@ -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
|
||||
|
||||
+34
-5
@@ -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).
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
Generated
+20
-1
@@ -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",
|
||||
|
||||
@@ -169,5 +169,8 @@
|
||||
"tiny-async-pool": {
|
||||
"semver@^5": "5.7.2"
|
||||
}
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22.16.0"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -47,5 +47,8 @@
|
||||
"typescript": "^5.2.2",
|
||||
"vitest": "^4.1.6",
|
||||
"zx": "^8.8.5"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22.16.0"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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<AgentSession> {
|
||||
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);
|
||||
|
||||
@@ -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<void> | undefined {
|
||||
/** Stamps the turn's metrics and applies the event by type, returning the event as stamped. */
|
||||
private async recordStreamEvent(params: StreamEventDispatch): Promise<AgentStreamEvent> {
|
||||
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<void> | undefined {
|
||||
const { agent, event, options, isForegroundEvent, eventTurnId, terminalDisposition, flags } =
|
||||
params;
|
||||
switch (event.type) {
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
|
||||
@@ -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<string, Promise<void>>();
|
||||
private readonly sizes = new Map<string, number>();
|
||||
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<void> {
|
||||
// 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<void> {
|
||||
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<T>(scope: TimelineScope, operation: () => T | Promise<T>): Promise<T> {
|
||||
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);
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
}
|
||||
@@ -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<T extends AgentTimelineRow>(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<string, MemoryTimelineState>();
|
||||
@@ -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[] {
|
||||
|
||||
@@ -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 } : {}),
|
||||
};
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -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, "item"> = {}): 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<string, unknown[]> {
|
||||
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<T>(fn: (sql: WriteSql) => T): T {
|
||||
return this.inner.write((sql) => fn({ ...this.counting(sql), run: sql.run, exec: sql.exec }));
|
||||
}
|
||||
|
||||
read<T>(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: <T>(query: string, ...params: Parameters<ReadSql["get"]>[1][]) => {
|
||||
const rows = sql.iterate<T>(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();
|
||||
});
|
||||
});
|
||||
@@ -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
|
||||
|
||||
@@ -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 }),
|
||||
|
||||
@@ -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<void>((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.
|
||||
|
||||
@@ -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<unknown> | 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);
|
||||
});
|
||||
});
|
||||
@@ -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";
|
||||
@@ -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<T>(sql: string, ...params: SqlValue[]): T | undefined;
|
||||
all<T>(sql: string, ...params: SqlValue[]): T[];
|
||||
/** Lazy rows. An unfinished iteration is closed when the callback returns. */
|
||||
iterate<T>(sql: string, ...params: SqlValue[]): Iterable<T>;
|
||||
}
|
||||
|
||||
/** 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<T>(fn: (sql: WriteSql) => T): T;
|
||||
/** One consistent read. Nested in a read or write, it joins the outer transaction. */
|
||||
read<T>(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<string>();
|
||||
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<StoredVersion>(
|
||||
"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<string, StatementSync>();
|
||||
private readonly iterating = new Set<StatementSync>();
|
||||
private checkpointer: CheckpointerState = { kind: "on_thread" };
|
||||
|
||||
constructor(
|
||||
private readonly connection: DatabaseSync,
|
||||
private readonly logger: Logger,
|
||||
) {}
|
||||
|
||||
write<T>(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<T>(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<T>(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<T>(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<T>(fn: (sql: WriteSql) => T): T {
|
||||
let valid = true;
|
||||
const iterations = new Set<OpenIteration>();
|
||||
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: <R>(sql: string, ...params: SqlValue[]) =>
|
||||
statement(sql).get(...params) as R | undefined,
|
||||
all: <R>(sql: string, ...params: SqlValue[]) => statement(sql).all(...params) as R[],
|
||||
iterate: <R>(sql: string, ...params: SqlValue[]) =>
|
||||
this.iterate<R>(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<R>(
|
||||
prepared: StatementSync,
|
||||
params: SqlValue[],
|
||||
iterations: Set<OpenIteration>,
|
||||
assertValid: () => void,
|
||||
): Iterable<R> {
|
||||
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<R> = {
|
||||
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);
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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`);
|
||||
}
|
||||
Reference in New Issue
Block a user