opencode-model-router 2.7.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 +583 -0
- package/README.md +20 -0
- package/package.json +5 -1
- package/src/commands/approvals.ts +354 -0
- package/src/commands/output.ts +34 -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 +2853 -109
- 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 +1789 -288
- package/src/router/config.ts +823 -26
- package/src/router/dispatch-header.ts +95 -2
- package/src/router/git-tools.ts +266 -19
- package/src/router/leases.ts +1469 -0
- package/src/router/logger.ts +44 -32
- package/src/router/protocol.ts +44 -10
- package/src/router/role-agents.ts +334 -20
- package/src/router/roles-config.ts +93 -1
- package/src/router/roles.ts +1 -1
- package/src/router/run-tools.ts +56 -4
- package/src/router/sessions.ts +11 -0
- 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/route-line.ts +96 -5
- package/src/routing/classify/rules.ts +11 -0
- package/src/routing/classify/types.ts +26 -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/signals.ts +17 -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/admission.ts +1028 -0
- package/src/routing/roles/approvals.ts +957 -0
- package/src/routing/roles/binding.ts +116 -13
- package/src/routing/roles/check-placement.ts +112 -0
- package/src/routing/roles/git-root.ts +500 -0
- package/src/routing/roles/orphans.ts +68 -0
- package/src/routing/roles/policy.ts +30 -3
- package/src/routing/roles/read-set.ts +325 -0
- package/src/routing/roles/work-root.ts +12 -2
- package/src/routing/wire/dispatch.ts +697 -30
- package/src/routing/wire/hint.ts +56 -8
- package/src/routing/wire/working-set.ts +58 -0
- package/src/util/linear-trim.ts +32 -0
- package/src/v2.ts +94 -49
- package/src/verify/batch.ts +7 -2
- package/src/verify/branch.ts +141 -0
- package/src/verify/canonical-path.ts +35 -0
- package/src/verify/deterministic.ts +268 -17
- package/src/verify/dispatch.ts +348 -37
- package/src/verify/dod.ts +46 -0
- package/src/verify/edges.ts +817 -0
- package/src/verify/exec.ts +52 -9
- package/src/verify/gate.ts +349 -16
- package/src/verify/git-top.ts +43 -0
- package/src/verify/head.ts +107 -0
- package/src/verify/pending.ts +1846 -18
- package/src/verify/perimeter.ts +1186 -0
- package/src/verify/pin.ts +109 -0
- package/src/verify/plan-task.ts +729 -0
- package/src/verify/reference.ts +297 -8
- package/src/verify/risk.ts +16 -3
- package/src/verify/runner.ts +706 -32
- package/src/verify/tree.ts +372 -16
- package/src/verify/types.ts +66 -2
- package/src/verify/wiring.ts +1594 -46
|
@@ -19,6 +19,7 @@ import {
|
|
|
19
19
|
SCOPES,
|
|
20
20
|
TASK_CLASSES,
|
|
21
21
|
type Detection,
|
|
22
|
+
type InvalidCrossRepo,
|
|
22
23
|
type Need,
|
|
23
24
|
type Risk,
|
|
24
25
|
type RouteLine,
|
|
@@ -61,6 +62,28 @@ function isWorkRootPath(value: string): boolean {
|
|
|
61
62
|
return WORK_ROOT_RE.test(value) && !PARENT_SEGMENT_RE.test(value) && !value.includes("\0");
|
|
62
63
|
}
|
|
63
64
|
|
|
65
|
+
const REPO_NAME_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/;
|
|
66
|
+
/** Never in a git branch name (`git check-ref-format`): ASCII control, DEL, space, `~ ^ : ? * [ \`. */
|
|
67
|
+
const BRANCH_FORBIDDEN_RE = /[\u0000-\u001f\u007f ~^:?*[\\]/;
|
|
68
|
+
const BRANCH_MAX_CHARS = 200;
|
|
69
|
+
|
|
70
|
+
/** `repo=` value: a single directory name (no separators), not `.` / `..`. Case is kept. */
|
|
71
|
+
function isRepoName(value: string): boolean {
|
|
72
|
+
return REPO_NAME_RE.test(value) && value !== "." && value !== "..";
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* `branch=` value: a name `git check-ref-format --branch` accepts (QA round 1, F3). Case is kept; declare-then-check happens
|
|
77
|
+
* later. The value is only compared with `git worktree list --porcelain` output, never passed to git as an argument.
|
|
78
|
+
*/
|
|
79
|
+
function isBranchRef(value: string): boolean {
|
|
80
|
+
if (value.length < 1 || value.length > BRANCH_MAX_CHARS) return false;
|
|
81
|
+
if (BRANCH_FORBIDDEN_RE.test(value)) return false;
|
|
82
|
+
if (value === "@" || value.includes("@{") || value.includes("..") || value.includes("//")) return false;
|
|
83
|
+
if (value.startsWith("-") || value.startsWith("/") || value.endsWith("/") || value.endsWith(".")) return false;
|
|
84
|
+
return value.split("/").every((component) => !component.startsWith(".") && !component.endsWith(".lock"));
|
|
85
|
+
}
|
|
86
|
+
|
|
64
87
|
function isMember<T extends string>(values: readonly T[], value: string): value is T {
|
|
65
88
|
return (values as readonly string[]).includes(value);
|
|
66
89
|
}
|
|
@@ -87,6 +110,13 @@ function parseNeeds(value: string): readonly Need[] | undefined {
|
|
|
87
110
|
return NEEDS.filter((need) => found.has(need));
|
|
88
111
|
}
|
|
89
112
|
|
|
113
|
+
/** The `root=` value as written: a quoted path from `quotedRoots`, else the token's value; undefined for a bare `root`. */
|
|
114
|
+
function rootCandidate(rawValue: string | null, quotedRoots: readonly string[]): string | undefined {
|
|
115
|
+
if (rawValue === null) return undefined;
|
|
116
|
+
const q = QUOTED_PLACEHOLDER_RE.exec(stripTail(rawValue.toLowerCase()));
|
|
117
|
+
return q ? quotedRoots[Number(q[1])] : stripTail(rawValue);
|
|
118
|
+
}
|
|
119
|
+
|
|
90
120
|
/** L2: the fields of one route line body. */
|
|
91
121
|
function parseFields(body: string): RouteLine {
|
|
92
122
|
let taskClass: TaskClass | undefined;
|
|
@@ -98,7 +128,10 @@ function parseFields(body: string): RouteLine {
|
|
|
98
128
|
let tier: string | undefined;
|
|
99
129
|
let budget: number | undefined;
|
|
100
130
|
let root: string | undefined;
|
|
131
|
+
let repo: string | undefined;
|
|
132
|
+
let branch: string | undefined;
|
|
101
133
|
const ignored: string[] = [];
|
|
134
|
+
const invalidCrossRepo: InvalidCrossRepo[] = [];
|
|
102
135
|
const seen = new Set<string>();
|
|
103
136
|
|
|
104
137
|
const quotedRoots: string[] = [];
|
|
@@ -119,6 +152,8 @@ function parseFields(body: string): RouteLine {
|
|
|
119
152
|
}
|
|
120
153
|
if (seen.has(key)) {
|
|
121
154
|
ignored.push(`dup:${key}`);
|
|
155
|
+
if (key === "repo" || key === "branch") invalidCrossRepo.push({ key, value: rawValue === null ? "" : stripTail(rawValue) });
|
|
156
|
+
else if (key === "root") invalidCrossRepo.push({ key, value: rootCandidate(rawValue, quotedRoots) ?? "" });
|
|
122
157
|
continue;
|
|
123
158
|
}
|
|
124
159
|
seen.add(key);
|
|
@@ -162,10 +197,31 @@ function parseFields(body: string): RouteLine {
|
|
|
162
197
|
break;
|
|
163
198
|
}
|
|
164
199
|
case "root": {
|
|
165
|
-
const
|
|
166
|
-
const candidate = q ? quotedRoots[Number(q[1])] : rawValue === null ? undefined : stripTail(rawValue);
|
|
200
|
+
const candidate = rootCandidate(rawValue, quotedRoots);
|
|
167
201
|
if (candidate !== undefined && isWorkRootPath(candidate)) root = candidate;
|
|
168
|
-
else
|
|
202
|
+
else {
|
|
203
|
+
// A declared work root that cannot be accepted is an invalid declaration, never "nothing declared".
|
|
204
|
+
ignored.push(key);
|
|
205
|
+
invalidCrossRepo.push({ key, value: candidate ?? "" });
|
|
206
|
+
}
|
|
207
|
+
break;
|
|
208
|
+
}
|
|
209
|
+
case "repo": {
|
|
210
|
+
const candidate = rawValue === null ? undefined : stripTail(rawValue);
|
|
211
|
+
if (candidate !== undefined && isRepoName(candidate)) repo = candidate;
|
|
212
|
+
else {
|
|
213
|
+
ignored.push(key);
|
|
214
|
+
invalidCrossRepo.push({ key, value: candidate ?? "" });
|
|
215
|
+
}
|
|
216
|
+
break;
|
|
217
|
+
}
|
|
218
|
+
case "branch": {
|
|
219
|
+
const candidate = rawValue === null ? undefined : stripTail(rawValue);
|
|
220
|
+
if (candidate !== undefined && isBranchRef(candidate)) branch = candidate;
|
|
221
|
+
else {
|
|
222
|
+
ignored.push(key);
|
|
223
|
+
invalidCrossRepo.push({ key, value: candidate ?? "" });
|
|
224
|
+
}
|
|
169
225
|
break;
|
|
170
226
|
}
|
|
171
227
|
default:
|
|
@@ -182,6 +238,9 @@ function parseFields(body: string): RouteLine {
|
|
|
182
238
|
...(tier ? { tier } : {}),
|
|
183
239
|
...(budget !== undefined ? { budget } : {}),
|
|
184
240
|
...(root ? { root } : {}),
|
|
241
|
+
...(repo ? { repo } : {}),
|
|
242
|
+
...(branch ? { branch } : {}),
|
|
243
|
+
...(invalidCrossRepo.length > 0 ? { invalidCrossRepo } : {}),
|
|
185
244
|
pin,
|
|
186
245
|
ignored,
|
|
187
246
|
};
|
|
@@ -207,7 +266,25 @@ function isRecognisable(line: string, inFence: boolean): boolean {
|
|
|
207
266
|
}
|
|
208
267
|
|
|
209
268
|
function canonical(line: RouteLine): string {
|
|
210
|
-
|
|
269
|
+
// Invalid `root=` entries are not compared: a tier dispatch's conflict detection stays what it was before they were
|
|
270
|
+
// recorded (an invalid root was only an `ignored` key). They are merged into the effective line instead (mergeInvalidRoots).
|
|
271
|
+
const invalid = line.invalidCrossRepo?.filter((entry) => entry.key !== "root");
|
|
272
|
+
return JSON.stringify([line.class, line.risk, line.scope, line.needs, line.detection, line.pin, line.tier, line.budget, line.root, line.repo, line.branch, invalid !== undefined && invalid.length > 0 ? invalid : undefined]);
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/**
|
|
276
|
+
* Several route lines that agree on every compared field: the first line, with the invalid `root=` declarations of
|
|
277
|
+
* every line (a declared-but-invalid work root on any line is never silently dropped).
|
|
278
|
+
*/
|
|
279
|
+
function mergeInvalidRoots(lines: readonly RouteLine[]): RouteLine {
|
|
280
|
+
const first = lines[0]!;
|
|
281
|
+
const merged: InvalidCrossRepo[] = [...(first.invalidCrossRepo ?? [])];
|
|
282
|
+
for (const l of lines.slice(1)) {
|
|
283
|
+
for (const entry of l.invalidCrossRepo ?? []) {
|
|
284
|
+
if (!merged.some((seenEntry) => seenEntry.key === entry.key && seenEntry.value === entry.value)) merged.push(entry);
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
return merged.length === (first.invalidCrossRepo?.length ?? 0) ? first : { ...first, invalidCrossRepo: merged };
|
|
211
288
|
}
|
|
212
289
|
|
|
213
290
|
/**
|
|
@@ -242,7 +319,18 @@ function resolveConflict(lines: readonly RouteLine[]): RouteLine {
|
|
|
242
319
|
const tier = keep("tier", first.tier, (l) => l.tier);
|
|
243
320
|
const budget = keep("budget", first.budget, (l) => l.budget);
|
|
244
321
|
const root = keep("root", first.root, (l) => l.root);
|
|
322
|
+
const repo = keep("repo", first.repo, (l) => l.repo);
|
|
323
|
+
const branch = keep("branch", first.branch, (l) => l.branch);
|
|
245
324
|
if (lines.some((l) => l.detection !== undefined)) ignored.push("conflict:d");
|
|
325
|
+
// QA round 1 (F3): a declaration that no line can carry is declared-but-invalid, never a silent fallback to the session directory.
|
|
326
|
+
const invalidCrossRepo: InvalidCrossRepo[] = [];
|
|
327
|
+
const mark = (entry: InvalidCrossRepo): void => {
|
|
328
|
+
if (!invalidCrossRepo.some((seenEntry) => seenEntry.key === entry.key && seenEntry.value === entry.value)) invalidCrossRepo.push(entry);
|
|
329
|
+
};
|
|
330
|
+
for (const l of lines) for (const entry of l.invalidCrossRepo ?? []) mark(entry);
|
|
331
|
+
if (first.repo !== undefined && repo === undefined) mark({ key: "repo", value: first.repo });
|
|
332
|
+
if (first.branch !== undefined && branch === undefined) mark({ key: "branch", value: first.branch });
|
|
333
|
+
if (first.root !== undefined && root === undefined) mark({ key: "root", value: first.root });
|
|
246
334
|
return {
|
|
247
335
|
...(taskClass ? { class: taskClass } : {}),
|
|
248
336
|
...(risk ? { risk } : {}),
|
|
@@ -251,6 +339,9 @@ function resolveConflict(lines: readonly RouteLine[]): RouteLine {
|
|
|
251
339
|
...(tier ? { tier } : {}),
|
|
252
340
|
...(budget !== undefined ? { budget } : {}),
|
|
253
341
|
...(root ? { root } : {}),
|
|
342
|
+
...(repo ? { repo } : {}),
|
|
343
|
+
...(branch ? { branch } : {}),
|
|
344
|
+
...(invalidCrossRepo.length > 0 ? { invalidCrossRepo } : {}),
|
|
254
345
|
// The first line is the directive; a later line cannot take its pin away or add one (A22).
|
|
255
346
|
pin: first.pin,
|
|
256
347
|
ignored,
|
|
@@ -326,7 +417,7 @@ export function parseRouteLine(text: string, options: RouteLineOptions = {}): Ro
|
|
|
326
417
|
const conflict = new Set(parsed.map(canonical)).size > 1;
|
|
327
418
|
return {
|
|
328
419
|
// QA-P12-2-2: the flag lives on the parse result only; the line's `ignored` list is the tier-mode one.
|
|
329
|
-
line: conflict ? resolveConflict(parsed) : parsed
|
|
420
|
+
line: conflict ? resolveConflict(parsed) : mergeInvalidRoots(parsed),
|
|
330
421
|
count: parsed.length,
|
|
331
422
|
stripped: kept.join(""),
|
|
332
423
|
conflict,
|
|
@@ -665,3 +665,14 @@ export function analyzeRules(
|
|
|
665
665
|
export function classifyByRules(text: string, cfg: RulesConfig, ctx?: { cwd?: string }): TaskFacts {
|
|
666
666
|
return analyzeRules(text, cfg, ctx).facts;
|
|
667
667
|
}
|
|
668
|
+
|
|
669
|
+
/** Observability only: the first high-risk hit under R11's exact section/negation rules, without surrounding task text. */
|
|
670
|
+
export function highRiskTermOf(text: string): string | undefined {
|
|
671
|
+
const raw = collapseLongRuns(String(text ?? "").slice(0, RULES_MAX_CHARS));
|
|
672
|
+
const { riskText, prohibitionText } = splitSections(prepareBody(raw));
|
|
673
|
+
const hit = firstHit(HIGH_RISK_RES, riskText, false) ?? firstHit(HIGH_RISK_RES, prohibitionText, true);
|
|
674
|
+
if (hit === null) return undefined;
|
|
675
|
+
const word = hit.text.toLowerCase();
|
|
676
|
+
// Multiword/command regexes can span arbitrary arguments, and credential names can be private: log only a table id for those.
|
|
677
|
+
return /^[a-z-]{1,40}$/.test(word) ? word : `term-${hit.index}`;
|
|
678
|
+
}
|
|
@@ -273,6 +273,13 @@ export type FetchLike = (
|
|
|
273
273
|
/** Environment lookup (process.env in production, a plain object in tests). */
|
|
274
274
|
export type EnvLike = Readonly<Record<string, string | undefined>>;
|
|
275
275
|
|
|
276
|
+
/** A `repo=` / `branch=` / `root=` declaration of a route line that was not accepted (see {@link RouteLine.invalidCrossRepo}). */
|
|
277
|
+
export interface InvalidCrossRepo {
|
|
278
|
+
readonly key: "repo" | "branch" | "root";
|
|
279
|
+
/** The value as written (empty for a bare key). */
|
|
280
|
+
readonly value: string;
|
|
281
|
+
}
|
|
282
|
+
|
|
276
283
|
/** Parsed `[route …]` line (D13). Absent fields were missing or invalid. */
|
|
277
284
|
export interface RouteLine {
|
|
278
285
|
readonly class?: TaskClass;
|
|
@@ -297,6 +304,25 @@ export interface RouteLine {
|
|
|
297
304
|
* `git worktree list --porcelain` BEFORE any filesystem call on it; no match → no work root.
|
|
298
305
|
*/
|
|
299
306
|
readonly root?: string;
|
|
307
|
+
/**
|
|
308
|
+
* `repo=<name>`: cross-repo (Phase 1): a repository name below `routing.repoParents`, as written (case kept).
|
|
309
|
+
* One directory name, `[A-Za-z0-9][A-Za-z0-9._-]{0,99}`, not `.` / `..`; separators are rejected at parse.
|
|
310
|
+
* Parse and validation only: resolution against `routing.repoParents` happens later.
|
|
311
|
+
*/
|
|
312
|
+
readonly repo?: string;
|
|
313
|
+
/**
|
|
314
|
+
* `branch=<ref>`: the branch whose worktree to bind; declare-then-check (the declared branch is verified against
|
|
315
|
+
* the worktree later). Case kept. 1..200 chars, git `check-ref-format` rules for a branch name: no ASCII control,
|
|
316
|
+
* space, `~ ^ : ? * [ \`; rejected at parse: `..`, `@{`, `@` alone, `//`, a leading `-` or `/`, a trailing `/` or
|
|
317
|
+
* `.`, a component starting with `.` or ending in `.lock`. The value is only ever compared with porcelain output.
|
|
318
|
+
*/
|
|
319
|
+
readonly branch?: string;
|
|
320
|
+
/**
|
|
321
|
+
* `repo=` / `branch=` / `root=` the line declared but the parser could not accept (invalid value, bare key, duplicate or
|
|
322
|
+
* conflicting key), with the value as written (a quoted `root=` without its quotes). The route flow gives such a dispatch NO work root and a note: an
|
|
323
|
+
* invalid declaration never falls back to the session directory. Absent when every declaration was valid.
|
|
324
|
+
*/
|
|
325
|
+
readonly invalidCrossRepo?: readonly InvalidCrossRepo[];
|
|
300
326
|
/** Bare `pin` flag (or `pin=true|yes|1`). */
|
|
301
327
|
readonly pin: boolean;
|
|
302
328
|
/** Keys that were unknown or whose values were invalid (for logging only). */
|
|
@@ -20,7 +20,7 @@ import { homedir, tmpdir } from "node:os";
|
|
|
20
20
|
import { dirname, join } from "node:path";
|
|
21
21
|
import { fileURLToPath } from "node:url";
|
|
22
22
|
import { resolveRouting, type RouterConfig } from "../../router/config";
|
|
23
|
-
import { acquireOutcomes, createPersister, nodePersistDeps, resolveOutcomesDir, runStatsCli } from "../outcomes";
|
|
23
|
+
import { acquireOutcomes, createPersister, createSideLogs, nodePersistDeps, resolveOutcomesDir, runStatsCli } from "../outcomes";
|
|
24
24
|
import { ingestSettings } from "../outcomes/ingest";
|
|
25
25
|
import type { OutcomesBundle } from "../outcomes";
|
|
26
26
|
|
|
@@ -85,7 +85,7 @@ export async function runStatsCommand(args: string, deps: StatsCommandDeps): Pro
|
|
|
85
85
|
stderr: (text) => {
|
|
86
86
|
stderr += text;
|
|
87
87
|
},
|
|
88
|
-
});
|
|
88
|
+
}, deps.host === "v2" ? { open: (dir) => createSideLogs(dir, persistDeps) } : undefined); // 1.1.4: the side-log sections are v2 only
|
|
89
89
|
return { stdout, stderr, exit };
|
|
90
90
|
} catch (error) {
|
|
91
91
|
deps.logger.warn("[router] /router stats failed", { error: describeError(error) });
|
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
// ---------------------------------------------------------------------------
|
|
2
|
+
// Dispatch duration estimator (Phase 1.1, task 1.1.3).
|
|
3
|
+
//
|
|
4
|
+
// Estimates how long a child dispatch of (role, class, scope) takes, from the rows of `timings.jsonl`
|
|
5
|
+
// (`DispatchTimingRow`). Pure module: no I/O of its own, the rows come through the injected `readTimings` seam
|
|
6
|
+
// and the clock through `now`. Like every module under src/routing/outcomes/ it must stay runnable under Node's
|
|
7
|
+
// type stripping: type imports use `import type`, the one value import is MAX_FUTURE_SKEW_MS from ./timings; no enum,
|
|
8
|
+
// namespace or parameter property.
|
|
9
|
+
//
|
|
10
|
+
// Rules:
|
|
11
|
+
// - fallback: exact (role, class, scope) -> (role, class) -> role -> prior. A level answers p50 only with at least
|
|
12
|
+
// `minSamples` samples; otherwise the next, coarser level is tried. p90 needs at least `p90MinSamples` (10): it
|
|
13
|
+
// comes from the finest level, from the p50 level on, that has them, else from the prior (never below p50);
|
|
14
|
+
// - rows that ended more than `MAX_FUTURE_SKEW_MS` (timings.ts, one day) after `now()` are dropped by `observe` and
|
|
15
|
+
// `load`, never kept in a window (a clock jump wrote them; QA-1.1-21);
|
|
16
|
+
// - only rows with `outcome: "succeeded"` count, and rows whose `capacity` is not null are excluded (ADR 0007 D6:
|
|
17
|
+
// a provider capacity condition says nothing about how long the work takes);
|
|
18
|
+
// - p50 / p90 are nearest-rank percentiles (rank = ceil(p * n), 1-based) over the newest `window` rows of the key
|
|
19
|
+
// whose `endedAt` is within `maxAgeDays` of `now()`;
|
|
20
|
+
// - the prior answers p50 = p90 = `priorMs`, n = 0, source "prior";
|
|
21
|
+
// - memory is bounded: at most `window` newest rows are kept per key and level.
|
|
22
|
+
//
|
|
23
|
+
// Loading: `estimate` is synchronous. Call `await load()` once (idempotent; concurrent callers share one read) to
|
|
24
|
+
// fold the persisted rows in; until it resolves, `estimate` sees only the rows given to `observe`. `observe(row)`
|
|
25
|
+
// folds a live row in at any time. A row seen twice (from the file and from `observe`) counts once.
|
|
26
|
+
// ---------------------------------------------------------------------------
|
|
27
|
+
|
|
28
|
+
import { MAX_FUTURE_SKEW_MS } from "./timings";
|
|
29
|
+
import type { DispatchTimingRow } from "./types";
|
|
30
|
+
|
|
31
|
+
export const DURATION_WINDOW = 50;
|
|
32
|
+
export const DURATION_MAX_AGE_DAYS = 30;
|
|
33
|
+
export const DURATION_PRIOR_MS = 480_000;
|
|
34
|
+
export const DURATION_MIN_SAMPLES = 5;
|
|
35
|
+
/** Samples a level needs before its p90 is reported (QA-1.1-10). */
|
|
36
|
+
export const DURATION_P90_MIN_SAMPLES = 10;
|
|
37
|
+
|
|
38
|
+
const DAY_MS = 24 * 60 * 60 * 1000;
|
|
39
|
+
const SEP = "\u0000";
|
|
40
|
+
|
|
41
|
+
export type DurationSource = "exact" | "role-class" | "role" | "prior";
|
|
42
|
+
|
|
43
|
+
export interface DurationEstimate {
|
|
44
|
+
readonly p50: number;
|
|
45
|
+
readonly p90: number;
|
|
46
|
+
/** Samples behind the p50 (0 for the prior). */
|
|
47
|
+
readonly n: number;
|
|
48
|
+
/** Level the p50 came from. */
|
|
49
|
+
readonly source: DurationSource;
|
|
50
|
+
/** Level the p90 came from (QA-1.1-22): the finest level from the p50 level on with enough samples, else `"prior"`. */
|
|
51
|
+
readonly p90Source: DurationSource;
|
|
52
|
+
/** Samples behind the p90 (0 when it is the prior). `source`/`n` describe the p50 only. */
|
|
53
|
+
readonly p90N: number;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export interface DurationQuery {
|
|
57
|
+
readonly role: string;
|
|
58
|
+
readonly class: string;
|
|
59
|
+
readonly scope: string;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export interface DurationSeams {
|
|
63
|
+
/** The persisted dispatch-timing rows (any order). Called once by `load()`. */
|
|
64
|
+
readonly readTimings: () => Promise<readonly DispatchTimingRow[]> | readonly DispatchTimingRow[];
|
|
65
|
+
/** Epoch milliseconds. */
|
|
66
|
+
readonly now: () => number;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export interface DurationOptions {
|
|
70
|
+
/** Newest rows kept and used per key (default 50). */
|
|
71
|
+
readonly window?: number;
|
|
72
|
+
/** Rows ended longer ago than this are ignored (default 30). */
|
|
73
|
+
readonly maxAgeDays?: number;
|
|
74
|
+
/** p50 = p90 of the prior, in milliseconds (default 480000). */
|
|
75
|
+
readonly priorMs?: number;
|
|
76
|
+
/** Samples a level needs to answer p50 (default 5). */
|
|
77
|
+
readonly minSamples?: number;
|
|
78
|
+
/** Samples a level needs to answer p90 (default 10); a thinner level hands p90 to a coarser one, else to the prior. */
|
|
79
|
+
readonly p90MinSamples?: number;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export interface DurationModel {
|
|
83
|
+
/** Synchronous. Uses the rows loaded and observed so far. */
|
|
84
|
+
estimate(query: DurationQuery): DurationEstimate;
|
|
85
|
+
/** Folds one live row in. Rows that do not count (not succeeded, capacity, malformed numbers) are ignored. */
|
|
86
|
+
observe(row: DispatchTimingRow): void;
|
|
87
|
+
/** Reads `readTimings` once and folds its rows in. Idempotent; never rejects (a failed read leaves the model on the prior). */
|
|
88
|
+
load(): Promise<void>;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
interface Sample {
|
|
92
|
+
readonly endedAt: number;
|
|
93
|
+
readonly durationMs: number;
|
|
94
|
+
readonly id: string;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
interface Bucket {
|
|
98
|
+
/** Ascending by endedAt, at most `window` long. */
|
|
99
|
+
readonly list: Sample[];
|
|
100
|
+
/** Ids of `list`. */
|
|
101
|
+
readonly ids: Set<string>;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function positiveInt(value: number | undefined, fallback: number): number {
|
|
105
|
+
return value !== undefined && Number.isFinite(value) && value >= 1 ? Math.floor(value) : fallback;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function positiveNumber(value: number | undefined, fallback: number): number {
|
|
109
|
+
return value !== undefined && Number.isFinite(value) && value > 0 ? value : fallback;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** Nearest rank on an ascending-sorted, non-empty list. */
|
|
113
|
+
function nearestRank(sorted: readonly number[], p: number): number {
|
|
114
|
+
const rank = Math.min(sorted.length, Math.max(1, Math.ceil(p * sorted.length)));
|
|
115
|
+
return sorted[rank - 1] as number;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
export function createDurationModel(seams: DurationSeams, opts: DurationOptions = {}): DurationModel {
|
|
119
|
+
const window = positiveInt(opts.window, DURATION_WINDOW);
|
|
120
|
+
const maxAgeMs = positiveNumber(opts.maxAgeDays, DURATION_MAX_AGE_DAYS) * DAY_MS;
|
|
121
|
+
const priorMs = opts.priorMs !== undefined && Number.isFinite(opts.priorMs) && opts.priorMs >= 0 ? opts.priorMs : DURATION_PRIOR_MS;
|
|
122
|
+
const minSamples = positiveInt(opts.minSamples, DURATION_MIN_SAMPLES);
|
|
123
|
+
|
|
124
|
+
const p90MinSamples = positiveInt(opts.p90MinSamples, DURATION_P90_MIN_SAMPLES);
|
|
125
|
+
|
|
126
|
+
// One map per level; each bucket holds the newest `window` samples of its key, ascending by endedAt, and the set of
|
|
127
|
+
// their row ids (QA-1.1-11: the dedupe is a set lookup, not a scan of the list).
|
|
128
|
+
const exact = new Map<string, Bucket>();
|
|
129
|
+
const roleClass = new Map<string, Bucket>();
|
|
130
|
+
const role = new Map<string, Bucket>();
|
|
131
|
+
let loading: Promise<void> | null = null;
|
|
132
|
+
|
|
133
|
+
function insert(level: Map<string, Bucket>, key: string, sample: Sample): void {
|
|
134
|
+
let bucket = level.get(key);
|
|
135
|
+
if (bucket === undefined) {
|
|
136
|
+
bucket = { list: [], ids: new Set() };
|
|
137
|
+
level.set(key, bucket);
|
|
138
|
+
}
|
|
139
|
+
if (bucket.ids.has(sample.id)) return;
|
|
140
|
+
const { list } = bucket;
|
|
141
|
+
let at = list.length;
|
|
142
|
+
while (at > 0 && (list[at - 1] as Sample).endedAt > sample.endedAt) at -= 1;
|
|
143
|
+
list.splice(at, 0, sample);
|
|
144
|
+
bucket.ids.add(sample.id);
|
|
145
|
+
if (list.length > window) {
|
|
146
|
+
for (const dropped of list.splice(0, list.length - window)) bucket.ids.delete(dropped.id);
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
function observe(row: DispatchTimingRow): void {
|
|
151
|
+
if (row.outcome !== "succeeded" || row.capacity !== null) return;
|
|
152
|
+
if (!Number.isFinite(row.endedAt) || !Number.isFinite(row.durationMs) || row.durationMs < 0) return;
|
|
153
|
+
// QA-1.1-21: a row from the future (a clock jump wrote it) is dropped, not kept in the window where it would displace real samples.
|
|
154
|
+
const t = seams.now();
|
|
155
|
+
if (row.endedAt > (Number.isFinite(t) ? t : Date.now()) + MAX_FUTURE_SKEW_MS) return;
|
|
156
|
+
const sample: Sample = {
|
|
157
|
+
endedAt: row.endedAt,
|
|
158
|
+
durationMs: row.durationMs,
|
|
159
|
+
id: `${row.childSessionID}${SEP}${row.callID}${SEP}${row.endedAt}`,
|
|
160
|
+
};
|
|
161
|
+
insert(exact, `${row.role}${SEP}${row.class}${SEP}${row.scope}`, sample);
|
|
162
|
+
insert(roleClass, `${row.role}${SEP}${row.class}`, sample);
|
|
163
|
+
insert(role, row.role, sample);
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* Durations (ascending) of the key's samples within the age limit and not from the future (QA-1.1-9: a row that ended more
|
|
168
|
+
* than a day after `now` carries a bad clock). Empty when there are none.
|
|
169
|
+
*/
|
|
170
|
+
function durationsOf(level: Map<string, Bucket>, key: string, cutoff: number, ceiling: number): number[] {
|
|
171
|
+
const bucket = level.get(key);
|
|
172
|
+
if (bucket === undefined) return [];
|
|
173
|
+
const durations: number[] = [];
|
|
174
|
+
for (const sample of bucket.list) if (sample.endedAt >= cutoff && sample.endedAt <= ceiling) durations.push(sample.durationMs);
|
|
175
|
+
return durations.sort((a, b) => a - b);
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* p50 comes from the finest level with at least `minSamples` samples. p90 (QA-1.1-10) comes from the finest level, starting
|
|
180
|
+
* at that one, with at least `p90MinSamples` (10) samples, else from the prior: a tail estimate needs a tail. p90 is never
|
|
181
|
+
* reported below p50.
|
|
182
|
+
*/
|
|
183
|
+
function estimate(query: DurationQuery): DurationEstimate {
|
|
184
|
+
const t = seams.now();
|
|
185
|
+
const now = Number.isFinite(t) ? t : Date.now();
|
|
186
|
+
const cutoff = now - maxAgeMs;
|
|
187
|
+
const ceiling = now + MAX_FUTURE_SKEW_MS;
|
|
188
|
+
const levels: Array<{ readonly source: DurationSource; readonly durations: number[] }> = [
|
|
189
|
+
{ source: "exact", durations: durationsOf(exact, `${query.role}${SEP}${query.class}${SEP}${query.scope}`, cutoff, ceiling) },
|
|
190
|
+
{ source: "role-class", durations: durationsOf(roleClass, `${query.role}${SEP}${query.class}`, cutoff, ceiling) },
|
|
191
|
+
{ source: "role", durations: durationsOf(role, query.role, cutoff, ceiling) },
|
|
192
|
+
];
|
|
193
|
+
const start = levels.findIndex((level) => level.durations.length >= minSamples);
|
|
194
|
+
if (start < 0) return { p50: priorMs, p90: priorMs, n: 0, source: "prior", p90Source: "prior", p90N: 0 };
|
|
195
|
+
const chosen = levels[start] as (typeof levels)[number];
|
|
196
|
+
const p50 = nearestRank(chosen.durations, 0.5);
|
|
197
|
+
const tail = levels.slice(start).find((level) => level.durations.length >= p90MinSamples);
|
|
198
|
+
const p90 = tail === undefined ? priorMs : nearestRank(tail.durations, 0.9);
|
|
199
|
+
return {
|
|
200
|
+
p50,
|
|
201
|
+
p90: Math.max(p90, p50),
|
|
202
|
+
n: chosen.durations.length,
|
|
203
|
+
source: chosen.source,
|
|
204
|
+
p90Source: tail === undefined ? "prior" : tail.source,
|
|
205
|
+
p90N: tail === undefined ? 0 : tail.durations.length,
|
|
206
|
+
};
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
function load(): Promise<void> {
|
|
210
|
+
if (loading === null) {
|
|
211
|
+
loading = (async () => {
|
|
212
|
+
try {
|
|
213
|
+
const rows = await seams.readTimings();
|
|
214
|
+
for (const row of rows) observe(row);
|
|
215
|
+
} catch {
|
|
216
|
+
// A failed read leaves the model on what `observe` supplied (and the prior): estimating must never throw.
|
|
217
|
+
return;
|
|
218
|
+
}
|
|
219
|
+
})();
|
|
220
|
+
}
|
|
221
|
+
return loading;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
return { estimate, observe, load };
|
|
225
|
+
}
|
|
@@ -60,16 +60,73 @@ export {
|
|
|
60
60
|
compactStamp,
|
|
61
61
|
createFlusher,
|
|
62
62
|
createPersister,
|
|
63
|
+
createSideLogs,
|
|
64
|
+
durationSeamsFor,
|
|
65
|
+
isSideLogLabel,
|
|
63
66
|
nodePersistDeps,
|
|
64
67
|
nodePersistFs,
|
|
65
68
|
nodeScheduler,
|
|
66
69
|
parseLogLine,
|
|
70
|
+
parseTimingLine,
|
|
71
|
+
parseTurnLine,
|
|
67
72
|
renameWithRetry,
|
|
68
73
|
resolveOutcomesDir,
|
|
69
74
|
} from "./persist";
|
|
75
|
+
export type { SideLogOptions } from "./persist";
|
|
76
|
+
export {
|
|
77
|
+
DEFAULT_TURN_IDLE_MS,
|
|
78
|
+
MAX_FUTURE_SKEW_MS,
|
|
79
|
+
MAX_OPEN_STARTS,
|
|
80
|
+
MAX_ROOT_SESSIONS,
|
|
81
|
+
MAX_SEEN_EVENT_IDS,
|
|
82
|
+
MAX_UNBOUND_OUTCOMES,
|
|
83
|
+
OPEN_START_TTL_MS,
|
|
84
|
+
UNBOUND_OUTCOME_TTL_MS,
|
|
85
|
+
acquireTimingRecorder,
|
|
86
|
+
classifyCapacity,
|
|
87
|
+
createTimingRecorder,
|
|
88
|
+
} from "./timings";
|
|
89
|
+
export type {
|
|
90
|
+
AcquireTimingRecorderOptions,
|
|
91
|
+
DispatchStartInput,
|
|
92
|
+
RootStepTokens,
|
|
93
|
+
TimingLogger,
|
|
94
|
+
TimingRecorder,
|
|
95
|
+
TimingRecorderHolder,
|
|
96
|
+
TimingRecorderOptions,
|
|
97
|
+
} from "./timings";
|
|
98
|
+
export {
|
|
99
|
+
DURATION_MAX_AGE_DAYS,
|
|
100
|
+
DURATION_MIN_SAMPLES,
|
|
101
|
+
DURATION_P90_MIN_SAMPLES,
|
|
102
|
+
DURATION_PRIOR_MS,
|
|
103
|
+
DURATION_WINDOW,
|
|
104
|
+
createDurationModel,
|
|
105
|
+
} from "./durations";
|
|
106
|
+
export type {
|
|
107
|
+
DurationEstimate,
|
|
108
|
+
DurationModel,
|
|
109
|
+
DurationOptions,
|
|
110
|
+
DurationQuery,
|
|
111
|
+
DurationSeams,
|
|
112
|
+
DurationSource,
|
|
113
|
+
} from "./durations";
|
|
70
114
|
|
|
71
|
-
export {
|
|
72
|
-
|
|
115
|
+
export {
|
|
116
|
+
USAGE,
|
|
117
|
+
hasRoleRows,
|
|
118
|
+
parseStatsArgs,
|
|
119
|
+
renderCacheShareMarkdown,
|
|
120
|
+
renderDurationsMarkdown,
|
|
121
|
+
renderMarkdown,
|
|
122
|
+
renderRoleMarkdown,
|
|
123
|
+
runStatsCli,
|
|
124
|
+
summarize,
|
|
125
|
+
summarizeCacheShare,
|
|
126
|
+
summarizeDurations,
|
|
127
|
+
summarizeRoles,
|
|
128
|
+
} from "./stats";
|
|
129
|
+
export type { CacheShareStats, DurationStatsRow, ParseStatsResult, StatsArgs, StatsSideLogs } from "./stats";
|
|
73
130
|
export {
|
|
74
131
|
REDISPATCH_MAX_EARLIER,
|
|
75
132
|
REDISPATCH_MIN_TOKENS,
|