@linxiraos/pi-stats 1.5.1 → 1.5.10
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 +22 -3
- package/THIRD-PARTY-NOTICES.txt +22 -11
- package/dist/client/favicon.ico +0 -0
- package/dist/client/index.css +1 -1
- package/dist/client/index.js +95 -94
- package/dist/types/aggregator.d.ts +5 -0
- package/dist/types/client/api.d.ts +7 -1
- package/dist/types/client/app/nav.d.ts +1 -1
- package/dist/types/client/data/formatters.d.ts +2 -2
- package/dist/types/client/data/range.d.ts +5 -4
- package/dist/types/client/data/series.d.ts +14 -2
- package/dist/types/client/i18n/messages/costs.d.ts +4 -4
- package/dist/types/client/i18n/messages/en.d.ts +86 -6
- package/dist/types/client/i18n/messages/gain.d.ts +2 -2
- package/dist/types/client/i18n/messages/nav.d.ts +2 -0
- package/dist/types/client/i18n/messages/tracking.d.ts +89 -0
- package/dist/types/client/i18n/messages/zh-CN.d.ts +1 -1
- package/dist/types/client/routes/TrackingRoute.d.ts +10 -0
- package/dist/types/client/routes/index.d.ts +1 -0
- package/dist/types/db.d.ts +20 -0
- package/dist/types/index.d.ts +1 -1
- package/dist/types/parser.d.ts +7 -1
- package/dist/types/rollup.d.ts +4 -0
- package/dist/types/shared-types.d.ts +88 -0
- package/dist/types/spotlight-aggregator.d.ts +24 -5
- package/dist/types/spotlight-ingest.d.ts +48 -9
- package/dist/types/spotlight-worker.d.ts +27 -0
- package/dist/types/trace.d.ts +7 -1
- package/dist/types/tracking.d.ts +29 -0
- package/dist/types/types.d.ts +5 -5
- package/package.json +4 -4
- package/src/aggregator.ts +16 -0
- package/src/client/App.tsx +3 -0
- package/src/client/api.ts +11 -0
- package/src/client/app/nav.ts +3 -0
- package/src/client/data/formatters.ts +7 -7
- package/src/client/data/range.ts +22 -9
- package/src/client/data/series.ts +33 -14
- package/src/client/favicon.ico +0 -0
- package/src/client/i18n/messages/costs.ts +4 -4
- package/src/client/i18n/messages/en.ts +2 -0
- package/src/client/i18n/messages/gain.ts +2 -2
- package/src/client/i18n/messages/nav.ts +2 -0
- package/src/client/i18n/messages/tracking.ts +91 -0
- package/src/client/i18n/messages/zh-CN.ts +2 -0
- package/src/client/routes/CostsRoute.tsx +4 -4
- package/src/client/routes/GainRoute.tsx +5 -4
- package/src/client/routes/ProvidersRoute.tsx +4 -4
- package/src/client/routes/TrackingRoute.tsx +262 -0
- package/src/client/routes/index.ts +1 -0
- package/src/client/routes/tracking.css +94 -0
- package/src/client/spotlight/Overhead.tsx +46 -1
- package/src/db.ts +105 -21
- package/src/gain-aggregator.ts +3 -6
- package/src/index.ts +5 -1
- package/src/parser.ts +75 -10
- package/src/rollup.ts +67 -14
- package/src/server.ts +57 -16
- package/src/shared-types.ts +98 -0
- package/src/spotlight-aggregator.ts +207 -45
- package/src/spotlight-ingest.ts +141 -37
- package/src/spotlight-measures.ts +117 -85
- package/src/spotlight-worker.ts +45 -0
- package/src/trace.ts +56 -20
- package/src/tracking.ts +394 -0
- package/src/types.ts +5 -5
|
@@ -14,6 +14,7 @@
|
|
|
14
14
|
|
|
15
15
|
import type { Database, Statement } from "bun:sqlite";
|
|
16
16
|
import * as path from "node:path";
|
|
17
|
+
import { getStatsDbPath, workerHostEntry } from "@linxiraos/pi-utils";
|
|
17
18
|
import { getTimeRangeConfig } from "./aggregator";
|
|
18
19
|
import { initDb } from "./db";
|
|
19
20
|
import { classifyAgentType } from "./parser";
|
|
@@ -44,7 +45,14 @@ import type {
|
|
|
44
45
|
SpotlightToolTotals,
|
|
45
46
|
} from "./shared-types";
|
|
46
47
|
import { BOOTSTRAP_MIN_SESSIONS, bootstrapInterval, bootstrapRatio, quantile } from "./spotlight-bootstrap";
|
|
47
|
-
import {
|
|
48
|
+
import {
|
|
49
|
+
artifactIds,
|
|
50
|
+
parseFailureCauses,
|
|
51
|
+
parseReadSelection,
|
|
52
|
+
resolveReadPath,
|
|
53
|
+
type SpotlightWindowFacts,
|
|
54
|
+
selectedLines,
|
|
55
|
+
} from "./spotlight-ingest";
|
|
48
56
|
import {
|
|
49
57
|
computeAdjusted,
|
|
50
58
|
computeCoverage,
|
|
@@ -56,6 +64,7 @@ import {
|
|
|
56
64
|
holdoutBaselines,
|
|
57
65
|
type SessionMoney,
|
|
58
66
|
} from "./spotlight-measures";
|
|
67
|
+
import type { SpotlightWorkerRequest, SpotlightWorkerResponse } from "./spotlight-worker";
|
|
59
68
|
|
|
60
69
|
const CHARS_PER_TOKEN = 4;
|
|
61
70
|
/** A request whose prompt is under this share of the previous request's follows a compaction. */
|
|
@@ -125,6 +134,7 @@ interface ResultRow {
|
|
|
125
134
|
artifacts: string | null;
|
|
126
135
|
sp_calls: number | null;
|
|
127
136
|
sp_failures: number | null;
|
|
137
|
+
sp_failure_causes: string | null;
|
|
128
138
|
sp_ms: number | null;
|
|
129
139
|
sp_cost: number | null;
|
|
130
140
|
shape_ms: number | null;
|
|
@@ -135,6 +145,7 @@ interface ResultRow {
|
|
|
135
145
|
gated: number;
|
|
136
146
|
heat: string | null;
|
|
137
147
|
kept: string | null;
|
|
148
|
+
windows: string | null;
|
|
138
149
|
need_reread: string | null;
|
|
139
150
|
need_edit: string | null;
|
|
140
151
|
}
|
|
@@ -192,14 +203,18 @@ export interface Result {
|
|
|
192
203
|
kept: [number, number][];
|
|
193
204
|
/** Original lines (1-based positions) later calls needed; null for results that collect none. */
|
|
194
205
|
needs: { reread: [number, number][]; edit: [number, number][] } | null;
|
|
195
|
-
|
|
196
|
-
/** The original window (`details.spotlight.original`): first line and line count; 0 lines without one. */
|
|
197
|
-
start: number;
|
|
206
|
+
/** The original's line count (all its windows'); 0 without one. */
|
|
198
207
|
lines: number;
|
|
199
|
-
|
|
208
|
+
/**
|
|
209
|
+
* The windows of the original (`details.spotlight.original`): its one window, or a `;`/`,` list read's several;
|
|
210
|
+
* none without an original.
|
|
211
|
+
*/
|
|
212
|
+
windows: SpotlightWindowFacts[];
|
|
200
213
|
hiddenLines: number;
|
|
201
214
|
spotlightCalls: number;
|
|
202
215
|
spotlightFailures: number;
|
|
216
|
+
/** Failed Spotlight calls by cause; null when none failed or the shape entry predates causes. */
|
|
217
|
+
spotlightFailureCauses: Record<string, number> | null;
|
|
203
218
|
spotlightMs: number;
|
|
204
219
|
spotlightUsd: number;
|
|
205
220
|
/** Wall time shaping took; null before its shape entry landed. */
|
|
@@ -291,20 +306,60 @@ function parseStrings(json: string | null): string[] {
|
|
|
291
306
|
}
|
|
292
307
|
}
|
|
293
308
|
|
|
309
|
+
/** The `sp_failure_causes` column, by ingest's rules; null when empty or unreadable. */
|
|
310
|
+
function failureCausesColumn(json: string | null): Record<string, number> | null {
|
|
311
|
+
if (!json) return null;
|
|
312
|
+
try {
|
|
313
|
+
return parseFailureCauses(JSON.parse(json));
|
|
314
|
+
} catch {
|
|
315
|
+
return null;
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
|
|
294
319
|
function parseRanges(json: string | null): [number, number][] {
|
|
295
320
|
if (!json) return [];
|
|
296
321
|
try {
|
|
297
|
-
|
|
298
|
-
if (!Array.isArray(value)) return [];
|
|
299
|
-
return value.filter(
|
|
300
|
-
(pair): pair is [number, number] =>
|
|
301
|
-
Array.isArray(pair) && typeof pair[0] === "number" && typeof pair[1] === "number",
|
|
302
|
-
);
|
|
322
|
+
return rangeList(JSON.parse(json));
|
|
303
323
|
} catch {
|
|
304
324
|
return [];
|
|
305
325
|
}
|
|
306
326
|
}
|
|
307
327
|
|
|
328
|
+
function rangeList(value: unknown): [number, number][] {
|
|
329
|
+
if (!Array.isArray(value)) return [];
|
|
330
|
+
return value.filter(
|
|
331
|
+
(pair): pair is [number, number] =>
|
|
332
|
+
Array.isArray(pair) && typeof pair[0] === "number" && typeof pair[1] === "number",
|
|
333
|
+
);
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
/** The `windows` column: a list read's windows; null for a single-window original (or a value with none valid). */
|
|
337
|
+
function parseWindowsColumn(json: string | null): SpotlightWindowFacts[] | null {
|
|
338
|
+
if (!json) return null;
|
|
339
|
+
try {
|
|
340
|
+
const value: unknown = JSON.parse(json);
|
|
341
|
+
if (!Array.isArray(value)) return null;
|
|
342
|
+
const windows = value.flatMap((window: unknown): SpotlightWindowFacts[] => {
|
|
343
|
+
if (typeof window !== "object" || window === null) return [];
|
|
344
|
+
const { path, start, lines, at, hidden, wholeFile } = window as Record<string, unknown>;
|
|
345
|
+
if (typeof start !== "number" || typeof lines !== "number" || typeof at !== "number") return [];
|
|
346
|
+
return [
|
|
347
|
+
{
|
|
348
|
+
path: typeof path === "string" ? path : null,
|
|
349
|
+
start,
|
|
350
|
+
lines,
|
|
351
|
+
at,
|
|
352
|
+
hidden: rangeList(hidden),
|
|
353
|
+
wholeFile: wholeFile === true,
|
|
354
|
+
},
|
|
355
|
+
];
|
|
356
|
+
});
|
|
357
|
+
return windows.length > 0 ? windows : null;
|
|
358
|
+
} catch {
|
|
359
|
+
return null;
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
|
|
308
363
|
/**
|
|
309
364
|
* What `plain` would have shown of a read/bash/eval result whose trace predates `plainTokens`: its input scaled to
|
|
310
365
|
* the inline cap ({@link PLAIN_CAP_BYTES}), in × min(1, cap / inChars). Null for any other tool: the generic path
|
|
@@ -326,7 +381,21 @@ function parseSteps(json: string): string[] {
|
|
|
326
381
|
}
|
|
327
382
|
|
|
328
383
|
function toResult(row: ResultRow): Result {
|
|
329
|
-
|
|
384
|
+
// A list read's windows, else the one window the columns describe (none without an original).
|
|
385
|
+
const windows =
|
|
386
|
+
parseWindowsColumn(row.windows) ??
|
|
387
|
+
(row.lines === null
|
|
388
|
+
? []
|
|
389
|
+
: [
|
|
390
|
+
{
|
|
391
|
+
path: row.path,
|
|
392
|
+
start: row.start_line ?? 1,
|
|
393
|
+
lines: row.lines,
|
|
394
|
+
at: 0,
|
|
395
|
+
hidden: parseRanges(row.hidden),
|
|
396
|
+
wholeFile: false,
|
|
397
|
+
},
|
|
398
|
+
]);
|
|
330
399
|
const steps = parseSteps(row.steps);
|
|
331
400
|
// A cut wider than plain pi did not apply: the model got plain's text, as for a result shaping kept.
|
|
332
401
|
const capped = row.capped_tokens !== null || steps.at(-1) === "plain-cap";
|
|
@@ -360,13 +429,12 @@ function toResult(row: ResultRow): Result {
|
|
|
360
429
|
row.need_reread !== null || row.need_edit !== null
|
|
361
430
|
? { reread: parseRanges(row.need_reread), edit: parseRanges(row.need_edit) }
|
|
362
431
|
: null,
|
|
363
|
-
path: row.path,
|
|
364
|
-
start: row.start_line ?? 1,
|
|
365
432
|
lines: row.lines ?? 0,
|
|
366
|
-
|
|
433
|
+
windows,
|
|
367
434
|
hiddenLines: row.hidden_lines,
|
|
368
435
|
spotlightCalls: row.sp_calls ?? 0,
|
|
369
436
|
spotlightFailures: row.sp_failures ?? 0,
|
|
437
|
+
spotlightFailureCauses: failureCausesColumn(row.sp_failure_causes),
|
|
370
438
|
spotlightMs: row.sp_ms ?? 0,
|
|
371
439
|
spotlightUsd: row.sp_cost ?? 0,
|
|
372
440
|
shapeMs: row.shape_ms,
|
|
@@ -412,8 +480,8 @@ class SessionLoader {
|
|
|
412
480
|
this.#results = database.query<ResultRow, [string]>(
|
|
413
481
|
`SELECT r.tool_call_id, r.timestamp, r.tool, r.in_chars, r.out_chars, r.in_tokens, r.out_tokens,
|
|
414
482
|
r.steps, r.holdout, r.path, r.start_line, r.lines, r.hidden, r.hidden_lines, r.artifacts, r.sp_calls,
|
|
415
|
-
r.sp_failures, r.sp_ms, r.sp_cost, r.shape_ms, r.plain_chars, r.plain_tokens, r.capped_tokens, r.score_free,
|
|
416
|
-
r.gated, r.heat, r.kept,
|
|
483
|
+
r.sp_failures, r.sp_failure_causes, r.sp_ms, r.sp_cost, r.shape_ms, r.plain_chars, r.plain_tokens, r.capped_tokens, r.score_free,
|
|
484
|
+
r.gated, r.heat, r.kept, r.windows,
|
|
417
485
|
n.reread AS need_reread, n.edit AS need_edit
|
|
418
486
|
FROM spotlight_results r
|
|
419
487
|
LEFT JOIN spotlight_needs n ON n.session_file = r.session_file AND n.tool_call_id = r.tool_call_id
|
|
@@ -603,33 +671,41 @@ export class EditLog {
|
|
|
603
671
|
}
|
|
604
672
|
|
|
605
673
|
/**
|
|
606
|
-
* Whether `call` re-reads
|
|
607
|
-
* later selection must overlap
|
|
608
|
-
* fetch-back rule, where a whole-file read overlaps everything).
|
|
674
|
+
* Whether `call` re-reads a file `source` read (any window of a `;`/`,` list read), unless that file was edited in
|
|
675
|
+
* between: `recovery`, the later selection must overlap the window's hidden lines (a recovery of a cut); else it must
|
|
676
|
+
* overlap the window itself (the fetch-back rule, where a whole-file read overlaps everything).
|
|
609
677
|
*/
|
|
610
|
-
function rereads(call: Call, source: Call, analysis: SessionAnalysis,
|
|
611
|
-
const
|
|
612
|
-
|
|
613
|
-
const
|
|
678
|
+
function rereads(call: Call, source: Call, analysis: SessionAnalysis, recovery = false): boolean {
|
|
679
|
+
const windows = source.result?.windows ?? [];
|
|
680
|
+
// A list read's target (`a.py;b.txt`) is no one path: only its windows name its files and tell which are whole.
|
|
681
|
+
const sourceSelection = windows.length > 1 ? null : parseReadSelection(source.target);
|
|
614
682
|
const selection = parseReadSelection(call.target);
|
|
615
|
-
if (!sourcePath) return false;
|
|
616
683
|
const file = resolveReadPath(selection.path, analysis.cwd);
|
|
617
|
-
if (file !== resolveReadPath(sourcePath, analysis.cwd)) return false;
|
|
618
|
-
if (analysis.edits.between(source.seq, call.seq, file)) return false;
|
|
619
684
|
const later = selectedLines(selection);
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
685
|
+
const reads: (SpotlightWindowFacts | null)[] = windows.length > 0 ? windows : [null];
|
|
686
|
+
return reads.some(window => {
|
|
687
|
+
const sourcePath = window?.path ?? sourceSelection?.path;
|
|
688
|
+
if (!sourcePath || file !== resolveReadPath(sourcePath, analysis.cwd)) return false;
|
|
689
|
+
if (analysis.edits.between(source.seq, call.seq, file)) return false;
|
|
690
|
+
if (later === null) return true;
|
|
691
|
+
const wholeFile = sourceSelection ? selectedLines(sourceSelection) === null : window?.wholeFile === true;
|
|
692
|
+
if (recovery) {
|
|
693
|
+
if (!window) return false;
|
|
694
|
+
const end = window.start + window.lines - 1;
|
|
695
|
+
// A list part's tail is known only when it read its file whole.
|
|
696
|
+
const ranges: [number, number][] =
|
|
697
|
+
selection.tail !== null && (sourceSelection !== null || wholeFile)
|
|
698
|
+
? [...later, [end - selection.tail + 1, end]]
|
|
699
|
+
: later;
|
|
700
|
+
return overlaps(ranges, window.hidden);
|
|
701
|
+
}
|
|
702
|
+
// A whole-file read overlaps any later selection; a tail read lands somewhere unknown in a windowed read.
|
|
703
|
+
if (wholeFile) return true;
|
|
704
|
+
const span = sourceSelection ? (selectedLines(sourceSelection) ?? []) : [];
|
|
705
|
+
const own: [number, number][] =
|
|
706
|
+
window && window.lines > 0 ? [[window.start, window.start + window.lines - 1]] : span;
|
|
707
|
+
return overlaps(later, own);
|
|
708
|
+
});
|
|
633
709
|
}
|
|
634
710
|
|
|
635
711
|
/** Jaccard similarity of two token sets; 0 when both are empty. */
|
|
@@ -677,7 +753,7 @@ function recoveryKind(
|
|
|
677
753
|
(result?.shortened || (wouldBe && (result?.holdout || result?.gated))) &&
|
|
678
754
|
result.tool === "read"
|
|
679
755
|
) {
|
|
680
|
-
if (rereads(call, source, analysis,
|
|
756
|
+
if (rereads(call, source, analysis, true)) return "reread";
|
|
681
757
|
}
|
|
682
758
|
if (reruns(call, source, analysis)) return "rerun";
|
|
683
759
|
return null;
|
|
@@ -1612,6 +1688,9 @@ function computeGaps(evaluated: readonly Evaluated[], tools: readonly SpotlightT
|
|
|
1612
1688
|
return tools.flatMap(tool => counts.get(tool) ?? []);
|
|
1613
1689
|
}
|
|
1614
1690
|
|
|
1691
|
+
/** The cause of failed results whose shape entry predates journaled causes. */
|
|
1692
|
+
const UNRECORDED_CAUSE = "unrecorded";
|
|
1693
|
+
|
|
1615
1694
|
/** Shaping time, Spotlight latency, failures and bill over every evaluated result. */
|
|
1616
1695
|
function computeOverhead(evaluated: readonly Evaluated[]): SpotlightOverhead {
|
|
1617
1696
|
const shapeMs: number[] = [];
|
|
@@ -1620,6 +1699,7 @@ function computeOverhead(evaluated: readonly Evaluated[]): SpotlightOverhead {
|
|
|
1620
1699
|
let failedWaitMs = 0;
|
|
1621
1700
|
let called = 0;
|
|
1622
1701
|
let spotlightUsd = 0;
|
|
1702
|
+
const causes = new Map<string, number>();
|
|
1623
1703
|
for (const { result } of evaluated) {
|
|
1624
1704
|
spotlightUsd += result.spotlightUsd;
|
|
1625
1705
|
if (result.shapeMs !== null) shapeMs.push(result.shapeMs);
|
|
@@ -1629,6 +1709,10 @@ function computeOverhead(evaluated: readonly Evaluated[]): SpotlightOverhead {
|
|
|
1629
1709
|
// A failed call records no Spotlight time; its wait shows in the shaping time instead.
|
|
1630
1710
|
failed++;
|
|
1631
1711
|
failedWaitMs += result.shapeMs ?? 0;
|
|
1712
|
+
const named = Object.keys(result.spotlightFailureCauses ?? {});
|
|
1713
|
+
for (const cause of named.length > 0 ? named : [UNRECORDED_CAUSE]) {
|
|
1714
|
+
causes.set(cause, (causes.get(cause) ?? 0) + 1);
|
|
1715
|
+
}
|
|
1632
1716
|
} else {
|
|
1633
1717
|
spotlightMs.push(result.spotlightMs);
|
|
1634
1718
|
}
|
|
@@ -1644,6 +1728,9 @@ function computeOverhead(evaluated: readonly Evaluated[]): SpotlightOverhead {
|
|
|
1644
1728
|
spotlightMsP50: at(spotlightMs, 0.5),
|
|
1645
1729
|
spotlightMsP90: at(spotlightMs, 0.9),
|
|
1646
1730
|
failureRate: called > 0 ? failed / called : null,
|
|
1731
|
+
failureCauses: [...causes]
|
|
1732
|
+
.map(([cause, results]) => ({ cause, results, share: results / called }))
|
|
1733
|
+
.sort((a, b) => b.results - a.results || a.cause.localeCompare(b.cause)),
|
|
1647
1734
|
failedWaitMs,
|
|
1648
1735
|
spotlightUsd,
|
|
1649
1736
|
};
|
|
@@ -1714,14 +1801,89 @@ function contextPoints(analysis: SessionAnalysis): SpotlightContextPoint[] {
|
|
|
1714
1801
|
// Entry points
|
|
1715
1802
|
// ---------------------------------------------------------------------------
|
|
1716
1803
|
|
|
1717
|
-
/**
|
|
1804
|
+
/** The dashboard for a `?range=` and `?agent=`; an unknown `agent` measures every transcript. */
|
|
1805
|
+
export function spotlightDashboard(
|
|
1806
|
+
database: Database,
|
|
1807
|
+
range: string | null | undefined,
|
|
1808
|
+
agent: string | null | undefined,
|
|
1809
|
+
): SpotlightDashboardStats {
|
|
1810
|
+
const scope: SpotlightAgentScope = agent === "main" || agent === "subagent" ? agent : "all";
|
|
1811
|
+
return buildSpotlightDashboard(database, getTimeRangeConfig(range), scope);
|
|
1812
|
+
}
|
|
1813
|
+
|
|
1814
|
+
/** `GET /api/stats/spotlight?range=&agent=`, built on the calling thread. */
|
|
1718
1815
|
export async function getSpotlightDashboardStats(
|
|
1719
1816
|
range?: string | null,
|
|
1720
1817
|
agent?: string | null,
|
|
1721
1818
|
): Promise<SpotlightDashboardStats> {
|
|
1722
|
-
|
|
1723
|
-
|
|
1724
|
-
|
|
1819
|
+
return spotlightDashboard(await initDb(), range, agent);
|
|
1820
|
+
}
|
|
1821
|
+
|
|
1822
|
+
/**
|
|
1823
|
+
* A fresh Spotlight worker: through the CLI entry with its argv selector when the process started from one (source
|
|
1824
|
+
* `cli.ts`, the npm bundle, the compiled binary), else this package's worker module (standalone `omp-stats`, tests,
|
|
1825
|
+
* SDK embedding).
|
|
1826
|
+
*/
|
|
1827
|
+
function createSpotlightWorker(): Worker {
|
|
1828
|
+
const hostEntry = workerHostEntry();
|
|
1829
|
+
if (hostEntry) {
|
|
1830
|
+
return new Worker(hostEntry, { type: "module", argv: ["__zeta_worker_stats_spotlight"] });
|
|
1831
|
+
}
|
|
1832
|
+
return new Worker(new URL("./spotlight-worker.ts", import.meta.url).href, { type: "module" });
|
|
1833
|
+
}
|
|
1834
|
+
|
|
1835
|
+
/**
|
|
1836
|
+
* Send one request to a fresh worker and terminate it after the reply, so a build's memory goes with it. Aborting
|
|
1837
|
+
* `signal` terminates it early and rejects with the signal's reason.
|
|
1838
|
+
*/
|
|
1839
|
+
async function askSpotlightWorker(
|
|
1840
|
+
request: SpotlightWorkerRequest,
|
|
1841
|
+
signal?: AbortSignal,
|
|
1842
|
+
): Promise<Extract<SpotlightWorkerResponse, { ok: true }>> {
|
|
1843
|
+
signal?.throwIfAborted();
|
|
1844
|
+
const worker = createSpotlightWorker();
|
|
1845
|
+
const { promise, resolve, reject } = Promise.withResolvers<SpotlightWorkerResponse>();
|
|
1846
|
+
const onAbort = () => reject(signal?.reason);
|
|
1847
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
1848
|
+
worker.onmessage = (event: MessageEvent<SpotlightWorkerResponse>) => resolve(event.data);
|
|
1849
|
+
worker.onerror = (event: ErrorEvent) => {
|
|
1850
|
+
reject(event.error instanceof Error ? event.error : new Error(event.message || "spotlight worker error"));
|
|
1851
|
+
};
|
|
1852
|
+
worker.addEventListener("close", () => reject(new Error("spotlight worker exited without replying")));
|
|
1853
|
+
try {
|
|
1854
|
+
worker.postMessage(request);
|
|
1855
|
+
const response = await promise;
|
|
1856
|
+
if (!response.ok) throw new Error(response.error);
|
|
1857
|
+
return response;
|
|
1858
|
+
} finally {
|
|
1859
|
+
signal?.removeEventListener("abort", onAbort);
|
|
1860
|
+
worker.terminate();
|
|
1861
|
+
}
|
|
1862
|
+
}
|
|
1863
|
+
|
|
1864
|
+
/**
|
|
1865
|
+
* `GET /api/stats/spotlight?range=&agent=` as JSON, built on a worker: a build takes seconds, and on the server's
|
|
1866
|
+
* thread it held every other request and ingest until it ended. Aborting `signal` ends the build.
|
|
1867
|
+
*/
|
|
1868
|
+
export async function buildSpotlightDashboardJson(
|
|
1869
|
+
range: string | null,
|
|
1870
|
+
agent: string | null,
|
|
1871
|
+
signal?: AbortSignal,
|
|
1872
|
+
): Promise<string> {
|
|
1873
|
+
// The worker opens the database read-only, so it must already exist with the current schema.
|
|
1874
|
+
await initDb();
|
|
1875
|
+
const response = await askSpotlightWorker({ kind: "build", dbPath: getStatsDbPath(), range, agent }, signal);
|
|
1876
|
+
if (response.kind !== "build") throw new Error(`spotlight worker: expected a build, got ${response.kind}`);
|
|
1877
|
+
return response.json;
|
|
1878
|
+
}
|
|
1879
|
+
|
|
1880
|
+
/**
|
|
1881
|
+
* Smoke test for `zetacode --smoke-test`: spawns a Spotlight worker, pings it, and asserts the pong, so install-method CI
|
|
1882
|
+
* catches a worker that fails to load from the compiled binary or npm bundle.
|
|
1883
|
+
*/
|
|
1884
|
+
export async function smokeTestSpotlightWorker({ timeoutMs = 5_000 }: { timeoutMs?: number } = {}): Promise<void> {
|
|
1885
|
+
const response = await askSpotlightWorker({ kind: "ping" }, AbortSignal.timeout(timeoutMs));
|
|
1886
|
+
if (response.kind !== "pong") throw new Error(`spotlight worker: expected pong, got ${response.kind}`);
|
|
1725
1887
|
}
|
|
1726
1888
|
|
|
1727
1889
|
/** `GET /api/stats/spotlight/session?file=`; null when the file is not an experiment session. */
|