@linxiraos/pi-stats 1.5.1 → 1.5.11

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.
Files changed (66) hide show
  1. package/CHANGELOG.md +28 -3
  2. package/THIRD-PARTY-NOTICES.txt +22 -11
  3. package/dist/client/favicon.ico +0 -0
  4. package/dist/client/index.css +1 -1
  5. package/dist/client/index.js +90 -89
  6. package/dist/types/aggregator.d.ts +5 -0
  7. package/dist/types/client/api.d.ts +7 -1
  8. package/dist/types/client/app/nav.d.ts +1 -1
  9. package/dist/types/client/data/formatters.d.ts +2 -2
  10. package/dist/types/client/data/range.d.ts +5 -4
  11. package/dist/types/client/data/series.d.ts +14 -2
  12. package/dist/types/client/i18n/messages/costs.d.ts +4 -4
  13. package/dist/types/client/i18n/messages/en.d.ts +86 -6
  14. package/dist/types/client/i18n/messages/gain.d.ts +2 -2
  15. package/dist/types/client/i18n/messages/nav.d.ts +2 -0
  16. package/dist/types/client/i18n/messages/tracking.d.ts +89 -0
  17. package/dist/types/client/i18n/messages/zh-CN.d.ts +1 -1
  18. package/dist/types/client/routes/TrackingRoute.d.ts +10 -0
  19. package/dist/types/client/routes/index.d.ts +1 -0
  20. package/dist/types/db.d.ts +20 -0
  21. package/dist/types/index.d.ts +1 -1
  22. package/dist/types/parser.d.ts +7 -1
  23. package/dist/types/rollup.d.ts +4 -0
  24. package/dist/types/shared-types.d.ts +88 -0
  25. package/dist/types/spotlight-aggregator.d.ts +24 -5
  26. package/dist/types/spotlight-ingest.d.ts +48 -9
  27. package/dist/types/spotlight-worker.d.ts +27 -0
  28. package/dist/types/trace.d.ts +7 -1
  29. package/dist/types/tracking.d.ts +29 -0
  30. package/dist/types/types.d.ts +5 -5
  31. package/package.json +4 -4
  32. package/src/aggregator.ts +16 -0
  33. package/src/client/App.tsx +3 -0
  34. package/src/client/api.ts +11 -0
  35. package/src/client/app/nav.ts +3 -0
  36. package/src/client/data/formatters.ts +7 -7
  37. package/src/client/data/range.ts +22 -9
  38. package/src/client/data/series.ts +33 -14
  39. package/src/client/favicon.ico +0 -0
  40. package/src/client/i18n/messages/costs.ts +4 -4
  41. package/src/client/i18n/messages/en.ts +2 -0
  42. package/src/client/i18n/messages/gain.ts +2 -2
  43. package/src/client/i18n/messages/nav.ts +2 -0
  44. package/src/client/i18n/messages/tracking.ts +91 -0
  45. package/src/client/i18n/messages/zh-CN.ts +2 -0
  46. package/src/client/routes/CostsRoute.tsx +4 -4
  47. package/src/client/routes/GainRoute.tsx +5 -4
  48. package/src/client/routes/ProvidersRoute.tsx +4 -4
  49. package/src/client/routes/TrackingRoute.tsx +262 -0
  50. package/src/client/routes/index.ts +1 -0
  51. package/src/client/routes/tracking.css +94 -0
  52. package/src/client/spotlight/Overhead.tsx +46 -1
  53. package/src/db.ts +105 -21
  54. package/src/gain-aggregator.ts +3 -6
  55. package/src/index.ts +5 -1
  56. package/src/parser.ts +75 -10
  57. package/src/rollup.ts +67 -14
  58. package/src/server.ts +57 -16
  59. package/src/shared-types.ts +98 -0
  60. package/src/spotlight-aggregator.ts +207 -45
  61. package/src/spotlight-ingest.ts +141 -37
  62. package/src/spotlight-measures.ts +117 -85
  63. package/src/spotlight-worker.ts +45 -0
  64. package/src/trace.ts +56 -20
  65. package/src/tracking.ts +394 -0
  66. package/src/types.ts +5 -5
