@tidegap/core 0.20.0 → 0.22.0
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/channels/digest.js +4 -4
- package/dist/channels/format.d.ts +30 -4
- package/dist/channels/format.js +125 -22
- package/dist/channels/payload.js +8 -6
- package/dist/channels/plan.js +3 -2
- package/dist/channels/types.d.ts +17 -1
- package/dist/energy.d.ts +7 -0
- package/dist/energy.js +7 -0
- package/dist/grid.d.ts +10 -2
- package/dist/grid.js +14 -5
- package/dist/handoff.d.ts +88 -6
- package/dist/handoff.js +177 -20
- package/dist/history.d.ts +19 -0
- package/dist/history.js +24 -1
- package/dist/index.d.ts +24 -18
- package/dist/index.js +16 -12
- package/dist/job-cadence.d.ts +10 -0
- package/dist/job-cadence.js +34 -0
- package/dist/job-wake.d.ts +55 -0
- package/dist/job-wake.js +91 -0
- package/dist/jobs.d.ts +74 -17
- package/dist/jobs.js +420 -75
- package/dist/notify.d.ts +9 -0
- package/dist/notify.js +17 -3
- package/dist/providers/anthropic.js +8 -6
- package/dist/providers/base.d.ts +47 -9
- package/dist/providers/base.js +29 -4
- package/dist/providers/gemini.d.ts +3 -0
- package/dist/providers/gemini.js +9 -6
- package/dist/providers/http.d.ts +40 -0
- package/dist/providers/http.js +82 -0
- package/dist/providers/index.d.ts +1 -1
- package/dist/providers/index.js +1 -1
- package/dist/providers/ollama.d.ts +3 -0
- package/dist/providers/ollama.js +8 -5
- package/dist/providers/openai.js +7 -5
- package/dist/providers/timeout.d.ts +26 -8
- package/dist/providers/timeout.js +53 -15
- package/dist/readiness.d.ts +39 -3
- package/dist/readiness.js +73 -1
- package/dist/run-limits.d.ts +268 -0
- package/dist/run-limits.js +572 -0
- package/dist/schedule-job.d.ts +41 -2
- package/dist/schedule-job.js +70 -2
- package/dist/scheduler.d.ts +161 -17
- package/dist/scheduler.js +485 -128
- package/dist/storage/sqlite.d.ts +52 -5
- package/dist/storage/sqlite.js +200 -33
- package/dist/task-events.d.ts +19 -4
- package/dist/task-events.js +51 -5
- package/dist/tool-surface.js +62 -7
- package/dist/types.d.ts +72 -11
- package/dist/types.js +1 -3
- package/package.json +5 -2
package/dist/scheduler.js
CHANGED
|
@@ -26,14 +26,15 @@ import { deferRetryAt } from "./providers/defer.js";
|
|
|
26
26
|
import { postponeOptions, resolveLimitReset, resolvePostpone, taskProvider, writeLimitResetHint, } from "./postpone.js";
|
|
27
27
|
import { candidateId, parseCandidates, previewRouting, scoreCandidates, } from "./routing.js";
|
|
28
28
|
import { capHistory, deriveTitle, displayTitle, isRepeating, taskActions, taskHistory } from "./history.js";
|
|
29
|
-
import { BATCH_SUBMIT_INTERRUPTED_ERROR, JOB_INTERRUPTED_ERROR } from "./jobs.js";
|
|
30
|
-
import {
|
|
29
|
+
import { BATCH_SUBMIT_INTERRUPTED_ERROR, JOB_CAPS_KEYS, JOB_INTERRUPTED_ERROR } from "./jobs.js";
|
|
30
|
+
import { attemptNumber, CAPS_VERSION, capValueError, classifyFailure, failureFactsOf, finalFailureError, isRetryableFailure, loadRunLimitSettings, planRetry, resolveTaskRunLimits, retryPolicyOf, runLimitsDetails, taskRunLimitsView, } from "./run-limits.js";
|
|
31
31
|
import { resolveQuotaDeadline } from "./quota.js";
|
|
32
|
+
import { tickDispatch } from "./readiness.js";
|
|
32
33
|
import { redactBodyJson, redactPrompt } from "./redact.js";
|
|
33
34
|
import { selectWindow } from "./select-window.js";
|
|
34
35
|
import { loadOrCreateSigningKey, signReceipt, } from "./sign.js";
|
|
35
36
|
import { TaskStore } from "./storage/sqlite.js";
|
|
36
|
-
import { createProgressRecorder, eventDetails, impliedEventKind, } from "./task-events.js";
|
|
37
|
+
import { PROGRESS_BUSY_MS, createProgressRecorder, eventDetails, impliedEventKind, } from "./task-events.js";
|
|
37
38
|
export const PENDING_STATUSES = ["queued", "scheduled"];
|
|
38
39
|
export const UNFINISHED_STATUSES = ["queued", "scheduled", "submitted", "running"];
|
|
39
40
|
const TERMINAL = new Set(["completed", "failed", "cancelled"]);
|
|
@@ -70,6 +71,10 @@ export class InvalidDeadlineError extends Error {
|
|
|
70
71
|
this.name = "InvalidDeadlineError";
|
|
71
72
|
}
|
|
72
73
|
}
|
|
74
|
+
/** How often a held run's row is read for a cancel, or any other move off `running`, by another writer. */
|
|
75
|
+
const RUN_STATUS_CHECK_MS = 10_000;
|
|
76
|
+
/** The tick result of a run stopped because its task was cancelled. */
|
|
77
|
+
const STOPPED_RUN_ERROR = "task was cancelled while running; its run was stopped";
|
|
73
78
|
export class Scheduler {
|
|
74
79
|
feed;
|
|
75
80
|
defaultRegionOption;
|
|
@@ -80,6 +85,8 @@ export class Scheduler {
|
|
|
80
85
|
bodies = new Map();
|
|
81
86
|
/** Rows a tick moved to `running` whose dispatch has not settled (KTD12), and what each is doing. */
|
|
82
87
|
held = new Map();
|
|
88
|
+
/** Failed attempts per task without a ledger, where no `attempt_failed` event is stored to count. */
|
|
89
|
+
attemptsWithoutLedger = new Map();
|
|
83
90
|
store;
|
|
84
91
|
// Mutable: a single load failure disables signing for the rest of
|
|
85
92
|
// this scheduler instance (see `getSigningKey`).
|
|
@@ -91,6 +98,8 @@ export class Scheduler {
|
|
|
91
98
|
limitReset;
|
|
92
99
|
actor;
|
|
93
100
|
sleepCounter;
|
|
101
|
+
lockedTick;
|
|
102
|
+
runLimitSettings;
|
|
94
103
|
defaultRegion() {
|
|
95
104
|
const option = this.defaultRegionOption;
|
|
96
105
|
return typeof option === "function" ? option() : option;
|
|
@@ -111,7 +120,30 @@ export class Scheduler {
|
|
|
111
120
|
this.quotaConfig = opts.quotaConfig;
|
|
112
121
|
this.limitReset = opts.limitReset;
|
|
113
122
|
this.actor = opts.actor ?? "system";
|
|
123
|
+
this.lockedTick = opts.lockedTick;
|
|
114
124
|
this.sleepCounter = opts.sleepCounter;
|
|
125
|
+
this.runLimitSettings = opts.runLimits ?? (() => loadRunLimitSettings());
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* The time limits a run of `spec` gets if it starts now: the stored
|
|
129
|
+
* values, then the settings, then the defaults. A settings read that
|
|
130
|
+
* throws gives the stored values and the defaults.
|
|
131
|
+
*/
|
|
132
|
+
runLimitsFor(spec) {
|
|
133
|
+
return resolveTaskRunLimits(spec, this.settingsNow());
|
|
134
|
+
}
|
|
135
|
+
/** A task's time limits as views show them: the ones its newest run recorded, else the ones a run now gets. */
|
|
136
|
+
taskRunLimits(record, events = this.listTaskEvents(record.taskId)) {
|
|
137
|
+
return taskRunLimitsView(record.bodyJson, events, this.settingsNow());
|
|
138
|
+
}
|
|
139
|
+
/** The run-limit settings now; a reader that throws gives none (the stored values and the defaults apply). */
|
|
140
|
+
settingsNow() {
|
|
141
|
+
try {
|
|
142
|
+
return this.runLimitSettings();
|
|
143
|
+
}
|
|
144
|
+
catch {
|
|
145
|
+
return { values: {}, ignored: [] };
|
|
146
|
+
}
|
|
115
147
|
}
|
|
116
148
|
/**
|
|
117
149
|
* Compute the current aggregate carbon-budget status (ROADMAP item 4)
|
|
@@ -339,12 +371,15 @@ export class Scheduler {
|
|
|
339
371
|
title: occ.title,
|
|
340
372
|
originHost: occ.originHost,
|
|
341
373
|
originCwd: occ.originCwd,
|
|
374
|
+
...(occ.originSessionId ? { originSessionId: occ.originSessionId } : {}),
|
|
342
375
|
repeat: "none",
|
|
343
376
|
jobId: occ.jobId,
|
|
344
377
|
};
|
|
345
378
|
const created = this.eventFor(undefined, record, { kind: "created", actor: "system", details });
|
|
346
379
|
if (!this.store.insertIfAbsent(record, created))
|
|
347
380
|
return false;
|
|
381
|
+
if (record.originSessionId)
|
|
382
|
+
this.store.startSessionNotices(new Date(record.enqueuedAt));
|
|
348
383
|
this.cacheRow(record);
|
|
349
384
|
try {
|
|
350
385
|
await this.scheduleProviderCall(record.taskId, new Date(deadlineMs));
|
|
@@ -438,6 +473,9 @@ export class Scheduler {
|
|
|
438
473
|
if (typeof spec.prompt !== "string" || spec.prompt.length === 0) {
|
|
439
474
|
throw new Error("enqueueProviderCall: spec.prompt must be a non-empty string");
|
|
440
475
|
}
|
|
476
|
+
if (spec.caps !== undefined) {
|
|
477
|
+
spec = { ...spec, caps: checkedCaps(spec.caps, MODEL_CALL_CAPS_KEYS, "enqueueProviderCall") };
|
|
478
|
+
}
|
|
441
479
|
const checked = checkedHandoff(spec, opts, "enqueueProviderCall");
|
|
442
480
|
if (checked.tools !== undefined) {
|
|
443
481
|
const toolsError = claudeCodeToolsError(checked.tools);
|
|
@@ -456,9 +494,11 @@ export class Scheduler {
|
|
|
456
494
|
* an empty prompt) with `command.origin: "cli"` and no job id, planned
|
|
457
495
|
* like any provider call. Only the CLI tick's command adapter runs it.
|
|
458
496
|
* Checks: a command of 1 to 32,000 characters, an existing absolute
|
|
459
|
-
* folder,
|
|
460
|
-
*
|
|
461
|
-
*
|
|
497
|
+
* folder, valid caps, and the result path rules. Only the caps the caller
|
|
498
|
+
* set are stored; the time limits not set come from the settings when the
|
|
499
|
+
* run starts. `enqueueProviderCall` keeps refusing `command`, and
|
|
500
|
+
* `retryTask` refuses these rows: running a shell command again is the
|
|
501
|
+
* user's call.
|
|
462
502
|
*/
|
|
463
503
|
async enqueueCommandTask(task, opts = {}) {
|
|
464
504
|
if (typeof task.run !== "string" || task.run.trim() === "") {
|
|
@@ -470,15 +510,7 @@ export class Scheduler {
|
|
|
470
510
|
const cwdError = handoffCwdError(task.cwd, "command");
|
|
471
511
|
if (cwdError)
|
|
472
512
|
throw new Error(`enqueueCommandTask: ${cwdError}`);
|
|
473
|
-
const caps =
|
|
474
|
-
for (const [key, value] of Object.entries(task.caps ?? {})) {
|
|
475
|
-
if (!(key in DEFAULT_JOB_CAPS))
|
|
476
|
-
throw new Error(`enqueueCommandTask: unknown cap "${key}"`);
|
|
477
|
-
if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) {
|
|
478
|
-
throw new Error(`enqueueCommandTask: cap ${key} must be a positive number`);
|
|
479
|
-
}
|
|
480
|
-
caps[key] = value;
|
|
481
|
-
}
|
|
513
|
+
const caps = checkedCaps(task.caps, JOB_CAPS_KEYS, "enqueueCommandTask");
|
|
482
514
|
if (task.resultPath !== undefined) {
|
|
483
515
|
const pathError = resultPathError(task.resultPath, { cwd: task.cwd, originCwd: opts.originCwd });
|
|
484
516
|
if (pathError)
|
|
@@ -583,6 +615,7 @@ export class Scheduler {
|
|
|
583
615
|
let dispatched = 0;
|
|
584
616
|
let failed = 0;
|
|
585
617
|
let deferred = 0;
|
|
618
|
+
let retrying = 0;
|
|
586
619
|
let inspected = 0;
|
|
587
620
|
// Provider and model → retryAt after its first defer this tick: later due
|
|
588
621
|
// tasks on that provider and model defer to the same time without a
|
|
@@ -594,9 +627,16 @@ export class Scheduler {
|
|
|
594
627
|
dispatched++;
|
|
595
628
|
else if (entry.status === "deferred")
|
|
596
629
|
deferred++;
|
|
630
|
+
else if (entry.status === "retrying")
|
|
631
|
+
retrying++;
|
|
597
632
|
else
|
|
598
633
|
failed++;
|
|
599
634
|
};
|
|
635
|
+
// ---- (0) Rows a dead tick left running, under the tick lock only ----
|
|
636
|
+
for (const entry of this.freeDeadTickRuns()) {
|
|
637
|
+
results.push(await this.planRetryWindow(entry));
|
|
638
|
+
count(entry);
|
|
639
|
+
}
|
|
600
640
|
// ---- (1) Batch-submit sweep, BEFORE the due sweep ----
|
|
601
641
|
// A batch-eligible task's deferral mechanism IS the Batch API: the
|
|
602
642
|
// provider runs it within its own 24h SLA and picks the execution
|
|
@@ -657,10 +697,8 @@ export class Scheduler {
|
|
|
657
697
|
batchSubmitted++;
|
|
658
698
|
submittedThisTick.add(record.taskId);
|
|
659
699
|
}
|
|
660
|
-
else if (entry.status === "completed")
|
|
661
|
-
dispatched++;
|
|
662
700
|
else
|
|
663
|
-
|
|
701
|
+
count(entry);
|
|
664
702
|
}
|
|
665
703
|
// ---- (2) Due sweep (sync provider calls) ----
|
|
666
704
|
const now = Date.now();
|
|
@@ -755,12 +793,10 @@ export class Scheduler {
|
|
|
755
793
|
inspected++;
|
|
756
794
|
const entry = await this.holding(record, "batch_poll", () => this.pollBatch(record, adapters));
|
|
757
795
|
results.push(entry);
|
|
758
|
-
if (entry.status === "
|
|
759
|
-
dispatched++;
|
|
760
|
-
else if (entry.status === "submitted")
|
|
796
|
+
if (entry.status === "submitted")
|
|
761
797
|
batchPolled++;
|
|
762
798
|
else
|
|
763
|
-
|
|
799
|
+
count(entry);
|
|
764
800
|
}
|
|
765
801
|
// ---- (4) Aggregate carbon-budget alert (ROADMAP item 4) ----
|
|
766
802
|
// After every receipt this tick wrote (sync due-sweep + batch poll),
|
|
@@ -781,6 +817,7 @@ export class Scheduler {
|
|
|
781
817
|
batchSubmitted,
|
|
782
818
|
batchPolled,
|
|
783
819
|
deferred,
|
|
820
|
+
retrying,
|
|
784
821
|
};
|
|
785
822
|
}
|
|
786
823
|
/**
|
|
@@ -983,7 +1020,9 @@ export class Scheduler {
|
|
|
983
1020
|
/**
|
|
984
1021
|
* The progress callback of one run: the lines an adapter reports become
|
|
985
1022
|
* `progress` events (actor `tick`) within the core caps. None without a
|
|
986
|
-
* ledger.
|
|
1023
|
+
* ledger. Each write waits at most `PROGRESS_BUSY_MS` for a busy ledger.
|
|
1024
|
+
* A failed write costs its line, never the run; the first failure of a
|
|
1025
|
+
* task logs one warning that says later failed lines are dropped too.
|
|
987
1026
|
*/
|
|
988
1027
|
progressFor(taskId) {
|
|
989
1028
|
const store = this.store;
|
|
@@ -992,16 +1031,20 @@ export class Scheduler {
|
|
|
992
1031
|
let warned = false;
|
|
993
1032
|
return createProgressRecorder((details) => {
|
|
994
1033
|
try {
|
|
995
|
-
store.recordEvent(taskId, { kind: "progress", actor: "tick", details });
|
|
1034
|
+
store.recordEvent(taskId, { kind: "progress", actor: "tick", details }, { busyMs: PROGRESS_BUSY_MS });
|
|
996
1035
|
}
|
|
997
1036
|
catch (err) {
|
|
998
1037
|
if (warned)
|
|
999
1038
|
return;
|
|
1000
1039
|
warned = true;
|
|
1001
1040
|
// eslint-disable-next-line no-console
|
|
1002
|
-
console.warn(`[tidegap/scheduler] task ${taskId}: could not record a progress event: ${describeErr(err)}`);
|
|
1041
|
+
console.warn(`[tidegap/scheduler] task ${taskId}: could not record a progress event (this and later failed lines are dropped): ${describeErr(err)}`);
|
|
1003
1042
|
}
|
|
1004
|
-
}, { existing: () => store.
|
|
1043
|
+
}, { existing: () => store.countTaskEvents(taskId, "progress") });
|
|
1044
|
+
}
|
|
1045
|
+
/** `{ tick }` for a `dispatched` event under the tick lock; else nothing. */
|
|
1046
|
+
tickDetails() {
|
|
1047
|
+
return this.lockedTick ? { tick: this.lockedTick.tick } : {};
|
|
1005
1048
|
}
|
|
1006
1049
|
/** `{ sleep }` for a `dispatched` event when the host reads a sleep counter; else nothing. Never throws. */
|
|
1007
1050
|
sleepDetails() {
|
|
@@ -1582,56 +1625,57 @@ export class Scheduler {
|
|
|
1582
1625
|
});
|
|
1583
1626
|
}
|
|
1584
1627
|
/**
|
|
1585
|
-
*
|
|
1586
|
-
*
|
|
1587
|
-
*
|
|
1588
|
-
*
|
|
1628
|
+
* Retry a failed task by hand, starting a new attempt count. With a ready
|
|
1629
|
+
* adapter for the task's provider in `adapters`, the call runs now and
|
|
1630
|
+
* its result comes back. Otherwise, and always for a `command` or
|
|
1631
|
+
* `claude-code` task, which only the tidegap tick runs, the task is due
|
|
1632
|
+
* now ({@link retryLater}) and the next tick runs it. A manual retry
|
|
1633
|
+
* ignores the deadline: the user asked for it. Throws for a task that is
|
|
1634
|
+
* not failed, stopped during its Batch submit, closure-based or a run of
|
|
1635
|
+
* a job.
|
|
1589
1636
|
*/
|
|
1590
1637
|
async retryTask(taskId, adapters, opts = {}) {
|
|
1591
1638
|
const record = this.refreshTask(taskId);
|
|
1592
1639
|
if (!record) {
|
|
1593
|
-
throw new
|
|
1640
|
+
throw new TaskActionError(`retryTask: task ${JSON.stringify(taskId)} not found`);
|
|
1594
1641
|
}
|
|
1595
|
-
|
|
1596
|
-
|
|
1642
|
+
retryRefusal("retryTask", record);
|
|
1643
|
+
const provider = taskProvider(record);
|
|
1644
|
+
const adapter = provider ? adapters[provider] : undefined;
|
|
1645
|
+
if (provider === "command" || provider === "claude-code" || !adapter?.ready) {
|
|
1646
|
+
const queued = this.retryLater(taskId, opts);
|
|
1647
|
+
return { taskId, status: "scheduled", scheduledFor: queued.scheduledFor };
|
|
1597
1648
|
}
|
|
1598
|
-
if (record.error === BATCH_SUBMIT_INTERRUPTED_ERROR) {
|
|
1599
|
-
// Before the job-run refusal: the job does not retry this run either.
|
|
1600
|
-
throw new TaskActionError(`retryTask: task ${taskId} stopped during its Batch submit, and the provider may have accepted the batch; ` +
|
|
1601
|
-
"a retry could run and bill it twice, so check the provider's batch list and enqueue the task again only if no batch exists");
|
|
1602
|
-
}
|
|
1603
|
-
if (!record.bodyJson) {
|
|
1604
|
-
throw new Error(`retryTask: task ${taskId} is closure-based; only provider-call tasks can be retried`);
|
|
1605
|
-
}
|
|
1606
|
-
if (record.jobId) {
|
|
1607
|
-
// The job sweep already recorded this failure and queued a retry or
|
|
1608
|
-
// the next run; a second run of the same slot would go unrecorded.
|
|
1609
|
-
throw new TaskActionError(`retryTask: task ${taskId} is a run of job ${record.jobId}, which retries failed runs itself; use run now on the job`);
|
|
1610
|
-
}
|
|
1611
|
-
if (taskProvider(record) === "command") {
|
|
1612
|
-
// A one-off shell command: running it again is the user's call.
|
|
1613
|
-
throw new TaskActionError(`retryTask: task ${taskId} ran a shell command, which is never run again by a retry; ` +
|
|
1614
|
-
"queue it again with tidegap queue add --runner command");
|
|
1615
|
-
}
|
|
1616
|
-
const next = {
|
|
1617
|
-
...record,
|
|
1618
|
-
status: "scheduled",
|
|
1619
|
-
scheduledFor: new Date().toISOString(),
|
|
1620
|
-
completedAt: undefined,
|
|
1621
|
-
error: undefined,
|
|
1622
|
-
// A retry re-dispatches synchronously via the due path below — clear
|
|
1623
|
-
// any stale batchId from a prior batch attempt so the completed row
|
|
1624
|
-
// no longer points at a dead/failed batch.
|
|
1625
|
-
batchId: undefined,
|
|
1626
|
-
};
|
|
1627
1649
|
// Row-level claim: don't double-dispatch if a concurrent tick in
|
|
1628
1650
|
// another process grabbed the freshly re-scheduled row first.
|
|
1629
|
-
if (!this.writeIf(record,
|
|
1630
|
-
(
|
|
1631
|
-
throw new Error(`task ${taskId} was just claimed by another process (racing tick?)`);
|
|
1651
|
+
if (!this.writeIf(record, retryWrite(record), ["failed"], retryEvent(opts)) || (this.store && !this.store.claimScheduled(taskId))) {
|
|
1652
|
+
throw new TaskActionError(`retryTask: task ${taskId} was just claimed by another process (racing tick?)`);
|
|
1632
1653
|
}
|
|
1654
|
+
this.attemptsWithoutLedger.delete(taskId);
|
|
1633
1655
|
return await this.dispatchProviderCall(record, adapters);
|
|
1634
1656
|
}
|
|
1657
|
+
/**
|
|
1658
|
+
* Retry a failed task on the next tick: `failed → scheduled`, due now, its
|
|
1659
|
+
* earliest start, error and completion time cleared, with a `rescheduled`
|
|
1660
|
+
* event (`reason: retry`), which starts a new attempt count. A write
|
|
1661
|
+
* only, for a process that does not dispatch (the CLI, the page's server)
|
|
1662
|
+
* or holds no adapter for the task. A manual retry ignores the deadline.
|
|
1663
|
+
* Throws {@link TaskActionError} for a task that is not failed, stopped
|
|
1664
|
+
* during its Batch submit, closure-based or a run of a job, and when
|
|
1665
|
+
* another process moved the row first.
|
|
1666
|
+
*/
|
|
1667
|
+
retryLater(taskId, opts = {}) {
|
|
1668
|
+
const record = this.refreshTask(taskId);
|
|
1669
|
+
if (!record)
|
|
1670
|
+
throw new TaskActionError(`retryLater: task ${JSON.stringify(taskId)} not found`);
|
|
1671
|
+
retryRefusal("retryLater", record);
|
|
1672
|
+
this.clearPendingTimer(taskId);
|
|
1673
|
+
if (!this.writeIf(record, retryWrite(record), ["failed"], retryEvent(opts))) {
|
|
1674
|
+
throw new TaskActionError(`retryLater: task ${taskId} was just claimed by another process (racing tick?)`);
|
|
1675
|
+
}
|
|
1676
|
+
this.attemptsWithoutLedger.delete(taskId);
|
|
1677
|
+
return record;
|
|
1678
|
+
}
|
|
1635
1679
|
/**
|
|
1636
1680
|
* Pure read-only planning helper: compute the scheduled window and
|
|
1637
1681
|
* carbon receipt that the same call to `enqueueProviderCall` would
|
|
@@ -1743,11 +1787,239 @@ export class Scheduler {
|
|
|
1743
1787
|
this.held.delete(record.taskId);
|
|
1744
1788
|
}
|
|
1745
1789
|
}
|
|
1790
|
+
/**
|
|
1791
|
+
* Watch a held row while its run is in flight: read its status every
|
|
1792
|
+
* {@link RUN_STATUS_CHECK_MS} and abort the returned signal once another
|
|
1793
|
+
* writer moved it off `running` (a cancel, or a `failed` written
|
|
1794
|
+
* elsewhere), so a retry can never overlap the run; `end` stops the watch
|
|
1795
|
+
* when the run settles.
|
|
1796
|
+
*/
|
|
1797
|
+
cancelWatch(taskId) {
|
|
1798
|
+
const controller = new AbortController();
|
|
1799
|
+
const timer = setInterval(() => {
|
|
1800
|
+
let status;
|
|
1801
|
+
try {
|
|
1802
|
+
status = (this.store?.get(taskId) ?? this.tasks.get(taskId))?.status;
|
|
1803
|
+
}
|
|
1804
|
+
catch {
|
|
1805
|
+
return; // a busy ledger: the next check reads it again
|
|
1806
|
+
}
|
|
1807
|
+
if (status === undefined || status === "running")
|
|
1808
|
+
return;
|
|
1809
|
+
clearInterval(timer);
|
|
1810
|
+
controller.abort();
|
|
1811
|
+
}, RUN_STATUS_CHECK_MS);
|
|
1812
|
+
timer.unref?.();
|
|
1813
|
+
return { signal: controller.signal, end: () => clearInterval(timer) };
|
|
1814
|
+
}
|
|
1815
|
+
/**
|
|
1816
|
+
* A run the watch stopped because its row left `running`. A cancel keeps
|
|
1817
|
+
* the row, and its event gains `stopped_run: true`; any other move (a row
|
|
1818
|
+
* failed elsewhere) keeps what that writer wrote. Nothing else is written,
|
|
1819
|
+
* as for a late result; the writer that moved the row settled its series.
|
|
1820
|
+
*/
|
|
1821
|
+
stoppedRun(record) {
|
|
1822
|
+
let status = "cancelled";
|
|
1823
|
+
try {
|
|
1824
|
+
status = this.store?.get(record.taskId)?.status ?? record.status;
|
|
1825
|
+
}
|
|
1826
|
+
catch {
|
|
1827
|
+
// A busy ledger: report it as the cancel the watch most likely saw.
|
|
1828
|
+
}
|
|
1829
|
+
record.status = status;
|
|
1830
|
+
if (status !== "cancelled") {
|
|
1831
|
+
// eslint-disable-next-line no-console
|
|
1832
|
+
console.warn(`[tidegap/scheduler] task ${record.taskId} was ${status} while running; its run was stopped`);
|
|
1833
|
+
return { taskId: record.taskId, status: "failed", error: `task was ${status} while running; its run was stopped` };
|
|
1834
|
+
}
|
|
1835
|
+
try {
|
|
1836
|
+
this.store?.annotateEvent(record.taskId, "cancelled", { stopped_run: true });
|
|
1837
|
+
}
|
|
1838
|
+
catch (err) {
|
|
1839
|
+
// eslint-disable-next-line no-console
|
|
1840
|
+
console.warn(`[tidegap/scheduler] task ${record.taskId}: could not note the stopped run: ${describeErr(err)}`);
|
|
1841
|
+
}
|
|
1842
|
+
// eslint-disable-next-line no-console
|
|
1843
|
+
console.warn(`[tidegap/scheduler] task ${record.taskId} was cancelled while running; its run was stopped`);
|
|
1844
|
+
return { taskId: record.taskId, status: "failed", error: STOPPED_RUN_ERROR };
|
|
1845
|
+
}
|
|
1846
|
+
/**
|
|
1847
|
+
* The retry funnel: every provider-call run that fails ends here. A
|
|
1848
|
+
* one-off row whose failure class may retry, with retries left and a next
|
|
1849
|
+
* start that fits before its deadline, goes back to `scheduled`
|
|
1850
|
+
* (compare-and-set on `expected`, `running` by default) with an
|
|
1851
|
+
* `attempt_failed` event: `notBefore` is the next start, the fallback time
|
|
1852
|
+
* one minute later, the deadline unchanged, the estimate, the run-now mark
|
|
1853
|
+
* and any batch id cleared. Anything else fails for good: `failed`, with
|
|
1854
|
+
* `attempts` and `failure_class` on the event and `(after N attempts)` on
|
|
1855
|
+
* the error when more than one ran. A job row always fails for good (the
|
|
1856
|
+
* job sweep makes its retry row). The series rolls on a final failure
|
|
1857
|
+
* only. Synchronous; an async caller then plans the next attempt's window
|
|
1858
|
+
* ({@link planRetryWindow}).
|
|
1859
|
+
*/
|
|
1860
|
+
failRun(record, failure, expected = ["running"]) {
|
|
1861
|
+
const now = Date.now();
|
|
1862
|
+
const failureClass = classifyFailure(failure.facts);
|
|
1863
|
+
const attempt = this.store ? attemptNumber(this.listTaskEvents(record.taskId)) : (this.attemptsWithoutLedger.get(record.taskId) ?? 0) + 1;
|
|
1864
|
+
let spec;
|
|
1865
|
+
try {
|
|
1866
|
+
spec = JSON.parse(record.bodyJson ?? "null");
|
|
1867
|
+
}
|
|
1868
|
+
catch {
|
|
1869
|
+
spec = undefined;
|
|
1870
|
+
}
|
|
1871
|
+
const deadlineMs = record.deadline ? Date.parse(record.deadline) : Number.NaN;
|
|
1872
|
+
const notBeforeMs = record.notBefore ? Date.parse(record.notBefore) : Number.NaN;
|
|
1873
|
+
let plan;
|
|
1874
|
+
if (!record.jobId && typeof spec?.provider === "string" && isRetryableFailure(failureClass)) {
|
|
1875
|
+
plan = planRetry({
|
|
1876
|
+
attempt,
|
|
1877
|
+
...retryPolicyOf(this.runLimitsFor(spec)),
|
|
1878
|
+
failedAt: now,
|
|
1879
|
+
...(Number.isFinite(deadlineMs) ? { deadline: deadlineMs } : {}),
|
|
1880
|
+
...(Number.isFinite(notBeforeMs) ? { notBefore: notBeforeMs } : {}),
|
|
1881
|
+
});
|
|
1882
|
+
}
|
|
1883
|
+
const firstLine = failure.error.split("\n")[0].slice(0, 300);
|
|
1884
|
+
if (plan && "retryAt" in plan) {
|
|
1885
|
+
const retryAt = new Date(plan.retryAt).toISOString();
|
|
1886
|
+
const fallback = Number.isFinite(deadlineMs) ? Math.min(plan.retryAt + MINUTE_MS, deadlineMs) : plan.retryAt + MINUTE_MS;
|
|
1887
|
+
const next = {
|
|
1888
|
+
...record,
|
|
1889
|
+
status: "scheduled",
|
|
1890
|
+
notBefore: retryAt,
|
|
1891
|
+
scheduledFor: new Date(fallback).toISOString(),
|
|
1892
|
+
estimatedCarbonGCo2: undefined,
|
|
1893
|
+
intensitySource: undefined,
|
|
1894
|
+
batchId: undefined,
|
|
1895
|
+
completedAt: undefined,
|
|
1896
|
+
error: undefined,
|
|
1897
|
+
};
|
|
1898
|
+
const event = {
|
|
1899
|
+
kind: "attempt_failed",
|
|
1900
|
+
details: { ...failure.details, attempt, failure_class: failureClass, error: firstLine, retry_at: retryAt },
|
|
1901
|
+
};
|
|
1902
|
+
if (!this.writeIf(record, next, expected, event)) {
|
|
1903
|
+
return { taskId: record.taskId, status: "failed", error: `task was ${record.status} while running; retry dropped` };
|
|
1904
|
+
}
|
|
1905
|
+
if (!this.store)
|
|
1906
|
+
this.attemptsWithoutLedger.set(record.taskId, attempt);
|
|
1907
|
+
return { taskId: record.taskId, status: "retrying", retryAt, error: failure.error };
|
|
1908
|
+
}
|
|
1909
|
+
// The Batch submit marker stays exact: retry refusals compare the error with it.
|
|
1910
|
+
const error = failureClass === "batch_submit_interrupted" ? failure.error : finalFailureError(failure.error, attempt, plan && "final" in plan ? plan.final : undefined);
|
|
1911
|
+
if (!failure.keepSeries)
|
|
1912
|
+
this.rollSeries(record);
|
|
1913
|
+
this.attemptsWithoutLedger.delete(record.taskId);
|
|
1914
|
+
this.writeIf(record, { ...record, status: "failed", completedAt: new Date(now).toISOString(), error }, expected, {
|
|
1915
|
+
kind: "failed",
|
|
1916
|
+
details: { ...failure.details, attempts: attempt, failure_class: failureClass },
|
|
1917
|
+
});
|
|
1918
|
+
return { taskId: record.taskId, status: "failed", error };
|
|
1919
|
+
}
|
|
1920
|
+
/** {@link failRun} for a thrown error: its facts, and its run details (`steps`, `stopped_by`, `truncated`) for the event. */
|
|
1921
|
+
failRunWith(record, err) {
|
|
1922
|
+
const details = runDetails(err?.details);
|
|
1923
|
+
return this.failRun(record, { error: err instanceof Error ? err.message : String(err), facts: failureFactsOf(err), details });
|
|
1924
|
+
}
|
|
1925
|
+
/**
|
|
1926
|
+
* After {@link failRun} queued another attempt: plan it at the cleanest
|
|
1927
|
+
* hour between its earliest start and its deadline. Best effort: without
|
|
1928
|
+
* a deadline, or when the forecast fails, the row keeps its fallback time
|
|
1929
|
+
* and `replanSweep` plans it before a later tick.
|
|
1930
|
+
*/
|
|
1931
|
+
async planRetryWindow(entry) {
|
|
1932
|
+
if (entry.status !== "retrying")
|
|
1933
|
+
return entry;
|
|
1934
|
+
const record = this.tasks.get(entry.taskId);
|
|
1935
|
+
if (!record?.deadline)
|
|
1936
|
+
return entry;
|
|
1937
|
+
try {
|
|
1938
|
+
await this.scheduleProviderCall(entry.taskId, new Date(record.deadline));
|
|
1939
|
+
}
|
|
1940
|
+
catch (err) {
|
|
1941
|
+
// eslint-disable-next-line no-console
|
|
1942
|
+
console.warn(`[tidegap/scheduler] could not plan the next attempt of ${entry.taskId}: ${describeErr(err)}; replanSweep plans it later`);
|
|
1943
|
+
}
|
|
1944
|
+
return entry;
|
|
1945
|
+
}
|
|
1946
|
+
/**
|
|
1947
|
+
* The tick-lock rule for a `running` row, shared by the head of a locked
|
|
1948
|
+
* tick and the job sweep: true when the run was dispatched under another
|
|
1949
|
+
* locked tick whose process is gone, false when that tick is this one or
|
|
1950
|
+
* its process still runs. Undefined when this scheduler holds no lock, the
|
|
1951
|
+
* row's newest event (progress lines aside) is not a dispatch with tick
|
|
1952
|
+
* details (no locked tick ran it, or the row moved on since), or the host
|
|
1953
|
+
* cannot tell whether that tick's process runs: the run may be live.
|
|
1954
|
+
*/
|
|
1955
|
+
deadTickRun(row) {
|
|
1956
|
+
const locked = this.lockedTick;
|
|
1957
|
+
if (!locked)
|
|
1958
|
+
return undefined;
|
|
1959
|
+
const tick = tickDispatch(this.listTaskEvents(row.taskId))?.tick;
|
|
1960
|
+
if (!tick)
|
|
1961
|
+
return undefined;
|
|
1962
|
+
if (tick.id === locked.tick.id)
|
|
1963
|
+
return false;
|
|
1964
|
+
try {
|
|
1965
|
+
const running = locked.isRunning(tick);
|
|
1966
|
+
return running === undefined ? undefined : !running;
|
|
1967
|
+
}
|
|
1968
|
+
catch {
|
|
1969
|
+
return undefined;
|
|
1970
|
+
}
|
|
1971
|
+
}
|
|
1972
|
+
/**
|
|
1973
|
+
* The head of a locked tick, before any sweep claims a row: a one-off
|
|
1974
|
+
* `running` row whose run a dead tick dispatched ({@link deadTickRun})
|
|
1975
|
+
* fails as interrupted through the retry funnel (another attempt when the
|
|
1976
|
+
* policy allows it), and a Batch row with its batch id goes back to
|
|
1977
|
+
* `submitted` for the poll sweep. Compare-and-set from `running`. Job rows
|
|
1978
|
+
* are the job sweep's; rows this scheduler holds are live. Returns the
|
|
1979
|
+
* entries of the rows it failed or queued again.
|
|
1980
|
+
*/
|
|
1981
|
+
freeDeadTickRuns() {
|
|
1982
|
+
if (!this.lockedTick || !this.store)
|
|
1983
|
+
return [];
|
|
1984
|
+
let rows;
|
|
1985
|
+
try {
|
|
1986
|
+
rows = this.store.list({ status: "running" });
|
|
1987
|
+
}
|
|
1988
|
+
catch (err) {
|
|
1989
|
+
// eslint-disable-next-line no-console
|
|
1990
|
+
console.warn(`[tidegap/scheduler] tick: could not read running rows: ${describeErr(err)}; no dead tick's row freed this round`);
|
|
1991
|
+
return [];
|
|
1992
|
+
}
|
|
1993
|
+
const out = [];
|
|
1994
|
+
for (const row of rows) {
|
|
1995
|
+
if (row.jobId || this.held.has(row.taskId))
|
|
1996
|
+
continue;
|
|
1997
|
+
try {
|
|
1998
|
+
if (this.deadTickRun(row) !== true)
|
|
1999
|
+
continue;
|
|
2000
|
+
const record = this.cacheRow(row);
|
|
2001
|
+
if (row.batchId) {
|
|
2002
|
+
this.writeIf(record, { ...row, status: "submitted", completedAt: undefined, error: undefined }, ["running"]);
|
|
2003
|
+
continue;
|
|
2004
|
+
}
|
|
2005
|
+
const entry = this.failRun(record, { error: JOB_INTERRUPTED_ERROR, facts: { interrupted: "run" }, details: { reason: "interrupted" } });
|
|
2006
|
+
if (entry.status === "retrying" || record.status === "failed")
|
|
2007
|
+
out.push(entry);
|
|
2008
|
+
}
|
|
2009
|
+
catch (err) {
|
|
2010
|
+
// eslint-disable-next-line no-console
|
|
2011
|
+
console.warn(`[tidegap/scheduler] tick: could not free ${row.taskId} of a dead tick: ${describeErr(err)}; skipping this round`);
|
|
2012
|
+
}
|
|
2013
|
+
}
|
|
2014
|
+
return out;
|
|
2015
|
+
}
|
|
1746
2016
|
/**
|
|
1747
2017
|
* A forced stop of the tick (KTD12, batch 25 KTD4): settle every row this
|
|
1748
2018
|
* scheduler moved to `running` in a tick whose dispatch has not settled,
|
|
1749
2019
|
* by what the row was doing:
|
|
1750
|
-
* - a provider call fails as interrupted (`JOB_INTERRUPTED_ERROR`)
|
|
2020
|
+
* - a provider call fails as interrupted (`JOB_INTERRUPTED_ERROR`)
|
|
2021
|
+
* through the retry funnel: a one-off row with retries left is
|
|
2022
|
+
* queued again, its window planned before a later tick;
|
|
1751
2023
|
* - a Batch poll goes back to `submitted` with its `batchId`: the batch
|
|
1752
2024
|
* is live at the provider, and the next tick polls it again;
|
|
1753
2025
|
* - a Batch submit fails with `BATCH_SUBMIT_INTERRUPTED_ERROR`: the
|
|
@@ -1756,8 +2028,8 @@ export class Scheduler {
|
|
|
1756
2028
|
* keeps its status; rows another process holds, or a crashed tick
|
|
1757
2029
|
* stranded, are not touched (the job sweep frees job runs, and the next
|
|
1758
2030
|
* tick a Batch poll past its deadline: `freeStrandedPolls`). Synchronous, for
|
|
1759
|
-
* a process about to exit. Returns the ids it failed; a
|
|
1760
|
-
* changes nothing.
|
|
2031
|
+
* a process about to exit. Returns the ids it failed or queued again; a
|
|
2032
|
+
* second call changes nothing.
|
|
1761
2033
|
*/
|
|
1762
2034
|
failHeldRuns() {
|
|
1763
2035
|
const failed = [];
|
|
@@ -1766,12 +2038,12 @@ export class Scheduler {
|
|
|
1766
2038
|
this.writeIf(record, { ...record, status: "submitted", completedAt: undefined, error: undefined }, ["running"]);
|
|
1767
2039
|
continue;
|
|
1768
2040
|
}
|
|
1769
|
-
this.rollSeries(record);
|
|
1770
2041
|
const submit = phase === "batch_submit";
|
|
1771
2042
|
const details = { reason: "interrupted", ...(submit ? { phase } : {}), ...(record.jobId ? { job_id: record.jobId } : {}) };
|
|
1772
2043
|
const error = submit ? BATCH_SUBMIT_INTERRUPTED_ERROR : JOB_INTERRUPTED_ERROR;
|
|
1773
|
-
|
|
1774
|
-
|
|
2044
|
+
// The next attempt keeps its fallback time; replanSweep plans it before a later tick.
|
|
2045
|
+
const entry = this.failRun(record, { error, facts: { interrupted: submit ? "batch_submit" : "run" }, details });
|
|
2046
|
+
if (entry.status === "retrying" || record.status === "failed")
|
|
1775
2047
|
failed.push(record.taskId);
|
|
1776
2048
|
}
|
|
1777
2049
|
this.held.clear();
|
|
@@ -2185,13 +2457,10 @@ export class Scheduler {
|
|
|
2185
2457
|
}
|
|
2186
2458
|
catch (err) {
|
|
2187
2459
|
const msg = err instanceof Error ? err.message : String(err);
|
|
2188
|
-
this.
|
|
2189
|
-
return { taskId: record.taskId, status: "failed", error: msg };
|
|
2460
|
+
return this.failRun(record, { error: `tick: corrupt body_json: ${msg}`, facts: { permanent: true }, keepSeries: true }, UNFINISHED_STATUSES);
|
|
2190
2461
|
}
|
|
2191
2462
|
if (!spec || spec.type !== "provider_call") {
|
|
2192
|
-
|
|
2193
|
-
this.failTask(record.taskId, new Error(msg));
|
|
2194
|
-
return { taskId: record.taskId, status: "failed", error: msg };
|
|
2463
|
+
return this.failRun(record, { error: "tick: body is not a provider_call spec", facts: { permanent: true }, keepSeries: true }, UNFINISHED_STATUSES);
|
|
2195
2464
|
}
|
|
2196
2465
|
// Cross-provider routing fallback (ROADMAP item 1): when a routing
|
|
2197
2466
|
// decision is attached, dispatch the highest-scoring candidate whose
|
|
@@ -2209,9 +2478,7 @@ export class Scheduler {
|
|
|
2209
2478
|
if (!picked) {
|
|
2210
2479
|
const msg = `tick: no configured/ready adapter for any routing candidate ` +
|
|
2211
2480
|
`(${routing.considered.map((c) => candidateId(c)).join(", ")})`;
|
|
2212
|
-
this.
|
|
2213
|
-
this.failTask(record.taskId, new Error(msg));
|
|
2214
|
-
return { taskId: record.taskId, status: "failed", error: msg };
|
|
2481
|
+
return this.failRun(record, { error: msg, facts: { permanent: true } }, UNFINISHED_STATUSES);
|
|
2215
2482
|
}
|
|
2216
2483
|
const pickedId = candidateId(picked);
|
|
2217
2484
|
if (pickedId !== routing.chosen) {
|
|
@@ -2231,21 +2498,27 @@ export class Scheduler {
|
|
|
2231
2498
|
// No rollover: a missing adapter is a skip (OpenClaw restores the row
|
|
2232
2499
|
// to `scheduled`), and a successor would run beside the occurrence.
|
|
2233
2500
|
// A retry that completes rolls the series then.
|
|
2234
|
-
this.
|
|
2235
|
-
return { taskId: record.taskId, status: "failed", error: msg };
|
|
2501
|
+
return this.failRun(record, { error: msg, facts: { permanent: true }, keepSeries: true }, UNFINISHED_STATUSES);
|
|
2236
2502
|
}
|
|
2237
2503
|
const deferKey = deferKeyOf(spec);
|
|
2238
2504
|
const earlier = deferrals?.get(deferKey);
|
|
2239
2505
|
if (earlier) {
|
|
2240
2506
|
return this.deferTask(record, earlier, `${spec.provider}: deferred with an earlier task this tick until ${earlier.toISOString()}`);
|
|
2241
2507
|
}
|
|
2508
|
+
const limits = this.runLimitsFor(spec);
|
|
2242
2509
|
let stillOurs = true;
|
|
2243
2510
|
try {
|
|
2244
2511
|
// The row was claimed (`running`) or, without a store, is ours. A
|
|
2245
2512
|
// cancel that landed after the claim wins: do not make the call.
|
|
2246
2513
|
stillOurs = this.writeIf(record, { ...record, status: "running" }, ["running", "scheduled"], {
|
|
2247
2514
|
kind: "dispatched",
|
|
2248
|
-
details: {
|
|
2515
|
+
details: {
|
|
2516
|
+
provider: spec.provider,
|
|
2517
|
+
model: spec.model,
|
|
2518
|
+
limits: runLimitsDetails(limits),
|
|
2519
|
+
...this.sleepDetails(),
|
|
2520
|
+
...this.tickDetails(),
|
|
2521
|
+
},
|
|
2249
2522
|
});
|
|
2250
2523
|
}
|
|
2251
2524
|
catch (err) {
|
|
@@ -2270,6 +2543,7 @@ export class Scheduler {
|
|
|
2270
2543
|
// Lines the run reports while it runs (the command adapter's output);
|
|
2271
2544
|
// nothing is written once the call settled.
|
|
2272
2545
|
const progress = this.progressFor(record.taskId);
|
|
2546
|
+
const watch = this.cancelWatch(record.taskId);
|
|
2273
2547
|
try {
|
|
2274
2548
|
// Batch routing (deadline > 24h) is handled by the dedicated
|
|
2275
2549
|
// submit/poll sweeps in tick(); by the time a task reaches this
|
|
@@ -2281,21 +2555,24 @@ export class Scheduler {
|
|
|
2281
2555
|
messages: spec.messages,
|
|
2282
2556
|
...(spec.tools !== undefined ? { tools: spec.tools } : {}),
|
|
2283
2557
|
...dispatchOrigin(record, spec),
|
|
2284
|
-
...jobDispatchOptions(record, spec),
|
|
2558
|
+
...jobDispatchOptions(record, spec, limits),
|
|
2285
2559
|
...(progress ? { onProgress: (line) => progress.onLine(line), onProgressEnd: () => progress.close() } : {}),
|
|
2286
|
-
|
|
2560
|
+
signal: watch.signal,
|
|
2561
|
+
}), watch.signal).finally(() => progress?.close());
|
|
2287
2562
|
}
|
|
2288
2563
|
catch (err) {
|
|
2564
|
+
if (watch.signal.aborted)
|
|
2565
|
+
return this.stoppedRun(record);
|
|
2289
2566
|
const msg = err instanceof Error ? err.message : String(err);
|
|
2290
2567
|
const retryAt = deferRetryAt(err);
|
|
2291
2568
|
if (retryAt) {
|
|
2292
2569
|
deferrals?.set(deferKey, retryAt);
|
|
2293
2570
|
return this.deferTask(record, retryAt, msg);
|
|
2294
2571
|
}
|
|
2295
|
-
this.
|
|
2296
|
-
|
|
2297
|
-
|
|
2298
|
-
|
|
2572
|
+
return this.planRetryWindow(this.failRunWith(record, err));
|
|
2573
|
+
}
|
|
2574
|
+
finally {
|
|
2575
|
+
watch.end();
|
|
2299
2576
|
}
|
|
2300
2577
|
const durationMs = Date.now() - start;
|
|
2301
2578
|
// The task may have been cancelled while the provider call was in
|
|
@@ -2461,10 +2738,8 @@ export class Scheduler {
|
|
|
2461
2738
|
const retryMs = retryAt.getTime();
|
|
2462
2739
|
const capMs = Date.parse(record.enqueuedAt) + DEFER_CAP_MS;
|
|
2463
2740
|
if (retryMs + NOT_BEFORE_SPAN_MS > capMs) {
|
|
2464
|
-
|
|
2465
|
-
this.
|
|
2466
|
-
this.writeIf(record, { ...record, status: "failed", completedAt: new Date().toISOString(), error }, ["running"]);
|
|
2467
|
-
return { taskId: record.taskId, status: "failed", error };
|
|
2741
|
+
// A later attempt would meet the same cap: permanent.
|
|
2742
|
+
return this.failRun(record, { error: `${message}; limit did not reset before the 8-day cap`, facts: { permanent: true } });
|
|
2468
2743
|
}
|
|
2469
2744
|
const next = {
|
|
2470
2745
|
...record,
|
|
@@ -2502,8 +2777,7 @@ export class Scheduler {
|
|
|
2502
2777
|
}
|
|
2503
2778
|
catch (err) {
|
|
2504
2779
|
const msg = err instanceof Error ? err.message : String(err);
|
|
2505
|
-
this.
|
|
2506
|
-
return { taskId: record.taskId, status: "failed", error: msg };
|
|
2780
|
+
return this.failRun(record, { error: `tick: corrupt body_json: ${msg}`, facts: { permanent: true }, keepSeries: true }, UNFINISHED_STATUSES);
|
|
2507
2781
|
}
|
|
2508
2782
|
const adapter = adapters[spec.provider];
|
|
2509
2783
|
const dispatchBatch = adapter?.dispatchBatch;
|
|
@@ -2511,8 +2785,7 @@ export class Scheduler {
|
|
|
2511
2785
|
// Should not happen — collectBatchSubmitCandidates already filtered
|
|
2512
2786
|
// — but stay defensive: fall back to a clear failure.
|
|
2513
2787
|
const msg = `tick: batch submit selected but adapter/dispatchBatch missing for ${spec.provider}`;
|
|
2514
|
-
this.
|
|
2515
|
-
return { taskId: record.taskId, status: "failed", error: msg };
|
|
2788
|
+
return this.failRun(record, { error: msg, facts: { permanent: true }, keepSeries: true }, UNFINISHED_STATUSES);
|
|
2516
2789
|
}
|
|
2517
2790
|
try {
|
|
2518
2791
|
const handle = await retryWithBackoff(() => dispatchBatch.call(adapter, spec.model, [spec.prompt], {
|
|
@@ -2522,7 +2795,7 @@ export class Scheduler {
|
|
|
2522
2795
|
messages: spec.messages,
|
|
2523
2796
|
}));
|
|
2524
2797
|
try {
|
|
2525
|
-
if (!this.writeIf(record, { ...record, status: "submitted", batchId: handle.batchId }, ["running"], { kind: "dispatched", details: { batch_id: handle.batchId } })) {
|
|
2798
|
+
if (!this.writeIf(record, { ...record, status: "submitted", batchId: handle.batchId }, ["running"], { kind: "dispatched", details: { batch_id: handle.batchId, ...this.tickDetails() } })) {
|
|
2526
2799
|
// Another writer moved the row (a cancel) during the submit: it
|
|
2527
2800
|
// keeps its status, and the live batch is reported, not stored.
|
|
2528
2801
|
const error = `task was ${record.status} while its batch was submitted; batch ${handle.batchId} is not stored, and the provider may still run and bill it`;
|
|
@@ -2559,9 +2832,8 @@ export class Scheduler {
|
|
|
2559
2832
|
held.phase = "provider_call";
|
|
2560
2833
|
return this.dispatchProviderCall(record, adapters);
|
|
2561
2834
|
}
|
|
2562
|
-
|
|
2563
|
-
this.
|
|
2564
|
-
return { taskId: record.taskId, status: "failed", error: msg };
|
|
2835
|
+
// The submit failed, so no batch exists: a later attempt may submit again.
|
|
2836
|
+
return this.planRetryWindow(this.failRunWith(record, err));
|
|
2565
2837
|
}
|
|
2566
2838
|
}
|
|
2567
2839
|
/**
|
|
@@ -2581,8 +2853,7 @@ export class Scheduler {
|
|
|
2581
2853
|
}
|
|
2582
2854
|
catch (err) {
|
|
2583
2855
|
const msg = err instanceof Error ? err.message : String(err);
|
|
2584
|
-
this.
|
|
2585
|
-
return { taskId: record.taskId, status: "failed", error: msg };
|
|
2856
|
+
return this.failRun(record, { error: `tick: corrupt body_json: ${msg}`, facts: { permanent: true }, keepSeries: true }, UNFINISHED_STATUSES);
|
|
2586
2857
|
}
|
|
2587
2858
|
const adapter = adapters[spec.provider];
|
|
2588
2859
|
if (!adapter || typeof adapter.retrieveBatch !== "function") {
|
|
@@ -2596,9 +2867,7 @@ export class Scheduler {
|
|
|
2596
2867
|
}
|
|
2597
2868
|
const batchId = record.batchId;
|
|
2598
2869
|
if (!batchId) {
|
|
2599
|
-
|
|
2600
|
-
this.failTask(record.taskId, new Error(msg));
|
|
2601
|
-
return { taskId: record.taskId, status: "failed", error: msg };
|
|
2870
|
+
return this.failRun(record, { error: "tick: submitted task has no batchId", facts: { permanent: true }, keepSeries: true }, UNFINISHED_STATUSES);
|
|
2602
2871
|
}
|
|
2603
2872
|
const ranAt = new Date();
|
|
2604
2873
|
let poll;
|
|
@@ -2618,18 +2887,13 @@ export class Scheduler {
|
|
|
2618
2887
|
return { taskId: record.taskId, status: "submitted" };
|
|
2619
2888
|
}
|
|
2620
2889
|
if (poll.status === "failed" || poll.status === "expired") {
|
|
2621
|
-
|
|
2622
|
-
this.
|
|
2623
|
-
this.writeIf(record, { ...record, status: "failed", completedAt: new Date().toISOString(), error: msg }, ["running"]);
|
|
2624
|
-
return { taskId: record.taskId, status: "failed", error: msg };
|
|
2890
|
+
// The batch is over at the provider: a later attempt submits the task again.
|
|
2891
|
+
return this.planRetryWindow(this.failRun(record, { error: poll.error ?? `batch ${poll.status}`, facts: {} }));
|
|
2625
2892
|
}
|
|
2626
2893
|
// completed — take the first (single-prompt) result.
|
|
2627
2894
|
const first = poll.results?.[0];
|
|
2628
2895
|
if (!first) {
|
|
2629
|
-
|
|
2630
|
-
this.rollSeries(record);
|
|
2631
|
-
this.writeIf(record, { ...record, status: "failed", completedAt: new Date().toISOString(), error: msg }, ["running"]);
|
|
2632
|
-
return { taskId: record.taskId, status: "failed", error: msg };
|
|
2896
|
+
return this.planRetryWindow(this.failRun(record, { error: "batch completed with no results", facts: {} }));
|
|
2633
2897
|
}
|
|
2634
2898
|
// Shape a DispatchResult-like object so the receipt path is identical
|
|
2635
2899
|
// to the sync dispatch.
|
|
@@ -2753,18 +3017,46 @@ export class Scheduler {
|
|
|
2753
3017
|
};
|
|
2754
3018
|
}
|
|
2755
3019
|
}
|
|
3020
|
+
/** The caps keys a one-off model call takes: its LLM time limit and its retry policy. */
|
|
3021
|
+
const MODEL_CALL_CAPS_KEYS = new Set(["llmTimeoutMs", "retries", "retryDelayMs"]);
|
|
3022
|
+
/**
|
|
3023
|
+
* The caps a one-off row stores: only the keys the caller set, each checked
|
|
3024
|
+
* (a time limit from 1 s to 7 days or `"none"`, retries from 0 to 10, a
|
|
3025
|
+
* retry delay from 1 s to 7 days, any other cap a positive number), with
|
|
3026
|
+
* `capsVersion: 2`. Throws on an unknown key or a bad value.
|
|
3027
|
+
*/
|
|
3028
|
+
function checkedCaps(caps, keys, what) {
|
|
3029
|
+
if (caps === undefined)
|
|
3030
|
+
return { capsVersion: CAPS_VERSION };
|
|
3031
|
+
if (!caps || typeof caps !== "object" || Array.isArray(caps))
|
|
3032
|
+
throw new Error(`${what}: caps must be an object`);
|
|
3033
|
+
const out = {};
|
|
3034
|
+
for (const [key, value] of Object.entries(caps)) {
|
|
3035
|
+
if (key === "capsVersion" || value === undefined)
|
|
3036
|
+
continue;
|
|
3037
|
+
if (!keys.has(key))
|
|
3038
|
+
throw new Error(`${what}: unknown cap "${key}"`);
|
|
3039
|
+
const error = capValueError(key, value);
|
|
3040
|
+
if (error)
|
|
3041
|
+
throw new Error(`${what}: ${error}`);
|
|
3042
|
+
out[key] = value;
|
|
3043
|
+
}
|
|
3044
|
+
return { ...out, capsVersion: CAPS_VERSION };
|
|
3045
|
+
}
|
|
2756
3046
|
/**
|
|
2757
|
-
* Dispatch options of a
|
|
2758
|
-
*
|
|
2759
|
-
*
|
|
2760
|
-
*
|
|
3047
|
+
* Dispatch options of a run: its resolved time limits, the caps' budget,
|
|
3048
|
+
* and for a row with `job_id` its working directory and job id. A
|
|
3049
|
+
* `claude-code` row without a job gets its handoff folder. A `command` body
|
|
3050
|
+
* also hands over its shell and summarize steps.
|
|
2761
3051
|
*/
|
|
2762
|
-
function jobDispatchOptions(record, spec) {
|
|
3052
|
+
function jobDispatchOptions(record, spec, limits) {
|
|
2763
3053
|
const out = {};
|
|
2764
|
-
if (
|
|
2765
|
-
out.timeoutMs =
|
|
3054
|
+
if (limits.llm_timeout)
|
|
3055
|
+
out.timeoutMs = limits.llm_timeout.value;
|
|
3056
|
+
if (limits.command_timeout)
|
|
3057
|
+
out.commandTimeoutMs = limits.command_timeout.value;
|
|
3058
|
+
if (spec.caps?.maxBudgetUsd !== undefined)
|
|
2766
3059
|
out.maxBudgetUsd = spec.caps.maxBudgetUsd;
|
|
2767
|
-
}
|
|
2768
3060
|
if (record.jobId) {
|
|
2769
3061
|
out.jobId = record.jobId;
|
|
2770
3062
|
if (record.originCwd)
|
|
@@ -3070,6 +3362,51 @@ function refusal(action, record, allowed) {
|
|
|
3070
3362
|
const what = record.bodyJson ? record.status : `${record.status} (closure-based)`;
|
|
3071
3363
|
return `${action}: task ${record.taskId} is ${what}; ${allowed}`;
|
|
3072
3364
|
}
|
|
3365
|
+
/**
|
|
3366
|
+
* Throws the refusal of a manual retry, or returns for a task that can be
|
|
3367
|
+
* retried: a failed provider-call one-off that did not stop during its
|
|
3368
|
+
* Batch submit.
|
|
3369
|
+
*/
|
|
3370
|
+
function retryRefusal(action, record) {
|
|
3371
|
+
const taskId = record.taskId;
|
|
3372
|
+
if (record.status !== "failed") {
|
|
3373
|
+
throw new TaskActionError(`${action}: task ${taskId} has status ${record.status}; retry is only valid on failed tasks`);
|
|
3374
|
+
}
|
|
3375
|
+
if (record.error === BATCH_SUBMIT_INTERRUPTED_ERROR) {
|
|
3376
|
+
// Before the job-run refusal: the job does not retry this run either.
|
|
3377
|
+
throw new TaskActionError(`${action}: task ${taskId} stopped during its Batch submit, and the provider may have accepted the batch; ` +
|
|
3378
|
+
"a retry could run and bill it twice, so check the provider's batch list and enqueue the task again only if no batch exists");
|
|
3379
|
+
}
|
|
3380
|
+
if (!record.bodyJson) {
|
|
3381
|
+
throw new TaskActionError(`${action}: task ${taskId} is closure-based; only provider-call tasks can be retried`);
|
|
3382
|
+
}
|
|
3383
|
+
if (record.jobId) {
|
|
3384
|
+
// The job sweep already recorded this failure and queued a retry or
|
|
3385
|
+
// the next run; a second run of the same slot would go unrecorded.
|
|
3386
|
+
throw new TaskActionError(`${action}: task ${taskId} is a run of job ${record.jobId}, which retries failed runs itself; use run now on the job`);
|
|
3387
|
+
}
|
|
3388
|
+
}
|
|
3389
|
+
/**
|
|
3390
|
+
* A failed row retried by hand: due now with no earliest start, error and
|
|
3391
|
+
* completion time cleared, and no stale batch id (the retry dispatches
|
|
3392
|
+
* synchronously). The run-now mark keeps it off the Batch API.
|
|
3393
|
+
*/
|
|
3394
|
+
function retryWrite(record) {
|
|
3395
|
+
return {
|
|
3396
|
+
...record,
|
|
3397
|
+
status: "scheduled",
|
|
3398
|
+
scheduledFor: new Date().toISOString(),
|
|
3399
|
+
notBefore: undefined,
|
|
3400
|
+
completedAt: undefined,
|
|
3401
|
+
error: undefined,
|
|
3402
|
+
batchId: undefined,
|
|
3403
|
+
intensitySource: "expedited",
|
|
3404
|
+
};
|
|
3405
|
+
}
|
|
3406
|
+
/** The event of a manual retry; its reason starts a new attempt count. */
|
|
3407
|
+
function retryEvent(opts) {
|
|
3408
|
+
return { kind: "rescheduled", actor: opts.actor, details: { reason: "retry" } };
|
|
3409
|
+
}
|
|
3073
3410
|
/** Classify a reschedule target; exactly one shape must be given. */
|
|
3074
3411
|
function rescheduleShape(target) {
|
|
3075
3412
|
const t = (target ?? {});
|
|
@@ -3157,13 +3494,19 @@ export function pickBestWindow(entries, deadline) {
|
|
|
3157
3494
|
* errors raised *before* the request could reach the provider
|
|
3158
3495
|
* (ECONNREFUSED / ENOTFOUND / EAI_AGAIN). Ambiguous mid-flight errors
|
|
3159
3496
|
* (ETIMEDOUT, ECONNRESET) are NOT retried — the provider may already
|
|
3160
|
-
* have accepted and billed the call. Other 4xx bubble up immediately
|
|
3497
|
+
* have accepted and billed the call. Other 4xx bubble up immediately;
|
|
3498
|
+
* a 408 or 425 then gets the task retry (`isPermanentStatus` in run-limits).
|
|
3161
3499
|
*
|
|
3162
|
-
* This is the
|
|
3163
|
-
*
|
|
3164
|
-
*
|
|
3500
|
+
* This is the in-call resend for Tidegap: provider adapters construct
|
|
3501
|
+
* their SDK clients with `maxRetries: 0` so vendor-side retries cannot
|
|
3502
|
+
* multiply with this one. The task's retry policy (a later attempt) is a
|
|
3503
|
+
* separate layer, in the scheduler's retry funnel.
|
|
3504
|
+
*
|
|
3505
|
+
* `signal` (the task's cancel watch) ends the waits: once it aborts, no
|
|
3506
|
+
* further call is made, even when the adapter ignored the signal, and the
|
|
3507
|
+
* last error is thrown.
|
|
3165
3508
|
*/
|
|
3166
|
-
export async function retryWithBackoff(fn) {
|
|
3509
|
+
export async function retryWithBackoff(fn, signal) {
|
|
3167
3510
|
const waits = [1_000, 4_000, 16_000];
|
|
3168
3511
|
let lastErr;
|
|
3169
3512
|
for (let attempt = 0; attempt <= waits.length; attempt++) {
|
|
@@ -3172,16 +3515,30 @@ export async function retryWithBackoff(fn) {
|
|
|
3172
3515
|
}
|
|
3173
3516
|
catch (err) {
|
|
3174
3517
|
lastErr = err;
|
|
3175
|
-
if (!isRetryable(err) || attempt === waits.length) {
|
|
3518
|
+
if (!isRetryable(err) || attempt === waits.length || signal?.aborted) {
|
|
3176
3519
|
throw err;
|
|
3177
3520
|
}
|
|
3178
3521
|
// eslint-disable-next-line no-console
|
|
3179
3522
|
console.warn(`[tidegap/scheduler] dispatch attempt ${attempt + 1} failed (${describeErr(err)}); retrying in ${waits[attempt] / 1000}s`);
|
|
3180
|
-
await
|
|
3523
|
+
await waitUnlessAborted(waits[attempt], signal);
|
|
3524
|
+
if (signal?.aborted)
|
|
3525
|
+
throw err;
|
|
3181
3526
|
}
|
|
3182
3527
|
}
|
|
3183
3528
|
throw lastErr;
|
|
3184
3529
|
}
|
|
3530
|
+
/** Wait `ms`, or less when `signal` aborts first. */
|
|
3531
|
+
function waitUnlessAborted(ms, signal) {
|
|
3532
|
+
return new Promise((resolve) => {
|
|
3533
|
+
const done = () => {
|
|
3534
|
+
clearTimeout(timer);
|
|
3535
|
+
signal?.removeEventListener("abort", done);
|
|
3536
|
+
resolve();
|
|
3537
|
+
};
|
|
3538
|
+
const timer = setTimeout(done, ms);
|
|
3539
|
+
signal?.addEventListener("abort", done, { once: true });
|
|
3540
|
+
});
|
|
3541
|
+
}
|
|
3185
3542
|
function isRetryable(err) {
|
|
3186
3543
|
if (!err || typeof err !== "object")
|
|
3187
3544
|
return false;
|