hammerkit 2.1.0-next.13 → 2.1.0-next.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.unavailableExecutor = exports.RunRegistry = exports.MAX_COMMANDS = exports.MAX_TASK_ERROR = exports.MAX_CAUSES = exports.SANDBOX_ID_PATTERN = exports.RUN_ID_PATTERN = exports.QuotaError = exports.ShuttingDownError = exports.RunError = exports.RUN_PHASES = exports.isFinal = void 0;
3
+ exports.unavailableExecutor = exports.RunRegistry = exports.isLogCursor = exports.logCursors = exports.MAX_CURSORS_PER_ITEM = exports.MAX_COMMANDS = exports.MAX_TASK_ERROR = exports.MAX_CAUSES = exports.MAX_RESUMES = exports.CLOSE_TIMEOUT = exports.SANDBOX_ID_PATTERN = exports.RUN_ID_PATTERN = exports.QuotaError = exports.ShuttingDownError = exports.RunError = exports.isDetached = exports.RUN_PHASES = exports.isFinal = void 0;
4
4
  const crypto_1 = require("crypto");
5
5
  const oauth_1 = require("./oauth");
6
6
  const run_logs_1 = require("./run-logs");
@@ -30,6 +30,11 @@ function ranFor(result) {
30
30
  }
31
31
  return result.durationMs;
32
32
  }
33
+ // Whether the server stops and leaves the run to the next one (RunContext.detached)
34
+ function isDetached(context) {
35
+ return context.signal.aborted && !!context.detached?.();
36
+ }
37
+ exports.isDetached = isDetached;
33
38
  // The server can not take the run now; `status` is what the caller is told
