@bastani/atomic 0.9.66-alpha.1 → 0.9.67-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.
@@ -1898,6 +1898,37 @@ class SqlRunJournal {
1898
1898
  return row ? entryFromRow(row) : undefined;
1899
1899
  });
1900
1900
  }
1901
+ static async* readKeyRange(journal, runId, fromKey, toKey) {
1902
+ journal.assertOpen();
1903
+ validateText("runId", runId);
1904
+ validateText("key", fromKey);
1905
+ validateText("key", toKey);
1906
+ if (journal.legacy !== undefined && await journal.operation(() => journal.isUnconvertedLegacyRun(runId))) {
1907
+ const bytes = (key) => Buffer.from(key, "utf8");
1908
+ for await (const entry of journal.read(runId)) {
1909
+ const key = entry.key === undefined ? undefined : bytes(entry.key);
1910
+ if (key !== undefined && Buffer.compare(key, bytes(fromKey)) >= 0 && Buffer.compare(key, bytes(toKey)) < 0)
1911
+ yield entry;
1912
+ }
1913
+ return;
1914
+ }
1915
+ let after;
1916
+ for (;; ) {
1917
+ const page = await journal.operation(async () => {
1918
+ const rows = await journal.database.all(`SELECT * FROM ${journal.tables.events} WHERE ${JOURNAL_COLUMNS.runId} = ? AND ${JOURNAL_COLUMNS.key} ${after === undefined ? ">=" : ">"} ? AND ${JOURNAL_COLUMNS.key} < ? ORDER BY ${JOURNAL_COLUMNS.key} LIMIT ?`, runId, after ?? fromKey, toKey, JOURNAL_READ_PAGE_SIZE);
1919
+ return rows.map(entryFromRow);
1920
+ });
1921
+ for (const entry of page) {
1922
+ journal.assertOpen();
1923
+ yield entry;
1924
+ }
1925
+ journal.assertOpen();
1926
+ const last = page.at(-1);
1927
+ if (last === undefined || page.length < JOURNAL_READ_PAGE_SIZE)
1928
+ return;
1929
+ after = last.key;
1930
+ }
1931
+ }
1901
1932
  async deleteRun(runId) {
1902
1933
  this.assertOpen();
1903
1934
  validateText("runId", runId);
@@ -9374,7 +9405,8 @@ class JournalProjection {
9374
9405
  uiByHash: new Map,
9375
9406
  stageOutputByReplayKey: new Map,
9376
9407
  stageSessionByReplayKey: new Map,
9377
- nestedSnapshotVersion: new NestedSnapshotVersion(handle.workflowId)
9408
+ nestedSnapshotVersion: new NestedSnapshotVersion(handle.workflowId),
9409
+ released: 0
9378
9410
  });
9379
9411
  }
