@bastani/atomic 0.9.66 → 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.
@@ -853,7 +853,8 @@ class JournalProjection {
853
853
  uiByHash: new Map,
854
854
  stageOutputByReplayKey: new Map,
855
855
  stageSessionByReplayKey: new Map,
856
- nestedSnapshotVersion: new NestedSnapshotVersion(handle.workflowId)
856
+ nestedSnapshotVersion: new NestedSnapshotVersion(handle.workflowId),
857
+ released: 0
857
858
  });
858
859
  }
859
860
  applyWorkflowSnapshot(handle) {
@@ -862,7 +863,7 @@ class JournalProjection {
862
863
  const record = this.workflows.get(handle.workflowId);
863
864
  record.handle = {
864
865
  ...handle,
865
- completedCheckpoints: Math.max(handle.completedCheckpoints, record.checkpoints.size)
866
+ completedCheckpoints: Math.max(handle.completedCheckpoints, record.checkpoints.size + record.released)
866
867
  };
867
868
  }
868
869
  async archivePendingStageMessage(workflowId, entry) {
@@ -918,6 +919,47 @@ class JournalProjection {
918
919
  return this.stickyReceipts.changesSince(workflowId, cursor);
919
920
  }
920
921
  recordCheckpoint(recorded) {
922
+ const rec = this.workflows.get(recorded.workflowId);
923
+ if (!rec)
924
+ return;
925
+ const checkpoint = this.index(rec, recorded);
926
+ if (checkpoint === undefined)
927
+ return;
928
+ rec.handle = {
929
+ ...rec.handle,
930
+ completedCheckpoints: rec.checkpoints.size + rec.released,
931
+ updatedAt: checkpoint.completedAt
932
+ };
933
+ }
934
+ countCheckpoint(recorded) {
935
+ const rec = this.workflows.get(recorded.workflowId);
936
+ if (!rec)
937
+ return;
938
+ rec.released++;
939
+ rec.handle = {
940
+ ...rec.handle,
941
+ completedCheckpoints: rec.checkpoints.size + rec.released,
942
+ updatedAt: recorded.completedAt
943
+ };
944
+ }
945
+ releaseCheckpoints(workflowId) {
946
+ const rec = this.workflows.get(workflowId);
947
+ if (!rec)
948
+ return;
949
+ rec.released += rec.checkpoints.size;
950
+ rec.checkpoints.clear();
951
+ rec.toolByHash.clear();
952
+ rec.uiByHash.clear();
953
+ rec.stageOutputByReplayKey.clear();
954
+ rec.stageSessionByReplayKey.clear();
955
+ rec.nestedSnapshotVersion = new NestedSnapshotVersion(workflowId);
956
+ }
957
+ restoreCheckpoint(recorded) {
958
+ const rec = this.workflows.get(recorded.workflowId);
959
+ if (rec !== undefined && this.index(rec, recorded) !== undefined && rec.released > 0)
960
+ rec.released--;
961
+ }
962
+ index(rec, recorded) {
921
963
  const checkpoint = recorded.kind === "stage" ? migrateStageSessionCheckpoint(recorded) : recorded;
922
964
  const currentCheckpoint = checkpoint.kind === "stage" && checkpoint.topology === undefined ? {
923
965
  ...checkpoint,
@@ -927,9 +969,6 @@ class JournalProjection {
927
969
  parentIds: []
928
970
  }
929
971
  } : checkpoint;
930
- const rec = this.workflows.get(currentCheckpoint.workflowId);
931
- if (!rec)
932
- return;
933
972
  const key = checkpointKey(currentCheckpoint);
934
973
  if (rec.checkpoints.has(key))
935
974
  return;
@@ -952,11 +991,7 @@ class JournalProjection {
952
991
  }
953
992
  }
954
993
  }
955
- rec.handle = {
956
- ...rec.handle,
957
- completedCheckpoints: rec.checkpoints.size,
958
- updatedAt: currentCheckpoint.completedAt
959
- };
994
+ return currentCheckpoint;
960
995
  }
961
996
  getToolOutput(workflowId, argsHash) {
962
997
  return this.workflows.get(workflowId)?.toolByHash.get(argsHash)?.output;
@@ -2027,6 +2062,25 @@ async function execute(operation) {
2027
2062
  }
2028
2063
  return step.value;
2029
2064
  }