34
39
  class RunError extends Error {
35
40
  constructor() {
@@ -79,6 +84,18 @@ function servicePlaces(runs, asleep = false) {
79
84
  function onSandbox(run, sandbox) {
80
85
  return run.source.type === 'sandbox' && run.source.id === sandbox;
81
86
  }
87
+ // How long a server that stops waits for the executions it detaches: a pod gets 30s by
88
+ // default, and the records are written after. The process of a detached run gets less than
89
+ // this to stop its tasks on a host (DETACH_GRACE_MS in executor.ts), so what its execution
90
+ // does after (its directory, a release of its volumes) fits too. A server without a store
91
+ // cancels its runs and waits for them as long as they take (STOP_GRACE_MS, then a kill).
92
+ exports.CLOSE_TIMEOUT = 15000;
93
+ // how often the record of a run that executes is written while it says something
94
+ const PERSIST_EVERY = 2000;
95
+ // how often a run is resumed in a row without getting anywhere, then it fails
96
+ exports.MAX_RESUMES = 3;
97
+ // what a move that waited or executed when the server stopped says
98
+ const MOVE_LOST = 'not applied, the server restarted';
82
99
  // the tasks of a run whose check keys are kept, a build file has fewer
83
100
  const MAX_KEYED_TASKS = 1000;
84
101
  // how much of the end of a task's output its result carries
@@ -122,6 +139,114 @@ function taskEventSize(event) {
122
139
  const causes = (event.causes ?? []).reduce((sum, cause) => sum + Buffer.byteLength(cause) + 4, 0);
123
140
  return 64 + causes + Buffer.byteLength(event.error ?? '') + (event.commands?.length ?? 0) * 64;
124
141
  }
142
+ // what an event weighs against the log limits of a run; a state change weighs nothing, it is
143
+ // always kept
144
+ function eventSize(event) {
145
+ if (event.type === 'state') {
146
+ return 0;
147
+ }
148
+ return event.type === 'log' ? Buffer.byteLength(event.text) + 64 : event.type === 'task' ? taskEventSize(event) : 64;
149
+ }
150
+ // the instances of the container of a task or service whose cursors a run keeps: the kubelet
151
+ // keeps the log of the one that runs and of the one before it
152
+ exports.MAX_CURSORS_PER_ITEM = 10;
153
+ // lines with the same time of a log, which has nanoseconds
154
+ const MAX_CURSOR_COUNT = 1000000;
155
+ // The cursors of a record, as the registry keeps them: by task, those of a pod's log
156
+ function logCursors(cursors) {
157
+ const kept = new Map();
158
+ if (!cursors || typeof cursors !== 'object' || Array.isArray(cursors)) {
159
+ return kept;
160
+ }
161
+ for (const [item, list] of Object.entries(cursors)) {
162
+ if (kept.size >= MAX_KEYED_TASKS) {
163
+ break;
164
+ }
165
+ const valid = Array.isArray(list) ? list.filter(isLogCursor).slice(-exports.MAX_CURSORS_PER_ITEM) : [];
166
+ if (valid.length > 0) {
167
+ kept.set(item, valid.map(copyCursor));
168
+ }
169
+ }
170
+ return kept;
171
+ }
172
+ exports.logCursors = logCursors;
173
+ function isLogCursor(cursor) {
174
+ const value = cursor;
175
+ return (!!value &&
176
+ typeof value === 'object' &&
177
+ typeof value.container === 'string' &&
178
+ value.container.length > 0 &&
179
+ value.container.length <= 256 &&
180
+ typeof value.at === 'string' &&
181
+ /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{9}$/.test(value.at) &&
182
+ Number.isSafeInteger(value.count) &&
183
+ value.count >= 0 &&
184
+ value.count <= MAX_CURSOR_COUNT);
185
+ }
186
+ exports.isLogCursor = isLogCursor;
187
+ function copyCursor(cursor) {
188
+ return { container: cursor.container, at: cursor.at, count: cursor.count };
189
+ }
190
+ // Where the log of an instance got to: in place of the cursor it had, the newest last
191
+ function keepCursor(cursors, item, cursor) {
192
+ const list = cursors.get(item);
193
+ if (!list) {
194
+ if (cursors.size < MAX_KEYED_TASKS) {
195
+ cursors.set(item, [copyCursor(cursor)]);
196
+ }
197
+ return;
198
+ }
199
+ const index = list.findIndex((kept) => kept.container === cursor.container);
200
+ if (index >= 0) {
201
+ list.splice(index, 1);
202
+ }
203
+ list.push(copyCursor(cursor));
204
+ list.splice(0, Math.max(0, list.length - exports.MAX_CURSORS_PER_ITEM));
205
+ }
206
+ // without a prototype: an item may be named as a property of any object
207
+ function cursorsOf(cursors) {
208
+ const record = Object.create(null);
209
+ for (const [item, list] of cursors) {
210
+ record[item] = list.map(copyCursor);
211
+ }
212
+ return record;
213
+ }
214
+ // The check keys of a record, as the registry keeps them: by task, a key or null
215
+ function checkKeys(keys) {
216
+ if (!keys || typeof keys !== 'object' || Array.isArray(keys)) {
217
+ return {};
218
+ }
219
+ return Object.fromEntries(Object.entries(keys)
220
+ .filter(([, key]) => key === null || typeof key === 'string')
221
+ .slice(0, MAX_KEYED_TASKS));
222
+ }
223
+ // What keeps the run of a record from executing again: what it runs, from where, is not in it
224
+ function unresumable(run) {
225
+ if (typeof run.id !== 'string' || !exports.RUN_ID_PATTERN.test(run.id)) {
226
+ return 'its id is not one of a run';
227
+ }
228
+ if (!run.owner || typeof run.owner.iss !== 'string' || typeof run.owner.sub !== 'string') {
229
+ return 'it names no owner';
230
+ }
231
+ if (typeof run.definition !== 'string') {
232
+ return 'it names no build file';
233
+ }
234
+ if (!Array.isArray(run.tasks) || !Array.isArray(run.accounts) || !run.options || typeof run.options !== 'object') {
235
+ return 'it names no tasks';
236
+ }
237
+ if (!run.source || !['ref', 'upload', 'sandbox'].includes(run.source.type)) {
238
+ return 'it names no source';
239
+ }
240
+ if (run.up &&
241
+ (typeof run.up.name !== 'string' ||
242
+ !Array.isArray(run.up.services) ||
243
+ !run.up.services.every((service) => typeof service === 'string') ||
244
+ !Array.isArray(run.up.endpoints) ||
245
+ !run.up.endpoints.every((endpoint) => endpoint && typeof endpoint.host === 'string'))) {
246
+ return 'it names no services';
247
+ }
248
+ return undefined;
249
+ }
125
250
  // Where runs are kept while the server is up. Everything is scoped to the
126
251
  // caller that submitted the run: the same id asked for by someone else is
127
252
  // "not found", so ids can't be used to find out which runs exist.
@@ -134,10 +259,15 @@ class RunRegistry {
134
259
  this.closed = false;
135
260
  // callers that wait for a run to finish, let go when the server stops
136
261
  this.waiters = new Set();
137
- // the moves of service runs that execute beside their services
138
- this.moving = new Set();
262
+ // the executions of runs, until they ended, and the moves of service runs that execute
263
+ // beside their services
264
+ this.executions = new Map();
265
+ this.moving = new Map();
139
266
  // the records of evicted runs still being removed from the store, waited for by close
140
267
  this.removing = new Set();
268
+ // close wrote every run down with all it said: a later write (a stop, an extend, a run that
269
+ // ends after the server stopped waiting for it) has it all too
270
+ this.written = false;
141
271
  this.maxConcurrent = options.maxConcurrent ?? 4;
142
272
  this.keep = options.keep ?? 200;
143
273
  this.maxEvents = options.maxEvents ?? 5000;
@@ -148,8 +278,8 @@ class RunRegistry {
148
278
  }
149
279
  /**
150
280
  * Takes back the runs of a previous start. Those that waited for an approval wait
151
- * again, for what is left of their time; those that were queued or running when the
152
- * server stopped failed with it, and say so.
281
+ * again, for what is left of their time, and those that were asleep sleep on. Those that
282
+ * were queued, running or up go back in the queue under their id (resume).
153
283
  */
154
284
  async restore() {
155
285
  const store = this.options.store;
@@ -159,8 +289,10 @@ class RunRegistry {
159
289
  return;
160
290
  }
161
291
  const { records, skipped } = await store.load();
292
+ // the queue as it was: the runs that executed first, then the others as they were queued
293
+ const resuming = [];
162
294
  skipped.forEach((name) => this.options.log?.(`skip run record ${name}: it can not be read`));
163
- for (const { run, events } of records) {
295
+ for (const { run, events, keys, cursors, clean } of records) {
164
296
  // a move that executed went with the server
165
297
  delete run.moving;
166
298
  const entry = {
@@ -172,7 +304,8 @@ class RunRegistry {
172
304
  bytes: 0,
173
305
  tails: new Map(Object.entries(run.results ?? {}).map(([task, result]) => [task, result.lastLog])),
174
306
  saving: Promise.resolve(),
175
- keys: {},
307
+ keys: checkKeys(keys),
308
+ cursors: logCursors(cursors),
176
309
  };
177
310
  this.entries.set(run.id, entry);
178
311
  if (run.state === 'awaiting-approval') {
@@ -185,41 +318,109 @@ class RunRegistry {
185
318
  this.finish(entry, 'rejected', 'nobody approved it in time');
186
319
  }
187
320
  }
188
- else if (this.maySleep(entry) && ['queued', 'running', 'up', 'asleep'].includes(run.state)) {
189
- // the services went with the process that held them, the next request wakes them
190
- if (run.state === 'queued' || run.state === 'running' || run.state === 'up') {
191
- // a server that stopped without putting the run to sleep left its volumes where they
192
- // were, for the wake to mount
193
- if (this.keepsVolumes()) {
194
- run.volumesKept = true;
321
+ else if (run.state === 'asleep') {
322
+ if (this.maySleep(entry)) {
323
+ this.expireLater(entry);
324
+ if (!this.keepsVolumes()) {
325
+ // the backend no longer keeps them, the sweep below removes them
326
+ delete run.volumesKept;
195
327
  }
196
- this.sleep(entry);
197
328
  }
198
329
  else {
199
- this.expireLater(entry);
200
- }
201
- if (!this.keepsVolumes()) {
202
- // the backend no longer keeps them, the sweep below removes them
203
- delete run.volumesKept;
330
+ // its time ran out while the server was down: it ends now, and gives its place back
331
+ run.stoppedBy ?? (run.stoppedBy = 'ttl');
332
+ this.finish(entry, 'succeeded');
204
333
  }
205
334
  }
206
- else if (run.state === 'asleep') {
207
- // its time ran out while the server was down: it ends now, and gives its place back
208
- run.stoppedBy ?? (run.stoppedBy = 'ttl');
209
- this.finish(entry, 'succeeded');
335
+ else if (run.state === 'queued' || run.state === 'running' || run.state === 'up') {
336
+ resuming.push({
337
+ entry,
338
+ executed: run.state !== 'queued',
339
+ queuedAt: String(run.queuedAt ?? run.createdAt ?? ''),
340
+ clean: clean === true,
341
+ });
342
+ }
343
+ }
344
+ resuming
345
+ .sort((a, b) => Number(b.executed) - Number(a.executed) || a.queuedAt.localeCompare(b.queuedAt))
346
+ .forEach(({ entry, clean }) => this.resume(entry, clean));
347
+ this.evict();
348
+ try {
349
+ this.options.executor.restored?.([...this.entries.values()]
350
+ .filter((entry) => !isFinal(entry.run.state) && (entry.run.volumesKept || entry.resumed))
351
+ .map((entry) => this.copy(entry.run)));
352
+ }
353
+ catch (e) {
354
+ // the server starts all the same, what the backend kept is looked at again on the next start
355
+ this.options.log?.(`the backend could not take back what it kept: ${e instanceof Error ? e.message : e}`);
356
+ }
357
+ this.dispatch();
358
+ }
359
+ // A run that was queued or executing when the server stopped goes back in the queue, under
360
+ // its id and with what it was pinned to; its tasks that finished are taken from the cache.
361
+ // It ends instead when it was to end: a cancel or a stop came while the server stopped, its
362
+ // time ran out, or it took the server down too often. One that can not be read fails.
363
+ // `clean`: the server that stopped wrote it down with all it said.
364
+ resume(entry, clean) {
365
+ const run = entry.run;
366
+ const was = run.state;
367
+ // what an execution before the restart left goes when the run ends before it executes again
368
+ entry.resumed = !!run.startedAt;
369
+ const unreadable = unresumable(run);
370
+ if (unreadable) {
371
+ // enough of a run to show how it ended, to nobody when its owner is not known
372
+ if (!run.owner || typeof run.owner.iss !== 'string' || typeof run.owner.sub !== 'string') {
373
+ run.owner = { iss: '', sub: '' };
374
+ }
375
+ run.tasks = Array.isArray(run.tasks) ? run.tasks : [];
376
+ run.accounts = Array.isArray(run.accounts) ? run.accounts : [];
377
+ run.options = run.options && typeof run.options === 'object' ? run.options : {};
378
+ if (!run.source || typeof run.source !== 'object') {
379
+ run.source = { type: 'upload', snapshot: '' };
210
380
  }
211
- else if (run.state === 'queued' || run.state === 'running') {
212
- this.finish(entry, 'failed', `the server stopped while the run was ${run.state}, submit it again`);
381
+ this.finish(entry, 'failed', `the server stopped while the run was ${was} and its record can not resume it: ${unreadable}, submit it again`);
382
+ return;
383
+ }
384
+ if (run.cancelling) {
385
+ this.finish(entry, 'cancelled');
386
+ return;
387
+ }
388
+ if (run.up && run.stoppedBy) {
389
+ // stopped while it was up, or replaced
390
+ this.finish(entry, 'succeeded');
391
+ return;
392
+ }
393
+ if (run.up && run.upAt && !(Date.parse(run.expiresAt ?? '') > this.now())) {
394
+ run.stoppedBy = 'ttl';
395
+ this.finish(entry, 'succeeded');
396
+ return;
397
+ }
398
+ // the time a run gets counts from its first start; a service run that was up gets it again
399
+ const limit = this.options.maxDuration;
400
+ if (limit && run.startedAt && !run.upAt && this.now() - Date.parse(run.startedAt) >= limit) {
401
+ this.finish(entry, 'failed', this.tooLong());
402
+ return;
403
+ }
404
+ if (was !== 'queued') {
405
+ run.resumes = (run.resumes ?? 0) + 1;
406
+ if (run.resumes > exports.MAX_RESUMES) {
407
+ this.finish(entry, 'failed', `the server stopped ${run.resumes} times in a row while the run was ${was}, it is not resumed again, submit it again`);
408
+ return;
213
409
  }
214
- else if (run.state === 'up') {
215
- // the services went with the process that held them
216
- this.finish(entry, 'failed', 'the server stopped while the services were up, start them again');
410
+ if (!clean) {
411
+ // a server that was killed: what the run said since it was last written down is gone
412
+ run.lostAfter = entry.events.length;
217
413
  }
218
414
  }
219
- this.evict();
220
- this.options.executor.restored?.([...this.entries.values()]
221
- .filter((entry) => entry.run.volumesKept && !isFinal(entry.run.state))
222
- .map((entry) => this.copy(entry.run)));
415
+ // what it said counts against its limits as before
416
+ entry.bytes = entry.events.reduce((sum, event) => sum + eventSize(event), 0);
417
+ delete run.sleepsAt;
418
+ run.state = 'queued';
419
+ run.queuedAt = this.timestamp();
420
+ const lost = was !== 'queued' && !clean ? ', the last of its log before is lost' : '';
421
+ this.record(entry, { type: 'log', task: 'hammerkit', stream: 'stdout', text: `resumed after a server restart${lost}` }, true);
422
+ this.record(entry, { type: 'state', state: 'queued' });
423
+ this.queue.push(entry);
223
424
  }
224
425
  // A run that needs approvals (for the accounts named) waits for them, the others
225
426
  // are queued at once.
@@ -262,6 +463,7 @@ class RunRegistry {
262
463
  tails: new Map(),
263
464
  saving: Promise.resolve(),
264
465
  keys: {},
466
+ cursors: new Map(),
265
467
  };
266
468
  this.entries.set(run.id, entry);
267
469
  if (waiting) {
@@ -492,12 +694,16 @@ class RunRegistry {
492
694
  this.finish(entry, 'cancelled', reason);
493
695
  }
494
696
  else if (entry.run.state === 'running') {
697
+ // written down at once: a server that stops before the run did ends it on its next start
698
+ entry.run.cancelling = true;
699
+ this.persist(entry);
495
700
  entry.abort.abort();
496
701
  }
497
702
  else if (entry.run.state === 'up') {
498
703
  (_a = entry.run).stoppedBy ?? (_a.stoppedBy = by ?? 'replaced');
499
704
  entry.sleeping = false;
500
705
  entry.restartTo = undefined;
706
+ this.persist(entry);
501
707
  entry.mover?.abort.abort();
502
708
  entry.abort.abort();
503
709
  }
@@ -574,7 +780,11 @@ class RunRegistry {
574
780
  if (!entry) {
575
781
  return undefined;
576
782
  }
577
- const events = entry.events.filter((event) => event.seq > after);
783
+ // a cursor past the end comes from a server that was killed after it sent what it did not
784
+ // write down: those events are gone, the ones said again since have their numbers
785
+ const last = entry.events.length;
786
+ const from = after > last ? Math.min(entry.run.lostAfter ?? last, last) : after;
787
+ const events = entry.events.filter((event) => event.seq > from);
578
788
  const finished = FINAL_STATES.includes(entry.run.state);
579
789
  if (!finished) {
580
790
  entry.listeners.add(listener);
@@ -622,46 +832,47 @@ class RunRegistry {
622
832
  if (!entry) {
623
833
  return undefined;
624
834
  }
625
- // only the events since the last read are looked at
626
- entry.index ?? (entry.index = new run_logs_1.LogIndex());
627
- entry.index.update(entry.events);
628
- return { events: entry.events, index: entry.index, truncated: entry.truncated };
835
+ return this.logOf(entry);
629
836
  }
630
837
  // The log of any run, for a caller whose right to read it was checked already (an
631
838
  // entitlement with `observe`).
632
839
  logsOf(id) {
633
840
  const entry = this.entries.get(id);
634
- if (!entry) {
635
- return undefined;
636
- }
841
+ return entry ? this.logOf(entry) : undefined;
842
+ }
843
+ logOf(entry) {
844
+ // only the events since the last read are looked at
637
845
  entry.index ?? (entry.index = new run_logs_1.LogIndex());
638
846
  entry.index.update(entry.events);
639
- return { events: entry.events, index: entry.index, truncated: entry.truncated };
847
+ return {
848
+ events: entry.events,
849
+ index: entry.index,
850
+ truncated: entry.truncated,
851
+ ...(entry.run.lostAfter !== undefined ? { lostAfter: entry.run.lostAfter } : {}),
852
+ };
640
853
  }
641
- // Stops accepting runs and aborts the ones in flight.
854
+ /**
855
+ * Stops accepting runs. Without a store the runs in flight are cancelled. With one they are
856
+ * detached: a queued run stays in the queue of its record, and a running one or a service
857
+ * run that is up stops its execution without cancelling what it started (RunContext.detached).
858
+ * The next start takes them all back (restore). The executions get `closeTimeout` to stop,
859
+ * then every run is written down as it is.
860
+ */
642
861
  async close() {
643
862
  this.closed = true;
863
+ const detach = !!this.options.store;
644
864
  for (const entry of this.queue.splice(0)) {
645
- if (this.maySleep(entry) && this.options.store) {
646
- // a woken service run sleeps again, the next start keeps it
647
- this.sleep(entry);
648
- }
649
- else {
865
+ if (!detach) {
650
866
  this.finish(entry, 'cancelled');
651
867
  }
652
868
  }
653
869
  for (const entry of this.entries.values()) {
654
- if (entry.run.state === 'asleep') {
655
- this.clearTimer(entry);
870
+ if (entry.run.state === 'awaiting-approval' && !detach) {
871
+ this.finish(entry, 'cancelled');
656
872
  }
657
- else if (entry.run.state === 'awaiting-approval') {
658
- if (this.options.store) {
659
- // the record keeps it waiting, the next start takes it back
660
- this.clearTimer(entry);
661
- }
662
- else {
663
- this.finish(entry, 'cancelled');
664
- }
873
+ else if (!isFinal(entry.run.state)) {
874
+ // the record keeps it waiting, asleep or up; the next start takes it back, with its time
875
+ this.clearTimer(entry);
665
876
  }
666
877
  }
667
878
  // who waits for a run that waits for an approval is told how it stands now
@@ -669,19 +880,44 @@ class RunRegistry {
669
880
  done();
670
881
  }
671
882
  for (const entry of this.entries.values()) {
883
+ if (detach && !isFinal(entry.run.state)) {
884
+ // the next server starts the run at the commit it is at
885
+ this.dropMove(entry);
886
+ }
672
887
  if (entry.run.state === 'running' || entry.run.state === 'up') {
673
- // a service run that may sleep is asleep in its record, the next request after the
674
- // start wakes it
675
- entry.sleeping = this.maySleep(entry) && !!this.options.store;
888
+ // one that stops already (a cancel, its ttl, a sleep, a move) ends as it would
889
+ if (detach && !entry.abort.signal.aborted) {
890
+ entry.detached = true;
891
+ clearTimeout(entry.durationTimer);
892
+ }
676
893
  entry.mover?.abort.abort();
677
894
  entry.abort.abort();
678
895
  }
679
896
  }
680
- while (this.running > 0 ||
681
- this.moving.size > 0 ||
682
- [...this.entries.values()].some((entry) => entry.run.state === 'running' || entry.run.state === 'up')) {
897
+ // a server without a store waits for its cancels to clean up, however long they take
898
+ const deadline = detach ? Date.now() + (this.options.closeTimeout ?? exports.CLOSE_TIMEOUT) : Infinity;
899
+ const stopping = () => new Set([
900
+ ...this.executions.values(),
901
+ ...this.moving.values(),
902
+ ...[...this.entries.values()].filter((entry) => (entry.run.state === 'running' || entry.run.state === 'up') && !entry.detached),
903
+ ]);
904
+ while (stopping().size > 0 && Date.now() < deadline) {
683
905
  await new Promise((resolve) => setTimeout(resolve, 10));
684
906
  }
907
+ const left = stopping().size;
908
+ if (left > 0) {
909
+ this.options.log?.(`the server stops while ${left} ${left === 1 ? 'run still stops, it is' : 'runs still stop, they are'} written down as ${left === 1 ? 'it is' : 'they are'}`);
910
+ }
911
+ if (detach) {
912
+ // with all they said, for the start that resumes them
913
+ this.written = true;
914
+ for (const entry of this.entries.values()) {
915
+ clearTimeout(entry.persistTimer);
916
+ if (!isFinal(entry.run.state)) {
917
+ this.persist(entry, true);
918
+ }
919
+ }
920
+ }
685
921
  // the runs that were stopped are written down before the server is gone, and the records
686
922
  // of evicted runs are gone from the store
687
923
  await Promise.all([...this.entries.values()].map((entry) => entry.saving));
@@ -860,7 +1096,8 @@ class RunRegistry {
860
1096
  // does not keep the others from the machine. A run on a sandbox another run works on
861
1097
  // waits for it, as does one that needs what an executing run holds.
862
1098
  dispatch() {
863
- while (this.running < this.maxConcurrent) {
1099
+ // the runs left in the queue start with the next server
1100
+ while (this.running < this.maxConcurrent && !this.closed) {
864
1101
  const perCaller = this.options.limits?.running ?? Infinity;
865
1102
  const index = this.queue.findIndex((entry) => this.runningOf(entry.run.owner) < perCaller && !this.sandboxBusy(entry.run) && !this.held(entry.run));
866
1103
  if (index < 0) {
@@ -874,26 +1111,36 @@ class RunRegistry {
874
1111
  }
875
1112
  const [entry] = this.queue.splice(index, 1);
876
1113
  this.running++;
877
- this.execute(entry).finally(() => {
1114
+ const execution = this.execute(entry).finally(() => {
1115
+ this.executions.delete(execution);
878
1116
  // a service run that is up gave its place back already
879
1117
  if (!entry.released) {
880
1118
  this.running--;
881
1119
  }
882
1120
  this.dispatch();
883
1121
  });
1122
+ this.executions.set(execution, entry);
884
1123
  }
885
1124
  }
886
1125
  async execute(entry) {
1126
+ // a run that resumes executes again: what it left is this execution's to remove, and its
1127
+ // time counts from its first start (a service run that was up gets it again)
1128
+ const resumed = !!entry.resumed;
1129
+ const continues = resumed && !!entry.run.startedAt && !entry.run.upAt;
1130
+ entry.resumed = false;
887
1131
  entry.run.state = 'running';
888
- entry.run.startedAt = this.timestamp();
1132
+ if (!continues) {
1133
+ entry.run.startedAt = this.timestamp();
1134
+ }
889
1135
  this.record(entry, { type: 'state', state: 'running' });
890
1136
  // a service run gets this long to be up, then its ttl counts
891
1137
  const limit = this.options.maxDuration;
1138
+ const ran = continues ? Math.max(0, this.now() - Date.parse(entry.run.startedAt)) : 0;
892
1139
  entry.durationTimer = limit
893
1140
  ? setTimeout(() => {
894
1141
  entry.timedOut = true;
895
1142
  entry.abort.abort();
896
- }, limit)
1143
+ }, Math.max(0, limit - ran))
897
1144
  : undefined;
898
1145
  entry.durationTimer?.unref();
899
1146
  const token = {};
@@ -908,6 +1155,8 @@ class RunRegistry {
908
1155
  await this.options.executor.execute(run, {
909
1156
  emit: (event) => this.record(entry, event),
910
1157
  signal: entry.abort.signal,
1158
+ detached: () => !!entry.detached,
1159
+ ...(resumed ? { resumed: { logs: cursorsOf(entry.cursors) } } : {}),
911
1160
  ...(Object.keys(durations).length > 0 ? { durations } : {}),
912
1161
  ...(this.options.artifacts && !entry.run.up
913
1162
  ? {
@@ -924,8 +1173,8 @@ class RunRegistry {
924
1173
  }
925
1174
  : {}),
926
1175
  });
927
- if (entry.holder !== token) {
928
- // a move took the services over
1176
+ if (entry.holder !== token || entry.detached) {
1177
+ // a move took the services over, or the run resumes with the next server
929
1178
  return;
930
1179
  }
931
1180
  if (this.fallBack(entry, entry.timedOut ? this.tooLong() : 'its services stopped before they were up')) {
@@ -944,7 +1193,7 @@ class RunRegistry {
944
1193
  }
945
1194
  catch (e) {
946
1195
  const message = e instanceof Error ? e.message : String(e);
947
- if (entry.holder !== token) {
1196
+ if (entry.holder !== token || entry.detached) {
948
1197
  return;
949
1198
  }
950
1199
  if (this.fallBack(entry, entry.timedOut ? this.tooLong() : message)) {
@@ -983,6 +1232,7 @@ class RunRegistry {
983
1232
  this.moveTo(entry, landing.change);
984
1233
  }
985
1234
  entry.run.state = 'up';
1235
+ delete entry.run.resumes;
986
1236
  // one reading of the clock, so the ttl is exactly expiresAt - upAt
987
1237
  const now = this.now();
988
1238
  // the ttl counts from the first time, not from a wake
@@ -1189,7 +1439,7 @@ class RunRegistry {
1189
1439
  ...(change.plan ? { plan: change.plan } : {}),
1190
1440
  };
1191
1441
  const execution = this.executeMove(entry, token, abort, run);
1192
- this.moving.add(execution);
1442
+ this.moving.set(execution, entry);
1193
1443
  void execution.finally(() => this.moving.delete(execution));
1194
1444
  }
1195
1445
  // A move beside the services of a run that is up: once its services are ready it holds them
@@ -1200,6 +1450,7 @@ class RunRegistry {
1200
1450
  await this.options.executor.execute(run, {
1201
1451
  emit: (event) => this.record(entry, event),
1202
1452
  signal: abort.signal,
1453
+ detached: () => !!entry.detached,
1203
1454
  up: (targets) => this.moved(entry, token, targets),
1204
1455
  keep: () => (entry.holder === token ? this.keepOf(entry) : 'everything'),
1205
1456
  });
@@ -1213,6 +1464,10 @@ class RunRegistry {
1213
1464
  failure = `the move took longer than ${(0, units_1.formatDuration)(this.options.maxDuration)} and was stopped`;
1214
1465
  }
1215
1466
  this.releaseMover(mover);
1467
+ if (entry.detached) {
1468
+ // the run resumes with the next server, at the commit it is at
1469
+ return;
1470
+ }
1216
1471
  if (entry.holder === token) {
1217
1472
  // the run's services were this execution's
1218
1473
  if (entry.restartTo || entry.sleeping) {
@@ -1280,12 +1535,7 @@ class RunRegistry {
1280
1535
  if (this.closed) {
1281
1536
  // the record keeps it asleep, at the commit it was up at
1282
1537
  this.moveTo(entry, restart, 'the server stopped before the services were up at the commit');
1283
- if (this.maySleep(entry) && this.options.store) {
1284
- this.sleep(entry);
1285
- }
1286
- else {
1287
- this.finish(entry, 'failed', 'the server stopped while the services were up, start them again');
1288
- }
1538
+ this.leaveForRestart(entry);
1289
1539
  return;
1290
1540
  }
1291
1541
  // up at its commit, the run is there (markUp); else it goes back (fallBack)
@@ -1322,17 +1572,49 @@ class RunRegistry {
1322
1572
  text: `did not get up at ${landing.change.source.commit}, starting again at ${from.commit}: ${error}`,
1323
1573
  });
1324
1574
  if (this.closed) {
1325
- if (this.maySleep(entry) && this.options.store) {
1326
- this.sleep(entry);
1327
- }
1328
- else {
1329
- this.finish(entry, 'failed', 'the server stopped while the services were up, start them again');
1330
- }
1575
+ this.leaveForRestart(entry);
1331
1576
  return true;
1332
1577
  }
1333
1578
  this.requeue(entry);
1334
1579
  return true;
1335
1580
  }
1581
+ // The server stops: a move that waits, executes beside the services or starts them at its
1582
+ // commit does not get there, the run stays at the commit it is at and says so
1583
+ dropMove(entry) {
1584
+ const landing = entry.landing && !entry.landing.recorded ? entry.landing : undefined;
1585
+ const change = entry.mover?.change ?? entry.pendingMove ?? landing?.change;
1586
+ if (!change) {
1587
+ return;
1588
+ }
1589
+ entry.pendingMove = undefined;
1590
+ if (landing) {
1591
+ entry.landing = undefined;
1592
+ entry.run.source = { ...landing.from.source };
1593
+ if (landing.from.plan) {
1594
+ entry.run.plan = landing.from.plan;
1595
+ }
1596
+ }
1597
+ // the execution of a move ends with the server, its record says where it got
1598
+ const mover = entry.mover;
1599
+ entry.mover = undefined;
1600
+ this.moveTo(entry, change, MOVE_LOST);
1601
+ entry.mover = mover;
1602
+ }
1603
+ // The server stops while the services of a run stop to start again at another commit: it
1604
+ // sleeps in its record if it may, else the next server resumes it at the commit it was up at
1605
+ leaveForRestart(entry) {
1606
+ if (this.maySleep(entry) && this.options.store) {
1607
+ this.sleep(entry);
1608
+ }
1609
+ else if (this.options.store) {
1610
+ entry.targets = undefined;
1611
+ entry.run.state = 'queued';
1612
+ this.record(entry, { type: 'state', state: 'queued' });
1613
+ }
1614
+ else {
1615
+ this.finish(entry, 'failed', 'the server stopped while the services were up, start them again');
1616
+ }
1617
+ }
1336
1618
  // where a run that moves goes back to: the commit it is at (service runs start from a ref)
1337
1619
  landingFrom(entry) {
1338
1620
  return {
@@ -1401,8 +1683,8 @@ class RunRegistry {
1401
1683
  // the record, so the volumes are removed (RunExecutor.forget) when the run ends asleep, or
1402
1684
  // when a stop came after the sleep began.
1403
1685
  keepOf(entry) {
1404
- // a run that starts again at another commit keeps them on any server
1405
- if (entry.restartTo || entry.landing || (entry.sleeping && this.keepsVolumes())) {
1686
+ // a run that starts again at another commit, or with the next server, keeps them on any server
1687
+ if (entry.restartTo || entry.landing || entry.detached || (entry.sleeping && this.keepsVolumes())) {
1406
1688
  entry.run.volumesKept = true;
1407
1689
  return 'volumes';
1408
1690
  }
@@ -1439,7 +1721,7 @@ class RunRegistry {
1439
1721
  }
1440
1722
  const sleepTtl = entry.run.up.sleepTtl;
1441
1723
  if (entry.run.state === 'up' && sleepTtl) {
1442
- // only kept in memory: a server that stops puts the run to sleep anyway
1724
+ // only kept in memory: a run that resumes after a restart is up for its sleepTtl from then
1443
1725
  entry.run.sleepsAt = new Date(this.now() + sleepTtl).toISOString();
1444
1726
  return undefined;
1445
1727
  }
@@ -1475,7 +1757,7 @@ class RunRegistry {
1475
1757
  return undefined;
1476
1758
  }
1477
1759
  // The end of a run that was up: stopped by somebody, its ttl or a newer run it succeeded,
1478
- // stopped by the server going away it failed, as its record says after a restart.
1760
+ // stopped by a server without a store going away it failed (one with a store detaches it).
1479
1761
  endServices(entry, failure) {
1480
1762
  if (entry.timedOut) {
1481
1763
  this.finish(entry, 'failed', this.tooLong());
@@ -1503,14 +1785,17 @@ class RunRegistry {
1503
1785
  entry.mover?.abort.abort();
1504
1786
  entry.mover = undefined;
1505
1787
  delete entry.run.moving;
1506
- if (entry.run.volumesKept) {
1507
- // it ends without waking: what was kept for it goes
1788
+ if (entry.run.volumesKept || entry.resumed) {
1789
+ // it ends without waking, or after a restart: what was kept for it, or what an execution
1790
+ // before the restart left, goes
1508
1791
  delete entry.run.volumesKept;
1792
+ entry.resumed = false;
1509
1793
  const run = this.copy(entry.run);
1510
1794
  Promise.resolve()
1511
1795
  .then(() => this.options.executor.forget?.(run))
1512
1796
  .catch((e) => this.options.log?.(`the volumes run ${run.id} kept could not be removed: ${e instanceof Error ? e.message : e}`));
1513
1797
  }
1798
+ delete entry.run.cancelling;
1514
1799
  entry.run.state = state;
1515
1800
  entry.run.finishedAt = this.timestamp();
1516
1801
  if (error) {
@@ -1546,17 +1831,29 @@ class RunRegistry {
1546
1831
  this.keepPhase(entry, recorded);
1547
1832
  return;
1548
1833
  }
1834
+ if (recorded.type === 'log' && 'cursor' in recorded) {
1835
+ // with the line it came with: a record has the cursor of the last line it has
1836
+ const { cursor, ...line } = recorded;
1837
+ if (isLogCursor(cursor)) {
1838
+ keepCursor(entry.cursors, recorded.task, cursor);
1839
+ }
1840
+ recorded = line;
1841
+ }
1549
1842
  const event = recorded.type === 'task' ? bounded(recorded) : recorded;
1550
1843
  if (event.type === 'log') {
1551
1844
  this.keepTail(entry, event.task, event.text);
1552
1845
  }
1553
1846
  else if (event.type === 'task') {
1554
1847
  this.keepResult(entry, event);
1848
+ if (event.state === 'succeeded' || event.state === 'failed') {
1849
+ // it got somewhere since the last restart
1850
+ delete entry.run.resumes;
1851
+ }
1555
1852
  }
1556
1853
  // an executor that keeps talking can't fill the memory of the server or its disk; the
1557
1854
  // state changes, which are few, are always kept, and the results above are kept apart
1558
1855
  if (!force && event.type !== 'state') {
1559
- const size = event.type === 'log' ? Buffer.byteLength(event.text) + 64 : event.type === 'task' ? taskEventSize(event) : 64;
1856
+ const size = eventSize(event);
1560
1857
  if (entry.events.length >= this.maxEvents || entry.bytes + size > this.maxLogBytes) {
1561
1858
  if (!entry.truncated) {
1562
1859
  entry.truncated = true;
@@ -1639,18 +1936,35 @@ class RunRegistry {
1639
1936
  for (const listener of entry.listeners) {
1640
1937
  listener(stored);
1641
1938
  }
1642
- // what a restart must not lose: the runs that wait, and how a run ended. A running
1643
- // run is not kept up to date, it fails with the server.
1939
+ // what a restart must not lose: the runs that wait, and how a run ended, at once; what a
1940
+ // run says while it executes every so often, as the next server resumes it
1644
1941
  if (event.type === 'state' || event.type === 'approval' || event.type === 'extended' || event.type === 'moved') {
1645
1942
  this.persist(entry);
1646
1943
  }
1944
+ else if (this.options.store && !entry.persistTimer && !this.closed) {
1945
+ entry.persistTimer = setTimeout(() => this.persist(entry), this.options.persistEvery ?? PERSIST_EVERY);
1946
+ entry.persistTimer.unref();
1947
+ }
1647
1948
  }
1648
- persist(entry) {
1949
+ // `clean`: the server stops, and the record has all the run said
1950
+ persist(entry, clean = false) {
1649
1951
  const store = this.options.store;
1952
+ clearTimeout(entry.persistTimer);
1953
+ entry.persistTimer = undefined;
1650
1954
  if (!store) {
1651
1955
  return;
1652
1956
  }
1653
- const record = { run: this.copy(entry.run), events: [...entry.events] };
1957
+ // the check keys of a run that resumes are the ones from before anything of it ran
1958
+ const keys = isFinal(entry.run.state) || Object.keys(entry.keys).length === 0 ? {} : { keys: { ...entry.keys } };
1959
+ // where the logs of its pods got to, for the next server that resumes it
1960
+ const cursors = isFinal(entry.run.state) || entry.cursors.size === 0 ? {} : { cursors: cursorsOf(entry.cursors) };
1961
+ const record = {
1962
+ run: this.copy(entry.run),
1963
+ events: [...entry.events],
1964
+ ...keys,
1965
+ ...cursors,
1966
+ ...(clean || this.written ? { clean: true } : {}),
1967
+ };
1654
1968
  entry.saving = entry.saving
1655
1969
  .then(() => store.save(record))
1656
1970
  .catch((e) => this.options.log?.(`could not keep run ${record.run.id}: ${e instanceof Error ? e.message : e}`));