9380
9412
  applyWorkflowSnapshot(handle) {
@@ -9383,7 +9415,7 @@ class JournalProjection {
9383
9415
  const record = this.workflows.get(handle.workflowId);
9384
9416
  record.handle = {
9385
9417
  ...handle,
9386
- completedCheckpoints: Math.max(handle.completedCheckpoints, record.checkpoints.size)
9418
+ completedCheckpoints: Math.max(handle.completedCheckpoints, record.checkpoints.size + record.released)
9387
9419
  };
9388
9420
  }
9389
9421
  async archivePendingStageMessage(workflowId, entry) {
@@ -9439,6 +9471,47 @@ class JournalProjection {
9439
9471
  return this.stickyReceipts.changesSince(workflowId, cursor);
9440
9472
  }
9441
9473
  recordCheckpoint(recorded) {
9474
+ const rec = this.workflows.get(recorded.workflowId);
9475
+ if (!rec)
9476
+ return;
9477
+ const checkpoint = this.index(rec, recorded);
9478
+ if (checkpoint === undefined)
9479
+ return;
9480
+ rec.handle = {
9481
+ ...rec.handle,
9482
+ completedCheckpoints: rec.checkpoints.size + rec.released,
9483
+ updatedAt: checkpoint.completedAt
9484
+ };
9485
+ }
9486
+ countCheckpoint(recorded) {
9487
+ const rec = this.workflows.get(recorded.workflowId);
9488
+ if (!rec)
9489
+ return;
9490
+ rec.released++;
9491
+ rec.handle = {
9492
+ ...rec.handle,
9493
+ completedCheckpoints: rec.checkpoints.size + rec.released,
9494
+ updatedAt: recorded.completedAt
9495
+ };
9496
+ }
9497
+ releaseCheckpoints(workflowId) {
9498
+ const rec = this.workflows.get(workflowId);
9499
+ if (!rec)
9500
+ return;
9501
+ rec.released += rec.checkpoints.size;
9502
+ rec.checkpoints.clear();
9503
+ rec.toolByHash.clear();
9504
+ rec.uiByHash.clear();
9505
+ rec.stageOutputByReplayKey.clear();
9506
+ rec.stageSessionByReplayKey.clear();
9507
+ rec.nestedSnapshotVersion = new NestedSnapshotVersion(workflowId);
9508
+ }
9509
+ restoreCheckpoint(recorded) {
9510
+ const rec = this.workflows.get(recorded.workflowId);
9511
+ if (rec !== undefined && this.index(rec, recorded) !== undefined && rec.released > 0)
9512
+ rec.released--;
9513
+ }
9514
+ index(rec, recorded) {
9442
9515
  const checkpoint = recorded.kind === "stage" ? migrateStageSessionCheckpoint(recorded) : recorded;
9443
9516
  const currentCheckpoint = checkpoint.kind === "stage" && checkpoint.topology === undefined ? {
9444
9517
  ...checkpoint,
@@ -9448,9 +9521,6 @@ class JournalProjection {
9448
9521
  parentIds: []
9449
9522
  }
9450
9523
  } : checkpoint;
9451
- const rec = this.workflows.get(currentCheckpoint.workflowId);
9452
- if (!rec)
9453
- return;
9454
9524
  const key = checkpointKey(currentCheckpoint);
9455
9525
  if (rec.checkpoints.has(key))
9456
9526
  return;
@@ -9473,11 +9543,7 @@ class JournalProjection {
9473
9543
  }
9474
9544
  }
9475
9545
  }
9476
- rec.handle = {
9477
- ...rec.handle,
9478
- completedCheckpoints: rec.checkpoints.size,
9479
- updatedAt: currentCheckpoint.completedAt
9480
- };
9546
+ return currentCheckpoint;
9481
9547
  }
9482
9548
  getToolOutput(workflowId, argsHash) {
9483
9549
  return this.workflows.get(workflowId)?.toolByHash.get(argsHash)?.output;
@@ -11925,6 +11991,25 @@ async function execute(operation) {
11925
11991
  }
11926
11992
  return step.value;
11927
11993
  }
11994
+ function selectsCheckpoint(selection, checkpoint) {
11995
+ const id = checkpoint.checkpointId;
11996
+ return selection.ids.includes(id) || selection.prefixes.some((prefix) => id.startsWith(prefix));
11997
+ }
11998
+ function checkpointEventKey(kind, checkpointId) {
11999
+ return JSON.stringify([RUN_EVENT_TYPES.checkpointRecorded, kind, checkpointId]);
12000
+ }
12001
+ function checkpointKeyRanges(selection) {
12002
+ if (selection.prefixes.some((prefix) => prefix.length === 0 || !/^[\x20-\x7e]+$/.test(prefix)))
12003
+ return;
12004
+ return selection.prefixes.flatMap((prefix) => CHECKPOINT_KINDS.map((kind) => {
12005
+ const from = checkpointEventKey(kind, prefix).slice(0, -2);
12006
+ const to = from.slice(0, -1) + String.fromCharCode(from.charCodeAt(from.length - 1) + 1);
12007
+ return [from, to];
12008
+ }));
12009
+ }
12010
+ function keyRangeJournal(journal) {
12011
+ return typeof journal.readKeyRange === "function" ? journal : undefined;
12012
+ }
11928
12013
 
