@bastani/atomic 0.9.83 → 0.9.84-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/dist/builtin/intercom/package.json +1 -1
  3. package/dist/builtin/mcp/package.json +1 -1
  4. package/dist/builtin/subagents/package.json +1 -1
  5. package/dist/builtin/web-access/package.json +1 -1
  6. package/dist/builtin/workflows/package.json +1 -1
  7. package/dist/cli/storage-command.d.ts +12 -1
  8. package/dist/cli/storage-command.d.ts.map +1 -1
  9. package/dist/cli/storage-command.js +210 -47
  10. package/dist/cli/storage-command.js.map +1 -1
  11. package/dist/core/session-transfer.d.ts +84 -0
  12. package/dist/core/session-transfer.d.ts.map +1 -0
  13. package/dist/core/session-transfer.js +270 -0
  14. package/dist/core/session-transfer.js.map +1 -0
  15. package/dist/core/storage/journal-transfer.d.ts +74 -35
  16. package/dist/core/storage/journal-transfer.d.ts.map +1 -1
  17. package/dist/core/storage/journal-transfer.js +384 -278
  18. package/dist/core/storage/journal-transfer.js.map +1 -1
  19. package/dist/core/storage/transfer-files.d.ts +75 -0
  20. package/dist/core/storage/transfer-files.d.ts.map +1 -0
  21. package/dist/core/storage/transfer-files.js +170 -0
  22. package/dist/core/storage/transfer-files.js.map +1 -0
  23. package/dist/core/storage-transfer.d.ts +30 -0
  24. package/dist/core/storage-transfer.d.ts.map +1 -0
  25. package/dist/core/storage-transfer.js +49 -0
  26. package/dist/core/storage-transfer.js.map +1 -0
  27. package/dist/modes/interactive-engine/isolated-runtime.d.ts +7 -0
  28. package/dist/modes/interactive-engine/isolated-runtime.d.ts.map +1 -1
  29. package/dist/modes/interactive-engine/isolated-runtime.js +21 -1
  30. package/dist/modes/interactive-engine/isolated-runtime.js.map +1 -1
  31. package/dist/modes/rpc/rpc-command-handler.d.ts.map +1 -1
  32. package/dist/modes/rpc/rpc-command-handler.js +1 -0
  33. package/dist/modes/rpc/rpc-command-handler.js.map +1 -1
  34. package/docs/reference/cli.md +31 -3
  35. package/docs/storage.md +81 -17
  36. package/npm-shrinkwrap.json +38 -38
  37. package/package.json +3 -3
@@ -1,63 +1,45 @@
1
1
  /**
2
- * Workflow runs as versioned JSONL files (#4716): `exportWorkflowRuns` writes each run of a local workflow journal to
3
- * `<dir>/<runId>.jsonl`, and `importWorkflowRuns` restores such files into one. The journal stays the working store;
4
- * the files are the form runs take at rest, so a host that persists only files can carry them between machines.
2
+ * Workflow runs as versioned JSONL files (#4716, #4720): `exportWorkflowRuns` writes each run of a local workflow
3
+ * journal to `<dir>/<runId>.jsonl`, and the import functions restore such files into one. The journal stays the
4
+ * working store; the files are the form runs take at rest, so a host that persists only files can carry them between
5
+ * machines. `atomic storage export` and `import` use `<exportDir>/workflows` as `<dir>`.
5
6
  *
6
7
  * Line 1 of a file is the run's header: the row of the journal's runs table. Every later line is one row of its
7
8
  * events table, in sequence order, with its payload as a JSON value instead of JSON text. Leases, local-worker pool
8
9
  * state and worktree snapshot blobs are not exported: they belong to the machine that wrote them.
9
10
  */
10
- import { randomUUID } from "node:crypto";
11
11
  import { existsSync } from "node:fs";
12
- import { mkdir, open, readdir, readFile, rename, rm } from "node:fs/promises";
13
- import { join, resolve } from "node:path";
12
+ import { mkdir } from "node:fs/promises";
13
+ import { join } from "node:path";
14
14
  import { closeEach, withCleanup } from "./cleanup.js";
15
- import { StorageError } from "./errors.js";
16
15
  import { discoverLegacyJournal, ensureRunJournalSchema, legacyDefaultJournalPath, runJournalTables, } from "./journal-adoption.js";
17
16
  import { isFinishedJournalStatus, JOURNAL_CATALOG_FILE, JournalCatalog, } from "./journal-catalog.js";
18
17
  import { openNodeSqliteDatabase } from "./node-sqlite.js";
19
18
  import { RUN_EVENT_TYPES, RUN_JOURNAL_SCHEMA_VERSION } from "./run-journal.js";
19
+ import { readTransferDirectory, StorageImportIncompleteError, StorageTransferError, transferFile, writeLinesAtomically, } from "./transfer-files.js";
20
20
  /** The `type` of an export file's header line. */
21
21
  export const WORKFLOW_RUN_EXPORT_TYPE = "atomic.workflow-run";
22
22
  /** The export format version this Atomic writes and reads. */
23
23
  export const WORKFLOW_RUN_EXPORT_VERSION = 1;
24
- /** The file name extension of an exported run; import reads every file with it and ignores the rest. */
25
- export const WORKFLOW_RUN_EXPORT_EXTENSION = ".jsonl";
26
24
  /**
27
25
  * A lease renewed this recently belongs to a process that may still be running the run on this machine, so an import
28
26
  * does not add events to that run. It matches the window in which the workflows runtime treats a running run's owner
29
27
  * as live.
30
28
  */
31
29
  export const WORKFLOW_RUN_IMPORT_LIVE_LEASE_MS = 120_000;
