@bastani/atomic 0.9.82 → 0.9.83-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.
@@ -1,3 +1,4 @@
1
+ import type { SqliteExecutor, SqliteRow } from "./database.js";
1
2
  import { type JournalAdoptErrorCode, JournalCatalogError, JournalShardUnavailableError } from "./errors.js";
2
3
  import { JournalCatalog, type JournalCatalogRunHeader } from "./journal-catalog.js";
3
4
  /** The journal store's directory under an agent directory: `<agent dir's parent>/workflows/journal`. */
@@ -7,6 +8,22 @@ export declare function defaultJournalStoreDirectory(agentDir: string): string;
7
8
  * A store opened in `directory` adopts it in place when it holds workflow runs.
8
9
  */
9
10
  export declare function legacyDefaultJournalPath(directory: string): string;
11
+ /** The tables of a SQL run journal, before the storage prefix and the `wf_` domain prefix. */
12
+ export declare const RUN_JOURNAL_TABLE_NAMES: {
13
+ readonly meta: "meta";
14
+ readonly runs: "runs";
15
+ readonly events: "events";
16
+ readonly leases: "leases";
17
+ };
18
+ /** A SQL run journal's table names under `prefix`. */
19
+ export declare function runJournalTables(prefix?: string): Readonly<Record<keyof typeof RUN_JOURNAL_TABLE_NAMES, string>>;
20
+ /** `CREATE TABLE IF NOT EXISTS` statements for a SQL run journal's runs, events and leases tables. */
21
+ export declare function runJournalTableDefinitions(prefix?: string): string;
22
+ /**
23
+ * Creates a SQL run journal's metadata and tables inside the caller's transaction when they are missing, and checks
24
+ * that an existing journal has the supported schema version. Throws `StorageSchemaVersionError` otherwise.
25
+ */
26
+ export declare function ensureRunJournalSchema(tx: SqliteExecutor, prefix?: string): Promise<void>;
10
27
  /** Most journals one adoption follows through the run references it finds. */
11
28
  export declare const JOURNAL_DISCOVERY_LIMIT = 64;
12
29
  /** The lease holder a consolidation fences a run with while it moves; its successor recognizes an interrupted move. */
@@ -94,6 +111,37 @@ export interface JournalConsolidationReport {
94
111
  readonly skipped: number;
95
112
  readonly runs: readonly JournalConsolidationRun[];
96
113
  }
114
+ /** A row of a SQL run journal's runs table. */
115
+ export type JournalRunTableRow = SqliteRow & {
116
+ run_id: string;
117
+ name: string;
118
+ cwd: string;
119
+ created_at: number;
120
+ status: string;
121
+ header_json: string;
122
+ };
123
+ /** A row of a SQL run journal's events table: one journal entry, its payload as JSON text. */
124
+ export type JournalEventTableRow = SqliteRow & {
125
+ run_id: string;
126
+ seq: number;
127
+ epoch: number;
128
+ key: string | null;
129
+ type: string;
130
+ payload: string;
131
+ at: number;
132
+ };
133
+ /** A row of a SQL run journal's leases table. */
134
+ export type JournalLeaseTableRow = SqliteRow & {
135
+ run_id: string;
136
+ holder_id: string | null;
137
+ epoch: number;
138
+ renewed_at: number;
139
+ };
140
+ /** A run's row and its events in sequence order, as one journal file holds them. */
141
+ export interface JournalRunSnapshot {
142
+ readonly run: JournalRunTableRow;
143
+ readonly events: readonly JournalEventTableRow[];
144
+ }
97
145
  /**
98
146
  * Moves finished runs out of adopted journals into the store's own shards. A run moves only when it finished
99
147
  * (completed, failed or cancelled), no process holds its lease, it never ran local workers (their pool state stays in
@@ -1 +1 @@
1
- {"version":3,"file":"journal-adoption.d.ts","sourceRoot":"","sources":["../../../src/core/storage/journal-adoption.ts"],"names":[],"mappings":"AAOA,OAAO,EAGN,KAAK,qBAAqB,EAC1B,mBAAmB,EACnB,4BAA4B,EAC5B,MAAM,aAAa,CAAC;AAErB,OAAO,EAEN,cAAc,EACd,KAAK,uBAAuB,EAG5B,MAAM,sBAAsB,CAAC;AAK9B,wGAAwG;AACxG,wBAAgB,4BAA4B,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,CAErE;AAED;;;GAGG;AACH,wBAAgB,wBAAwB,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM,CAElE;AAED,8EAA8E;AAC9E,eAAO,MAAM,uBAAuB,KAAK,CAAC;AAC1C,uHAAuH;AACvH,eAAO,MAAM,mCAAmC,gCAAgC,CAAC;AAQjF,0HAA0H;AAC1H,eAAO,MAAM,yBAAyB,8BAA8B,C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AAE,CAAC;CACjD;AA2PD;;;;;;;;GAQG;AACH,wBAAsB,uBAAuB,CAAC,KAAK,EAAE,MAAM,GAAG,cAAc,GAAG,OAAO,CAAC,0BAA0B,CAAC,CAuDjH"}
@@ -3,7 +3,7 @@ import { existsSync } from "node:fs";
3
3
  import { open, stat } from "node:fs/promises";
4
4
  import { dirname, join, resolve } from "node:path";
5
5
  import { closeEach, withCleanup } from "./cleanup.js";
6
- import { isJournalAdoptError, JournalAdoptError, JournalCatalogError, JournalShardUnavailableError, } from "./errors.js";
6
+ import { isJournalAdoptError, JournalAdoptError, JournalCatalogError, JournalShardUnavailableError, StorageSchemaVersionError, } from "./errors.js";
7
7
  import { isSameFile } from "./file-identity.js";
8
8
  import { isFinishedJournalStatus, JournalCatalog, } from "./journal-catalog.js";
9
9
  import { openNodeSqliteDatabase } from "./node-sqlite.js";
@@ -20,6 +20,46 @@ export function defaultJournalStoreDirectory(agentDir) {
20
20
  export function legacyDefaultJournalPath(directory) {
21
21
  return join(dirname(resolve(directory)), "journal.sqlite");
22
22
  }
23
+ /** The tables of a SQL run journal, before the storage prefix and the `wf_` domain prefix. */
24
+ export const RUN_JOURNAL_TABLE_NAMES = { meta: "meta", runs: "runs", events: "events", leases: "leases" };
25
+ /** A SQL run journal's table names under `prefix`. */
26
+ export function runJournalTables(prefix = "") {
27
+ return renderStorageIdentifiers("journal", RUN_JOURNAL_TABLE_NAMES, prefix);
28
+ }
29
+ /** `CREATE TABLE IF NOT EXISTS` statements for a SQL run journal's runs, events and leases tables. */
30
+ export function runJournalTableDefinitions(prefix = "") {
31
+ const t = runJournalTables(prefix);
32
+ return `
33
+ CREATE TABLE IF NOT EXISTS ${t.runs}(
34
+ run_id TEXT PRIMARY KEY, name TEXT NOT NULL, cwd TEXT NOT NULL,
35
+ created_at INTEGER NOT NULL, status TEXT NOT NULL, header_json TEXT NOT NULL
36
+ );
37
+ CREATE TABLE IF NOT EXISTS ${t.events}(
38
+ run_id TEXT NOT NULL,
39
+ seq INTEGER NOT NULL, epoch INTEGER NOT NULL, key TEXT,
40
+ type TEXT NOT NULL, payload TEXT NOT NULL, at INTEGER NOT NULL,
41
+ PRIMARY KEY(run_id, seq), UNIQUE(run_id, key)
42
+ );
43
+ CREATE TABLE IF NOT EXISTS ${t.leases}(
44
+ run_id TEXT PRIMARY KEY,
45
+ holder_id TEXT, epoch INTEGER NOT NULL, renewed_at INTEGER NOT NULL
46
+ );
47
+ `;
48
+ }
49
+ /**
50
+ * Creates a SQL run journal's metadata and tables inside the caller's transaction when they are missing, and checks
51
+ * that an existing journal has the supported schema version. Throws `StorageSchemaVersionError` otherwise.
52
+ */
53
+ export async function ensureRunJournalSchema(tx, prefix = "") {
54
+ const t = runJournalTables(prefix);
55
+ await tx.exec(`CREATE TABLE IF NOT EXISTS ${t.meta}(schema_version INTEGER NOT NULL)`);
56
+ const versions = await tx.all(`SELECT schema_version FROM ${t.meta}`);
57
+ if (versions.length === 0)
58
+ await tx.run(`INSERT INTO ${t.meta} VALUES (?)`, RUN_JOURNAL_SCHEMA_VERSION);
59
+ else if (versions.length > 1 || versions[0].schema_version !== RUN_JOURNAL_SCHEMA_VERSION)
60
+ throw new StorageSchemaVersionError("journal", versions.length > 1 ? `${versions.length} rows` : versions[0].schema_version, RUN_JOURNAL_SCHEMA_VERSION);
61
+ await tx.exec(runJournalTableDefinitions(prefix));
62
+ }
23
63
  /** Most journals one adoption follows through the run references it finds. */
24
64
  export const JOURNAL_DISCOVERY_LIMIT = 64;
25
65
  /** The lease holder a consolidation fences a run with while it moves; its successor recognizes an interrupted move. */