11929
12014
  class JournalDurableBackend {
11930
12015
  journal;
@@ -11946,6 +12031,7 @@ class JournalDurableBackend {
11946
12031
  catalogQueue = Symbol("catalog");
11947
12032
  lost = new Map;
11948
12033
  prompts = new Map;
12034
+ checkpointSelections = new Map;
11949
12035
  timer;
11950
12036
  state = "open";
11951
12037
  closing;
@@ -12016,7 +12102,11 @@ class JournalDurableBackend {
12016
12102
  if (event.type === RUN_EVENT_TYPES.checkpointRecorded) {
12017
12103
  const checkpoint = event.payload;
12018
12104
  validateCheckpointInvocationFingerprint(checkpoint);
12019
- this.projection.recordCheckpoint(checkpoint);
12105
+ const selection = this.checkpointSelections.get(entry.runId);
12106
+ if (selection === undefined || selectsCheckpoint(selection, checkpoint))
12107
+ this.projection.recordCheckpoint(checkpoint);
12108
+ else
12109
+ this.projection.countCheckpoint(checkpoint);
12020
12110
  } else if (event.type === RUN_EVENT_TYPES.messageSettled) {
12021
12111
  this.projection.archivePendingStageMessage(entry.runId, event.payload.message);
12022
12112
  } else if (event.type === RUN_EVENT_TYPES.messageDelivered) {
@@ -12578,6 +12668,48 @@ class JournalDurableBackend {
12578
12668
  async catchUpWorkflow(runId) {
12579
12669
  await this.serialize(runId, () => this.extend(runId), false);
12580
12670
  }
12671
+ async retainCheckpoints(runId, selection) {
12672
+ await this.serialize(runId, () => this.narrow(runId, selection), false);
12673
+ }
12674
+ *narrow(runId, selection) {
12675
+ this.checkpointSelections.set(runId, selection);
12676
+ this.projection.releaseCheckpoints(runId);
12677
+ const folded = this.sequences.get(runId) ?? 0;
12678
+ if (folded === 0 || selection.ids.length === 0 && selection.prefixes.length === 0)
12679
+ return;
12680
+ for (const entry of yield* this.selectedCheckpoints(runId, selection, folded)) {
12681
+ const checkpoint = entry.event.payload;
12682
+ validateCheckpointInvocationFingerprint(checkpoint);
12683
+ this.projection.restoreCheckpoint(checkpoint);
12684
+ }
12685
+ }
12686
+ *selectedCheckpoints(runId, selection, throughSeq) {
12687
+ return yield* invoke(async () => {
12688
+ const selected = new Map;
12689
+ const keep = (entry) => {
12690
+ const event = entry?.event;
12691
+ if (entry !== undefined && entry.seq <= throughSeq && event?.type === RUN_EVENT_TYPES.checkpointRecorded && selectsCheckpoint(selection, event.payload))
12692
+ selected.set(entry.seq, entry);
12693
+ };
12694
+ const ranged = keyRangeJournal(this.journal);
12695
+ const ranges = ranged === undefined ? undefined : checkpointKeyRanges(selection);
12696
+ if (ranged === undefined || ranges === undefined) {
12697
+ for await (const entry of this.journal.read(runId)) {
12698
+ if (entry.seq > throughSeq)
12699
+ break;
12700
+ keep(entry);
12701
+ }
12702
+ } else {
12703
+ for (const id of selection.ids)
12704
+ for (const kind of CHECKPOINT_KINDS)
12705
+ keep(await this.journal.readKey(runId, checkpointEventKey(kind, id)));
12706
+ for (const [from, to] of ranges)
12707
+ for await (const entry of ranged.readKeyRange(runId, from, to))
12708
+ keep(entry);
12709
+ }
12710
+ return [...selected.values()].sort((left, right) => left.seq - right.seq);
12711
+ });
12712
+ }
12581
12713
  hydrateResumableWorkflows() {
12582
12714
  return this.serialize(this.catalogQueue, () => invoke(async () => {
12583
12715
  const journal = runJournalVersions(this.journal);
@@ -13016,7 +13148,7 @@ function decodePendingStageDeliveries(previous, messages) {
13016
13148
  function hasPendingStageDeliveryDelta(messages) {
13017
13149
  return messages?.some(isDeltaEncoded) === true;
13018
13150
  }
13019
- var PROCESS_HOLDER_ID, CHANGE_APPEND_ATTEMPTS = 4, APPEND_BATCH_LIMIT = 256, processExitCleanups, TURN_BUDGET_MS = 8, FAN_OUT_WAITING_OPERATIONS = 32, turnStartedAt, runInJournalTurns, CUSTOM_JOURNAL, JournalOwnershipError, JournalBackendClosedError, JournalOperationAbortedError, JournalExecutionRetiredError, JournalMessageScopeError, entryIdentity, entryJson;
13151
+ var PROCESS_HOLDER_ID, CHANGE_APPEND_ATTEMPTS = 4, APPEND_BATCH_LIMIT = 256, processExitCleanups, TURN_BUDGET_MS = 8, FAN_OUT_WAITING_OPERATIONS = 32, turnStartedAt, runInJournalTurns, CUSTOM_JOURNAL, JournalOwnershipError, JournalBackendClosedError, JournalOperationAbortedError, JournalExecutionRetiredError, JournalMessageScopeError, CHECKPOINT_KINDS, entryIdentity, entryJson;
13020
13152
  var init_journal_backend = __esm(() => {
13021
13153
  init_workflow_instance_ownership_error();
13022
13154
  init_backend();
@@ -13076,6 +13208,7 @@ var init_journal_backend = __esm(() => {
13076
13208
  this.name = "JournalMessageScopeError";
13077
13209
  }
13078
13210
  };
13211
+ CHECKPOINT_KINDS = ["tool", "ui", "stage"];
13079
13212
  entryIdentity = new WeakMap;
13080
13213
  entryJson = new WeakMap;
13081
13214
  });
@@ -66071,6 +66204,7 @@ class PoolCoordinator {
66071
66204
  closed = false;
66072
66205
  closing;
66073
66206
  replacements = 0;
66207
+ recycleLimitReported = false;
66074
66208
  rootLeaseLost = false;
66075
66209
  lateRoot;
66076
66210
  attemptBase = new Map;
@@ -66749,7 +66883,8 @@ class PoolCoordinator {
66749
66883
  definitions: this.sources,
66750
66884
  admission: options.admission,
66751
66885
  ...this.promptNodes ? { promptNodes: true } : {},
66752
- ...options.stageStartMaxLoadPerCpu === undefined ? {} : { stageStartMaxLoadPerCpu: options.stageStartMaxLoadPerCpu }
66886
+ ...options.stageStartMaxLoadPerCpu === undefined ? {} : { stageStartMaxLoadPerCpu: options.stageStartMaxLoadPerCpu },
66887
+ ...options.maxWorkerRssBytes === undefined ? {} : { maxRssBytes: options.maxWorkerRssBytes }
66753
66888
  })
66754
66889
  ], {
66755
66890
  stdio: ["ignore", "ignore", "pipe", "ipc"],
@@ -66859,6 +66994,8 @@ class PoolCoordinator {
66859
66994
  this.held.delete(held.id);
66860
66995
  }
66861
66996
  }).then(async () => {
66997
+ if (slot.recycled === true && slot.work === undefined && child.exitCode === 0 && !this.keptLogs.has(logPath))
66998
+ await rm3(logPath, { force: true }).catch(() => {});
66862
66999
  if (this.closed || !ready || this.desiredControl === "quit" || this.rootLeaseLost)
66863
67000
  return;
66864
67001
  let work = slot.work;
@@ -66877,7 +67014,9 @@ class PoolCoordinator {
66877
67014
  const superseded = work !== undefined && !settled && await this.superseded(work);
66878
67015
  if (work !== undefined && exhausted && !superseded)
66879
67016
  this.failWork(work, diagnosed(`${childRetryLimit(work, "lost its worker")}${unconfirmed === undefined ? "" : `; ${unconfirmed.message}`}`));
66880
- if (work === undefined && ++this.replacements > 3)
67017
+ if (work === undefined && slot.recycled === true)
67018
+ await this.spawn();
67019
+ else if (work === undefined && ++this.replacements > 3)
66881
67020
  this.fail(diagnosed("Local worker retry limit"));
66882
67021
  else
66883
67022
  await this.spawn();
@@ -66977,6 +67116,19 @@ class PoolCoordinator {
66977
67116
  this.controlAcks.set(worker, Math.max(this.controlAcks.get(worker) ?? -1, message.revision));
66978
67117
  return;
66979
67118
  }
67119
+ if (message.kind === "recycle") {
67120
+ if (slot.work)
67121
+ throw new Error("Worker holds an attempt");
67122
+ slot.recycled = true;
67123
+ if (message.attempts <= 1 && !this.recycleLimitReported) {
67124
+ this.recycleLimitReported = true;
67125
+ this.port.send({
67126
+ kind: "health",
67127
+ message: `localWorkers.maxWorkerRssBytes (${options.maxWorkerRssBytes} bytes) is below the resident memory of a worker that ran one child (${message.rssBytes} bytes), so every worker is replaced after each child it runs; set it well above that`
67128
+ });
67129
+ }
67130
+ return;
67131
+ }
66980
67132
  if (message.kind === "claim") {
66981
67133
  if (slot.work)
66982
67134
  throw new Error("Worker already holds an attempt");
@@ -69318,6 +69470,8 @@ class LocalWorkerPool {
69318
69470
  throw new Error(`Invalid local worker lease: must be an integer from ${MINIMUM_WORK_LEASE_MS} to ${MAX_TIMER_DELAY_MS} ms`);
69319
69471
  if (options.maxLoadPerCpu !== undefined && (!Number.isFinite(options.maxLoadPerCpu) || options.maxLoadPerCpu < 0))
69320
69472
  throw new Error("Invalid local worker load threshold: maxLoadPerCpu must be a number of at least 0");
69473
+ if (options.maxWorkerRssBytes !== undefined && (!Number.isSafeInteger(options.maxWorkerRssBytes) || options.maxWorkerRssBytes < 1))
69474
+ throw new Error("Invalid local worker memory limit: maxWorkerRssBytes must be a positive integer");
69321
69475
  this.leaseMs = options.leaseMs ?? DEFAULT_WORK_LEASE_MS;
69322
69476
  this.releaseBinding = bindChildWorkerDispatcher(backend, this, options.rootId);
69323
69477
  if (options.admission && options.rootId === undefined)
@@ -69371,6 +69525,7 @@ class LocalWorkerPool {
69371
69525
  startupTimeoutMs: this.options.startupTimeoutMs ?? defaultStartupTimeoutMs(this.options.workers),
69372
69526
  ...this.options.admission === undefined ? {} : { admission: this.options.admission },
69373
69527
  ...this.options.maxLoadPerCpu === undefined ? {} : { stageStartMaxLoadPerCpu: this.options.maxLoadPerCpu },
69528
+ ...this.options.maxWorkerRssBytes === undefined ? {} : { maxWorkerRssBytes: this.options.maxWorkerRssBytes },
69374
69529
  ...workerEntry === undefined ? {} : { workerEntry }
69375
69530
  },
69376
69531
  ...this.desiredControl === undefined ? {} : { control: this.desiredControl }
@@ -70510,6 +70665,7 @@ async function activatePublicPool(backend, options) {
70510
70665
  startupTimeoutMs: undefined,
70511
70666
  leaseMs: undefined,
70512
70667
  maxLoadPerCpu: undefined,
70668
+ maxWorkerRssBytes: undefined,
70513
70669
  definitions: options.localWorkers.definitions.map((source) => ({ ...source, path: resolve16(cwd, source.path) }))
70514
70670
  };
70515
70671
  const admission = options.admission && {
@@ -70556,6 +70712,7 @@ async function activatePublicPool(backend, options) {
70556
70712
  startupTimeoutMs: options.localWorkers?.startupTimeoutMs,
70557
70713
  leaseMs: options.localWorkers?.leaseMs,
70558
70714
  maxLoadPerCpu: options.localWorkers?.maxLoadPerCpu ?? DEFAULT_POOLED_STAGE_START_MAX_LOAD_PER_CPU,
70715
+ ...options.localWorkers?.maxWorkerRssBytes === undefined ? {} : { maxWorkerRssBytes: options.localWorkers.maxWorkerRssBytes },
70559
70716
  ...options.acceptEntryChanges === true ? { acceptEntryChanges: true } : {},
70560
70717
  ...options.stageControlRegistry === undefined || options[hostWorkerBindings] ? {} : { stageControlRegistry: options.stageControlRegistry }
70561
70718
  });