32
- /** An export or import that could not be done; an import that fails this way changed nothing. */
33
- export class WorkflowRunTransferError extends StorageError {
34
- name = "WorkflowRunTransferError";
35
- path;
36
- line;
37
- runId;
38
- reason;
39
- constructor(init) {
40
- super(`${init.path}${init.line === undefined ? "" : `:${init.line}`}: ${init.reason}`, { cause: init.cause });
41
- this.path = init.path;
42
- this.line = init.line;
43
- this.runId = init.runId;
44
- this.reason = init.reason;
45
- }
46
- }
47
- export function isWorkflowRunTransferError(value) {
48
- if (value instanceof WorkflowRunTransferError)
49
- return true;
50
- return (typeof value === "object" && value !== null && value.name === "WorkflowRunTransferError");
51
- }
30
+ /**
31
+ * How many times an export reads the catalog again after reading the journal files, for runs a consolidation moved
32
+ * in between; a run still not found where the catalog names it after the last read is reported with its reason.
33
+ */
34
+ export const WORKFLOW_RUN_EXPORT_PLACEMENT_ATTEMPTS = 5;
52
35
  const STORE_NOW = "CAST(unixepoch('subsec') * 1000 AS INTEGER)";
53
36
  const TRANSFER_TRANSACTION = { lockWaitMs: 10 * 60_000 };
54
37
  const EVENT_TYPES = new Set(Object.values(RUN_EVENT_TYPES));
55
38
  const HEADER_FIELDS = ["type", "version", "runId", "name", "cwd", "createdAt", "status", "events", "header"];
56
39
  const EVENT_FIELDS = ["type", "seq", "epoch", "key", "at", "payload"];
57
- /** The file an exported run is written to in `directory`. */
58
- export function workflowRunExportFile(directory, runId) {
59
- return join(directory, `${encodeURIComponent(runId)}${WORKFLOW_RUN_EXPORT_EXTENSION}`);
60
- }
40
+ /** The runs table of the journal format before 0.9.38, which an export cannot read. */
41
+ const LEGACY_RUNS_TABLE = "runs";
42
+ const OLD_FORMAT_REASON = "it is in the journal format of Atomic before 0.9.38; resume it once to convert it";
61
43
  function storageLocation(storage) {
62
44
  return storage.kind === "store" ? storage.directory : storage.path;
63
45
  }
@@ -66,21 +48,21 @@ function parseStored(text, path, runId, what) {
66
48
  return JSON.parse(text);
67
49
  }
