opencode-model-router 2.1.0 → 2.3.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 +86 -0
- package/README.md +44 -5
- package/package.json +4 -1
- package/src/commands/output.ts +4 -1
- package/src/compat/child-session.ts +43 -0
- package/src/compat/v2-client.ts +107 -7
- package/src/compat/v2-hooks.ts +174 -47
- package/src/escalate/attempt-recorder.ts +263 -0
- package/src/escalate/ladder.ts +484 -10
- package/src/escalate/resume.ts +208 -0
- package/src/escalate/variants.ts +391 -0
- package/src/index.ts +557 -61
- package/src/router/build-info.ts +151 -0
- package/src/router/config.ts +1691 -67
- package/src/router/protocol.ts +47 -0
- package/src/router/sessions.ts +441 -9
- package/src/routing/advisor/findings.ts +706 -0
- package/src/routing/advisor/index.ts +606 -0
- package/src/routing/classify/backends/host.ts +163 -0
- package/src/routing/classify/backends/openai-compatible.ts +275 -0
- package/src/routing/classify/backends/shared.ts +741 -0
- package/src/routing/classify/backends/typesafe.ts +315 -0
- package/src/routing/classify/fences.ts +96 -0
- package/src/routing/classify/index.ts +576 -0
- package/src/routing/classify/route-line.ts +298 -0
- package/src/routing/classify/rules.ts +607 -0
- package/src/routing/classify/scrub.ts +214 -0
- package/src/routing/classify/state.ts +148 -0
- package/src/routing/classify/text.ts +20 -0
- package/src/routing/classify/types.ts +1280 -0
- package/src/routing/commands/annotate-plan.ts +652 -0
- package/src/routing/commands/stats.ts +131 -0
- package/src/routing/commands/v1-roles.ts +64 -0
- package/src/routing/engine/index.ts +32 -0
- package/src/routing/engine/kernel.ts +597 -0
- package/src/routing/engine/ladders.ts +561 -0
- package/src/routing/engine/plan.ts +404 -0
- package/src/routing/engine/protocol-line.ts +133 -0
- package/src/routing/engine/simulate.ts +167 -0
- package/src/routing/engine/types.ts +270 -0
- package/src/routing/file-lock.ts +53 -0
- package/src/routing/outcomes/beta.ts +141 -0
- package/src/routing/outcomes/cost.ts +313 -0
- package/src/routing/outcomes/index.ts +172 -0
- package/src/routing/outcomes/ingest.ts +812 -0
- package/src/routing/outcomes/persist.ts +1058 -0
- package/src/routing/outcomes/stats.ts +602 -0
- package/src/routing/outcomes/store.ts +653 -0
- package/src/routing/outcomes/types.ts +954 -0
- package/src/routing/wire/dispatch.ts +799 -0
- package/src/routing/wire/hint.ts +208 -0
- package/src/routing/wire/host-info.ts +256 -0
- package/src/routing/wire/runtime.ts +259 -0
- package/src/v2.ts +15 -1
- package/tiers.json +43 -0
|
@@ -0,0 +1,812 @@
|
|
|
1
|
+
// ---------------------------------------------------------------------------
|
|
2
|
+
// Telemetry ingestion (M6, plan 2.1.2) — child-session outcomes and costs → outcome store.
|
|
3
|
+
//
|
|
4
|
+
// Signals handled (OpenCode v2 only, D1):
|
|
5
|
+
// - `session.step.ended` of a registered child → `store.recordStep` (cost and tokens, D6/A1)
|
|
6
|
+
// - a verifier verdict → `store.recordVerdict` + a `VerdictRow`
|
|
7
|
+
// - a false-refusal observation → `store.recordFalseRefusal` + a `RefusalRow`
|
|
8
|
+
// - a session that went away → open attempts folded, registry entries forgotten
|
|
9
|
+
//
|
|
10
|
+
// Rules (docs/qa/cost-aware-routing/phase-1.2.md, phase-1.3.md "to 2.1"):
|
|
11
|
+
// - Nothing happens unless `routing.engine !== "static"` (§1.2: no new files in static mode). The
|
|
12
|
+
// outcomes bundle is acquired lazily, on the first signal that is actually recorded.
|
|
13
|
+
// - Only children registered with `rememberDispatch` are recorded (`src/router/sessions.ts`).
|
|
14
|
+
// - Never record under a class whose `facts.confidence < routing.minClassConfidence`, and never under
|
|
15
|
+
// a backend label: the registry only ever holds `facts.class` (A19, QA-1.2-27). Such a dispatch has
|
|
16
|
+
// no store call and no verdict/refusal row.
|
|
17
|
+
// - The same `session.step.ended` (same event id) reaches every live location's plugin instance (S3b,
|
|
18
|
+
// A3): a module-scope LRU of event ids counts it once. The registry, the dedupe state and the store
|
|
19
|
+
// bundle (`acquireOutcomes`) are all process-wide; there is one writer per process.
|
|
20
|
+
// - Never on a dispatch's hot path: handlers only update memory and enqueue rows; the flusher writes
|
|
21
|
+
// (D15: on session idle/deleted and at most every 30 s, coalesced).
|
|
22
|
+
// - Errors are logged and swallowed (§0.10.10); a handler never throws into a session or the event loop.
|
|
23
|
+
// ---------------------------------------------------------------------------
|
|
24
|
+
|
|
25
|
+
import { homedir, tmpdir } from "node:os";
|
|
26
|
+
import type { RouterConfig, RouterHost } from "../../router/config";
|
|
27
|
+
import { resolveRouting } from "../../router/config";
|
|
28
|
+
import { getActiveTiers } from "../../router/protocol";
|
|
29
|
+
import {
|
|
30
|
+
forgetDispatch,
|
|
31
|
+
forgetDispatchesOf,
|
|
32
|
+
lookupDispatch,
|
|
33
|
+
noteExecutionEnded,
|
|
34
|
+
noteStepContext,
|
|
35
|
+
sweepDispatches,
|
|
36
|
+
touchDispatch,
|
|
37
|
+
} from "../../router/sessions";
|
|
38
|
+
import { stepContextTokens } from "../../escalate/variants";
|
|
39
|
+
import type { DispatchRecord } from "../../router/sessions";
|
|
40
|
+
import type { AcquireOutcomesOptions } from "./index";
|
|
41
|
+
import { acquireOutcomes } from "./index";
|
|
42
|
+
import { pricingState, tokenSampleFromEvent } from "./cost";
|
|
43
|
+
import { resolveOutcomesDir } from "./persist";
|
|
44
|
+
import type {
|
|
45
|
+
AttemptSignal,
|
|
46
|
+
Clock,
|
|
47
|
+
LoggedRoutingMode,
|
|
48
|
+
ModelPricing,
|
|
49
|
+
OutcomeKey,
|
|
50
|
+
OutcomeLogger,
|
|
51
|
+
OutcomesBundle,
|
|
52
|
+
OutcomeTuning,
|
|
53
|
+
RefusalRow,
|
|
54
|
+
OutcomeStore,
|
|
55
|
+
StepEndedTokens,
|
|
56
|
+
StepSample,
|
|
57
|
+
Verdict,
|
|
58
|
+
VerdictRow,
|
|
59
|
+
} from "./types";
|
|
60
|
+
import { LOG_ROW_VERSION, classifyAgentOrigin, makeKey, safeNow, splitModelRef } from "./types";
|
|
61
|
+
|
|
62
|
+
// ---------------------------------------------------------------------------
|
|
63
|
+
// Settings
|
|
64
|
+
// ---------------------------------------------------------------------------
|
|
65
|
+
|
|
66
|
+
/** What ingestion needs from the resolved config. `null` from {@link ingestSettings} = ingestion is off. */
|
|
67
|
+
export interface IngestSettings {
|
|
68
|
+
/** Never `static`: a static engine has no settings at all. */
|
|
69
|
+
readonly engine: LoggedRoutingMode;
|
|
70
|
+
readonly minClassConfidence: number;
|
|
71
|
+
/** Resolved outcomes directory (`routing.outcomes.path`, else the scorecard directory). */
|
|
72
|
+
readonly outcomesDir: string;
|
|
73
|
+
readonly tuning: OutcomeTuning;
|
|
74
|
+
/** Ids of the active preset's router tier agents (origin `router`); every other agent is `host`. */
|
|
75
|
+
readonly routerAgentIds: ReadonlySet<string>;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
const settingsCache = new WeakMap<RouterConfig, IngestSettings | null>();
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Ingestion settings for `cfg` on `host`, or `null` when ingestion must do nothing: any host but v2 (D1) and
|
|
82
|
+
* `routing.engine === "static"` (§1.2). Cached per config object (hot reload builds a new object).
|
|
83
|
+
*/
|
|
84
|
+
export function ingestSettings(cfg: RouterConfig | undefined, host: RouterHost): IngestSettings | null {
|
|
85
|
+
if (host !== "v2") return null;
|
|
86
|
+
const cached = cfg === undefined ? undefined : settingsCache.get(cfg);
|
|
87
|
+
if (cached !== undefined) return cached;
|
|
88
|
+
const routing = resolveRouting(cfg, host);
|
|
89
|
+
let settings: IngestSettings | null = null;
|
|
90
|
+
const engine = routing.engine;
|
|
91
|
+
if (engine !== "static") {
|
|
92
|
+
settings = Object.freeze({
|
|
93
|
+
engine,
|
|
94
|
+
minClassConfidence: routing.minClassConfidence,
|
|
95
|
+
outcomesDir: resolveOutcomesDir(routing.outcomes.path, { tmpdir: tmpdir(), homedir: homedir() }),
|
|
96
|
+
tuning: Object.freeze({
|
|
97
|
+
halfLifeDays: routing.outcomes.halfLifeDays,
|
|
98
|
+
maxEffectiveSamples: routing.outcomes.maxEffectiveSamples,
|
|
99
|
+
}),
|
|
100
|
+
routerAgentIds: new Set(cfg === undefined ? [] : Object.keys(getActiveTiers(cfg))),
|
|
101
|
+
});
|
|
102
|
+
}
|
|
103
|
+
if (cfg !== undefined) settingsCache.set(cfg, settings);
|
|
104
|
+
return settings;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
// ---------------------------------------------------------------------------
|
|
108
|
+
// Catalog pricing (A1/A10): supplied from the catalog lookup the v2 adapter already uses (`ctx.model.list`)
|
|
109
|
+
// ---------------------------------------------------------------------------
|
|
110
|
+
|
|
111
|
+
/** The part of a host catalog model that pricing needs (`Model.Info` is assignable). */
|
|
112
|
+
export interface CatalogModel {
|
|
113
|
+
readonly providerID: string;
|
|
114
|
+
readonly id: string;
|
|
115
|
+
readonly cost?: unknown;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
export type PricingLookup = (provider: string, model: string) => Promise<ModelPricing>;
|
|
119
|
+
|
|
120
|
+
export interface CatalogPricingOptions {
|
|
121
|
+
readonly now?: Clock;
|
|
122
|
+
readonly logger?: OutcomeLogger;
|
|
123
|
+
/** How long a loaded catalog is fresh (default 60 s); after that it is served stale while it reloads in the background. */
|
|
124
|
+
readonly ttlMs?: number;
|
|
125
|
+
/** After a failed or timed-out load, wait this long before trying again (default 15 s). */
|
|
126
|
+
readonly retryMs?: number;
|
|
127
|
+
/** The longest a lookup waits for the very first load of a catalog (default 2 s); then it answers `unpriced` (QA-2.1-5). */
|
|
128
|
+
readonly loadTimeoutMs?: number;
|
|
129
|
+
/** Shutdown: lookups waiting for a load return at once. The shared load itself is not cancelled. */
|
|
130
|
+
readonly signal?: AbortSignal;
|
|
131
|
+
/**
|
|
132
|
+
* Share the table, the in-flight load and the back-off with every lookup created with the same key, in the whole
|
|
133
|
+
* process (QA-2.1-2): the location directory. The first creator's `list` serves them all. Without a key the lookup
|
|
134
|
+
* has a private cache.
|
|
135
|
+
*/
|
|
136
|
+
readonly cacheKey?: string;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
interface CatalogLoad {
|
|
140
|
+
readonly promise: Promise<void>;
|
|
141
|
+
readonly startedAt: number;
|
|
142
|
+
/** A lookup stopped waiting for it (timeout). It stays pending: no other load starts while it does (QA-2.1-R2-4). */
|
|
143
|
+
abandoned: boolean;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
interface CatalogState {
|
|
147
|
+
table: Map<string, ModelPricing>;
|
|
148
|
+
loadedAt: number | null;
|
|
149
|
+
failedAt: number | null;
|
|
150
|
+
loading: CatalogLoad | null;
|
|
151
|
+
/** A lookup has timed out once: none waits again, however many loads follow, until one has succeeded (QA-2.1-R2-4). */
|
|
152
|
+
timedOut: boolean;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
const sharedCatalogs = new Map<string, CatalogState>();
|
|
156
|
+
|
|
157
|
+
/** Test-only: forget every shared catalog cache. */
|
|
158
|
+
export function resetCatalogPricing(): void {
|
|
159
|
+
sharedCatalogs.clear();
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
function asPricing(value: unknown): ModelPricing {
|
|
163
|
+
return typeof value === "object" && value !== null ? (value as ModelPricing) : undefined;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* Cached `provider/model → catalog cost` lookup over `list`. A model that is absent, a failed or slow first load, or
|
|
168
|
+
* a lookup that was aborted gives `undefined`, which {@link pricingState} reads as `unpriced` (A1): a `0` cost is then
|
|
169
|
+
* stored as unknown and only a positive host-reported cost is kept.
|
|
170
|
+
*
|
|
171
|
+
* It never blocks the serial event loop for long (QA-2.1-5): once a table has loaded it is served immediately, stale
|
|
172
|
+
* after the TTL while it reloads in the background; only the first lookup of a cold catalog waits, for at most
|
|
173
|
+
* `loadTimeoutMs` and never past `signal`. After one timeout nobody waits again until a load has succeeded, and a load
|
|
174
|
+
* that timed out stays pending: no second `list()` starts behind it (QA-2.1-R2-4). A failed load backs off for
|
|
175
|
+
* `retryMs`. Never rejects.
|
|
176
|
+
*/
|
|
177
|
+
export function createCatalogPricing(
|
|
178
|
+
list: () => Promise<readonly CatalogModel[]>,
|
|
179
|
+
options: CatalogPricingOptions = {},
|
|
180
|
+
): PricingLookup {
|
|
181
|
+
const now = options.now ?? Date.now;
|
|
182
|
+
const ttlMs = options.ttlMs ?? 60_000;
|
|
183
|
+
const retryMs = options.retryMs ?? 15_000;
|
|
184
|
+
const loadTimeoutMs = options.loadTimeoutMs ?? 2_000;
|
|
185
|
+
const { signal, logger } = options;
|
|
186
|
+
let state: CatalogState | undefined = options.cacheKey === undefined ? undefined : sharedCatalogs.get(options.cacheKey);
|
|
187
|
+
if (state === undefined) {
|
|
188
|
+
state = { table: new Map(), loadedAt: null, failedAt: null, loading: null, timedOut: false };
|
|
189
|
+
if (options.cacheKey !== undefined) sharedCatalogs.set(options.cacheKey, state);
|
|
190
|
+
}
|
|
191
|
+
const shared = state;
|
|
192
|
+
|
|
193
|
+
const startLoad = (t: number): CatalogLoad => {
|
|
194
|
+
const run = async (): Promise<void> => {
|
|
195
|
+
try {
|
|
196
|
+
const models = await list();
|
|
197
|
+
const next = new Map<string, ModelPricing>();
|
|
198
|
+
for (const model of models) next.set(`${model.providerID}/${model.id}`, asPricing(model.cost));
|
|
199
|
+
shared.table = next;
|
|
200
|
+
shared.loadedAt = safeNow(now);
|
|
201
|
+
shared.failedAt = null;
|
|
202
|
+
shared.timedOut = false;
|
|
203
|
+
} catch (error) {
|
|
204
|
+
shared.failedAt = safeNow(now);
|
|
205
|
+
logger?.warn("[router] outcome ingestion: model catalog unavailable; step costs treated as unpriced", {
|
|
206
|
+
error: describe(error),
|
|
207
|
+
});
|
|
208
|
+
}
|
|
209
|
+
};
|
|
210
|
+
const load: CatalogLoad = {
|
|
211
|
+
startedAt: t,
|
|
212
|
+
abandoned: false,
|
|
213
|
+
promise: run().finally(() => {
|
|
214
|
+
if (shared.loading === load) shared.loading = null;
|
|
215
|
+
}),
|
|
216
|
+
};
|
|
217
|
+
shared.loading = load;
|
|
218
|
+
return load;
|
|
219
|
+
};
|
|
220
|
+
|
|
221
|
+
/** Wait for `load`, but not longer than `loadTimeoutMs` and not past an abort. */
|
|
222
|
+
const waitFor = (load: CatalogLoad): Promise<"done" | "timeout" | "aborted"> => {
|
|
223
|
+
if (signal?.aborted === true) return Promise.resolve("aborted");
|
|
224
|
+
return new Promise<"done" | "timeout" | "aborted">((resolve) => {
|
|
225
|
+
const onAbort = (): void => finish("aborted");
|
|
226
|
+
const timer = setTimeout(() => finish("timeout"), loadTimeoutMs);
|
|
227
|
+
timer.unref();
|
|
228
|
+
const finish = (outcome: "done" | "timeout" | "aborted"): void => {
|
|
229
|
+
clearTimeout(timer);
|
|
230
|
+
signal?.removeEventListener("abort", onAbort);
|
|
231
|
+
resolve(outcome);
|
|
232
|
+
};
|
|
233
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
234
|
+
void load.promise.then(() => finish("done"));
|
|
235
|
+
});
|
|
236
|
+
};
|
|
237
|
+
|
|
238
|
+
return async (provider, model) => {
|
|
239
|
+
const t = safeNow(now);
|
|
240
|
+
const fresh = shared.loadedAt !== null && t - shared.loadedAt < ttlMs;
|
|
241
|
+
if (!fresh) {
|
|
242
|
+
const backingOff = shared.failedAt !== null && t - shared.failedAt < retryMs;
|
|
243
|
+
let load = shared.loading;
|
|
244
|
+
if (load === null && !backingOff) load = startLoad(t);
|
|
245
|
+
if (shared.loadedAt === null && load !== null && !load.abandoned && !shared.timedOut) {
|
|
246
|
+
const outcome = await waitFor(load);
|
|
247
|
+
if (outcome === "timeout" && shared.loadedAt === null) {
|
|
248
|
+
load.abandoned = true;
|
|
249
|
+
shared.timedOut = true;
|
|
250
|
+
shared.failedAt = safeNow(now);
|
|
251
|
+
logger?.warn("[router] outcome ingestion: model catalog is slow; step costs treated as unpriced", { loadTimeoutMs });
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
return shared.table.get(`${provider}/${model}`);
|
|
256
|
+
};
|
|
257
|
+
}
|
|
258
|
+
// ---------------------------------------------------------------------------
|
|
259
|
+
// Module-scope state (A3: shared by every plugin instance of the process)
|
|
260
|
+
// ---------------------------------------------------------------------------
|
|
261
|
+
|
|
262
|
+
/** Event ids remembered for the duplicate-delivery dedupe (LRU). */
|
|
263
|
+
export const SEEN_EVENT_CAP = 4096;
|
|
264
|
+
/** Signals (verdict/refusal rows) remembered so a repeated signal enqueues one row. */
|
|
265
|
+
const SIGNAL_CAP = 4096;
|
|
266
|
+
/** Children whose last attempt id is tracked (so a superseded attempt can be folded). */
|
|
267
|
+
const LAST_ATTEMPT_CAP = 2000;
|
|
268
|
+
/** Final steps held back until their attempt ends (QA-2.1-6). */
|
|
269
|
+
const HELD_FINAL_CAP = 2000;
|
|
270
|
+
/** A held final step whose attempt never reported its end is folded after this idle time (the store's own default). */
|
|
271
|
+
const HELD_FINAL_IDLE_MS = 30 * 60_000;
|
|
272
|
+
/** Model references already reported as unkeyable (model unresolved), one warning each. */
|
|
273
|
+
const WARNED_CAP = 500;
|
|
274
|
+
|
|
275
|
+
const seenEvents = new Map<string, true>();
|
|
276
|
+
const signalled = new Set<string>();
|
|
277
|
+
/** What scored each attempt in the store (`pass`, `fail` or `refusal`), so a refusal knows whether it converts a pass. */
|
|
278
|
+
const scored = new Map<string, "pass" | "fail" | "refusal">();
|
|
279
|
+
/** `${outcomesDir}|${child}` → the attempt the child's latest step belongs to (a store in another directory is another recording). */
|
|
280
|
+
const lastAttemptByChild = new Map<string, LastAttempt>();
|
|
281
|
+
const warnedUnkeyed = new Set<string>();
|
|
282
|
+
|
|
283
|
+
interface LastAttempt {
|
|
284
|
+
readonly dir: string;
|
|
285
|
+
readonly attempt: string;
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
interface HeldFinal {
|
|
289
|
+
readonly dir: string;
|
|
290
|
+
readonly attempt: string;
|
|
291
|
+
readonly key: OutcomeKey;
|
|
292
|
+
/** Already marked `final`: recorded as such when the attempt ends. */
|
|
293
|
+
readonly sample: StepSample;
|
|
294
|
+
readonly at: number;
|
|
295
|
+
}
|
|
296
|
+
/**
|
|
297
|
+
* QA-2.1-6: a step that finished with anything but `tool-calls` only sets the attempt's `finalOutput`; the attempt
|
|
298
|
+
* stays open (a `length` or `error` finish may be followed by more steps) and is folded when its execution ends. The
|
|
299
|
+
* step is held here, outside the store, until the next step of the attempt (then it was not the last), the end of the
|
|
300
|
+
* execution, the session's deletion, a sweep or a dispose.
|
|
301
|
+
*/
|
|
302
|
+
const heldFinals = new Map<string, HeldFinal>();
|
|
303
|
+
|
|
304
|
+
function boundedSet<V>(map: Map<string, V>, key: string, value: V, cap: number): void {
|
|
305
|
+
map.delete(key);
|
|
306
|
+
map.set(key, value);
|
|
307
|
+
while (map.size > cap) {
|
|
308
|
+
const oldest = map.keys().next();
|
|
309
|
+
if (oldest.done === true) break;
|
|
310
|
+
map.delete(oldest.value);
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
function boundedAdd(set: Set<string>, value: string, cap: number): boolean {
|
|
315
|
+
if (set.has(value)) return false;
|
|
316
|
+
set.add(value);
|
|
317
|
+
while (set.size > cap) {
|
|
318
|
+
const oldest = set.values().next();
|
|
319
|
+
if (oldest.done === true) break;
|
|
320
|
+
set.delete(oldest.value);
|
|
321
|
+
}
|
|
322
|
+
return true;
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
/** True the first time an event id is seen. A repeat refreshes its recency (LRU). */
|
|
326
|
+
function firstDelivery(eventKey: string): boolean {
|
|
327
|
+
if (seenEvents.has(eventKey)) {
|
|
328
|
+
seenEvents.delete(eventKey);
|
|
329
|
+
seenEvents.set(eventKey, true);
|
|
330
|
+
return false;
|
|
331
|
+
}
|
|
332
|
+
seenEvents.set(eventKey, true);
|
|
333
|
+
while (seenEvents.size > SEEN_EVENT_CAP) {
|
|
334
|
+
const oldest = seenEvents.keys().next();
|
|
335
|
+
if (oldest.done === true) break;
|
|
336
|
+
seenEvents.delete(oldest.value);
|
|
337
|
+
}
|
|
338
|
+
return true;
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
const scopeKey = (dir: string, id: string): string => `${dir}|${id}`;
|
|
342
|
+
|
|
343
|
+
function rememberAttempt(dir: string, child: string, attemptId: string): string | undefined {
|
|
344
|
+
const mapKey = scopeKey(dir, child);
|
|
345
|
+
const previous = lastAttemptByChild.get(mapKey)?.attempt;
|
|
346
|
+
lastAttemptByChild.delete(mapKey);
|
|
347
|
+
lastAttemptByChild.set(mapKey, { dir, attempt: attemptId });
|
|
348
|
+
while (lastAttemptByChild.size > LAST_ATTEMPT_CAP) {
|
|
349
|
+
const oldest = lastAttemptByChild.keys().next();
|
|
350
|
+
if (oldest.done === true) break;
|
|
351
|
+
lastAttemptByChild.delete(oldest.value);
|
|
352
|
+
}
|
|
353
|
+
return previous;
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
/** Test-only: drop the module-scope dedupe and attempt state (the dispatch registry has its own reset). */
|
|
357
|
+
export function resetIngestState(): void {
|
|
358
|
+
resetCatalogPricing();
|
|
359
|
+
seenEvents.clear();
|
|
360
|
+
signalled.clear();
|
|
361
|
+
scored.clear();
|
|
362
|
+
lastAttemptByChild.clear();
|
|
363
|
+
warnedUnkeyed.clear();
|
|
364
|
+
heldFinals.clear();
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
// ---------------------------------------------------------------------------
|
|
368
|
+
// Ingest
|
|
369
|
+
// ---------------------------------------------------------------------------
|
|
370
|
+
|
|
371
|
+
/** A v2 event as delivered by `ctx.event.subscribe` (only what ingestion reads). */
|
|
372
|
+
export interface IngestEvent {
|
|
373
|
+
readonly id?: unknown;
|
|
374
|
+
readonly type: string;
|
|
375
|
+
readonly data?: unknown;
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
export interface IngestDeps {
|
|
379
|
+
/** Settings for the current call; `null` = ingestion off. Called per event, so it must be cheap (cache by config). */
|
|
380
|
+
readonly settings: () => IngestSettings | null;
|
|
381
|
+
readonly logger: OutcomeLogger;
|
|
382
|
+
/** Catalog pricing of `provider`/`model`; absent → every step is priced as `unpriced` (A1). Only step events use it. */
|
|
383
|
+
readonly pricing?: PricingLookup;
|
|
384
|
+
/** Clock for row timestamps (default `Date.now`). */
|
|
385
|
+
readonly now?: Clock;
|
|
386
|
+
/** Seam over `acquireOutcomes` (tests pass injected deps/scheduler through). */
|
|
387
|
+
readonly acquire?: (options: AcquireOutcomesOptions) => OutcomesBundle;
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
export interface Ingest {
|
|
391
|
+
/**
|
|
392
|
+
* `session.step.ended` (and `session.step.failed`, when it carries a cost or tokens) of a registered child. Awaits
|
|
393
|
+
* only the cached catalog lookup, bounded by its load timeout. Never rejects.
|
|
394
|
+
*/
|
|
395
|
+
onStepEnded(event: IngestEvent): Promise<void>;
|
|
396
|
+
/**
|
|
397
|
+
* The child's execution ended (succeeded, failed or interrupted): its open attempt is folded (QA-2.1-6) and its
|
|
398
|
+
* registration is marked ended for the delegate ladder (QA-2.3-2). `eventId` is the host event's id: a copy of the
|
|
399
|
+
* same event delivered again (to another plugin instance, perhaps after the child was registered again) is ignored
|
|
400
|
+
* (QA-2.3-R2-1). Without an id every delivery is applied.
|
|
401
|
+
*/
|
|
402
|
+
onExecutionEnded(childSessionID: string, eventId?: unknown): void;
|
|
403
|
+
/** A verifier verdict for the child's current attempt. Never throws. */
|
|
404
|
+
onVerdict(childSessionID: string, outcome: Verdict): void;
|
|
405
|
+
/** A false refusal (zero tool calls) observed for the child's current attempt. Never throws. */
|
|
406
|
+
onFalseRefusal(childSessionID: string): void;
|
|
407
|
+
/** A session was deleted: the child's open attempt is folded and its registry entry dropped; children of the session too. */
|
|
408
|
+
onSessionGone(sessionID: string): void;
|
|
409
|
+
/** Idle/deleted flush point (D15): coalesced and throttled by the flusher, never awaited. No-op without recorded data. */
|
|
410
|
+
requestFlush(): void;
|
|
411
|
+
/** Opportunistic maintenance for the idle sweeper: expired dispatches, idle open attempts. */
|
|
412
|
+
sweep(): void;
|
|
413
|
+
/** Flush and release this instance's reference to the outcomes bundle. Never rejects. */
|
|
414
|
+
dispose(): Promise<void>;
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
/** Event types after which the router flushes (v2's equivalents of `session.idle`, plus the idle/deleted events). */
|
|
418
|
+
/** An ingest that does nothing (a v2 adapter started without the plugin's own). */
|
|
419
|
+
export const NOOP_INGEST: Ingest = Object.freeze({
|
|
420
|
+
onStepEnded: () => Promise.resolve(),
|
|
421
|
+
onExecutionEnded: () => undefined,
|
|
422
|
+
onVerdict: () => undefined,
|
|
423
|
+
onFalseRefusal: () => undefined,
|
|
424
|
+
onSessionGone: () => undefined,
|
|
425
|
+
requestFlush: () => undefined,
|
|
426
|
+
sweep: () => undefined,
|
|
427
|
+
dispose: () => Promise.resolve(),
|
|
428
|
+
});
|
|
429
|
+
|
|
430
|
+
/** The v2 events that end a session's execution (the adapter maps them to `session.idle`). */
|
|
431
|
+
export const EXECUTION_END_TYPES: ReadonlySet<string> = new Set([
|
|
432
|
+
"session.execution.succeeded",
|
|
433
|
+
"session.execution.failed",
|
|
434
|
+
"session.execution.interrupted",
|
|
435
|
+
]);
|
|
436
|
+
|
|
437
|
+
export const FLUSH_EVENT_TYPES: ReadonlySet<string> = new Set([
|
|
438
|
+
"session.idle",
|
|
439
|
+
"session.deleted",
|
|
440
|
+
...EXECUTION_END_TYPES,
|
|
441
|
+
]);
|
|
442
|
+
|
|
443
|
+
function describe(error: unknown): string {
|
|
444
|
+
return error instanceof Error ? error.message : String(error);
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
448
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
interface Target {
|
|
452
|
+
readonly record: DispatchRecord;
|
|
453
|
+
readonly settings: IngestSettings;
|
|
454
|
+
readonly key: OutcomeKey;
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
export function createIngest(deps: IngestDeps): Ingest {
|
|
458
|
+
const now: Clock = deps.now ?? Date.now;
|
|
459
|
+
const acquire = deps.acquire ?? acquireOutcomes;
|
|
460
|
+
let held: { readonly dir: string; readonly bundle: OutcomesBundle; tuning: OutcomeTuning } | null = null;
|
|
461
|
+
let disposed = false;
|
|
462
|
+
|
|
463
|
+
const warn = (message: string, error: unknown, extra?: Record<string, unknown>): void => {
|
|
464
|
+
deps.logger.warn(`[router] outcome ingestion: ${message}`, { ...extra, error: describe(error) });
|
|
465
|
+
};
|
|
466
|
+
|
|
467
|
+
/** The bundle for `settings.outcomesDir`, acquired on first use; a changed directory re-acquires. */
|
|
468
|
+
const bundleFor = (settings: IngestSettings): OutcomesBundle | null => {
|
|
469
|
+
if (disposed) return null;
|
|
470
|
+
if (held !== null && held.dir === settings.outcomesDir) {
|
|
471
|
+
if (
|
|
472
|
+
held.tuning.halfLifeDays !== settings.tuning.halfLifeDays ||
|
|
473
|
+
held.tuning.maxEffectiveSamples !== settings.tuning.maxEffectiveSamples
|
|
474
|
+
) {
|
|
475
|
+
held.bundle.store.configure(settings.tuning);
|
|
476
|
+
held.tuning = settings.tuning;
|
|
477
|
+
}
|
|
478
|
+
return held.bundle;
|
|
479
|
+
}
|
|
480
|
+
const previous = held;
|
|
481
|
+
if (previous !== null) settleOwned(); // while `held` still names the old directory
|
|
482
|
+
held = null;
|
|
483
|
+
if (previous !== null) {
|
|
484
|
+
void previous.bundle.release().catch((error: unknown) => warn("releasing the previous outcomes directory failed", error));
|
|
485
|
+
}
|
|
486
|
+
const bundle = acquire({ dir: settings.outcomesDir, tuning: settings.tuning, logger: deps.logger });
|
|
487
|
+
held = { dir: settings.outcomesDir, bundle, tuning: settings.tuning };
|
|
488
|
+
return bundle;
|
|
489
|
+
};
|
|
490
|
+
|
|
491
|
+
/** Registered, trusted and keyable? Otherwise nothing may be recorded for the child. */
|
|
492
|
+
const targetOf = (childSessionID: string): Target | null => {
|
|
493
|
+
// Registry first: most `session.step.ended` events belong to sessions that are not registered children
|
|
494
|
+
// (the orchestrator's own), and the settings may cost a config fingerprint check.
|
|
495
|
+
const record = lookupDispatch(childSessionID);
|
|
496
|
+
if (record === undefined) return null;
|
|
497
|
+
// Registered where ingestion was off (QA-2.3-6): another instance's configuration decides, not this one's.
|
|
498
|
+
if (record.outcomes === false) return null;
|
|
499
|
+
const settings = deps.settings();
|
|
500
|
+
if (settings === null) return null;
|
|
501
|
+
const confidence = record.facts.confidence;
|
|
502
|
+
// Phase 1.2 handoff (QA-1.2-27): a class below the threshold is "unknown" for learning, not a class of
|
|
503
|
+
// its own. No fallback class, no store call, no row.
|
|
504
|
+
if (typeof confidence !== "number" || !Number.isFinite(confidence) || confidence < settings.minClassConfidence) {
|
|
505
|
+
return null;
|
|
506
|
+
}
|
|
507
|
+
const cls = record.facts.class;
|
|
508
|
+
if (typeof cls !== "string" || cls === "" || cls === "unknown") return null;
|
|
509
|
+
if (record.model === null) return unkeyable(`${record.agent}|`, childSessionID, "the dispatch registered no model");
|
|
510
|
+
const ref = splitModelRef(record.model);
|
|
511
|
+
if (ref === null) return unkeyable(`${record.agent}|${record.model}`, childSessionID, `model "${record.model}" is not provider/model`);
|
|
512
|
+
const variant = record.variant ?? ref.variant;
|
|
513
|
+
const origin = classifyAgentOrigin(record.agent, settings.routerAgentIds);
|
|
514
|
+
const key = makeKey(cls, { origin, id: record.agent }, ref.provider, ref.model, variant);
|
|
515
|
+
return { record, settings, key };
|
|
516
|
+
};
|
|
517
|
+
|
|
518
|
+
// One warning per model reference (QA-2.1-12), not per child: every child of an unresolved agent says the same.
|
|
519
|
+
const unkeyable = (reference: string, childSessionID: string, why: string): null => {
|
|
520
|
+
if (boundedAdd(warnedUnkeyed, reference, WARNED_CAP)) {
|
|
521
|
+
deps.logger.warn(`[router] outcome ingestion: child ${childSessionID} is not recorded: ${why}`);
|
|
522
|
+
}
|
|
523
|
+
return null;
|
|
524
|
+
};
|
|
525
|
+
|
|
526
|
+
const signalOf = (record: DispatchRecord): AttemptSignal => ({ attemptID: record.attemptId, step: record.step });
|
|
527
|
+
|
|
528
|
+
const rowBase = (record: DispatchRecord): { v: typeof LOG_ROW_VERSION; ts: string; sessionID: string } => ({
|
|
529
|
+
v: LOG_ROW_VERSION,
|
|
530
|
+
ts: new Date(safeNow(now)).toISOString(),
|
|
531
|
+
sessionID: record.parentSessionID ?? "",
|
|
532
|
+
});
|
|
533
|
+
|
|
534
|
+
/** Held final steps this instance created (`${dir}|${attempt}`), released with it. */
|
|
535
|
+
const ownedHeld = new Set<string>();
|
|
536
|
+
|
|
537
|
+
/** The outcomes directory this instance writes to right now, or null when ingestion is off. */
|
|
538
|
+
const currentDir = (): string | null => held?.dir ?? deps.settings()?.outcomesDir ?? null;
|
|
539
|
+
|
|
540
|
+
/** The shared store of `dir`, through this instance's bundle when it has one; null when ingestion is off for `dir`. */
|
|
541
|
+
const storeOf = (dir: string): OutcomeStore | null => {
|
|
542
|
+
if (held !== null) return held.dir === dir ? held.bundle.store : null;
|
|
543
|
+
const settings = deps.settings();
|
|
544
|
+
return settings === null || settings.outcomesDir !== dir ? null : (bundleFor(settings)?.store ?? null);
|
|
545
|
+
};
|
|
546
|
+
|
|
547
|
+
/** Record the held final step of an attempt: as its last step (`asFinal`, folds the attempt) or as a plain step. */
|
|
548
|
+
const settle = (dir: string, attemptId: string, asFinal: boolean): void => {
|
|
549
|
+
const heldKey = scopeKey(dir, attemptId);
|
|
550
|
+
const pending = heldFinals.get(heldKey);
|
|
551
|
+
if (pending === undefined) return;
|
|
552
|
+
// The held step is shared by every instance of the process (QA-2.1-R2-1): when this one cannot reach the store of
|
|
553
|
+
// `dir` (it is off, disposed or writes elsewhere) the step stays for the instance that can.
|
|
554
|
+
const store = storeOf(dir);
|
|
555
|
+
if (store === null) return;
|
|
556
|
+
heldFinals.delete(heldKey);
|
|
557
|
+
ownedHeld.delete(heldKey);
|
|
558
|
+
store.recordStep(pending.key, asFinal ? pending.sample : { ...pending.sample, final: false });
|
|
559
|
+
};
|
|
560
|
+
|
|
561
|
+
/** Fold an attempt that is over: its held final step first, then whatever is still open. */
|
|
562
|
+
const endAttempt = (dir: string, attemptId: string): void => {
|
|
563
|
+
settle(dir, attemptId, true);
|
|
564
|
+
storeOf(dir)?.closeAttempt(attemptId);
|
|
565
|
+
};
|
|
566
|
+
|
|
567
|
+
const closeLastAttempt = (childSessionID: string): void => {
|
|
568
|
+
const dir = currentDir();
|
|
569
|
+
if (dir === null) return;
|
|
570
|
+
const mapKey = scopeKey(dir, childSessionID);
|
|
571
|
+
const last = lastAttemptByChild.get(mapKey);
|
|
572
|
+
lastAttemptByChild.delete(mapKey);
|
|
573
|
+
if (last !== undefined) endAttempt(last.dir, last.attempt);
|
|
574
|
+
};
|
|
575
|
+
|
|
576
|
+
const settleOwned = (): void => {
|
|
577
|
+
for (const heldKey of [...ownedHeld]) {
|
|
578
|
+
const pending = heldFinals.get(heldKey);
|
|
579
|
+
if (pending === undefined) ownedHeld.delete(heldKey);
|
|
580
|
+
else settle(pending.dir, pending.attempt, true);
|
|
581
|
+
}
|
|
582
|
+
};
|
|
583
|
+
|
|
584
|
+
/** QA-2.1-11: ingestion went off (engine switched to static): finish what is pending and let the bundle go. */
|
|
585
|
+
const dropIfOff = (): boolean => {
|
|
586
|
+
if (held === null || deps.settings() !== null) return false;
|
|
587
|
+
settleOwned();
|
|
588
|
+
const current = held;
|
|
589
|
+
held = null;
|
|
590
|
+
void current.bundle.release().catch((error: unknown) => warn("releasing the outcomes bundle failed", error));
|
|
591
|
+
return true;
|
|
592
|
+
};
|
|
593
|
+
return {
|
|
594
|
+
async onStepEnded(event: IngestEvent): Promise<void> {
|
|
595
|
+
try {
|
|
596
|
+
const failed = event.type === "session.step.failed";
|
|
597
|
+
if ((event.type !== "session.step.ended" && !failed) || !isRecord(event.data)) return;
|
|
598
|
+
const data = event.data;
|
|
599
|
+
const sessionID = data.sessionID;
|
|
600
|
+
if (typeof sessionID !== "string") return;
|
|
601
|
+
// Phase 2.3 (D11): the delegate ladder decides resume vs fresh from the child's context size, in every engine
|
|
602
|
+
// mode, so this runs before the settings gate. It only updates the in-memory registry (nothing is written)
|
|
603
|
+
// and ignores children that are not registered.
|
|
604
|
+
if (!failed && lookupDispatch(sessionID) !== undefined) {
|
|
605
|
+
const context = stepContextTokens(isRecord(data.tokens) ? data.tokens : undefined);
|
|
606
|
+
if (context !== null) noteStepContext(sessionID, context, safeNow(now));
|
|
607
|
+
}
|
|
608
|
+
const first = targetOf(sessionID);
|
|
609
|
+
if (first === null) return;
|
|
610
|
+
const tokens = isRecord(data.tokens) ? (data.tokens as unknown as StepEndedTokens) : undefined;
|
|
611
|
+
// A failed step reports cost and tokens only when it got that far (QA-2.1-6): nothing measured, nothing to add.
|
|
612
|
+
if (failed && typeof data.cost !== "number" && tokens === undefined) return;
|
|
613
|
+
const eventKey =
|
|
614
|
+
typeof event.id === "string" && event.id !== ""
|
|
615
|
+
? event.id
|
|
616
|
+
: `${sessionID}|${String(data.assistantMessageID)}|${String(data.cost)}|${tokens?.input}|${tokens?.output}`;
|
|
617
|
+
// Pricing first (cached, or bounded by the catalog's own load timeout): a slow lookup must not decide
|
|
618
|
+
// which instance owns the event (QA-2.1-2).
|
|
619
|
+
const ref = splitModelRef(first.record.model ?? "");
|
|
620
|
+
const pricing = ref === null || deps.pricing === undefined ? undefined : await deps.pricing(ref.provider, ref.model);
|
|
621
|
+
if (disposed) return;
|
|
622
|
+
// From here on everything is synchronous, so the check and the record of an event id cannot interleave
|
|
623
|
+
// with another instance. The registry and the settings may have changed during the await.
|
|
624
|
+
const target = targetOf(sessionID);
|
|
625
|
+
if (target === null) return;
|
|
626
|
+
const { record, settings, key } = target;
|
|
627
|
+
// The pricing above belongs to the registration read before the await. A child that was registered again
|
|
628
|
+
// meanwhile (a new attempt, perhaps another model) must not receive a step of the previous one
|
|
629
|
+
// (QA-2.1-R2-11).
|
|
630
|
+
if (record.attemptId !== first.record.attemptId) return;
|
|
631
|
+
// Dedupe only a step that is about to be recorded: an instance whose own settings are static must not
|
|
632
|
+
// consume the event another instance (another location, another config) will record. The directory is
|
|
633
|
+
// part of the key (QA-2.1-8): a store in another directory is a different recording.
|
|
634
|
+
if (!firstDelivery(`${settings.outcomesDir}|${eventKey}`)) return;
|
|
635
|
+
const bundle = bundleFor(settings);
|
|
636
|
+
if (bundle === null) return;
|
|
637
|
+
const dir = settings.outcomesDir;
|
|
638
|
+
const superseded = rememberAttempt(dir, sessionID, record.attemptId);
|
|
639
|
+
if (superseded !== undefined && superseded !== record.attemptId) endAttempt(dir, superseded);
|
|
640
|
+
const sample: StepSample = {
|
|
641
|
+
attemptID: record.attemptId,
|
|
642
|
+
cost: typeof data.cost === "number" ? data.cost : Number.NaN,
|
|
643
|
+
pricing: pricingState(pricing),
|
|
644
|
+
tokens: tokenSampleFromEvent(
|
|
645
|
+
tokens ?? { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
|
|
646
|
+
),
|
|
647
|
+
final: false,
|
|
648
|
+
};
|
|
649
|
+
// A step after a held final one proves that one was not the last.
|
|
650
|
+
settle(dir, record.attemptId, false);
|
|
651
|
+
if (!failed && data.finish !== "tool-calls") {
|
|
652
|
+
const heldKey = scopeKey(dir, record.attemptId);
|
|
653
|
+
boundedSet(heldFinals, heldKey, { dir, attempt: record.attemptId, key, sample: { ...sample, final: true }, at: safeNow(now) }, HELD_FINAL_CAP);
|
|
654
|
+
ownedHeld.add(heldKey);
|
|
655
|
+
} else {
|
|
656
|
+
bundle.store.recordStep(key, sample);
|
|
657
|
+
}
|
|
658
|
+
touchDispatch(sessionID, safeNow(now));
|
|
659
|
+
} catch (error) {
|
|
660
|
+
warn("session.step.ended failed", error);
|
|
661
|
+
}
|
|
662
|
+
},
|
|
663
|
+
onExecutionEnded(childSessionID: string, eventId?: unknown): void {
|
|
664
|
+
try {
|
|
665
|
+
if (lookupDispatch(childSessionID) === undefined) return;
|
|
666
|
+
const id = typeof eventId === "string" && eventId !== "" ? eventId : undefined;
|
|
667
|
+
// Phase 2.3 (QA-2.3-2): every step event of this registration has been noted, whatever the engine mode; the
|
|
668
|
+
// delegate ladder reads the child's context only after this. The registry applies an end id once per process.
|
|
669
|
+
noteExecutionEnded(childSessionID, safeNow(now), id);
|
|
670
|
+
// The fold is per outcomes directory, like the step events' dedupe: an instance that cannot record (static, or
|
|
671
|
+
// another directory) must not consume the end another instance folds with. A stale copy delivered after the
|
|
672
|
+
// child was registered again would otherwise fold the NEW attempt early (QA-2.3-R2-1).
|
|
673
|
+
const dir = currentDir();
|
|
674
|
+
if (id !== undefined && dir !== null && !firstDelivery(`${dir}|end|${id}`)) return;
|
|
675
|
+
closeLastAttempt(childSessionID);
|
|
676
|
+
} catch (error) {
|
|
677
|
+
warn("execution end failed", error, { childSessionID });
|
|
678
|
+
}
|
|
679
|
+
},
|
|
680
|
+
|
|
681
|
+
onVerdict(childSessionID: string, outcome: Verdict): void {
|
|
682
|
+
try {
|
|
683
|
+
const target = targetOf(childSessionID);
|
|
684
|
+
if (target === null) return;
|
|
685
|
+
const { record, settings, key } = target;
|
|
686
|
+
const bundle = bundleFor(settings);
|
|
687
|
+
if (bundle === null) return;
|
|
688
|
+
const attempt = record.attemptId;
|
|
689
|
+
// Rows follow the store (QA-2.1-3): a verdict that moves nothing (the attempt was scored already, by a
|
|
690
|
+
// verdict or a refusal) writes no row, or `routing:stats` would count outcomes the store never saw.
|
|
691
|
+
// `unverifiable` moves nothing by design; it is a row only while the attempt is still unscored.
|
|
692
|
+
if (outcome === "unverifiable") {
|
|
693
|
+
if (scored.has(attempt) || !boundedAdd(signalled, `unverifiable|${attempt}`, SIGNAL_CAP)) return;
|
|
694
|
+
} else {
|
|
695
|
+
if (!bundle.store.recordVerdict(key, outcome, signalOf(record))) return;
|
|
696
|
+
boundedSet(scored, attempt, outcome, SIGNAL_CAP);
|
|
697
|
+
}
|
|
698
|
+
const row: VerdictRow = {
|
|
699
|
+
...rowBase(record),
|
|
700
|
+
kind: "verdict",
|
|
701
|
+
decisionID: record.decisionID,
|
|
702
|
+
childSessionID,
|
|
703
|
+
attemptID: attempt,
|
|
704
|
+
key,
|
|
705
|
+
verdict: outcome,
|
|
706
|
+
step: record.step,
|
|
707
|
+
};
|
|
708
|
+
bundle.flusher.enqueue(row);
|
|
709
|
+
touchDispatch(childSessionID, safeNow(now));
|
|
710
|
+
} catch (error) {
|
|
711
|
+
warn("verdict failed", error, { childSessionID });
|
|
712
|
+
}
|
|
713
|
+
},
|
|
714
|
+
|
|
715
|
+
onFalseRefusal(childSessionID: string): void {
|
|
716
|
+
try {
|
|
717
|
+
const target = targetOf(childSessionID);
|
|
718
|
+
if (target === null) return;
|
|
719
|
+
const { record, settings, key } = target;
|
|
720
|
+
const attempt = record.attemptId;
|
|
721
|
+
// One refusal per attempt (QA-2.1-9): a repeat must not reach the store, whose lifetime counter would grow.
|
|
722
|
+
if (!boundedAdd(signalled, `refusal|${attempt}`, SIGNAL_CAP)) return;
|
|
723
|
+
const bundle = bundleFor(settings);
|
|
724
|
+
if (bundle === null) return;
|
|
725
|
+
const prior = scored.get(attempt);
|
|
726
|
+
// The store converts an earlier `pass` of the same attempt into a failure (C5, QA-1.3-6); the row says so,
|
|
727
|
+
// and `routing:stats` moves that pass to a fail the same way.
|
|
728
|
+
const changed = bundle.store.recordFalseRefusal(key, signalOf(record));
|
|
729
|
+
boundedSet(scored, attempt, "refusal", SIGNAL_CAP);
|
|
730
|
+
const row: RefusalRow = {
|
|
731
|
+
...rowBase(record),
|
|
732
|
+
kind: "refusal",
|
|
733
|
+
decisionID: record.decisionID,
|
|
734
|
+
childSessionID,
|
|
735
|
+
attemptID: attempt,
|
|
736
|
+
key,
|
|
737
|
+
step: record.step,
|
|
738
|
+
...(prior === "pass" && changed ? { overrides: "pass" as const } : {}),
|
|
739
|
+
};
|
|
740
|
+
bundle.flusher.enqueue(row);
|
|
741
|
+
touchDispatch(childSessionID, safeNow(now));
|
|
742
|
+
} catch (error) {
|
|
743
|
+
warn("false refusal failed", error, { childSessionID });
|
|
744
|
+
}
|
|
745
|
+
},
|
|
746
|
+
onSessionGone(sessionID: string): void {
|
|
747
|
+
try {
|
|
748
|
+
if (lookupDispatch(sessionID) !== undefined) {
|
|
749
|
+
closeLastAttempt(sessionID);
|
|
750
|
+
forgetDispatch(sessionID);
|
|
751
|
+
}
|
|
752
|
+
// The orchestrator went away: its children can no longer receive verdicts.
|
|
753
|
+
for (const child of forgetDispatchesOf(sessionID)) closeLastAttempt(child.childSessionID);
|
|
754
|
+
if (held !== null) void held.bundle.flusher.requestFlush();
|
|
755
|
+
} catch (error) {
|
|
756
|
+
warn("session cleanup failed", error, { sessionID });
|
|
757
|
+
}
|
|
758
|
+
},
|
|
759
|
+
|
|
760
|
+
requestFlush(): void {
|
|
761
|
+
try {
|
|
762
|
+
if (dropIfOff()) return;
|
|
763
|
+
if (held !== null) void held.bundle.flusher.requestFlush();
|
|
764
|
+
} catch (error) {
|
|
765
|
+
warn("flush request failed", error);
|
|
766
|
+
}
|
|
767
|
+
},
|
|
768
|
+
|
|
769
|
+
sweep(): void {
|
|
770
|
+
try {
|
|
771
|
+
dropIfOff();
|
|
772
|
+
const t = safeNow(now);
|
|
773
|
+
sweepDispatches(t);
|
|
774
|
+
// Only what belongs to this instance's own directory: another instance (or another directory) owns the rest
|
|
775
|
+
// (QA-2.1-R2-1).
|
|
776
|
+
const dir = currentDir();
|
|
777
|
+
if (dir !== null) {
|
|
778
|
+
// A child that was swept away can no longer end its attempt: fold it.
|
|
779
|
+
for (const [mapKey, last] of [...lastAttemptByChild]) {
|
|
780
|
+
if (last.dir !== dir) continue;
|
|
781
|
+
const child = mapKey.slice(last.dir.length + 1);
|
|
782
|
+
if (lookupDispatch(child) !== undefined) continue;
|
|
783
|
+
lastAttemptByChild.delete(mapKey);
|
|
784
|
+
endAttempt(last.dir, last.attempt);
|
|
785
|
+
}
|
|
786
|
+
for (const pending of [...heldFinals.values()]) {
|
|
787
|
+
if (pending.dir === dir && t - pending.at >= HELD_FINAL_IDLE_MS) settle(pending.dir, pending.attempt, true);
|
|
788
|
+
}
|
|
789
|
+
}
|
|
790
|
+
// Keys of held steps that someone else settled (QA-2.1-R2-8).
|
|
791
|
+
for (const heldKey of [...ownedHeld]) if (!heldFinals.has(heldKey)) ownedHeld.delete(heldKey);
|
|
792
|
+
held?.bundle.store.sweepAttempts();
|
|
793
|
+
} catch (error) {
|
|
794
|
+
warn("sweep failed", error);
|
|
795
|
+
}
|
|
796
|
+
},
|
|
797
|
+
|
|
798
|
+
async dispose(): Promise<void> {
|
|
799
|
+
if (disposed) return;
|
|
800
|
+
disposed = true;
|
|
801
|
+
settleOwned();
|
|
802
|
+
const current = held;
|
|
803
|
+
held = null;
|
|
804
|
+
if (current === null) return;
|
|
805
|
+
try {
|
|
806
|
+
await current.bundle.release();
|
|
807
|
+
} catch (error) {
|
|
808
|
+
warn("release failed", error);
|
|
809
|
+
}
|
|
810
|
+
},
|
|
811
|
+
};
|
|
812
|
+
}
|