opencode-model-router 2.8.0 → 2.9.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/CHANGELOG.md +364 -0
- package/README.md +20 -0
- package/package.json +5 -1
- package/src/commands/output.ts +23 -1
- package/src/compat/background.ts +2439 -0
- package/src/compat/child-session.ts +6 -0
- package/src/compat/turn-state.ts +215 -0
- package/src/compat/v2-client.ts +136 -17
- package/src/compat/v2-hooks.ts +2656 -114
- package/src/compat/v2-observations.ts +328 -0
- package/src/executor/capacity.ts +362 -0
- package/src/executor/child-guards.ts +40 -0
- package/src/executor/command.ts +265 -0
- package/src/executor/compile/edges.ts +809 -0
- package/src/executor/compile/estimate.ts +158 -0
- package/src/executor/compile/footprint.ts +829 -0
- package/src/executor/compile/index.ts +1080 -0
- package/src/executor/compile/parse.ts +1492 -0
- package/src/executor/compile/residue.ts +706 -0
- package/src/executor/compile/validate.ts +280 -0
- package/src/executor/create.ts +672 -0
- package/src/executor/expand.ts +551 -0
- package/src/executor/git.ts +1214 -0
- package/src/executor/host-preamble.ts +17 -0
- package/src/executor/instructions.ts +35 -0
- package/src/executor/integrate/bisect.ts +73 -0
- package/src/executor/integrate/checks.ts +1086 -0
- package/src/executor/integrate/land.ts +177 -0
- package/src/executor/integrate/phase-suite.ts +407 -0
- package/src/executor/integrate/queue.ts +3083 -0
- package/src/executor/integrate/run-resolver.ts +19 -0
- package/src/executor/launch.ts +652 -0
- package/src/executor/ledger.ts +2208 -0
- package/src/executor/observations.ts +212 -0
- package/src/executor/paths.ts +159 -0
- package/src/executor/platform.ts +39 -0
- package/src/executor/process-identity.ts +19 -0
- package/src/executor/qa-loop.ts +470 -0
- package/src/executor/recovery.ts +403 -0
- package/src/executor/runtime.ts +6233 -0
- package/src/executor/schedule.ts +246 -0
- package/src/executor/slots/env.ts +145 -0
- package/src/executor/slots/pool.ts +1564 -0
- package/src/executor/slots/provision.ts +853 -0
- package/src/executor/tool.ts +534 -0
- package/src/executor/types.ts +2064 -0
- package/src/executor/unattended.ts +488 -0
- package/src/guard/store.ts +3 -1
- package/src/index.ts +1498 -288
- package/src/router/config.ts +776 -25
- package/src/router/git-tools.ts +106 -15
- package/src/router/leases.ts +1469 -0
- package/src/router/logger.ts +44 -32
- package/src/router/protocol.ts +40 -10
- package/src/router/role-agents.ts +224 -17
- package/src/router/roles-config.ts +10 -1
- package/src/router/roles.ts +1 -1
- package/src/router/run-tools.ts +56 -4
- package/src/router/tool-paths.ts +308 -0
- package/src/router/work-roots.ts +86 -0
- package/src/routing/advisor/findings.ts +25 -5
- package/src/routing/classify/index.ts +7 -1
- package/src/routing/classify/rules.ts +11 -0
- package/src/routing/commands/stats.ts +2 -2
- package/src/routing/outcomes/durations.ts +225 -0
- package/src/routing/outcomes/index.ts +59 -2
- package/src/routing/outcomes/persist.ts +409 -0
- package/src/routing/outcomes/stats.ts +170 -11
- package/src/routing/outcomes/timings.ts +836 -0
- package/src/routing/outcomes/types.ts +98 -0
- package/src/routing/roles/approvals.ts +86 -5
- package/src/routing/roles/binding.ts +99 -9
- package/src/routing/roles/orphans.ts +68 -0
- package/src/routing/roles/policy.ts +21 -3
- package/src/routing/roles/work-root.ts +3 -1
- package/src/routing/wire/dispatch.ts +86 -12
- package/src/routing/wire/hint.ts +56 -8
- package/src/v2.ts +94 -49
- package/src/verify/branch.ts +8 -2
- package/src/verify/canonical-path.ts +35 -0
- package/src/verify/deterministic.ts +38 -9
- package/src/verify/dispatch.ts +64 -28
- package/src/verify/exec.ts +52 -9
- package/src/verify/pending.ts +1691 -10
- package/src/verify/perimeter.ts +12 -6
- package/src/verify/plan-task.ts +729 -0
- package/src/verify/reference.ts +216 -3
- package/src/verify/tree.ts +30 -13
- package/src/verify/types.ts +9 -2
- package/src/verify/wiring.ts +290 -31
|
@@ -0,0 +1,836 @@
|
|
|
1
|
+
// ---------------------------------------------------------------------------
|
|
2
|
+
// Timing recorder (critical-path 1.1.2): dispatch durations and orchestrator turn counters.
|
|
3
|
+
//
|
|
4
|
+
// Writes `timings.jsonl` (one DispatchTimingRow per finished or abandoned child dispatch) and `turns.jsonl` (one
|
|
5
|
+
// OrchestratorTurnRow per turn of a root session) through the side logs of persist.ts. It is independent of
|
|
6
|
+
// `routing.engine`: it needs no store, no flusher and no decision log, so it works with `static`.
|
|
7
|
+
// Counters and labels only: no prompt, output or tool text ever reaches a row.
|
|
8
|
+
// Every entry point is idempotent and never throws into the caller; each row is appended (awaited) before the
|
|
9
|
+
// method's promise resolves — there is no coalescing flush. Runnable under Node type stripping (see types.ts).
|
|
10
|
+
//
|
|
11
|
+
// Keys: an open dispatch is keyed by its `callID` (known when the dispatch starts); the child session id is bound to it
|
|
12
|
+
// later (`bindChild`) and the host's end events find the dispatch through it (QA-1.1-1).
|
|
13
|
+
// One recorder per outcomes directory and process: `acquireTimingRecorder` (QA-1.1-3).
|
|
14
|
+
// ---------------------------------------------------------------------------
|
|
15
|
+
|
|
16
|
+
import { resolve } from "node:path";
|
|
17
|
+
import { createSideLogs, isSideLogLabel, nodePersistDeps } from "./persist";
|
|
18
|
+
import type {
|
|
19
|
+
Clock,
|
|
20
|
+
DispatchCapacity,
|
|
21
|
+
DispatchTimingOutcome,
|
|
22
|
+
DispatchTimingRow,
|
|
23
|
+
OrchestratorTurnRow,
|
|
24
|
+
OutcomeLogger,
|
|
25
|
+
SideLogs,
|
|
26
|
+
WriteResult,
|
|
27
|
+
} from "./types";
|
|
28
|
+
import { SIDE_ROW_VERSION, safeNow } from "./types";
|
|
29
|
+
|
|
30
|
+
/** Open dispatch starts kept; past this the least recently used one is evicted (no row). */
|
|
31
|
+
export const MAX_OPEN_STARTS = 1000;
|
|
32
|
+
/** A start still open after this long is closed as `unknown` by {@link TimingRecorder.sweep}. */
|
|
33
|
+
export const OPEN_START_TTL_MS = 6 * 60 * 60 * 1000;
|
|
34
|
+
/** Event ids remembered for dedupe (LRU). */
|
|
35
|
+
export const MAX_SEEN_EVENT_IDS = 5000;
|
|
36
|
+
/** Root sessions tracked for turn aggregation (LRU). */
|
|
37
|
+
export const MAX_ROOT_SESSIONS = 1000;
|
|
38
|
+
/** A turn with no step for this long is flushed by {@link TimingRecorder.sweep}; a turn still receiving steps is left open. */
|
|
39
|
+
export const DEFAULT_TURN_IDLE_MS = 30 * 60 * 1000;
|
|
40
|
+
/**
|
|
41
|
+
* A row whose `endedAt` is later than `now` by more than this is dropped (clock-jump guard, QA-1.1-21): the duration estimator
|
|
42
|
+
* and the stats table both drop it when they observe or load it, so it never sits in a window. One shared constant.
|
|
43
|
+
*/
|
|
44
|
+
export const MAX_FUTURE_SKEW_MS = 24 * 60 * 60 * 1000;
|
|
45
|
+
/** Outcomes of children without an open start kept for a later `bindChild` (QA-1.1-18); past this the oldest is forgotten. */
|
|
46
|
+
export const MAX_UNBOUND_OUTCOMES = 200;
|
|
47
|
+
/** An outcome of a child without an open start is forgotten after this long. */
|
|
48
|
+
export const UNBOUND_OUTCOME_TTL_MS = 10 * 60 * 1000;
|
|
49
|
+
|
|
50
|
+
/** Plugin logger subset; `debug` is optional (only the missing-start notice uses it). */
|
|
51
|
+
export interface TimingLogger extends OutcomeLogger {
|
|
52
|
+
debug?(message: string, extra?: Record<string, unknown>): void;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** What is known when a child dispatch starts. */
|
|
56
|
+
export interface DispatchStartInput {
|
|
57
|
+
/** Identifies the dispatch from the moment it starts (the host tool call). */
|
|
58
|
+
readonly callID: string;
|
|
59
|
+
/** The child session when already known, else `null` and {@link TimingRecorder.bindChild} supplies it later. */
|
|
60
|
+
readonly childSessionID: string | null;
|
|
61
|
+
readonly parentSessionID: string;
|
|
62
|
+
readonly role: string;
|
|
63
|
+
readonly class: string;
|
|
64
|
+
readonly scope: string;
|
|
65
|
+
readonly tier: string;
|
|
66
|
+
readonly model: string;
|
|
67
|
+
readonly background: boolean;
|
|
68
|
+
/** Epoch ms the dispatch started. */
|
|
69
|
+
readonly at: number;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Token counters of one root-session step. */
|
|
73
|
+
export interface RootStepTokens {
|
|
74
|
+
readonly input: number;
|
|
75
|
+
readonly cacheRead: number;
|
|
76
|
+
readonly cacheWrite: number;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** Detached identity of one attempted row write; no row reference or payload is exposed to the callback. */
|
|
80
|
+
export type TimingWriteObservation = Readonly<Pick<DispatchTimingRow, "parentSessionID" | "callID" | "childSessionID" | "outcome">>;
|
|
81
|
+
|
|
82
|
+
export interface TimingRecorderOptions {
|
|
83
|
+
/** Optional synchronous diagnostic callback, before the actual append (including failed writes). Never affects the append. */
|
|
84
|
+
readonly onTimingWrite?: (row: TimingWriteObservation) => void;
|
|
85
|
+
/** Outcomes directory; used to create the side logs when `sideLogs` is not given, and as the dedupe namespace. */
|
|
86
|
+
readonly dir: string;
|
|
87
|
+
readonly now: Clock;
|
|
88
|
+
readonly logger?: TimingLogger;
|
|
89
|
+
/** Injected side logs (tests, or a shared instance); otherwise created from `dir`. */
|
|
90
|
+
readonly sideLogs?: SideLogs;
|
|
91
|
+
/** A turn idle for at least this long is flushed by `sweep` (default {@link DEFAULT_TURN_IDLE_MS}). */
|
|
92
|
+
readonly turnIdleMs?: number;
|
|
93
|
+
/** Called after each row was appended (only when the side logs are created here). */
|
|
94
|
+
readonly onRow?: (row: DispatchTimingRow | OrchestratorTurnRow) => void;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export interface TimingRecorder {
|
|
98
|
+
/**
|
|
99
|
+
* Opens the timing of a dispatch, keyed by `callID`. Again for an open `callID`: no-op (refreshes its LRU position). A child
|
|
100
|
+
* may have several open calls (oldest first); a start naming a child that has an older open call does NOT close that call:
|
|
101
|
+
* it is closed as `unknown` only when the newer one is confirmed by {@link bindChild} (QA-1.1-18).
|
|
102
|
+
* Labels (role, class, scope, tier, model) that are not printable non-whitespace ASCII become `unknown`; ids stay strict.
|
|
103
|
+
*/
|
|
104
|
+
recordDispatchStart(input: DispatchStartInput): void;
|
|
105
|
+
/**
|
|
106
|
+
* Confirms which child session runs the open `callID` (the host's result named the child). Re-callable (the last child wins).
|
|
107
|
+
* Every OLDER open call of that child is closed as `unknown` at this call's start. An outcome that arrived for the child
|
|
108
|
+
* before it was bound (remembered, see {@link MAX_UNBOUND_OUTCOMES}) is applied when its time is not before the start.
|
|
109
|
+
* Unknown `callID`: ignored.
|
|
110
|
+
*/
|
|
111
|
+
bindChild(callID: string, childSessionID: string): void;
|
|
112
|
+
/** Drops the open timing of `callID` without a row: the call was rejected, no dispatch happened. Older calls of the child are untouched. */
|
|
113
|
+
cancelStart(callID: string): void;
|
|
114
|
+
/** Sets the background flag of an open `callID` (known only after the host acknowledged the call). */
|
|
115
|
+
setBackground(callID: string, background: boolean): void;
|
|
116
|
+
/**
|
|
117
|
+
* Closes the OLDEST open timing of `childSessionID` and appends its row (`durationMs = at − startedAt`; an end before the
|
|
118
|
+
* start is clamped to 0 and written as `unknown`). A child with no open timing: the outcome is remembered for a later
|
|
119
|
+
* {@link bindChild} (a resume bound after its end) and logged once at debug; an event id is consumed only when a timing
|
|
120
|
+
* was closed, and a seen id is ignored.
|
|
121
|
+
*/
|
|
122
|
+
onExecutionOutcome(childSessionID: string, eventId: string, outcome: DispatchTimingOutcome, at: number): Promise<void>;
|
|
123
|
+
/** Records the latest provider capacity class on the OPEN timing of `childSessionID`; the row carries it. Ignored once closed. A child with no open linked call: the latest signal is
|
|
124
|
+
* remembered (same bound and TTL as remembered outcomes) and applied by {@link bindChild} when its time is not before the start.
|
|
125
|
+
*/
|
|
126
|
+
onCapacitySignal(childSessionID: string, capacity: DispatchCapacity, at: number): void;
|
|
127
|
+
/** Declares `sessionID` a root (orchestrator) session: its steps are aggregated into turns. Idempotent; refreshes its recency. */
|
|
128
|
+
markRootSession(sessionID: string): void;
|
|
129
|
+
/** True when `sessionID` is a tracked root session. */
|
|
130
|
+
isRootSession(sessionID: string): boolean;
|
|
131
|
+
/**
|
|
132
|
+
* Turn boundary of a root session (a user prompt): appends the current turn's row if it has steps, then starts the next turn.
|
|
133
|
+
* `turn` counts per process (a restart numbers from 1 again). A seen `eventId` is ignored. The end of a root run closes a turn
|
|
134
|
+
* too ({@link onRootExecutionEnd}), so a turn is one orchestrator run, closed by whichever boundary comes first.
|
|
135
|
+
*/
|
|
136
|
+
onRootPrompt(sessionID: string, at: number, eventId?: string): Promise<void>;
|
|
137
|
+
/**
|
|
138
|
+
* End of a root session's run (`session.execution.*`, DF-1-5): appends the current turn's row if it has steps, then starts the
|
|
139
|
+
* next turn, as {@link onRootPrompt} does. Under background-first dispatch the orchestrator's kickoff and each synthetic
|
|
140
|
+
* wake-up are runs without a `prompt` hook, so each run closes its own turn here (an open dispatch start does not keep it
|
|
141
|
+
* open). Any other session, or a turn with no step, is ignored. A seen `eventId` is ignored.
|
|
142
|
+
*/
|
|
143
|
+
onRootExecutionEnd(sessionID: string, eventId?: string): Promise<void>;
|
|
144
|
+
/**
|
|
145
|
+
* Adds one step to the current turn of a root session; any other session is ignored. A seen `eventId` is ignored.
|
|
146
|
+
* Returns whether the step was counted.
|
|
147
|
+
*/
|
|
148
|
+
onRootStep(sessionID: string, tokens: RootStepTokens, eventId?: string): boolean;
|
|
149
|
+
/**
|
|
150
|
+
* Housekeeping: closes open starts older than {@link OPEN_START_TTL_MS} as `unknown` and appends the turns idle for at least
|
|
151
|
+
* `turnIdleMs` (a turn still receiving steps stays open, and so does the turn of a root that still has an open dispatch
|
|
152
|
+
* start: it waits for its children; the start TTL bounds that). `at` defaults to now. A forward clock jump of more than 6 hours
|
|
153
|
+
* (a suspended machine) therefore closes every running dispatch as `unknown`, which no estimate uses.
|
|
154
|
+
*/
|
|
155
|
+
sweep(at?: number): Promise<void>;
|
|
156
|
+
/** Shutdown: appends every open turn whatever its idle time and waits for pending writes. Open starts get no row. */
|
|
157
|
+
flush(): Promise<void>;
|
|
158
|
+
/** Same as {@link flush}. */
|
|
159
|
+
dispose(): Promise<void>;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
interface OpenStart {
|
|
163
|
+
readonly input: DispatchStartInput;
|
|
164
|
+
child: string | null;
|
|
165
|
+
background: boolean;
|
|
166
|
+
readonly startedAt: number;
|
|
167
|
+
capacity: DispatchCapacity | null;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** An outcome delivered for a child that had no open start yet. */
|
|
171
|
+
interface UnboundOutcome {
|
|
172
|
+
readonly child: string;
|
|
173
|
+
readonly eventId: string;
|
|
174
|
+
readonly outcome: DispatchTimingOutcome;
|
|
175
|
+
/** The outcome's own time (epoch ms). */
|
|
176
|
+
readonly at: number;
|
|
177
|
+
/** When it was remembered (epoch ms of the recorder's clock), for the TTL. */
|
|
178
|
+
readonly storedAt: number;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/** A capacity signal delivered for a child that had no open linked call. */
|
|
182
|
+
interface UnboundCapacity {
|
|
183
|
+
readonly child: string;
|
|
184
|
+
readonly capacity: DispatchCapacity;
|
|
185
|
+
/** The signal's own time (epoch ms). */
|
|
186
|
+
readonly at: number;
|
|
187
|
+
/** When it was remembered (epoch ms of the recorder's clock), for the TTL. */
|
|
188
|
+
readonly storedAt: number;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
interface RootTurn {
|
|
192
|
+
/** Index the next appended row carries (1-based). */
|
|
193
|
+
turn: number;
|
|
194
|
+
steps: number;
|
|
195
|
+
input: number;
|
|
196
|
+
cacheRead: number;
|
|
197
|
+
cacheWrite: number;
|
|
198
|
+
/** Epoch ms of the latest step (or of the turn's creation); `sweep` flushes the turn once it is old enough. */
|
|
199
|
+
lastStepAt: number;
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
const NOOP_LOGGER: TimingLogger = { warn: () => undefined };
|
|
203
|
+
|
|
204
|
+
function counter(value: number): number {
|
|
205
|
+
return Number.isFinite(value) && value > 0 ? value : 0;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/** Remembers `key` (most recent last); true when it was not remembered yet. Past `cap` the oldest is forgotten. */
|
|
209
|
+
function rememberOnce(seen: Set<string>, key: string, cap: number): boolean {
|
|
210
|
+
if (seen.has(key)) {
|
|
211
|
+
seen.delete(key);
|
|
212
|
+
seen.add(key);
|
|
213
|
+
return false;
|
|
214
|
+
}
|
|
215
|
+
seen.add(key);
|
|
216
|
+
if (seen.size > cap) {
|
|
217
|
+
const oldest = seen.values().next();
|
|
218
|
+
if (oldest.done !== true) seen.delete(oldest.value);
|
|
219
|
+
}
|
|
220
|
+
return true;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/** A label as written to the side log: itself when valid, else `unknown` (a refused label would drop the whole row). */
|
|
224
|
+
function safeLabel(value: string): string {
|
|
225
|
+
return typeof value === "string" && isSideLogLabel(value) ? value : "unknown";
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/** True for a non-empty event id (an absent or empty id cannot be deduplicated). */
|
|
229
|
+
function hasId(id: string | undefined): id is string {
|
|
230
|
+
return typeof id === "string" && id !== "";
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/**
|
|
234
|
+
* Capacity class of a provider error (ADR 0007 D6/D13). `type` decides, the body never does:
|
|
235
|
+
* `provider.rate-limit` → rate-limit; `provider.internal` with status 529 → overload; `provider.quota` → usage-limit;
|
|
236
|
+
* any other type is classified by status: 429 → rate-limit, 529 → overload; anything else → `null`.
|
|
237
|
+
*/
|
|
238
|
+
export function classifyCapacity(error: { readonly type?: string | null; readonly status?: number | null }): DispatchCapacity | null {
|
|
239
|
+
const { type, status } = error;
|
|
240
|
+
if (type === "provider.rate-limit") return "rate-limit";
|
|
241
|
+
if (type === "provider.quota") return "usage-limit";
|
|
242
|
+
if (type === "provider.internal" && status === 529) return "overload";
|
|
243
|
+
if (status === 429) return "rate-limit";
|
|
244
|
+
if (status === 529) return "overload";
|
|
245
|
+
return null;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/**
|
|
249
|
+
* Timing recorder over the side logs. Independent of `routing.engine`. Entry points are idempotent and never throw; a write
|
|
250
|
+
* failure is logged once per kind (`timings`, `turns`, `internal`) and the row is dropped, never retried.
|
|
251
|
+
*/
|
|
252
|
+
export function createTimingRecorder(options: TimingRecorderOptions): TimingRecorder {
|
|
253
|
+
const logger = options.logger ?? NOOP_LOGGER;
|
|
254
|
+
const sideLogs =
|
|
255
|
+
options.sideLogs ?? createSideLogs(options.dir, nodePersistDeps(logger), options.onRow === undefined ? {} : { onRow: options.onRow });
|
|
256
|
+
const clock = (): number => safeNow(options.now);
|
|
257
|
+
const stamp = (at: number): number => (Number.isFinite(at) && at >= 0 ? at : clock());
|
|
258
|
+
const turnIdleMs = options.turnIdleMs !== undefined && Number.isFinite(options.turnIdleMs) && options.turnIdleMs >= 0 ? options.turnIdleMs : DEFAULT_TURN_IDLE_MS;
|
|
259
|
+
const namespace = options.dir;
|
|
260
|
+
|
|
261
|
+
/** Insertion order = recency: the first key is the least recently used. Keyed by callID. */
|
|
262
|
+
const open = new Map<string, OpenStart>();
|
|
263
|
+
/** child session → callIDs of its open timings, oldest first (every listed callID is in `open`). */
|
|
264
|
+
const childCalls = new Map<string, string[]>();
|
|
265
|
+
/** Outcomes of children that had no open start (insertion order = age), kept for a later `bindChild`. */
|
|
266
|
+
const unbound: UnboundOutcome[] = [];
|
|
267
|
+
/** Latest capacity signal per child that had no open linked call (insertion order = age), kept for a later `bindChild`. */
|
|
268
|
+
const unboundCapacity: UnboundCapacity[] = [];
|
|
269
|
+
const seenEvents = new Set<string>();
|
|
270
|
+
const roots = new Map<string, RootTurn>();
|
|
271
|
+
const warned = new Set<string>();
|
|
272
|
+
const pending = new Set<Promise<void>>();
|
|
273
|
+
let noticedMissingStart = false;
|
|
274
|
+
|
|
275
|
+
function warnOnce(kind: string, message: string, error?: unknown): void {
|
|
276
|
+
if (warned.has(kind)) return;
|
|
277
|
+
warned.add(kind);
|
|
278
|
+
try {
|
|
279
|
+
logger.warn(message, { kind, ...(error === undefined ? {} : { error: error instanceof Error ? error.message : String(error) }) });
|
|
280
|
+
} catch {
|
|
281
|
+
warned.add(`${kind}:logger`); // a failing logger must not reach the caller; nothing else to do
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
function checkWrite(kind: "timings" | "turns", result: WriteResult): void {
|
|
286
|
+
if (!result.ok) warnOnce(kind, `[router] ${kind} side log write failed; the rows were dropped`, result.error);
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
/** Runs a write that nobody awaits; `flush` waits for it. */
|
|
290
|
+
function track(work: Promise<void>): void {
|
|
291
|
+
const done: Promise<void> = work.then(
|
|
292
|
+
() => undefined,
|
|
293
|
+
(error: unknown) => warnOnce("internal", "[router] timing recorder background write failed", error),
|
|
294
|
+
);
|
|
295
|
+
pending.add(done);
|
|
296
|
+
void done.then(() => {
|
|
297
|
+
pending.delete(done);
|
|
298
|
+
});
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
function unlinkChild(callID: string, child: string): void {
|
|
302
|
+
const calls = childCalls.get(child);
|
|
303
|
+
if (calls === undefined) return;
|
|
304
|
+
const index = calls.indexOf(callID);
|
|
305
|
+
if (index >= 0) calls.splice(index, 1);
|
|
306
|
+
if (calls.length === 0) childCalls.delete(child);
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
function linkChild(callID: string, child: string): void {
|
|
310
|
+
const calls = childCalls.get(child);
|
|
311
|
+
if (calls === undefined) childCalls.set(child, [callID]);
|
|
312
|
+
else if (!calls.includes(callID)) calls.push(callID);
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
function removeOpen(callID: string, entry: OpenStart): void {
|
|
316
|
+
open.delete(callID);
|
|
317
|
+
if (entry.child !== null) unlinkChild(callID, entry.child);
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
/** The oldest open call of `child`, if any. */
|
|
321
|
+
function oldestOpen(child: string): { readonly callID: string; readonly entry: OpenStart } | undefined {
|
|
322
|
+
for (const callID of childCalls.get(child) ?? []) {
|
|
323
|
+
const entry = open.get(callID);
|
|
324
|
+
if (entry !== undefined) return { callID, entry };
|
|
325
|
+
}
|
|
326
|
+
return undefined;
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
function pruneUnbound(t: number): void {
|
|
330
|
+
for (;;) {
|
|
331
|
+
const oldest = unbound[0];
|
|
332
|
+
if (oldest === undefined) return;
|
|
333
|
+
if (unbound.length <= MAX_UNBOUND_OUTCOMES && t - oldest.storedAt <= UNBOUND_OUTCOME_TTL_MS) return;
|
|
334
|
+
unbound.shift();
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
function pruneUnboundCapacity(t: number): void {
|
|
339
|
+
for (;;) {
|
|
340
|
+
const oldest = unboundCapacity[0];
|
|
341
|
+
if (oldest === undefined) return;
|
|
342
|
+
if (unboundCapacity.length <= MAX_UNBOUND_OUTCOMES && t - oldest.storedAt <= UNBOUND_OUTCOME_TTL_MS) return;
|
|
343
|
+
unboundCapacity.shift();
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
/** Counts per parent session the open starts (the idle sweep leaves a root with a running dispatch alone, QA-1.1-20). */
|
|
348
|
+
function parentsWithOpenStarts(): Set<string> {
|
|
349
|
+
const parents = new Set<string>();
|
|
350
|
+
for (const entry of open.values()) parents.add(entry.input.parentSessionID);
|
|
351
|
+
return parents;
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
/** The row of a closed timing; null when the dispatch never got a child session (nothing to attribute the row to). */
|
|
355
|
+
function timingRow(entry: OpenStart, outcome: DispatchTimingOutcome, at: number): DispatchTimingRow | null {
|
|
356
|
+
if (entry.child === null) return null;
|
|
357
|
+
const { input } = entry;
|
|
358
|
+
// QA-1.1-9: an end before the start means the clock moved; the duration is clamped and the row is `unknown` (no estimate uses it).
|
|
359
|
+
const clamped = at < entry.startedAt;
|
|
360
|
+
const endedAt = Math.max(at, entry.startedAt);
|
|
361
|
+
return {
|
|
362
|
+
kind: "dispatch-timing",
|
|
363
|
+
v: SIDE_ROW_VERSION,
|
|
364
|
+
ts: new Date(clock()).toISOString(),
|
|
365
|
+
parentSessionID: input.parentSessionID,
|
|
366
|
+
childSessionID: entry.child,
|
|
367
|
+
callID: input.callID,
|
|
368
|
+
role: input.role,
|
|
369
|
+
class: input.class,
|
|
370
|
+
scope: input.scope,
|
|
371
|
+
tier: input.tier,
|
|
372
|
+
model: input.model,
|
|
373
|
+
background: entry.background,
|
|
374
|
+
startedAt: entry.startedAt,
|
|
375
|
+
endedAt,
|
|
376
|
+
durationMs: endedAt - entry.startedAt,
|
|
377
|
+
outcome: clamped ? "unknown" : outcome,
|
|
378
|
+
capacity: entry.capacity,
|
|
379
|
+
};
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
function turnRow(sessionID: string, state: RootTurn): OrchestratorTurnRow {
|
|
383
|
+
return {
|
|
384
|
+
kind: "orchestrator-turn",
|
|
385
|
+
v: SIDE_ROW_VERSION,
|
|
386
|
+
ts: new Date(clock()).toISOString(),
|
|
387
|
+
sessionID,
|
|
388
|
+
turn: state.turn,
|
|
389
|
+
steps: state.steps,
|
|
390
|
+
input: state.input,
|
|
391
|
+
cacheRead: state.cacheRead,
|
|
392
|
+
cacheWrite: state.cacheWrite,
|
|
393
|
+
};
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
/** Takes the finished turn out of `state` (so a step arriving during the append counts for the next one); null without steps. */
|
|
397
|
+
function takeTurn(sessionID: string, state: RootTurn): OrchestratorTurnRow | null {
|
|
398
|
+
if (state.steps === 0) return null;
|
|
399
|
+
const row = turnRow(sessionID, state);
|
|
400
|
+
state.turn += 1;
|
|
401
|
+
state.steps = 0;
|
|
402
|
+
state.input = 0;
|
|
403
|
+
state.cacheRead = 0;
|
|
404
|
+
state.cacheWrite = 0;
|
|
405
|
+
return row;
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
/** Every append goes through `track`, so `flush` waits for it whoever awaits it (QA-1.1-25). */
|
|
409
|
+
function appendTimingRows(rows: readonly DispatchTimingRow[]): Promise<void> {
|
|
410
|
+
const work = (async (): Promise<void> => {
|
|
411
|
+
if (options.onTimingWrite !== undefined) for (const row of rows) {
|
|
412
|
+
try {
|
|
413
|
+
options.onTimingWrite(Object.freeze({ parentSessionID: row.parentSessionID, callID: row.callID,
|
|
414
|
+
childSessionID: row.childSessionID, outcome: row.outcome }));
|
|
415
|
+
} catch { /* Diagnostic callbacks never lose or change a timing row. */ }
|
|
416
|
+
}
|
|
417
|
+
if (rows.length > 0) checkWrite("timings", await sideLogs.appendTimings(rows));
|
|
418
|
+
})();
|
|
419
|
+
track(work);
|
|
420
|
+
return work;
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
function appendTurnRows(rows: readonly OrchestratorTurnRow[]): Promise<void> {
|
|
424
|
+
const work = (async (): Promise<void> => {
|
|
425
|
+
if (rows.length > 0) checkWrite("turns", await sideLogs.appendTurns(rows));
|
|
426
|
+
})();
|
|
427
|
+
track(work);
|
|
428
|
+
return work;
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
function touchRoot(sessionID: string, state: RootTurn): void {
|
|
432
|
+
roots.delete(sessionID);
|
|
433
|
+
roots.set(sessionID, state);
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
async function flushTurns(idleOnly: boolean, t: number): Promise<void> {
|
|
437
|
+
const turns: OrchestratorTurnRow[] = [];
|
|
438
|
+
// The idle sweep leaves a root with an open dispatch start alone (it is waiting for its children); the start TTL bounds that.
|
|
439
|
+
const busy = idleOnly ? parentsWithOpenStarts() : new Set<string>();
|
|
440
|
+
for (const [sessionID, state] of roots) {
|
|
441
|
+
if (idleOnly && (busy.has(sessionID) || t - state.lastStepAt < turnIdleMs)) continue;
|
|
442
|
+
const row = takeTurn(sessionID, state);
|
|
443
|
+
if (row !== null) turns.push(row);
|
|
444
|
+
}
|
|
445
|
+
await appendTurnRows(turns);
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
async function waitPending(): Promise<void> {
|
|
449
|
+
while (pending.size > 0) await Promise.all([...pending]);
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
async function flush(): Promise<void> {
|
|
453
|
+
try {
|
|
454
|
+
await waitPending();
|
|
455
|
+
await flushTurns(false, clock());
|
|
456
|
+
await waitPending();
|
|
457
|
+
} catch (error) {
|
|
458
|
+
warnOnce("internal", "[router] timing recorder flush failed", error);
|
|
459
|
+
}
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
return {
|
|
463
|
+
recordDispatchStart(input: DispatchStartInput): void {
|
|
464
|
+
try {
|
|
465
|
+
const existing = open.get(input.callID);
|
|
466
|
+
if (existing !== undefined) {
|
|
467
|
+
open.delete(input.callID); // idempotent: the first start stays, only the recency moves
|
|
468
|
+
open.set(input.callID, existing);
|
|
469
|
+
return;
|
|
470
|
+
}
|
|
471
|
+
const startedAt = stamp(input.at);
|
|
472
|
+
// QA-1.1-19: a label the side log would refuse (the whole row would be lost) is written as `unknown`; ids stay strict.
|
|
473
|
+
const clean: DispatchStartInput = {
|
|
474
|
+
...input,
|
|
475
|
+
role: safeLabel(input.role),
|
|
476
|
+
class: safeLabel(input.class),
|
|
477
|
+
scope: safeLabel(input.scope),
|
|
478
|
+
tier: safeLabel(input.tier),
|
|
479
|
+
model: safeLabel(input.model),
|
|
480
|
+
};
|
|
481
|
+
// QA-1.1-18: an older open call of the same child stays open until this one is confirmed by `bindChild`.
|
|
482
|
+
open.set(input.callID, { input: clean, child: input.childSessionID, background: input.background, startedAt, capacity: null });
|
|
483
|
+
if (input.childSessionID !== null) linkChild(input.callID, input.childSessionID);
|
|
484
|
+
while (open.size > MAX_OPEN_STARTS) {
|
|
485
|
+
const oldest = open.entries().next();
|
|
486
|
+
if (oldest.done === true) break;
|
|
487
|
+
removeOpen(oldest.value[0], oldest.value[1]); // evicted: no row
|
|
488
|
+
}
|
|
489
|
+
} catch (error) {
|
|
490
|
+
warnOnce("internal", "[router] timing recorder failed to record a dispatch start", error);
|
|
491
|
+
}
|
|
492
|
+
},
|
|
493
|
+
|
|
494
|
+
bindChild(callID: string, childSessionID: string): void {
|
|
495
|
+
try {
|
|
496
|
+
const entry = open.get(callID);
|
|
497
|
+
if (entry === undefined || typeof childSessionID !== "string" || childSessionID === "") return;
|
|
498
|
+
if (entry.child !== null && entry.child !== childSessionID) unlinkChild(callID, entry.child); // the last child wins
|
|
499
|
+
entry.child = childSessionID;
|
|
500
|
+
linkChild(callID, childSessionID);
|
|
501
|
+
const t = clock();
|
|
502
|
+
// Confirmed: every older open call of this child ended without an outcome event of its own (QA-1.1-2, QA-1.1-18).
|
|
503
|
+
const olderRows: DispatchTimingRow[] = [];
|
|
504
|
+
for (const otherID of [...(childCalls.get(childSessionID) ?? [])]) {
|
|
505
|
+
const other = open.get(otherID);
|
|
506
|
+
if (otherID === callID || other === undefined || other.startedAt > entry.startedAt) continue;
|
|
507
|
+
removeOpen(otherID, other);
|
|
508
|
+
const row = timingRow(other, "unknown", entry.startedAt);
|
|
509
|
+
if (row !== null) olderRows.push(row);
|
|
510
|
+
}
|
|
511
|
+
if (olderRows.length > 0) void appendTimingRows(olderRows);
|
|
512
|
+
// A capacity signal that arrived before the bind (a fresh foreground dispatch) belongs to this call, if not older than it.
|
|
513
|
+
pruneUnboundCapacity(t);
|
|
514
|
+
const capIndex = unboundCapacity.findIndex((item) => item.child === childSessionID && item.at >= entry.startedAt);
|
|
515
|
+
if (capIndex >= 0) {
|
|
516
|
+
const [signal] = unboundCapacity.splice(capIndex, 1);
|
|
517
|
+
if (signal !== undefined) entry.capacity = signal.capacity;
|
|
518
|
+
}
|
|
519
|
+
// An outcome that arrived before the bind (a foreground resume ending before its result) closes this call now.
|
|
520
|
+
pruneUnbound(t);
|
|
521
|
+
const index = unbound.findIndex((item) => item.child === childSessionID && item.at >= entry.startedAt);
|
|
522
|
+
if (index >= 0) {
|
|
523
|
+
const [item] = unbound.splice(index, 1);
|
|
524
|
+
if (item !== undefined && (!hasId(item.eventId) || rememberOnce(seenEvents, `${namespace}|end|${item.eventId}`, MAX_SEEN_EVENT_IDS))) {
|
|
525
|
+
removeOpen(callID, entry);
|
|
526
|
+
const row = timingRow(entry, item.outcome, item.at);
|
|
527
|
+
if (row !== null) void appendTimingRows([row]);
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
} catch (error) {
|
|
531
|
+
warnOnce("internal", "[router] timing recorder failed to bind a child session", error);
|
|
532
|
+
}
|
|
533
|
+
},
|
|
534
|
+
|
|
535
|
+
cancelStart(callID: string): void {
|
|
536
|
+
try {
|
|
537
|
+
const entry = open.get(callID);
|
|
538
|
+
if (entry !== undefined) removeOpen(callID, entry);
|
|
539
|
+
} catch (error) {
|
|
540
|
+
warnOnce("internal", "[router] timing recorder failed to cancel a dispatch start", error);
|
|
541
|
+
}
|
|
542
|
+
},
|
|
543
|
+
|
|
544
|
+
setBackground(callID: string, background: boolean): void {
|
|
545
|
+
try {
|
|
546
|
+
const entry = open.get(callID);
|
|
547
|
+
if (entry !== undefined) entry.background = background === true;
|
|
548
|
+
} catch (error) {
|
|
549
|
+
warnOnce("internal", "[router] timing recorder failed to set the background flag", error);
|
|
550
|
+
}
|
|
551
|
+
},
|
|
552
|
+
|
|
553
|
+
async onExecutionOutcome(childSessionID: string, eventId: string, outcome: DispatchTimingOutcome, at: number): Promise<void> {
|
|
554
|
+
try {
|
|
555
|
+
const found = oldestOpen(childSessionID);
|
|
556
|
+
if (found === undefined) {
|
|
557
|
+
// QA-1.1-3: an end id is consumed only by a delivery that found a start, so it cannot be spent on an unknown child.
|
|
558
|
+
if (!noticedMissingStart) {
|
|
559
|
+
noticedMissingStart = true;
|
|
560
|
+
logger.debug?.("[router] execution outcome without an open dispatch start; no timing row", { childSessionID });
|
|
561
|
+
}
|
|
562
|
+
// QA-1.1-18: remember it; a resume bound to this child right after (`bindChild`) takes it.
|
|
563
|
+
const t = clock();
|
|
564
|
+
const seen = hasId(eventId) && seenEvents.has(`${namespace}|end|${eventId}`);
|
|
565
|
+
const duplicate = hasId(eventId) && unbound.some((item) => item.eventId === eventId && item.child === childSessionID);
|
|
566
|
+
if (!seen && !duplicate && typeof childSessionID === "string" && childSessionID !== "") {
|
|
567
|
+
unbound.push({ child: childSessionID, eventId: hasId(eventId) ? eventId : "", outcome, at: stamp(at), storedAt: t });
|
|
568
|
+
}
|
|
569
|
+
pruneUnbound(t);
|
|
570
|
+
return;
|
|
571
|
+
}
|
|
572
|
+
const { callID, entry } = found;
|
|
573
|
+
// Same dedupe style as Ingest.onExecutionEnded: an event id is consumed by its first delivery.
|
|
574
|
+
if (hasId(eventId) && !rememberOnce(seenEvents, `${namespace}|end|${eventId}`, MAX_SEEN_EVENT_IDS)) return;
|
|
575
|
+
removeOpen(callID, entry); // closed before the append, so a concurrent outcome finds nothing
|
|
576
|
+
const row = timingRow(entry, outcome, stamp(at));
|
|
577
|
+
if (row !== null) await appendTimingRows([row]);
|
|
578
|
+
} catch (error) {
|
|
579
|
+
warnOnce("internal", "[router] timing recorder failed to record an execution outcome", error);
|
|
580
|
+
}
|
|
581
|
+
},
|
|
582
|
+
|
|
583
|
+
onCapacitySignal(childSessionID: string, capacity: DispatchCapacity, at: number): void {
|
|
584
|
+
try {
|
|
585
|
+
const found = oldestOpen(childSessionID);
|
|
586
|
+
if (found !== undefined) {
|
|
587
|
+
found.entry.capacity = capacity;
|
|
588
|
+
return;
|
|
589
|
+
}
|
|
590
|
+
// QA-1.1-27: a child without an open linked call (a fresh foreground dispatch, bound only at its result) is remembered.
|
|
591
|
+
if (typeof childSessionID !== "string" || childSessionID === "") return;
|
|
592
|
+
const t = clock();
|
|
593
|
+
const previous = unboundCapacity.findIndex((item) => item.child === childSessionID);
|
|
594
|
+
if (previous >= 0) unboundCapacity.splice(previous, 1); // the latest signal per child wins
|
|
595
|
+
unboundCapacity.push({ child: childSessionID, capacity, at: stamp(at), storedAt: t });
|
|
596
|
+
pruneUnboundCapacity(t);
|
|
597
|
+
} catch (error) {
|
|
598
|
+
warnOnce("internal", "[router] timing recorder failed to record a capacity signal", error);
|
|
599
|
+
}
|
|
600
|
+
},
|
|
601
|
+
|
|
602
|
+
markRootSession(sessionID: string): void {
|
|
603
|
+
try {
|
|
604
|
+
const existing = roots.get(sessionID);
|
|
605
|
+
if (existing !== undefined) {
|
|
606
|
+
touchRoot(sessionID, existing);
|
|
607
|
+
return;
|
|
608
|
+
}
|
|
609
|
+
roots.set(sessionID, { turn: 1, steps: 0, input: 0, cacheRead: 0, cacheWrite: 0, lastStepAt: clock() });
|
|
610
|
+
while (roots.size > MAX_ROOT_SESSIONS) {
|
|
611
|
+
const oldest = roots.entries().next();
|
|
612
|
+
if (oldest.done === true) break;
|
|
613
|
+
const [evictedID, evicted] = oldest.value;
|
|
614
|
+
roots.delete(evictedID);
|
|
615
|
+
const row = takeTurn(evictedID, evicted); // a turn in progress is not lost with its session
|
|
616
|
+
if (row !== null) void appendTurnRows([row]);
|
|
617
|
+
}
|
|
618
|
+
} catch (error) {
|
|
619
|
+
warnOnce("internal", "[router] timing recorder failed to mark a root session", error);
|
|
620
|
+
}
|
|
621
|
+
},
|
|
622
|
+
|
|
623
|
+
isRootSession(sessionID: string): boolean {
|
|
624
|
+
return roots.has(sessionID);
|
|
625
|
+
},
|
|
626
|
+
|
|
627
|
+
async onRootPrompt(sessionID: string, _at: number, eventId?: string): Promise<void> {
|
|
628
|
+
try {
|
|
629
|
+
const state = roots.get(sessionID);
|
|
630
|
+
if (state === undefined) return;
|
|
631
|
+
if (hasId(eventId) && !rememberOnce(seenEvents, `${namespace}|prompt|${eventId}`, MAX_SEEN_EVENT_IDS)) return;
|
|
632
|
+
touchRoot(sessionID, state);
|
|
633
|
+
state.lastStepAt = clock();
|
|
634
|
+
const row = takeTurn(sessionID, state);
|
|
635
|
+
if (row !== null) await appendTurnRows([row]);
|
|
636
|
+
} catch (error) {
|
|
637
|
+
warnOnce("internal", "[router] timing recorder failed to close an orchestrator turn", error);
|
|
638
|
+
}
|
|
639
|
+
},
|
|
640
|
+
|
|
641
|
+
async onRootExecutionEnd(sessionID: string, eventId?: string): Promise<void> {
|
|
642
|
+
try {
|
|
643
|
+
const state = roots.get(sessionID);
|
|
644
|
+
if (state === undefined) return;
|
|
645
|
+
if (hasId(eventId) && !rememberOnce(seenEvents, `${namespace}|run-end|${eventId}`, MAX_SEEN_EVENT_IDS)) return;
|
|
646
|
+
if (state.steps === 0) return; // a run that counted no step (its steps preceded `markRootSession`): nothing to close
|
|
647
|
+
touchRoot(sessionID, state);
|
|
648
|
+
state.lastStepAt = clock();
|
|
649
|
+
const row = takeTurn(sessionID, state);
|
|
650
|
+
if (row !== null) await appendTurnRows([row]);
|
|
651
|
+
} catch (error) {
|
|
652
|
+
warnOnce("internal", "[router] timing recorder failed to close an orchestrator turn", error);
|
|
653
|
+
}
|
|
654
|
+
},
|
|
655
|
+
|
|
656
|
+
onRootStep(sessionID: string, tokens: RootStepTokens, eventId?: string): boolean {
|
|
657
|
+
try {
|
|
658
|
+
const state = roots.get(sessionID);
|
|
659
|
+
if (state === undefined) return false;
|
|
660
|
+
if (hasId(eventId) && !rememberOnce(seenEvents, `${namespace}|step|${eventId}`, MAX_SEEN_EVENT_IDS)) return false;
|
|
661
|
+
touchRoot(sessionID, state);
|
|
662
|
+
state.lastStepAt = clock();
|
|
663
|
+
state.steps += 1;
|
|
664
|
+
state.input += counter(tokens.input);
|
|
665
|
+
state.cacheRead += counter(tokens.cacheRead);
|
|
666
|
+
state.cacheWrite += counter(tokens.cacheWrite);
|
|
667
|
+
return true;
|
|
668
|
+
} catch (error) {
|
|
669
|
+
warnOnce("internal", "[router] timing recorder failed to add a root step", error);
|
|
670
|
+
return false;
|
|
671
|
+
}
|
|
672
|
+
},
|
|
673
|
+
|
|
674
|
+
async sweep(at?: number): Promise<void> {
|
|
675
|
+
try {
|
|
676
|
+
const t = at === undefined ? clock() : stamp(at);
|
|
677
|
+
const stale: DispatchTimingRow[] = [];
|
|
678
|
+
for (const [callID, entry] of [...open]) {
|
|
679
|
+
if (t - entry.startedAt <= OPEN_START_TTL_MS) continue;
|
|
680
|
+
removeOpen(callID, entry);
|
|
681
|
+
const row = timingRow(entry, "unknown", t);
|
|
682
|
+
if (row !== null) stale.push(row);
|
|
683
|
+
}
|
|
684
|
+
await appendTimingRows(stale);
|
|
685
|
+
await flushTurns(true, t);
|
|
686
|
+
} catch (error) {
|
|
687
|
+
warnOnce("internal", "[router] timing recorder sweep failed", error);
|
|
688
|
+
}
|
|
689
|
+
},
|
|
690
|
+
|
|
691
|
+
flush,
|
|
692
|
+
dispose: flush,
|
|
693
|
+
};
|
|
694
|
+
}
|
|
695
|
+
|
|
696
|
+
// ---------------------------------------------------------------------------
|
|
697
|
+
// Process-wide registry (QA-1.1-3): one recorder per outcomes directory
|
|
698
|
+
// ---------------------------------------------------------------------------
|
|
699
|
+
|
|
700
|
+
export interface AcquireTimingRecorderOptions {
|
|
701
|
+
/** One actual write is reported to the first live holder with a callback, not once per holder. */
|
|
702
|
+
readonly onTimingWrite?: (row: TimingWriteObservation) => void;
|
|
703
|
+
readonly dir: string;
|
|
704
|
+
readonly now: Clock;
|
|
705
|
+
readonly logger?: TimingLogger;
|
|
706
|
+
/** Injected side logs (tests); applies to the first acquirer of the directory only. */
|
|
707
|
+
readonly sideLogs?: SideLogs;
|
|
708
|
+
readonly turnIdleMs?: number;
|
|
709
|
+
/** Observer of this holder: called after each row of the shared recorder was appended, until {@link TimingRecorderHolder.release}. */
|
|
710
|
+
readonly onRow?: (row: DispatchTimingRow | OrchestratorTurnRow) => void;
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
/** A holder of the shared recorder of a directory; `release()` once. */
|
|
714
|
+
export interface TimingRecorderHolder extends TimingRecorder {
|
|
715
|
+
/** Gives up this holder; the last release of the directory flushes the recorder and removes it from the registry. */
|
|
716
|
+
release(): Promise<void>;
|
|
717
|
+
}
|
|
718
|
+
|
|
719
|
+
/**
|
|
720
|
+
* Layout/behaviour version of a registry entry; bump it whenever `RegistryEntry` or the recorder it holds changes shape.
|
|
721
|
+
* An entry of another version in the process-wide map is foreign: it is neither reused nor touched (QA-PDF12-4).
|
|
722
|
+
*/
|
|
723
|
+
export const TIMING_REGISTRY_VERSION = 3;
|
|
724
|
+
|
|
725
|
+
interface RegistryEntry {
|
|
726
|
+
readonly version: number;
|
|
727
|
+
readonly recorder: TimingRecorder;
|
|
728
|
+
readonly observers: Set<(row: DispatchTimingRow | OrchestratorTurnRow) => void>;
|
|
729
|
+
readonly writeObservers: Map<symbol, (row: TimingWriteObservation) => void>;
|
|
730
|
+
refs: number;
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
/**
|
|
734
|
+
* DF-1.1-2: the host boots the plugin once per location, i.e. several copies of this module in one process; a module-level
|
|
735
|
+
* map would give every copy its own recorder (duplicate turn rows, restarting turn numbers). The registry therefore lives on
|
|
736
|
+
* `globalThis` under a registered symbol, as in `verify/pending.ts`; a value that is not a map is replaced. A recorder made by
|
|
737
|
+
* one copy is used by another: all copies are the same build, so the recorder's shape is identical.
|
|
738
|
+
*/
|
|
739
|
+
const PROCESS_REGISTRY_KEY = Symbol.for(`opencode-model-router.timings.registry.v${TIMING_REGISTRY_VERSION}`);
|
|
740
|
+
|
|
741
|
+
function processRegistry(): Map<string, RegistryEntry> {
|
|
742
|
+
const holder = globalThis as unknown as Record<symbol, unknown>;
|
|
743
|
+
let all = holder[PROCESS_REGISTRY_KEY];
|
|
744
|
+
if (!(all instanceof Map)) {
|
|
745
|
+
all = new Map<string, RegistryEntry>();
|
|
746
|
+
holder[PROCESS_REGISTRY_KEY] = all;
|
|
747
|
+
}
|
|
748
|
+
return all as Map<string, RegistryEntry>;
|
|
749
|
+
}
|
|
750
|
+
|
|
751
|
+
/** The entry of `id` in `registry` when it is of this build's version; a foreign entry (another layout) is not used (QA-PDF12-11). */
|
|
752
|
+
function currentEntry(registry: Map<string, RegistryEntry>, id: string): RegistryEntry | undefined {
|
|
753
|
+
const existing: unknown = registry.get(id);
|
|
754
|
+
if (typeof existing !== "object" || existing === null) return undefined;
|
|
755
|
+
return (existing as Partial<RegistryEntry>).version === TIMING_REGISTRY_VERSION ? (existing as RegistryEntry) : undefined;
|
|
756
|
+
}
|
|
757
|
+
|
|
758
|
+
/** The directory's key in the shared map: versioned too, so an entry another layout left at the bare path is never seen. */
|
|
759
|
+
function registryId(dir: string): string {
|
|
760
|
+
const abs = resolve(dir);
|
|
761
|
+
return `${process.platform === "win32" ? abs.toLowerCase() : abs}\u0000v${TIMING_REGISTRY_VERSION}`;
|
|
762
|
+
}
|
|
763
|
+
|
|
764
|
+
/**
|
|
765
|
+
* The process-wide recorder for `options.dir` (case-insensitive on win32): two plugin instances of one host process share
|
|
766
|
+
* its open starts, root turns and event-id dedupe, so an event delivered to both is counted once. The first acquirer
|
|
767
|
+
* creates it (its `now`, `logger`, `sideLogs` and `turnIdleMs` apply); each holder `release()`s once.
|
|
768
|
+
*/
|
|
769
|
+
export function acquireTimingRecorder(options: AcquireTimingRecorderOptions): TimingRecorderHolder {
|
|
770
|
+
const id = registryId(options.dir);
|
|
771
|
+
// The version is in the slot's key and in each entry's key, so every copy of this version shares one map and one entry per
|
|
772
|
+
// directory; a foreign entry is ignored (never reused, never touched), without a private fallback map (QA-PDF12-11).
|
|
773
|
+
const registry = processRegistry();
|
|
774
|
+
let entry = currentEntry(registry, id);
|
|
775
|
+
if (entry === undefined) {
|
|
776
|
+
const observers = new Set<(row: DispatchTimingRow | OrchestratorTurnRow) => void>();
|
|
777
|
+
const writeObservers = new Map<symbol, (row: TimingWriteObservation) => void>();
|
|
778
|
+
const logger = options.logger ?? NOOP_LOGGER;
|
|
779
|
+
const recorder = createTimingRecorder({
|
|
780
|
+
dir: options.dir,
|
|
781
|
+
now: options.now,
|
|
782
|
+
logger,
|
|
783
|
+
// One actual invocation => ONE stream, even with several plugin copies sharing this recorder.
|
|
784
|
+
onTimingWrite: (row) => { writeObservers.values().next().value?.(row); },
|
|
785
|
+
...(options.sideLogs === undefined ? {} : { sideLogs: options.sideLogs }),
|
|
786
|
+
...(options.turnIdleMs === undefined ? {} : { turnIdleMs: options.turnIdleMs }),
|
|
787
|
+
onRow: (row) => {
|
|
788
|
+
for (const observer of [...observers]) {
|
|
789
|
+
try {
|
|
790
|
+
observer(row);
|
|
791
|
+
} catch (error) {
|
|
792
|
+
logger.warn("[router] timing row observer failed", { error: error instanceof Error ? error.message : String(error) });
|
|
793
|
+
}
|
|
794
|
+
}
|
|
795
|
+
},
|
|
796
|
+
});
|
|
797
|
+
entry = { version: TIMING_REGISTRY_VERSION, recorder, observers, writeObservers, refs: 0 };
|
|
798
|
+
registry.set(id, entry);
|
|
799
|
+
}
|
|
800
|
+
// QA-PDF12-8: the first acquirer's clock, logger and turnIdleMs apply; every plugin instance passes its own closures, so a
|
|
801
|
+
// later caller with other ones is the normal case and is not reported.
|
|
802
|
+
const shared = entry;
|
|
803
|
+
shared.refs += 1;
|
|
804
|
+
const observer = options.onRow;
|
|
805
|
+
if (observer !== undefined) shared.observers.add(observer);
|
|
806
|
+
const observationHolder = Symbol();
|
|
807
|
+
if (options.onTimingWrite !== undefined) shared.writeObservers.set(observationHolder, options.onTimingWrite);
|
|
808
|
+
let released = false;
|
|
809
|
+
// When side logs are injected the recorder does not install `onRow` (the injected logs own their observer): a holder's observer then never fires.
|
|
810
|
+
return {
|
|
811
|
+
recordDispatchStart: (input) => shared.recorder.recordDispatchStart(input),
|
|
812
|
+
bindChild: (callID, childSessionID) => shared.recorder.bindChild(callID, childSessionID),
|
|
813
|
+
cancelStart: (callID) => shared.recorder.cancelStart(callID),
|
|
814
|
+
setBackground: (callID, background) => shared.recorder.setBackground(callID, background),
|
|
815
|
+
onExecutionOutcome: (childSessionID, eventId, outcome, at) => shared.recorder.onExecutionOutcome(childSessionID, eventId, outcome, at),
|
|
816
|
+
onCapacitySignal: (childSessionID, capacity, at) => shared.recorder.onCapacitySignal(childSessionID, capacity, at),
|
|
817
|
+
markRootSession: (sessionID) => shared.recorder.markRootSession(sessionID),
|
|
818
|
+
isRootSession: (sessionID) => shared.recorder.isRootSession(sessionID),
|
|
819
|
+
onRootPrompt: (sessionID, at, eventId) => shared.recorder.onRootPrompt(sessionID, at, eventId),
|
|
820
|
+
onRootExecutionEnd: (sessionID, eventId) => shared.recorder.onRootExecutionEnd(sessionID, eventId),
|
|
821
|
+
onRootStep: (sessionID, tokens, eventId) => shared.recorder.onRootStep(sessionID, tokens, eventId),
|
|
822
|
+
sweep: (at) => shared.recorder.sweep(at),
|
|
823
|
+
flush: () => shared.recorder.flush(),
|
|
824
|
+
dispose: () => shared.recorder.flush(),
|
|
825
|
+
async release(): Promise<void> {
|
|
826
|
+
if (released) return;
|
|
827
|
+
released = true;
|
|
828
|
+
if (observer !== undefined) shared.observers.delete(observer);
|
|
829
|
+
shared.writeObservers.delete(observationHolder);
|
|
830
|
+
shared.refs -= 1;
|
|
831
|
+
if (shared.refs > 0) return;
|
|
832
|
+
if (registry.get(id) === shared) registry.delete(id);
|
|
833
|
+
await shared.recorder.flush();
|
|
834
|
+
},
|
|
835
|
+
};
|
|
836
|
+
}
|