@terreno/ai 57.10.1 → 57.11.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/harness/errors.d.ts +6 -0
- package/dist/harness/errors.js +6 -0
- package/dist/harness/harness.d.ts +2 -2
- package/dist/harness/harness.js +4 -2
- package/dist/harness/models/harnessTask.js +5 -0
- package/dist/harness/runners/inProcessRunner.d.ts +11 -4
- package/dist/harness/runners/inProcessRunner.js +44 -13
- package/dist/harness/runners/jobsRunner.d.ts +62 -0
- package/dist/harness/runners/jobsRunner.js +212 -0
- package/dist/harness/runtime.d.ts +20 -2
- package/dist/harness/runtime.js +84 -31
- package/dist/types/harness.d.ts +19 -1
- package/package.json +17 -6
- package/src/harness/concurrency.test.ts +155 -0
- package/src/harness/errors.ts +6 -0
- package/src/harness/events.test.ts +17 -5
- package/src/harness/harness.ts +14 -3
- package/src/harness/models/harnessTask.ts +5 -0
- package/src/harness/ownership.test.ts +9 -9
- package/src/harness/recovery.test.ts +2 -7
- package/src/harness/runners/inProcessRunner.test.ts +128 -0
- package/src/harness/runners/inProcessRunner.ts +54 -14
- package/src/harness/runners/jobsRunner.test.ts +709 -0
- package/src/harness/runners/jobsRunner.ts +252 -0
- package/src/harness/runtime.ts +117 -29
- package/src/types/harness.ts +25 -1
package/dist/harness/errors.d.ts
CHANGED
|
@@ -87,6 +87,12 @@ export declare const HARNESS_ERRORS: {
|
|
|
87
87
|
readonly status: 409;
|
|
88
88
|
readonly title: "requestId is already in use";
|
|
89
89
|
};
|
|
90
|
+
/** A `JobsRunner` phase job ran on an instance whose harness is not started. */
|
|
91
|
+
readonly runnerStopped: {
|
|
92
|
+
readonly code: "harness-runner-stopped";
|
|
93
|
+
readonly status: 503;
|
|
94
|
+
readonly title: "Harness runner is not running";
|
|
95
|
+
};
|
|
90
96
|
/** `retry` on a task whose abort is still running. */
|
|
91
97
|
readonly taskAborting: {
|
|
92
98
|
readonly code: "harness-task-aborting";
|
package/dist/harness/errors.js
CHANGED
|
@@ -65,6 +65,12 @@ exports.HARNESS_ERRORS = {
|
|
|
65
65
|
status: 409,
|
|
66
66
|
title: "requestId is already in use",
|
|
67
67
|
},
|
|
68
|
+
/** A `JobsRunner` phase job ran on an instance whose harness is not started. */
|
|
69
|
+
runnerStopped: {
|
|
70
|
+
code: "harness-runner-stopped",
|
|
71
|
+
status: 503,
|
|
72
|
+
title: "Harness runner is not running",
|
|
73
|
+
},
|
|
68
74
|
/** `retry` on a task whose abort is still running. */
|
|
69
75
|
taskAborting: { code: "harness-task-aborting", status: 409, title: "Task is being aborted" },
|
|
70
76
|
/** `resolveInterrupted` on a task that is not interrupted. */
|
|
@@ -6,7 +6,7 @@ import type { HarnessAbortOptions, HarnessAgentDefinition, HarnessApprovalDocume
|
|
|
6
6
|
import { HarnessConversationHandle } from "./conversation";
|
|
7
7
|
import type { ExecutionEnv } from "./executionEnv";
|
|
8
8
|
import { type HarnessRegistryEntry } from "./registry";
|
|
9
|
-
export type { AnyHarnessToolDefinition, HarnessAbortOptions, HarnessAbortRuntime, HarnessAgentDefinition, HarnessAgentDefinitionInput, HarnessApprovalDocument, HarnessApprovalOptions, HarnessApprovalPolicy, HarnessApprovalRequest, HarnessApprovalResult, HarnessApprovalStatus, HarnessApprover, HarnessBeforeToolResult, HarnessChildOutcome, HarnessChildTaskOptions, HarnessCommit, HarnessConversationAgent, HarnessConversationDocument, HarnessConversationStatus, HarnessCreateTaskOptions, HarnessDecideApprovalOptions, HarnessEventDocument, HarnessEventType, HarnessExtensionDefinition, HarnessExtensionDefinitionInput, HarnessHook, HarnessHookApi, HarnessHookHandlers, HarnessHookKind, HarnessInboxEventDocument, HarnessInterruptAction, HarnessLeaseSettings, HarnessMemo, HarnessMemoDocument, HarnessMessageDocument, HarnessMessagePart, HarnessMessageRole, HarnessModelRef, HarnessModelRequest, HarnessModelResolver, HarnessOutcome, HarnessPhaseCommit, HarnessPhaseDefinition, HarnessReplayPolicy, HarnessResolveAction, HarnessResolveInterruptedOptions, HarnessRetryPolicy, HarnessRunAgentOptions, HarnessRunner, HarnessRunnerContext, HarnessSection, HarnessSectionInput, HarnessSendEventOptions, HarnessSendOptions, HarnessStreamingOptions, HarnessSubmitDisposition, HarnessSubmitOptions, HarnessSubmitResult, HarnessSystemPromptPart, HarnessTaskDefinition, HarnessTaskDefinitionInput, HarnessTaskDocument, HarnessTaskRuntime, HarnessTaskSpanKind, HarnessTaskStatus, HarnessTaskView, HarnessTerminalCommit, HarnessTestHooks, HarnessTextPart, HarnessToolApi, HarnessToolCall, HarnessToolCallPart, HarnessToolDefinition, HarnessToolDefinitionInput, HarnessToolHookApi, HarnessToolResultPart, HarnessToolWrap, HarnessTurnResult, HarnessWaitCall, HarnessWaitForOptions, HarnessWaitForTasksOptions, HarnessWaiting, HarnessWaitKind, HarnessWaitPolicy, HarnessWaitResolution, HarnessWhenBusy, } from "../types/harness";
|
|
9
|
+
export type { AnyHarnessToolDefinition, HarnessAbortOptions, HarnessAbortRuntime, HarnessAgentDefinition, HarnessAgentDefinitionInput, HarnessApprovalDocument, HarnessApprovalOptions, HarnessApprovalPolicy, HarnessApprovalRequest, HarnessApprovalResult, HarnessApprovalStatus, HarnessApprover, HarnessBeforeToolResult, HarnessChildOutcome, HarnessChildTaskOptions, HarnessCommit, HarnessConversationAgent, HarnessConversationDocument, HarnessConversationStatus, HarnessCreateTaskOptions, HarnessDecideApprovalOptions, HarnessEventDocument, HarnessEventType, HarnessExtensionDefinition, HarnessExtensionDefinitionInput, HarnessHook, HarnessHookApi, HarnessHookHandlers, HarnessHookKind, HarnessInboxEventDocument, HarnessInterruptAction, HarnessLeaseSettings, HarnessMemo, HarnessMemoDocument, HarnessMessageDocument, HarnessMessagePart, HarnessMessageRole, HarnessModelRef, HarnessModelRequest, HarnessModelResolver, HarnessOutcome, HarnessPhaseCommit, HarnessPhaseDefinition, HarnessReplayPolicy, HarnessResolveAction, HarnessResolveInterruptedOptions, HarnessRetryPolicy, HarnessRunAgentOptions, HarnessRunnableTask, HarnessRunner, HarnessRunnerContext, HarnessRunTaskOptions, HarnessSection, HarnessSectionInput, HarnessSendEventOptions, HarnessSendOptions, HarnessStreamingOptions, HarnessSubmitDisposition, HarnessSubmitOptions, HarnessSubmitResult, HarnessSystemPromptPart, HarnessTaskDefinition, HarnessTaskDefinitionInput, HarnessTaskDocument, HarnessTaskRuntime, HarnessTaskSpanKind, HarnessTaskStatus, HarnessTaskView, HarnessTerminalCommit, HarnessTestHooks, HarnessTextPart, HarnessToolApi, HarnessToolCall, HarnessToolCallPart, HarnessToolDefinition, HarnessToolDefinitionInput, HarnessToolHookApi, HarnessToolResultPart, HarnessToolWrap, HarnessTurnResult, HarnessWaitCall, HarnessWaitForOptions, HarnessWaitForTasksOptions, HarnessWaiting, HarnessWaitKind, HarnessWaitPolicy, HarnessWaitResolution, HarnessWhenBusy, } from "../types/harness";
|
|
10
10
|
export { HARNESS_AGENT_DEFAULT_MAX_STEPS, HARNESS_APPROVAL_STATUSES, HARNESS_CONVERSATION_STATUSES, HARNESS_EVENT_TYPES, HARNESS_HOOK_KINDS, HARNESS_INTERRUPT_ACTIONS, HARNESS_MESSAGE_ROLES, HARNESS_MODEL_RETRY_DEFAULTS, HARNESS_RESOLVE_ACTIONS, HARNESS_RETRY_DEFAULTS, HARNESS_SUBMIT_DISPOSITIONS, HARNESS_TASK_STATUSES, HARNESS_WAIT_KINDS, HARNESS_WAIT_POLICIES, HARNESS_WAIT_RESOLUTIONS, HARNESS_WHEN_BUSY, } from "../types/harness";
|
|
11
11
|
export { AI_HARNESS_GROUP, HARNESS_APPROVALS_SCREEN, harnessAdminScreens } from "./adminScreens";
|
|
12
12
|
export { AGENT_TOOL_TASK_NAME, AGENT_TURN_TASK_NAME } from "./agentTaskNames";
|
|
@@ -89,7 +89,7 @@ export declare class Harness {
|
|
|
89
89
|
* process died between a turn's end and starting the next queued turn) and claim again.
|
|
90
90
|
*/
|
|
91
91
|
private claimNextOrSweep;
|
|
92
|
-
/** Stop claiming work and wait for
|
|
92
|
+
/** Stop claiming work and wait for every phase in flight to settle. */
|
|
93
93
|
stop(): Promise<void>;
|
|
94
94
|
/**
|
|
95
95
|
* Create a root task pinned to `definition`'s `name@version`. With `requestId`, a
|
package/dist/harness/harness.js
CHANGED
|
@@ -234,9 +234,11 @@ class Harness {
|
|
|
234
234
|
await this.runner.start({
|
|
235
235
|
acquireOwnerLease: (lease) => (0, leases_1.acquireOwnerLease)({ lease, models, testHooks }),
|
|
236
236
|
claimNext: (lease) => this.claimNextOrSweep(lease),
|
|
237
|
+
claimTask: (taskId, lease) => (0, runtime_1.claimTaskById)({ definitions, lease, models, taskId }),
|
|
238
|
+
listRunnable: (limit) => (0, runtime_1.listRunnableTasks)({ definitions, limit, models }),
|
|
237
239
|
recoverExpired: () => (0, runtime_1.recoverExpiredTasks)(engine),
|
|
238
240
|
releaseOwnerLease: (lease) => (0, leases_1.releaseOwnerLease)({ lease, models }),
|
|
239
|
-
runTask: (task, lease) => (0, runtime_1.runClaimedTask)({ engine, lease, task }),
|
|
241
|
+
runTask: (task, lease, options) => (0, runtime_1.runClaimedTask)({ engine, lease, maxPhases: options?.maxPhases, task }),
|
|
240
242
|
});
|
|
241
243
|
}
|
|
242
244
|
/**
|
|
@@ -256,7 +258,7 @@ class Harness {
|
|
|
256
258
|
}
|
|
257
259
|
return (0, runtime_1.claimNextTask)({ definitions, lease, models });
|
|
258
260
|
}
|
|
259
|
-
/** Stop claiming work and wait for
|
|
261
|
+
/** Stop claiming work and wait for every phase in flight to settle. */
|
|
260
262
|
async stop() {
|
|
261
263
|
if (!this.isStarted) {
|
|
262
264
|
return;
|
|
@@ -37,6 +37,11 @@ const harnessTaskSchema = new mongoose_1.default.Schema({
|
|
|
37
37
|
description: "When true, the task outlives its owning conversation turn",
|
|
38
38
|
type: Boolean,
|
|
39
39
|
},
|
|
40
|
+
claims: {
|
|
41
|
+
default: 0,
|
|
42
|
+
description: "Times a runner claimed the task; numbers each runnable visit for job dispatch",
|
|
43
|
+
type: Number,
|
|
44
|
+
},
|
|
40
45
|
eventSeq: {
|
|
41
46
|
default: 0,
|
|
42
47
|
description: "Events received by harness.sendEvent; numbers the task's inbox",
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import { type DurationLike } from "luxon";
|
|
2
2
|
import type { HarnessRunner, HarnessRunnerContext } from "../../types/harness";
|
|
3
3
|
export interface InProcessRunnerOptions {
|
|
4
|
+
/** Most claimed tasks this runner executes at once. Default 8. */
|
|
5
|
+
concurrency?: number;
|
|
4
6
|
/** How often the runner renews its owner lease and its running task's lease. */
|
|
5
7
|
heartbeatInterval?: DurationLike;
|
|
6
8
|
/** How long the owner lease and each task lease live without a heartbeat. */
|
|
@@ -18,16 +20,19 @@ export declare const IN_PROCESS_RUNNER_ROLES: {
|
|
|
18
20
|
};
|
|
19
21
|
export type InProcessRunnerRole = (typeof IN_PROCESS_RUNNER_ROLES)[keyof typeof IN_PROCESS_RUNNER_ROLES];
|
|
20
22
|
/**
|
|
21
|
-
* Executes runnable tasks inside this process,
|
|
23
|
+
* Executes runnable tasks inside this process, up to `concurrency` at a time, each until it
|
|
24
|
+
* stops (terminal, retry, waiting, or aborted).
|
|
22
25
|
* Only the process holding the singleton `HarnessOwner` lease drains; every other
|
|
23
26
|
* process stays on standby and takes over once that lease expires. On becoming owner,
|
|
24
27
|
* and on every heartbeat while owner, it recovers tasks whose lease expired.
|
|
25
28
|
*/
|
|
26
29
|
export declare class InProcessRunner implements HarnessRunner {
|
|
30
|
+
private readonly concurrency;
|
|
27
31
|
private context;
|
|
28
32
|
private heartbeatInFlight;
|
|
29
33
|
private heartbeatTimer;
|
|
30
34
|
private hasPendingWake;
|
|
35
|
+
private readonly inFlight;
|
|
31
36
|
private isHeartbeatStopped;
|
|
32
37
|
private isStopping;
|
|
33
38
|
private readonly lease;
|
|
@@ -41,15 +46,17 @@ export declare class InProcessRunner implements HarnessRunner {
|
|
|
41
46
|
/** Id written into every lease this runner holds. */
|
|
42
47
|
get ownerId(): string;
|
|
43
48
|
start(context: HarnessRunnerContext): Promise<void>;
|
|
44
|
-
/** Stop claiming new work, wait for
|
|
49
|
+
/** Stop claiming new work, wait for every task in flight, then release the owner lease. */
|
|
45
50
|
stop(): Promise<void>;
|
|
46
51
|
/** Skip the rest of the idle sleep, e.g. right after a task is created. */
|
|
47
52
|
wake(): void;
|
|
48
53
|
private drain;
|
|
49
54
|
/** Become owner when the lease is free or expired, then recover abandoned tasks. */
|
|
50
55
|
private tryTakeOwnership;
|
|
51
|
-
/**
|
|
52
|
-
private
|
|
56
|
+
/** Claim and start tasks until every slot is busy or nothing is runnable. */
|
|
57
|
+
private fillSlots;
|
|
58
|
+
/** Run one claimed task to a stop; its own task lease and heartbeat guard its commits. */
|
|
59
|
+
private runOne;
|
|
53
60
|
private scheduleHeartbeat;
|
|
54
61
|
/** Renew the owner lease and sweep for expired task leases; demote on a lost lease. */
|
|
55
62
|
private heartbeat;
|
|
@@ -13,16 +13,19 @@ exports.IN_PROCESS_RUNNER_ROLES = {
|
|
|
13
13
|
stopped: "stopped",
|
|
14
14
|
};
|
|
15
15
|
/**
|
|
16
|
-
* Executes runnable tasks inside this process,
|
|
16
|
+
* Executes runnable tasks inside this process, up to `concurrency` at a time, each until it
|
|
17
|
+
* stops (terminal, retry, waiting, or aborted).
|
|
17
18
|
* Only the process holding the singleton `HarnessOwner` lease drains; every other
|
|
18
19
|
* process stays on standby and takes over once that lease expires. On becoming owner,
|
|
19
20
|
* and on every heartbeat while owner, it recovers tasks whose lease expired.
|
|
20
21
|
*/
|
|
21
22
|
class InProcessRunner {
|
|
23
|
+
concurrency;
|
|
22
24
|
context;
|
|
23
25
|
heartbeatInFlight = Promise.resolve();
|
|
24
26
|
heartbeatTimer;
|
|
25
27
|
hasPendingWake = false;
|
|
28
|
+
inFlight = new Set();
|
|
26
29
|
isHeartbeatStopped = false;
|
|
27
30
|
isStopping = false;
|
|
28
31
|
lease;
|
|
@@ -39,6 +42,14 @@ class InProcessRunner {
|
|
|
39
42
|
kind: "configInvalid",
|
|
40
43
|
});
|
|
41
44
|
}
|
|
45
|
+
const concurrency = options.concurrency ?? 8;
|
|
46
|
+
if (!Number.isInteger(concurrency) || concurrency < 1) {
|
|
47
|
+
throw (0, errors_1.harnessError)({
|
|
48
|
+
detail: "InProcessRunner concurrency must be a positive integer",
|
|
49
|
+
kind: "configInvalid",
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
this.concurrency = concurrency;
|
|
42
53
|
this.lease = {
|
|
43
54
|
duration,
|
|
44
55
|
heartbeat,
|
|
@@ -65,14 +76,14 @@ class InProcessRunner {
|
|
|
65
76
|
this.loop = this.drain();
|
|
66
77
|
this.scheduleHeartbeat();
|
|
67
78
|
}
|
|
68
|
-
/** Stop claiming new work, wait for
|
|
79
|
+
/** Stop claiming new work, wait for every task in flight, then release the owner lease. */
|
|
69
80
|
async stop() {
|
|
70
81
|
if (this.loop === undefined) {
|
|
71
82
|
return;
|
|
72
83
|
}
|
|
73
84
|
this.isStopping = true;
|
|
74
85
|
this.wake();
|
|
75
|
-
// Keep renewing the owner lease until the
|
|
86
|
+
// Keep renewing the owner lease until the tasks in flight settle, so a standby does
|
|
76
87
|
// not take over while this process is still working.
|
|
77
88
|
await this.loop;
|
|
78
89
|
this.isHeartbeatStopped = true;
|
|
@@ -109,11 +120,13 @@ class InProcessRunner {
|
|
|
109
120
|
continue;
|
|
110
121
|
}
|
|
111
122
|
}
|
|
112
|
-
|
|
113
|
-
if (
|
|
123
|
+
await this.fillSlots(this.context);
|
|
124
|
+
if (!this.isStopping) {
|
|
125
|
+
// Woken early by new work or by a task that frees a slot.
|
|
114
126
|
await this.sleep(this.pollIntervalMs);
|
|
115
127
|
}
|
|
116
128
|
}
|
|
129
|
+
await Promise.allSettled([...this.inFlight]);
|
|
117
130
|
}
|
|
118
131
|
/** Become owner when the lease is free or expired, then recover abandoned tasks. */
|
|
119
132
|
async tryTakeOwnership(context) {
|
|
@@ -131,19 +144,37 @@ class InProcessRunner {
|
|
|
131
144
|
return this.currentRole === exports.IN_PROCESS_RUNNER_ROLES.owner;
|
|
132
145
|
}
|
|
133
146
|
}
|
|
134
|
-
/**
|
|
135
|
-
async
|
|
136
|
-
|
|
137
|
-
|
|
147
|
+
/** Claim and start tasks until every slot is busy or nothing is runnable. */
|
|
148
|
+
async fillSlots(context) {
|
|
149
|
+
while (this.inFlight.size < this.concurrency &&
|
|
150
|
+
!this.isStopping &&
|
|
151
|
+
this.currentRole === exports.IN_PROCESS_RUNNER_ROLES.owner) {
|
|
152
|
+
let task;
|
|
153
|
+
try {
|
|
154
|
+
task = await context.claimNext(this.lease);
|
|
155
|
+
}
|
|
156
|
+
catch (error) {
|
|
157
|
+
api_1.logger.error(`InProcessRunner iteration failed: ${(0, errors_1.errorMessage)(error)}`);
|
|
158
|
+
return;
|
|
159
|
+
}
|
|
138
160
|
if (!task) {
|
|
139
|
-
return
|
|
161
|
+
return;
|
|
140
162
|
}
|
|
163
|
+
const run = this.runOne(context, task);
|
|
164
|
+
this.inFlight.add(run);
|
|
165
|
+
void run.finally(() => {
|
|
166
|
+
this.inFlight.delete(run);
|
|
167
|
+
this.wake();
|
|
168
|
+
});
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
/** Run one claimed task to a stop; its own task lease and heartbeat guard its commits. */
|
|
172
|
+
async runOne(context, task) {
|
|
173
|
+
try {
|
|
141
174
|
await context.runTask(task, this.lease);
|
|
142
|
-
return false;
|
|
143
175
|
}
|
|
144
176
|
catch (error) {
|
|
145
|
-
api_1.logger.error(`InProcessRunner
|
|
146
|
-
return true;
|
|
177
|
+
api_1.logger.error(`InProcessRunner task ${task._id} failed to run: ${(0, errors_1.errorMessage)(error)}`);
|
|
147
178
|
}
|
|
148
179
|
}
|
|
149
180
|
scheduleHeartbeat() {
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { type JobsApp } from "@terreno/jobs";
|
|
2
|
+
import { type DurationLike } from "luxon";
|
|
3
|
+
import type { HarnessRunner, HarnessRunnerContext } from "../../types/harness";
|
|
4
|
+
/** Job that runs one phase of one harness task. */
|
|
5
|
+
export declare const HARNESS_PHASE_JOB_NAME = "terreno.harness.phase";
|
|
6
|
+
export interface JobsRunnerOptions {
|
|
7
|
+
/** How many runnable tasks one dispatch tick enqueues at most. */
|
|
8
|
+
dispatchBatchSize?: number;
|
|
9
|
+
/** How often a running phase renews its task lease, and how often expired leases are swept. */
|
|
10
|
+
heartbeatInterval?: DurationLike;
|
|
11
|
+
/** The registered `JobsApp`; the runner defines `terreno.harness.phase` on it. */
|
|
12
|
+
jobs: JobsApp;
|
|
13
|
+
/** How long a task lease lives without a heartbeat. */
|
|
14
|
+
leaseDuration?: DurationLike;
|
|
15
|
+
/** Runner instance id written into task leases. Defaults to `hostname:pid:uuid`. */
|
|
16
|
+
ownerId?: string;
|
|
17
|
+
/** How long the dispatcher sleeps between scans for runnable tasks. */
|
|
18
|
+
pollInterval?: DurationLike;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Executes harness phases as `@terreno/jobs` jobs so any number of instances share the
|
|
22
|
+
* work. Every instance runs a dispatcher that enqueues one `terreno.harness.phase` job per
|
|
23
|
+
* runnable task (deduplicated by idempotency key) and sweeps expired task leases. The job
|
|
24
|
+
* handler claims its task under a fenced lease, runs one phase while heartbeating, and
|
|
25
|
+
* hands a still-running task back as `pending` for the next job. The task lease, not the
|
|
26
|
+
* job lock, decides who may commit: a duplicate or late job finds the task claimed and
|
|
27
|
+
* does nothing, and a stale lease holder's commit is rejected.
|
|
28
|
+
*/
|
|
29
|
+
export declare class JobsRunner implements HarnessRunner {
|
|
30
|
+
private context;
|
|
31
|
+
private readonly dispatchBatchSize;
|
|
32
|
+
private hasPendingWake;
|
|
33
|
+
private readonly inFlight;
|
|
34
|
+
private isStopping;
|
|
35
|
+
private readonly lease;
|
|
36
|
+
private loop;
|
|
37
|
+
private nextSweepAt;
|
|
38
|
+
private readonly pollIntervalMs;
|
|
39
|
+
private wakeSleeper;
|
|
40
|
+
constructor(options: JobsRunnerOptions);
|
|
41
|
+
/** Id written into every task lease this runner holds. */
|
|
42
|
+
get ownerId(): string;
|
|
43
|
+
start(context: HarnessRunnerContext): Promise<void>;
|
|
44
|
+
/** Stop dispatching, then wait for every phase this instance is running. */
|
|
45
|
+
stop(): Promise<void>;
|
|
46
|
+
/** Dispatch now instead of after the rest of the idle sleep. */
|
|
47
|
+
wake(): void;
|
|
48
|
+
/** Job handler: claim the task, run one phase, and hand it back if it still runs. */
|
|
49
|
+
private runPhaseJob;
|
|
50
|
+
private claimAndRunPhase;
|
|
51
|
+
private dispatchLoop;
|
|
52
|
+
/** Recover expired leases once per heartbeat, then enqueue a job per runnable task. */
|
|
53
|
+
private tick;
|
|
54
|
+
/**
|
|
55
|
+
* Enqueue the job for this runnable visit. When the job with that key already ended
|
|
56
|
+
* without claiming the task (its handler kept failing, or it ran where the task was not
|
|
57
|
+
* runnable), follow or extend the chain `<key>:<endedJobId>` until a job is in flight, so
|
|
58
|
+
* the task is not stranded. A newly created job is always in flight, so this ends.
|
|
59
|
+
*/
|
|
60
|
+
private dispatch;
|
|
61
|
+
private sleep;
|
|
62
|
+
}
|
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.JobsRunner = exports.HARNESS_PHASE_JOB_NAME = void 0;
|
|
4
|
+
const node_crypto_1 = require("node:crypto");
|
|
5
|
+
const node_os_1 = require("node:os");
|
|
6
|
+
const api_1 = require("@terreno/api");
|
|
7
|
+
const jobs_1 = require("@terreno/jobs");
|
|
8
|
+
const luxon_1 = require("luxon");
|
|
9
|
+
const errors_1 = require("../errors");
|
|
10
|
+
/** Job that runs one phase of one harness task. */
|
|
11
|
+
exports.HARNESS_PHASE_JOB_NAME = "terreno.harness.phase";
|
|
12
|
+
/** Job statuses that still lead to a handler run; any other status will never claim. */
|
|
13
|
+
const IN_FLIGHT_JOB_STATUSES = new Set(["pending", "running", "scheduled"]);
|
|
14
|
+
const parsePayload = (payload) => {
|
|
15
|
+
const taskId = payload?.taskId;
|
|
16
|
+
if (typeof taskId !== "string" || !taskId) {
|
|
17
|
+
throw (0, errors_1.harnessError)({
|
|
18
|
+
detail: `${exports.HARNESS_PHASE_JOB_NAME} payload needs a taskId string`,
|
|
19
|
+
kind: "invalidRequest",
|
|
20
|
+
});
|
|
21
|
+
}
|
|
22
|
+
return { taskId };
|
|
23
|
+
};
|
|
24
|
+
/** `taskId:phase:attempt:claims` — one key per runnable visit of a phase. */
|
|
25
|
+
const phaseJobKey = (task) => `${task.taskId}:${task.phase}:${task.attempt}:${task.claims}`;
|
|
26
|
+
/**
|
|
27
|
+
* Executes harness phases as `@terreno/jobs` jobs so any number of instances share the
|
|
28
|
+
* work. Every instance runs a dispatcher that enqueues one `terreno.harness.phase` job per
|
|
29
|
+
* runnable task (deduplicated by idempotency key) and sweeps expired task leases. The job
|
|
30
|
+
* handler claims its task under a fenced lease, runs one phase while heartbeating, and
|
|
31
|
+
* hands a still-running task back as `pending` for the next job. The task lease, not the
|
|
32
|
+
* job lock, decides who may commit: a duplicate or late job finds the task claimed and
|
|
33
|
+
* does nothing, and a stale lease holder's commit is rejected.
|
|
34
|
+
*/
|
|
35
|
+
class JobsRunner {
|
|
36
|
+
context;
|
|
37
|
+
dispatchBatchSize;
|
|
38
|
+
hasPendingWake = false;
|
|
39
|
+
inFlight = new Set();
|
|
40
|
+
isStopping = false;
|
|
41
|
+
lease;
|
|
42
|
+
loop;
|
|
43
|
+
nextSweepAt = luxon_1.DateTime.fromMillis(0);
|
|
44
|
+
pollIntervalMs;
|
|
45
|
+
wakeSleeper;
|
|
46
|
+
constructor(options) {
|
|
47
|
+
const duration = luxon_1.Duration.fromDurationLike(options.leaseDuration ?? { seconds: 30 });
|
|
48
|
+
const heartbeat = luxon_1.Duration.fromDurationLike(options.heartbeatInterval ?? { seconds: 10 });
|
|
49
|
+
if (heartbeat.toMillis() <= 0 || heartbeat.toMillis() >= duration.toMillis()) {
|
|
50
|
+
throw (0, errors_1.harnessError)({
|
|
51
|
+
detail: "JobsRunner heartbeatInterval must be positive and shorter than leaseDuration",
|
|
52
|
+
kind: "configInvalid",
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
this.lease = {
|
|
56
|
+
duration,
|
|
57
|
+
heartbeat,
|
|
58
|
+
owner: options.ownerId ?? `${(0, node_os_1.hostname)()}:${process.pid}:${(0, node_crypto_1.randomUUID)()}`,
|
|
59
|
+
};
|
|
60
|
+
this.pollIntervalMs = luxon_1.Duration.fromDurationLike(options.pollInterval ?? { milliseconds: 500 }).toMillis();
|
|
61
|
+
const dispatchBatchSize = options.dispatchBatchSize ?? 100;
|
|
62
|
+
if (!Number.isInteger(dispatchBatchSize) || dispatchBatchSize < 1) {
|
|
63
|
+
throw (0, errors_1.harnessError)({
|
|
64
|
+
detail: "JobsRunner dispatchBatchSize must be a positive integer",
|
|
65
|
+
kind: "configInvalid",
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
this.dispatchBatchSize = dispatchBatchSize;
|
|
69
|
+
options.jobs.define(exports.HARNESS_PHASE_JOB_NAME, {
|
|
70
|
+
handler: (payload) => this.runPhaseJob(payload),
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
/** Id written into every task lease this runner holds. */
|
|
74
|
+
get ownerId() {
|
|
75
|
+
return this.lease.owner;
|
|
76
|
+
}
|
|
77
|
+
async start(context) {
|
|
78
|
+
if (this.loop !== undefined) {
|
|
79
|
+
throw (0, errors_1.harnessError)({ detail: "JobsRunner is already started", kind: "alreadyStarted" });
|
|
80
|
+
}
|
|
81
|
+
if (!(0, jobs_1.tryGetJobsService)()) {
|
|
82
|
+
throw (0, errors_1.harnessError)({
|
|
83
|
+
detail: "JobsRunner needs a registered JobsApp: register it and build the app before harness.start()",
|
|
84
|
+
kind: "configInvalid",
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
this.context = context;
|
|
88
|
+
this.isStopping = false;
|
|
89
|
+
this.nextSweepAt = luxon_1.DateTime.fromMillis(0);
|
|
90
|
+
this.loop = this.dispatchLoop();
|
|
91
|
+
}
|
|
92
|
+
/** Stop dispatching, then wait for every phase this instance is running. */
|
|
93
|
+
async stop() {
|
|
94
|
+
if (this.loop === undefined) {
|
|
95
|
+
return;
|
|
96
|
+
}
|
|
97
|
+
this.isStopping = true;
|
|
98
|
+
this.wake();
|
|
99
|
+
await this.loop;
|
|
100
|
+
await Promise.allSettled([...this.inFlight]);
|
|
101
|
+
this.loop = undefined;
|
|
102
|
+
this.context = undefined;
|
|
103
|
+
}
|
|
104
|
+
/** Dispatch now instead of after the rest of the idle sleep. */
|
|
105
|
+
wake() {
|
|
106
|
+
if (this.wakeSleeper) {
|
|
107
|
+
this.wakeSleeper();
|
|
108
|
+
return;
|
|
109
|
+
}
|
|
110
|
+
this.hasPendingWake = true;
|
|
111
|
+
}
|
|
112
|
+
/** Job handler: claim the task, run one phase, and hand it back if it still runs. */
|
|
113
|
+
async runPhaseJob(payload) {
|
|
114
|
+
const { taskId } = parsePayload(payload);
|
|
115
|
+
// Tracked from before the claim, so stop() also waits for a claim in flight.
|
|
116
|
+
const job = this.claimAndRunPhase(taskId);
|
|
117
|
+
this.inFlight.add(job);
|
|
118
|
+
try {
|
|
119
|
+
await job;
|
|
120
|
+
}
|
|
121
|
+
finally {
|
|
122
|
+
this.inFlight.delete(job);
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
async claimAndRunPhase(taskId) {
|
|
126
|
+
const context = this.context;
|
|
127
|
+
if (!context || this.isStopping) {
|
|
128
|
+
// Throwing makes the jobs worker retry later, on this instance or another one.
|
|
129
|
+
throw (0, errors_1.harnessError)({
|
|
130
|
+
detail: `JobsRunner is not running; task ${taskId} stays runnable`,
|
|
131
|
+
kind: "runnerStopped",
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
const task = await context.claimTask(taskId, this.lease);
|
|
135
|
+
if (!task) {
|
|
136
|
+
// Another job claimed it first, or it stopped being runnable since dispatch.
|
|
137
|
+
return;
|
|
138
|
+
}
|
|
139
|
+
await context.runTask(task, this.lease, { maxPhases: 1 });
|
|
140
|
+
// The next phase (or a retry that is already due) can be dispatched right away.
|
|
141
|
+
this.wake();
|
|
142
|
+
}
|
|
143
|
+
async dispatchLoop() {
|
|
144
|
+
while (!this.isStopping && this.context) {
|
|
145
|
+
await this.tick(this.context);
|
|
146
|
+
if (!this.isStopping) {
|
|
147
|
+
await this.sleep(this.pollIntervalMs);
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
/** Recover expired leases once per heartbeat, then enqueue a job per runnable task. */
|
|
152
|
+
async tick(context) {
|
|
153
|
+
try {
|
|
154
|
+
if (luxon_1.DateTime.now() >= this.nextSweepAt) {
|
|
155
|
+
this.nextSweepAt = luxon_1.DateTime.now().plus(this.lease.heartbeat);
|
|
156
|
+
await context.recoverExpired();
|
|
157
|
+
}
|
|
158
|
+
const runnable = await context.listRunnable(this.dispatchBatchSize);
|
|
159
|
+
for (const task of runnable) {
|
|
160
|
+
if (this.isStopping) {
|
|
161
|
+
return;
|
|
162
|
+
}
|
|
163
|
+
await this.dispatch(task);
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
catch (error) {
|
|
167
|
+
api_1.logger.error(`JobsRunner dispatch failed: ${(0, errors_1.errorMessage)(error)}`);
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
/**
|
|
171
|
+
* Enqueue the job for this runnable visit. When the job with that key already ended
|
|
172
|
+
* without claiming the task (its handler kept failing, or it ran where the task was not
|
|
173
|
+
* runnable), follow or extend the chain `<key>:<endedJobId>` until a job is in flight, so
|
|
174
|
+
* the task is not stranded. A newly created job is always in flight, so this ends.
|
|
175
|
+
*/
|
|
176
|
+
async dispatch(task) {
|
|
177
|
+
const jobs = (0, jobs_1.tryGetJobsService)();
|
|
178
|
+
if (!jobs) {
|
|
179
|
+
throw (0, errors_1.harnessError)({ detail: "JobsApp is no longer registered", kind: "configInvalid" });
|
|
180
|
+
}
|
|
181
|
+
let idempotencyKey = phaseJobKey(task);
|
|
182
|
+
for (;;) {
|
|
183
|
+
const job = await jobs.enqueue({
|
|
184
|
+
idempotencyKey,
|
|
185
|
+
name: exports.HARNESS_PHASE_JOB_NAME,
|
|
186
|
+
payload: { taskId: task.taskId },
|
|
187
|
+
});
|
|
188
|
+
if (IN_FLIGHT_JOB_STATUSES.has(job.status)) {
|
|
189
|
+
return;
|
|
190
|
+
}
|
|
191
|
+
idempotencyKey = `${phaseJobKey(task)}:${job._id}`;
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
sleep(ms) {
|
|
195
|
+
if (this.hasPendingWake) {
|
|
196
|
+
this.hasPendingWake = false;
|
|
197
|
+
return Promise.resolve();
|
|
198
|
+
}
|
|
199
|
+
return new Promise((resolve) => {
|
|
200
|
+
const timer = setTimeout(() => {
|
|
201
|
+
this.wakeSleeper = undefined;
|
|
202
|
+
resolve();
|
|
203
|
+
}, ms);
|
|
204
|
+
this.wakeSleeper = () => {
|
|
205
|
+
clearTimeout(timer);
|
|
206
|
+
this.wakeSleeper = undefined;
|
|
207
|
+
resolve();
|
|
208
|
+
};
|
|
209
|
+
});
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
exports.JobsRunner = JobsRunner;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { HarnessLeaseSettings, HarnessTaskDefinition, HarnessTaskDocument } from "../types/harness";
|
|
1
|
+
import type { HarnessLeaseSettings, HarnessRunnableTask, HarnessTaskDefinition, HarnessTaskDocument } from "../types/harness";
|
|
2
2
|
import { type HarnessModels } from "./commit";
|
|
3
3
|
import { type HarnessEngine } from "./ownership";
|
|
4
4
|
/**
|
|
@@ -10,6 +10,22 @@ export declare const claimNextTask: ({ definitions, lease, models, }: {
|
|
|
10
10
|
lease: HarnessLeaseSettings;
|
|
11
11
|
models: HarnessModels;
|
|
12
12
|
}) => Promise<HarnessTaskDocument | null>;
|
|
13
|
+
/**
|
|
14
|
+
* Claim one task by id under the same rules as `claimNextTask`. Null when the task is not
|
|
15
|
+
* runnable now: unknown, not due, already claimed by another runner, terminal, or aborting.
|
|
16
|
+
*/
|
|
17
|
+
export declare const claimTaskById: ({ definitions, lease, models, taskId, }: {
|
|
18
|
+
definitions: Map<string, HarnessTaskDefinition>;
|
|
19
|
+
lease: HarnessLeaseSettings;
|
|
20
|
+
models: HarnessModels;
|
|
21
|
+
taskId: string;
|
|
22
|
+
}) => Promise<HarnessTaskDocument | null>;
|
|
23
|
+
/** Oldest runnable, registered tasks first, at most `limit`, without claiming them. */
|
|
24
|
+
export declare const listRunnableTasks: ({ definitions, limit, models, }: {
|
|
25
|
+
definitions: Map<string, HarnessTaskDefinition>;
|
|
26
|
+
limit: number;
|
|
27
|
+
models: HarnessModels;
|
|
28
|
+
}) => Promise<HarnessRunnableTask[]>;
|
|
13
29
|
/**
|
|
14
30
|
* Find `running` tasks whose lease expired (their runner died or froze mid-phase) and
|
|
15
31
|
* resolve each by its current phase's `replay`: `safe` goes back to `pending` at the same
|
|
@@ -27,8 +43,10 @@ export declare const recoverExpiredTasks: (engine: HarnessEngine) => Promise<num
|
|
|
27
43
|
* was lost, the task is left at its last checkpoint and expired-lease recovery decides
|
|
28
44
|
* what happens next. A terminal task re-checks the task that owns it.
|
|
29
45
|
*/
|
|
30
|
-
export declare const runClaimedTask: ({ engine, lease, task, }: {
|
|
46
|
+
export declare const runClaimedTask: ({ engine, lease, maxPhases, task, }: {
|
|
31
47
|
engine: HarnessEngine;
|
|
32
48
|
lease: HarnessLeaseSettings;
|
|
49
|
+
/** Hand the task back as `pending` once this many phases committed and it still runs. */
|
|
50
|
+
maxPhases?: number;
|
|
33
51
|
task: HarnessTaskDocument;
|
|
34
52
|
}) => Promise<void>;
|