@@ -1 +1 @@
1
- {"version":3,"file":"journal-adoption.js","sourceRoot":"","sources":["../../../src/core/storage/journal-adoption.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AACrC,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,kBAAkB,CAAC;AAC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AC,CAAC,EAAE,KAAK,CAAC,EAAE,KAAK,WAAW,CAAC,EAAE,EAAE,CAAC;QAC9E,MAAM,SAAS,CAAC,QAAQ,EAAE,KAAK,EAAE,MAAM,CAAC,CAAC;QACzC,MAAM,OAAO,CAAC,MAAM,EAAE,KAAK,EAAE,MAAM,CAAC,CAAC;QACrC,OAAO,EAAE,KAAK,EAAE,IAAI,EAAE,KAAK,CAAC,EAAE,EAAE,OAAO,EAAE,SAAS,EAAE,MAAM,EAAE,SAAS,EAAE,CAAC;IACzE,CAAC;IACD,MAAM,OAAO,GAAG,MAAM,UAAU,CAAC,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,WAAW,EAAE,QAAQ,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;IACnH,kGAAkG;IAClG,OAAO,SAAS,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,IAAI,EAAE,KAAK,CAAC,EAAE,EAAE,OAAO,EAAE,SAAS,EAAE,MAAM,EAAE,SAAS,EAAE,CAAC;AAC/F,CAAC","sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport { existsSync } from \"node:fs\";\nimport { open, stat } from \"node:fs/promises\";\nimport { dirname, join, resolve } from \"node:path\";\nimport { closeEach, withCleanup } from \"./cleanup.js\";\nimport type { SqliteDatabase, SqliteExecutor, SqliteRow, SqliteValue } from \"./database.js\";\nimport type { StorageFailureCause } from \"./errors.js\";\nimport {\n\tisJournalAdoptError,\n\tJournalAdoptError,\n\ttype JournalAdoptErrorCode,\n\tJournalCatalogError,\n\tJournalShardUnavailableError,\n} from \"./errors.js\";\nimport { isSameFile } from \"./file-identity.js\";\nimport {\n\tisFinishedJournalStatus,\n\tJournalCatalog,\n\ttype JournalCatalogRunHeader,\n\ttype JournalShardRecord,\n\ttype JournalShardRegistration,\n} from \"./journal-catalog.js\";\nimport { openNodeSqliteDatabase } from \"./node-sqlite.js\";\nimport { renderStorageIdentifiers } from \"./prefix.js\";\nimport { RUN_JOURNAL_SCHEMA_VERSION } from \"./run-journal.js\";\n\n/** The journal store's directory under an agent directory: `<agent dir's parent>/workflows/journal`. */\nexport function defaultJournalStoreDirectory(agentDir: string): string {\n\treturn join(dirname(agentDir), \"workflows\", \"journal\");\n}\n\n/**\n * The single-file journal every workflow run used by default before the journal store, beside the store's directory.\n * A store opened in `directory` adopts it in place when it holds workflow runs.\n */\nexport function legacyDefaultJournalPath(directory: string): string {\n\treturn join(dirname(resolve(directory)), \"journal.sqlite\");\n}\n\n/** Most journals one adoption follows through the run references it finds. */\nexport const JOURNAL_DISCOVERY_LIMIT = 64;\n/** The lease holder a consolidation fences a run with while it moves; its successor recognizes an interrupted move. */\nexport const JOURNAL_CONSOLIDATION_HOLDER_PREFIX = \"atomic-storage-consolidate:\";\n\nconst SQLITE_HEADER = \"SQLite format 3\\u0000\";\nconst TABLES = renderStorageIdentifiers(\"journal\", { meta: \"meta\", runs: \"runs\", events: \"events\", leases: \"leases\" });\nconst POOL_ROOTS = `${TABLES.runs}_pool_roots`;\nconst LEGACY_RUNS = \"runs\";\nconst LEGACY_DELETED = renderStorageIdentifiers(\"journal\", { legacyDeleted: \"legacy_deleted\" }).legacyDeleted;\nconst MIGRATIONS = renderStorageIdentifiers(\"journal\", { migrations: \"migrations\" }).migrations;\n/** Recorded in a journal's migrations by the earlier version that copied every pre-0.9.38 run into the current tables. */\nexport const JOURNAL_COPIED_ALL_MARKER = \"unprefixed-journal-tables\";\nconst STORE_NOW = \"CAST(unixepoch('subsec') * 1000 AS INTEGER)\";\n\n/** What a journal file holds, read without changing it. */\nexport interface JournalFileInspection {\n\treadonly path: string;\n\treadonly runs: readonly JournalCatalogRunHeader[];\n\t/** Other node-sqlite journal files its runs say they were written to. */\n\treadonly references: readonly string[];\n}\n\n/** The journal file an adoption path names: the file itself, or `journal.sqlite` in a directory. */\nasync function adoptionFile(path: string): Promise<string> {\n\tconst absolute = resolve(path);\n\tlet info: Awaited<ReturnType<typeof stat>>;\n\ttry {\n\t\tinfo = await stat(absolute);\n\t} catch (cause) {\n\t\tthrow new JournalAdoptError({ code: \"path-not-found\", path: absolute, cause: cause as StorageFailureCause });\n\t}\n\tif (!info.isDirectory()) return absolute;\n\tconst inside = join(absolute, \"journal.sqlite\");\n\tif (!existsSync(inside)) throw new JournalAdoptError({ code: \"not-a-journal\", path: absolute, reason: \"directory\" });\n\treturn inside;\n}\n\nasync function hasSqliteHeader(path: string): Promise<boolean> {\n\tconst handle = await open(path, \"r\");\n\treturn withCleanup(\n\t\tasync () => {\n\t\t\tconst buffer = Buffer.alloc(SQLITE_HEADER.length);\n\t\t\tconst { bytesRead } = await handle.read(buffer, 0, buffer.length, 0);\n\t\t\treturn bytesRead === buffer.length && buffer.toString(\"latin1\") === SQLITE_HEADER;\n\t\t},\n\t\t() => handle.close(),\n\t);\n}\n\nasync function tableNames(executor: SqliteExecutor): Promise<ReadonlySet<string>> {\n\tconst rows = await executor.all<SqliteRow & { name: string }>(\"SELECT name FROM sqlite_master WHERE type = 'table'\");\n\treturn new Set(rows.map((row) => row.name));\n}\n\nfunction referencedJournal(headerJson: string, self: string): string | undefined {\n\tlet header: { storage?: { adapter?: unknown; location?: unknown } };\n\ttry {\n\t\theader = JSON.parse(headerJson) as typeof header;\n\t} catch {\n\t\treturn undefined;\n\t}\n\tconst location = header.storage?.location;\n\tif (header.storage?.adapter !== \"node-sqlite\" || typeof location !== \"string\") return undefined;\n\tif (location === \"\" || location === \":memory:\") return undefined;\n\tconst absolute = resolve(location);\n\treturn absolute === self ? undefined : absolute;\n}\n\n/**\n * Reads a journal file without changing it: that it is a SQLite workflow journal of a supported schema version, its\n * runs, and the other journal files its runs reference. Throws `JournalAdoptError` for anything that cannot be adopted.\n */\nexport async function inspectJournalFile(path: string): Promise<JournalFileInspection> {\n\tconst file = await adoptionFile(path);\n\tlet sqlite: boolean;\n\ttry {\n\t\tsqlite = await hasSqliteHeader(file);\n\t} catch (cause) {\n\t\tthrow new JournalAdoptError({\n\t\t\tcode: \"not-a-journal\",\n\t\t\tpath: file,\n\t\t\treason: \"not-sqlite\",\n\t\t\tcause: cause as StorageFailureCause,\n\t\t});\n\t}\n\tif (!sqlite) throw new JournalAdoptError({ code: \"not-a-journal\", path: file, reason: \"not-sqlite\" });\n\tlet database: SqliteDatabase;\n\ttry {\n\t\tdatabase = await openNodeSqliteDatabase(file, { readOnly: true });\n\t} catch (cause) {\n\t\tthrow new JournalAdoptError({\n\t\t\tcode: \"not-a-journal\",\n\t\t\tpath: file,\n\t\t\treason: \"not-sqlite\",\n\t\t\tcause: cause as StorageFailureCause,\n\t\t});\n\t}\n\treturn withCleanup(\n\t\tasync () => {\n\t\t\ttry {\n\t\t\t\tconst names = await tableNames(database);\n\t\t\t\tif (names.has(\"catalog_shards\"))\n\t\t\t\t\tthrow new JournalAdoptError({ code: \"not-a-journal\", path: file, reason: \"store-catalog\" });\n\t\t\t\tconst current = names.has(TABLES.meta) && names.has(TABLES.runs);\n\t\t\t\tconst legacy = names.has(\"meta\") && names.has(LEGACY_RUNS) && names.has(\"events\");\n\t\t\t\tif (!current && !legacy)\n\t\t\t\t\tthrow new JournalAdoptError({ code: \"not-a-journal\", path: file, reason: \"no-journal-tables\" });\n\t\t\t\tconst versions = await database.all<SqliteRow & { schema_version: SqliteValue }>(\n\t\t\t\t\t`SELECT schema_version FROM ${current ? TABLES.meta : \"meta\"}`,\n\t\t\t\t);\n\t\t\t\tconst found = versions[0]?.schema_version;\n\t\t\t\tif (versions.length !== 1 || found !== RUN_JOURNAL_SCHEMA_VERSION)\n\t\t\t\t\tthrow new JournalAdoptError({\n\t\t\t\t\t\tcode: \"schema-version\",\n\t\t\t\t\t\tpath: file,\n\t\t\t\t\t\tfound: found ?? null,\n\t\t\t\t\t\tsupported: RUN_JOURNAL_SCHEMA_VERSION,\n\t\t\t\t\t});\n\t\t\t\ttype RunRows = (SqliteRow & {\n\t\t\t\t\trun_id: string;\n\t\t\t\t\tname: string;\n\t\t\t\t\tcwd: string;\n\t\t\t\t\tstatus: string;\n\t\t\t\t\theader_json: string;\n\t\t\t\t})[];\n\t\t\t\tconst rows: RunRows = current\n\t\t\t\t\t? await database.all(`SELECT run_id, name, cwd, status, header_json FROM ${TABLES.runs} ORDER BY run_id`)\n\t\t\t\t\t: [];\n\t\t\t\tconst copiedAll =\n\t\t\t\t\tnames.has(MIGRATIONS) &&\n\t\t\t\t\t(await database.get(`SELECT name FROM ${MIGRATIONS} WHERE name = ?`, JOURNAL_COPIED_ALL_MARKER)) !==\n\t\t\t\t\t\tundefined;\n\t\t\t\tif (legacy && !copiedAll) {\n\t\t\t\t\t// Runs of the pre-0.9.38 tables that were not converted or deleted since: read, never converted. A journal\n\t\t\t\t\t// that an earlier version copied in full has its legacy tables ignored, as the journal itself ignores them.\n\t\t\t\t\tconst converted = [\n\t\t\t\t\t\tnames.has(TABLES.runs) ? `AND run_id NOT IN (SELECT run_id FROM ${TABLES.runs})` : \"\",\n\t\t\t\t\t\tnames.has(LEGACY_DELETED) ? `AND run_id NOT IN (SELECT run_id FROM ${LEGACY_DELETED})` : \"\",\n\t\t\t\t\t].join(\" \");\n\t\t\t\t\trows.push(\n\t\t\t\t\t\t...(await database.all<RunRows[number]>(\n\t\t\t\t\t\t\t`SELECT run_id, name, cwd, status, header_json FROM ${LEGACY_RUNS} WHERE 1 = 1 ${converted} ORDER BY run_id`,\n\t\t\t\t\t\t)),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tconst references = new Set<string>();\n\t\t\t\tfor (const row of rows) {\n\t\t\t\t\tconst referenced = referencedJournal(row.header_json, file);\n\t\t\t\t\tif (referenced !== undefined) references.add(referenced);\n\t\t\t\t}\n\t\t\t\treturn {\n\t\t\t\t\tpath: file,\n\t\t\t\t\truns: rows.map((row) => ({ runId: row.run_id, name: row.name, cwd: row.cwd, status: row.status })),\n\t\t\t\t\treferences: [...references],\n\t\t\t\t};\n\t\t\t} catch (cause) {\n\t\t\t\tif (cause instanceof JournalAdoptError) throw cause;\n\t\t\t\tthrow new JournalAdoptError({\n\t\t\t\t\tcode: \"not-a-journal\",\n\t\t\t\t\tpath: file,\n\t\t\t\t\treason: \"not-sqlite\",\n\t\t\t\t\tcause: cause as StorageFailureCause,\n\t\t\t\t});\n\t\t\t}\n\t\t},\n\t\t() => database.close(),\n\t);\n}\n\nexport interface JournalAdoptionOutcome {\n\t/** The journal file, as an absolute path. */\n\treadonly path: string;\n\treadonly status: \"adopted\" | \"already-registered\";\n\treadonly shardId: number;\n\t/** Runs the catalog indexed from it. */\n\treadonly runs: number;\n}\n\ntype DiscoveredJournal =\n\t| {\n\t\t\treadonly path: string;\n\t\t\treadonly referencedBy: string;\n\t\t\treadonly outcome: \"adopted\" | \"already-registered\";\n\t\t\treadonly reason?: undefined;\n\t }\n\t| {\n\t\t\treadonly path: string;\n\t\t\treadonly referencedBy: string;\n\t\t\treadonly outcome: \"skipped\";\n\t\t\t/** The code of the `JournalAdoptError` adopting it raised. */\n\t\t\treadonly reason: JournalAdoptErrorCode;\n\t };\n\n/** A journal found through the runs of an adopted journal, which it names: adopted, or skipped with the reason. */\nexport type JournalDiscovered = DiscoveredJournal & { readonly checkedAt: number };\n\nexport interface JournalAdoptionReport {\n\treadonly adopted: readonly JournalAdoptionOutcome[];\n\t/** Journals found through the runs of adopted journals, adopted or skipped with the reason. */\n\treadonly discovered: readonly JournalDiscovered[];\n}\n\nexport interface JournalAdoptionOptions {\n\t/** Follow the journal files the adopted runs reference, adopting each that can be. Default `true`. */\n\treadonly discover?: boolean;\n}\n\nasync function withCatalog<T>(store: string | JournalCatalog, body: (catalog: JournalCatalog) => Promise<T>) {\n\tif (typeof store !== \"string\") return body(store);\n\tconst catalog = await JournalCatalog.open(store);\n\treturn withCleanup(\n\t\t() => body(catalog),\n\t\t() => catalog.close(),\n\t);\n}\n\nfunction adoptionOutcome(\n\tinspection: JournalFileInspection,\n\t{ shard, status }: JournalShardRegistration,\n): JournalAdoptionOutcome {\n\treturn { path: inspection.path, status, shardId: shard.id, runs: status === \"adopted\" ? inspection.runs.length : 0 };\n}\n\nasync function register(catalog: JournalCatalog, inspection: JournalFileInspection): Promise<JournalAdoptionOutcome> {\n\treturn adoptionOutcome(inspection, await catalog.registerAdopted(inspection.path, inspection.runs));\n}\n\n/** Follows run references breadth first from `start`, adopting what can be and recording what cannot. */\nasync function discover(\n\tcatalog: JournalCatalog,\n\tstart: readonly JournalFileInspection[],\n): Promise<JournalDiscovered[]> {\n\tconst records: JournalDiscovered[] = [];\n\tconst registered = new Set((await catalog.shards()).map((shard) => resolve(shard.path)));\n\tconst visited = new Set<string>();\n\tconst queue = start.flatMap((inspection) =>\n\t\tinspection.references.map((reference) => ({ reference, from: inspection.path })),\n\t);\n\twhile (queue.length > 0 && visited.size < JOURNAL_DISCOVERY_LIMIT) {\n\t\tconst { reference, from } = queue.shift()!;\n\t\tif (visited.has(reference) || registered.has(reference)) continue;\n\t\tvisited.add(reference);\n\t\tlet record: DiscoveredJournal;\n\t\ttry {\n\t\t\tconst inspection = await inspectJournalFile(reference);\n\t\t\tconst outcome = await register(catalog, inspection);\n\t\t\tregistered.add(inspection.path);\n\t\t\trecord = { path: inspection.path, outcome: outcome.status, referencedBy: from };\n\t\t\tfor (const next of inspection.references) queue.push({ reference: next, from: inspection.path });\n\t\t} catch (error) {\n\t\t\tif (!isJournalAdoptError(error)) throw error;\n\t\t\trecord = { path: reference, outcome: \"skipped\", reason: error.code, referencedBy: from };\n\t\t}\n\t\tawait catalog.recordDiscovery(record);\n\t\trecords.push({ ...record, checkedAt: Date.now() });\n\t}\n\treturn records;\n}\n\n/**\n * Registers existing journal files in the journal store in place: nothing is copied, each file becomes a shard that\n * keeps the runs it has and takes no new roots, and every run in it resolves through the catalog. Every path is\n * checked first, and all of them are then registered in one catalog transaction: a conflict registers none. Unless\n * `discover: false`, the journals the adopted runs reference are adopted too, and those that cannot be are recorded\n * with the reason.\n */\nexport async function adoptJournals(\n\tstore: string | JournalCatalog,\n\tpaths: readonly string[],\n\toptions: JournalAdoptionOptions = {},\n): Promise<JournalAdoptionReport> {\n\treturn withCatalog(store, async (catalog) => {\n\t\tconst inspections: JournalFileInspection[] = [];\n\t\tconst owners = new Map<string, string>();\n\t\tfor (const path of paths) {\n\t\t\tconst inspection = await inspectJournalFile(path);\n\t\t\tif (inspections.some((earlier) => isSameFile(earlier.path, inspection.path))) continue;\n\t\t\tfor (const run of inspection.runs) {\n\t\t\t\tconst other = owners.get(run.runId);\n\t\t\t\tif (other !== undefined)\n\t\t\t\t\tthrow new JournalAdoptError({\n\t\t\t\t\t\tcode: \"run-conflict\",\n\t\t\t\t\t\tpath: inspection.path,\n\t\t\t\t\t\trunId: run.runId,\n\t\t\t\t\t\texistingPath: other,\n\t\t\t\t\t});\n\t\t\t\towners.set(run.runId, inspection.path);\n\t\t\t}\n\t\t\tinspections.push(inspection);\n\t\t}\n\t\tconst registrations = await catalog.registerAdoptedAll(inspections);\n\t\tconst adopted = inspections.map((inspection, index) => adoptionOutcome(inspection, registrations[index]!));\n\t\tfor (const outcome of adopted) await catalog.recordDiscovery({ path: outcome.path, outcome: outcome.status });\n\t\tconst discovered = options.discover === false ? [] : await discover(catalog, inspections);\n\t\treturn { adopted, discovered };\n\t});\n}\n\n/**\n * Adopts the legacy default journal beside the store when it holds workflow runs and is not registered yet, then the\n * journals its runs reference. A legacy file that is not a journal (a sessions-only database) is recorded once.\n */\nexport async function discoverLegacyJournal(\n\tcatalog: JournalCatalog,\n\tlegacyPath: string,\n): Promise<JournalAdoptionReport> {\n\tconst path = resolve(legacyPath);\n\tif (!existsSync(path)) return { adopted: [], discovered: [] };\n\tif ((await catalog.shards()).some((shard) => resolve(shard.path) === path)) return { adopted: [], discovered: [] };\n\tlet inspection: JournalFileInspection;\n\ttry {\n\t\tinspection = await inspectJournalFile(path);\n\t} catch (error) {\n\t\tif (!isJournalAdoptError(error)) throw error;\n\t\tconst known = (await catalog.discoveries()).find((record) => record.path === path);\n\t\tif (known?.outcome !== \"skipped\" || known.reason !== error.code)\n\t\t\tawait catalog.recordDiscovery({ path, outcome: \"skipped\", reason: error.code });\n\t\treturn { adopted: [], discovered: [] };\n\t}\n\tconst outcome = await register(catalog, inspection);\n\tawait catalog.recordDiscovery({ path, outcome: outcome.status });\n\treturn { adopted: [outcome], discovered: await discover(catalog, [inspection]) };\n}\n\nexport type JournalConsolidationSkip =\n\t| \"unfinished\"\n\t| \"leased\"\n\t| \"pooled\"\n\t| \"legacy-format\"\n\t| \"conflict\"\n\t| \"changed\"\n\t| \"shard-unavailable\";\n\n/** One run a consolidation considered: moved from shard `from` to shard `to`, or left where it is with the reason. */\nexport type JournalConsolidationRun =\n\t| {\n\t\t\treadonly runId: string;\n\t\t\treadonly from: number;\n\t\t\treadonly to: number;\n\t\t\treadonly outcome: \"moved\";\n\t\t\treadonly reason?: undefined;\n\t\t\treadonly error?: undefined;\n\t }\n\t| {\n\t\t\treadonly runId: string;\n\t\t\treadonly from: number;\n\t\t\treadonly to?: number;\n\t\t\treadonly outcome: \"skipped\";\n\t\t\treadonly reason: JournalConsolidationSkip;\n\t\t\t/** The typed error behind `conflict` or `shard-unavailable`. */\n\t\t\treadonly error?: JournalCatalogError | JournalShardUnavailableError;\n\t };\n\nexport interface JournalConsolidationReport {\n\treadonly moved: number;\n\treadonly skipped: number;\n\treadonly runs: readonly JournalConsolidationRun[];\n}\n\ntype RunRow = SqliteRow & {\n\trun_id: string;\n\tname: string;\n\tcwd: string;\n\tcreated_at: number;\n\tstatus: string;\n\theader_json: string;\n};\ntype EventRow = SqliteRow & {\n\trun_id: string;\n\tseq: number;\n\tepoch: number;\n\tkey: string | null;\n\ttype: string;\n\tpayload: string;\n\tat: number;\n};\ntype LeaseRow = SqliteRow & { run_id: string; holder_id: string | null; epoch: number; renewed_at: number };\n\ninterface FencedRun {\n\treadonly run: RunRow;\n\treadonly events: readonly EventRow[];\n\treadonly lease: LeaseRow;\n}\n\nconst CONSOLIDATION_TRANSACTION = { lockWaitMs: 10 * 60_000 } as const;\n\nasync function openShardFile(record: JournalShardRecord, runId?: string): Promise<SqliteDatabase> {\n\tif (!existsSync(record.path))\n\t\tthrow new JournalShardUnavailableError({\n\t\t\tcode: \"shard-missing\",\n\t\t\tshardId: record.id,\n\t\t\tshardPath: record.path,\n\t\t\trunId,\n\t\t});\n\ttry {\n\t\treturn await openNodeSqliteDatabase(record.path);\n\t} catch (cause) {\n\t\tthrow new JournalShardUnavailableError({\n\t\t\tcode: \"shard-open-failed\",\n\t\t\tshardId: record.id,\n\t\t\tshardPath: record.path,\n\t\t\trunId,\n\t\t\tcause: cause as StorageFailureCause,\n\t\t});\n\t}\n}\n\n/** Whether a journal file has the current journal tables, which a file of only the pre-0.9.38 format does not. */\nasync function hasJournalTables(database: SqliteExecutor): Promise<boolean> {\n\tconst names = await tableNames(database);\n\treturn [TABLES.runs, TABLES.events, TABLES.leases].every((table) => names.has(table));\n}\n\nasync function ensureJournalTables(source: SqliteExecutor, target: SqliteExecutor): Promise<void> {\n\tconst definitions = await source.all<SqliteRow & { name: string; sql: string }>(\n\t\t`SELECT name, sql FROM sqlite_master WHERE type = 'table' AND name IN (?, ?, ?, ?)`,\n\t\tTABLES.meta,\n\t\tTABLES.runs,\n\t\tTABLES.events,\n\t\tTABLES.leases,\n\t);\n\tfor (const definition of definitions)\n\t\tawait target.exec(definition.sql.replace(\"CREATE TABLE \", \"CREATE TABLE IF NOT EXISTS \"));\n\tconst meta = await target.all(`SELECT schema_version FROM ${TABLES.meta}`);\n\tif (meta.length === 0) await target.run(`INSERT INTO ${TABLES.meta} VALUES (?)`, RUN_JOURNAL_SCHEMA_VERSION);\n}\n\n/**\n * Fences a finished run in its source journal: takes its lease for this consolidation, as a resume would, so no other\n * process can append to it while it moves. Undefined with the reason when it must stay where it is.\n */\nasync function fence(\n\tsource: SqliteDatabase,\n\trunId: string,\n\tholder: string,\n): Promise<FencedRun | JournalConsolidationSkip> {\n\treturn source.transaction(async (tx) => {\n\t\tconst run = await tx.get<RunRow>(`SELECT * FROM ${TABLES.runs} WHERE run_id = ?`, runId);\n\t\tconst names = await tableNames(tx);\n\t\tif (run === undefined) return \"legacy-format\";\n\t\tif (names.has(LEGACY_RUNS) && (await tx.get(`SELECT run_id FROM ${LEGACY_RUNS} WHERE run_id = ?`, runId)))\n\t\t\treturn \"legacy-format\";\n\t\tif (!isFinishedJournalStatus(run.status)) return \"unfinished\";\n\t\tif (names.has(POOL_ROOTS) && (await tx.get(`SELECT root FROM ${POOL_ROOTS} WHERE root = ?`, runId)))\n\t\t\treturn \"pooled\";\n\t\tconst lease = await tx.get<LeaseRow>(`SELECT * FROM ${TABLES.leases} WHERE run_id = ?`, runId);\n\t\tconst heldByOther =\n\t\t\tlease?.holder_id !== undefined &&\n\t\t\tlease.holder_id !== null &&\n\t\t\t!lease.holder_id.startsWith(JOURNAL_CONSOLIDATION_HOLDER_PREFIX);\n\t\tif (heldByOther) return \"leased\";\n\t\tconst epoch = Number(lease?.epoch ?? 0) + 1;\n\t\tawait tx.run(\n\t\t\t`INSERT INTO ${TABLES.leases} VALUES (?, ?, ?, ${STORE_NOW}) ON CONFLICT(run_id) DO UPDATE SET holder_id = excluded.holder_id, epoch = excluded.epoch, renewed_at = excluded.renewed_at`,\n\t\t\trunId,\n\t\t\tholder,\n\t\t\tepoch,\n\t\t);\n\t\tconst events = await tx.all<EventRow>(`SELECT * FROM ${TABLES.events} WHERE run_id = ? ORDER BY seq`, runId);\n\t\tconst fenced = await tx.get<LeaseRow>(`SELECT * FROM ${TABLES.leases} WHERE run_id = ?`, runId);\n\t\treturn { run, events, lease: fenced! };\n\t}, CONSOLIDATION_TRANSACTION);\n}\n\n/**\n * Lifts the fence of any consolidation, this one or a crashed one, from a run's lease in the journal that now holds it. A\n * lease a resume holds is never touched.\n */\n/** Whether a process that is not a consolidation holds the lease of a run in a journal: a resume took it over. */\nasync function heldByResume(database: SqliteDatabase, runId: string): Promise<boolean> {\n\tconst lease = await database.get<LeaseRow>(`SELECT * FROM ${TABLES.leases} WHERE run_id = ?`, runId);\n\treturn lease?.holder_id != null && !lease.holder_id.startsWith(JOURNAL_CONSOLIDATION_HOLDER_PREFIX);\n}\n\n/** Whether a consolidation, this one or another, fences the lease of a run in a journal. */\nasync function fencedByConsolidation(database: SqliteDatabase, runId: string): Promise<boolean> {\n\tconst lease = await database.get<LeaseRow>(`SELECT * FROM ${TABLES.leases} WHERE run_id = ?`, runId);\n\treturn lease?.holder_id?.startsWith(JOURNAL_CONSOLIDATION_HOLDER_PREFIX) === true;\n}\n\n/**\n * How long a consolidation's fence goes unrenewed before another consolidation takes it over: the window after which a\n * resume takes over a consolidation's fence too. Consolidations never renew their fences, so a fence this old belongs to\n * a consolidation that stopped, or to one so slow that a resume could take its run from it anyway.\n */\nconst STALE_CONSOLIDATION_FENCE_MS = 120_000;\n\n/** Whether a run's lease in a journal is a consolidation's fence left unrenewed for longer than the stale window. */\nasync function staleFence(executor: SqliteExecutor, runId: string): Promise<boolean> {\n\tconst stale = await executor.get(\n\t\t`SELECT run_id FROM ${TABLES.leases} WHERE run_id = ? AND holder_id LIKE ? AND renewed_at < ${STORE_NOW} - ?`,\n\t\trunId,\n\t\t`${JOURNAL_CONSOLIDATION_HOLDER_PREFIX}%`,\n\t\tSTALE_CONSOLIDATION_FENCE_MS,\n\t);\n\treturn stale !== undefined;\n}\n\n/**\n * Whether `holder`, a consolidation, holds the lease of a run in a journal, taking it over first from another\n * consolidation whose fence is stale, as lease takeover does: in one transaction, at the next epoch. A lease a resume\n * holds, a lease nobody holds and a fresh fence are never taken.\n */\nasync function takeOverFence(database: SqliteDatabase, runId: string, holder: string): Promise<boolean> {\n\treturn database.transaction(async (tx) => {\n\t\tconst lease = await tx.get<LeaseRow>(`SELECT * FROM ${TABLES.leases} WHERE run_id = ?`, runId);\n\t\tif (lease?.holder_id === holder) return true;\n\t\tif (!(await staleFence(tx, runId))) return false;\n\t\tawait tx.run(\n\t\t\t`UPDATE ${TABLES.leases} SET holder_id = ?, epoch = epoch + 1, renewed_at = ${STORE_NOW} WHERE run_id = ?`,\n\t\t\tholder,\n\t\t\trunId,\n\t\t);\n\t\treturn true;\n\t}, CONSOLIDATION_TRANSACTION);\n}\n\nasync function liftFence(database: SqliteDatabase, runId: string): Promise<void> {\n\tawait database.transaction(\n\t\t(tx) =>\n\t\t\ttx.run(\n\t\t\t\t`UPDATE ${TABLES.leases} SET holder_id = NULL WHERE run_id = ? AND holder_id LIKE ?`,\n\t\t\t\trunId,\n\t\t\t\t`${JOURNAL_CONSOLIDATION_HOLDER_PREFIX}%`,\n\t\t\t),\n\t\tCONSOLIDATION_TRANSACTION,\n\t);\n}\n\nasync function unfence(database: SqliteDatabase, runId: string, holder: string): Promise<void> {\n\tawait database.transaction(\n\t\t(tx) => tx.run(`UPDATE ${TABLES.leases} SET holder_id = NULL WHERE run_id = ? AND holder_id = ?`, runId, holder),\n\t\tCONSOLIDATION_TRANSACTION,\n\t);\n}\n\ninterface RunSnapshot {\n\treadonly run: RunRow;\n\treadonly events: readonly EventRow[];\n}\n\nfunction sameEvent(left: EventRow, right: EventRow): boolean {\n\treturn (\n\t\tleft.seq === right.seq &&\n\t\tleft.epoch === right.epoch &&\n\t\tleft.key === right.key &&\n\t\tleft.type === right.type &&\n\t\tleft.payload === right.payload &&\n\t\tleft.at === right.at\n\t);\n}\n\n/** Whether `copy` holds everything `source` holds: the same header and the same first events, and maybe more. */\nfunction holdsSnapshot(source: RunSnapshot, copy: RunSnapshot): boolean {\n\treturn (\n\t\tsource.run.header_json === copy.run.header_json &&\n\t\tcopy.events.length >= source.events.length &&\n\t\tsource.events.every((event, index) => sameEvent(event, copy.events[index]!))\n\t);\n}\n\nasync function readRun(database: SqliteExecutor, runId: string): Promise<RunSnapshot | undefined> {\n\tif (!(await hasJournalTables(database))) return undefined;\n\tconst run = await database.get<RunRow>(`SELECT * FROM ${TABLES.runs} WHERE run_id = ?`, runId);\n\tif (run === undefined) return undefined;\n\treturn {\n\t\trun,\n\t\tevents: await database.all<EventRow>(`SELECT * FROM ${TABLES.events} WHERE run_id = ? ORDER BY seq`, runId),\n\t};\n}\n\n/**\n * Copies a fenced run into the target journal in one transaction and says whether the target now holds it. A run the\n * target already holds is left alone, and its lease with it: it counts when that copy holds everything the source does,\n * and not when it differs. A copy holding only the first part of the source's history under another consolidation's\n * stale fence was left by a consolidation that stopped, and is replaced. Only a copy this call inserts gets a lease,\n * fenced by `holder` at an epoch above any lease row the target kept for the run.\n */\nasync function copy(\n\tsource: SqliteDatabase,\n\ttarget: SqliteDatabase,\n\tsnapshot: RunSnapshot,\n\tholder: string,\n\tsourceEpoch: number,\n): Promise<boolean> {\n\treturn target.transaction(async (tx) => {\n\t\tawait ensureJournalTables(source, tx);\n\t\tconst { run } = snapshot;\n\t\tconst existing = await readRun(tx, run.run_id);\n\t\tif (existing !== undefined) {\n\t\t\tif (holdsSnapshot(snapshot, existing)) return true;\n\t\t\tif (!holdsSnapshot(existing, snapshot) || !(await staleFence(tx, run.run_id))) return false;\n\t\t\tawait tx.run(`DELETE FROM ${TABLES.events} WHERE run_id = ?`, run.run_id);\n\t\t\tawait tx.run(`DELETE FROM ${TABLES.runs} WHERE run_id = ?`, run.run_id);\n\t\t}\n\t\tawait tx.run(\n\t\t\t`INSERT INTO ${TABLES.runs}(run_id, name, cwd, created_at, status, header_json) VALUES (?, ?, ?, ?, ?, ?)`,\n\t\t\trun.run_id,\n\t\t\trun.name,\n\t\t\trun.cwd,\n\t\t\trun.created_at,\n\t\t\trun.status,\n\t\t\trun.header_json,\n\t\t);\n\t\tfor (const event of snapshot.events)\n\t\t\tawait tx.run(\n\t\t\t\t`INSERT INTO ${TABLES.events}(run_id, seq, epoch, key, type, payload, at) VALUES (?, ?, ?, ?, ?, ?, ?)`,\n\t\t\t\tevent.run_id,\n\t\t\t\tevent.seq,\n\t\t\t\tevent.epoch,\n\t\t\t\tevent.key,\n\t\t\t\tevent.type,\n\t\t\t\tevent.payload,\n\t\t\t\tevent.at,\n\t\t\t);\n\t\tconst kept = await tx.get<LeaseRow>(`SELECT * FROM ${TABLES.leases} WHERE run_id = ?`, run.run_id);\n\t\tawait tx.run(\n\t\t\t`INSERT INTO ${TABLES.leases} VALUES (?, ?, ?, ${STORE_NOW}) ON CONFLICT(run_id) DO UPDATE SET holder_id = excluded.holder_id, epoch = excluded.epoch, renewed_at = excluded.renewed_at`,\n\t\t\trun.run_id,\n\t\t\tholder,\n\t\t\tMath.max(sourceEpoch, Number(kept?.epoch ?? 0) + 1),\n\t\t);\n\t\treturn true;\n\t}, CONSOLIDATION_TRANSACTION);\n}\n\n/** Deletes a journal's copy of a run, only while `holder` still holds its lease: a compare-and-set on the fence. */\nasync function removeRun(database: SqliteDatabase, runId: string, holder: string): Promise<boolean> {\n\treturn database.transaction(async (tx) => {\n\t\tconst lease = await tx.get<LeaseRow>(`SELECT * FROM ${TABLES.leases} WHERE run_id = ?`, runId);\n\t\tif (lease?.holder_id !== holder) return false;\n\t\tawait tx.run(`DELETE FROM ${TABLES.events} WHERE run_id = ?`, runId);\n\t\tawait tx.run(`DELETE FROM ${TABLES.runs} WHERE run_id = ?`, runId);\n\t\tawait tx.run(`DELETE FROM ${TABLES.leases} WHERE run_id = ?`, runId);\n\t\treturn true;\n\t}, CONSOLIDATION_TRANSACTION);\n}\n\n/**\n * The skip for a run whose destination shard is the very file it is in, under another shard entry: copying into it and\n * deleting the source would delete the only copy. Undefined when the two shards are different files.\n */\nfunction sameFileSkip(\n\tcatalog: JournalCatalog,\n\tfrom: JournalShardRecord,\n\tdestination: JournalShardRecord,\n\trunId: string,\n): JournalConsolidationRun | undefined {\n\tif (!isSameFile(from.path, destination.path)) return undefined;\n\treturn {\n\t\trunId,\n\t\tfrom: from.id,\n\t\tto: destination.id,\n\t\toutcome: \"skipped\",\n\t\treason: \"conflict\",\n\t\terror: new JournalCatalogError({\n\t\t\tcode: \"corrupt\",\n\t\t\tcatalogPath: catalog.path,\n\t\t\trunId,\n\t\t\tshardId: destination.id,\n\t\t\tshardPath: destination.path,\n\t\t\trule: `shards ${from.id} and ${destination.id} are the same file ${from.path}`,\n\t\t}),\n\t};\n}\n\nfunction conflictRun(catalog: JournalCatalog, from: number, destination: JournalShardRecord, runId: string) {\n\treturn {\n\t\trunId,\n\t\tfrom,\n\t\tto: destination.id,\n\t\toutcome: \"skipped\",\n\t\treason: \"conflict\",\n\t\terror: new JournalCatalogError({\n\t\t\tcode: \"run-conflict\",\n\t\t\tcatalogPath: catalog.path,\n\t\t\trunId,\n\t\t\tshardId: destination.id,\n\t\t\tshardPath: destination.path,\n\t\t}),\n\t} as const;\n}\n\n/**\n * Moves a run's catalog entry from `destination` back to `from`, whose copy holds more of the run, then settles the\n * destination's copy in one transaction on it. A copy holding events the source lacks, or that a resume holds, is where\n * the run belongs, and the catalog goes back there. Otherwise the catalog stays on the source, which holds every event:\n * the copy is deleted while `holder` fences it or nobody holds it, unless another consolidation fences it or the source\n * and may still select it. Whether the catalog stays on the source.\n */\nasync function returnToSource(\n\tcatalog: JournalCatalog,\n\tfrom: JournalShardRecord,\n\tdestination: JournalShardRecord,\n\tsource: SqliteDatabase,\n\tdatabase: SqliteDatabase,\n\trunId: string,\n\tholder: string,\n): Promise<boolean> {\n\tawait catalog.moveRun(runId, destination.id, from.id);\n\tconst stays = await database.transaction(async (tx) => {\n\t\tconst there = await readRun(tx, runId);\n\t\tif (there === undefined) return true;\n\t\tconst left = await readRun(source, runId);\n\t\tif (left === undefined || !holdsSnapshot(there, left)) return false;\n\t\tconst lease = await tx.get<LeaseRow>(`SELECT * FROM ${TABLES.leases} WHERE run_id = ?`, runId);\n\t\tif (lease?.holder_id != null && lease.holder_id !== holder)\n\t\t\treturn lease.holder_id.startsWith(JOURNAL_CONSOLIDATION_HOLDER_PREFIX);\n\t\tconst kept = await source.get<SqliteRow & { holder_id: string | null }>(\n\t\t\t`SELECT leases.holder_id FROM ${TABLES.runs} AS runs LEFT JOIN ${TABLES.leases} AS leases ON leases.run_id = runs.run_id WHERE runs.run_id = ?`,\n\t\t\trunId,\n\t\t);\n\t\tif (kept === undefined) return false;\n\t\tif (kept.holder_id?.startsWith(JOURNAL_CONSOLIDATION_HOLDER_PREFIX) && kept.holder_id !== holder) return true;\n\t\tawait tx.run(`DELETE FROM ${TABLES.events} WHERE run_id = ?`, runId);\n\t\tawait tx.run(`DELETE FROM ${TABLES.runs} WHERE run_id = ?`, runId);\n\t\tawait tx.run(`DELETE FROM ${TABLES.leases} WHERE run_id = ?`, runId);\n\t\treturn true;\n\t}, CONSOLIDATION_TRANSACTION);\n\tif (stays) return true;\n\tawait catalog.moveRun(runId, from.id, destination.id);\n\treturn false;\n}\n\n/**\n * Finishes a move whose catalog entry already names `destination`: checks that the destination holds everything the\n * fenced source does (copying the run again if it lost it), deletes the source only while `holder` still fences it, and\n * lifts the fence on the destination. A fence another process took over leaves the source alone; if that process added\n * events the destination lacks, the catalog goes back to the source and the destination copy is removed under\n * `holder`'s fence, taken over first from a consolidation whose fence went stale. Every step compares holders, so\n * overlapping consolidations and a resume that took over an expired fence lose nothing, and a resume's lease on the\n * destination is never overwritten.\n */\nasync function settleMove(\n\tcatalog: JournalCatalog,\n\tsource: SqliteDatabase,\n\tfrom: JournalShardRecord,\n\tdestination: JournalShardRecord,\n\tdatabase: SqliteDatabase,\n\trunId: string,\n\tholder: string,\n\tsourceEpoch: number,\n): Promise<JournalConsolidationRun> {\n\tconst moved = { runId, from: from.id, to: destination.id, outcome: \"moved\" } as const;\n\t// A resume that took the destination's fence may already have written there, so the run stays where it is written\n\t// and is reported leased, or as a conflict when the source gained events the destination lacks.\n\tconst keptOnDestination = async (): Promise<JournalConsolidationRun> => {\n\t\tconst left = await readRun(source, runId);\n\t\tconst there = await readRun(database, runId);\n\t\tif (left !== undefined && there !== undefined && !holdsSnapshot(left, there))\n\t\t\treturn conflictRun(catalog, from.id, destination, runId);\n\t\treturn { runId, from: from.id, to: destination.id, outcome: \"skipped\", reason: \"leased\" };\n\t};\n\tconst undo = async (): Promise<JournalConsolidationRun> => {\n\t\t// The catalog never moves off a destination that someone else leases or that holds events the source lacks.\n\t\tconst left = await readRun(source, runId);\n\t\tconst there = await readRun(database, runId);\n\t\tconst ahead = left !== undefined && there !== undefined && there.events.length > left.events.length;\n\t\tif (ahead || !(await takeOverFence(database, runId, holder))) return keptOnDestination();\n\t\tif (await returnToSource(catalog, from, destination, source, database, runId, holder))\n\t\t\treturn { runId, from: from.id, outcome: \"skipped\", reason: \"leased\" };\n\t\treturn keptOnDestination();\n\t};\n\tconst snapshot = await readRun(source, runId);\n\tif (snapshot === undefined) {\n\t\tawait liftFence(database, runId);\n\t\treturn moved;\n\t}\n\tlet held = await readRun(database, runId);\n\tif (held === undefined) {\n\t\tif (!(await copy(source, database, snapshot, holder, sourceEpoch)))\n\t\t\treturn conflictRun(catalog, from.id, destination, runId);\n\t\theld = (await readRun(database, runId))!;\n\t}\n\tif (!holdsSnapshot(snapshot, held))\n\t\treturn holdsSnapshot(held, snapshot) ? undo() : conflictRun(catalog, from.id, destination, runId);\n\tawait removeRun(source, runId, holder);\n\tconst left = await readRun(source, runId);\n\tif (left !== undefined) {\n\t\tconst now = await readRun(database, runId);\n\t\tconst leased = await source.get<LeaseRow>(`SELECT * FROM ${TABLES.leases} WHERE run_id = ?`, runId);\n\t\tconst resumed = leased?.holder_id != null && !leased.holder_id.startsWith(JOURNAL_CONSOLIDATION_HOLDER_PREFIX);\n\t\t// A resume that took the source lease, with or without events yet, belongs on the file the catalog names.\n\t\tif (resumed || now === undefined || !holdsSnapshot(left, now)) return undo();\n\t}\n\tawait liftFence(database, runId);\n\treturn moved;\n}\n\n/**\n * Moves finished runs out of adopted journals into the store's own shards. A run moves only when it finished\n * (completed, failed or cancelled), no process holds its lease, it never ran local workers (their pool state stays in\n * its journal) and it is not in the pre-0.9.38 table format; every other run stays where it is, with the reason. Each\n * run moves on its own: it is fenced in its journal, copied into a shard in one transaction, repointed in the\n * catalog, and only then deleted from its journal. A consolidation that is interrupted leaves every run readable in\n * exactly one place through the catalog, and running it again finishes the move, or returns the run to its journal\n * when the move was being abandoned or undone.\n */\nexport async function consolidateJournalStore(store: string | JournalCatalog): Promise<JournalConsolidationReport> {\n\treturn withCatalog(store, async (catalog) => {\n\t\tconst holder = `${JOURNAL_CONSOLIDATION_HOLDER_PREFIX}${randomUUID()}`;\n\t\tconst results: JournalConsolidationRun[] = [];\n\t\tconst shards = await catalog.shards();\n\t\tconst targets = new Map<number, SqliteDatabase>();\n\t\tconst target = async (record: JournalShardRecord): Promise<SqliteDatabase> => {\n\t\t\tlet database = targets.get(record.id);\n\t\t\tif (database === undefined) {\n\t\t\t\tdatabase = await openShardFile(record);\n\t\t\t\ttargets.set(record.id, database);\n\t\t\t}\n\t\t\treturn database;\n\t\t};\n\t\tawait withCleanup(\n\t\t\tasync () => {\n\t\t\t\tfor (const shard of shards.filter((candidate) => candidate.kind === \"adopted\")) {\n\t\t\t\t\tlet source: SqliteDatabase;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tsource = await openShardFile(shard);\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tif (!(error instanceof JournalShardUnavailableError)) throw error;\n\t\t\t\t\t\tfor (const run of await catalog.runs({ shard: shard.id }))\n\t\t\t\t\t\t\tresults.push({\n\t\t\t\t\t\t\t\trunId: run.runId,\n\t\t\t\t\t\t\t\tfrom: shard.id,\n\t\t\t\t\t\t\t\toutcome: \"skipped\",\n\t\t\t\t\t\t\t\treason: \"shard-unavailable\",\n\t\t\t\t\t\t\t\terror,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tawait withCleanup(\n\t\t\t\t\t\tasync () => {\n\t\t\t\t\t\t\tconst legacyOnly = !(await hasJournalTables(source));\n\t\t\t\t\t\t\tif (!legacyOnly) {\n\t\t\t\t\t\t\t\tresults.push(...(await finishInterruptedMoves(catalog, source, shard, target)));\n\t\t\t\t\t\t\t\tresults.push(...(await returnStrandedRuns(catalog, source, shard, holder, target)));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tfor (const run of await catalog.runs({ shard: shard.id }))\n\t\t\t\t\t\t\t\tresults.push(\n\t\t\t\t\t\t\t\t\tlegacyOnly\n\t\t\t\t\t\t\t\t\t\t? { runId: run.runId, from: shard.id, outcome: \"skipped\", reason: \"legacy-format\" }\n\t\t\t\t\t\t\t\t\t\t: await moveOne(catalog, source, shard, run.runId, holder, target),\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t},\n\t\t\t\t\t\t() => source.close(),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t},\n\t\t\t() => closeEach(targets.values()),\n\t\t);\n\t\tconst moved = results.filter((run) => run.outcome === \"moved\").length;\n\t\treturn { moved, skipped: results.length - moved, runs: results };\n\t});\n}\n\n/**\n * Returns to this journal the runs a crashed consolidation stranded on another shard: a run this journal holds, with no\n * consolidation fencing it here, whose catalog entry names a shard that lost the run, or that holds only the first part\n * of its history under a consolidation's stale fence. That consolidation was abandoning or undoing the move, so\n * `finishInterruptedMoves` has nothing to finish; the moves that follow find the run here again. A fresh fence may\n * belong to a consolidation still undoing the move, and is left to it. A run whose shard cannot be opened is reported.\n * A run whose named copy lacks events this journal holds and cannot be returned is reported a conflict, and both copies\n * are kept: the two histories differ, as when resumes wrote to both copies during an interrupted move, or a resume\n * holds the named copy.\n */\nasync function returnStrandedRuns(\n\tcatalog: JournalCatalog,\n\tsource: SqliteDatabase,\n\tfrom: JournalShardRecord,\n\tholder: string,\n\ttarget: (record: JournalShardRecord) => Promise<SqliteDatabase>,\n): Promise<JournalConsolidationRun[]> {\n\tconst skipped: JournalConsolidationRun[] = [];\n\tconst listed = new Set((await catalog.runs({ shard: from.id })).map((run) => run.runId));\n\tconst unfenced = await source.all<SqliteRow & { run_id: string }>(\n\t\t`SELECT run_id FROM ${TABLES.runs} WHERE run_id NOT IN (SELECT run_id FROM ${TABLES.leases} WHERE holder_id LIKE ?) ORDER BY run_id`,\n\t\t`${JOURNAL_CONSOLIDATION_HOLDER_PREFIX}%`,\n\t);\n\tfor (const { run_id: runId } of unfenced.filter((row) => !listed.has(row.run_id))) {\n\t\tconst destination = (await catalog.locate(runId))?.shard;\n\t\tif (destination === undefined) continue;\n\t\tlet database: SqliteDatabase;\n\t\ttry {\n\t\t\tdatabase = await target(destination);\n\t\t} catch (error) {\n\t\t\tif (!(error instanceof JournalShardUnavailableError)) throw error;\n\t\t\tskipped.push({\n\t\t\t\trunId,\n\t\t\t\tfrom: from.id,\n\t\t\t\tto: destination.id,\n\t\t\t\toutcome: \"skipped\",\n\t\t\t\treason: \"shard-unavailable\",\n\t\t\t\terror,\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tconst left = await readRun(source, runId);\n\t\tconst there = await readRun(database, runId);\n\t\tif (left === undefined) continue;\n\t\tif (there === undefined) {\n\t\t\tawait source.transaction(async (tx) => {\n\t\t\t\tconst lease = await tx.get<LeaseRow>(`SELECT * FROM ${TABLES.leases} WHERE run_id = ?`, runId);\n\t\t\t\tif (lease?.holder_id?.startsWith(JOURNAL_CONSOLIDATION_HOLDER_PREFIX)) return;\n\t\t\t\tif ((await readRun(tx, runId)) !== undefined && (await readRun(database, runId)) === undefined)\n\t\t\t\t\tawait catalog.moveRun(runId, destination.id, from.id);\n\t\t\t}, CONSOLIDATION_TRANSACTION);\n\t\t\tcontinue;\n\t\t}\n\t\tif (holdsSnapshot(left, there)) continue;\n\t\tif (holdsSnapshot(there, left)) {\n\t\t\tif (await takeOverFence(database, runId, holder)) {\n\t\t\t\tif (await returnToSource(catalog, from, destination, source, database, runId, holder)) continue;\n\t\t\t} else if (await fencedByConsolidation(database, runId)) continue;\n\t\t}\n\t\tconst kept = await readRun(source, runId);\n\t\tconst named = await readRun(database, runId);\n\t\tif (kept !== undefined && named !== undefined && !holdsSnapshot(kept, named))\n\t\t\tskipped.push(conflictRun(catalog, from.id, destination, runId));\n\t}\n\treturn skipped;\n}\n\n/**\n * Finishes the moves a consolidation was interrupted in after it had repointed the catalog: the run's source copy,\n * still fenced by it, is deleted once its new shard is checked to hold it, and the fence it left there is lifted. A run\n * whose new shard cannot be opened keeps its source copy and is reported skipped.\n */\nasync function finishInterruptedMoves(\n\tcatalog: JournalCatalog,\n\tsource: SqliteDatabase,\n\tfrom: JournalShardRecord,\n\ttarget: (record: JournalShardRecord) => Promise<SqliteDatabase>,\n): Promise<JournalConsolidationRun[]> {\n\tconst skipped: JournalConsolidationRun[] = [];\n\tconst fenced = await source.all<LeaseRow>(\n\t\t`SELECT * FROM ${TABLES.leases} WHERE holder_id LIKE ?`,\n\t\t`${JOURNAL_CONSOLIDATION_HOLDER_PREFIX}%`,\n\t);\n\tfor (const lease of fenced) {\n\t\t// Where the catalog names the run now, not where it did when this consolidation began: another consolidation may\n\t\t// have repointed it since, and a fence it left on this file is then not an interrupted move to finish.\n\t\tconst destination = (await catalog.locate(lease.run_id))?.shard;\n\t\tif (destination === undefined || destination.id === from.id) continue;\n\t\tconst same = sameFileSkip(catalog, from, destination, lease.run_id);\n\t\tif (same !== undefined) {\n\t\t\tskipped.push(same);\n\t\t\tcontinue;\n\t\t}\n\t\tlet database: SqliteDatabase;\n\t\ttry {\n\t\t\tdatabase = await target(destination);\n\t\t} catch (error) {\n\t\t\tif (!(error instanceof JournalShardUnavailableError)) throw error;\n\t\t\tskipped.push({\n\t\t\t\trunId: lease.run_id,\n\t\t\t\tfrom: from.id,\n\t\t\t\tto: destination.id,\n\t\t\t\toutcome: \"skipped\",\n\t\t\t\treason: \"shard-unavailable\",\n\t\t\t\terror,\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tconst settled = await settleMove(\n\t\t\tcatalog,\n\t\t\tsource,\n\t\t\tfrom,\n\t\t\tdestination,\n\t\t\tdatabase,\n\t\t\tlease.run_id,\n\t\t\tlease.holder_id!,\n\t\t\tNumber(lease.epoch),\n\t\t);\n\t\tif (settled.outcome === \"skipped\") skipped.push(settled);\n\t}\n\treturn skipped;\n}\n\nasync function moveOne(\n\tcatalog: JournalCatalog,\n\tsource: SqliteDatabase,\n\tshard: JournalShardRecord,\n\trunId: string,\n\tholder: string,\n\ttarget: (record: JournalShardRecord) => Promise<SqliteDatabase>,\n): Promise<JournalConsolidationRun> {\n\tconst fenced = await fence(source, runId, holder);\n\tif (typeof fenced === \"string\") return { runId, from: shard.id, outcome: \"skipped\", reason: fenced };\n\tconst destination = await catalog.homeShard(runId);\n\tconst same = sameFileSkip(catalog, shard, destination, runId);\n\tif (same !== undefined) {\n\t\tawait unfence(source, runId, holder);\n\t\treturn same;\n\t}\n\tlet database: SqliteDatabase;\n\ttry {\n\t\tdatabase = await target(destination);\n\t} catch (error) {\n\t\tawait unfence(source, runId, holder);\n\t\tif (!(error instanceof JournalShardUnavailableError)) throw error;\n\t\treturn { runId, from: shard.id, outcome: \"skipped\", reason: \"shard-unavailable\", error };\n\t}\n\tif (!(await copy(source, database, fenced, holder, fenced.lease.epoch))) {\n\t\tawait unfence(source, runId, holder);\n\t\treturn conflictRun(catalog, shard.id, destination, runId);\n\t}\n\t// A move that waited so long that a resume took the source's fence is abandoned before the catalog changes.\n\tif (await heldByResume(source, runId)) {\n\t\tconst selected = async () => (await catalog.locate(runId))?.shard.id === destination.id;\n\t\tif (!(await selected()) && (!(await removeRun(database, runId, holder)) || !(await selected())))\n\t\t\treturn { runId, from: shard.id, outcome: \"skipped\", reason: \"leased\" };\n\t\tconst settled = await settleMove(\n\t\t\tcatalog,\n\t\t\tsource,\n\t\t\tshard,\n\t\t\tdestination,\n\t\t\tdatabase,\n\t\t\trunId,\n\t\t\tholder,\n\t\t\tfenced.lease.epoch,\n\t\t);\n\t\treturn settled.outcome === \"moved\" ? { runId, from: shard.id, outcome: \"skipped\", reason: \"changed\" } : settled;\n\t}\n\tconst repointed = await catalog.moveRun(runId, shard.id, destination.id);\n\tif (!repointed && (await catalog.locate(runId))?.shard.id !== destination.id) {\n\t\tawait removeRun(database, runId, holder);\n\t\tawait unfence(source, runId, holder);\n\t\treturn { runId, from: shard.id, outcome: \"skipped\", reason: \"changed\" };\n\t}\n\tconst settled = await settleMove(catalog, source, shard, destination, database, runId, holder, fenced.lease.epoch);\n\t// Another consolidation repointed the run first: it moved it, this one only cleaned up behind it.\n\treturn repointed ? settled : { runId, from: shard.id, outcome: \"skipped\", reason: \"changed\" };\n}\n"]}
1
+ {"version":3,"file":"journal-adoption.js","sourceRoot":"","sources":["../../../src/core/storage/journal-adoption.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AACrC,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,kBAAkB,CAAC;AAC9C,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACnD,OAAO,EAAE,SAAS,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAGtD,OAAO,EACN,mBAAmB,EACnB,iBAAiB,EAEjB,mBAAmB,EACnB,4BAA4B,EAC5B,yBAAyB,GACzB,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAChD,OAAO,EACN,uBAAuB,EACvB,cAAc,GAId,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAE,sBAAsB,EAAE,MAAM,kBAAkB,CAAC;AAC1D,OAAO,EAAE,wBAAwB,EAAE,MAAM,aAAa,CAAC;AACvD,OAAO,EAAE,0BAA0B,EAAE,MAAM,kBAAkB,CAAC;AAE9D,wGAAwG;AACxG,MAAM,UAAU,4BAA4B,CAAC,QAAgB;IAC5D,OAAO,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,EAAE,WAAW,EAAE,SAAS,CAAC,CAAC;AACxD,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,wBAAwB,CAAC,SAAiB;IACzD,OAAO,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC,EAAE,gBAAgB,CA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AI,EAAE,KAAK,CAAC,EAAE,EAAE,OAAO,EAAE,SAAS,EAAE,MAAM,EAAE,SAAS,EAAE,CAAC;AAC/F,CAAC","sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport { existsSync } from \"node:fs\";\nimport { open, stat } from \"node:fs/promises\";\nimport { dirname, join, resolve } from \"node:path\";\nimport { closeEach, withCleanup } from \"./cleanup.js\";\nimport type { SqliteDatabase, SqliteExecutor, SqliteRow, SqliteValue } from \"./database.js\";\nimport type { StorageFailureCause } from \"./errors.js\";\nimport {\n\tisJournalAdoptError,\n\tJournalAdoptError,\n\ttype JournalAdoptErrorCode,\n\tJournalCatalogError,\n\tJournalShardUnavailableError,\n\tStorageSchemaVersionError,\n} from \"./errors.js\";\nimport { isSameFile } from \"./file-identity.js\";\nimport {\n\tisFinishedJournalStatus,\n\tJournalCatalog,\n\ttype JournalCatalogRunHeader,\n\ttype JournalShardRecord,\n\ttype JournalShardRegistration,\n} from \"./journal-catalog.js\";\nimport { openNodeSqliteDatabase } from \"./node-sqlite.js\";\nimport { renderStorageIdentifiers } from \"./prefix.js\";\nimport { RUN_JOURNAL_SCHEMA_VERSION } from \"./run-journal.js\";\n\n/** The journal store's directory under an agent directory: `<agent dir's parent>/workflows/journal`. */\nexport function defaultJournalStoreDirectory(agentDir: string): string {\n\treturn join(dirname(agentDir), \"workflows\", \"journal\");\n}\n\n/**\n * The single-file journal every workflow run used by default before the journal store, beside the store's directory.\n * A store opened in `directory` adopts it in place when it holds workflow runs.\n */\nexport function legacyDefaultJournalPath(directory: string): string {\n\treturn join(dirname(resolve(directory)), \"journal.sqlite\");\n}\n\n/** The tables of a SQL run journal, before the storage prefix and the `wf_` domain prefix. */\nexport const RUN_JOURNAL_TABLE_NAMES = { meta: \"meta\", runs: \"runs\", events: \"events\", leases: \"leases\" } as const;\n\n/** A SQL run journal's table names under `prefix`. */\nexport function runJournalTables(prefix = \"\"): Readonly<Record<keyof typeof RUN_JOURNAL_TABLE_NAMES, string>> {\n\treturn renderStorageIdentifiers(\"journal\", RUN_JOURNAL_TABLE_NAMES, prefix);\n}\n\n/** `CREATE TABLE IF NOT EXISTS` statements for a SQL run journal's runs, events and leases tables. */\nexport function runJournalTableDefinitions(prefix = \"\"): string {\n\tconst t = runJournalTables(prefix);\n\treturn `\n\t\tCREATE TABLE IF NOT EXISTS ${t.runs}(\n\t\t\trun_id TEXT PRIMARY KEY, name TEXT NOT NULL, cwd TEXT NOT NULL,\n\t\t\tcreated_at INTEGER NOT NULL, status TEXT NOT NULL, header_json TEXT NOT NULL\n\t\t);\n\t\tCREATE TABLE IF NOT EXISTS ${t.events}(\n\t\t\trun_id TEXT NOT NULL,\n\t\t\tseq INTEGER NOT NULL, epoch INTEGER NOT NULL, key TEXT,\n\t\t\ttype TEXT NOT NULL, payload TEXT NOT NULL, at INTEGER NOT NULL,\n\t\t\tPRIMARY KEY(run_id, seq), UNIQUE(run_id, key)\n\t\t);\n\t\tCREATE TABLE IF NOT EXISTS ${t.leases}(\n\t\t\trun_id TEXT PRIMARY KEY,\n\t\t\tholder_id TEXT, epoch INTEGER NOT NULL, renewed_at INTEGER NOT NULL\n\t\t);\n\t`;\n}\n\n/**\n * Creates a SQL run journal's metadata and tables inside the caller's transaction when they are missing, and checks\n * that an existing journal has the supported schema version. Throws `StorageSchemaVersionError` otherwise.\n */\nexport async function ensureRunJournalSchema(tx: SqliteExecutor, prefix = \"\"): Promise<void> {\n\tconst t = runJournalTables(prefix);\n\tawait tx.exec(`CREATE TABLE IF NOT EXISTS ${t.meta}(schema_version INTEGER NOT NULL)`);\n\tconst versions = await tx.all<SqliteRow & { schema_version: SqliteValue }>(`SELECT schema_version FROM ${t.meta}`);\n\tif (versions.length === 0) await tx.run(`INSERT INTO ${t.meta} VALUES (?)`, RUN_JOURNAL_SCHEMA_VERSION);\n\telse if (versions.length > 1 || versions[0]!.schema_version !== RUN_JOURNAL_SCHEMA_VERSION)\n\t\tthrow new StorageSchemaVersionError(\n\t\t\t\"journal\",\n\t\t\tversions.length > 1 ? `${versions.length} rows` : versions[0]!.schema_version,\n\t\t\tRUN_JOURNAL_SCHEMA_VERSION,\n\t\t);\n\tawait tx.exec(runJournalTableDefinitions(prefix));\n}\n\n/** Most journals one adoption follows through the run references it finds. */\nexport const JOURNAL_DISCOVERY_LIMIT = 64;\n/** The lease holder a consolidation fences a run with while it moves; its successor recognizes an interrupted move. */\nexport const JOURNAL_CONSOLIDATION_HOLDER_PREFIX = \"atomic-storage-consolidate:\";\n\nconst SQLITE_HEADER = \"SQLite format 3\\u0000\";\nconst TABLES = renderStorageIdentifiers(\"journal\", { meta: \"meta\", runs: \"runs\", events: \"events\", leases: \"leases\" });\nconst POOL_ROOTS = `${TABLES.runs}_pool_roots`;\nconst LEGACY_RUNS = \"runs\";\nconst LEGACY_DELETED = renderStorageIdentifiers(\"journal\", { legacyDeleted: \"legacy_deleted\" }).legacyDeleted;\nconst MIGRATIONS = renderStorageIdentifiers(\"journal\", { migrations: \"migrations\" }).migrations;\n/** Recorded in a journal's migrations by the earlier version that copied every pre-0.9.38 run into the current tables. */\nexport const JOURNAL_COPIED_ALL_MARKER = \"unprefixed-journal-tables\";\nconst STORE_NOW = \"CAST(unixepoch('subsec') * 1000 AS INTEGER)\";\n\n/** What a journal file holds, read without changing it. */\nexport interface JournalFileInspection {\n\treadonly path: string;\n\treadonly runs: readonly JournalCatalogRunHeader[];\n\t/** Other node-sqlite journal files its runs say they were written to. */\n\treadonly references: readonly string[];\n}\n\n/** The journal file an adoption path names: the file itself, or `journal.sqlite` in a directory. */\nasync function adoptionFile(path: string): Promise<string> {\n\tconst absolute = resolve(path);\n\tlet info: Awaited<ReturnType<typeof stat>>;\n\ttry {\n\t\tinfo = await stat(absolute);\n\t} catch (cause) {\n\t\tthrow new JournalAdoptError({ code: \"path-not-found\", path: absolute, cause: cause as StorageFailureCause });\n\t}\n\tif (!info.isDirectory()) return absolute;\n\tconst inside = join(absolute, \"journal.sqlite\");\n\tif (!existsSync(inside)) throw new JournalAdoptError({ code: \"not-a-journal\", path: absolute, reason: \"directory\" });\n\treturn inside;\n}\n\nasync function hasSqliteHeader(path: string): Promise<boolean> {\n\tconst handle = await open(path, \"r\");\n\treturn withCleanup(\n\t\tasync () => {\n\t\t\tconst buffer = Buffer.alloc(SQLITE_HEADER.length);\n\t\t\tconst { bytesRead } = await handle.read(buffer, 0, buffer.length, 0);\n\t\t\treturn bytesRead === buffer.length && buffer.toString(\"latin1\") === SQLITE_HEADER;\n\t\t},\n\t\t() => handle.close(),\n\t);\n}\n\nasync function tableNames(executor: SqliteExecutor): Promise<ReadonlySet<string>> {\n\tconst rows = await executor.all<SqliteRow & { name: string }>(\"SELECT name FROM sqlite_master WHERE type = 'table'\");\n\treturn new Set(rows.map((row) => row.name));\n}\n\nfunction referencedJournal(headerJson: string, self: string): string | undefined {\n\tlet header: { storage?: { adapter?: unknown; location?: unknown } };\n\ttry {\n\t\theader = JSON.parse(headerJson) as typeof header;\n\t} catch {\n\t\treturn undefined;\n\t}\n\tconst location = header.storage?.location;\n\tif (header.storage?.adapter !== \"node-sqlite\" || typeof location !== \"string\") return undefined;\n\tif (location === \"\" || location === \":memory:\") return undefined;\n\tconst absolute = resolve(location);\n\treturn absolute === self ? undefined : absolute;\n}\n\n/**\n * Reads a journal file without changing it: that it is a SQLite workflow journal of a supported schema version, its\n * runs, and the other journal files its runs reference. Throws `JournalAdoptError` for anything that cannot be adopted.\n */\nexport async function inspectJournalFile(path: string): Promise<JournalFileInspection> {\n\tconst file = await adoptionFile(path);\n\tlet sqlite: boolean;\n\ttry {\n\t\tsqlite = await hasSqliteHeader(file);\n\t} catch (cause) {\n\t\tthrow new JournalAdoptError({\n\t\t\tcode: \"not-a-journal\",\n\t\t\tpath: file,\n\t\t\treason: \"not-sqlite\",\n\t\t\tcause: cause as StorageFailureCause,\n\t\t});\n\t}\n\tif (!sqlite) throw new JournalAdoptError({ code: \"not-a-journal\", path: file, reason: \"not-sqlite\" });\n\tlet database: SqliteDatabase;\n\ttry {\n\t\tdatabase = await openNodeSqliteDatabase(file, { readOnly: true });\n\t} catch (cause) {\n\t\tthrow new JournalAdoptError({\n\t\t\tcode: \"not-a-journal\",\n\t\t\tpath: file,\n\t\t\treason: \"not-sqlite\",\n\t\t\tcause: cause as StorageFailureCause,\n\t\t});\n\t}\n\treturn withCleanup(\n\t\tasync () => {\n\t\t\ttry {\n\t\t\t\tconst names = await tableNames(database);\n\t\t\t\tif (names.has(\"catalog_shards\"))\n\t\t\t\t\tthrow new JournalAdoptError({ code: \"not-a-journal\", path: file, reason: \"store-catalog\" });\n\t\t\t\tconst current = names.has(TABLES.meta) && names.has(TABLES.runs);\n\t\t\t\tconst legacy = names.has(\"meta\") && names.has(LEGACY_RUNS) && names.has(\"events\");\n\t\t\t\tif (!current && !legacy)\n\t\t\t\t\tthrow new JournalAdoptError({ code: \"not-a-journal\", path: file, reason: \"no-journal-tables\" });\n\t\t\t\tconst versions = await database.all<SqliteRow & { schema_version: SqliteValue }>(\n\t\t\t\t\t`SELECT schema_version FROM ${current ? TABLES.meta : \"meta\"}`,\n\t\t\t\t);\n\t\t\t\tconst found = versions[0]?.schema_version;\n\t\t\t\tif (versions.length !== 1 || found !== RUN_JOURNAL_SCHEMA_VERSION)\n\t\t\t\t\tthrow new JournalAdoptError({\n\t\t\t\t\t\tcode: \"schema-version\",\n\t\t\t\t\t\tpath: file,\n\t\t\t\t\t\tfound: found ?? null,\n\t\t\t\t\t\tsupported: RUN_JOURNAL_SCHEMA_VERSION,\n\t\t\t\t\t});\n\t\t\t\ttype RunRows = (SqliteRow & {\n\t\t\t\t\trun_id: string;\n\t\t\t\t\tname: string;\n\t\t\t\t\tcwd: string;\n\t\t\t\t\tstatus: string;\n\t\t\t\t\theader_json: string;\n\t\t\t\t})[];\n\t\t\t\tconst rows: RunRows = current\n\t\t\t\t\t? await database.all(`SELECT run_id, name, cwd, status, header_json FROM ${TABLES.runs} ORDER BY run_id`)\n\t\t\t\t\t: [];\n\t\t\t\tconst copiedAll =\n\t\t\t\t\tnames.has(MIGRATIONS) &&\n\t\t\t\t\t(await database.get(`SELECT name FROM ${MIGRATIONS} WHERE name = ?`, JOURNAL_COPIED_ALL_MARKER)) !==\n\t\t\t\t\t\tundefined;\n\t\t\t\tif (legacy && !copiedAll) {\n\t\t\t\t\t// Runs of the pre-0.9.38 tables that were not converted or deleted since: read, never converted. A journal\n\t\t\t\t\t// that an earlier version copied in full has its legacy tables ignored, as the journal itself ignores them.\n\t\t\t\t\tconst converted = [\n\t\t\t\t\t\tnames.has(TABLES.runs) ? `AND run_id NOT IN (SELECT run_id FROM ${TABLES.runs})` : \"\",\n\t\t\t\t\t\tnames.has(LEGACY_DELETED) ? `AND run_id NOT IN (SELECT run_id FROM ${LEGACY_DELETED})` : \"\",\n\t\t\t\t\t].join(\" \");\n\t\t\t\t\trows.push(\n\t\t\t\t\t\t...(await database.all<RunRows[number]>(\n\t\t\t\t\t\t\t`SELECT run_id, name, cwd, status, header_json FROM ${LEGACY_RUNS} WHERE 1 = 1 ${converted} ORDER BY run_id`,\n\t\t\t\t\t\t)),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tconst references = new Set<string>();\n\t\t\t\tfor (const row of rows) {\n\t\t\t\t\tconst referenced = referencedJournal(row.header_json, file);\n\t\t\t\t\tif (referenced !== undefined) references.add(referenced);\n\t\t\t\t}\n\t\t\t\treturn {\n\t\t\t\t\tpath: file,\n\t\t\t\t\truns: rows.map((row) => ({ runId: row.run_id, name: row.name, cwd: row.cwd, status: row.status })),\n\t\t\t\t\treferences: [...references],\n\t\t\t\t};\n\t\t\t} catch (cause) {\n\t\t\t\tif (cause instanceof JournalAdoptError) throw cause;\n\t\t\t\tthrow new JournalAdoptError({\n\t\t\t\t\tcode: \"not-a-journal\",\n\t\t\t\t\tpath: file,\n\t\t\t\t\treason: \"not-sqlite\",\n\t\t\t\t\tcause: cause as StorageFailureCause,\n\t\t\t\t});\n\t\t\t}\n\t\t},\n\t\t() => database.close(),\n\t);\n}\n\nexport interface JournalAdoptionOutcome {\n\t/** The journal file, as an absolute path. */\n\treadonly path: string;\n\treadonly status: \"adopted\" | \"already-registered\";\n\treadonly shardId: number;\n\t/** Runs the catalog indexed from it. */\n\treadonly runs: number;\n}\n\ntype DiscoveredJournal =\n\t| {\n\t\t\treadonly path: string;\n\t\t\treadonly referencedBy: string;\n\t\t\treadonly outcome: \"adopted\" | \"already-registered\";\n\t\t\treadonly reason?: undefined;\n\t }\n\t| {\n\t\t\treadonly path: string;\n\t\t\treadonly referencedBy: string;\n\t\t\treadonly outcome: \"skipped\";\n\t\t\t/** The code of the `JournalAdoptError` adopting it raised. */\n\t\t\treadonly reason: JournalAdoptErrorCode;\n\t };\n\n/** A journal found through the runs of an adopted journal, which it names: adopted, or skipped with the reason. */\nexport type JournalDiscovered = DiscoveredJournal & { readonly checkedAt: number };\n\nexport interface JournalAdoptionReport {\n\treadonly adopted: readonly JournalAdoptionOutcome[];\n\t/** Journals found through the runs of adopted journals, adopted or skipped with the reason. */\n\treadonly discovered: readonly JournalDiscovered[];\n}\n\nexport interface JournalAdoptionOptions {\n\t/** Follow the journal files the adopted runs reference, adopting each that can be. Default `true`. */\n\treadonly discover?: boolean;\n}\n\nasync function withCatalog<T>(store: string | JournalCatalog, body: (catalog: JournalCatalog) => Promise<T>) {\n\tif (typeof store !== \"string\") return body(store);\n\tconst catalog = await JournalCatalog.open(store);\n\treturn withCleanup(\n\t\t() => body(catalog),\n\t\t() => catalog.close(),\n\t);\n}\n\nfunction adoptionOutcome(\n\tinspection: JournalFileInspection,\n\t{ shard, status }: JournalShardRegistration,\n): JournalAdoptionOutcome {\n\treturn { path: inspection.path, status, shardId: shard.id, runs: status === \"adopted\" ? inspection.runs.length : 0 };\n}\n\nasync function register(catalog: JournalCatalog, inspection: JournalFileInspection): Promise<JournalAdoptionOutcome> {\n\treturn adoptionOutcome(inspection, await catalog.registerAdopted(inspection.path, inspection.runs));\n}\n\n/** Follows run references breadth first from `start`, adopting what can be and recording what cannot. */\nasync function discover(\n\tcatalog: JournalCatalog,\n\tstart: readonly JournalFileInspection[],\n): Promise<JournalDiscovered[]> {\n\tconst records: JournalDiscovered[] = [];\n\tconst registered = new Set((await catalog.shards()).map((shard) => resolve(shard.path)));\n\tconst visited = new Set<string>();\n\tconst queue = start.flatMap((inspection) =>\n\t\tinspection.references.map((reference) => ({ reference, from: inspection.path })),\n\t);\n\twhile (queue.length > 0 && visited.size < JOURNAL_DISCOVERY_LIMIT) {\n\t\tconst { reference, from } = queue.shift()!;\n\t\tif (visited.has(reference) || registered.has(reference)) continue;\n\t\tvisited.add(reference);\n\t\tlet record: DiscoveredJournal;\n\t\ttry {\n\t\t\tconst inspection = await inspectJournalFile(reference);\n\t\t\tconst outcome = await register(catalog, inspection);\n\t\t\tregistered.add(inspection.path);\n\t\t\trecord = { path: inspection.path, outcome: outcome.status, referencedBy: from };\n\t\t\tfor (const next of inspection.references) queue.push({ reference: next, from: inspection.path });\n\t\t} catch (error) {\n\t\t\tif (!isJournalAdoptError(error)) throw error;\n\t\t\trecord = { path: reference, outcome: \"skipped\", reason: error.code, referencedBy: from };\n\t\t}\n\t\tawait catalog.recordDiscovery(record);\n\t\trecords.push({ ...record, checkedAt: Date.now() });\n\t}\n\treturn records;\n}\n\n/**\n * Registers existing journal files in the journal store in place: nothing is copied, each file becomes a shard that\n * keeps the runs it has and takes no new roots, and every run in it resolves through the catalog. Every path is\n * checked first, and all of them are then registered in one catalog transaction: a conflict registers none. Unless\n * `discover: false`, the journals the adopted runs reference are adopted too, and those that cannot be are recorded\n * with the reason.\n */\nexport async function adoptJournals(\n\tstore: string | JournalCatalog,\n\tpaths: readonly string[],\n\toptions: JournalAdoptionOptions = {},\n): Promise<JournalAdoptionReport> {\n\treturn withCatalog(store, async (catalog) => {\n\t\tconst inspections: JournalFileInspection[] = [];\n\t\tconst owners = new Map<string, string>();\n\t\tfor (const path of paths) {\n\t\t\tconst inspection = await inspectJournalFile(path);\n\t\t\tif (inspections.some((earlier) => isSameFile(earlier.path, inspection.path))) continue;\n\t\t\tfor (const run of inspection.runs) {\n\t\t\t\tconst other = owners.get(run.runId);\n\t\t\t\tif (other !== undefined)\n\t\t\t\t\tthrow new JournalAdoptError({\n\t\t\t\t\t\tcode: \"run-conflict\",\n\t\t\t\t\t\tpath: inspection.path,\n\t\t\t\t\t\trunId: run.runId,\n\t\t\t\t\t\texistingPath: other,\n\t\t\t\t\t});\n\t\t\t\towners.set(run.runId, inspection.path);\n\t\t\t}\n\t\t\tinspections.push(inspection);\n\t\t}\n\t\tconst registrations = await catalog.registerAdoptedAll(inspections);\n\t\tconst adopted = inspections.map((inspection, index) => adoptionOutcome(inspection, registrations[index]!));\n\t\tfor (const outcome of adopted) await catalog.recordDiscovery({ path: outcome.path, outcome: outcome.status });\n\t\tconst discovered = options.discover === false ? [] : await discover(catalog, inspections);\n\t\treturn { adopted, discovered };\n\t});\n}\n\n/**\n * Adopts the legacy default journal beside the store when it holds workflow runs and is not registered yet, then the\n * journals its runs reference. A legacy file that is not a journal (a sessions-only database) is recorded once.\n */\nexport async function discoverLegacyJournal(\n\tcatalog: JournalCatalog,\n\tlegacyPath: string,\n): Promise<JournalAdoptionReport> {\n\tconst path = resolve(legacyPath);\n\tif (!existsSync(path)) return { adopted: [], discovered: [] };\n\tif ((await catalog.shards()).some((shard) => resolve(shard.path) === path)) return { adopted: [], discovered: [] };\n\tlet inspection: JournalFileInspection;\n\ttry {\n\t\tinspection = await inspectJournalFile(path);\n\t} catch (error) {\n\t\tif (!isJournalAdoptError(error)) throw error;\n\t\tconst known = (await catalog.discoveries()).find((record) => record.path === path);\n\t\tif (known?.outcome !== \"skipped\" || known.reason !== error.code)\n\t\t\tawait catalog.recordDiscovery({ path, outcome: \"skipped\", reason: error.code });\n\t\treturn { adopted: [], discovered: [] };\n\t}\n\tconst outcome = await register(catalog, inspection);\n\tawait catalog.recordDiscovery({ path, outcome: outcome.status });\n\treturn { adopted: [outcome], discovered: await discover(catalog, [inspection]) };\n}\n\nexport type JournalConsolidationSkip =\n\t| \"unfinished\"\n\t| \"leased\"\n\t| \"pooled\"\n\t| \"legacy-format\"\n\t| \"conflict\"\n\t| \"changed\"\n\t| \"shard-unavailable\";\n\n/** One run a consolidation considered: moved from shard `from` to shard `to`, or left where it is with the reason. */\nexport type JournalConsolidationRun =\n\t| {\n\t\t\treadonly runId: string;\n\t\t\treadonly from: number;\n\t\t\treadonly to: number;\n\t\t\treadonly outcome: \"moved\";\n\t\t\treadonly reason?: undefined;\n\t\t\treadonly error?: undefined;\n\t }\n\t| {\n\t\t\treadonly runId: string;\n\t\t\treadonly from: number;\n\t\t\treadonly to?: number;\n\t\t\treadonly outcome: \"skipped\";\n\t\t\treadonly reason: JournalConsolidationSkip;\n\t\t\t/** The typed error behind `conflict` or `shard-unavailable`. */\n\t\t\treadonly error?: JournalCatalogError | JournalShardUnavailableError;\n\t };\n\nexport interface JournalConsolidationReport {\n\treadonly moved: number;\n\treadonly skipped: number;\n\treadonly runs: readonly JournalConsolidationRun[];\n}\n\n/** A row of a SQL run journal's runs table. */\nexport type JournalRunTableRow = SqliteRow & {\n\trun_id: string;\n\tname: string;\n\tcwd: string;\n\tcreated_at: number;\n\tstatus: string;\n\theader_json: string;\n};\n/** A row of a SQL run journal's events table: one journal entry, its payload as JSON text. */\nexport type JournalEventTableRow = SqliteRow & {\n\trun_id: string;\n\tseq: number;\n\tepoch: number;\n\tkey: string | null;\n\ttype: string;\n\tpayload: string;\n\tat: number;\n};\ntype RunRow = JournalRunTableRow;\ntype EventRow = JournalEventTableRow;\n/** A row of a SQL run journal's leases table. */\nexport type JournalLeaseTableRow = SqliteRow & {\n\trun_id: string;\n\tholder_id: string | null;\n\tepoch: number;\n\trenewed_at: number;\n};\ntype LeaseRow = JournalLeaseTableRow;\n\ninterface FencedRun {\n\treadonly run: RunRow;\n\treadonly events: readonly EventRow[];\n\treadonly lease: LeaseRow;\n}\n\nconst CONSOLIDATION_TRANSACTION = { lockWaitMs: 10 * 60_000 } as const;\n\nasync function openShardFile(record: JournalShardRecord, runId?: string): Promise<SqliteDatabase> {\n\tif (!existsSync(record.path))\n\t\tthrow new JournalShardUnavailableError({\n\t\t\tcode: \"shard-missing\",\n\t\t\tshardId: record.id,\n\t\t\tshardPath: record.path,\n\t\t\trunId,\n\t\t});\n\ttry {\n\t\treturn await openNodeSqliteDatabase(record.path);\n\t} catch (cause) {\n\t\tthrow new JournalShardUnavailableError({\n\t\t\tcode: \"shard-open-failed\",\n\t\t\tshardId: record.id,\n\t\t\tshardPath: record.path,\n\t\t\trunId,\n\t\t\tcause: cause as StorageFailureCause,\n\t\t});\n\t}\n}\n\n/** Whether a journal file has the current journal tables, which a file of only the pre-0.9.38 format does not. */\nasync function hasJournalTables(database: SqliteExecutor): Promise<boolean> {\n\tconst names = await tableNames(database);\n\treturn [TABLES.runs, TABLES.events, TABLES.leases].every((table) => names.has(table));\n}\n\nasync function ensureJournalTables(source: SqliteExecutor, target: SqliteExecutor): Promise<void> {\n\tconst definitions = await source.all<SqliteRow & { name: string; sql: string }>(\n\t\t`SELECT name, sql FROM sqlite_master WHERE type = 'table' AND name IN (?, ?, ?, ?)`,\n\t\tTABLES.meta,\n\t\tTABLES.runs,\n\t\tTABLES.events,\n\t\tTABLES.leases,\n\t);\n\tfor (const definition of definitions)\n\t\tawait target.exec(definition.sql.replace(\"CREATE TABLE \", \"CREATE TABLE IF NOT EXISTS \"));\n\tconst meta = await target.all(`SELECT schema_version FROM ${TABLES.meta}`);\n\tif (meta.length === 0) await target.run(`INSERT INTO ${TABLES.meta} VALUES (?)`, RUN_JOURNAL_SCHEMA_VERSION);\n}\n\n/**\n * Fences a finished run in its source journal: takes its lease for this consolidation, as a resume would, so no other\n * process can append to it while it moves. Undefined with the reason when it must stay where it is.\n */\nasync function fence(\n\tsource: SqliteDatabase,\n\trunId: string,\n\tholder: string,\n): Promise<FencedRun | JournalConsolidationSkip> {\n\treturn source.transaction(async (tx) => {\n\t\tconst run = await tx.get<RunRow>(`SELECT * FROM ${TABLES.runs} WHERE run_id = ?`, runId);\n\t\tconst names = await tableNames(tx);\n\t\tif (run === undefined) return \"legacy-format\";\n\t\tif (names.has(LEGACY_RUNS) && (await tx.get(`SELECT run_id FROM ${LEGACY_RUNS} WHERE run_id = ?`, runId)))\n\t\t\treturn \"legacy-format\";\n\t\tif (!isFinishedJournalStatus(run.status)) return \"unfinished\";\n\t\tif (names.has(POOL_ROOTS) && (await tx.get(`SELECT root FROM ${POOL_ROOTS} WHERE root = ?`, runId)))\n\t\t\treturn \"pooled\";\n\t\tconst lease = await tx.get<LeaseRow>(`SELECT * FROM ${TABLES.leases} WHERE run_id = ?`, runId);\n\t\tconst heldByOther =\n\t\t\tlease?.holder_id !== undefined &&\n\t\t\tlease.holder_id !== null &&\n\t\t\t!lease.holder_id.startsWith(JOURNAL_CONSOLIDATION_HOLDER_PREFIX);\n\t\tif (heldByOther) return \"leased\";\n\t\tconst epoch = Number(lease?.epoch ?? 0) + 1;\n\t\tawait tx.run(\n\t\t\t`INSERT INTO ${TABLES.leases} VALUES (?, ?, ?, ${STORE_NOW}) ON CONFLICT(run_id) DO UPDATE SET holder_id = excluded.holder_id, epoch = excluded.epoch, renewed_at = excluded.renewed_at`,\n\t\t\trunId,\n\t\t\tholder,\n\t\t\tepoch,\n\t\t);\n\t\tconst events = await tx.all<EventRow>(`SELECT * FROM ${TABLES.events} WHERE run_id = ? ORDER BY seq`, runId);\n\t\tconst fenced = await tx.get<LeaseRow>(`SELECT * FROM ${TABLES.leases} WHERE run_id = ?`, runId);\n\t\treturn { run, events, lease: fenced! };\n\t}, CONSOLIDATION_TRANSACTION);\n}\n\n/**\n * Lifts the fence of any consolidation, this one or a crashed one, from a run's lease in the journal that now holds it. A\n * lease a resume holds is never touched.\n */\n/** Whether a process that is not a consolidation holds the lease of a run in a journal: a resume took it over. */\nasync function heldByResume(database: SqliteDatabase, runId: string): Promise<boolean> {\n\tconst lease = await database.get<LeaseRow>(`SELECT * FROM ${TABLES.leases} WHERE run_id = ?`, runId);\n\treturn lease?.holder_id != null && !lease.holder_id.startsWith(JOURNAL_CONSOLIDATION_HOLDER_PREFIX);\n}\n\n/** Whether a consolidation, this one or another, fences the lease of a run in a journal. */\nasync function fencedByConsolidation(database: SqliteDatabase, runId: string): Promise<boolean> {\n\tconst lease = await database.get<LeaseRow>(`SELECT * FROM ${TABLES.leases} WHERE run_id = ?`, runId);\n\treturn lease?.holder_id?.startsWith(JOURNAL_CONSOLIDATION_HOLDER_PREFIX) === true;\n}\n\n/**\n * How long a consolidation's fence goes unrenewed before another consolidation takes it over: the window after which a\n * resume takes over a consolidation's fence too. Consolidations never renew their fences, so a fence this old belongs to\n * a consolidation that stopped, or to one so slow that a resume could take its run from it anyway.\n */\nconst STALE_CONSOLIDATION_FENCE_MS = 120_000;\n\n/** Whether a run's lease in a journal is a consolidation's fence left unrenewed for longer than the stale window. */\nasync function staleFence(executor: SqliteExecutor, runId: string): Promise<boolean> {\n\tconst stale = await executor.get(\n\t\t`SELECT run_id FROM ${TABLES.leases} WHERE run_id = ? AND holder_id LIKE ? AND renewed_at < ${STORE_NOW} - ?`,\n\t\trunId,\n\t\t`${JOURNAL_CONSOLIDATION_HOLDER_PREFIX}%`,\n\t\tSTALE_CONSOLIDATION_FENCE_MS,\n\t);\n\treturn stale !== undefined;\n}\n\n/**\n * Whether `holder`, a consolidation, holds the lease of a run in a journal, taking it over first from another\n * consolidation whose fence is stale, as lease takeover does: in one transaction, at the next epoch. A lease a resume\n * holds, a lease nobody holds and a fresh fence are never taken.\n */\nasync function takeOverFence(database: SqliteDatabase, runId: string, holder: string): Promise<boolean> {\n\treturn database.transaction(async (tx) => {\n\t\tconst lease = await tx.get<LeaseRow>(`SELECT * FROM ${TABLES.leases} WHERE run_id = ?`, runId);\n\t\tif (lease?.holder_id === holder) return true;\n\t\tif (!(await staleFence(tx, runId))) return false;\n\t\tawait tx.run(\n\t\t\t`UPDATE ${TABLES.leases} SET holder_id = ?, epoch = epoch + 1, renewed_at = ${STORE_NOW} WHERE run_id = ?`,\n\t\t\tholder,\n\t\t\trunId,\n\t\t);\n\t\treturn true;\n\t}, CONSOLIDATION_TRANSACTION);\n}\n\nasync function liftFence(database: SqliteDatabase, runId: string): Promise<void> {\n\tawait database.transaction(\n\t\t(tx) =>\n\t\t\ttx.run(\n\t\t\t\t`UPDATE ${TABLES.leases} SET holder_id = NULL WHERE run_id = ? AND holder_id LIKE ?`,\n\t\t\t\trunId,\n\t\t\t\t`${JOURNAL_CONSOLIDATION_HOLDER_PREFIX}%`,\n\t\t\t),\n\t\tCONSOLIDATION_TRANSACTION,\n\t);\n}\n\nasync function unfence(database: SqliteDatabase, runId: string, holder: string): Promise<void> {\n\tawait database.transaction(\n\t\t(tx) => tx.run(`UPDATE ${TABLES.leases} SET holder_id = NULL WHERE run_id = ? AND holder_id = ?`, runId, holder),\n\t\tCONSOLIDATION_TRANSACTION,\n\t);\n}\n\n/** A run's row and its events in sequence order, as one journal file holds them. */\nexport interface JournalRunSnapshot {\n\treadonly run: JournalRunTableRow;\n\treadonly events: readonly JournalEventTableRow[];\n}\ntype RunSnapshot = JournalRunSnapshot;\n\nfunction sameEvent(left: EventRow, right: EventRow): boolean {\n\treturn (\n\t\tleft.seq === right.seq &&\n\t\tleft.epoch === right.epoch &&\n\t\tleft.key === right.key &&\n\t\tleft.type === right.type &&\n\t\tleft.payload === right.payload &&\n\t\tleft.at === right.at\n\t);\n}\n\n/** Whether `copy` holds everything `source` holds: the same header and the same first events, and maybe more. */\nfunction holdsSnapshot(source: RunSnapshot, copy: RunSnapshot): boolean {\n\treturn (\n\t\tsource.run.header_json === copy.run.header_json &&\n\t\tcopy.events.length >= source.events.length &&\n\t\tsource.events.every((event, index) => sameEvent(event, copy.events[index]!))\n\t);\n}\n\nasync function readRun(database: SqliteExecutor, runId: string): Promise<RunSnapshot | undefined> {\n\tif (!(await hasJournalTables(database))) return undefined;\n\tconst run = await database.get<RunRow>(`SELECT * FROM ${TABLES.runs} WHERE run_id = ?`, runId);\n\tif (run === undefined) return undefined;\n\treturn {\n\t\trun,\n\t\tevents: await database.all<EventRow>(`SELECT * FROM ${TABLES.events} WHERE run_id = ? ORDER BY seq`, runId),\n\t};\n}\n\n/**\n * Copies a fenced run into the target journal in one transaction and says whether the target now holds it. A run the\n * target already holds is left alone, and its lease with it: it counts when that copy holds everything the source does,\n * and not when it differs. A copy holding only the first part of the source's history under another consolidation's\n * stale fence was left by a consolidation that stopped, and is replaced. Only a copy this call inserts gets a lease,\n * fenced by `holder` at an epoch above any lease row the target kept for the run.\n */\nasync function copy(\n\tsource: SqliteDatabase,\n\ttarget: SqliteDatabase,\n\tsnapshot: RunSnapshot,\n\tholder: string,\n\tsourceEpoch: number,\n): Promise<boolean> {\n\treturn target.transaction(async (tx) => {\n\t\tawait ensureJournalTables(source, tx);\n\t\tconst { run } = snapshot;\n\t\tconst existing = await readRun(tx, run.run_id);\n\t\tif (existing !== undefined) {\n\t\t\tif (holdsSnapshot(snapshot, existing)) return true;\n\t\t\tif (!holdsSnapshot(existing, snapshot) || !(await staleFence(tx, run.run_id))) return false;\n\t\t\tawait tx.run(`DELETE FROM ${TABLES.events} WHERE run_id = ?`, run.run_id);\n\t\t\tawait tx.run(`DELETE FROM ${TABLES.runs} WHERE run_id = ?`, run.run_id);\n\t\t}\n\t\tawait tx.run(\n\t\t\t`INSERT INTO ${TABLES.runs}(run_id, name, cwd, created_at, status, header_json) VALUES (?, ?, ?, ?, ?, ?)`,\n\t\t\trun.run_id,\n\t\t\trun.name,\n\t\t\trun.cwd,\n\t\t\trun.created_at,\n\t\t\trun.status,\n\t\t\trun.header_json,\n\t\t);\n\t\tfor (const event of snapshot.events)\n\t\t\tawait tx.run(\n\t\t\t\t`INSERT INTO ${TABLES.events}(run_id, seq, epoch, key, type, payload, at) VALUES (?, ?, ?, ?, ?, ?, ?)`,\n\t\t\t\tevent.run_id,\n\t\t\t\tevent.seq,\n\t\t\t\tevent.epoch,\n\t\t\t\tevent.key,\n\t\t\t\tevent.type,\n\t\t\t\tevent.payload,\n\t\t\t\tevent.at,\n\t\t\t);\n\t\tconst kept = await tx.get<LeaseRow>(`SELECT * FROM ${TABLES.leases} WHERE run_id = ?`, run.run_id);\n\t\tawait tx.run(\n\t\t\t`INSERT INTO ${TABLES.leases} VALUES (?, ?, ?, ${STORE_NOW}) ON CONFLICT(run_id) DO UPDATE SET holder_id = excluded.holder_id, epoch = excluded.epoch, renewed_at = excluded.renewed_at`,\n\t\t\trun.run_id,\n\t\t\tholder,\n\t\t\tMath.max(sourceEpoch, Number(kept?.epoch ?? 0) + 1),\n\t\t);\n\t\treturn true;\n\t}, CONSOLIDATION_TRANSACTION);\n}\n\n/** Deletes a journal's copy of a run, only while `holder` still holds its lease: a compare-and-set on the fence. */\nasync function removeRun(database: SqliteDatabase, runId: string, holder: string): Promise<boolean> {\n\treturn database.transaction(async (tx) => {\n\t\tconst lease = await tx.get<LeaseRow>(`SELECT * FROM ${TABLES.leases} WHERE run_id = ?`, runId);\n\t\tif (lease?.holder_id !== holder) return false;\n\t\tawait tx.run(`DELETE FROM ${TABLES.events} WHERE run_id = ?`, runId);\n\t\tawait tx.run(`DELETE FROM ${TABLES.runs} WHERE run_id = ?`, runId);\n\t\tawait tx.run(`DELETE FROM ${TABLES.leases} WHERE run_id = ?`, runId);\n\t\treturn true;\n\t}, CONSOLIDATION_TRANSACTION);\n}\n\n/**\n * The skip for a run whose destination shard is the very file it is in, under another shard entry: copying into it and\n * deleting the source would delete the only copy. Undefined when the two shards are different files.\n */\nfunction sameFileSkip(\n\tcatalog: JournalCatalog,\n\tfrom: JournalShardRecord,\n\tdestination: JournalShardRecord,\n\trunId: string,\n): JournalConsolidationRun | undefined {\n\tif (!isSameFile(from.path, destination.path)) return undefined;\n\treturn {\n\t\trunId,\n\t\tfrom: from.id,\n\t\tto: destination.id,\n\t\toutcome: \"skipped\",\n\t\treason: \"conflict\",\n\t\terror: new JournalCatalogError({\n\t\t\tcode: \"corrupt\",\n\t\t\tcatalogPath: catalog.path,\n\t\t\trunId,\n\t\t\tshardId: destination.id,\n\t\t\tshardPath: destination.path,\n\t\t\trule: `shards ${from.id} and ${destination.id} are the same file ${from.path}`,\n\t\t}),\n\t};\n}\n\nfunction conflictRun(catalog: JournalCatalog, from: number, destination: JournalShardRecord, runId: string) {\n\treturn {\n\t\trunId,\n\t\tfrom,\n\t\tto: destination.id,\n\t\toutcome: \"skipped\",\n\t\treason: \"conflict\",\n\t\terror: new JournalCatalogError({\n\t\t\tcode: \"run-conflict\",\n\t\t\tcatalogPath: catalog.path,\n\t\t\trunId,\n\t\t\tshardId: destination.id,\n\t\t\tshardPath: destination.path,\n\t\t}),\n\t} as const;\n}\n\n/**\n * Moves a run's catalog entry from `destination` back to `from`, whose copy holds more of the run, then settles the\n * destination's copy in one transaction on it. A copy holding events the source lacks, or that a resume holds, is where\n * the run belongs, and the catalog goes back there. Otherwise the catalog stays on the source, which holds every event:\n * the copy is deleted while `holder` fences it or nobody holds it, unless another consolidation fences it or the source\n * and may still select it. Whether the catalog stays on the source.\n */\nasync function returnToSource(\n\tcatalog: JournalCatalog,\n\tfrom: JournalShardRecord,\n\tdestination: JournalShardRecord,\n\tsource: SqliteDatabase,\n\tdatabase: SqliteDatabase,\n\trunId: string,\n\tholder: string,\n): Promise<boolean> {\n\tawait catalog.moveRun(runId, destination.id, from.id);\n\tconst stays = await database.transaction(async (tx) => {\n\t\tconst there = await readRun(tx, runId);\n\t\tif (there === undefined) return true;\n\t\tconst left = await readRun(source, runId);\n\t\tif (left === undefined || !holdsSnapshot(there, left)) return false;\n\t\tconst lease = await tx.get<LeaseRow>(`SELECT * FROM ${TABLES.leases} WHERE run_id = ?`, runId);\n\t\tif (lease?.holder_id != null && lease.holder_id !== holder)\n\t\t\treturn lease.holder_id.startsWith(JOURNAL_CONSOLIDATION_HOLDER_PREFIX);\n\t\tconst kept = await source.get<SqliteRow & { holder_id: string | null }>(\n\t\t\t`SELECT leases.holder_id FROM ${TABLES.runs} AS runs LEFT JOIN ${TABLES.leases} AS leases ON leases.run_id = runs.run_id WHERE runs.run_id = ?`,\n\t\t\trunId,\n\t\t);\n\t\tif (kept === undefined) return false;\n\t\tif (kept.holder_id?.startsWith(JOURNAL_CONSOLIDATION_HOLDER_PREFIX) && kept.holder_id !== holder) return true;\n\t\tawait tx.run(`DELETE FROM ${TABLES.events} WHERE run_id = ?`, runId);\n\t\tawait tx.run(`DELETE FROM ${TABLES.runs} WHERE run_id = ?`, runId);\n\t\tawait tx.run(`DELETE FROM ${TABLES.leases} WHERE run_id = ?`, runId);\n\t\treturn true;\n\t}, CONSOLIDATION_TRANSACTION);\n\tif (stays) return true;\n\tawait catalog.moveRun(runId, from.id, destination.id);\n\treturn false;\n}\n\n/**\n * Finishes a move whose catalog entry already names `destination`: checks that the destination holds everything the\n * fenced source does (copying the run again if it lost it), deletes the source only while `holder` still fences it, and\n * lifts the fence on the destination. A fence another process took over leaves the source alone; if that process added\n * events the destination lacks, the catalog goes back to the source and the destination copy is removed under\n * `holder`'s fence, taken over first from a consolidation whose fence went stale. Every step compares holders, so\n * overlapping consolidations and a resume that took over an expired fence lose nothing, and a resume's lease on the\n * destination is never overwritten.\n */\nasync function settleMove(\n\tcatalog: JournalCatalog,\n\tsource: SqliteDatabase,\n\tfrom: JournalShardRecord,\n\tdestination: JournalShardRecord,\n\tdatabase: SqliteDatabase,\n\trunId: string,\n\tholder: string,\n\tsourceEpoch: number,\n): Promise<JournalConsolidationRun> {\n\tconst moved = { runId, from: from.id, to: destination.id, outcome: \"moved\" } as const;\n\t// A resume that took the destination's fence may already have written there, so the run stays where it is written\n\t// and is reported leased, or as a conflict when the source gained events the destination lacks.\n\tconst keptOnDestination = async (): Promise<JournalConsolidationRun> => {\n\t\tconst left = await readRun(source, runId);\n\t\tconst there = await readRun(database, runId);\n\t\tif (left !== undefined && there !== undefined && !holdsSnapshot(left, there))\n\t\t\treturn conflictRun(catalog, from.id, destination, runId);\n\t\treturn { runId, from: from.id, to: destination.id, outcome: \"skipped\", reason: \"leased\" };\n\t};\n\tconst undo = async (): Promise<JournalConsolidationRun> => {\n\t\t// The catalog never moves off a destination that someone else leases or that holds events the source lacks.\n\t\tconst left = await readRun(source, runId);\n\t\tconst there = await readRun(database, runId);\n\t\tconst ahead = left !== undefined && there !== undefined && there.events.length > left.events.length;\n\t\tif (ahead || !(await takeOverFence(database, runId, holder))) return keptOnDestination();\n\t\tif (await returnToSource(catalog, from, destination, source, database, runId, holder))\n\t\t\treturn { runId, from: from.id, outcome: \"skipped\", reason: \"leased\" };\n\t\treturn keptOnDestination();\n\t};\n\tconst snapshot = await readRun(source, runId);\n\tif (snapshot === undefined) {\n\t\tawait liftFence(database, runId);\n\t\treturn moved;\n\t}\n\tlet held = await readRun(database, runId);\n\tif (held === undefined) {\n\t\tif (!(await copy(source, database, snapshot, holder, sourceEpoch)))\n\t\t\treturn conflictRun(catalog, from.id, destination, runId);\n\t\theld = (await readRun(database, runId))!;\n\t}\n\tif (!holdsSnapshot(snapshot, held))\n\t\treturn holdsSnapshot(held, snapshot) ? undo() : conflictRun(catalog, from.id, destination, runId);\n\tawait removeRun(source, runId, holder);\n\tconst left = await readRun(source, runId);\n\tif (left !== undefined) {\n\t\tconst now = await readRun(database, runId);\n\t\tconst leased = await source.get<LeaseRow>(`SELECT * FROM ${TABLES.leases} WHERE run_id = ?`, runId);\n\t\tconst resumed = leased?.holder_id != null && !leased.holder_id.startsWith(JOURNAL_CONSOLIDATION_HOLDER_PREFIX);\n\t\t// A resume that took the source lease, with or without events yet, belongs on the file the catalog names.\n\t\tif (resumed || now === undefined || !holdsSnapshot(left, now)) return undo();\n\t}\n\tawait liftFence(database, runId);\n\treturn moved;\n}\n\n/**\n * Moves finished runs out of adopted journals into the store's own shards. A run moves only when it finished\n * (completed, failed or cancelled), no process holds its lease, it never ran local workers (their pool state stays in\n * its journal) and it is not in the pre-0.9.38 table format; every other run stays where it is, with the reason. Each\n * run moves on its own: it is fenced in its journal, copied into a shard in one transaction, repointed in the\n * catalog, and only then deleted from its journal. A consolidation that is interrupted leaves every run readable in\n * exactly one place through the catalog, and running it again finishes the move, or returns the run to its journal\n * when the move was being abandoned or undone.\n */\nexport async function consolidateJournalStore(store: string | JournalCatalog): Promise<JournalConsolidationReport> {\n\treturn withCatalog(store, async (catalog) => {\n\t\tconst holder = `${JOURNAL_CONSOLIDATION_HOLDER_PREFIX}${randomUUID()}`;\n\t\tconst results: JournalConsolidationRun[] = [];\n\t\tconst shards = await catalog.shards();\n\t\tconst targets = new Map<number, SqliteDatabase>();\n\t\tconst target = async (record: JournalShardRecord): Promise<SqliteDatabase> => {\n\t\t\tlet database = targets.get(record.id);\n\t\t\tif (database === undefined) {\n\t\t\t\tdatabase = await openShardFile(record);\n\t\t\t\ttargets.set(record.id, database);\n\t\t\t}\n\t\t\treturn database;\n\t\t};\n\t\tawait withCleanup(\n\t\t\tasync () => {\n\t\t\t\tfor (const shard of shards.filter((candidate) => candidate.kind === \"adopted\")) {\n\t\t\t\t\tlet source: SqliteDatabase;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tsource = await openShardFile(shard);\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tif (!(error instanceof JournalShardUnavailableError)) throw error;\n\t\t\t\t\t\tfor (const run of await catalog.runs({ shard: shard.id }))\n\t\t\t\t\t\t\tresults.push({\n\t\t\t\t\t\t\t\trunId: run.runId,\n\t\t\t\t\t\t\t\tfrom: shard.id,\n\t\t\t\t\t\t\t\toutcome: \"skipped\",\n\t\t\t\t\t\t\t\treason: \"shard-unavailable\",\n\t\t\t\t\t\t\t\terror,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tawait withCleanup(\n\t\t\t\t\t\tasync () => {\n\t\t\t\t\t\t\tconst legacyOnly = !(await hasJournalTables(source));\n\t\t\t\t\t\t\tif (!legacyOnly) {\n\t\t\t\t\t\t\t\tresults.push(...(await finishInterruptedMoves(catalog, source, shard, target)));\n\t\t\t\t\t\t\t\tresults.push(...(await returnStrandedRuns(catalog, source, shard, holder, target)));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tfor (const run of await catalog.runs({ shard: shard.id }))\n\t\t\t\t\t\t\t\tresults.push(\n\t\t\t\t\t\t\t\t\tlegacyOnly\n\t\t\t\t\t\t\t\t\t\t? { runId: run.runId, from: shard.id, outcome: \"skipped\", reason: \"legacy-format\" }\n\t\t\t\t\t\t\t\t\t\t: await moveOne(catalog, source, shard, run.runId, holder, target),\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t},\n\t\t\t\t\t\t() => source.close(),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t},\n\t\t\t() => closeEach(targets.values()),\n\t\t);\n\t\tconst moved = results.filter((run) => run.outcome === \"moved\").length;\n\t\treturn { moved, skipped: results.length - moved, runs: results };\n\t});\n}\n\n/**\n * Returns to this journal the runs a crashed consolidation stranded on another shard: a run this journal holds, with no\n * consolidation fencing it here, whose catalog entry names a shard that lost the run, or that holds only the first part\n * of its history under a consolidation's stale fence. That consolidation was abandoning or undoing the move, so\n * `finishInterruptedMoves` has nothing to finish; the moves that follow find the run here again. A fresh fence may\n * belong to a consolidation still undoing the move, and is left to it. A run whose shard cannot be opened is reported.\n * A run whose named copy lacks events this journal holds and cannot be returned is reported a conflict, and both copies\n * are kept: the two histories differ, as when resumes wrote to both copies during an interrupted move, or a resume\n * holds the named copy.\n */\nasync function returnStrandedRuns(\n\tcatalog: JournalCatalog,\n\tsource: SqliteDatabase,\n\tfrom: JournalShardRecord,\n\tholder: string,\n\ttarget: (record: JournalShardRecord) => Promise<SqliteDatabase>,\n): Promise<JournalConsolidationRun[]> {\n\tconst skipped: JournalConsolidationRun[] = [];\n\tconst listed = new Set((await catalog.runs({ shard: from.id })).map((run) => run.runId));\n\tconst unfenced = await source.all<SqliteRow & { run_id: string }>(\n\t\t`SELECT run_id FROM ${TABLES.runs} WHERE run_id NOT IN (SELECT run_id FROM ${TABLES.leases} WHERE holder_id LIKE ?) ORDER BY run_id`,\n\t\t`${JOURNAL_CONSOLIDATION_HOLDER_PREFIX}%`,\n\t);\n\tfor (const { run_id: runId } of unfenced.filter((row) => !listed.has(row.run_id))) {\n\t\tconst destination = (await catalog.locate(runId))?.shard;\n\t\tif (destination === undefined) continue;\n\t\tlet database: SqliteDatabase;\n\t\ttry {\n\t\t\tdatabase = await target(destination);\n\t\t} catch (error) {\n\t\t\tif (!(error instanceof JournalShardUnavailableError)) throw error;\n\t\t\tskipped.push({\n\t\t\t\trunId,\n\t\t\t\tfrom: from.id,\n\t\t\t\tto: destination.id,\n\t\t\t\toutcome: \"skipped\",\n\t\t\t\treason: \"shard-unavailable\",\n\t\t\t\terror,\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tconst left = await readRun(source, runId);\n\t\tconst there = await readRun(database, runId);\n\t\tif (left === undefined) continue;\n\t\tif (there === undefined) {\n\t\t\tawait source.transaction(async (tx) => {\n\t\t\t\tconst lease = await tx.get<LeaseRow>(`SELECT * FROM ${TABLES.leases} WHERE run_id = ?`, runId);\n\t\t\t\tif (lease?.holder_id?.startsWith(JOURNAL_CONSOLIDATION_HOLDER_PREFIX)) return;\n\t\t\t\tif ((await readRun(tx, runId)) !== undefined && (await readRun(database, runId)) === undefined)\n\t\t\t\t\tawait catalog.moveRun(runId, destination.id, from.id);\n\t\t\t}, CONSOLIDATION_TRANSACTION);\n\t\t\tcontinue;\n\t\t}\n\t\tif (holdsSnapshot(left, there)) continue;\n\t\tif (holdsSnapshot(there, left)) {\n\t\t\tif (await takeOverFence(database, runId, holder)) {\n\t\t\t\tif (await returnToSource(catalog, from, destination, source, database, runId, holder)) continue;\n\t\t\t} else if (await fencedByConsolidation(database, runId)) continue;\n\t\t}\n\t\tconst kept = await readRun(source, runId);\n\t\tconst named = await readRun(database, runId);\n\t\tif (kept !== undefined && named !== undefined && !holdsSnapshot(kept, named))\n\t\t\tskipped.push(conflictRun(catalog, from.id, destination, runId));\n\t}\n\treturn skipped;\n}\n\n/**\n * Finishes the moves a consolidation was interrupted in after it had repointed the catalog: the run's source copy,\n * still fenced by it, is deleted once its new shard is checked to hold it, and the fence it left there is lifted. A run\n * whose new shard cannot be opened keeps its source copy and is reported skipped.\n */\nasync function finishInterruptedMoves(\n\tcatalog: JournalCatalog,\n\tsource: SqliteDatabase,\n\tfrom: JournalShardRecord,\n\ttarget: (record: JournalShardRecord) => Promise<SqliteDatabase>,\n): Promise<JournalConsolidationRun[]> {\n\tconst skipped: JournalConsolidationRun[] = [];\n\tconst fenced = await source.all<LeaseRow>(\n\t\t`SELECT * FROM ${TABLES.leases} WHERE holder_id LIKE ?`,\n\t\t`${JOURNAL_CONSOLIDATION_HOLDER_PREFIX}%`,\n\t);\n\tfor (const lease of fenced) {\n\t\t// Where the catalog names the run now, not where it did when this consolidation began: another consolidation may\n\t\t// have repointed it since, and a fence it left on this file is then not an interrupted move to finish.\n\t\tconst destination = (await catalog.locate(lease.run_id))?.shard;\n\t\tif (destination === undefined || destination.id === from.id) continue;\n\t\tconst same = sameFileSkip(catalog, from, destination, lease.run_id);\n\t\tif (same !== undefined) {\n\t\t\tskipped.push(same);\n\t\t\tcontinue;\n\t\t}\n\t\tlet database: SqliteDatabase;\n\t\ttry {\n\t\t\tdatabase = await target(destination);\n\t\t} catch (error) {\n\t\t\tif (!(error instanceof JournalShardUnavailableError)) throw error;\n\t\t\tskipped.push({\n\t\t\t\trunId: lease.run_id,\n\t\t\t\tfrom: from.id,\n\t\t\t\tto: destination.id,\n\t\t\t\toutcome: \"skipped\",\n\t\t\t\treason: \"shard-unavailable\",\n\t\t\t\terror,\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tconst settled = await settleMove(\n\t\t\tcatalog,\n\t\t\tsource,\n\t\t\tfrom,\n\t\t\tdestination,\n\t\t\tdatabase,\n\t\t\tlease.run_id,\n\t\t\tlease.holder_id!,\n\t\t\tNumber(lease.epoch),\n\t\t);\n\t\tif (settled.outcome === \"skipped\") skipped.push(settled);\n\t}\n\treturn skipped;\n}\n\nasync function moveOne(\n\tcatalog: JournalCatalog,\n\tsource: SqliteDatabase,\n\tshard: JournalShardRecord,\n\trunId: string,\n\tholder: string,\n\ttarget: (record: JournalShardRecord) => Promise<SqliteDatabase>,\n): Promise<JournalConsolidationRun> {\n\tconst fenced = await fence(source, runId, holder);\n\tif (typeof fenced === \"string\") return { runId, from: shard.id, outcome: \"skipped\", reason: fenced };\n\tconst destination = await catalog.homeShard(runId);\n\tconst same = sameFileSkip(catalog, shard, destination, runId);\n\tif (same !== undefined) {\n\t\tawait unfence(source, runId, holder);\n\t\treturn same;\n\t}\n\tlet database: SqliteDatabase;\n\ttry {\n\t\tdatabase = await target(destination);\n\t} catch (error) {\n\t\tawait unfence(source, runId, holder);\n\t\tif (!(error instanceof JournalShardUnavailableError)) throw error;\n\t\treturn { runId, from: shard.id, outcome: \"skipped\", reason: \"shard-unavailable\", error };\n\t}\n\tif (!(await copy(source, database, fenced, holder, fenced.lease.epoch))) {\n\t\tawait unfence(source, runId, holder);\n\t\treturn conflictRun(catalog, shard.id, destination, runId);\n\t}\n\t// A move that waited so long that a resume took the source's fence is abandoned before the catalog changes.\n\tif (await heldByResume(source, runId)) {\n\t\tconst selected = async () => (await catalog.locate(runId))?.shard.id === destination.id;\n\t\tif (!(await selected()) && (!(await removeRun(database, runId, holder)) || !(await selected())))\n\t\t\treturn { runId, from: shard.id, outcome: \"skipped\", reason: \"leased\" };\n\t\tconst settled = await settleMove(\n\t\t\tcatalog,\n\t\t\tsource,\n\t\t\tshard,\n\t\t\tdestination,\n\t\t\tdatabase,\n\t\t\trunId,\n\t\t\tholder,\n\t\t\tfenced.lease.epoch,\n\t\t);\n\t\treturn settled.outcome === \"moved\" ? { runId, from: shard.id, outcome: \"skipped\", reason: \"changed\" } : settled;\n\t}\n\tconst repointed = await catalog.moveRun(runId, shard.id, destination.id);\n\tif (!repointed && (await catalog.locate(runId))?.shard.id !== destination.id) {\n\t\tawait removeRun(database, runId, holder);\n\t\tawait unfence(source, runId, holder);\n\t\treturn { runId, from: shard.id, outcome: \"skipped\", reason: \"changed\" };\n\t}\n\tconst settled = await settleMove(catalog, source, shard, destination, database, runId, holder, fenced.lease.epoch);\n\t// Another consolidation repointed the run first: it moved it, this one only cleaned up behind it.\n\treturn repointed ? settled : { runId, from: shard.id, outcome: \"skipped\", reason: \"changed\" };\n}\n"]}