@hearsay-tools/squawk 0.18.0-pr4088.7818 → 0.18.0-pr4089.7823
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.
- package/dist/artifacts/reports-index.d.ts +3 -7
- package/dist/artifacts/reports-index.js +6 -6
- package/dist/artifacts/reports-index.js.map +1 -1
- package/dist/ci-wait/controller.d.ts +46 -46
- package/dist/delegation/routes.d.ts +10 -10
- package/dist/delegation/transport.d.ts +14 -14
- package/dist/runs/lifecycle.d.ts +2 -1
- package/dist/runs/lifecycle.js.map +1 -1
- package/dist/runs/ports.d.ts +12 -2
- package/dist/runs/run-persistence.d.ts +150 -0
- package/dist/runs/run-persistence.js +396 -0
- package/dist/runs/run-persistence.js.map +1 -0
- package/dist/runs/run-retention.d.ts +6 -2
- package/dist/runs/run-retention.js +11 -2
- package/dist/runs/run-retention.js.map +1 -1
- package/dist/runs/store.d.ts +3 -70
- package/dist/runs/store.js +58 -399
- package/dist/runs/store.js.map +1 -1
- package/dist/server/models-routes.d.ts +13 -13
- package/dist/server/reports-api.d.ts +2 -2
- package/dist/server/start-server.js +1 -1
- package/dist/server/start-server.js.map +1 -1
- package/dist/server/workspace-live-routes.d.ts +6 -6
- package/dist/workflows/run/continuation-acceptance.js +2 -2
- package/dist/workflows/run/continuation-acceptance.js.map +1 -1
- package/dist/workflows/run/family-reconciler.d.ts +2 -1
- package/dist/workflows/run/family-reconciler.js.map +1 -1
- package/dist/workflows/run/native-skill-input-queue.js +1 -1
- package/dist/workflows/run/native-skill-input-queue.js.map +1 -1
- package/dist/workflows/run/queued-revival.js +3 -3
- package/dist/workflows/run/queued-revival.js.map +1 -1
- package/dist/workflows/run/run-cancel.js +4 -4
- package/dist/workflows/run/run-cancel.js.map +1 -1
- package/dist/workflows/run/run-finish.js +1 -1
- package/dist/workflows/run/run-finish.js.map +1 -1
- package/dist/workflows/run/run-settlement.js +4 -4
- package/dist/workflows/run/run-settlement.js.map +1 -1
- package/dist/workflows/run/step-loop.js +4 -4
- package/dist/workflows/run/step-loop.js.map +1 -1
- package/dist/workflows/run/turn-nudges.js +1 -1
- package/dist/workflows/run/turn-nudges.js.map +1 -1
- package/dist/workflows/run/turn-settler.js +1 -1
- package/dist/workflows/run/turn-settler.js.map +1 -1
- package/dist/workflows/run/usage-accounting.js +1 -1
- package/dist/workflows/run/usage-accounting.js.map +1 -1
- package/package.json +4 -4
- package/scripts/benchmark-family-reconcile.ts +1 -1
- package/scripts/benchmark-run-store.ts +3 -3
- package/scripts/benchmark-workspace-events.ts +2 -2
package/dist/runs/store.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { legacyIndexRows, readableSavedRunner, upgradeLegacyRunRow, withKeptFields } from './legacy-run-rows.js';
|
|
2
2
|
import { addRunSource, fallbackRunSource } from './project-run-sources.js';
|
|
3
3
|
import { registeredWaitRecord, registeredReceiptRecord } from './wait-registration-write.js';
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
4
|
+
import { stageDurableUpdate, stageDebouncedUpdate, stageConversation, stageStepUpdate, stepTotals, redactPatch } from './record-write-rules.js';
|
|
5
|
+
import { RunLifecycle, snapshotRun } from './lifecycle.js';
|
|
6
6
|
import { listPeerTaskSummaries, parseStoredSummary } from './run-summary-page.js';
|
|
7
7
|
export { parseStoredSummary } from './run-summary-page.js';
|
|
8
8
|
import { workerExecutionsFactory } from './worker-executions-registry.js';
|
|
@@ -27,21 +27,21 @@ import { restoreHistory } from './history-file.js';
|
|
|
27
27
|
// Type-only module (zod + nothing else), so this cannot cycle back into the store.
|
|
28
28
|
import { workflowDefSchema } from '../workflows/types.js';
|
|
29
29
|
import { applyOutcomes } from './outcome-commit.js';
|
|
30
|
-
import { ISSUE_URL_RE, namesForeignReference, rescopeRun,
|
|
30
|
+
import { ISSUE_URL_RE, namesForeignReference, rescopeRun, trackReferencedIssues, trackReferencedPrs } from './run-references.js';
|
|
31
31
|
import { applyExit, doneCommits, exitDurability, RUN_EXITS } from './run-exits.js';
|
|
32
32
|
import { assertConversationIdFree } from './conversation-identity.js';
|
|
33
33
|
export { ConversationIdInUseError } from './conversation-identity.js';
|
|
34
34
|
import { LEGACY_RUNNER_IDS } from '../core/runner-ids.js';
|
|
35
|
-
import { ARCHIVED_ROOT, RUNS_DB_FILE, RUNS_IMPORT_COMPLETE_KEY,
|
|
35
|
+
import { ARCHIVED_ROOT, RUNS_DB_FILE, RUNS_IMPORT_COMPLETE_KEY, RunDatabase, RunDatabaseBusyError, } from './run-database.js';
|
|
36
36
|
import { listBranchOwners } from './branch-owners.js';
|
|
37
37
|
import { guardedJsonSql } from './guarded-json-sql.js';
|
|
38
38
|
import { reconcileLoadedRun } from './loaded-run-exits.js';
|
|
39
39
|
import { hasLegacyWaitFields, UNREADABLE_WAIT } from './legacy-waits.js';
|
|
40
40
|
export { ciWaitEntry, holdsWorkerWait, upgradeLegacyWaits, workerWaitEntry } from './legacy-waits.js';
|
|
41
41
|
import { ExitEvents } from './exit-events.js';
|
|
42
|
-
import {
|
|
42
|
+
import { familyRootOf, isLiveRecord, materializedWorktreePath, newestFirst } from './run-row.js';
|
|
43
43
|
import { RunRetentionTopic } from './run-retention.js';
|
|
44
|
-
import { collectRawExtras
|
|
44
|
+
import { collectRawExtras } from './raw-record.js';
|
|
45
45
|
import { ColdReadCache, storedRow } from './cold-reads.js';
|
|
46
46
|
import { LEGACY_INDEX_FILE, LegacyWriterError } from './legacy-index.js';
|
|
47
47
|
import { toRunStoreOpenError } from './store-open-error.js';
|
|
@@ -54,8 +54,8 @@ import { RunEventLogTopic } from './event-log.js';
|
|
|
54
54
|
import { RunRedaction } from './run-redaction.js';
|
|
55
55
|
import { RunArchiveTopic } from './run-archive.js';
|
|
56
56
|
import { RunReadFlagsTopic } from './run-read-flags.js';
|
|
57
|
+
import { replaceRecord, RunPersistenceTopic } from './run-persistence.js';
|
|
57
58
|
import { closeClaimSession, familyKey, openClaimSession, rowFamily } from './run-claims.js';
|
|
58
|
-
import { assertProjectWritable, projectWriteRefused } from '../server/cockpit-ownership.js';
|
|
59
59
|
/**
|
|
60
60
|
* A runner id as it may appear in a PERSISTED record (#547), spec 2026-11-18-runner-definitions.
|
|
61
61
|
*
|
|
@@ -182,13 +182,6 @@ export { LEGACY_INDEX_BACKUP_FILE, LEGACY_INDEX_FILE } from './legacy-index.js';
|
|
|
182
182
|
* through `GET /run-summaries/archived` and the workspace search. */
|
|
183
183
|
export const ARCHIVED_WINDOW = 200;
|
|
184
184
|
export { branchOwnerOf } from './branch-owners.js';
|
|
185
|
-
/** Make `target` hold exactly `source`'s fields, keeping the object every holder references. */
|
|
186
|
-
function replaceRecord(target, source) {
|
|
187
|
-
for (const key of Object.keys(target))
|
|
188
|
-
if (!(key in source))
|
|
189
|
-
delete target[key];
|
|
190
|
-
Object.assign(target, source);
|
|
191
|
-
}
|
|
192
185
|
/**
|
|
193
186
|
* A worker's destroy moving between two unfinished phases, and nothing else changing: nothing the
|
|
194
187
|
* family reconcile reads changed, so it may skip that pass (#880). The first request and the
|
|
@@ -246,15 +239,11 @@ export class RunStore {
|
|
|
246
239
|
pins = new Map();
|
|
247
240
|
/** Staged ids while a durable commit installs and announces them: never evicted mid-commit. */
|
|
248
241
|
committing = new Set();
|
|
249
|
-
saveTimer = null;
|
|
250
242
|
/** `null` once the store is closed, and in a `RunStore.unavailable` store (nothing is written,
|
|
251
243
|
* nothing is evicted). */
|
|
252
244
|
db = null;
|
|
253
|
-
/** Persistence source for consumers that build the reports index. No index is created here. */
|
|
254
|
-
reportSource() { return { db: this.db, dataDir: this.dataDir, openFailure: this.openFailure }; }
|
|
255
245
|
/** Why `open` failed, in a `RunStore.unavailable` store. */
|
|
256
246
|
openFailure;
|
|
257
|
-
persistence;
|
|
258
247
|
/** Runs whose held record is ahead of its row; the next save or commit writes them. */
|
|
259
248
|
dirty = new Set();
|
|
260
249
|
/** The typed lifecycle events the store publishes after each write (lifecycle.ts). */
|
|
@@ -290,8 +279,6 @@ export class RunStore {
|
|
|
290
279
|
* Cleared at the next microtask: no commit spans a turn. */
|
|
291
280
|
coldBase = new Map();
|
|
292
281
|
coldReads = new ColdReadCache();
|
|
293
|
-
/** The family of each pending deletion, whose claim the deleting write is fenced against. */
|
|
294
|
-
deletedFamilies = new Map();
|
|
295
282
|
/** Rows a conflicting write excluded: this store refuses to write them until it is reopened. */
|
|
296
283
|
quarantined = new Set();
|
|
297
284
|
/** Rows whose `data` this store tried to decode and could not: left in the database untouched,
|
|
@@ -315,13 +302,15 @@ export class RunStore {
|
|
|
315
302
|
claims;
|
|
316
303
|
/** The holds that keep a run loaded (hearsay-tools/squawk#4042). */
|
|
317
304
|
runPins;
|
|
305
|
+
/** Flush, persist, the fence, conflicts and the save debounce (hearsay-tools/squawk#4043). */
|
|
306
|
+
persistence;
|
|
318
307
|
executions;
|
|
319
308
|
/** A worker's execution, process, identity and scope records (hearsay-tools/squawk#4039), built on
|
|
320
309
|
* first use by the factory this process registered; throws when none is registered. */
|
|
321
310
|
get workerExecutions() {
|
|
322
311
|
return this.executions ??= workerExecutionsFactory()(this.dataDir, {
|
|
323
312
|
peek: (id) => this.peek(id), getRun: (id) => this.getRun(id), writeDir: (id) => this.claims.writeDir(id),
|
|
324
|
-
sourceDataDir: (id) => this.claims.sourceDataDir(id), commitIndex: (input) => this.commitIndex(input),
|
|
313
|
+
sourceDataDir: (id) => this.claims.sourceDataDir(id), commitIndex: (input) => this.persistence.commitIndex(input),
|
|
325
314
|
published: this.published, workerResults: this.workerResults,
|
|
326
315
|
});
|
|
327
316
|
}
|
|
@@ -330,15 +319,15 @@ export class RunStore {
|
|
|
330
319
|
liveReadSnapshot(runId) {
|
|
331
320
|
return { events: this.liveItems.read(runId), throughSeq: this.seqs.get(runId) ?? Infinity };
|
|
332
321
|
}
|
|
333
|
-
constructor(dataDir) {
|
|
322
|
+
constructor(dataDir, persist) {
|
|
334
323
|
this.dataDir = dataDir;
|
|
335
324
|
this.redaction = new RunRedaction();
|
|
336
325
|
this.claims = new RunClaimsTopic(dataDir, {
|
|
337
326
|
db: () => this.db, owner: () => this.owner, keepLive: () => this.keepLive, held: this.held, base: this.base, dirty: this.dirty,
|
|
338
327
|
deleted: this.deleted, quarantined: this.quarantined, unreadable: this.unreadable, claimed: this.claimed, pendingClaims: this.pendingClaims,
|
|
339
|
-
exitEvents: this.exitEvents, coldReads: this.coldReads, decodeRunRow, anchoredFamilies: () => this.anchoredFamilies(), scheduleSave: () => this.scheduleSave(),
|
|
328
|
+
exitEvents: this.exitEvents, coldReads: this.coldReads, decodeRunRow, anchoredFamilies: () => this.anchoredFamilies(), scheduleSave: () => this.persistence.scheduleSave(),
|
|
340
329
|
});
|
|
341
|
-
this.runPins = new RunPinsTopic({ pins: this.pins, published: this.published, record: (id) => this.record(id), peek: (id) => this.peek(id), sweepIfSettled: (ids) => this.sweepIfSettled(ids) });
|
|
330
|
+
this.runPins = new RunPinsTopic({ pins: this.pins, published: this.published, record: (id) => this.record(id), peek: (id) => this.peek(id), sweepIfSettled: (ids) => this.persistence.sweepIfSettled(ids) });
|
|
342
331
|
this.transcriptFacts = new RunTranscriptFacts(dataDir, {
|
|
343
332
|
isFallbackRun: (id) => this.claims.isFallbackRun(id),
|
|
344
333
|
sourceDataDir: (id) => this.claims.sourceDataDir(id),
|
|
@@ -357,7 +346,7 @@ export class RunStore {
|
|
|
357
346
|
this.eventLog = new RunEventLogTopic(dataDir, {
|
|
358
347
|
seqs: this.seqs, published: this.published, liveItems: this.liveItems, transcriptFacts: this.transcriptFacts, redaction: this.redaction,
|
|
359
348
|
record: (id) => this.record(id), missingRunError: (runId) => this.claims.missingRunError(runId), sourceDataDir: (id) => this.claims.sourceDataDir(id),
|
|
360
|
-
touch: (run, before) => this.touch(run, before), change: (id, apply) => this.change(id, apply), repoHandle: () => this.repoHandle,
|
|
349
|
+
touch: (run, before) => this.persistence.touch(run, before), change: (id, apply) => this.change(id, apply), repoHandle: () => this.repoHandle,
|
|
361
350
|
maybeEnqueueHistoryCompress: (run) => this.archive.maybeEnqueueHistoryCompress(run),
|
|
362
351
|
});
|
|
363
352
|
this.retention = new RunRetentionTopic(dataDir, {
|
|
@@ -366,32 +355,39 @@ export class RunStore {
|
|
|
366
355
|
peek: (id) => this.peek(id), hasRun: (id) => this.hasRun(id), record: (id) => this.record(id),
|
|
367
356
|
listWorkersOf: (parentId) => this.listWorkersOf(parentId), isFallbackRun: (id) => this.claims.isFallbackRun(id),
|
|
368
357
|
hasFallbackRun: (id) => this.claims.hasFallbackRun(id), listOrder: (run) => this.listOrder(run),
|
|
369
|
-
claimFamilies: (families) => this.claims.claimFamilies(families), markDeleted: (id, family) => this.markDeleted(id, family),
|
|
370
|
-
scheduleSave: () => this.scheduleSave(), commitIndex: (input) => this.commitIndex(input),
|
|
358
|
+
claimFamilies: (families) => this.claims.claimFamilies(families), markDeleted: (id, family) => this.persistence.markDeleted(id, family),
|
|
359
|
+
scheduleSave: () => this.persistence.scheduleSave(), commitIndex: (input) => this.persistence.commitIndex(input),
|
|
371
360
|
commitDelegation: (patches) => this.commitDelegation(patches), applyArchived: (run, archived) => this.archive.applyArchived(run, archived),
|
|
372
361
|
workerDeletionEvidence: (id) => this.workerExecutions.workerDeletionEvidence(id),
|
|
373
362
|
workerResults: this.workerResults,
|
|
374
363
|
readWorkerExecution: (id) => this.workerExecutions.readWorkerExecution(id), identityPath: (id) => this.workerExecutions.identityPath(id),
|
|
375
364
|
processesPath: (id) => this.workerExecutions.processesPath(id), scopePath: (id) => this.workerExecutions.scopePath(id),
|
|
376
|
-
executionPath: (id) => this.workerExecutions.executionPath(id),
|
|
377
|
-
imagesDir: (runId) => this.imagesDir(runId),
|
|
365
|
+
executionPath: (id) => this.workerExecutions.executionPath(id), sourceDataDir: (id) => this.claims.sourceDataDir(id),
|
|
378
366
|
});
|
|
379
367
|
this.archive = new RunArchiveTopic(dataDir, {
|
|
380
368
|
db: () => this.db, held: this.held, deleted: this.deleted, quarantined: this.quarantined, pins: this.pins,
|
|
381
369
|
claimed: this.claimed, base: this.base, owner: () => this.owner, transcriptFacts: this.transcriptFacts,
|
|
382
370
|
decodeRunRow, sortNewestFirst, peek: (id) => this.peek(id), record: (id) => this.record(id),
|
|
383
|
-
listWorkersOf: (parentId) => this.listWorkersOf(parentId), familyOf: (id) => this.familyOf(id),
|
|
371
|
+
listWorkersOf: (parentId) => this.listWorkersOf(parentId), familyOf: (id) => this.persistence.familyOf(id),
|
|
384
372
|
claimFamilies: (families, opts) => this.claims.claimFamilies(families, opts), writeRefusal: (id) => this.claims.writeRefusal(id),
|
|
385
|
-
assertWritable: (staged) => this.assertWritable(staged), decodeCold: (row) => this.decodeCold(row),
|
|
386
|
-
listOrder: (run) => this.listOrder(run), commitIndex: (input, source, write) => this.commitIndex(input, source, write),
|
|
387
|
-
touch: (run, before, exit) => this.touch(run, before, exit),
|
|
373
|
+
assertWritable: (staged) => this.persistence.assertWritable(staged), decodeCold: (row) => this.decodeCold(row),
|
|
374
|
+
listOrder: (run) => this.listOrder(run), commitIndex: (input, source, write) => this.persistence.commitIndex(input, source, write),
|
|
375
|
+
touch: (run, before, exit) => this.persistence.touch(run, before, exit),
|
|
388
376
|
readWorkerExecution: (id) => this.workerExecutions.readWorkerExecution(id),
|
|
389
377
|
});
|
|
390
378
|
this.readFlags = new RunReadFlagsTopic({
|
|
391
379
|
db: () => this.db, held: this.held, deleted: this.deleted, record: (id) => this.record(id),
|
|
392
|
-
claimFamilies: (families) => this.claims.claimFamilies(families), touch: (run, before) => this.touch(run, before),
|
|
380
|
+
claimFamilies: (families) => this.claims.claimFamilies(families), touch: (run, before) => this.persistence.touch(run, before),
|
|
393
381
|
change: (id, apply) => this.change(id, apply),
|
|
394
382
|
});
|
|
383
|
+
this.persistence = new RunPersistenceTopic(dataDir, persist, {
|
|
384
|
+
db: () => this.db, owner: () => this.owner, openFailure: () => this.openFailure, repoHandle: () => this.repoHandle,
|
|
385
|
+
held: this.held, committing: this.committing, dirty: this.dirty, deleted: this.deleted, historyOwed: this.historyOwed,
|
|
386
|
+
quarantined: this.quarantined, claimed: this.claimed, pendingClaims: this.pendingClaims, base: this.base, coldBase: this.coldBase,
|
|
387
|
+
coldReads: this.coldReads, liveItems: this.liveItems, published: this.published, archive: this.archive, claims: this.claims,
|
|
388
|
+
retention: this.retention, decodeRunRow, peek: (id) => this.peek(id), isAnchor: (id, run) => this.isAnchor(id, run),
|
|
389
|
+
evictSettled: () => this.evictSettled(),
|
|
390
|
+
});
|
|
395
391
|
}
|
|
396
392
|
/**
|
|
397
393
|
* Open the project's run store. See `reconcileLoadedRun` for what `keepLive` (#367) decides
|
|
@@ -432,9 +428,8 @@ export class RunStore {
|
|
|
432
428
|
const deferred = source && !existsSync(path) && !existsSync(join(dataDir, LEGACY_INDEX_FILE));
|
|
433
429
|
if (!deferred)
|
|
434
430
|
mkdirSync(join(dataDir, 'runs'), { recursive: true });
|
|
435
|
-
const store = new RunStore(dataDir);
|
|
431
|
+
const store = new RunStore(dataDir, persist);
|
|
436
432
|
store.keepLive = keepLive;
|
|
437
|
-
store.persistence = persist;
|
|
438
433
|
let db = RunDatabase.open(deferred ? ':memory:' : path);
|
|
439
434
|
try {
|
|
440
435
|
if (deferred)
|
|
@@ -584,7 +579,7 @@ export class RunStore {
|
|
|
584
579
|
if (!run)
|
|
585
580
|
return undefined;
|
|
586
581
|
this.holdDecoded(run);
|
|
587
|
-
this.scheduleSave();
|
|
582
|
+
this.persistence.scheduleSave();
|
|
588
583
|
return run;
|
|
589
584
|
}
|
|
590
585
|
/** The record a store write changes in place: held, or loaded to be. Undefined for a run this
|
|
@@ -652,7 +647,7 @@ export class RunStore {
|
|
|
652
647
|
for (const run of [...this.held.values()]) {
|
|
653
648
|
const before = snapshotRun(run);
|
|
654
649
|
if (rescopeRun(run, this.repoHandle)) {
|
|
655
|
-
this.touch(run, before);
|
|
650
|
+
this.persistence.touch(run, before);
|
|
656
651
|
healed = true;
|
|
657
652
|
}
|
|
658
653
|
}
|
|
@@ -667,13 +662,13 @@ export class RunStore {
|
|
|
667
662
|
if (!run || !this.storedScopeDiffers(row, run))
|
|
668
663
|
continue;
|
|
669
664
|
this.holdDecoded(run);
|
|
670
|
-
this.touch(run, before ?? snapshotRun(run));
|
|
665
|
+
this.persistence.touch(run, before ?? snapshotRun(run));
|
|
671
666
|
healed = true;
|
|
672
667
|
}
|
|
673
668
|
// Discovery may finish after headless shutdown's final flush. Persist repairs now: the
|
|
674
669
|
// debounced save is unref'd, so it cannot keep the CLI alive once the lookup completes.
|
|
675
670
|
if (healed)
|
|
676
|
-
this.flush();
|
|
671
|
+
this.persistence.flush();
|
|
677
672
|
}
|
|
678
673
|
/** Whether the stored summary still names a reference the scoped record no longer has. */
|
|
679
674
|
storedScopeDiffers(row, run) {
|
|
@@ -1120,7 +1115,7 @@ export class RunStore {
|
|
|
1120
1115
|
throw new RunWriteRefusedError(run.id, 'foreign');
|
|
1121
1116
|
this.held.set(run.id, run);
|
|
1122
1117
|
this.retention.pruneOldRuns();
|
|
1123
|
-
this.touch(run, undefined);
|
|
1118
|
+
this.persistence.touch(run, undefined);
|
|
1124
1119
|
return run;
|
|
1125
1120
|
}
|
|
1126
1121
|
/** Build without publishing: owned creation must commit its receipt and run together. */
|
|
@@ -1180,7 +1175,7 @@ export class RunStore {
|
|
|
1180
1175
|
assertConversationIdFree(root, message ?? delivery?.input, id => this.peek(id), (runId, id) => this.eventLog.hasProjection(runId, id));
|
|
1181
1176
|
const staged = new Map();
|
|
1182
1177
|
stageConversation(staged, root, conversation, delivery, id => this.peek(id), text => this.redaction.redactText(text));
|
|
1183
|
-
this.commitIndex(staged);
|
|
1178
|
+
this.persistence.commitIndex(staged);
|
|
1184
1179
|
}
|
|
1185
1180
|
/** Crash recovery (#505): input a harness accepted but was never seen reading goes
|
|
1186
1181
|
* back to the queue. Returns the requeued IDs. */
|
|
@@ -1224,7 +1219,7 @@ export class RunStore {
|
|
|
1224
1219
|
throw new Error('live inbox receipt changed');
|
|
1225
1220
|
}
|
|
1226
1221
|
}
|
|
1227
|
-
this.commitIndex(new Map([[id, { ...run, agentInputs }]]));
|
|
1222
|
+
this.persistence.commitIndex(new Map([[id, { ...run, agentInputs }]]));
|
|
1228
1223
|
}
|
|
1229
1224
|
/** Reserve only unread conversation inputs in one durable index replacement. */
|
|
1230
1225
|
claimInboxInputs(runId, ids, claim) {
|
|
@@ -1246,7 +1241,7 @@ export class RunStore {
|
|
|
1246
1241
|
}
|
|
1247
1242
|
}
|
|
1248
1243
|
const selectedIds = new Set(selected);
|
|
1249
|
-
this.commitIndex(new Map([[runId, { ...run, agentInputs: inputs.map(input => selectedIds.has(input.id)
|
|
1244
|
+
this.persistence.commitIndex(new Map([[runId, { ...run, agentInputs: inputs.map(input => selectedIds.has(input.id)
|
|
1250
1245
|
? agentInputSchema.parse({ ...input, inboxClaim: receipt }) : input) }]]));
|
|
1251
1246
|
}
|
|
1252
1247
|
/** A receipt owns every matching input or none; exact ACK retries preserve the first timestamp. */
|
|
@@ -1285,7 +1280,7 @@ export class RunStore {
|
|
|
1285
1280
|
if (!matching.length || matching.some(input => input.inboxClaim?.generation !== generation ||
|
|
1286
1281
|
input.inboxClaim?.acknowledgedAt || input.deliveredAt))
|
|
1287
1282
|
throw new Error('inbox receipt changed');
|
|
1288
|
-
this.commitIndex(new Map([[runId, { ...run, agentInputs: run.agentInputs.map(input => {
|
|
1283
|
+
this.persistence.commitIndex(new Map([[runId, { ...run, agentInputs: run.agentInputs.map(input => {
|
|
1289
1284
|
if (input.inboxClaim?.receiptId !== receiptId)
|
|
1290
1285
|
return input;
|
|
1291
1286
|
const { inboxClaim: _claim, ...unclaimed } = input;
|
|
@@ -1300,7 +1295,7 @@ export class RunStore {
|
|
|
1300
1295
|
inboxClaimSchema.shape.expiresAt.parse(now);
|
|
1301
1296
|
if (!run.agentInputs?.some(input => input.inboxClaim && !input.inboxClaim.acknowledgedAt && input.inboxClaim.expiresAt <= now))
|
|
1302
1297
|
return;
|
|
1303
|
-
this.commitIndex(new Map([[runId, { ...run, agentInputs: run.agentInputs.map(input => {
|
|
1298
|
+
this.persistence.commitIndex(new Map([[runId, { ...run, agentInputs: run.agentInputs.map(input => {
|
|
1304
1299
|
if (!input.inboxClaim || input.inboxClaim.acknowledgedAt || input.inboxClaim.expiresAt > now)
|
|
1305
1300
|
return input;
|
|
1306
1301
|
const { inboxClaim: _claim, ...unclaimed } = input;
|
|
@@ -1318,14 +1313,14 @@ export class RunStore {
|
|
|
1318
1313
|
const run = this.peek(id);
|
|
1319
1314
|
if (!run)
|
|
1320
1315
|
throw new Error('missing wait target');
|
|
1321
|
-
this.commitIndex(new Map([[id, registeredWaitRecord(run, wait, input, registration)]]));
|
|
1316
|
+
this.persistence.commitIndex(new Map([[id, registeredWaitRecord(run, wait, input, registration)]]));
|
|
1322
1317
|
}
|
|
1323
1318
|
/** Record a deduplicated registration without mutating its wait. */
|
|
1324
1319
|
commitWaitRegistration(id, receipt) {
|
|
1325
1320
|
const run = this.peek(id);
|
|
1326
1321
|
if (!run)
|
|
1327
1322
|
throw new Error('missing wait target');
|
|
1328
|
-
this.commitIndex(new Map([[id, registeredReceiptRecord(run, receipt)]]));
|
|
1323
|
+
this.persistence.commitIndex(new Map([[id, registeredReceiptRecord(run, receipt)]]));
|
|
1329
1324
|
}
|
|
1330
1325
|
/** A usage-limit appointment withdrawn, committed at once instead of on the debounced save
|
|
1331
1326
|
* (hearsay-tools/cezarion#1236): a crash right after the withdrawal must not find it on disk,
|
|
@@ -1338,7 +1333,7 @@ export class RunStore {
|
|
|
1338
1333
|
if (isUsageLimitHold(run))
|
|
1339
1334
|
this.move(id, 'withdraw-hold');
|
|
1340
1335
|
else
|
|
1341
|
-
this.commitIndex(new Map([[id, { ...run, autoResumeAt: undefined, autoResumeAttempts: undefined, autoResumeReason: undefined }]]));
|
|
1336
|
+
this.persistence.commitIndex(new Map([[id, { ...run, autoResumeAt: undefined, autoResumeAttempts: undefined, autoResumeReason: undefined }]]));
|
|
1342
1337
|
}
|
|
1343
1338
|
/** A human message beside a run's waits (hearsay-tools/cezarion#1235): accepted durably, and
|
|
1344
1339
|
* every wait stays. A lifecycle opening becomes
|
|
@@ -1348,7 +1343,7 @@ export class RunStore {
|
|
|
1348
1343
|
const run = this.peek(id);
|
|
1349
1344
|
if (!run)
|
|
1350
1345
|
throw new Error('missing queued message target');
|
|
1351
|
-
this.commitIndex(new Map([[id, { ...run, queuedMessages: [...(run.queuedMessages ?? []), queuedMessageSchema.parse(acceptedHumanMessage)],
|
|
1346
|
+
this.persistence.commitIndex(new Map([[id, { ...run, queuedMessages: [...(run.queuedMessages ?? []), queuedMessageSchema.parse(acceptedHumanMessage)],
|
|
1352
1347
|
...(run.continuationMessage ? { continuationMessage: { ...run.continuationMessage, origin: 'human' } } : {}),
|
|
1353
1348
|
}]]));
|
|
1354
1349
|
}
|
|
@@ -1370,7 +1365,7 @@ export class RunStore {
|
|
|
1370
1365
|
if (!staged.changed)
|
|
1371
1366
|
return { committed: false, answered: [], settled: [] };
|
|
1372
1367
|
try {
|
|
1373
|
-
this.commitIndex(new Map([[id, staged.next]]), undefined, { exits: new Map([[id, staged.exit]]) });
|
|
1368
|
+
this.persistence.commitIndex(new Map([[id, staged.next]]), undefined, { exits: new Map([[id, staged.exit]]) });
|
|
1374
1369
|
}
|
|
1375
1370
|
catch (error) {
|
|
1376
1371
|
if (!opts.bestEffort)
|
|
@@ -1381,7 +1376,7 @@ export class RunStore {
|
|
|
1381
1376
|
return { committed: false, answered: staged.answered, settled: staged.settled };
|
|
1382
1377
|
const before = snapshotRun(live);
|
|
1383
1378
|
replaceRecord(live, staged.next);
|
|
1384
|
-
this.touch(live, before, staged.exit);
|
|
1379
|
+
this.persistence.touch(live, before, staged.exit);
|
|
1385
1380
|
return { committed: false, answered: staged.answered, settled: staged.settled };
|
|
1386
1381
|
}
|
|
1387
1382
|
return { committed: true, answered: staged.answered, settled: staged.settled };
|
|
@@ -1412,7 +1407,7 @@ export class RunStore {
|
|
|
1412
1407
|
}
|
|
1413
1408
|
// In-process cause only: consumers can skip metadata replay when delegation
|
|
1414
1409
|
// is disabled without dropping real status or termination-proof notifications.
|
|
1415
|
-
this.commitIndex(staged, destroyProgress ? 'delegation-destroy-progress' : 'delegation-checkpoint');
|
|
1410
|
+
this.persistence.commitIndex(staged, destroyProgress ? 'delegation-destroy-progress' : 'delegation-checkpoint');
|
|
1416
1411
|
}
|
|
1417
1412
|
/** A pending destroy's automatic retry state, or its removal (hearsay-tools/cezarion#879). Kept on
|
|
1418
1413
|
* the record beside the strict delegation, so an older Squawk strips it rather than quarantining the
|
|
@@ -1424,7 +1419,7 @@ export class RunStore {
|
|
|
1424
1419
|
if (!retry && !run.destroyRetry)
|
|
1425
1420
|
return;
|
|
1426
1421
|
// An explicit `undefined`, not an omitted key: commitIndex assigns onto the live record.
|
|
1427
|
-
this.commitIndex(new Map([[id, { ...run, destroyRetry: retry ? workerDestroyRetrySchema.parse(retry) : undefined }]]), 'delegation-destroy-progress');
|
|
1422
|
+
this.persistence.commitIndex(new Map([[id, { ...run, destroyRetry: retry ? workerDestroyRetrySchema.parse(retry) : undefined }]]), 'delegation-destroy-progress');
|
|
1428
1423
|
}
|
|
1429
1424
|
/** Accepted execution revision is public lifecycle identity, separate from process generations. */
|
|
1430
1425
|
commitWorkerContinuation(id, exit, patch = {}, step, conversation) {
|
|
@@ -1449,7 +1444,7 @@ export class RunStore {
|
|
|
1449
1444
|
throw new Error('missing conversation ownership');
|
|
1450
1445
|
stageConversation(staged, root, conversation.state, { recipientRunId: id, input: conversation.input }, runId => this.peek(runId), text => this.redaction.redactText(text));
|
|
1451
1446
|
}
|
|
1452
|
-
this.commitIndex(staged, undefined, { exits: new Map([[id, exit]]) });
|
|
1447
|
+
this.persistence.commitIndex(staged, undefined, { exits: new Map([[id, exit]]) });
|
|
1453
1448
|
}
|
|
1454
1449
|
/** Create an owned worker run and its parent receipt; `createStoreOwnedRun` holds the checks. */
|
|
1455
1450
|
createOwnedRun(input, parentId, requestId, worker, requestHash, spawnCapacityRefusal, executionIdentity = { kind: 'internal' }) {
|
|
@@ -1460,98 +1455,9 @@ export class RunStore {
|
|
|
1460
1455
|
buildRun: (ownedInput, id) => this.buildRun(ownedInput, id),
|
|
1461
1456
|
writeWorkerIdentity: (id, identity) => this.workerExecutions.writeWorkerIdentity(id, identity),
|
|
1462
1457
|
writeWorkerExecution: (id, proof, fresh) => this.workerExecutions.writeWorkerExecution(id, proof, fresh),
|
|
1463
|
-
commitIndex: (owned) => this.commitIndex(owned),
|
|
1458
|
+
commitIndex: (owned) => this.persistence.commitIndex(owned),
|
|
1464
1459
|
}, input, parentId, requestId, worker, requestHash, spawnCapacityRefusal, executionIdentity);
|
|
1465
1460
|
}
|
|
1466
|
-
/**
|
|
1467
|
-
* Durably replace or delete staged rows together with pending dirty rows. Persist before
|
|
1468
|
-
* changing held objects or notifying subscribers. On failure retain all pending state; flush()
|
|
1469
|
-
* remains best-effort.
|
|
1470
|
-
*/
|
|
1471
|
-
commitIndex(input, source, write = {}) {
|
|
1472
|
-
const exits = new Map(write.exits);
|
|
1473
|
-
const staged = stageCommit(input, {
|
|
1474
|
-
peek: id => this.peek(id),
|
|
1475
|
-
completionArchiveBlocker: run => this.archive.completionArchiveBlocker(run),
|
|
1476
|
-
stageArchive: (staged, run, archived) => this.archive.stageArchive(staged, run, archived, exits),
|
|
1477
|
-
});
|
|
1478
|
-
const before = new Map([...staged].map(([id, next]) => [id, next ? write.before?.get(id) ?? snapshotRun(this.peek(id)) : undefined])), committed = new Map([...staged].map(([id, next]) => [id, snapshotRun(next ?? undefined)]));
|
|
1479
|
-
if (!this.db)
|
|
1480
|
-
throw this.openFailure ?? new Error('runs database unavailable: nothing can be saved');
|
|
1481
|
-
this.assertWritable(staged);
|
|
1482
|
-
this.persist(staged);
|
|
1483
|
-
// Preserve existing record references, but expose the entire transaction before its first event, which
|
|
1484
|
-
// carries the record this commit wrote (`committed`). A finished run is held until the next sweep.
|
|
1485
|
-
for (const [id, next] of staged) {
|
|
1486
|
-
this.coldReads.forget(id);
|
|
1487
|
-
if (!next) {
|
|
1488
|
-
this.held.delete(id);
|
|
1489
|
-
continue;
|
|
1490
|
-
}
|
|
1491
|
-
this.committing.add(id);
|
|
1492
|
-
const current = this.held.get(id);
|
|
1493
|
-
if (current)
|
|
1494
|
-
replaceRecord(current, next);
|
|
1495
|
-
else
|
|
1496
|
-
this.held.set(id, next);
|
|
1497
|
-
}
|
|
1498
|
-
try {
|
|
1499
|
-
for (const id of staged.keys()) {
|
|
1500
|
-
const run = this.held.get(id);
|
|
1501
|
-
if (run)
|
|
1502
|
-
publishRunWrite(this.published, committed.get(id) ?? run, before.get(id), source, exits.get(id));
|
|
1503
|
-
else
|
|
1504
|
-
this.published.publish('run.deleted', { runId: id });
|
|
1505
|
-
}
|
|
1506
|
-
}
|
|
1507
|
-
finally {
|
|
1508
|
-
for (const id of staged.keys())
|
|
1509
|
-
this.committing.delete(id);
|
|
1510
|
-
this.sweepIfSettled(staged.keys());
|
|
1511
|
-
}
|
|
1512
|
-
for (const [id, next] of staged)
|
|
1513
|
-
if (next?.archived)
|
|
1514
|
-
this.archive.compressor.enqueue(id);
|
|
1515
|
-
}
|
|
1516
|
-
/**
|
|
1517
|
-
* Refuse (throwing, with nothing changed) a commit that stages a quarantined run, or a run whose
|
|
1518
|
-
* family this store does not claim and cannot take: another process owns it, or a dead process
|
|
1519
|
-
* left it live and it has not been adopted.
|
|
1520
|
-
*/
|
|
1521
|
-
assertWritable(staged) {
|
|
1522
|
-
const families = new Map();
|
|
1523
|
-
const held = new Set();
|
|
1524
|
-
for (const [id, next] of staged) {
|
|
1525
|
-
if (this.quarantined.has(id))
|
|
1526
|
-
throw new RunWriteRefusedError(id, 'quarantined');
|
|
1527
|
-
const family = next ? familyKey(next) : this.familyOf(id);
|
|
1528
|
-
families.set(id, family);
|
|
1529
|
-
if (this.held.has(id))
|
|
1530
|
-
held.add(family);
|
|
1531
|
-
}
|
|
1532
|
-
// A run this store holds may move to a new family; any other row is claimed as a plain write.
|
|
1533
|
-
const owned = new Set([...this.claims.claimFamilies(held, { allowLive: true }),
|
|
1534
|
-
...this.claims.claimFamilies([...families.values()].filter((family) => !held.has(family)))]);
|
|
1535
|
-
for (const [id, family] of families) {
|
|
1536
|
-
if (!owned.has(family))
|
|
1537
|
-
throw this.claims.runOwnership(id) === 'fallback' ? this.claims.fallbackRefusal(id) : new RunWriteRefusedError(id, this.claims.runOwnership(id) === 'orphaned' ? 'orphaned' : 'foreign');
|
|
1538
|
-
}
|
|
1539
|
-
}
|
|
1540
|
-
/** The family of a run this store knows: held, else its row; a run nowhere is its own. */
|
|
1541
|
-
familyOf(id) {
|
|
1542
|
-
const held = this.held.get(id);
|
|
1543
|
-
return held ? familyKey(held) : this.deletedFamilies.get(id) ?? this.db?.familyOf(id) ?? id;
|
|
1544
|
-
}
|
|
1545
|
-
/** Schedule the sweep that lets any of `ids` leave memory, when one of them now can. */
|
|
1546
|
-
sweepIfSettled(ids) {
|
|
1547
|
-
for (const id of ids) {
|
|
1548
|
-
const run = this.held.get(id);
|
|
1549
|
-
if (run && !this.isAnchor(id, run)) {
|
|
1550
|
-
this.scheduleSave();
|
|
1551
|
-
return;
|
|
1552
|
-
}
|
|
1553
|
-
}
|
|
1554
|
-
}
|
|
1555
1461
|
/** Move run `id` by `exit` (ADR 0056): its status and `extras` in one write, checked against the
|
|
1556
1462
|
* record that write changes. A run this store cannot write is neither checked nor written. The
|
|
1557
1463
|
* exit decides how the write persists (`exitDurability`), never the extras. A guarded exit (one
|
|
@@ -1575,7 +1481,7 @@ export class RunStore {
|
|
|
1575
1481
|
moved = this.writeRun(id, run, applyExit(run, exit, redacted, call), exitDurability(exit, run), exit);
|
|
1576
1482
|
else {
|
|
1577
1483
|
const input = { ...run, ...redacted };
|
|
1578
|
-
this.commitIndex(new Map([[id, { ...(spec.settle?.(input, { ...call, now: new Date().toISOString() }) ?? input), ...applyExit(run, exit, {}, call) }]]), undefined, { exits: new Map([[id, exit]]) });
|
|
1484
|
+
this.persistence.commitIndex(new Map([[id, { ...(spec.settle?.(input, { ...call, now: new Date().toISOString() }) ?? input), ...applyExit(run, exit, {}, call) }]]), undefined, { exits: new Map([[id, exit]]) });
|
|
1579
1485
|
moved = this.peek(id);
|
|
1580
1486
|
}
|
|
1581
1487
|
if (event)
|
|
@@ -1602,11 +1508,11 @@ export class RunStore {
|
|
|
1602
1508
|
repoHandle: this.repoHandle,
|
|
1603
1509
|
restore: () => restoreHistory(this.dataDir, id),
|
|
1604
1510
|
archive: (record, archived) => this.archive.applyArchived(record, archived, before, exit),
|
|
1605
|
-
touch: (record) => this.touch(record, before, exit),
|
|
1511
|
+
touch: (record) => this.persistence.touch(record, before, exit),
|
|
1606
1512
|
};
|
|
1607
1513
|
if (durability === 'committed') {
|
|
1608
1514
|
const staged = stageDurableUpdate(run, patch, hooks, exit);
|
|
1609
|
-
this.commitIndex(new Map([[id, staged.run]]), undefined, { before: new Map([[id, before]]), exits: new Map([[id, staged.exit]]) });
|
|
1515
|
+
this.persistence.commitIndex(new Map([[id, staged.run]]), undefined, { before: new Map([[id, before]]), exits: new Map([[id, staged.exit]]) });
|
|
1610
1516
|
return this.record(id);
|
|
1611
1517
|
}
|
|
1612
1518
|
stageDebouncedUpdate(run, patch, hooks);
|
|
@@ -1622,7 +1528,7 @@ export class RunStore {
|
|
|
1622
1528
|
return;
|
|
1623
1529
|
const before = snapshotRun(run);
|
|
1624
1530
|
run.steps = [...run.steps, { ...step, status: 'pending', iterations: 0, tokensUsed: 0 }];
|
|
1625
|
-
this.touch(run, before);
|
|
1531
|
+
this.persistence.touch(run, before);
|
|
1626
1532
|
}
|
|
1627
1533
|
updateStep(runId, stepId, patch) {
|
|
1628
1534
|
const run = this.record(runId);
|
|
@@ -1633,7 +1539,7 @@ export class RunStore {
|
|
|
1633
1539
|
// Replaced, never changed in place, so `before` keeps the steps as they were.
|
|
1634
1540
|
run.steps = run.steps.map((candidate) => candidate === step ? next : candidate);
|
|
1635
1541
|
Object.assign(run, stepTotals(run.steps));
|
|
1636
|
-
this.touch(run, before);
|
|
1542
|
+
this.persistence.touch(run, before);
|
|
1637
1543
|
}
|
|
1638
1544
|
/** A debounced write of the held record `id`: `apply` changes it in place, then `touch` saves it. */
|
|
1639
1545
|
change(id, apply) {
|
|
@@ -1641,7 +1547,7 @@ export class RunStore {
|
|
|
1641
1547
|
if (!run)
|
|
1642
1548
|
return undefined;
|
|
1643
1549
|
apply(run);
|
|
1644
|
-
this.touch(run, before);
|
|
1550
|
+
this.persistence.touch(run, before);
|
|
1645
1551
|
return run;
|
|
1646
1552
|
}
|
|
1647
1553
|
/** Indexed family enumeration, including members not yet flushed to SQLite. */
|
|
@@ -1657,251 +1563,8 @@ export class RunStore {
|
|
|
1657
1563
|
ids.delete(id);
|
|
1658
1564
|
return [...ids];
|
|
1659
1565
|
}
|
|
1660
|
-
/** Write the pending rows out now (used on shutdown). */
|
|
1661
|
-
flush() {
|
|
1662
|
-
if (this.saveTimer) {
|
|
1663
|
-
clearTimeout(this.saveTimer);
|
|
1664
|
-
this.saveTimer = null;
|
|
1665
|
-
}
|
|
1666
|
-
this.saveNow();
|
|
1667
|
-
}
|
|
1668
1566
|
// ---- internals -----------------------------------------------------------
|
|
1669
1567
|
seqs = new Map();
|
|
1670
|
-
/** Same location `handoffPath()` in handoff.ts produces — inlined to keep
|
|
1671
|
-
* the store free of upward imports. */
|
|
1672
|
-
handoffPath(runId) {
|
|
1673
|
-
return join(this.claims.sourceDataDir(runId), 'runs', `${runId}.handoff.md`);
|
|
1674
|
-
}
|
|
1675
|
-
/** Agent screenshots persisted by the run manager (see persistImage). */
|
|
1676
|
-
imagesDir(runId) {
|
|
1677
|
-
return join(this.claims.sourceDataDir(runId), 'runs', `${runId}-images`);
|
|
1678
|
-
}
|
|
1679
|
-
/** Save `run` debounced and publish it; `before` is the record at the write's entry (none: created). */
|
|
1680
|
-
touch(run, before, exit) {
|
|
1681
|
-
this.dirty.add(run.id);
|
|
1682
|
-
this.scheduleSave();
|
|
1683
|
-
publishRunWrite(this.published, run, before, undefined, exit);
|
|
1684
|
-
this.archive.maybeEnqueueHistoryCompress(run);
|
|
1685
|
-
}
|
|
1686
|
-
/** The held record is gone; the next save or commit deletes its row, fenced by `family`'s claim
|
|
1687
|
-
* and by the revision this store last saw (kept in `base` until the delete is written). */
|
|
1688
|
-
markDeleted(id, family) {
|
|
1689
|
-
this.liveItems.forget(id);
|
|
1690
|
-
this.coldReads.forget(id);
|
|
1691
|
-
const read = this.coldBase.get(id);
|
|
1692
|
-
if (!this.base.has(id) && read)
|
|
1693
|
-
this.base.set(id, storedRow(read));
|
|
1694
|
-
this.dirty.delete(id);
|
|
1695
|
-
this.deleted.add(id);
|
|
1696
|
-
this.deletedFamilies.set(id, family);
|
|
1697
|
-
this.historyOwed.add(id);
|
|
1698
|
-
}
|
|
1699
|
-
/** Debounced so token-usage updates don't rewrite a row per event. Nothing to schedule without
|
|
1700
|
-
* a database: a `RunStore.unavailable` store, or a closed one, writes nothing. */
|
|
1701
|
-
scheduleSave() {
|
|
1702
|
-
if (this.saveTimer || !this.db)
|
|
1703
|
-
return;
|
|
1704
|
-
this.saveTimer = setTimeout(() => {
|
|
1705
|
-
this.saveTimer = null;
|
|
1706
|
-
this.saveNow();
|
|
1707
|
-
}, 300);
|
|
1708
|
-
this.saveTimer.unref?.();
|
|
1709
|
-
}
|
|
1710
|
-
/** The single database write, so a test can fail it the way a full disk would. */
|
|
1711
|
-
writeIndex(changes) {
|
|
1712
|
-
const transaction = (changes) => { assertProjectWritable(this.dataDir); return this.db.transaction(changes); };
|
|
1713
|
-
return this.persistence ? this.persistence(changes, transaction) : transaction(changes);
|
|
1714
|
-
}
|
|
1715
|
-
/**
|
|
1716
|
-
* Write `staged` plus everything still pending — dirty rows from memory, deletions — in one
|
|
1717
|
-
* transaction, then clear the pending marks. Throws with nothing cleared when it fails.
|
|
1718
|
-
* Never copies or sorts the whole store: the cost is the rows that changed.
|
|
1719
|
-
*
|
|
1720
|
-
* Fenced (#779, plan step 3): the transaction commits only if every family it writes still
|
|
1721
|
-
* carries this store's claim and every row is at the revision this store last saw. Otherwise
|
|
1722
|
-
* nothing is written and `handleConflicts` deals with the rows that changed under it.
|
|
1723
|
-
*/
|
|
1724
|
-
persist(staged) {
|
|
1725
|
-
const upserts = [];
|
|
1726
|
-
const deletes = [];
|
|
1727
|
-
const families = new Map();
|
|
1728
|
-
const extras = new Map();
|
|
1729
|
-
const encode = (run) => {
|
|
1730
|
-
const encoded = encodeRawRecord(run, (this.base.get(run.id) ?? this.coldBase.get(run.id))?.extras);
|
|
1731
|
-
extras.set(run.id, encoded.extras);
|
|
1732
|
-
const projected = { ...run };
|
|
1733
|
-
restoreOriginatingIssue(projected);
|
|
1734
|
-
upserts.push({ ...encodeRunRow(run, encoded.data),
|
|
1735
|
-
issueAttributionCurrent: isDeepStrictEqual(projected, run) });
|
|
1736
|
-
};
|
|
1737
|
-
for (const [id, next] of staged) {
|
|
1738
|
-
if (next)
|
|
1739
|
-
encode(next);
|
|
1740
|
-
else
|
|
1741
|
-
deletes.push(id);
|
|
1742
|
-
families.set(id, next ? familyKey(next) : this.familyOf(id));
|
|
1743
|
-
}
|
|
1744
|
-
for (const id of this.dirty) {
|
|
1745
|
-
const run = this.held.get(id);
|
|
1746
|
-
if (!run || staged.has(id))
|
|
1747
|
-
continue;
|
|
1748
|
-
encode(run);
|
|
1749
|
-
families.set(id, familyKey(run));
|
|
1750
|
-
}
|
|
1751
|
-
for (const id of this.deleted) {
|
|
1752
|
-
if (staged.has(id))
|
|
1753
|
-
continue;
|
|
1754
|
-
deletes.push(id);
|
|
1755
|
-
families.set(id, this.familyOf(id));
|
|
1756
|
-
}
|
|
1757
|
-
// A row's insertion order (`seq`) is the order this write inserts it in, and it is where the
|
|
1758
|
-
// run lists among runs created in the same millisecond. Insert new runs in creation order (the
|
|
1759
|
-
// held set's, then staged runs not held yet), whether staged or dirty brought them here.
|
|
1760
|
-
if (upserts.filter((row) => !this.base.has(row.id)).length > 1) {
|
|
1761
|
-
const created = new Map();
|
|
1762
|
-
for (const id of [...this.held.keys(), ...staged.keys()])
|
|
1763
|
-
if (!created.has(id))
|
|
1764
|
-
created.set(id, created.size);
|
|
1765
|
-
upserts.sort((a, b) => created.get(a.id) - created.get(b.id));
|
|
1766
|
-
}
|
|
1767
|
-
// A held run whose write moved it into a new family (a worker quarantined to `invalid`) takes
|
|
1768
|
-
// that family's claim first; one it cannot take fails the fence below as claim-lost.
|
|
1769
|
-
const moved = [...new Set(families.values())].filter((family) => !this.claimed.has(family) && !this.pendingClaims.has(family));
|
|
1770
|
-
if (moved.length > 0)
|
|
1771
|
-
this.claims.claimFamilies(moved, { allowLive: true });
|
|
1772
|
-
let commit;
|
|
1773
|
-
try {
|
|
1774
|
-
commit = this.writeIndex({ upserts, deletes, ...(this.owner ? { fence: this.fence(families) } : {}) });
|
|
1775
|
-
}
|
|
1776
|
-
catch (error) {
|
|
1777
|
-
if (error instanceof RunConflictError)
|
|
1778
|
-
this.handleConflicts(error, staged);
|
|
1779
|
-
throw error;
|
|
1780
|
-
}
|
|
1781
|
-
for (const [family, generation] of commit.claims) {
|
|
1782
|
-
this.claimed.set(family, generation);
|
|
1783
|
-
this.pendingClaims.delete(family);
|
|
1784
|
-
}
|
|
1785
|
-
for (const row of upserts) {
|
|
1786
|
-
this.base.set(row.id, { revision: commit.revisions.get(row.id), seq: commit.seqs.get(row.id), data: row.data, extras: extras.get(row.id) });
|
|
1787
|
-
}
|
|
1788
|
-
for (const id of deletes) {
|
|
1789
|
-
this.liveItems.forget(id);
|
|
1790
|
-
this.base.delete(id);
|
|
1791
|
-
this.deletedFamilies.delete(id);
|
|
1792
|
-
this.retention.removeOwedHistory(id);
|
|
1793
|
-
}
|
|
1794
|
-
this.dirty.clear();
|
|
1795
|
-
this.deleted.clear();
|
|
1796
|
-
if (this.saveTimer) {
|
|
1797
|
-
clearTimeout(this.saveTimer);
|
|
1798
|
-
this.saveTimer = null;
|
|
1799
|
-
}
|
|
1800
|
-
}
|
|
1801
|
-
/** What a write of these rows (id → family) must still find: this store's claims, at the
|
|
1802
|
-
* generations it took them, and each row at the revision it last saw (none for a new row). */
|
|
1803
|
-
fence(families) {
|
|
1804
|
-
const claims = new Map();
|
|
1805
|
-
const rows = new Map();
|
|
1806
|
-
for (const [id, family] of families) {
|
|
1807
|
-
const pending = this.pendingClaims.get(family);
|
|
1808
|
-
// Generations start at 1, so an unclaimed family's 0 fails the fence as claim-lost.
|
|
1809
|
-
claims.set(family, pending !== undefined ? { take: pending } : { generation: this.claimed.get(family) ?? 0 });
|
|
1810
|
-
rows.set(id, { revision: (this.base.get(id) ?? this.coldBase.get(id))?.revision ?? null, family });
|
|
1811
|
-
}
|
|
1812
|
-
return { owner: this.owner, claims, rows };
|
|
1813
|
-
}
|
|
1814
|
-
/**
|
|
1815
|
-
* Handle a fenced-write conflict. Save unexpected conflict evidence before clearing pending
|
|
1816
|
-
* state or quarantining the row. If evidence persistence fails, retain pending writes. Other
|
|
1817
|
-
* rows remain writable; stale unclaimed reads only fail their write.
|
|
1818
|
-
*/
|
|
1819
|
-
handleConflicts(error, staged) {
|
|
1820
|
-
const unexpected = error.conflicts.filter((conflict) => this.held.has(conflict.id) || this.deleted.has(conflict.id) || this.coldBase.get(conflict.id)?.owned === true);
|
|
1821
|
-
if (unexpected.length === 0 || !this.db || !this.owner)
|
|
1822
|
-
return;
|
|
1823
|
-
const evidence = unexpected.map((conflict) => {
|
|
1824
|
-
const seen = this.base.get(conflict.id) ?? this.coldBase.get(conflict.id);
|
|
1825
|
-
const local = staged.has(conflict.id) ? staged.get(conflict.id) : this.deleted.has(conflict.id) ? null : this.held.get(conflict.id) ?? null;
|
|
1826
|
-
return {
|
|
1827
|
-
runId: conflict.id, reason: conflict.reason,
|
|
1828
|
-
baseRevision: seen?.revision ?? null, baseData: seen?.data ?? null,
|
|
1829
|
-
localData: local === null ? null : JSON.stringify(local), localDeleted: local === null,
|
|
1830
|
-
currentRevision: conflict.current?.revision ?? null, currentData: conflict.current?.data ?? null,
|
|
1831
|
-
};
|
|
1832
|
-
});
|
|
1833
|
-
let seqs;
|
|
1834
|
-
try {
|
|
1835
|
-
seqs = this.db.recordConflicts(this.owner.session, evidence);
|
|
1836
|
-
}
|
|
1837
|
-
catch (evidenceError) {
|
|
1838
|
-
const message = evidenceError instanceof Error ? evidenceError.message : String(evidenceError);
|
|
1839
|
-
console.error(`[hsq] ${RUNS_DB_FILE}: could not record the conflicting write on ${unexpected.map((c) => c.id).join(', ')}; it stays pending: ${message}`);
|
|
1840
|
-
return;
|
|
1841
|
-
}
|
|
1842
|
-
unexpected.forEach((conflict, index) => {
|
|
1843
|
-
const family = this.familyOf(conflict.id);
|
|
1844
|
-
this.liveItems.forget(conflict.id);
|
|
1845
|
-
this.quarantined.add(conflict.id);
|
|
1846
|
-
this.coldReads.forget(conflict.id);
|
|
1847
|
-
this.dirty.delete(conflict.id);
|
|
1848
|
-
this.deleted.delete(conflict.id);
|
|
1849
|
-
this.deletedFamilies.delete(conflict.id);
|
|
1850
|
-
// The delete did not happen, so the history stays with the row.
|
|
1851
|
-
this.historyOwed.delete(conflict.id);
|
|
1852
|
-
if (conflict.reason === 'claim-lost') {
|
|
1853
|
-
this.claimed.delete(family);
|
|
1854
|
-
this.pendingClaims.delete(family);
|
|
1855
|
-
}
|
|
1856
|
-
const decoded = conflict.current ? decodeRunRow(conflict.current.data) : undefined;
|
|
1857
|
-
const current = decoded?.run;
|
|
1858
|
-
if (this.claims.isFallbackRun(conflict.id))
|
|
1859
|
-
this.held.delete(conflict.id);
|
|
1860
|
-
const held = this.held.get(conflict.id);
|
|
1861
|
-
const before = snapshotRun(held ?? staged.get(conflict.id) ?? undefined);
|
|
1862
|
-
if (current && conflict.current) {
|
|
1863
|
-
// The other writer's record as it stands, normalized only as a live owner's run would be.
|
|
1864
|
-
reconcileLoadedRun(current, { keepLive: true });
|
|
1865
|
-
rescopeRun(current, this.repoHandle);
|
|
1866
|
-
if (held)
|
|
1867
|
-
replaceRecord(held, current);
|
|
1868
|
-
this.base.set(conflict.id, { revision: conflict.current.revision, seq: conflict.current.seq, data: conflict.current.data, extras: decoded.extras });
|
|
1869
|
-
publishRunWrite(this.published, held ?? current, before ?? snapshotRun(current), 'conflict');
|
|
1870
|
-
}
|
|
1871
|
-
else {
|
|
1872
|
-
this.held.delete(conflict.id);
|
|
1873
|
-
this.base.delete(conflict.id);
|
|
1874
|
-
this.published.publish('run.deleted', { runId: conflict.id });
|
|
1875
|
-
}
|
|
1876
|
-
console.error(`[hsq] run ${conflict.id} was changed by another writer (${conflict.reason}); this process will not write it again until Squawk restarts. Evidence: ${join(this.dataDir, RUNS_DB_FILE)}, table run_conflicts, seq ${seqs[index]}.`);
|
|
1877
|
-
});
|
|
1878
|
-
this.scheduleSave();
|
|
1879
|
-
}
|
|
1880
|
-
/** Write what is pending, then (unless closing) let every run whose write settled leave memory. */
|
|
1881
|
-
saveNow(evict = true) {
|
|
1882
|
-
if (!this.db || projectWriteRefused(this.dataDir))
|
|
1883
|
-
return;
|
|
1884
|
-
// A second attempt only after a conflict excluded its rows: the unrelated rest goes out at once.
|
|
1885
|
-
for (let attempt = 0; attempt < 2 && (this.dirty.size > 0 || this.deleted.size > 0); attempt++) {
|
|
1886
|
-
const quarantined = this.quarantined.size;
|
|
1887
|
-
try {
|
|
1888
|
-
this.persist(new Map());
|
|
1889
|
-
}
|
|
1890
|
-
catch (err) {
|
|
1891
|
-
if (err instanceof RunConflictError && this.quarantined.size > quarantined)
|
|
1892
|
-
continue;
|
|
1893
|
-
// A pending save may outlive its directory; never recreate it or hide live-directory
|
|
1894
|
-
// failures. The rows stay pending (and held), so the next save or commit retries them.
|
|
1895
|
-
if (existsSync(this.dataDir)) {
|
|
1896
|
-
const message = err instanceof Error ? err.message : String(err);
|
|
1897
|
-
console.error(`[hsq] failed to save ${RUNS_DB_FILE}: ${message}`);
|
|
1898
|
-
}
|
|
1899
|
-
break;
|
|
1900
|
-
}
|
|
1901
|
-
}
|
|
1902
|
-
if (evict)
|
|
1903
|
-
this.evictSettled();
|
|
1904
|
-
}
|
|
1905
1568
|
/**
|
|
1906
1569
|
* Write what is pending and release the database (store disposal, process shutdown).
|
|
1907
1570
|
* Idempotent. A closed store keeps answering reads for what it holds — the final save evicts
|
|
@@ -1914,11 +1577,7 @@ export class RunStore {
|
|
|
1914
1577
|
this.published.publish('store.closed', {});
|
|
1915
1578
|
this.archive.compressor.stop();
|
|
1916
1579
|
this.transcriptFacts.stop();
|
|
1917
|
-
|
|
1918
|
-
clearTimeout(this.saveTimer);
|
|
1919
|
-
this.saveTimer = null;
|
|
1920
|
-
}
|
|
1921
|
-
this.saveNow(false);
|
|
1580
|
+
this.persistence.closeSave();
|
|
1922
1581
|
if (this.db && this.owner) {
|
|
1923
1582
|
// Every claim goes with the store. Should the release fail, the claims stay until this
|
|
1924
1583
|
// process exits; from then on they are provably dead and the next opener takes them.
|