-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathframework.test.ts
More file actions
1226 lines (1077 loc) · 34 KB
/
framework.test.ts
File metadata and controls
1226 lines (1077 loc) · 34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
beforeAll,
expect,
describe,
test,
beforeEach,
afterEach,
vi,
} from "vitest";
import {
defaultErrorScoreHandler,
Eval,
EvalScorer,
runEvaluator,
} from "./framework";
import { _exportsForTestingOnly, BraintrustState } from "./logger";
import { configureNode } from "./node";
import type { ProgressReporter } from "./reporters/types";
import { InternalAbortError } from "./util";
beforeAll(() => {
configureNode();
});
class NoopProgressReporter implements ProgressReporter {
public start() {}
public stop() {}
public increment() {}
}
test("meta (write) is passed to task", async () => {
const metadata = {
bar: "baz",
foo: "bar",
};
const out = await runEvaluator(
null,
{
projectName: "proj",
evalName: "eval",
data: [{ input: 1, metadata }],
task: async (input: number, { meta }) => {
meta({
foo: "barbar",
});
return input * 2;
},
scores: [],
},
new NoopProgressReporter(),
[],
undefined,
undefined,
true,
);
// @ts-expect-error metadata is not typed if the experiment is missing
expect(out.results[0].metadata).toEqual({
bar: "baz",
foo: "barbar",
});
});
test("metadata (read/write) is passed to task", async () => {
const metadata = {
bar: "baz",
foo: "bar",
};
let passedIn: Record<string, unknown> | null = null;
const out = await runEvaluator(
null,
{
projectName: "proj",
evalName: "eval",
data: [{ input: 1, metadata }],
task: async (input: number, { metadata: m }) => {
passedIn = { ...m };
// modify the metadata object
m.foo = "barbar";
return input * 2;
},
scores: [],
},
new NoopProgressReporter(),
[],
undefined,
undefined,
true,
);
expect(passedIn).toEqual(metadata);
// @ts-expect-error metadata is not typed if the experiment is missing
expect(out.results[0].metadata).toEqual({
bar: "baz",
foo: "barbar",
});
});
test("expected (read/write) is passed to task", async () => {
const expected = {
bar: "baz",
foo: "bar",
};
let passedIn: Record<string, unknown> | null = null;
const out = await runEvaluator(
null,
{
projectName: "proj",
evalName: "eval",
data: [{ input: 1, expected }],
task: async (input: number, { expected: e }) => {
passedIn = { ...e };
// modify the expected object
e.foo = "barbar";
return input * 2;
},
scores: [],
},
new NoopProgressReporter(),
[],
undefined,
undefined,
true,
);
expect(passedIn).toEqual({
bar: "baz",
foo: "bar",
});
// @ts-expect-error metadata is not typed if the experiment is missing
expect(out.results[0].expected).toEqual({
bar: "baz",
foo: "barbar",
});
});
function makeTestScorer(
name: string,
willError?: boolean,
): EvalScorer<any, any, any, any> {
return () => {
if (willError) {
throw new Error("scorer errored");
}
return {
name,
score: 1,
};
};
}
describe("runEvaluator", () => {
describe("errors", () => {
test("task errors generate no scores", async () => {
const out = await runEvaluator(
null,
{
projectName: "proj",
evalName: "eval",
data: [{ input: 1 }],
task: async () => {
throw new Error("test error");
},
scores: Array.from({ length: 3 }, (_, i) =>
makeTestScorer(`scorer_${i}`),
),
},
new NoopProgressReporter(),
[],
undefined,
true,
);
expect(out.results.every((r) => Object.keys(r.scores).length === 0)).toBe(
true,
);
});
describe("errorScoreHandler", () => {
describe("default function", () => {
test("task errors generate 0 scores for all scorers", async () => {
const out = await runEvaluator(
null,
{
projectName: "proj",
evalName: "eval",
data: [{ input: 1 }],
task: async () => {
throw new Error("test error");
},
scores: Array.from({ length: 3 }, (_, i) =>
makeTestScorer(`scorer_${i}`),
),
errorScoreHandler: defaultErrorScoreHandler,
},
new NoopProgressReporter(),
[],
undefined,
true,
);
expect(
out.results.every(
(r) =>
Object.keys(r.scores).length === 3 &&
Object.values(r.scores).every((v) => v === 0),
),
).toBe(true);
});
test("scorer errors generate 0 scores for all errored scorers", async () => {
const out = await runEvaluator(
null,
{
projectName: "proj",
evalName: "eval",
data: [{ input: 1 }],
task: async () => {
return "valid output";
},
scores: Array.from({ length: 3 }, (_, i) =>
makeTestScorer(`scorer_${i}`, i === 0),
),
errorScoreHandler: defaultErrorScoreHandler,
},
new NoopProgressReporter(),
[],
undefined,
true,
);
expect(
out.results.every(
(r) =>
Object.keys(r.scores).length === 3 &&
r.scores.scorer_0 === 0 &&
r.scores.scorer_1 === 1 &&
r.scores.scorer_2 === 1,
),
).toBe(true);
});
});
describe("custom function", () => {
test("noop function generates no scores", async () => {
const out = await runEvaluator(
null,
{
projectName: "proj",
evalName: "eval",
data: [{ input: 1 }],
task: async () => {
throw new Error("test error");
},
scores: Array.from({ length: 3 }, (_, i) =>
makeTestScorer(`scorer_${i}`),
),
errorScoreHandler: () => undefined,
},
new NoopProgressReporter(),
[],
undefined,
true,
);
expect(
out.results.every((r) => Object.keys(r.scores).length === 0),
).toBe(true);
});
test("function can generate arbitrary scores", async () => {
const out = await runEvaluator(
null,
{
projectName: "proj",
evalName: "eval",
data: [{ input: 1 }],
task: async () => {
throw new Error("test error");
},
scores: Array.from({ length: 3 }, (_, i) =>
makeTestScorer(`scorer_${i}`),
),
errorScoreHandler: () => ({ error_score: 1 }),
},
new NoopProgressReporter(),
[],
undefined,
true,
);
expect(
out.results.every(
(r) =>
Object.keys(r.scores).length === 1 &&
r.scores.error_score === 1,
),
).toBe(true);
});
});
});
});
describe("aborts", () => {
beforeEach(() => {
vi.useFakeTimers();
});
afterEach(() => {
vi.clearAllTimers();
vi.useRealTimers();
});
test("runEvaluator rejects on timeout and kills remaining tasks", async () => {
const taskStarts: Set<number> = new Set();
const taskCompletions: Set<number> = new Set();
const runExpect = expect(
runEvaluator(
null,
{
projectName: "proj",
evalName: "eval",
data: Array.from({ length: 10 }, (_, i) => ({
input: i,
expected: i * 2,
})),
task: async (input: number) => {
taskStarts.add(input);
if (input > 2) {
await new Promise((r) => setTimeout(r, 100));
}
taskCompletions.add(input);
return input * 2;
},
scores: [],
timeout: 10,
maxConcurrency: 1,
},
new NoopProgressReporter(),
[],
undefined,
),
).rejects.toThrow(new InternalAbortError("Evaluator timed out"));
await vi.advanceTimersByTimeAsync(10);
await runExpect;
// first 3 tasks complete and 4th task was started but not completed before timeout
expect(taskStarts).toEqual(new Set([0, 1, 2, 3]));
expect(taskCompletions).toEqual(new Set([0, 1, 2]));
await vi.advanceTimersByTimeAsync(200);
// no other tasks are started after evaluator is aborted and the 4th in-flight task completes
expect(taskStarts).toEqual(new Set([0, 1, 2, 3]));
expect(taskCompletions).toEqual(new Set([0, 1, 2, 3]));
expect(vi.getTimerCount()).toBe(0);
});
test("runEvaluator rejects on abort signal and kills remaining tasks", async () => {
const taskStarts: Set<number> = new Set();
const taskCompletions: Set<number> = new Set();
const abortController = new AbortController();
const runExpect = expect(
runEvaluator(
null,
{
projectName: "proj",
evalName: "eval",
data: Array.from({ length: 10 }, (_, i) => ({
input: i,
expected: i * 2,
})),
task: async (input: number) => {
taskStarts.add(input);
if (input > 2) {
await new Promise((r) => setTimeout(r, 100));
}
taskCompletions.add(input);
return input * 2;
},
scores: [],
signal: abortController.signal,
maxConcurrency: 1,
},
new NoopProgressReporter(),
[],
undefined,
),
).rejects.toThrow(new InternalAbortError("Evaluator aborted"));
await vi.advanceTimersByTimeAsync(10);
abortController.abort();
await runExpect;
// first 3 tasks complete and 4th task was started but not completed before abort
expect(taskStarts).toEqual(new Set([0, 1, 2, 3]));
expect(taskCompletions).toEqual(new Set([0, 1, 2]));
await vi.advanceTimersByTimeAsync(200);
// no other tasks are started after evaluator is aborted and the 4th in-flight task completes
expect(taskStarts).toEqual(new Set([0, 1, 2, 3]));
expect(taskCompletions).toEqual(new Set([0, 1, 2, 3]));
expect(vi.getTimerCount()).toBe(0);
});
test("runEvaluator works with no timeout or abort signal", async () => {
const run = runEvaluator(
null,
{
projectName: "proj",
evalName: "eval",
data: [{ input: 1, expected: 2 }],
task: async (input: number) => {
await new Promise((r) => setTimeout(r, 100));
return input * 2;
},
scores: [],
},
new NoopProgressReporter(),
[],
undefined,
);
await vi.advanceTimersByTimeAsync(100);
await run;
expect(vi.getTimerCount()).toBe(0);
});
});
});
test("trialIndex is passed to task", async () => {
const trialIndices: number[] = [];
const { results } = await runEvaluator(
null,
{
projectName: "proj",
evalName: "eval",
data: [{ input: 1, expected: 2 }],
task: async (input: number, { trialIndex }) => {
trialIndices.push(trialIndex);
return input * 2;
},
scores: [],
trialCount: 3,
},
new NoopProgressReporter(),
[],
undefined,
undefined,
true,
);
// Should have 3 results (one for each trial)
expect(results).toHaveLength(3);
// Should have captured 3 trial indices
expect(trialIndices).toHaveLength(3);
expect(trialIndices.sort()).toEqual([0, 1, 2]);
// All results should be correct
results.forEach((result) => {
expect(result.input).toBe(1);
expect(result.expected).toBe(2);
expect(result.output).toBe(2);
expect(result.error).toBeUndefined();
});
});
test("trialIndex with multiple inputs", async () => {
const trialData: Array<{ input: number; trialIndex: number }> = [];
const { results } = await runEvaluator(
null,
{
projectName: "proj",
evalName: "eval",
data: [
{ input: 1, expected: 2 },
{ input: 2, expected: 4 },
],
task: async (input: number, { trialIndex }) => {
trialData.push({ input, trialIndex });
return input * 2;
},
scores: [],
trialCount: 2,
},
new NoopProgressReporter(),
[],
undefined,
undefined,
true,
);
// Should have 4 results total (2 inputs × 2 trials)
expect(results).toHaveLength(4);
expect(trialData).toHaveLength(4);
// Group by input to verify trial indices
const input1Trials = trialData
.filter((d) => d.input === 1)
.map((d) => d.trialIndex)
.sort();
const input2Trials = trialData
.filter((d) => d.input === 2)
.map((d) => d.trialIndex)
.sort();
// Each input should have been run with trial indices 0 and 1
expect(input1Trials).toEqual([0, 1]);
expect(input2Trials).toEqual([0, 1]);
});
test("per-input trialCount overrides global trialCount", async () => {
const trialData: Array<{ input: number; trialIndex: number }> = [];
const { results } = await runEvaluator(
null,
{
projectName: "proj",
evalName: "eval",
data: [
{ input: 1, expected: 2 },
{ input: 2, expected: 4, trialCount: 5 },
{ input: 3, expected: 6, trialCount: 1 },
],
task: async (input: number, { trialIndex }) => {
trialData.push({ input, trialIndex });
return input * 2;
},
scores: [],
trialCount: 2,
},
new NoopProgressReporter(),
[],
undefined,
undefined,
true,
);
expect(results).toHaveLength(8);
expect(trialData).toHaveLength(8);
// Input 1: should use global trialCount (2 trials)
const input1Trials = trialData
.filter((d) => d.input === 1)
.map((d) => d.trialIndex)
.sort();
expect(input1Trials).toEqual([0, 1]);
// Input 2: should use per-input trialCount (5 trials)
const input2Trials = trialData
.filter((d) => d.input === 2)
.map((d) => d.trialIndex)
.sort();
expect(input2Trials).toEqual([0, 1, 2, 3, 4]);
// Input 3: should use per-input trialCount (1 trial)
const input3Trials = trialData
.filter((d) => d.input === 3)
.map((d) => d.trialIndex)
.sort();
expect(input3Trials).toEqual([0]);
});
test("per-input trialCount works without global trialCount", async () => {
const trialData: Array<{ input: number; trialIndex: number }> = [];
const { results } = await runEvaluator(
null,
{
projectName: "proj",
evalName: "eval",
data: [
{ input: 1, expected: 2 },
{ input: 2, expected: 4, trialCount: 3 },
],
task: async (input: number, { trialIndex }) => {
trialData.push({ input, trialIndex });
return input * 2;
},
scores: [],
},
new NoopProgressReporter(),
[],
undefined,
undefined,
true,
);
expect(results).toHaveLength(4);
expect(trialData).toHaveLength(4);
const input1Trials = trialData
.filter((d) => d.input === 1)
.map((d) => d.trialIndex)
.sort();
expect(input1Trials).toEqual([0]);
const input2Trials = trialData
.filter((d) => d.input === 2)
.map((d) => d.trialIndex)
.sort();
expect(input2Trials).toEqual([0, 1, 2]);
});
test("Eval with noSendLogs: true runs locally without creating experiment", async () => {
const memoryLogger = _exportsForTestingOnly.useTestBackgroundLogger();
const result = await Eval(
"test-no-logs",
{
data: () => [
{ input: "hello", expected: "hello world" },
{ input: "test", expected: "test world" },
],
task: (input) => input + " world",
scores: [
(args) => ({
name: "exact_match",
score: args.output === args.expected ? 1 : 0,
}),
() => ({ name: "simple_scorer", score: 0.8 }),
],
},
{ noSendLogs: true, returnResults: true },
);
// Verify it returns results
expect(result.results).toHaveLength(2);
expect(result.results[0].input).toBe("hello");
expect(result.results[0].output).toBe("hello world");
expect(result.results[0].scores.exact_match).toBe(1);
expect(result.results[0].scores.simple_scorer).toBe(0.8);
expect(result.results[1].input).toBe("test");
expect(result.results[1].output).toBe("test world");
expect(result.results[1].scores.exact_match).toBe(1);
expect(result.results[1].scores.simple_scorer).toBe(0.8);
// Verify it builds a local summary (no experimentUrl means local run)
expect(result.summary.projectName).toBe("test-no-logs");
expect(result.summary.experimentUrl).toBeUndefined();
expect(result.summary.scores.exact_match.score).toBe(1);
expect(result.summary.scores.simple_scorer.score).toBe(0.8);
// Most importantly: verify that no logs were sent
await memoryLogger.flush();
expect(await memoryLogger.drain()).toHaveLength(0);
});
test("Eval with returnResults: false produces empty results but valid summary", async () => {
const result = await Eval(
"test-no-results",
{
projectName: "test-no-results-project",
data: [
{ input: "hello", expected: "hello world" },
{ input: "test", expected: "test world" },
{ input: "foo", expected: "foo bar" },
],
task: (input) => input + " world",
scores: [
(args) => ({
name: "exact_match",
score: args.output === args.expected ? 1 : 0,
}),
() => ({ name: "length_score", score: 0.75 }),
() => ({ name: "quality_score", score: 0.9 }),
],
},
{ noSendLogs: true, returnResults: false },
);
// Verify that results array is empty (memory not retained)
expect(result.results).toHaveLength(0);
// Verify that summary still has accurate aggregate scores
expect(result.summary.projectName).toBe("test-no-results-project");
expect(result.summary.experimentUrl).toBeUndefined();
// exact_match: 2 out of 3 match = 2/3 ≈ 0.6667
expect(result.summary.scores.exact_match.score).toBeCloseTo(2 / 3, 4);
// length_score: always 0.75, so average is 0.75
expect(result.summary.scores.length_score.score).toBe(0.75);
// quality_score: always 0.9, so average is 0.9
expect(result.summary.scores.quality_score.score).toBe(0.9);
});
test("Eval with returnResults: true collects all results", async () => {
const result = await Eval(
"test-with-results",
{
projectName: "test-with-results-project",
data: [
{ input: "hello", expected: "hello world" },
{ input: "test", expected: "test world" },
],
task: (input) => input + " world",
scores: [
(args) => ({
name: "exact_match",
score: args.output === args.expected ? 1 : 0,
}),
],
},
{ noSendLogs: true, returnResults: true },
);
// Verify that results are collected
expect(result.results).toHaveLength(2);
expect(result.results[0].input).toBe("hello");
expect(result.results[0].output).toBe("hello world");
expect(result.results[0].scores.exact_match).toBe(1);
expect(result.results[1].input).toBe("test");
expect(result.results[1].output).toBe("test world");
expect(result.results[1].scores.exact_match).toBe(1);
// Summary should also be correct
expect(result.summary.scores.exact_match.score).toBe(1);
});
test("tags can be appended and logged to root span", async () => {
await _exportsForTestingOnly.simulateLoginForTests();
const memoryLogger = _exportsForTestingOnly.useTestBackgroundLogger();
const experiment =
_exportsForTestingOnly.initTestExperiment("js-tags-append");
const initialTags = ["cookies n cream"];
const appendedTags = ["chocolate", "vanilla", "strawberry"];
const expectedTags = [
"cookies n cream",
"chocolate",
"vanilla",
"strawberry",
];
const result = await runEvaluator(
experiment,
{
projectName: "proj",
evalName: "js-tags-append",
data: [{ input: "hello", expected: "hello world", tags: initialTags }],
task: (input, hooks) => {
for (const t of appendedTags) hooks.tags.push(t);
return input;
},
scores: [() => ({ name: "simple_scorer", score: 0.8 })],
summarizeScores: false,
},
new NoopProgressReporter(),
[],
undefined,
undefined,
true,
);
expect(result.results[0].tags).toEqual(expectedTags);
await memoryLogger.flush();
const logs = await memoryLogger.drain();
const rootSpans = logs.filter((l: any) => !l["span_parents"]);
expect(rootSpans).toHaveLength(1);
expect((rootSpans[0] as any).tags).toEqual(expectedTags);
});
test.each([
{
title: "undefined list returns undefined for tags",
providedTags: undefined,
expectedTags: undefined,
},
{
title: "empty list returns undefined for tags",
providedTags: [],
expectedTags: undefined,
},
{
title: "tags can be set to a list",
providedTags: ["chocolate", "vanilla", "strawberry"],
expectedTags: ["chocolate", "vanilla", "strawberry"],
},
])("$title", async ({ providedTags, expectedTags }) => {
await _exportsForTestingOnly.simulateLoginForTests();
const memoryLogger = _exportsForTestingOnly.useTestBackgroundLogger();
const experiment = _exportsForTestingOnly.initTestExperiment("js-tags-list");
const result = await runEvaluator(
experiment,
{
projectName: "proj",
evalName: "js-tags-list",
data: [{ input: "hello", expected: "hello world" }],
task: (input, hooks) => {
hooks.tags = providedTags;
return input;
},
scores: [() => ({ name: "simple_scorer", score: 0.8 })],
summarizeScores: false,
},
new NoopProgressReporter(),
[],
undefined,
undefined,
true,
);
expect(result.results[0].tags).toEqual(expectedTags);
await memoryLogger.flush();
const logs = await memoryLogger.drain();
const rootSpans = logs.filter((l: any) => !l["span_parents"]);
expect(rootSpans).toHaveLength(1);
expect((rootSpans[0] as any).tags).toEqual(expectedTags);
});
test("tags are persisted with a failing scorer", async () => {
await _exportsForTestingOnly.simulateLoginForTests();
const memoryLogger = _exportsForTestingOnly.useTestBackgroundLogger();
const experiment = _exportsForTestingOnly.initTestExperiment("js-tags-list");
const expectedTags = ["chocolate", "vanilla", "strawberry"];
const result = await runEvaluator(
experiment,
{
projectName: "proj",
evalName: "js-tags-list",
data: [{ input: "hello", expected: "hello world" }],
task: (input, hooks) => {
hooks.tags = expectedTags;
return input;
},
scores: [
() => ({ name: "simple_scorer", score: 0.8 }),
() => {
throw new Error("test error");
},
],
summarizeScores: false,
},
new NoopProgressReporter(),
[],
undefined,
undefined,
true,
);
expect(result.results[0].tags).toEqual(expectedTags);
await memoryLogger.flush();
const logs = await memoryLogger.drain();
const rootSpans = logs.filter((l: any) => !l["span_parents"]);
expect(rootSpans).toHaveLength(1);
expect((rootSpans[0] as any).tags).toEqual(expectedTags);
});
test("tags remain empty when not set", async () => {
await _exportsForTestingOnly.simulateLoginForTests();
const memoryLogger = _exportsForTestingOnly.useTestBackgroundLogger();
const experiment =
_exportsForTestingOnly.initTestExperiment("js-tags-append");
const result = await runEvaluator(
experiment,
{
projectName: "proj",
evalName: "js-tags-append",
data: [{ input: "hello", expected: "hello world" }],
task: (input, hooks) => {
return input;
},
scores: [() => ({ name: "simple_scorer", score: 0.8 })],
summarizeScores: false,
},
new NoopProgressReporter(),
[],
undefined,
undefined,
true,
);
expect(result.results[0].tags).toEqual(undefined);
await memoryLogger.flush();
const logs = await memoryLogger.drain();
const rootSpans = logs.filter((l: any) => !l["span_parents"]);
expect(rootSpans).toHaveLength(1);
expect((rootSpans[0] as any).tags).toEqual(undefined);
});
test("scorer spans have purpose='scorer' attribute", async () => {
await _exportsForTestingOnly.simulateLoginForTests();
const memoryLogger = _exportsForTestingOnly.useTestBackgroundLogger();
const experiment =
_exportsForTestingOnly.initTestExperiment("js-scorer-purpose");
const result = await runEvaluator(
experiment,
{
projectName: "test-scorer-purpose",
evalName: "scorer-purpose-eval",
data: [{ input: "hello", expected: "hello" }],
task: async (input: string) => input,
scores: [
(args: { input: string; output: string; expected: string }) => ({
name: "simple_scorer",
score: args.output === args.expected ? 1 : 0,
}),
],
},
new NoopProgressReporter(),
[],
undefined,
undefined,
true,
);
expect(result.results).toHaveLength(1);
expect(result.results[0].scores.simple_scorer).toBe(1);
await memoryLogger.flush();
const logs = await memoryLogger.drain();
// Find scorer spans (type="score")
const scorerSpans = logs.filter(
(l: any) => l["span_attributes"]?.["type"] === "score",
);
expect(scorerSpans).toHaveLength(1);
// Verify the scorer span has purpose='scorer'
expect((scorerSpans[0] as any).span_attributes.purpose).toBe("scorer");
// Verify that non-scorer spans (task, eval) do NOT have purpose='scorer'
const nonScorerSpans = logs.filter(
(l: any) => l["span_attributes"]?.["type"] !== "score",
);
expect(nonScorerSpans.length).toBeGreaterThan(0);
for (const span of nonScorerSpans) {
expect((span as any).span_attributes?.purpose).not.toBe("scorer");
}
_exportsForTestingOnly.clearTestBackgroundLogger();
_exportsForTestingOnly.simulateLogoutForTests();
});
// ========== framework2 metadata tests ==========
import { z } from "zod/v3";
import { projects, CodePrompt } from "./framework2";
describe("framework2 metadata support", () => {
describe("CodeFunction metadata", () => {
test("tool stores metadata correctly", () => {
const project = projects.create({ name: "test-project" });
const metadata = { version: "1.0", author: "test" };
const tool = project.tools.create({
handler: (x: number) => x * 2,
name: "test-tool",
parameters: z.object({ x: z.number() }),
metadata,
});
expect(tool.metadata).toEqual(metadata);
expect(tool.name).toBe("test-tool");
expect(tool.slug).toBe("test-tool");
});
test("tool works without metadata", () => {
const project = projects.create({ name: "test-project" });
const tool = project.tools.create({
handler: (x: number) => x * 2,
name: "test-tool",
parameters: z.object({ x: z.number() }),
});
expect(tool.metadata).toBeUndefined();
});
});
describe("CodePrompt metadata", () => {
test("prompt stores metadata correctly", () => {
const project = projects.create({ name: "test-project" });
const metadata = { category: "greeting", priority: "high" };