@@ -31,14 +31,19 @@ export function experimentMarker(customType: unknown, data: Record<string, unkno
31
31
  /** Longest stored call target. */
32
32
  export const SPOTLIGHT_TARGET_CHARS = 500;
33
33
 
34
- /** A shaped read still collecting the lines the agent needs later (see {@link SpotlightCollector}). */
34
+ /**
35
+ * A window of a shaped read still collecting the lines the agent needs later (see {@link SpotlightCollector}): a
36
+ * `;`/`,` list read opens one per window that shows a file, all under its call.
37
+ */
35
38
  export interface SpotlightOpenRead {
36
39
  toolCallId: string;
37
40
  /** The read file, resolved against the session's working directory. */
38
41
  file: string;
39
- /** First file line of the original and its line count. */
42
+ /** First file line of the window and its line count. */
40
43
  start: number;
41
44
  lines: number;
45
+ /** 0-based position of the window's first line in the original; absent (0) in states persisted before windows. */
46
+ at?: number;
42
47
  /** `original.url`: the session artifact holding the original text. */
43
48
  url: string | null;
44
49
  }
@@ -107,21 +112,52 @@ export interface SpotlightShapeRow {
107
112
  original: SpotlightOriginalFacts | null;
108
113
  /** Artifact ids the result names (its text's `artifact://N` plus `original.url`); null before the result lands. */
109
114
  artifacts: number[] | null;
110
- /** Spotlight's own usage, from the shape entry; null before it lands. */
111
- spotlight: { calls: number; failures: number; ms: number; costUsd: number } | null;
115
+ /**
116
+ * Spotlight's own usage, from the shape entry; null before it lands. `failureCauses` counts failed calls by cause
117
+ * (`no_credential`, `timeout`, …); null when none failed or the entry predates it.
118
+ */
119
+ spotlight: {
120
+ calls: number;
121
+ failures: number;
122
+ failureCauses: Record<string, number> | null;
123
+ ms: number;
124
+ costUsd: number;
125
+ } | null;
112
126
  /** Wall time shaping took, from the shape entry. */
113
127
  shapeMs: number | null;
114
128
  }
115
129
 
130
+ /**
131
+ * One window of an original (`details.spotlight.original.windows`, else the one window the original is): the lines of
132
+ * one read it shows.
133
+ */
134
+ export interface SpotlightWindowFacts {
135
+ /** The file it shows; null for text no file names. */
136
+ path: string | null;
137
+ /** Line number of its first line (1-based file line for reads, else 1). */
138
+ start: number;
139
+ lines: number;
140
+ /** 0-based position of its first line in the original. */
141
+ at: number;
142
+ /** Hidden absolute line ranges (numbered from {@link start}), inclusive: the window minus the kept ranges. */
143
+ hidden: [number, number][];
144
+ /**
145
+ * A list read's part read its file whole (no line selector): a tail of the file lies in it. Always false for a single
146
+ * window, whose call target tells.
147
+ */
148
+ wholeFile: boolean;
149
+ }
150
+
116
151
  export interface SpotlightOriginalFacts {
117
152
  url: string | null;
153
+ /** The single window's file, start and hidden lines; of a multi-window original null, 1 and its hidden positions. */
118
154
  path: string | null;
119
- /** First original line of the window (1-based file line for reads, else 1). */
120
155
  start: number;
121
156
  lines: number;
122
- /** Hidden absolute line ranges, inclusive: the window minus the kept ranges. */
123
157
  hidden: [number, number][];
124
158
  hiddenLines: number;
159
+ /** The windows it is made of, in order: one for an original without `windows`. */
160
+ windows: SpotlightWindowFacts[];
125
161
  /** Spotlight's per-line heat (`0`–`9`, `-` unscored) over the first lines; null when the trace has none. */
126
162
  heat: string | null;
127
163
  /** Kept runs, 1-based positions in the original (of a held-out result: what the cut would have kept). */
@@ -129,14 +165,16 @@ export interface SpotlightOriginalFacts {
129
165
  }
130
166
 
131
167
  /**
132
- * `spotlight_needs` row (merged on upsert): original lines (1-based positions in the original) a shaped read's later
133
- * calls needed. Ranges of later parses are added to the stored ones; `open` is the latest.
168
+ * `spotlight_needs` row (merged on upsert): original lines (1-based positions in the whole original) a shaped read's
169
+ * later calls needed. Ranges of later parses are added to the stored ones; `open` is the latest. One row per call:
170
+ * `file` is the read's file, of a `;`/`,` list read the file of its first window that shows one (the first row
171
+ * stored keeps it).
134
172
  */
135
173
  export interface SpotlightNeedRow {
136
174
  sessionFile: string;
137
175
  toolCallId: string;
138
176
  file: string;
139
- /** Still collecting: no edit, whole-file read or later shaped read of the file yet. */
177
+ /** Still collecting: some window's file has no edit, whole-file read or later shaped read yet. */
140
178
  open: boolean;
141
179
  /** Lines later `read` selections covered. */
142
180
  reread: [number, number][];
@@ -386,9 +424,9 @@ export function selectedLines(selection: ReadSelection): [number, number][] | nu
386
424
  return selection.ranges.length === 0 && selection.tail === null ? null : selection.ranges;
387
425
  }
388
426
 
389
- /** A path as written, resolved against the session's working directory (URLs and absolute paths kept). */
427
+ /** A path as written, resolved and normalized against the session's working directory (URLs kept). */
390
428
  export function resolveReadPath(target: string, cwd: string | null): string {
391
- if (URL_SCHEME.test(target) || !cwd || path.isAbsolute(target)) return target;
429
+ if (URL_SCHEME.test(target) || !cwd) return target;
392
430
  return path.resolve(cwd, target);
393
431
  }
394
432
 
@@ -522,19 +560,56 @@ function parseKept(value: unknown): [number, number][] {
522
560
  return out;
523
561
  }
524
562
 
563
+ /** Ranges of 1-based original positions clipped to a window (`at + 1 … at + lines`), renumbered 1-based within it. */
564
+ export function windowRanges(ranges: readonly [number, number][], at: number, lines: number): [number, number][] {
565
+ const out: [number, number][] = [];
566
+ for (const [a, b] of ranges) {
567
+ const from = Math.max(a - at, 1);
568
+ const to = Math.min(b - at, lines);
569
+ if (from <= to) out.push([from, to]);
570
+ }
571
+ return out;
572
+ }
573
+
574
+ /** The original's windows: its `windows` when it joins several reads, else the one window it is. */
575
+ function parseWindows(
576
+ value: Record<string, unknown>,
577
+ lines: number,
578
+ kept: readonly [number, number][],
579
+ ): SpotlightWindowFacts[] {
580
+ const raw: Record<string, unknown>[] = Array.isArray(value.windows) ? value.windows.filter(isRecord) : [value];
581
+ return raw.map(window => {
582
+ const own = window === value;
583
+ const start = finite(window.start) || 1;
584
+ const at = own ? 0 : finite(window.at);
585
+ const count = own ? lines : finite(window.lines);
586
+ return {
587
+ path: typeof window.path === "string" ? window.path : null,
588
+ start,
589
+ lines: count,
590
+ at,
591
+ hidden: hiddenRanges(start, count, windowRanges(kept, at, count)),
592
+ // A single window's call target tells whether it is whole (the aggregator reads it there).
593
+ wholeFile: !own && window.wholeFile === true,
594
+ };
595
+ });
596
+ }
597
+
525
598
  function parseOriginal(value: unknown): SpotlightOriginalFacts | null {
526
599
  if (!isRecord(value)) return null;
527
600
  const lines = finite(value.lines);
528
- const start = finite(value.start) || 1;
529
601
  const kept = parseKept(value.kept);
530
- const hidden = hiddenRanges(start, lines, kept);
602
+ const windows = parseWindows(value, lines, kept);
603
+ const single = windows.length === 1 ? windows[0] : null;
604
+ const hidden = single ? single.hidden : hiddenRanges(1, lines, kept);
531
605
  return {
532
606
  url: typeof value.url === "string" ? value.url : null,
533
- path: typeof value.path === "string" ? value.path : null,
534
- start,
607
+ path: single ? single.path : null,
608
+ start: single ? single.start : 1,
535
609
  lines,
536
610
  hidden,
537
611
  hiddenLines: hidden.reduce((sum, [a, b]) => sum + b - a + 1, 0),
612
+ windows,
538
613
  heat: typeof value.heat === "string" ? value.heat : null,
539
614
  kept,
540
615
  };
@@ -579,6 +654,7 @@ export function shapeFromEntry(
579
654
  spotlight: {
580
655
  calls: finite(usage.calls),
581
656
  failures: finite(usage.failures),
657
+ failureCauses: parseFailureCauses(usage.failureCauses),
582
658
  ms: finite(usage.ms),
583
659
  costUsd: finite(usage.costUsd),
584
660
  },
@@ -586,6 +662,19 @@ export function shapeFromEntry(
586
662
  };
587
663
  }
588
664
 
665
+ /**
666
+ * Failed calls by cause, keeping positive finite counts; null when none is left. Normalizes both a shape entry's
667
+ * `failureCauses` at ingest and the decoded `sp_failure_causes` column at aggregation.
668
+ */
669
+ export function parseFailureCauses(value: unknown): Record<string, number> | null {
670
+ if (!isRecord(value)) return null;
671
+ const causes: Record<string, number> = {};
672
+ for (const [cause, count] of Object.entries(value)) {
673
+ if (typeof count === "number" && Number.isFinite(count) && count > 0) causes[cause] = count;
674
+ }
675
+ return Object.keys(causes).length > 0 ? causes : null;
676
+ }
677
+
589
678
  /** The row a result message's `details.spotlight` describes, or null when it carries none. */
590
679
  export function shapeFromDetails(
591
680
  sessionFile: string,
@@ -735,13 +824,14 @@ export class SpotlightCollector {
735
824
  const original = await text;
736
825
  if (!original) continue;
737
826
  const row = this.#need(read);
827
+ const at = read.at ?? 0;
828
+ // A list read's original joins several windows: a Find block lies in its own window's lines.
829
+ const lines = original.slice(at, at + read.lines);
738
830
  for (const block of blocks) {
739
- const spans = locateFind(original, block.lines);
831
+ const spans = locateFind(lines, block.lines);
740
832
  // Without `all` the edit needs exactly one match; more is a Find this text cannot place.
741
833
  const located = block.all ? spans : spans.length === 1 ? spans : [];
742
- for (const [a, b] of located) {
743
- if (a <= read.lines) row.edit.push([a, Math.min(b, read.lines)]);
744
- }
834
+ for (const [a, b] of located) row.edit.push([a + at, Math.min(b, read.lines) + at]);
745
835
  }
746
836
  row.edit = mergeRanges(row.edit);
747
837
  }
@@ -766,27 +856,38 @@ export class SpotlightCollector {
766
856
  }
767
857
 
768
858
  #close(read: SpotlightOpenRead): void {
769
- const open = this.state.open ?? [];
770
- this.state.open = open.filter(other => other !== read);
771
- if (this.#record) this.#need(read).open = false;
859
+ const open = (this.state.open ?? []).filter(other => other !== read);
860
+ this.state.open = open;
861
+ // A list read collects until none of its windows does.
862
+ if (this.#record) this.#need(read).open = open.some(other => other.toolCallId === read.toolCallId);
772
863
  }
773
864
 
774
- /** Start collecting for a shaped read whose result just landed; it stops an earlier one of the same file. */
865
+ /**
866
+ * Start collecting for a shaped read whose result just landed, one open read per window showing a file that shaping
867
+ * cut (hid lines of, or would have: a held-out window's would-be cut); a window shown unchanged was never ranked.
868
+ * Each stops an earlier read's window of the same file.
869
+ */
775
870
  #openRead(row: SpotlightShapeRow): void {
776
871
  const original = row.original;
777
- if (row.tool !== "read" || !original?.path || original.lines <= 0) return;
872
+ if (row.tool !== "read" || !original) return;
778
873
  if ((this.state.open ?? []).some(read => read.toolCallId === row.toolCallId)) return;
779
- const file = resolveReadPath(original.path, this.state.cwd);
780
- for (const read of this.state.open ?? []) if (read.file === file) this.#close(read);
781
- const read: SpotlightOpenRead = {
782
- toolCallId: row.toolCallId,
783
- file,
784
- start: original.start,
785
- lines: original.lines,
786
- url: original.url,
787
- };
788
- this.state.open = [...(this.state.open ?? []), read];
789
- if (this.#record) this.#need(read);
874
+ for (const window of original.windows) {
875
+ if (!window.path || window.lines <= 0 || window.hidden.length === 0) continue;
876
+ const file = resolveReadPath(window.path, this.state.cwd);
877
+ for (const read of this.state.open ?? []) {
878
+ if (read.file === file && read.toolCallId !== row.toolCallId) this.#close(read);
879
+ }
880
+ const read: SpotlightOpenRead = {
881
+ toolCallId: row.toolCallId,
882
+ file,
883
+ start: window.start,
884
+ lines: window.lines,
885
+ at: window.at,
886
+ url: original.url,
887
+ };
888
+ this.state.open = [...(this.state.open ?? []), read];
889
+ if (this.#record) this.#need(read);
890
+ }
790
891
  }
791
892
 
792
893
  /** What a later call needs of the open reads, and which ones it stops. */
@@ -804,16 +905,19 @@ export class SpotlightCollector {
804
905
  continue;
805
906
  }
806
907
  if (!this.#record) continue;
908
+ // Positions in the whole original: the window's own, past the windows before it.
909
+ const at = read.at ?? 0;
807
910
  const end = read.start + read.lines - 1;
911
+ const offset = at - read.start + 1;
808
912
  const positions: [number, number][] = [];
809
913
  for (const [a, b] of ranges) {
810
914
  const from = Math.max(a, read.start);
811
915
  const to = Math.min(b, end);
812
- if (from <= to) positions.push([from - read.start + 1, to - read.start + 1]);
916
+ if (from <= to) positions.push([from + offset, to + offset]);
813
917
  }
814
918
  // The last N lines are known only when the original reaches the file's end: a whole-file read's does.
815
919
  if (selection.tail !== null && read.start === 1)
816
- positions.push([Math.max(1, read.lines - selection.tail + 1), read.lines]);
920
+ positions.push([Math.max(1, read.lines - selection.tail + 1) + at, read.lines + at]);
817
921
  const row = this.#need(read);
818
922
  row.reread = mergeRanges([...row.reread, ...positions]);
819
923
  }
@@ -27,7 +27,7 @@ import {
27
27
  jointSamples,
28
28
  percentileInterval,
29
29
  } from "./spotlight-bootstrap";
30
- import { mergeRanges } from "./spotlight-ingest";
30
+ import { mergeRanges, windowRanges } from "./spotlight-ingest";
31
31
 
32
32
  const CHARS_PER_TOKEN = 4;
33
33
  /** Holdouts per tool below which its baseline is too thin to trust. */
@@ -364,6 +364,36 @@ const POSITION_LABELS: readonly string[] = [
364
364
  ...Array.from({ length: 10 }, (_, d) => `${d * 10}–${(d + 1) * 10}%`),
365
365
  ];
366
366
 
367
+ /** One ranked span of a result: its lines, heat, kept runs and needs, positions 1-based within it. */
368
+ interface RankingUnit {
369
+ lines: number;
370
+ heat: string;
371
+ kept: [number, number][];
372
+ needs: Result["needs"];
373
+ }
374
+
375
+ /**
376
+ * The spans a result's ranking is judged over: the whole result, or of a `;`/`,` list read each window shaping cut
377
+ * (heat digits rank within their own window, and a window shown unchanged was never ranked).
378
+ */
379
+ function rankingUnits(result: Result): RankingUnit[] {
380
+ if (result.windows.length <= 1) {
381
+ return [{ lines: result.lines, heat: result.heat, kept: result.kept, needs: result.needs }];
382
+ }
383
+ const { needs } = result;
384
+ return result.windows
385
+ .filter(window => window.hidden.length > 0)
386
+ .map(({ at, lines }) => ({
387
+ lines,
388
+ heat: result.heat.slice(at, at + lines),
389
+ kept: windowRanges(result.kept, at, lines),
390
+ needs: needs && {
391
+ reread: windowRanges(needs.reread, at, lines),
392
+ edit: windowRanges(needs.edit, at, lines),
393
+ },
394
+ }));
395
+ }
396
+
367
397
  /**
368
398
  * Ranking quality per group over shaped reads with needed lines (see {@link SpotlightRankingCell}), mean heat by
369
399
  * line position over every scored cut or would-be cut, and how the needs were observed.
@@ -374,94 +404,96 @@ export function computeRanking(evaluated: readonly Evaluated[]): SpotlightRankin
374
404
  const positionSum = new Float64Array(POSITION_LABELS.length);
375
405
  const positionLines = new Float64Array(POSITION_LABELS.length);
376
406
  for (const { result, analysis } of evaluated) {
377
- const n = result.lines;
378
- if ((result.shortened || result.holdout) && !result.scoreFree && n >= POSITION_MIN_LINES) {
407
+ const group = rankingGroup(result);
408
+ for (const unit of rankingUnits(result)) {
409
+ const n = unit.lines;
410
+ if ((result.shortened || result.holdout) && !result.scoreFree && n >= POSITION_MIN_LINES) {
411
+ const m = Math.min(n, HEAT_LINES);
412
+ for (let i = 0; i < Math.min(m, unit.heat.length); i++) {
413
+ const c = unit.heat.charCodeAt(i);
414
+ if (c < 48 || c > 57) continue;
415
+ const slot = i === 0 ? 0 : i <= 2 ? 1 : 2 + Math.min(9, Math.floor((10 * i) / m));
416
+ positionSum[slot] += c - 48;
417
+ positionLines[slot]++;
418
+ }
419
+ }
420
+ if (result.tool !== "read" || n <= 0 || !unit.needs || !group) continue;
421
+ const needed = lineMask(n, mergeRanges([...unit.needs.reread, ...unit.needs.edit]));
422
+ let neededCount = 0;
423
+ for (let p = 1; p <= n; p++) neededCount += needed[p];
424
+ if (neededCount === 0) continue;
425
+ if (unit.needs.reread.some(([a, b]) => a <= n && b >= 1)) sources.reread++;
426
+ if (unit.needs.edit.some(([a, b]) => a <= n && b >= 1)) sources.edit++;
427
+
428
+ let bySession = cells.get(group);
429
+ if (!bySession) {
430
+ bySession = new Map();
431
+ cells.set(group, bySession);
432
+ }
433
+ const file = analysis.session.session_file;
434
+ let sums = bySession.get(file);
435
+ if (!sums) {
436
+ sums = {
437
+ results: 0,
438
+ neededLines: 0,
439
+ aucSum: 0,
440
+ aucCount: 0,
441
+ topObserved: 0,
442
+ topExpected: 0,
443
+ keptObserved: 0,
444
+ keptExpected: 0,
445
+ };
446
+ bySession.set(file, sums);
447
+ }
448
+ sums.results++;
449
+ sums.neededLines += neededCount;
450
+
451
+ const kept = lineMask(n, unit.kept);
452
+ let keptCount = 0;
453
+ let neededKept = 0;
454
+ for (let p = 1; p <= n; p++) {
455
+ keptCount += kept[p];
456
+ neededKept += kept[p] & needed[p];
457
+ }
458
+ sums.keptObserved += neededKept;
459
+ sums.keptExpected += (neededCount * keptCount) / n;
460
+
461
+ if (group === "scoreFree") continue;
379
462
  const m = Math.min(n, HEAT_LINES);
380
- for (let i = 0; i < Math.min(m, result.heat.length); i++) {
381
- const c = result.heat.charCodeAt(i);
382
- if (c < 48 || c > 57) continue;
383
- const slot = i === 0 ? 0 : i <= 2 ? 1 : 2 + Math.min(9, Math.floor((10 * i) / m));
384
- positionSum[slot] += c - 48;
385
- positionLines[slot]++;
463
+ const all = new Float64Array(10);
464
+ const need = new Float64Array(10);
465
+ for (let i = 0; i < m; i++) {
466
+ const d = heatDigit(unit.heat, i);
467
+ all[d]++;
468
+ need[d] += needed[i + 1];
386
469
  }
387
- }
388
- const group = rankingGroup(result);
389
- if (result.tool !== "read" || n <= 0 || !result.needs || !group) continue;
390
- const needed = lineMask(n, mergeRanges([...result.needs.reread, ...result.needs.edit]));
391
- let neededCount = 0;
392
- for (let p = 1; p <= n; p++) neededCount += needed[p];
393
- if (neededCount === 0) continue;
394
- if (result.needs.reread.some(([a, b]) => a <= n && b >= 1)) sources.reread++;
395
- if (result.needs.edit.some(([a, b]) => a <= n && b >= 1)) sources.edit++;
396
-
397
- let bySession = cells.get(group);
398
- if (!bySession) {
399
- bySession = new Map();
400
- cells.set(group, bySession);
401
- }
402
- const file = analysis.session.session_file;
403
- let sums = bySession.get(file);
404
- if (!sums) {
405
- sums = {
406
- results: 0,
407
- neededLines: 0,
408
- aucSum: 0,
409
- aucCount: 0,
410
- topObserved: 0,
411
- topExpected: 0,
412
- keptObserved: 0,
413
- keptExpected: 0,
414
- };
415
- bySession.set(file, sums);
416
- }
417
- sums.results++;
418
- sums.neededLines += neededCount;
419
-
420
- const kept = lineMask(n, result.kept);
421
- let keptCount = 0;
422
- let neededKept = 0;
423
- for (let p = 1; p <= n; p++) {
424
- keptCount += kept[p];
425
- neededKept += kept[p] & needed[p];
426
- }
427
- sums.keptObserved += neededKept;
428
- sums.keptExpected += (neededCount * keptCount) / n;
429
-
430
- if (group === "scoreFree") continue;
431
- const m = Math.min(n, HEAT_LINES);
432
- const all = new Float64Array(10);
433
- const need = new Float64Array(10);
434
- for (let i = 0; i < m; i++) {
435
- const d = heatDigit(result.heat, i);
436
- all[d]++;
437
- need[d] += needed[i + 1];
438
- }
439
- let neededIn = 0;
440
- for (const count of need) neededIn += count;
441
- const unneededIn = m - neededIn;
442
- if (neededIn > 0 && unneededIn > 0) {
443
- let below = 0;
444
- let concordant = 0;
445
- for (let d = 0; d < 10; d++) {
446
- const unneeded = all[d] - need[d];
447
- concordant += need[d] * below + 0.5 * need[d] * unneeded;
448
- below += unneeded;
470
+ let neededIn = 0;
471
+ for (const count of need) neededIn += count;
472
+ const unneededIn = m - neededIn;
473
+ if (neededIn > 0 && unneededIn > 0) {
474
+ let below = 0;
475
+ let concordant = 0;
476
+ for (let d = 0; d < 10; d++) {
477
+ const unneeded = all[d] - need[d];
478
+ concordant += need[d] * below + 0.5 * need[d] * unneeded;
479
+ below += unneeded;
480
+ }
481
+ sums.aucSum += concordant / (neededIn * unneededIn);
482
+ sums.aucCount++;
449
483
  }
450
- sums.aucSum += concordant / (neededIn * unneededIn);
451
- sums.aucCount++;
452
- }
453
- if (neededIn > 0) {
454
- // The hottest k lines; ties at the boundary digit share the remaining places evenly.
455
- const k = Math.ceil(TOP_SHARE * m);
456
- let remaining = k;
457
- let observed = 0;
458
- for (let d = 9; d >= 0 && remaining > 0; d--) {
459
- const take = Math.min(remaining, all[d]);
460
- if (take > 0) observed += (take * need[d]) / all[d];
461
- remaining -= take;
484
+ if (neededIn > 0) {
485
+ // The hottest k lines; ties at the boundary digit share the remaining places evenly.
486
+ const k = Math.ceil(TOP_SHARE * m);
487
+ let remaining = k;
488
+ let observed = 0;
489
+ for (let d = 9; d >= 0 && remaining > 0; d--) {
490
+ const take = Math.min(remaining, all[d]);
491
+ if (take > 0) observed += (take * need[d]) / all[d];
492
+ remaining -= take;
493
+ }
494
+ sums.topObserved += observed;
495
+ sums.topExpected += (k * neededIn) / m;
462
496
  }
463
- sums.topObserved += observed;
464
- sums.topExpected += (k * neededIn) / m;
465
497
  }
466
498
  }
467
499
 
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Builds one Spotlight dashboard for the stats server, then is terminated. A build reads every experiment session and
3
+ * takes seconds; on the server's thread it held every other request and ingest until it ended.
4
+ *
5
+ * The worker opens the database read-only and builds inside one read transaction, so the payload is a single snapshot
6
+ * while the server keeps ingesting. A `{ kind: "ping" }` request replies `{ ok: true, kind: "pong" }` for
7
+ * `smokeTestSpotlightWorker`, which proves the worker loads in compiled binaries and the npm bundle.
8
+ */
9
+
10
+ import { Database } from "bun:sqlite";
11
+ import { spotlightDashboard } from "./spotlight-aggregator";
12
+
13
+ export type SpotlightWorkerRequest =
14
+ | { kind: "build"; dbPath: string; range: string | null; agent: string | null }
15
+ | { kind: "ping" };
16
+
17
+ export type SpotlightWorkerResponse =
18
+ | { ok: true; kind: "build"; json: string }
19
+ | { ok: true; kind: "pong" }
20
+ | { ok: false; error: string };
21
+
22
+ declare const self: Worker & {
23
+ onmessage: ((event: MessageEvent<SpotlightWorkerRequest>) => void) | null;
24
+ };
25
+
26
+ self.onmessage = event => {
27
+ const request = event.data;
28
+ if (request.kind === "ping") {
29
+ self.postMessage({ ok: true, kind: "pong" } satisfies SpotlightWorkerResponse);
30
+ return;
31
+ }
32
+ try {
33
+ const database = new Database(request.dbPath, { readonly: true });
34
+ try {
35
+ database.run("PRAGMA busy_timeout = 5000");
36
+ const stats = database.transaction(() => spotlightDashboard(database, request.range, request.agent))();
37
+ self.postMessage({ ok: true, kind: "build", json: JSON.stringify(stats) } satisfies SpotlightWorkerResponse);
38
+ } finally {
39
+ database.close();
40
+ }
41
+ } catch (err) {
42
+ const error = err instanceof Error ? (err.stack ?? err.message) : String(err);
43
+ self.postMessage({ ok: false, error } satisfies SpotlightWorkerResponse);
44
+ }
45
+ };