pi-spine 2.26.0 → 2.27.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/README.md +1 -1
- package/bin/spine-review-step.mjs +8 -1
- package/bin/spine-worker-runner.mjs +14 -1
- package/package.json +3 -3
- package/skills/spine-release-operator/SKILL.md +3 -0
- package/src/batch/batch-meta-reconstruct.mjs +3 -0
- package/src/batch/contract-exec.mjs +2 -2
- package/src/batch/contract-parse.mjs +2 -2
- package/src/batch/contract-prelanded.mjs +2 -2
- package/src/batch/diagnosis-handoff-packet.mjs +74 -0
- package/src/batch/diagnosis-pending-lane.mjs +34 -1
- package/src/batch/engine-lanes/quota-fallback-run.mjs +153 -0
- package/src/batch/engine-lanes/quota-fallback-state.mjs +202 -0
- package/src/batch/engine-lanes/review-code.mjs +1 -0
- package/src/batch/engine-lanes/review-final.mjs +83 -46
- package/src/batch/engine-lanes/review-plan.mjs +22 -2
- package/src/batch/engine-lanes/review-poll.mjs +47 -1
- package/src/batch/engine-lanes.mjs +6 -7
- package/src/batch/journal.mjs +15 -0
- package/src/batch/metrics.mjs +13 -1
- package/src/batch/provider-quota.mjs +220 -0
- package/src/batch/quota-fallback.mjs +319 -0
- package/src/batch/reconcile-diagnosis-context.mjs +22 -0
- package/src/batch/resume-multi-queue.mjs +25 -10
- package/src/batch/review-artifacts.mjs +93 -15
- package/src/batch/review-spawn-retry.mjs +106 -0
- package/src/batch/review-spawn.mjs +48 -2
- package/src/batch/review-step-run.mjs +96 -6
- package/src/batch/reviewer-output.mjs +162 -0
- package/src/batch/worker-host.mjs +49 -3
- package/src/config/cursor-rules/discover.mjs +2 -2
- package/src/config/cursor-rules/match-globs.mjs +6 -4
- package/src/config/env-overrides.mjs +41 -4
- package/src/config/settings-fields.mjs +6 -0
- package/src/config/spine-config-schema.mjs +24 -0
- package/src/doctor/quota-risk.mjs +45 -0
- package/src/planner/file-scope.mjs +6 -6
- package/src/tasks/packet/validate-contract.mjs +3 -3
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pure classifier for provider quota exhaustion and transient overload in
|
|
3
|
+
* worker output (SP-804, partial #329).
|
|
4
|
+
*
|
|
5
|
+
* The worker runner forwards pi's stderr/stdout on a non-zero exit
|
|
6
|
+
* (`bin/spine-worker-runner.mjs`), so provider API error payloads end up
|
|
7
|
+
* verbatim inside `workerResult.output`. This module recognizes the payload
|
|
8
|
+
* shapes seen in retained `task.failed` events — Z.ai usage-limit JSON
|
|
9
|
+
* (`{"code":"1308",...}`) and Kimi error envelopes
|
|
10
|
+
* (`{"error":{"type":...}}`) — and reports the shared quota pool the model
|
|
11
|
+
* belongs to. Matching depends only on the payload text, never on the model;
|
|
12
|
+
* the model is used solely to resolve the pool id via `resolvePoolId`, so a
|
|
13
|
+
* mislabelled model cannot fabricate or hide a quota signal.
|
|
14
|
+
*/
|
|
15
|
+
import { resolvePoolId } from "../metrics/quota-snapshot.mjs";
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* @typedef {"quota_exhausted"|"transient_overload"} ProviderQuotaKind
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* @typedef {object} ProviderQuotaError
|
|
23
|
+
* @property {ProviderQuotaKind} kind Why the output was classified.
|
|
24
|
+
* @property {string} poolId Shared quota pool the model belongs to (`resolvePoolId`).
|
|
25
|
+
* @property {number|null} httpStatus Three-digit HTTP status preceding the JSON payload, when present.
|
|
26
|
+
* @property {string|null} providerCode z.ai `code` or Kimi `error.type` of the matched rule, when matched.
|
|
27
|
+
* @property {string|null} resetAtRaw Raw text after "reset at" in the provider message (z.ai), when present.
|
|
28
|
+
* @property {null} resetAt Always null for now: the z.ai reset text carries no timezone (UTC+8 is inferred, not confirmed — #329).
|
|
29
|
+
* @property {string} message Provider message string, truncated to 300 characters.
|
|
30
|
+
*/
|
|
31
|
+
|
|
32
|
+
/** Provider messages can embed long URLs/pricing pitches; keep a bounded slice. */
|
|
33
|
+
const MAX_MESSAGE_LENGTH = 300;
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Matches a standalone three-digit HTTP status immediately followed —
|
|
37
|
+
* optionally via `:` and/or whitespace — by a JSON object, exactly as
|
|
38
|
+
* providers and pi print it, e.g. `429: {"code":"1308",...}` or
|
|
39
|
+
* `403 {"error":{...}}`. The `\b` anchors keep multi-digit numbers
|
|
40
|
+
* (timestamps, token counts) from matching.
|
|
41
|
+
*/
|
|
42
|
+
const STATUS_JSON_PATTERN = /\b(\d{3})\b\s*:?\s*\{/g;
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Truncates a provider message to {@link MAX_MESSAGE_LENGTH} characters.
|
|
46
|
+
*
|
|
47
|
+
* @param {string} message
|
|
48
|
+
* @returns {string}
|
|
49
|
+
*/
|
|
50
|
+
function truncateMessage(message) {
|
|
51
|
+
return message.length > MAX_MESSAGE_LENGTH ? message.slice(0, MAX_MESSAGE_LENGTH) : message;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Extracts the substring of a balanced JSON object starting at `startIndex`
|
|
56
|
+
* (which must point at `{`). Tracks string and escape state so braces inside
|
|
57
|
+
* message text cannot truncate the payload.
|
|
58
|
+
*
|
|
59
|
+
* @param {string} text
|
|
60
|
+
* @param {number} startIndex
|
|
61
|
+
* @returns {string|null} The object substring, or null when unbalanced.
|
|
62
|
+
*/
|
|
63
|
+
function extractBalancedObject(text, startIndex) {
|
|
64
|
+
let depth = 0;
|
|
65
|
+
let inString = false;
|
|
66
|
+
let escaped = false;
|
|
67
|
+
for (let i = startIndex; i < text.length; i++) {
|
|
68
|
+
const ch = text[i];
|
|
69
|
+
if (inString) {
|
|
70
|
+
if (escaped) escaped = false;
|
|
71
|
+
else if (ch === "\\") escaped = true;
|
|
72
|
+
else if (ch === '"') inString = false;
|
|
73
|
+
continue;
|
|
74
|
+
}
|
|
75
|
+
if (ch === '"') inString = true;
|
|
76
|
+
else if (ch === "{") depth++;
|
|
77
|
+
else if (ch === "}") {
|
|
78
|
+
depth--;
|
|
79
|
+
if (depth === 0) return text.slice(startIndex, i + 1);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
return null;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Collects every status-prefixed JSON payload in the output, in order of
|
|
87
|
+
* appearance. Fragments that do not parse as JSON objects are ignored — they
|
|
88
|
+
* are not provider payloads.
|
|
89
|
+
*
|
|
90
|
+
* @param {string} output
|
|
91
|
+
* @returns {{httpStatus: number, payload: Record<string, any>}[]}
|
|
92
|
+
*/
|
|
93
|
+
function collectStatusPayloads(output) {
|
|
94
|
+
const candidates = [];
|
|
95
|
+
STATUS_JSON_PATTERN.lastIndex = 0;
|
|
96
|
+
let match;
|
|
97
|
+
while ((match = STATUS_JSON_PATTERN.exec(output)) !== null) {
|
|
98
|
+
const objectStart = match.index + match[0].length - 1;
|
|
99
|
+
const raw = extractBalancedObject(output, objectStart);
|
|
100
|
+
if (raw === null) continue;
|
|
101
|
+
try {
|
|
102
|
+
const payload = JSON.parse(raw);
|
|
103
|
+
if (payload && typeof payload === "object" && !Array.isArray(payload)) {
|
|
104
|
+
candidates.push({ httpStatus: Number(match[1]), payload });
|
|
105
|
+
}
|
|
106
|
+
} catch {
|
|
107
|
+
// Malformed JSON is not a provider payload; keep scanning.
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
return candidates;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* Extracts the raw text following "reset at" in a z.ai usage-limit message.
|
|
115
|
+
* The timestamp carries no timezone, so it is kept verbatim; parsing it into
|
|
116
|
+
* a Date would require guessing UTC+8 (#329).
|
|
117
|
+
*
|
|
118
|
+
* @param {string} message
|
|
119
|
+
* @returns {string|null}
|
|
120
|
+
*/
|
|
121
|
+
function extractResetAtRaw(message) {
|
|
122
|
+
const match = message.match(/reset at\s+(.+)$/i);
|
|
123
|
+
if (!match) return null;
|
|
124
|
+
return match[1].trim().replace(/[.!]+$/, "");
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* Applies the classification rules to a single payload. The HTTP status is
|
|
129
|
+
* part of every rule so unrelated 4xx/5xx output never matches; a payload
|
|
130
|
+
* that matches no rule returns null rather than a best guess.
|
|
131
|
+
*
|
|
132
|
+
* Rules (#329):
|
|
133
|
+
* - z.ai 429, top-level `code` "1308" (5-hour window) or "1310"
|
|
134
|
+
* (weekly/monthly) → quota_exhausted.
|
|
135
|
+
* - Kimi 403, `error.type` "permission_error", message mentions
|
|
136
|
+
* "usage limit" (billing-cycle exhaustion) → quota_exhausted.
|
|
137
|
+
* - Kimi 429, `error.type` "rate_limit_error", message mentions
|
|
138
|
+
* "currently overloaded" → transient_overload.
|
|
139
|
+
*
|
|
140
|
+
* @param {number} httpStatus
|
|
141
|
+
* @param {Record<string, any>} payload
|
|
142
|
+
* @returns {{kind: ProviderQuotaKind, providerCode: string, resetAtRaw: string|null, message: string}|null}
|
|
143
|
+
*/
|
|
144
|
+
function classifyPayload(httpStatus, payload) {
|
|
145
|
+
// Z.ai usage limits: flat `{"code":"1308","message":"..."}` right after the status.
|
|
146
|
+
if (httpStatus === 429 && typeof payload.code === "string" && typeof payload.message === "string") {
|
|
147
|
+
if (payload.code !== "1308" && payload.code !== "1310") return null;
|
|
148
|
+
return {
|
|
149
|
+
kind: "quota_exhausted",
|
|
150
|
+
providerCode: payload.code,
|
|
151
|
+
resetAtRaw: extractResetAtRaw(payload.message),
|
|
152
|
+
message: truncateMessage(payload.message),
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
// Kimi: nested error envelope `{"error":{"type":...,"message":...}}`.
|
|
157
|
+
const error = payload.error && typeof payload.error === "object" ? payload.error : null;
|
|
158
|
+
const errorMessage = typeof error?.message === "string" ? error.message : null;
|
|
159
|
+
if (!error || errorMessage === null) return null;
|
|
160
|
+
|
|
161
|
+
if (
|
|
162
|
+
httpStatus === 403 &&
|
|
163
|
+
error.type === "permission_error" &&
|
|
164
|
+
errorMessage.toLowerCase().includes("usage limit")
|
|
165
|
+
) {
|
|
166
|
+
return {
|
|
167
|
+
kind: "quota_exhausted",
|
|
168
|
+
providerCode: "permission_error",
|
|
169
|
+
resetAtRaw: null,
|
|
170
|
+
message: truncateMessage(errorMessage),
|
|
171
|
+
};
|
|
172
|
+
}
|
|
173
|
+
if (
|
|
174
|
+
httpStatus === 429 &&
|
|
175
|
+
error.type === "rate_limit_error" &&
|
|
176
|
+
errorMessage.toLowerCase().includes("currently overloaded")
|
|
177
|
+
) {
|
|
178
|
+
return {
|
|
179
|
+
kind: "transient_overload",
|
|
180
|
+
providerCode: "rate_limit_error",
|
|
181
|
+
resetAtRaw: null,
|
|
182
|
+
message: truncateMessage(errorMessage),
|
|
183
|
+
};
|
|
184
|
+
}
|
|
185
|
+
return null;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* Classifies provider quota exhaustion / transient overload in raw worker
|
|
190
|
+
* output. Pure: no I/O, no clocks, no configuration reads. When several
|
|
191
|
+
* status-prefixed payloads appear, the last one is classified — it is the
|
|
192
|
+
* terminal error the worker actually died on — and if it matches no rule the
|
|
193
|
+
* result is null even when an earlier payload would have matched.
|
|
194
|
+
*
|
|
195
|
+
* @param {string|null|undefined} output Forwarded worker stderr/stdout.
|
|
196
|
+
* @param {string|null|undefined} [model] Model identifier used only for the pool id.
|
|
197
|
+
* @returns {ProviderQuotaError|null}
|
|
198
|
+
*/
|
|
199
|
+
export function classifyProviderQuotaError(output, model) {
|
|
200
|
+
if (typeof output !== "string" || !output) return null;
|
|
201
|
+
|
|
202
|
+
const candidates = collectStatusPayloads(output);
|
|
203
|
+
const last = candidates.length > 0 ? candidates[candidates.length - 1] : null;
|
|
204
|
+
if (!last) return null;
|
|
205
|
+
|
|
206
|
+
const classified = classifyPayload(last.httpStatus, last.payload);
|
|
207
|
+
if (!classified) return null;
|
|
208
|
+
|
|
209
|
+
return {
|
|
210
|
+
kind: classified.kind,
|
|
211
|
+
// Narrow null → undefined for resolvePoolId's optional string param; the
|
|
212
|
+
// JSDoc accepts null from callers, and both map to pool "unknown".
|
|
213
|
+
poolId: resolvePoolId(model ?? undefined),
|
|
214
|
+
httpStatus: last.httpStatus,
|
|
215
|
+
providerCode: classified.providerCode,
|
|
216
|
+
resetAtRaw: classified.resetAtRaw,
|
|
217
|
+
resetAt: null,
|
|
218
|
+
message: classified.message,
|
|
219
|
+
};
|
|
220
|
+
}
|
|
@@ -0,0 +1,319 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pure decision and state helpers for single-hop provider quota fallback
|
|
3
|
+
* (SP-807, partial #329).
|
|
4
|
+
*
|
|
5
|
+
* `decideQuotaFallback` encodes the #329 fallback rules as a truth table over
|
|
6
|
+
* the resolved config, the batch's `state.resilience.quotaFallback` state, the
|
|
7
|
+
* SP-804 classification, and the worker backend:
|
|
8
|
+
*
|
|
9
|
+
* - at most one hop per batch (sticky once applied — a second exhaustion can
|
|
10
|
+
* only re-route lanes still pinned to the old pool, never pick a new pool);
|
|
11
|
+
* - one auto-retry per task (`retriedTaskIds`), so no task ping-pongs;
|
|
12
|
+
* - transient overload, an unset fallback key, and the in-process
|
|
13
|
+
* `agentSession` backend never fall back;
|
|
14
|
+
* - same-pool and probe-reported-exhausted fallback targets are refused.
|
|
15
|
+
*
|
|
16
|
+
* Everything here is pure: no state reads/writes, no journal, no probes, no
|
|
17
|
+
* clocks (the caller passes `now` in). The engine wiring lands in SP-809.
|
|
18
|
+
* `agents.escalatePolicy` is deliberately not consulted (#329 alternatives:
|
|
19
|
+
* fallback is not escalation) and only a single fallback profile is supported.
|
|
20
|
+
*/
|
|
21
|
+
import { resolvePoolId } from "../metrics/quota-snapshot.mjs";
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* @typedef {import("./provider-quota.mjs").ProviderQuotaError} ProviderQuotaError
|
|
25
|
+
*/
|
|
26
|
+
|
|
27
|
+
/** @typedef {"apply"|"retry"|"stop"|"none"} QuotaFallbackAction */
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Persisted fallback hop for a batch, stored by the engine at
|
|
31
|
+
* `state.resilience.quotaFallback`. Its presence alone means the hop already
|
|
32
|
+
* happened — no second hop is ever decided.
|
|
33
|
+
*
|
|
34
|
+
* @typedef {object} QuotaFallbackState
|
|
35
|
+
* @property {string|null} fromProfile Profile active when the hop was applied.
|
|
36
|
+
* @property {string} toProfile Fallback profile the batch moved to.
|
|
37
|
+
* @property {string|null} fromModel Worker model before the hop.
|
|
38
|
+
* @property {string} toModel Worker model after the hop.
|
|
39
|
+
* @property {string} exhaustedPool Pool whose exhaustion triggered the hop.
|
|
40
|
+
* @property {string|null} resetAtRaw Raw provider reset text for that pool, when it had one.
|
|
41
|
+
* @property {string} triggerTaskId Task whose failure triggered the hop.
|
|
42
|
+
* @property {string} at ISO timestamp of the hop.
|
|
43
|
+
* @property {string[]} retriedTaskIds Tasks already auto-retried onto the fallback pool.
|
|
44
|
+
*/
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Early-out result: the batch must keep running as configured.
|
|
48
|
+
*
|
|
49
|
+
* @typedef {object} QuotaFallbackNoneResult
|
|
50
|
+
* @property {"none"} action
|
|
51
|
+
* @property {"disabled"|"not_quota"|"backend_unsupported"} reason
|
|
52
|
+
*/
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Terminal result: the fallback chain is exhausted (or misconfigured); no hop
|
|
56
|
+
* and no retry. Carries every pool exhausted so far so the caller can report
|
|
57
|
+
* both reset times (#329 wants the operator to see each window).
|
|
58
|
+
*
|
|
59
|
+
* @typedef {object} QuotaFallbackStopResult
|
|
60
|
+
* @property {"stop"} action
|
|
61
|
+
* @property {"profile_missing"|"task_retry_spent"|"fallback_pool_exhausted"|"fallback_model_unresolved"|"same_pool"|"probe_exhausted"} reason
|
|
62
|
+
* @property {string[]} exhaustedPools Pools exhausted so far — recorded hop pool first (when present), current classification last.
|
|
63
|
+
* @property {(string|null)[]} resetAtRaw Reset text per pool, index-aligned with `exhaustedPools`.
|
|
64
|
+
*/
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Re-route result: a lane still pinned to the old pool hit the same
|
|
68
|
+
* exhaustion; retry it onto the already-applied fallback (no new hop).
|
|
69
|
+
*
|
|
70
|
+
* @typedef {object} QuotaFallbackRetryResult
|
|
71
|
+
* @property {"retry"} action
|
|
72
|
+
* @property {string} toProfile
|
|
73
|
+
* @property {string} toModel
|
|
74
|
+
*/
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Apply result: move the batch to the fallback profile (the single hop).
|
|
78
|
+
*
|
|
79
|
+
* @typedef {object} QuotaFallbackApplyResult
|
|
80
|
+
* @property {"apply"} action
|
|
81
|
+
* @property {string|null} fromProfile
|
|
82
|
+
* @property {string} toProfile
|
|
83
|
+
* @property {string|null} fromModel
|
|
84
|
+
* @property {string} toModel
|
|
85
|
+
* @property {string} exhaustedPool
|
|
86
|
+
* @property {string} toPool
|
|
87
|
+
*/
|
|
88
|
+
|
|
89
|
+
/** @typedef {QuotaFallbackApplyResult|QuotaFallbackRetryResult|QuotaFallbackStopResult|QuotaFallbackNoneResult} QuotaFallbackDecision */
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Structural slice of the resolved spine config this module reads. The config
|
|
93
|
+
* arrives untyped from config loading; this keeps checkJs honest without
|
|
94
|
+
* pulling in the full config schema.
|
|
95
|
+
*
|
|
96
|
+
* @typedef {{ agents?: { activeProfile?: unknown, worker?: { model?: unknown }, profiles?: Record<string, any>, quotaFallbackProfile?: unknown } }} QuotaFallbackConfig
|
|
97
|
+
*/
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Reads `agents.quotaFallbackProfile` from a resolved config. An unset,
|
|
101
|
+
* non-string, or blank value disables fallback entirely (SP-805 lets `""`
|
|
102
|
+
* clear the key).
|
|
103
|
+
*
|
|
104
|
+
* @param {QuotaFallbackConfig|undefined} config
|
|
105
|
+
* @returns {string|null} Profile name, or null when fallback is disabled.
|
|
106
|
+
*/
|
|
107
|
+
function readFallbackProfileName(config) {
|
|
108
|
+
const raw = config?.agents?.quotaFallbackProfile;
|
|
109
|
+
if (typeof raw !== "string") return null;
|
|
110
|
+
const trimmed = raw.trim();
|
|
111
|
+
return trimmed === "" ? null : trimmed;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Looks up a profile by name using the same membership rule as the config
|
|
116
|
+
* schema (`Object.prototype.hasOwnProperty` on a plain object), so inherited
|
|
117
|
+
* or malformed entries cannot fabricate a fallback target.
|
|
118
|
+
*
|
|
119
|
+
* @param {QuotaFallbackConfig|undefined} config
|
|
120
|
+
* @param {string} name
|
|
121
|
+
* @returns {{ worker?: { model?: unknown } } | null}
|
|
122
|
+
*/
|
|
123
|
+
function lookupProfile(config, name) {
|
|
124
|
+
const profiles = config?.agents?.profiles;
|
|
125
|
+
if (!profiles || typeof profiles !== "object") return null;
|
|
126
|
+
if (!Object.prototype.hasOwnProperty.call(profiles, name)) return null;
|
|
127
|
+
const profile = profiles[name];
|
|
128
|
+
return profile && typeof profile === "object" ? /** @type {{ worker?: { model?: unknown } }} */ (profile) : null;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* Builds the parallel `exhaustedPools`/`resetAtRaw` report carried by every
|
|
133
|
+
* stop result: the pool/reset recorded in the fallback state (when a hop
|
|
134
|
+
* already happened), then the current classification's. Entries are appended
|
|
135
|
+
* verbatim — a same-pool repeat keeps both reset readings, the later one
|
|
136
|
+
* being the newer window — and stay index-aligned.
|
|
137
|
+
*
|
|
138
|
+
* @param {QuotaFallbackState|null} fallbackState
|
|
139
|
+
* @param {ProviderQuotaError} classification
|
|
140
|
+
* @returns {{exhaustedPools: string[], resetAtRaw: (string|null)[]}}
|
|
141
|
+
*/
|
|
142
|
+
function buildExhaustedReport(fallbackState, classification) {
|
|
143
|
+
const exhaustedPools = [];
|
|
144
|
+
const resetAtRaw = [];
|
|
145
|
+
if (fallbackState) {
|
|
146
|
+
exhaustedPools.push(fallbackState.exhaustedPool);
|
|
147
|
+
resetAtRaw.push(typeof fallbackState.resetAtRaw === "string" ? fallbackState.resetAtRaw : null);
|
|
148
|
+
}
|
|
149
|
+
exhaustedPools.push(classification.poolId);
|
|
150
|
+
resetAtRaw.push(typeof classification.resetAtRaw === "string" ? classification.resetAtRaw : null);
|
|
151
|
+
return { exhaustedPools, resetAtRaw };
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* Decides what the engine should do about a provider quota exhaustion, as a
|
|
156
|
+
* pure function of its arguments. Precedence (first match wins):
|
|
157
|
+
*
|
|
158
|
+
* 1. `none/disabled` — `agents.quotaFallbackProfile` unset or blank.
|
|
159
|
+
* 2. `none/not_quota` — no classification, or not `quota_exhausted`
|
|
160
|
+
* (transient overload never falls back, even mid-fallback).
|
|
161
|
+
* 3. `none/backend_unsupported` — `agentSession` workers run in-process and
|
|
162
|
+
* ignore child env pins, so fallback cannot reach them.
|
|
163
|
+
* 4. `stop/profile_missing` — fallback profile absent from `agents.profiles`
|
|
164
|
+
* (defensive: the schema normally rejects this; fail closed on drift).
|
|
165
|
+
* 5. Fallback already applied (sticky, one hop per batch):
|
|
166
|
+
* `stop/task_retry_spent` when the task already used its auto-retry;
|
|
167
|
+
* `retry` when the classification hits the original pool (a lane still
|
|
168
|
+
* pinned there) — re-route it, no new hop; otherwise
|
|
169
|
+
* `stop/fallback_pool_exhausted` (the fallback pool died too).
|
|
170
|
+
* 6. `stop/fallback_model_unresolved` — fallback profile has no usable
|
|
171
|
+
* worker model (`missing`/`inherit`).
|
|
172
|
+
* 7. `stop/same_pool` — fallback model shares the exhausted pool.
|
|
173
|
+
* 8. `stop/probe_exhausted` — a live probe already reported the fallback
|
|
174
|
+
* pool exhausted.
|
|
175
|
+
* 9. `apply` — perform the single hop.
|
|
176
|
+
*
|
|
177
|
+
* @param {object} [params]
|
|
178
|
+
* @param {QuotaFallbackConfig} [params.config] Resolved spine config.
|
|
179
|
+
* @param {QuotaFallbackState|null} [params.fallbackState] `state.resilience.quotaFallback ?? null`.
|
|
180
|
+
* @param {ProviderQuotaError|null} [params.classification] SP-804 result.
|
|
181
|
+
* @param {string} [params.taskId] Task the classification came from.
|
|
182
|
+
* @param {string} [params.workerBackend] Resolved worker backend.
|
|
183
|
+
* @param {string[]} [params.probeExhaustedPools] Pools a live probe reported exhausted.
|
|
184
|
+
* @returns {QuotaFallbackDecision}
|
|
185
|
+
*/
|
|
186
|
+
export function decideQuotaFallback({
|
|
187
|
+
config,
|
|
188
|
+
fallbackState = null,
|
|
189
|
+
classification = null,
|
|
190
|
+
taskId,
|
|
191
|
+
workerBackend,
|
|
192
|
+
probeExhaustedPools,
|
|
193
|
+
} = {}) {
|
|
194
|
+
// Row 1 — no fallback target configured.
|
|
195
|
+
const toProfileName = readFallbackProfileName(config);
|
|
196
|
+
if (toProfileName === null) {
|
|
197
|
+
return { action: "none", reason: "disabled" };
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
// Row 2 — transient overload and everything non-quota stays on the active profile.
|
|
201
|
+
if (!classification || classification.kind !== "quota_exhausted") {
|
|
202
|
+
return { action: "none", reason: "not_quota" };
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
// Row 3 — the in-process backend ignores child env, so a hop could not take effect.
|
|
206
|
+
if (workerBackend === "agentSession") {
|
|
207
|
+
return { action: "none", reason: "backend_unsupported" };
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/** Stop results report every pool exhausted so far so callers can show both reset times. */
|
|
211
|
+
/**
|
|
212
|
+
* @param {QuotaFallbackStopResult["reason"]} reason
|
|
213
|
+
* @returns {QuotaFallbackStopResult}
|
|
214
|
+
*/
|
|
215
|
+
const stop = (reason) => ({
|
|
216
|
+
action: "stop",
|
|
217
|
+
reason,
|
|
218
|
+
...buildExhaustedReport(fallbackState, classification),
|
|
219
|
+
});
|
|
220
|
+
|
|
221
|
+
// Row 4 — fail closed on config drift instead of guessing a target.
|
|
222
|
+
const targetProfile = lookupProfile(config, toProfileName);
|
|
223
|
+
if (targetProfile === null) {
|
|
224
|
+
return stop("profile_missing");
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
// Row 5 — sticky: once the hop happened, no second hop is ever decided.
|
|
228
|
+
if (fallbackState) {
|
|
229
|
+
const retriedTaskIds = Array.isArray(fallbackState.retriedTaskIds) ? fallbackState.retriedTaskIds : [];
|
|
230
|
+
if (taskId !== undefined && taskId !== null && retriedTaskIds.includes(taskId)) {
|
|
231
|
+
return stop("task_retry_spent");
|
|
232
|
+
}
|
|
233
|
+
if (classification.poolId === fallbackState.exhaustedPool) {
|
|
234
|
+
// A lane pinned to the old pool hit the same exhaustion: re-route it
|
|
235
|
+
// to the fallback that is already applied (recorded in the state, so
|
|
236
|
+
// later config edits cannot change the destination mid-batch).
|
|
237
|
+
return { action: "retry", toProfile: fallbackState.toProfile, toModel: fallbackState.toModel };
|
|
238
|
+
}
|
|
239
|
+
return stop("fallback_pool_exhausted");
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
// Row 6 — `inherit`/missing resolves to the "unknown" pool, which can never
|
|
243
|
+
// be a real destination, so it is refused before any pool comparison.
|
|
244
|
+
const toModel = typeof targetProfile.worker?.model === "string" ? targetProfile.worker.model : null;
|
|
245
|
+
if (toModel === null || toModel === "inherit") {
|
|
246
|
+
return stop("fallback_model_unresolved");
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
// Row 7 — a fallback inside the exhausted pool buys nothing.
|
|
250
|
+
const toPool = resolvePoolId(toModel);
|
|
251
|
+
if (toPool === classification.poolId) {
|
|
252
|
+
return stop("same_pool");
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
// Row 8 — trust the live probe over blind configuration.
|
|
256
|
+
const probes = Array.isArray(probeExhaustedPools) ? probeExhaustedPools : [];
|
|
257
|
+
if (probes.includes(toPool)) {
|
|
258
|
+
return stop("probe_exhausted");
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
// Row 9 — the single hop.
|
|
262
|
+
return {
|
|
263
|
+
action: "apply",
|
|
264
|
+
fromProfile: typeof config?.agents?.activeProfile === "string" ? config.agents.activeProfile : null,
|
|
265
|
+
toProfile: toProfileName,
|
|
266
|
+
fromModel: typeof config?.agents?.worker?.model === "string" ? config.agents.worker.model : null,
|
|
267
|
+
toModel,
|
|
268
|
+
exhaustedPool: classification.poolId,
|
|
269
|
+
toPool,
|
|
270
|
+
};
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/**
|
|
274
|
+
* Builds the persisted fallback state from an `apply` decision. Pure: the
|
|
275
|
+
* timestamp comes from the injected `now`, and the returned object shares no
|
|
276
|
+
* references with the decision or classification.
|
|
277
|
+
*
|
|
278
|
+
* @param {QuotaFallbackApplyResult} decision An `apply` result from {@link decideQuotaFallback}.
|
|
279
|
+
* @param {object} params
|
|
280
|
+
* @param {ProviderQuotaError} params.classification The classification that produced the decision.
|
|
281
|
+
* @param {string} params.taskId Task whose failure triggered the hop.
|
|
282
|
+
* @param {Date|number} params.now Injection point for the clock.
|
|
283
|
+
* @returns {QuotaFallbackState}
|
|
284
|
+
*/
|
|
285
|
+
export function buildQuotaFallbackState(decision, { classification, taskId, now }) {
|
|
286
|
+
return {
|
|
287
|
+
fromProfile: decision.fromProfile,
|
|
288
|
+
toProfile: decision.toProfile,
|
|
289
|
+
fromModel: decision.fromModel,
|
|
290
|
+
toModel: decision.toModel,
|
|
291
|
+
exhaustedPool: decision.exhaustedPool,
|
|
292
|
+
resetAtRaw: typeof classification.resetAtRaw === "string" ? classification.resetAtRaw : null,
|
|
293
|
+
triggerTaskId: taskId,
|
|
294
|
+
at: new Date(now).toISOString(),
|
|
295
|
+
retriedTaskIds: [],
|
|
296
|
+
};
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
/**
|
|
300
|
+
* Records that a task consumed its one auto-retry onto the fallback pool.
|
|
301
|
+
* Pure: returns a new state object and never mutates the input; appending an
|
|
302
|
+
* already-recorded task is a no-op duplicate-wise (idempotent).
|
|
303
|
+
*
|
|
304
|
+
* @param {QuotaFallbackState} fallbackState State to evolve (must be an object).
|
|
305
|
+
* @param {string} taskId Task that was retried.
|
|
306
|
+
* @returns {QuotaFallbackState}
|
|
307
|
+
* @throws {TypeError} When `fallbackState` is not an object, so a missing hop
|
|
308
|
+
* cannot silently produce an empty-looking state.
|
|
309
|
+
*/
|
|
310
|
+
export function markQuotaFallbackRetry(fallbackState, taskId) {
|
|
311
|
+
if (!fallbackState || typeof fallbackState !== "object") {
|
|
312
|
+
throw new TypeError("markQuotaFallbackRetry requires a QuotaFallbackState object");
|
|
313
|
+
}
|
|
314
|
+
const retriedTaskIds = Array.isArray(fallbackState.retriedTaskIds) ? fallbackState.retriedTaskIds : [];
|
|
315
|
+
if (retriedTaskIds.includes(taskId)) {
|
|
316
|
+
return { ...fallbackState, retriedTaskIds: [...retriedTaskIds] };
|
|
317
|
+
}
|
|
318
|
+
return { ...fallbackState, retriedTaskIds: [...retriedTaskIds, taskId] };
|
|
319
|
+
}
|
|
@@ -42,6 +42,26 @@ export function buildReconcileDiagnosisContext(params) {
|
|
|
42
42
|
|
|
43
43
|
const pendingLaneLandTasks = findPendingLaneLandTasks(classifiedTasks);
|
|
44
44
|
|
|
45
|
+
// SP-810 (partial #329): surface the persisted quota-fallback hop and the
|
|
46
|
+
// latest quota-exhaustion journal payload so SBAR Background/Assessment can
|
|
47
|
+
// tell operators the real quota situation. Journal events are reused from
|
|
48
|
+
// signals.journalEvents (reconcileBatch already read them) — never a second
|
|
49
|
+
// journal read here. Payloads follow the SP-808 shapes: worker.quota_exhausted
|
|
50
|
+
// carries a single poolId/resetAtRaw; batch.quota_fallback_exhausted carries
|
|
51
|
+
// parallel exhaustedPools[]/resetAtRaw[] arrays.
|
|
52
|
+
const quotaFallbackRaw = signals.raw?.resilience?.quotaFallback;
|
|
53
|
+
const quotaFallback = quotaFallbackRaw && typeof quotaFallbackRaw === "object" ? quotaFallbackRaw : null;
|
|
54
|
+
const journalEvents = Array.isArray(signals.journalEvents) ? signals.journalEvents : [];
|
|
55
|
+
let lastQuotaExhausted = null;
|
|
56
|
+
for (let index = journalEvents.length - 1; index >= 0; index -= 1) {
|
|
57
|
+
const event = journalEvents[index];
|
|
58
|
+
if (event?.type !== "worker.quota_exhausted" && event?.type !== "batch.quota_fallback_exhausted") {
|
|
59
|
+
continue;
|
|
60
|
+
}
|
|
61
|
+
lastQuotaExhausted = event.payload && typeof event.payload === "object" ? event.payload : {};
|
|
62
|
+
break;
|
|
63
|
+
}
|
|
64
|
+
|
|
45
65
|
return {
|
|
46
66
|
batchId: batch.batchId,
|
|
47
67
|
baseBranch: batch.baseBranch ?? git.baseBranch ?? "main",
|
|
@@ -49,6 +69,8 @@ export function buildReconcileDiagnosisContext(params) {
|
|
|
49
69
|
phase: batch.phase,
|
|
50
70
|
failedTasks: signals.failedTasks,
|
|
51
71
|
failedTaskId,
|
|
72
|
+
quotaFallback,
|
|
73
|
+
lastQuotaExhausted,
|
|
52
74
|
driftTaskStatus,
|
|
53
75
|
exitReason,
|
|
54
76
|
launchFailureKind: resolvedLaunchFailureKind,
|
|
@@ -17,6 +17,8 @@ import {
|
|
|
17
17
|
markTaskCompleteFromDisk,
|
|
18
18
|
runResumedTaskOnLane,
|
|
19
19
|
} from "./resume-multi-lanes.mjs";
|
|
20
|
+
import { runWithQuotaFallback } from "./engine-lanes/quota-fallback-run.mjs";
|
|
21
|
+
import { resolveWorkerBackend } from "../config/worker-backend.mjs";
|
|
20
22
|
|
|
21
23
|
/**
|
|
22
24
|
* Build lane queues and run all tasks in a resume wave.
|
|
@@ -113,17 +115,30 @@ export async function executeResumeWave({
|
|
|
113
115
|
|
|
114
116
|
laneQueue.runs.push({
|
|
115
117
|
taskId,
|
|
118
|
+
// SP-809 (#329): the resumed path gets the same single-hop quota
|
|
119
|
+
// fallback retry as the normal lane path.
|
|
116
120
|
run: () =>
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
121
|
+
runWithQuotaFallback(
|
|
122
|
+
() =>
|
|
123
|
+
runResumedTaskOnLane({
|
|
124
|
+
projectRoot,
|
|
125
|
+
state,
|
|
126
|
+
batchId,
|
|
127
|
+
config,
|
|
128
|
+
task,
|
|
129
|
+
lane,
|
|
130
|
+
taskFolderRel,
|
|
131
|
+
laneCorrelationId,
|
|
132
|
+
}),
|
|
133
|
+
{
|
|
134
|
+
projectRoot,
|
|
135
|
+
batchId,
|
|
136
|
+
state,
|
|
137
|
+
taskId,
|
|
138
|
+
config,
|
|
139
|
+
workerBackend: resolveWorkerBackend(config),
|
|
140
|
+
},
|
|
141
|
+
).then((result) => {
|
|
127
142
|
if (result.aborted) batchAborted = true;
|
|
128
143
|
return result;
|
|
129
144
|
}),
|