2065
+ function selectsCheckpoint(selection, checkpoint) {
2066
+ const id = checkpoint.checkpointId;
2067
+ return selection.ids.includes(id) || selection.prefixes.some((prefix) => id.startsWith(prefix));
2068
+ }
2069
+ function checkpointEventKey(kind, checkpointId) {
2070
+ return JSON.stringify([RUN_EVENT_TYPES.checkpointRecorded, kind, checkpointId]);
2071
+ }
2072
+ function checkpointKeyRanges(selection) {
2073
+ if (selection.prefixes.some((prefix) => prefix.length === 0 || !/^[\x20-\x7e]+$/.test(prefix)))
2074
+ return;
2075
+ return selection.prefixes.flatMap((prefix) => CHECKPOINT_KINDS.map((kind) => {
2076
+ const from = checkpointEventKey(kind, prefix).slice(0, -2);
2077
+ const to = from.slice(0, -1) + String.fromCharCode(from.charCodeAt(from.length - 1) + 1);
2078
+ return [from, to];
2079
+ }));
2080
+ }
2081
+ function keyRangeJournal(journal) {
2082
+ return typeof journal.readKeyRange === "function" ? journal : undefined;
2083
+ }
2030
2084
 
2031
2085
  class JournalDurableBackend {
2032
2086
  journal;
@@ -2048,6 +2102,7 @@ class JournalDurableBackend {
2048
2102
  catalogQueue = Symbol("catalog");
2049
2103
  lost = new Map;
2050
2104
  prompts = new Map;
2105
+ checkpointSelections = new Map;
2051
2106
  timer;
2052
2107
  state = "open";
2053
2108
  closing;
@@ -2118,7 +2173,11 @@ class JournalDurableBackend {
2118
2173
  if (event.type === RUN_EVENT_TYPES.checkpointRecorded) {
2119
2174
  const checkpoint = event.payload;
2120
2175
  validateCheckpointInvocationFingerprint(checkpoint);
2121
- this.projection.recordCheckpoint(checkpoint);
2176
+ const selection = this.checkpointSelections.get(entry.runId);
2177
+ if (selection === undefined || selectsCheckpoint(selection, checkpoint))
2178
+ this.projection.recordCheckpoint(checkpoint);
2179
+ else
2180
+ this.projection.countCheckpoint(checkpoint);
2122
2181
  } else if (event.type === RUN_EVENT_TYPES.messageSettled) {
2123
2182
  this.projection.archivePendingStageMessage(entry.runId, event.payload.message);
2124
2183
  } else if (event.type === RUN_EVENT_TYPES.messageDelivered) {
@@ -2680,6 +2739,48 @@ class JournalDurableBackend {
2680
2739
  async catchUpWorkflow(runId) {
2681
2740
  await this.serialize(runId, () => this.extend(runId), false);
2682
2741
  }
2742
+ async retainCheckpoints(runId, selection) {
2743
+ await this.serialize(runId, () => this.narrow(runId, selection), false);
2744
+ }
2745
+ *narrow(runId, selection) {
2746
+ this.checkpointSelections.set(runId, selection);
2747
+ this.projection.releaseCheckpoints(runId);
2748
+ const folded = this.sequences.get(runId) ?? 0;
2749
+ if (folded === 0 || selection.ids.length === 0 && selection.prefixes.length === 0)
2750
+ return;
2751
+ for (const entry of yield* this.selectedCheckpoints(runId, selection, folded)) {
2752
+ const checkpoint = entry.event.payload;
2753
+ validateCheckpointInvocationFingerprint(checkpoint);
2754
+ this.projection.restoreCheckpoint(checkpoint);
2755
+ }
2756
+ }
2757
+ *selectedCheckpoints(runId, selection, throughSeq) {
2758
+ return yield* invoke(async () => {
2759
+ const selected = new Map;
2760
+ const keep = (entry) => {
2761
+ const event = entry?.event;
2762
+ if (entry !== undefined && entry.seq <= throughSeq && event?.type === RUN_EVENT_TYPES.checkpointRecorded && selectsCheckpoint(selection, event.payload))
2763
+ selected.set(entry.seq, entry);
2764
+ };
2765
+ const ranged = keyRangeJournal(this.journal);
2766
+ const ranges = ranged === undefined ? undefined : checkpointKeyRanges(selection);
2767
+ if (ranged === undefined || ranges === undefined) {
2768
+ for await (const entry of this.journal.read(runId)) {
2769
+ if (entry.seq > throughSeq)
2770
+ break;
2771
+ keep(entry);
2772
+ }
2773
+ } else {
2774
+ for (const id of selection.ids)
2775
+ for (const kind of CHECKPOINT_KINDS)
2776
+ keep(await this.journal.readKey(runId, checkpointEventKey(kind, id)));
2777
+ for (const [from, to] of ranges)
2778
+ for await (const entry of ranged.readKeyRange(runId, from, to))
2779
+ keep(entry);
2780
+ }
2781
+ return [...selected.values()].sort((left, right) => left.seq - right.seq);
2782
+ });
2783
+ }
2683
2784
  hydrateResumableWorkflows() {
2684
2785
  return this.serialize(this.catalogQueue, () => invoke(async () => {
2685
2786
  const journal = runJournalVersions(this.journal);
@@ -3118,7 +3219,7 @@ function decodePendingStageDeliveries(previous, messages) {
3118
3219
  function hasPendingStageDeliveryDelta(messages) {
3119
3220
  return messages?.some(isDeltaEncoded) === true;
3120
3221
  }
3121
- 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;
3222
+ 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;
3122
3223
  var init_journal_backend = __esm(() => {
3123
3224
  init_workflow_instance_ownership_error();
3124
3225
  init_backend();
@@ -3178,6 +3279,7 @@ var init_journal_backend = __esm(() => {
3178
3279
  this.name = "JournalMessageScopeError";
3179
3280
  }
3180
3281
  };
3282
+ CHECKPOINT_KINDS = ["tool", "ui", "stage"];
3181
3283
  entryIdentity = new WeakMap;
3182
3284
  entryJson = new WeakMap;
3183
3285
  });
@@ -3741,6 +3843,37 @@ class SqlRunJournal {
3741
3843
  return row ? entryFromRow(row) : undefined;
3742
3844
  });
3743
3845
  }
3846
+ static async* readKeyRange(journal, runId, fromKey, toKey) {
3847
+ journal.assertOpen();
3848
+ validateText("runId", runId);
3849
+ validateText("key", fromKey);
3850
+ validateText("key", toKey);
3851
+ if (journal.legacy !== undefined && await journal.operation(() => journal.isUnconvertedLegacyRun(runId))) {
3852
+ const bytes = (key) => Buffer.from(key, "utf8");
3853
+ for await (const entry of journal.read(runId)) {
3854
+ const key = entry.key === undefined ? undefined : bytes(entry.key);
3855
+ if (key !== undefined && Buffer.compare(key, bytes(fromKey)) >= 0 && Buffer.compare(key, bytes(toKey)) < 0)
3856
+ yield entry;
3857
+ }
3858
+ return;
3859
+ }
3860
+ let after;
3861
+ for (;; ) {
3862
+ const page = await journal.operation(async () => {
3863
+ 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);
3864
+ return rows.map(entryFromRow);
3865
+ });
3866
+ for (const entry of page) {
3867
+ journal.assertOpen();
3868
+ yield entry;
3869
+ }
3870
+ journal.assertOpen();
3871
+ const last = page.at(-1);
3872
+ if (last === undefined || page.length < JOURNAL_READ_PAGE_SIZE)
3873
+ return;
3874
+ after = last.key;
3875
+ }
3876
+ }
3744
3877
  async deleteRun(runId) {
3745
3878
  this.assertOpen();
3746
3879
  validateText("runId", runId);
@@ -65960,6 +66093,7 @@ class PoolCoordinator {
65960
66093
  closed = false;
65961
66094
  closing;
65962
66095
  replacements = 0;
66096
+ recycleLimitReported = false;
65963
66097
  rootLeaseLost = false;
65964
66098
  lateRoot;
65965
66099
  attemptBase = new Map;
@@ -66638,7 +66772,8 @@ class PoolCoordinator {
66638
66772
  definitions: this.sources,
66639
66773
  admission: options.admission,
66640
66774
  ...this.promptNodes ? { promptNodes: true } : {},
66641
- ...options.stageStartMaxLoadPerCpu === undefined ? {} : { stageStartMaxLoadPerCpu: options.stageStartMaxLoadPerCpu }
66775
+ ...options.stageStartMaxLoadPerCpu === undefined ? {} : { stageStartMaxLoadPerCpu: options.stageStartMaxLoadPerCpu },
66776
+ ...options.maxWorkerRssBytes === undefined ? {} : { maxRssBytes: options.maxWorkerRssBytes }
66642
66777
  })
66643
66778
  ], {
66644
66779
  stdio: ["ignore", "ignore", "pipe", "ipc"],
@@ -66748,6 +66883,8 @@ class PoolCoordinator {
66748
66883
  this.held.delete(held.id);
66749
66884
  }
66750
66885
  }).then(async () => {
66886
+ if (slot.recycled === true && slot.work === undefined && child.exitCode === 0 && !this.keptLogs.has(logPath))
66887
+ await rm3(logPath, { force: true }).catch(() => {});
66751
66888
  if (this.closed || !ready || this.desiredControl === "quit" || this.rootLeaseLost)
66752
66889
  return;
66753
66890
  let work = slot.work;
@@ -66766,7 +66903,9 @@ class PoolCoordinator {
66766
66903
  const superseded = work !== undefined && !settled && await this.superseded(work);
66767
66904
  if (work !== undefined && exhausted && !superseded)
66768
66905
  this.failWork(work, diagnosed(`${childRetryLimit(work, "lost its worker")}${unconfirmed === undefined ? "" : `; ${unconfirmed.message}`}`));
66769
- if (work === undefined && ++this.replacements > 3)
66906
+ if (work === undefined && slot.recycled === true)
66907
+ await this.spawn();
66908
+ else if (work === undefined && ++this.replacements > 3)
66770
66909
  this.fail(diagnosed("Local worker retry limit"));
66771
66910
  else
66772
66911
  await this.spawn();
@@ -66866,6 +67005,19 @@ class PoolCoordinator {
66866
67005
  this.controlAcks.set(worker, Math.max(this.controlAcks.get(worker) ?? -1, message.revision));
66867
67006
  return;
66868
67007
  }
67008
+ if (message.kind === "recycle") {
67009
+ if (slot.work)
67010
+ throw new Error("Worker holds an attempt");
67011
+ slot.recycled = true;
67012
+ if (message.attempts <= 1 && !this.recycleLimitReported) {
67013
+ this.recycleLimitReported = true;
67014
+ this.port.send({
67015
+ kind: "health",
67016
+ 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`
67017
+ });
67018
+ }
67019
+ return;
67020
+ }
66869
67021
  if (message.kind === "claim") {
66870
67022
  if (slot.work)
66871
67023
  throw new Error("Worker already holds an attempt");
@@ -69233,6 +69385,8 @@ class LocalWorkerPool {
69233
69385
  throw new Error(`Invalid local worker lease: must be an integer from ${MINIMUM_WORK_LEASE_MS} to ${MAX_TIMER_DELAY_MS} ms`);
69234
69386
  if (options.maxLoadPerCpu !== undefined && (!Number.isFinite(options.maxLoadPerCpu) || options.maxLoadPerCpu < 0))
69235
69387
  throw new Error("Invalid local worker load threshold: maxLoadPerCpu must be a number of at least 0");
69388
+ if (options.maxWorkerRssBytes !== undefined && (!Number.isSafeInteger(options.maxWorkerRssBytes) || options.maxWorkerRssBytes < 1))
69389
+ throw new Error("Invalid local worker memory limit: maxWorkerRssBytes must be a positive integer");
69236
69390
  this.leaseMs = options.leaseMs ?? DEFAULT_WORK_LEASE_MS;
69237
69391
  this.releaseBinding = bindChildWorkerDispatcher(backend, this, options.rootId);
69238
69392
  if (options.admission && options.rootId === undefined)
@@ -69286,6 +69440,7 @@ class LocalWorkerPool {
69286
69440
  startupTimeoutMs: this.options.startupTimeoutMs ?? defaultStartupTimeoutMs(this.options.workers),
69287
69441
  ...this.options.admission === undefined ? {} : { admission: this.options.admission },
69288
69442
  ...this.options.maxLoadPerCpu === undefined ? {} : { stageStartMaxLoadPerCpu: this.options.maxLoadPerCpu },
69443
+ ...this.options.maxWorkerRssBytes === undefined ? {} : { maxWorkerRssBytes: this.options.maxWorkerRssBytes },
69289
69444
  ...workerEntry === undefined ? {} : { workerEntry }
69290
69445
  },
69291
69446
  ...this.desiredControl === undefined ? {} : { control: this.desiredControl }
@@ -70425,6 +70580,7 @@ async function activatePublicPool(backend, options) {
70425
70580
  startupTimeoutMs: undefined,
70426
70581
  leaseMs: undefined,
70427
70582
  maxLoadPerCpu: undefined,
70583
+ maxWorkerRssBytes: undefined,
70428
70584
  definitions: options.localWorkers.definitions.map((source) => ({ ...source, path: resolve15(cwd, source.path) }))
70429
70585
  };
70430
70586
  const admission = options.admission && {
@@ -70471,6 +70627,7 @@ async function activatePublicPool(backend, options) {
70471
70627
  startupTimeoutMs: options.localWorkers?.startupTimeoutMs,
70472
70628
  leaseMs: options.localWorkers?.leaseMs,
70473
70629
  maxLoadPerCpu: options.localWorkers?.maxLoadPerCpu ?? DEFAULT_POOLED_STAGE_START_MAX_LOAD_PER_CPU,
70630
+ ...options.localWorkers?.maxWorkerRssBytes === undefined ? {} : { maxWorkerRssBytes: options.localWorkers.maxWorkerRssBytes },
70474
70631
  ...options.acceptEntryChanges === true ? { acceptEntryChanges: true } : {},
70475
70632
  ...options.stageControlRegistry === undefined || options[hostWorkerBindings] ? {} : { stageControlRegistry: options.stageControlRegistry }
70476
70633
  });
@@ -80928,6 +81085,7 @@ var init_pool_journal = __esm(() => {
80928
81085
  init_internal();
80929
81086
  init_journal_backend();
80930
81087
  init_resolution();
81088
+ init_sql_run_journal();
80931
81089
  init_pool_journal();
80932
81090
  init_workflows_host_module();
80933
81091
  init_run();
@@ -81879,12 +82037,12 @@ class WorkAttemptFencedError extends Error {
81879
82037
  this.name = "WorkAttemptFencedError";
81880
82038
  }
81881
82039
  }
81882
- var FENCED_STAGE_CLOSE_MS = 1e4;
82040
+ var ATTEMPT_STAGE_CLOSE_MS = 1e4;
81883
82041
  async function closeAttemptStages(stageControls, store, renew) {
81884
82042
  const closing = Promise.allSettled(store.runs().map((run) => stageControls.clear(run.id))).then((results) => {
81885
82043
  for (const result of results)
81886
82044
  if (result.status === "rejected")
81887
- console.warn("atomic-workflows: a fenced attempt's stage session did not close", result.reason);
82045
+ console.warn("atomic-workflows: an attempt's stage session did not close", result.reason);
81888
82046
  });
81889
82047
  let renewal;
81890
82048
  const pulse = () => {
@@ -81896,7 +82054,7 @@ async function closeAttemptStages(stageControls, store, renew) {
81896
82054
  const heartbeat = setInterval(pulse, WORKER_HEARTBEAT_INTERVAL_MS);
81897
82055
  const bound = new AbortController;
81898
82056
  try {
81899
- await Promise.race([closing, delay4(FENCED_STAGE_CLOSE_MS, undefined, { signal: bound.signal }).catch(() => {})]);
82057
+ await Promise.race([closing, delay4(ATTEMPT_STAGE_CLOSE_MS, undefined, { signal: bound.signal }).catch(() => {})]);
81900
82058
  } finally {
81901
82059
  clearInterval(heartbeat);
81902
82060
  bound.abort();
@@ -81957,6 +82115,21 @@ function failablePrompts(store) {
81957
82115
  return true;
81958
82116
  };
81959
82117
  }
82118
+ var NO_CHECKPOINTS = { ids: [], prefixes: [] };
82119
+ function attemptCheckpoints(scope) {
82120
+ return { ids: [`boundary-start:${scope}`], prefixes: [`${scope}:`, `boundary-terminal:${scope}:`] };
82121
+ }
82122
+ function releasableAdmission(admission) {
82123
+ let current = admission;
82124
+ return {
82125
+ admission: {
82126
+ acquire: (kind, signal, options) => current === undefined ? Promise.reject(new WorkAttemptFencedError("Work attempt ended")) : current.acquire(kind, signal, options)
82127
+ },
82128
+ release() {
82129
+ current = undefined;
82130
+ }
82131
+ };
82132
+ }
81960
82133
  async function runLocalWorker(start) {
81961
82134
  if ("role" in start && start.role === POOL_COORDINATOR_ROLE) {
81962
82135
  await Promise.resolve().then(() => init_pool_coordinator());
@@ -82007,7 +82180,8 @@ async function runWorker(start) {
82007
82180
  else
82008
82181
  receiver?.resolve(reply.value);
82009
82182
  });
82010
- process.on("disconnect", () => process.exit(rootLeaseLost ? 0 : 1));
82183
+ let recycled = false;
82184
+ process.on("disconnect", () => process.exit(rootLeaseLost || recycled ? 0 : 1));
82011
82185
  const request = (message, deliver) => new Promise((resolve, reject) => {
82012
82186
  const id = ++sequence;
82013
82187
  pending.set(id, { resolve, reject, deliver });
@@ -82024,6 +82198,8 @@ async function runWorker(start) {
82024
82198
  const journalReads = new Set(["descriptor", "getRun", "listRuns", "read", "readKey", "leaseState", "close"]);
82025
82199
  const readOnlyJournal = new Proxy(journal, {
82026
82200
  get(target, key) {
82201
+ if (key === "readKeyRange")
82202
+ return target instanceof SqlRunJournal ? (runId, fromKey, toKey) => SqlRunJournal.readKeyRange(target, runId, fromKey, toKey) : undefined;
82027
82203
  if (typeof key !== "string" || !journalReads.has(key))
82028
82204
  return () => {
82029
82205
  throw new Error(`Worker journal is read-only: ${String(key)}`);
@@ -82033,6 +82209,7 @@ async function runWorker(start) {
82033
82209
  }
82034
82210
  });
82035
82211
  const reader = await JournalDurableBackend.open(readOnlyJournal, { runs: [] });
82212
+ await reader.retainCheckpoints(start.root, NO_CHECKPOINTS);
82036
82213
  configurePooledWatchTrace(start.journalPath, `worker:${process.pid}`);
82037
82214
  const sessions = await new StorageProvider3().openSessionStore({ kind: "sqlite", path: start.journalPath, prefix: `${sqlPoolStorage(poolJournal).tables.runs}_pool_` }, { agentDir: "", domain: "sessions" });
82038
82215
  const commit = poolWorkerCommit({
@@ -82096,6 +82273,7 @@ async function runWorker(start) {
82096
82273
  });
82097
82274
  try {
82098
82275
  let controlRevision = -1;
82276
+ let attempts = 0;
82099
82277
  let controlState = "running";
82100
82278
  let currentStore = createStore();
82101
82279
  let activeController;
@@ -82148,6 +82326,7 @@ async function runWorker(start) {
82148
82326
  const index = start.definitions.findIndex((source) => `${source.path}#${source.exportName}` === work.definition && source.digest === work.digest);
82149
82327
  if (index < 0)
82150
82328
  throw new Error("Worker definition compatibility error");
82329
+ await reader.retainCheckpoints(start.root, attemptCheckpoints(work.scope));
82151
82330
  await reader.catchUpWorkflow(start.root);
82152
82331
  const controller = new AbortController;
82153
82332
  activeController = controller;
@@ -82249,7 +82428,8 @@ async function runWorker(start) {
82249
82428
  }
82250
82429
  }
82251
82430
  };
82252
- const admitted = admittedSessionAdapter(adapter, resourceAdmission, async (signal) => {
82431
+ const attemptAdmission = releasableAdmission(resourceAdmission);
82432
+ const admitted = admittedSessionAdapter(adapter, attemptAdmission.admission, async (signal) => {
82253
82433
  await awaitAdmission(signal);
82254
82434
  await admission?.validate(signal);
82255
82435
  });
@@ -82283,7 +82463,7 @@ async function runWorker(start) {
82283
82463
  controller.signal.throwIfAborted();
82284
82464
  await delay4(25);
82285
82465
  }
82286
- const result = await withResourceAdmission2(resourceAdmission, () => run(definitions[index], work.inputs, {
82466
+ const result = await withResourceAdmission2(attemptAdmission.admission, () => run(definitions[index], work.inputs, {
82287
82467
  ...work.execution,
82288
82468
  ...start.promptNodes === true ? { usePromptNodesForUi: true } : {},
82289
82469
  runId: work.childRunId,
@@ -82325,6 +82505,8 @@ async function runWorker(start) {
82325
82505
  attemptFenced = true;
82326
82506
  throw new WorkAttemptFencedError(poolFault);
82327
82507
  }
82508
+ await closeAttemptStages(stageControls, store, () => request({ kind: "renew" }));
82509
+ writable = false;
82328
82510
  await request({ kind: "complete", result });
82329
82511
  } catch (error) {
82330
82512
  if (!attemptFenced)
@@ -82346,8 +82528,20 @@ async function runWorker(start) {
82346
82528
  writable = false;
82347
82529
  await request({ kind: "fenced", ...poolFault === undefined ? {} : { fault: poolFault } });
82348
82530
  }
82531
+ attemptAdmission.release();
82532
+ reservations.clear();
82533
+ attempts++;
82534
+ await reader.retainCheckpoints(start.root, NO_CHECKPOINTS);
82349
82535
  if (rootLeaseLost)
82350
82536
  break;
82537
+ const rssBytes = process.memoryUsage.rss();
82538
+ if (start.maxRssBytes !== undefined && rssBytes > start.maxRssBytes) {
82539
+ await request({ kind: "recycle", rssBytes, attempts });
82540
+ process.stderr.write(`atomic-workflows: local worker ${process.pid} ends between children: resident memory ${rssBytes} bytes is over localWorkers.maxWorkerRssBytes (${start.maxRssBytes}); the pool starts a fresh worker
82541
+ `);
82542
+ recycled = true;
82543
+ break;
82544
+ }
82351
82545
  }
82352
82546
  } catch (error) {
82353
82547
  if (!rootLeaseLost)
@@ -82358,7 +82552,7 @@ async function runWorker(start) {
82358
82552
  if (poolJournal !== journal)
82359
82553
  await poolJournal.close().catch(() => {});
82360
82554
  }
82361
- if (rootLeaseLost)
82555
+ if (rootLeaseLost || recycled)
82362
82556
  process.disconnect?.();
82363
82557
  }
82364
82558
 
@@ -29,6 +29,13 @@ export interface LocalWorkerOptions {
29
29
  * off. Not saved with the root.
30
30
  */
31
31
  readonly maxLoadPerCpu?: number;
32
+ /**
33
+ * Resident memory, in bytes, past which a local worker is replaced once the child it runs ends: the worker exits
34
+ * cleanly between children and the pool starts a fresh one in its place, so whatever memory a long-lived worker
35
+ * accumulated goes back to the system. A running child is never interrupted. Unset: workers are never replaced for
36
+ * their memory. Not saved with the root.
37
+ */
38
+ readonly maxWorkerRssBytes?: number;
32
39
  }
33
40
  /** Load per CPU above which pooled stages wait to start, unless `localWorkers.maxLoadPerCpu` says otherwise. */
34
41
  export declare const DEFAULT_POOLED_STAGE_START_MAX_LOAD_PER_CPU = 3;
@@ -277,6 +277,7 @@ export declare const SettingsSchema: Type.TObject<{
277
277
  startupTimeoutMs: Type.TOptional<Type.TInteger>;
278
278
  leaseMs: Type.TOptional<Type.TInteger>;
279
279
  maxLoadPerCpu: Type.TOptional<Type.TNumber>;
280
+ maxWorkerRssBytes: Type.TOptional<Type.TInteger>;
280
281
  }>>;
281
282
  admission: Type.TOptional<Type.TObject<{
282
283
  limits: Type.TOptional<Type.TObject<{
@@ -1 +1 @@
1
- {"version":3,"file":"settings-schema.d.ts","sourceRoot":"","sources":["../../src/core/settings-schema.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,KAAK,MAAM,EAAuB,IAAI,EAAE,MAAM,SAAS,CAAC;AAkBjE,QAAA,MAAM,6BAA6B;;;EAGjC,CAAC;AAEH,QAAA,MAAM,wBAAwB;;;;;;;;;;;EAwC5B,CAAC;AAEH,QAAA,MAAM,2BAA2B;;;EAa/B,CAAC;AAEH,QAAA,MAAM,4BAA4B;;EAOhC,CAAC;AAEH,QAAA,MAAM,2BAA2B;;;;EAS/B,CAAC;AAEH,QAAA,MAAM,mBAAmB;;;;;;;;;;;;EA6BvB,CAAC;AAEH,QAAA,MAAM,sBAAsB;;;;;;;;EAwC1B,CAAC;AAEH,QAAA,MAAM,mBAAmB;;;EAavB,CAAC;AAEH,QAAA,MAAM,oBAAoB;;;EAaxB,CAAC;AAEH,QAAA,MAAM,6BAA6B;;EAQjC,CAAC;AAWH,QAAA,MAAM,0BAA0B;;;;;EA6B/B,CAAC;AAcF,QAAA,MAAM,6BAA6B;;;;;EAA4B,CAAC;AAEhE,QAAA,MAAM,sBAAsB;;;;EAa1B,CAAC;AAEH,QAAA,MAAM,qBAAqB;;EAEzB,CAAC;AAEH,QAAA,MAAM,kBAAkB;;EAQtB,CAAC;AAMH,QAAA,MAAM,kBAAkB,2DAAiB,CAAC;AAE1C,QAAA,MAAM,sBAAsB;;;EAe1B,CAAC;AAEH,QAAA,MAAM,mB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BAAsB,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC;AACjG,MAAM,WAAW,gBAAiB,SAAQ,MAAM,CAAC,OAAO,sBAAsB,CAAC;CAAG;AAClF,MAAM,WAAW,eAAgB,SAAQ,MAAM,CAAC,OAAO,qBAAqB,CAAC;CAAG;AAChF,MAAM,WAAW,YAAa,SAAQ,MAAM,CAAC,OAAO,kBAAkB,CAAC;CAAG;AAC1E,MAAM,MAAM,YAAY,GAAG,MAAM,CAAC,OAAO,kBAAkB,CAAC,CAAC;AAC7D,MAAM,WAAW,gBAAiB,SAAQ,MAAM,CAAC,OAAO,sBAAsB,CAAC;CAAG;AAClF,MAAM,MAAM,mBAAmB,GAAG,WAAW,CAAC,aAAa,CAAC,qBAAqB,CAAC,CAAC,CAAC;AACpF,MAAM,MAAM,YAAY,GAAG,WAAW,CAAC,aAAa,CAAC,cAAc,CAAC,CAAC,CAAC;AACtE,MAAM,MAAM,gBAAgB,GAAG,WAAW,CAAC,aAAa,CAAC,WAAW,CAAC,CAAC,CAAC;AACvE,MAAM,MAAM,aAAa,GAAG,MAAM,CAAC,OAAO,mBAAmB,CAAC,CAAC;AAC/D,MAAM,MAAM,oBAAoB,GAAG,WAAW,CAAC,aAAa,CAAC,sBAAsB,CAAC,CAAC,CAAC;AACtF,MAAM,MAAM,gBAAgB,GAAG,WAAW,CAAC,aAAa,CAAC,cAAc,CAAC,CAAC,CAAC;AAC1E,MAAM,WAAW,QAAS,SAAQ,IAAI,CAAC,aAAa,EAAE,WAAW,GAAG,OAAO,GAAG,QAAQ,GAAG,YAAY,CAAC;IACrG,KAAK,CAAC,EAAE,aAAa,CAAC;IACtB,MAAM,CAAC,EAAE,MAAM,EAAE,CAAC;CAClB"}
@@ -278,6 +278,11 @@ const WorkflowsSettingsSchema = Type.Union([
278
278
  minimum: 0,
279
279
  description: "Load per CPU (1-minute load average / CPU cores) above which pooled stages start one at a time, at most one every 5 seconds. Default: 3. 0 turns it off.",
280
280
  })),
281
+ maxWorkerRssBytes: Type.Optional(Type.Integer({
282
+ minimum: 1,
283
+ maximum: Number.MAX_SAFE_INTEGER,
284
+ description: "Resident memory in bytes past which a local worker is replaced by a fresh one once its current child ends. A running child is never interrupted. Default: unset (never).",
285
+ })),
281
286
  }, { additionalProperties: false })),
282
287
  admission: Type.Optional(Type.Object({
283
288
  limits: Type.Optional(ResourceLimitsSchema),