68
50
  catch (cause) {
69
- throw new WorkflowRunTransferError({
51
+ throw new StorageTransferError({
70
52
  path,
71
- runId,
53
+ id: runId,
72
54
  reason: `run ${runId} has ${what} that is not valid JSON`,
73
55
  cause: cause,
74
56
  });
75
57
  }
76
58
  }
77
- /** A run and its events as the lines of its export file, newline-terminated. */
78
- function exportText(run, events, path) {
59
+ /** A run and its events as the lines of its export file. */
60
+ function exportLines(run, events, path) {
79
61
  const header = parseStored(run.header_json, path, run.run_id, "a header");
80
62
  if (!isObject(header))
81
- throw new WorkflowRunTransferError({
63
+ throw new StorageTransferError({
82
64
  path,
83
- runId: run.run_id,
65
+ id: run.run_id,
84
66
  reason: `run ${run.run_id} has a header that is not an object`,
85
67
  });
86
68
  const lines = [
@@ -105,75 +87,61 @@ function exportText(run, events, path) {
105
87
  at: Number(event.at),
106
88
  payload: parseStored(event.payload, path, run.run_id, `event ${event.seq} with a payload`),
107
89
  }));
108
- return `${lines.join("\n")}\n`;
109
- }
110
- /**
111
- * Writes `content` to `file` through a temporary file in the same directory that is flushed and then renamed over it,
112
- * so `file` holds either its earlier content or all of `content`. A file that already holds `content` is left alone.
113
- */
114
- async function writeAtomically(file, content) {
115
- const existing = await readFile(file, "utf8").catch(() => undefined);
116
- if (existing === content)
117
- return "unchanged";
118
- const temporary = join(resolve(file, ".."), `.${randomUUID()}.tmp`);
119
- try {
120
- const handle = await open(temporary, "wx");
121
- await withCleanup(async () => {
122
- await handle.writeFile(content, "utf8");
123
- await handle.sync();
124
- }, () => handle.close());
125
- await rename(temporary, file);
126
- }
127
- catch (error) {
128
- await rm(temporary, { force: true }).catch(() => undefined);
129
- throw new WorkflowRunTransferError({
130
- path: file,
131
- reason: `cannot write the export file: ${error.message}`,
132
- cause: error,
133
- });
134
- }
135
- return "written";
90
+ return lines;
136
91
  }
137
92
  async function hasTables(executor, t) {
138
93
  const rows = await executor.all("SELECT name FROM sqlite_master WHERE type = 'table' AND name IN (?, ?, ?)", t.meta, t.runs, t.events);
139
94
  return rows.length === 3;
140
95
  }
96
+ async function hasTable(executor, name) {
97
+ return (await executor.get("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?", name)) !== undefined;
98
+ }
141
99
  async function schemaVersion(executor, t) {
142
100
  const rows = await executor.all(`SELECT schema_version FROM ${t.meta}`);
143
101
  return rows.length === 1 ? rows[0].schema_version : undefined;
144
102
  }
145
- /** Opens a journal file for an export and begins its read transaction; undefined, with the reason, when it cannot. */
103
+ /** Opens a journal file for an export and begins its read transaction; the reason when it cannot. */
146
104
  async function openExportSource(path, t, shardId) {
147
105
  if (!existsSync(path))
148
- return { path, reason: "the journal file no longer exists" };
106
+ return { path, reason: "the journal file no longer exists", oldFormat: false };
149
107
  let database;
150
108
  try {
151
109
  database = await openNodeSqliteDatabase(path, { readOnly: true });
152
110
  }
153
111
  catch (error) {
154
- return { path, reason: `the journal file cannot be opened: ${error.message}` };
112
+ return { path, reason: `the journal file cannot be opened: ${error.message}`, oldFormat: false };
155
113
  }
156
114
  try {
157
115
  await database.exec("BEGIN");
158
116
  if (!(await hasTables(database, t))) {
159
117
  await database.exec("COMMIT");
160
118
  await database.close();
161
- return { path, reason: "it has no workflow runs in the current journal format" };
119
+ return { path, reason: "it has no workflow runs in the current journal format", oldFormat: true };
162
120
  }
163
121
  const version = await schemaVersion(database, t);
164
122
  if (version !== RUN_JOURNAL_SCHEMA_VERSION) {
165
123
  await database.exec("COMMIT");
166
124
  await database.close();
167
- return { path, reason: `unsupported journal schema version ${String(version)}` };
125
+ return { path, reason: `unsupported journal schema version ${String(version)}`, oldFormat: false };
168
126
  }
169
127
  const runs = await database.all(`SELECT * FROM ${t.runs} ORDER BY run_id`);
170
- return { path, database, runs, ...(shardId === undefined ? {} : { shardId }) };
128
+ return {
129
+ path,
130
+ database,
131
+ runs,
132
+ byId: new Map(runs.map((run) => [run.run_id, run])),
133
+ ...(shardId === undefined ? {} : { shardId }),
134
+ };
171
135
  }
172
136
  catch (error) {
173
137
  await database.close().catch(() => undefined);
174
- return { path, reason: `the journal file cannot be read: ${error.message}` };
138
+ return { path, reason: `the journal file cannot be read: ${error.message}`, oldFormat: false };
175
139
  }
176
140
  }
141
+ async function closeExportSource(source) {
142
+ await source.database.exec("COMMIT").catch(() => undefined);
143
+ await source.database.close();
144
+ }
177
145
  /**
178
146
  * Adopts the default journal of Atomic before the journal store, as opening the store does, so its runs are exported
179
147
  * and compared like every other run; whether the store has a catalog.
@@ -187,88 +155,175 @@ async function adoptLegacyJournal(directory) {
187
155
  }
188
156
  return existsSync(join(directory, JOURNAL_CATALOG_FILE));
189
157
  }
158
+ async function readCatalog(directory) {
159
+ const catalog = await JournalCatalog.open(directory);
160
+ return withCleanup(async () => {
161
+ const shards = await catalog.shards();
162
+ const runs = await catalog.runs();
163
+ return { shards, runs, owners: new Map(runs.map((run) => [run.runId, run.shard])) };
164
+ }, () => catalog.close());
165
+ }
190
166
  function newestFirst(left, right) {
191
167
  const created = Number(right.created_at) - Number(left.created_at);
192
168
  if (created !== 0)
193
169
  return created;
194
170
  return left.run_id < right.run_id ? -1 : left.run_id > right.run_id ? 1 : 0;
195
171
  }
172
+ /** The journal files of a store an export reads, by shard, kept open in their read transactions until it finishes. */
173
+ class ExportSources {
174
+ opened = new Map();
175
+ unreadable = new Map();
176
+ t;
177
+ constructor(t) {
178
+ this.t = t;
179
+ }
180
+ /** Opens every shard of `view` not opened yet, and opens `fresh` again with a new snapshot. */
181
+ async open(view, fresh = new Set()) {
182
+ for (const shard of view.shards) {
183
+ const current = this.opened.get(shard.id);
184
+ if (current !== undefined && !fresh.has(shard.id))
185
+ continue;
186
+ if (current === undefined && this.unreadable.has(shard.id) && !fresh.has(shard.id))
187
+ continue;
188
+ if (current !== undefined) {
189
+ this.opened.delete(shard.id);
190
+ await closeExportSource(current);
191
+ }
192
+ this.unreadable.delete(shard.id);
193
+ const source = await openExportSource(shard.path, this.t, shard.id);
194
+ if ("database" in source)
195
+ this.opened.set(shard.id, source);
196
+ else
197
+ this.unreadable.set(shard.id, source);
198
+ }
199
+ }
200
+ /** The catalogued runs of `view` that the snapshot of the shard the catalog names for them does not hold. */
201
+ missing(view) {
202
+ return view.runs.filter((run) => {
203
+ const source = this.opened.get(run.shard);
204
+ return run.status !== undefined && source !== undefined && !source.byId.has(run.runId);
205
+ });
206
+ }
207
+ close() {
208
+ return closeEach([...this.opened.values()].map((source) => ({ close: () => closeExportSource(source) })));
209
+ }
210
+ }
211
+ /**
212
+ * Reads a journal store's catalog and opens its shards, then reads the catalog again for every run the shard it named
213
+ * did not hold: a consolidation may have moved the run between the two reads, into an existing shard or one it
214
+ * created. The shard the run moved to is read again, and so on until the placements agree or the attempts run out.
215
+ */
216
+ async function settleExportSources(directory, sources) {
217
+ let view = await readCatalog(directory);
218
+ await sources.open(view);
219
+ for (let attempt = 1; attempt < WORKFLOW_RUN_EXPORT_PLACEMENT_ATTEMPTS; attempt++) {
220
+ const missing = sources.missing(view);
221
+ if (missing.length === 0)
222
+ return view;
223
+ const next = await readCatalog(directory);
224
+ const moved = new Set();
225
+ for (const run of missing) {
226
+ const now = next.owners.get(run.runId);
227
+ if (now !== undefined && now !== run.shard)
228
+ moved.add(now);
229
+ }
230
+ const added = next.shards.some((shard) => !sources.opened.has(shard.id) && !sources.unreadable.has(shard.id));
231
+ view = next;
232
+ if (moved.size === 0 && !added)
233
+ return view;
234
+ await sources.open(view, moved);
235
+ }
236
+ return view;
237
+ }
238
+ /** Why a catalogued run that its shard's snapshot does not hold, or whose shard could not be read, is not exported. */
239
+ async function missingRunReason(run, view, sources) {
240
+ const unreadable = sources.unreadable.get(run.shard);
241
+ if (unreadable !== undefined)
242
+ return {
243
+ path: unreadable.path,
244
+ runId: run.runId,
245
+ reason: unreadable.oldFormat ? OLD_FORMAT_REASON : `its journal file cannot be read: ${unreadable.reason}`,
246
+ };
247
+ const source = sources.opened.get(run.shard);
248
+ if (source === undefined) {
249
+ const path = view.shards.find((shard) => shard.id === run.shard)?.path ?? `shard ${run.shard}`;
250
+ return { path, runId: run.runId, reason: `the catalog names shard ${run.shard} for it, which it does not list` };
251
+ }
252
+ if ((await hasTable(source.database, LEGACY_RUNS_TABLE)) &&
253
+ (await source.database.get(`SELECT 1 AS found FROM ${LEGACY_RUNS_TABLE} WHERE run_id = ?`, run.runId)))
254
+ return { path: source.path, runId: run.runId, reason: OLD_FORMAT_REASON };
255
+ return {
256
+ path: source.path,
257
+ runId: run.runId,
258
+ reason: "the journal file the catalog names for it does not hold it; it was moved or deleted while the export ran, so export again",
259
+ };
260
+ }
196
261
  /**
197
262
  * Exports runs of a local workflow journal to `<directory>/<runId>.jsonl`, one file per run. Each journal file is read
198
263
  * in one read transaction, and each export file is written whole or not at all. The same journal state gives the same
199
- * bytes, and a file that already holds them is not rewritten.
264
+ * bytes, and a file that already holds them is not rewritten. A run the store's catalog lists is taken only from the
265
+ * shard the catalog names for it, read again when a consolidation moved it while the export ran; one that cannot be
266
+ * exported is reported with the reason.
200
267
  */
201
268
  export async function exportWorkflowRuns(storage, directory, options = {}) {
202
269
  const t = runJournalTables(storage.kind === "sqlite" ? storage.prefix : undefined);
203
270
  const skipped = [];
204
- const sources = [];
205
- let owners;
206
- let catalogued = [];
207
- const add = (opened) => {
208
- if ("database" in opened)
209
- sources.push(opened);
210
- else
211
- skipped.push(opened);
212
- };
271
+ const sources = new ExportSources(t);
272
+ let single;
213
273
  return withCleanup(async () => {
274
+ const listed = new Map();
275
+ const unexported = new Map();
214
276
  if (storage.kind === "sqlite") {
215
- if (existsSync(storage.path))
216
- add(await openExportSource(storage.path, t, undefined));
277
+ if (existsSync(storage.path)) {
278
+ const opened = await openExportSource(storage.path, t, undefined);
279
+ if ("database" in opened)
280
+ single = opened;
281
+ else
282
+ skipped.push({ path: opened.path, reason: opened.reason });
283
+ }
284
+ for (const run of single?.runs ?? [])
285
+ listed.set(run.run_id, { source: single, run });
217
286
  }
218
287
  else if (await adoptLegacyJournal(storage.directory)) {
219
- const catalog = await JournalCatalog.open(storage.directory);
220
- let shards;
221
- await withCleanup(async () => {
222
- shards = await catalog.shards();
223
- catalogued = await catalog.runs();
224
- owners = new Map(catalogued.map((run) => [run.runId, run.shard]));
225
- }, () => catalog.close());
226
- for (const shard of shards)
227
- add(await openExportSource(shard.path, t, shard.id));
228
- }
229
- const listed = new Map();
230
- for (const source of sources)
231
- for (const run of source.runs) {
232
- const owner = owners?.get(run.run_id);
233
- if (owner === undefined ? listed.has(run.run_id) : owner !== source.shardId)
234
- continue;
235
- listed.set(run.run_id, { source, run });
236
- }
237
- // A consolidation that moved a run between reading the catalog and opening the journal files leaves it only in
238
- // a file the catalog did not name then: that copy is the run. A run whose named file could not be read is not
239
- // taken from another file, which may hold an older copy an interrupted consolidation left behind.
240
- const readable = new Set(sources.map((source) => source.shardId));
241
- for (const source of sources)
242
- for (const run of source.runs) {
243
- const owner = owners?.get(run.run_id);
244
- if (listed.has(run.run_id) || (owner !== undefined && !readable.has(owner)))
245
- continue;
246
- listed.set(run.run_id, { source, run });
247
- }
248
- // A run whose journal file was read but does not hold it in the current tables is in the pre-0.9.38 format;
249
- // the runs of a journal file that could not be read are covered by that file's own entry, and a root that is
250
- // only reserved (no status yet) has nothing to export.
251
- if (options.runs === undefined)
252
- for (const entry of catalogued) {
253
- const source = sources.find((candidate) => candidate.shardId === entry.shard);
254
- if (!listed.has(entry.runId) && source !== undefined && entry.status !== undefined)
255
- skipped.push({
256
- path: source.path,
257
- runId: entry.runId,
258
- reason: "it is in the journal format of Atomic before 0.9.38; resume it once to convert it",
259
- });
288
+ const view = await settleExportSources(storage.directory, sources);
289
+ const catalogued = new Set(view.runs.map((run) => run.shard));
290
+ for (const [id, unreadable] of sources.unreadable)
291
+ if (!catalogued.has(id))
292
+ skipped.push({ path: unreadable.path, reason: unreadable.reason });
293
+ for (const run of view.runs) {
294
+ const source = sources.opened.get(run.shard);
295
+ const row = source?.byId.get(run.runId);
296
+ if (source !== undefined && row !== undefined)
297
+ listed.set(run.runId, { source, run: row });
298
+ else if (run.status !== undefined)
299
+ unexported.set(run.runId, await missingRunReason(run, view, sources));
260
300
  }
301
+ // A run no catalog entry names yet (another process wrote it to a shard) is taken from the first shard
302
+ // holding it. A catalogued run is never taken from another shard, which may hold an older copy an
303
+ // interrupted consolidation left behind.
304
+ for (const source of sources.opened.values())
305
+ for (const run of source.runs)
306
+ if (!view.owners.has(run.run_id) && !listed.has(run.run_id))
307
+ listed.set(run.run_id, { source, run });
308
+ }
261
309
  let selected = [...listed.values()];
262
310
  if (options.runs !== undefined) {
263
- const missing = options.runs.find((runId) => !listed.has(runId));
264
- if (missing !== undefined)
265
- throw new WorkflowRunTransferError({
266
- path: storageLocation(storage),
267
- runId: missing,
268
- reason: `run ${missing} is not in this workflow journal`,
311
+ for (const runId of options.runs) {
312
+ if (listed.has(runId))
313
+ continue;
314
+ const reason = unexported.get(runId);
315
+ throw new StorageTransferError({
316
+ path: reason?.path ?? storageLocation(storage),
317
+ id: runId,
318
+ reason: reason === undefined
319
+ ? `run ${runId} is not in this workflow journal`
320
+ : `run ${runId} cannot be exported: ${reason.reason}`,
269
321
  });
322
+ }
270
323
  selected = [...new Set(options.runs)].map((runId) => listed.get(runId));
271
324
  }
325
+ else
326
+ skipped.push(...unexported.values());
272
327
  if (options.unfinished)
273
328
  selected = selected.filter(({ run }) => !isFinishedJournalStatus(run.status));
274
329
  selected.sort((left, right) => newestFirst(left.run, right.run));
@@ -279,14 +334,14 @@ export async function exportWorkflowRuns(storage, directory, options = {}) {
279
334
  const unchanged = [];
280
335
  for (const { source, run } of selected) {
281
336
  const events = await source.database.all(`SELECT * FROM ${t.events} WHERE run_id = ? ORDER BY seq`, run.run_id);
282
- const file = workflowRunExportFile(directory, run.run_id);
283
- const outcome = await writeAtomically(file, exportText(run, events, source.path));
337
+ const outcome = await writeLinesAtomically(transferFile(directory, run.run_id), exportLines(run, events, source.path));
284
338
  (outcome === "written" ? written : unchanged).push(run.run_id);
285
339
  }
286
340
  return { written, unchanged, skipped };
287
341
  }, async () => {
288
- await Promise.allSettled(sources.map((source) => source.database.exec("COMMIT")));
289
- await closeEach(sources.map((source) => source.database));
342
+ await sources.close();
343
+ if (single !== undefined)
344
+ await closeExportSource(single);
290
345
  });
291
346
  }
292
347
  function isObject(value) {
@@ -312,25 +367,15 @@ function fieldsReason(line, fields) {
312
367
  return `has an unexpected "${field}" field`;
313
368
  return undefined;
314
369
  }
315
- /** Reads and checks one export file, throwing a `WorkflowRunTransferError` that names the file and line. */
316
- function parseExportFile(file, bytes) {
370
+ /** Checks one export file, throwing a `StorageTransferError` that names the file and line. */
371
+ function parseExportFile({ file, lines }) {
317
372
  const fail = (line, reason, runId) => {
318
- throw new WorkflowRunTransferError({ path: file, ...(line === undefined ? {} : { line }), runId, reason });
373
+ throw new StorageTransferError({ path: file, ...(line === undefined ? {} : { line }), id: runId, reason });
319
374
  };
320
- let text;
321
- try {
322
- text = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
323
- }
324
- catch {
325
- return fail(undefined, "is not valid UTF-8 text");
326
- }
327
- const lines = text.split("\n");
328
- if (lines.at(-1) === "")
329
- lines.pop();
330
375
  if (lines.length === 0)
331
376
  return fail(1, "is empty; expected a workflow run header");
332
377
  const parse = (index) => {
333
- const line = lines[index];
378
+ const line = lines[index].text;
334
379
  if (line.trim() === "")
335
380
  return fail(index + 1, "is empty");
336
381
  let value;
@@ -433,6 +478,28 @@ function parseExportFile(file, bytes) {
433
478
  };
434
479
  return { file, header, events };
435
480
  }
481
+ /**
482
+ * Reads and checks every `*.jsonl` export file in `directory`; nothing is written. A directory that does not exist
483
+ * holds no runs. Throws `StorageTransferError` with the file and line for the first file that is not a valid export.
484
+ */
485
+ export async function readWorkflowRunExports(directory) {
486
+ const parsed = [];
487
+ const files = new Map();
488
+ for (const lines of await readTransferDirectory(directory)) {
489
+ const run = parseExportFile(lines);
490
+ const earlier = files.get(run.header.runId);
491
+ if (earlier !== undefined)
492
+ throw new StorageTransferError({
493
+ path: run.file,
494
+ line: 1,
495
+ id: run.header.runId,
496
+ reason: `run ${run.header.runId} is also in ${earlier}; keep one file per run`,
497
+ });
498
+ files.set(run.header.runId, run.file);
499
+ parsed.push(run);
500
+ }
501
+ return parsed;
502
+ }
436
503
  /** The fields import checks against a stored run: everything but string content, which a tool may redact. */
437
504
  function sameEntry(stored, exported) {
438
505
  return (Number(stored.seq) === exported.seq &&
@@ -448,12 +515,28 @@ async function readStoredRun(executor, t, runId) {
448
515
  if (run === undefined)
449
516
  return undefined;
450
517
  const events = await executor.all(`SELECT * FROM ${t.events} WHERE run_id = ? ORDER BY seq`, runId);
451
- const leases = await executor.get(`SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?`, t.leases);
452
- const lease = leases === undefined
453
- ? undefined
454
- : await executor.get(`SELECT *, MAX(0, ${STORE_NOW} - renewed_at) AS age_ms FROM ${t.leases} WHERE run_id = ?`, runId);
518
+ const lease = (await hasTable(executor, t.leases))
519
+ ? await executor.get(`SELECT *, MAX(0, ${STORE_NOW} - renewed_at) AS age_ms FROM ${t.leases} WHERE run_id = ?`, runId)
520
+ : undefined;
455
521
  return { run, events, ...(lease === undefined ? {} : { lease }) };
456
522
  }
523
+ /**
524
+ * What of a stored run an import depends on: its status, how many events it has and the last of them, and its lease.
525
+ * A run whose fingerprint differs from the one the import checked was changed by another process in between.
526
+ */
527
+ function fingerprint(stored) {
528
+ if (stored === undefined)
529
+ return "absent";
530
+ const last = stored.events.at(-1);
531
+ const lease = stored.lease;
532
+ return JSON.stringify([
533
+ stored.run.status,
534
+ Number(stored.run.created_at),
535
+ stored.events.length,
536
+ last === undefined ? null : [Number(last.seq), Number(last.epoch), last.key, last.type, Number(last.at)],
537
+ lease === undefined ? null : [lease.holder_id, Number(lease.epoch), Number(lease.renewed_at)],
538
+ ]);
539
+ }
457
540
  /**
458
541
  * What importing `parsed` does to the run as `stored` holds it: add it, add the file's later events, or nothing when
459
542
  * the storage already holds every event of the file. A run whose history differs from the file's, or that a process
@@ -464,7 +547,7 @@ function importAction(parsed, stored, location) {
464
547
  return "add";
465
548
  const { header, events, file } = parsed;
466
549
  const fail = (line, reason) => {
467
- throw new WorkflowRunTransferError({ path: file, line, runId: header.runId, reason });
550
+ throw new StorageTransferError({ path: file, line, id: header.runId, reason });
468
551
  };
469
552
  if (Number(stored.run.created_at) !== header.createdAt)
470
553
  fail(1, `run ${header.runId} in ${location} was created at another time; it is a different run with the same ID`);
@@ -484,67 +567,18 @@ function importAction(parsed, stored, location) {
484
567
  * events after the stored ones, the latest status, and an unheld lease at an epoch above every epoch the run's events
485
568
  * and any earlier holder used, so no holder from another machine is imported and a stale one here is fenced.
486
569
  */
487
- async function applyImport(tx, t, parsed, location) {
570
+ async function writeImport(tx, t, parsed, stored) {
488
571
  const { header, events } = parsed;
489
- const action = importAction(parsed, await readStoredRun(tx, t, header.runId), location);
490
- if (action === "unchanged")
491
- return action;
492
- if (action === "add")
572
+ if (stored === undefined)
493
573
  await tx.run(`INSERT INTO ${t.runs}(run_id, name, cwd, created_at, status, header_json) VALUES (?, ?, ?, ?, ?, ?)`, header.runId, header.name, header.cwd, header.createdAt, header.status, JSON.stringify(header.header));
494
574
  else
495
575
  await tx.run(`UPDATE ${t.runs} SET status = ? WHERE run_id = ?`, header.status, header.runId);
496
- const stored = action === "add"
497
- ? 0
498
- : Number((await tx.get(`SELECT COALESCE(MAX(seq), 0) AS seq FROM ${t.events} WHERE run_id = ?`, header.runId)).seq);
499
- for (const event of events.slice(stored))
576
+ for (const event of events.slice(stored?.events.length ?? 0))
500
577
  await tx.run(`INSERT INTO ${t.events}(run_id, seq, epoch, key, type, payload, at) VALUES (?, ?, ?, ?, ?, ?, ?)`, header.runId, event.seq, event.epoch, event.key, event.type, JSON.stringify(event.payload), event.at);
501
578
  const epoch = events.reduce((highest, event) => Math.max(highest, event.epoch), 0);
502
579
  await tx.run(`INSERT INTO ${t.leases}(run_id, holder_id, epoch, renewed_at) VALUES (?, NULL, ?, ${STORE_NOW})
503
580
  ON CONFLICT(run_id) DO UPDATE SET holder_id = NULL, renewed_at = excluded.renewed_at,
504
581
  epoch = MAX(excluded.epoch, ${t.leases}.epoch + (CASE WHEN ${t.leases}.holder_id IS NULL THEN 0 ELSE 1 END))`, header.runId, epoch);
505
- return action;
506
- }
507
- /** Reads and checks every export file in `directory`; nothing is written. */
508
- async function readExportDirectory(directory) {
509
- let names;
510
- try {
511
- names = await readdir(directory);
512
- }
513
- catch (error) {
514
- throw new WorkflowRunTransferError({
515
- path: directory,
516
- reason: `cannot read the directory: ${error.message}`,
517
- cause: error,
518
- });
519
- }
520
- const parsed = [];
521
- const files = new Map();
522
- for (const name of names.filter((entry) => entry.endsWith(WORKFLOW_RUN_EXPORT_EXTENSION)).sort()) {
523
- const file = join(directory, name);
524
- let bytes;
525
- try {
526
- bytes = await readFile(file);
527
- }
528
- catch (error) {
529
- throw new WorkflowRunTransferError({
530
- path: file,
531
- reason: `cannot read the file: ${error.message}`,
532
- cause: error,
533
- });
534
- }
535
- const run = parseExportFile(file, bytes);
536
- const earlier = files.get(run.header.runId);
537
- if (earlier !== undefined)
538
- throw new WorkflowRunTransferError({
539
- path: file,
540
- line: 1,
541
- runId: run.header.runId,
542
- reason: `run ${run.header.runId} is also in ${earlier}; keep one file per run`,
543
- });
544
- files.set(run.header.runId, file);
545
- parsed.push(run);
546
- }
547
- return parsed;
548
582
  }
549
583
  /** A journal file an import reads its runs from while it decides what to write: read-only, opened once. */
550
584
  class ReadOnlyFiles {
@@ -563,56 +597,61 @@ class ReadOnlyFiles {
563
597
  }
564
598
  }
565
599
  function unreadableShard(parsed, path, error) {
566
- return new WorkflowRunTransferError({
600
+ return new StorageTransferError({
567
601
  path: parsed.file,
568
602
  line: 1,
569
- runId: parsed.header.runId,
603
+ id: parsed.header.runId,
570
604
  reason: `run ${parsed.header.runId} is in the journal file ${path}, which cannot be read: ${error.message}`,
571
605
  cause: error,
572
606
  });
573
607
  }
574
- /** The journal file of a store holding `runId`: the one the catalog names, else an adopted journal that holds it. */
608
+ /**
609
+ * The shard of a store holding `runId`: the one the catalog names, else any shard that holds it although the catalog
610
+ * does not list it, as an adopted journal another process wrote to or a shard an interrupted import wrote to before
611
+ * it recorded the run in the catalog.
612
+ */
575
613
  async function storedShard(catalog, files, t, runId) {
576
614
  const found = await catalog.locate(runId);
577
615
  if (found !== undefined)
578
- return found.shard;
616
+ return { shard: found.shard, catalogued: true };
579
617
  for (const shard of await catalog.shards()) {
580
- if (shard.kind !== "adopted" || !existsSync(shard.path))
618
+ if (!existsSync(shard.path))
581
619
  continue;
582
620
  try {
583
621
  const database = await files.read(shard.path);
584
622
  if ((await hasTables(database, t)) && (await database.get(`SELECT 1 FROM ${t.runs} WHERE run_id = ?`, runId)))
585
- return shard;
623
+ return { shard, catalogued: false };
586
624
  }
587
625
  catch { }
588
626
  }
589
627
  return undefined;
590
628
  }
629
+ /** The runs of a plan an import writes. */
630
+ export function pendingWorkflowRuns(plan) {
631
+ return plan.runs.filter((run) => run.action !== "unchanged").map((run) => run.run.header.runId);
632
+ }
591
633
  /**
592
- * Imports every `<name>.jsonl` export file in `directory` into a local workflow journal. Every file is read and checked,
593
- * and every run compared with the storage's copy, before anything is written: a malformed file, an unsupported version,
594
- * a run that continued differently here, or a run a process here may still be running fails the import with the file
595
- * and line, and nothing changes. A run the storage does not hold is added; one whose earlier events it holds gets the
596
- * file's later ones; one it holds every event of is left as it is, so importing again changes nothing. String values
597
- * inside the records are not compared, so a file whose strings a tool redacted imports as the run it was exported from.
634
+ * Compares every run of `runs` with the storage's copy, writing nothing: a run that continued differently here, or that
635
+ * a process here may still be running, fails with the file and line.
598
636
  */
599
- export async function importWorkflowRuns(storage, directory) {
600
- const runs = await readExportDirectory(directory);
637
+ export async function planWorkflowRunImport(storage, runs) {
601
638
  const t = runJournalTables(storage.kind === "sqlite" ? storage.prefix : undefined);
602
639
  const location = storageLocation(storage);
603
640
  const files = new ReadOnlyFiles();
604
- const actions = [];
641
+ const planned = [];
642
+ if (runs.length === 0)
643
+ return { storage, runs: planned };
605
644
  await withCleanup(async () => {
606
645
  const catalogExists = storage.kind === "store" && (await adoptLegacyJournal(storage.directory));
607
646
  const catalog = catalogExists ? await JournalCatalog.open(storage.directory) : undefined;
608
647
  await withCleanup(async () => {
609
648
  for (const run of runs) {
610
- const shard = catalog === undefined ? undefined : await storedShard(catalog, files, t, run.header.runId);
611
- let path = shard?.path;
649
+ const found = catalog === undefined ? undefined : await storedShard(catalog, files, t, run.header.runId);
650
+ let path = found?.shard.path;
612
651
  if (storage.kind === "sqlite")
613
652
  path = existsSync(storage.path) ? storage.path : undefined;
614
653
  let stored;
615
- if (path !== undefined) {
654
+ if (path !== undefined && existsSync(path)) {
616
655
  try {
617
656
  stored = await readStoredRun(await files.read(path), t, run.header.runId);
618
657
  }
@@ -620,71 +659,138 @@ export async function importWorkflowRuns(storage, directory) {
620
659
  throw unreadableShard(run, path, error);
621
660
  }
622
661
  }
623
- actions.push({
662
+ planned.push({
624
663
  run,
625
664
  action: importAction(run, stored, path ?? location),
626
- ...(shard === undefined ? {} : { shard }),
665
+ stored,
666
+ catalogued: found?.catalogued ?? false,
667
+ ...(found === undefined ? {} : { shard: found.shard }),
627
668
  });
628
669
  }
629
670
  }, async () => catalog?.close());
630
671
  }, () => files.close());
672
+ return { storage, runs: planned };
673
+ }
674
+ /**
675
+ * Writes what `plan` decided. Every journal file the import writes to is opened and its write lock taken, in path
676
+ * order, before anything is written, and every run is compared again under those locks: a run another process changed
677
+ * since the plan was made (a resume took its lease, events were added, a consolidation moved it) fails the import with
678
+ * nothing written. The locks are held until the last run is written; each file then commits. Separate journal files
679
+ * cannot commit together, so when one fails to commit after another did, `StorageImportIncompleteError` names the runs
680
+ * written and the runs not written, and importing again writes only the rest. A store's catalog records added runs
681
+ * after their files commit; a run an interrupted import wrote before recording it is found and recorded by the next.
682
+ */
683
+ export async function applyWorkflowRunImport(plan) {
684
+ const { storage } = plan;
685
+ const prefix = storage.kind === "sqlite" ? storage.prefix : undefined;
686
+ const t = runJournalTables(prefix);
631
687
  const report = { added: [], updated: [], unchanged: [] };
632
- const record = (runId, action) => (action === "add" ? report.added : action === "update" ? report.updated : report.unchanged).push(runId);
633
- const pending = actions.filter(({ action, run }) => {
634
- if (action === "unchanged")
635
- record(run.header.runId, action);
636
- return action !== "unchanged";
688
+ const pending = plan.runs.filter((run) => {
689
+ if (run.action === "unchanged")
690
+ report.unchanged.push(run.run.header.runId);
691
+ return run.action !== "unchanged";
637
692
  });
638
- if (pending.length === 0)
639
- return report;
640
- if (storage.kind === "sqlite") {
641
- const database = await openNodeSqliteDatabase(storage.path);
642
- await withCleanup(async () => {
643
- for (const { run } of pending)
644
- record(run.header.runId, await database.transaction(async (tx) => {
645
- await ensureRunJournalSchema(tx, storage.prefix);
646
- return applyImport(tx, t, run, location);
647
- }, TRANSFER_TRANSACTION));
648
- }, () => database.close());
693
+ const uncatalogued = plan.runs.filter((run) => run.action === "unchanged" && !run.catalogued && run.shard);
694
+ if (pending.length === 0 && uncatalogued.length === 0)
649
695
  return report;
650
- }
651
- const catalog = await JournalCatalog.open(storage.directory);
652
- const shards = new Map();
653
- await withCleanup(async () => {
654
- for (const { run, shard: stored } of pending) {
655
- const { runId, name, cwd, status } = run.header;
656
- // A new run goes to the shard its ID hashes to, as a consolidated run does: it writes nothing until it is
657
- // resumed, so it never makes a shard busy for new roots.
658
- const shard = await catalog.shard(await catalog.index((stored ?? (await catalog.homeShard(runId))).id, { runId, name, cwd, status }));
659
- if (shard === undefined)
660
- throw new WorkflowRunTransferError({
661
- path: run.file,
662
- line: 1,
663
- runId,
664
- reason: `cannot place run ${runId} in ${location}`,
665
- });
666
- let database = shards.get(shard.path);
667
- if (database === undefined) {
668
- try {
669
- database = await openNodeSqliteDatabase(shard.path);
670
- }
671
- catch (error) {
672
- throw unreadableShard(run, shard.path, error);
696
+ const catalog = storage.kind === "store" ? await JournalCatalog.open(storage.directory) : undefined;
697
+ const groups = new Map();
698
+ const committed = [];
699
+ const written = () => committed.flatMap((group) => group.runs.map((run) => run.run.header.runId));
700
+ try {
701
+ for (const run of pending) {
702
+ const shard = catalog === undefined ? undefined : (run.shard ?? (await catalog.homeShard(run.run.header.runId)));
703
+ const path = shard?.path ?? storageLocation(storage);
704
+ let group = groups.get(path);
705
+ if (group === undefined) {
706
+ group = { path, runs: [], ...(shard === undefined ? {} : { shard }) };
707
+ groups.set(path, group);
708
+ }
709
+ group.runs.push(run);
710
+ }
711
+ const ordered = [...groups.values()].sort((left, right) => (left.path < right.path ? -1 : 1));
712
+ for (const group of ordered) {
713
+ try {
714
+ group.database = await openNodeSqliteDatabase(group.path);
715
+ }
716
+ catch (error) {
717
+ throw unreadableShard(group.runs[0].run, group.path, error);
718
+ }
719
+ }
720
+ const lockAll = async (index) => {
721
+ if (index === ordered.length) {
722
+ for (const group of ordered)
723
+ for (const run of group.runs) {
724
+ const now = await readStoredRun(group.tx, t, run.run.header.runId);
725
+ if (fingerprint(now) !== fingerprint(run.stored))
726
+ throw new StorageTransferError({
727
+ path: run.run.file,
728
+ line: 1,
729
+ id: run.run.header.runId,
730
+ reason: `run ${run.run.header.runId} changed in ${group.path} after the import compared it (another process wrote to it, took its lease or moved it); nothing was imported, so import again`,
731
+ });
732
+ importAction(run.run, now, group.path);
733
+ }
734
+ for (const group of ordered) {
735
+ await ensureRunJournalSchema(group.tx, prefix);
736
+ for (const run of group.runs)
737
+ await writeImport(group.tx, t, run.run, run.stored);
673
738
  }
674
- shards.set(shard.path, database);
739
+ return;
675
740
  }
676
- const action = await database.transaction(async (tx) => {
677
- await ensureRunJournalSchema(tx);
678
- return applyImport(tx, t, run, shard.path);
741
+ const group = ordered[index];
742
+ await group.database.transaction(async (tx) => {
743
+ group.tx = tx;
744
+ await lockAll(index + 1);
679
745
  }, TRANSFER_TRANSACTION);
680
- if (action !== "unchanged")
681
- await catalog.setStatus(runId, status);
682
- record(runId, action);
746
+ committed.push(group);
747
+ };
748
+ await lockAll(0);
749
+ if (catalog !== undefined) {
750
+ for (const group of ordered)
751
+ for (const run of group.runs) {
752
+ const { runId, name, cwd, status } = run.run.header;
753
+ if (run.catalogued)
754
+ await catalog.setStatus(runId, status);
755
+ else
756
+ await catalog.index(group.shard.id, { runId, name, cwd, status });
757
+ }
758
+ for (const run of uncatalogued) {
759
+ const { runId, name, cwd, status } = run.run.header;
760
+ await catalog.index(run.shard.id, { runId, name, cwd, status });
761
+ }
683
762
  }
684
- }, async () => {
685
- await closeEach(shards.values());
686
- await catalog.close();
687
- });
763
+ }
764
+ catch (error) {
765
+ const done = written();
766
+ if (done.length === 0)
767
+ throw error;
768
+ const doneSet = new Set(done);
769
+ throw new StorageImportIncompleteError(error, {
770
+ written: { sessions: [], workflows: done },
771
+ notWritten: {
772
+ sessions: [],
773
+ workflows: pending.map((run) => run.run.header.runId).filter((runId) => !doneSet.has(runId)),
774
+ },
775
+ });
776
+ }
777
+ finally {
778
+ await closeEach([...groups.values()].flatMap((group) => (group.database === undefined ? [] : [group.database]))).catch(() => undefined);
779
+ await catalog?.close();
780
+ }
781
+ for (const run of pending)
782
+ (run.action === "add" ? report.added : report.updated).push(run.run.header.runId);
688
783
  return report;
689
784
  }
785
+ /**
786
+ * Imports every `<name>.jsonl` export file in `directory` into a local workflow journal: `readWorkflowRunExports`,
787
+ * `planWorkflowRunImport` and `applyWorkflowRunImport` in turn. Every file is read and checked, and every run compared
788
+ * with the storage's copy, before anything is written. A run the storage does not hold is added; one whose earlier
789
+ * events it holds gets the file's later ones; one it holds every event of is left as it is, so importing again changes
790
+ * nothing. String values inside the records are not compared, so a file whose strings a tool redacted imports as the
791
+ * run it was exported from.
792
+ */
793
+ export async function importWorkflowRuns(storage, directory) {
794
+ return applyWorkflowRunImport(await planWorkflowRunImport(storage, await readWorkflowRunExports(directory)));
795
+ }
690
796
  //# sourceMappingURL=journal-transfer.js.map