@crowandraven/evalkeeper 0.4.1 → 0.7.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.
Files changed (101) hide show
  1. package/README.md +7 -0
  2. package/dist/activity.d.ts +58 -0
  3. package/dist/activity.js +125 -0
  4. package/dist/activity.js.map +1 -0
  5. package/dist/assertExpect.d.ts +52 -0
  6. package/dist/assertExpect.js +104 -0
  7. package/dist/assertExpect.js.map +1 -0
  8. package/dist/blind.d.ts +79 -0
  9. package/dist/blind.js +113 -0
  10. package/dist/blind.js.map +1 -0
  11. package/dist/cli/addPages.d.ts +34 -0
  12. package/dist/cli/addPages.js +91 -11
  13. package/dist/cli/addPages.js.map +1 -1
  14. package/dist/cli/main.d.ts +1 -1
  15. package/dist/cli/main.js +9 -0
  16. package/dist/cli/main.js.map +1 -1
  17. package/dist/compare.d.ts +38 -0
  18. package/dist/compare.js +62 -0
  19. package/dist/compare.js.map +1 -1
  20. package/dist/glossary.d.ts +20 -0
  21. package/dist/glossary.js +20 -0
  22. package/dist/glossary.js.map +1 -1
  23. package/dist/health.js +5 -3
  24. package/dist/health.js.map +1 -1
  25. package/dist/importCases.d.ts +76 -5
  26. package/dist/importCases.js +114 -14
  27. package/dist/importCases.js.map +1 -1
  28. package/dist/index.d.ts +4 -0
  29. package/dist/index.js +4 -0
  30. package/dist/index.js.map +1 -1
  31. package/dist/memoryStore.js +3 -1
  32. package/dist/memoryStore.js.map +1 -1
  33. package/dist/readCheck.d.ts +116 -0
  34. package/dist/readCheck.js +321 -0
  35. package/dist/readCheck.js.map +1 -0
  36. package/dist/runner.d.ts +7 -0
  37. package/dist/runner.js +25 -3
  38. package/dist/runner.js.map +1 -1
  39. package/dist/settings.d.ts +81 -3
  40. package/dist/settings.js +160 -23
  41. package/dist/settings.js.map +1 -1
  42. package/dist/store.d.ts +10 -3
  43. package/dist/suggest.d.ts +10 -1
  44. package/dist/suggest.js +22 -4
  45. package/dist/suggest.js.map +1 -1
  46. package/dist/suiteContract.d.ts +17 -0
  47. package/dist/suiteContract.js +69 -0
  48. package/dist/suiteContract.js.map +1 -0
  49. package/dist/suites/crisisRisk.d.ts +83 -0
  50. package/dist/suites/crisisRisk.js +176 -0
  51. package/dist/suites/crisisRisk.js.map +1 -0
  52. package/dist/suites/crisisRiskCases.d.ts +40 -0
  53. package/dist/suites/crisisRiskCases.js +179 -0
  54. package/dist/suites/crisisRiskCases.js.map +1 -0
  55. package/dist/suites/index.d.ts +9 -0
  56. package/dist/suites/index.js +10 -0
  57. package/dist/suites/index.js.map +1 -0
  58. package/dist/testing.d.ts +140 -8
  59. package/dist/testing.js +420 -125
  60. package/dist/testing.js.map +1 -1
  61. package/dist/types.d.ts +92 -0
  62. package/dist/types.js +68 -0
  63. package/dist/types.js.map +1 -1
  64. package/dist/weekly.d.ts +21 -3
  65. package/dist/weekly.js +18 -1
  66. package/dist/weekly.js.map +1 -1
  67. package/package.json +5 -1
  68. package/src/activity.ts +154 -0
  69. package/src/assertExpect.ts +168 -0
  70. package/src/blind.ts +138 -0
  71. package/src/cli/addPages.ts +119 -17
  72. package/src/cli/main.ts +11 -0
  73. package/src/compare.ts +85 -0
  74. package/src/glossary.ts +36 -0
  75. package/src/health.ts +5 -3
  76. package/src/importCases.ts +172 -33
  77. package/src/index.ts +4 -0
  78. package/src/memoryStore.ts +2 -1
  79. package/src/readCheck.ts +458 -0
  80. package/src/runner.ts +33 -4
  81. package/src/settings.ts +192 -26
  82. package/src/store.ts +11 -3
  83. package/src/suggest.ts +33 -4
  84. package/src/suiteContract.ts +101 -0
  85. package/src/suites/crisisRisk.ts +250 -0
  86. package/src/suites/crisisRiskCases.ts +205 -0
  87. package/src/suites/index.ts +9 -0
  88. package/src/testing.ts +564 -127
  89. package/src/types.ts +141 -0
  90. package/src/weekly.ts +39 -3
  91. package/templates/app/evals/[suite]/compare/page.tsx +375 -0
  92. package/templates/app/evals/[suite]/page.tsx +55 -19
  93. package/templates/app/evals/[suite]/rate/page.tsx +133 -0
  94. package/templates/app/evals/[suite]/runs/[runId]/page.tsx +12 -0
  95. package/templates/app/evals/[suite]/side-by-side/page.tsx +300 -0
  96. package/templates/components/evalkeeper/DisagreementChip.tsx +35 -0
  97. package/templates/components/evalkeeper/RollBack.tsx +21 -1
  98. package/templates/components/evalkeeper/SettingsHistory.tsx +20 -2
  99. package/templates/components/evalkeeper/WeeklyCheck.tsx +34 -2
  100. package/templates/lib/evalkeeper/actions.ts +68 -4
  101. package/templates/lib/evalkeeper/weekly.ts +27 -4
package/src/testing.ts CHANGED
@@ -1,36 +1,185 @@
1
1
  /**
2
- * The contracts every store must meet, as Vitest tests.
2
+ * The contracts every store and set of suites must meet, as tests. They
3
+ * register with Vitest by default, or with the test functions you pass
4
+ * (`node:test` with `assertExpect`, say), so Vitest stays optional.
3
5
  *
4
6
  * @module evalkeeper/testing
5
7
  */
6
- import { describe, expect, it } from "vitest";
7
8
  import { z } from "zod";
9
+ import type { ContractExpect } from "./assertExpect.js";
10
+ import { BLIND_RATER, blindRating, nextToRate, skipMark } from "./blind.js";
8
11
  import type { FeedbackStore, NewRating } from "./feedback.js";
12
+ import { confirmedLabel } from "./labels.js";
9
13
  import { createRunner } from "./runner.js";
10
14
  import {
15
+ CHANGE_KINDS,
11
16
  SettingsConflict,
12
17
  type Settings,
13
18
  type SettingsStore,
14
19
  } from "./settings.js";
15
20
  import type { EvalStore, NewCase } from "./store.js";
16
- import type { Suite } from "./types.js";
21
+ import { suiteContractProblems } from "./suiteContract.js";
22
+ import type { AnySuite, Suite } from "./types.js";
23
+ import { readCheckSummary, type ReadCheckReport } from "./readCheck.js";
24
+
25
+ export {
26
+ assertExpect,
27
+ type ContractExpect,
28
+ type ContractMatchers,
29
+ } from "./assertExpect.js";
30
+
31
+ /**
32
+ * The test functions a contract registers its tests with. Vitest's
33
+ * `describe`, `it`, `expect`, and `afterAll` fit, and so do `node:test`'s
34
+ * `describe`, `it`, and `after` with `assertExpect`.
35
+ */
36
+ export type ContractTest = {
37
+ /** Groups tests, like Vitest's or node:test's `describe`. */
38
+ describe: (name: string, fn: () => void) => unknown;
39
+ /** Adds a test, like Vitest's or node:test's `it`. */
40
+ it: (name: string, fn: () => Promise<void> | void) => unknown;
41
+ /** Checks values: Vitest's `expect`, or `assertExpect` on node:assert. */
42
+ expect: ContractExpect;
43
+ /**
44
+ * Runs once after a group's tests, like Vitest's `afterAll` or
45
+ * node:test's `after`. Needed only with `cleanup`.
46
+ */
47
+ afterAll?: (fn: () => Promise<void> | void) => unknown;
48
+ };
49
+
50
+ /**
51
+ * Vitest's test functions, or why they couldn't be loaded. A dynamic
52
+ * import (awaited as this module loads), so this module loads without
53
+ * Vitest when you pass your own test functions.
54
+ */
55
+ const vitest: ContractTest | Error = await import("vitest").then(
56
+ (v) => ({
57
+ describe: v.describe,
58
+ it: v.it,
59
+ expect: v.expect,
60
+ afterAll: v.afterAll,
61
+ }),
62
+ (e: unknown) => (e instanceof Error ? e : new Error(String(e))),
63
+ );
64
+
65
+ /** The test functions to register with: the ones given, else Vitest's. */
66
+ function testFunctions(given: ContractTest | undefined): ContractTest {
67
+ if (given) return given;
68
+ if (!(vitest instanceof Error)) return vitest;
69
+ throw new Error(
70
+ `Vitest couldn't be loaded (${vitest.message}), so pass your own test functions: { test: { describe, it, expect: assertExpect } } with describe and it from "node:test", and assertExpect from this module.`,
71
+ );
72
+ }
73
+
74
+ /** Options every contract takes. */
75
+ export type ContractOptions = {
76
+ /** The test functions to use. Vitest's by default. */
77
+ test?: ContractTest;
78
+ };
17
79
 
18
80
  /**
19
- * The contract every EvalStore must meet, as Vitest tests. Run it against
20
- * your store to know the runner will work on it. `make` must return an
21
- * empty store each time it's called.
81
+ * Options for running a store contract on a database that holds other
82
+ * rows too, such as a shared development database.
83
+ */
84
+ export type ScopedContractOptions = ContractOptions & {
85
+ /**
86
+ * A prefix for every suite and feature the contract writes (each test
87
+ * adds its own after it), so its rows never mix with others and `make`
88
+ * needn't return an empty store. Without it, `make` must return an
89
+ * empty store every time.
90
+ */
91
+ scope?: string;
92
+ /**
93
+ * Deletes the rows whose suite or feature starts with the scope, once
94
+ * after the contract's tests (and so also any left by an earlier run
95
+ * that stopped early). Needs `scope`, and `afterAll` among the test
96
+ * functions. For Prisma, `deleteScopedRows` from
97
+ * `@crowandraven/evalkeeper-prisma`.
98
+ */
99
+ cleanup?: (scope: string) => Promise<unknown>;
100
+ };
101
+
102
+ /**
103
+ * A namer for each test: in a scoped contract, a fresh prefix per test
104
+ * (so tests don't see each other's rows); otherwise names as they are.
105
+ */
106
+ function scopeNames(scope: string | undefined): () => (name: string) => string {
107
+ if (scope === undefined) return () => (name) => name;
108
+ if (!scope.trim())
109
+ throw new Error(
110
+ 'A contract\'s scope must be a prefix with some text in it, such as "contract-": an empty one would match every row.',
111
+ );
112
+ const run = Date.now().toString(36);
113
+ let n = 0;
114
+ return () => {
115
+ const prefix = `${scope}${run}-${(n++).toString(36)}-`;
116
+ return (name) => prefix + name;
117
+ };
118
+ }
119
+
120
+ /** Registers a scoped contract's cleanup, after checking it can run. */
121
+ function registerCleanup(t: ContractTest, opts: ScopedContractOptions) {
122
+ const { cleanup, scope } = opts;
123
+ if (!cleanup) return;
124
+ if (scope === undefined)
125
+ throw new Error(
126
+ "cleanup needs a scope: it deletes only the rows the scope names. Without a scope, return an empty store from make instead.",
127
+ );
128
+ if (!t.afterAll)
129
+ throw new Error(
130
+ "cleanup runs after the contract's tests, so pass afterAll (node:test's after) with your test functions.",
131
+ );
132
+ t.afterAll(async () => {
133
+ await cleanup(scope);
134
+ });
135
+ }
136
+
137
+ /**
138
+ * Options for a store contract, for a store on tables that lack an
139
+ * optional column.
140
+ */
141
+ export type StoreContractOptions = ScopedContractOptions & {
142
+ /**
143
+ * Settings the store has no column for. The contract then checks the
144
+ * store refuses a value for them (rather than losing it) and reads
145
+ * them as null.
146
+ */
147
+ without?: ("temperature" | "maxOutputTokens")[];
148
+ };
149
+
150
+ /**
151
+ * The contract every EvalStore must meet. Run it against your store to
152
+ * know the runner will work on it. `make` must return an empty store each
153
+ * time it's called, unless `opts.scope` is set: then every suite the
154
+ * contract writes (and every request hash it picks) starts with the
155
+ * scope, the tests never look past their own rows, and `opts.cleanup`
156
+ * deletes those suites' cases, answers, tests, and outputs afterward, so
157
+ * it can run on a database that holds other rows. `opts.without` names
158
+ * run settings its tables have no column for; `opts.test` passes test
159
+ * functions other than Vitest's.
22
160
  *
23
161
  * @example
24
162
  * ```ts
25
163
  * import { describeStoreContract } from "@crowandraven/evalkeeper/testing";
26
164
  *
27
165
  * describeStoreContract("my store", () => myStore(freshDatabase()));
166
+ *
167
+ * // On a database with other rows: only rows starting "contract-" are
168
+ * // written, and cleanup deletes only those.
169
+ * describeStoreContract("our tables", () => prismaStore(prisma, map), {
170
+ * scope: "contract-",
171
+ * cleanup: (scope) => deleteScopedRows(prisma, scope, { map }),
172
+ * });
28
173
  * ```
29
174
  */
30
175
  export function describeStoreContract(
31
176
  name: string,
32
177
  make: () => EvalStore | Promise<EvalStore>,
178
+ opts: StoreContractOptions = {},
33
179
  ) {
180
+ const t = testFunctions(opts.test);
181
+ const { describe, it, expect } = t;
182
+ const names = scopeNames(opts.scope);
34
183
  const newCase = (suite: string, over: Partial<NewCase> = {}): NewCase => ({
35
184
  suite,
36
185
  input: { text: "hello", nested: { n: 1 } },
@@ -66,10 +215,13 @@ export function describeStoreContract(
66
215
  });
67
216
 
68
217
  describe(`EvalStore contract: ${name}`, () => {
218
+ registerCleanup(t, opts);
219
+
69
220
  it("keeps a case's input, tags, and answers as given", async () => {
70
221
  const store = await make();
71
- const c = await store.createCase(newCase("s"));
72
- const [listed] = await store.listCases("s");
222
+ const n = names();
223
+ const c = await store.createCase(newCase(n("s")));
224
+ const [listed] = await store.listCases(n("s"));
73
225
  expect(listed?.id).toBe(c.id);
74
226
  expect(listed?.input).toEqual({ text: "hello", nested: { n: 1 } });
75
227
  expect(listed?.tags).toEqual(["a", "b"]);
@@ -81,27 +233,62 @@ export function describeStoreContract(
81
233
  });
82
234
  });
83
235
 
236
+ it("keeps where a case came from and when, retired ones too", async () => {
237
+ // Drafts from activity and imports skip what they made before by
238
+ // source and sourceRef, so both must read back as written.
239
+ const store = await make();
240
+ const n = names();
241
+ const before = Date.now();
242
+ const c = await store.createCase(
243
+ newCase(n("s"), {
244
+ status: "DRAFT",
245
+ source: "ACTIVITY",
246
+ sourceRef: "answer-42",
247
+ note: "Flagged by an admin.",
248
+ labels: [],
249
+ }),
250
+ );
251
+ await store.setCaseStatus(c.id, "RETIRED");
252
+ const [listed] = await store.listCases(n("s"), {
253
+ includeRetired: true,
254
+ });
255
+ expect(listed).toMatchObject({
256
+ status: "RETIRED",
257
+ source: "ACTIVITY",
258
+ sourceRef: "answer-42",
259
+ note: "Flagged by an admin.",
260
+ labels: [],
261
+ });
262
+ // Within a second either way: some databases round to the second.
263
+ expect(+(listed?.createdAt ?? 0)).toBeGreaterThanOrEqual(before - 1000);
264
+ expect(+(listed?.createdAt ?? 0)).toBeLessThanOrEqual(Date.now() + 1000);
265
+ });
266
+
84
267
  it("lists a suite's cases oldest first, leaving out retired ones", async () => {
85
268
  const store = await make();
86
- const first = await store.createCase(newCase("s"));
269
+ const n = names();
270
+ const first = await store.createCase(newCase(n("s")));
87
271
  // Apart in time: two cases made in the same millisecond have no
88
272
  // oldest one.
89
273
  await new Promise((r) => setTimeout(r, 5));
90
- const second = await store.createCase(newCase("s"));
91
- await store.createCase(newCase("other"));
274
+ const second = await store.createCase(newCase(n("s")));
275
+ await store.createCase(newCase(n("other")));
92
276
  await store.setCaseStatus(first.id, "RETIRED");
93
- expect((await store.listCases("s")).map((c) => c.id)).toEqual([
277
+ expect((await store.listCases(n("s"))).map((c) => c.id)).toEqual([
94
278
  second.id,
95
279
  ]);
96
280
  // On request, retired ones too, still oldest first.
97
281
  expect(
98
- (await store.listCases("s", { includeRetired: true })).map((c) => c.id),
282
+ (await store.listCases(n("s"), { includeRetired: true })).map(
283
+ (c) => c.id,
284
+ ),
99
285
  ).toEqual([first.id, second.id]);
100
286
  });
101
287
 
102
288
  it("adds answers without overwriting, and changes their status", async () => {
103
289
  const store = await make();
104
- const c = await store.createCase(newCase("s", { labels: [] }));
290
+ const n = names();
291
+ const c = await store.createCase(newCase(n("s"), { labels: [] }));
105
292
  const l = await store.addLabel(c.id, {
106
293
  kind: "EXPECTED",
107
294
  status: "PENDING",
@@ -111,54 +298,117 @@ export function describeStoreContract(
111
298
  note: null,
112
299
  });
113
300
  await store.setLabelStatus(l.id, "CONFIRMED");
114
- const [listed] = await store.listCases("s");
301
+ const [listed] = await store.listCases(n("s"));
115
302
  expect(listed?.labels).toHaveLength(1);
116
303
  expect(listed?.labels[0]?.status).toBe("CONFIRMED");
117
304
  });
118
305
 
306
+ it("keeps each rater's blind rating and skip beside others' answers", async () => {
307
+ const store = await make();
308
+ const n = names();
309
+ const c = await store.createCase(newCase(n("s")));
310
+ const before = (await store.listCases(n("s")))[0]?.updatedAt;
311
+ // Apart in time, so a skip that touched the case would show.
312
+ await new Promise((r) => setTimeout(r, 5));
313
+ await store.addLabel(c.id, skipMark("rater-1"));
314
+ const [skipped] = await store.listCases(n("s"));
315
+ expect(skipped?.updatedAt).toEqual(before);
316
+ expect(skipped?.labels.find((l) => l.status === "SKIPPED")).toMatchObject(
317
+ { value: null, raterId: "rater-1", raterRole: BLIND_RATER },
318
+ );
319
+ // The skip is never graded against: the owner's answer stays in use.
320
+ expect(confirmedLabel(skipped?.labels ?? [])?.value).toEqual({
321
+ want: "HELLO",
322
+ });
323
+ expect(nextToRate(await store.listCases(n("s")), "rater-1")).toBeNull();
324
+ expect(nextToRate(await store.listCases(n("s")), "rater-2")?.id).toBe(
325
+ c.id,
326
+ );
327
+
328
+ await store.addLabel(
329
+ c.id,
330
+ blindRating({
331
+ raterId: "rater-2",
332
+ value: { want: "HI" },
333
+ reason: "It greets",
334
+ }),
335
+ );
336
+ const [rated] = await store.listCases(n("s"));
337
+ expect(rated?.labels).toHaveLength(3);
338
+ expect(rated?.labels.find((l) => l.raterId === "rater-2")).toMatchObject({
339
+ status: "CONFIRMED",
340
+ value: { want: "HI" },
341
+ note: "It greets",
342
+ });
343
+ // The owner's answer is still there, unchanged.
344
+ expect(rated?.labels.find((l) => l.raterRole === "OWNER")).toMatchObject({
345
+ status: "CONFIRMED",
346
+ value: { want: "HELLO" },
347
+ });
348
+ expect(nextToRate(await store.listCases(n("s")), "rater-2")).toBeNull();
349
+ });
350
+
119
351
  it("starts runs as running, lists them newest first, and filters", async () => {
120
352
  const store = await make();
121
- const a = await store.createRun(newRun("s"));
353
+ const n = names();
354
+ const a = await store.createRun(newRun(n("s")));
122
355
  await new Promise((r) => setTimeout(r, 5));
123
- const b = await store.createRun(newRun("s"));
356
+ const b = await store.createRun(newRun(n("s")));
124
357
  expect(a.status).toBe("RUNNING");
125
- expect((await store.listRuns("s")).map((r) => r.id)).toEqual([
358
+ expect((await store.listRuns(n("s"))).map((r) => r.id)).toEqual([
126
359
  b.id,
127
360
  a.id,
128
361
  ]);
129
- expect(await store.listRuns("s", { limit: 1 })).toHaveLength(1);
362
+ expect(await store.listRuns(n("s"), { limit: 1 })).toHaveLength(1);
130
363
  await store.updateRun(a.id, { status: "SUCCEEDED" });
131
364
  expect(
132
- (await store.listRuns("s", { status: "SUCCEEDED" })).map((r) => r.id),
365
+ (await store.listRuns(n("s"), { status: "SUCCEEDED" })).map(
366
+ (r) => r.id,
367
+ ),
133
368
  ).toEqual([a.id]);
134
- expect(await store.getRun("missing")).toBeNull();
369
+ expect(await store.getRun(n("missing"))).toBeNull();
135
370
  });
136
371
 
137
- it("keeps the temperature a run was tested at", async () => {
138
- const store = await make();
139
- const warm = await store.createRun({ ...newRun("s"), temperature: 0.7 });
140
- const none = await store.createRun({ ...newRun("s"), temperature: null });
141
- expect((await store.getRun(warm.id))?.temperature).toBe(0.7);
142
- expect((await store.getRun(none.id))?.temperature ?? null).toBeNull();
143
- });
144
-
145
- it("keeps the output cap a run was tested at", async () => {
146
- const store = await make();
147
- const capped = await store.createRun({
148
- ...newRun("s"),
149
- maxOutputTokens: 4000,
150
- });
151
- const none = await store.createRun({
152
- ...newRun("s"),
153
- maxOutputTokens: null,
372
+ const runSettings = [
373
+ ["temperature", "temperature", 0.7],
374
+ ["maxOutputTokens", "output cap", 4000],
375
+ ] as const;
376
+ for (const [field, words, value] of runSettings) {
377
+ if (opts.without?.includes(field)) {
378
+ it(`refuses a ${words} it has no column for, and keeps none`, async () => {
379
+ const store = await make();
380
+ const n = names();
381
+ await expect(
382
+ store.createRun({ ...newRun(n("s")), [field]: value }),
383
+ ).rejects.toThrow(field);
384
+ const none = await store.createRun({
385
+ ...newRun(n("s")),
386
+ [field]: null,
387
+ });
388
+ expect((await store.getRun(none.id))?.[field] ?? null).toBeNull();
389
+ });
390
+ continue;
391
+ }
392
+ it(`keeps the ${words} a run was tested at`, async () => {
393
+ const store = await make();
394
+ const n = names();
395
+ const set = await store.createRun({
396
+ ...newRun(n("s")),
397
+ [field]: value,
398
+ });
399
+ const none = await store.createRun({
400
+ ...newRun(n("s")),
401
+ [field]: null,
402
+ });
403
+ expect((await store.getRun(set.id))?.[field]).toBe(value);
404
+ expect((await store.getRun(none.id))?.[field] ?? null).toBeNull();
154
405
  });
155
- expect((await store.getRun(capped.id))?.maxOutputTokens).toBe(4000);
156
- expect((await store.getRun(none.id))?.maxOutputTokens ?? null).toBeNull();
157
- });
406
+ }
158
407
 
159
408
  it("updates a run only while it has the status it's guarded by", async () => {
160
409
  const store = await make();
161
- const r = await store.createRun(newRun("s"));
410
+ const n = names();
411
+ const r = await store.createRun(newRun(n("s")));
162
412
  await store.updateRun(r.id, { status: "FAILED" }, { status: "RUNNING" });
163
413
  await store.updateRun(
164
414
  r.id,
@@ -170,13 +420,14 @@ export function describeStoreContract(
170
420
 
171
421
  it("stores outputs and scores, and finds only originals to reuse", async () => {
172
422
  const store = await make();
173
- const c = await store.createCase(newCase("s"));
174
- const r = await store.createRun(newRun("s"));
423
+ const n = names();
424
+ const c = await store.createCase(newCase(n("s")));
425
+ const r = await store.createRun(newRun(n("s")));
175
426
  const base = {
176
427
  runId: r.id,
177
428
  caseId: c.id,
178
429
  repeat: 1,
179
- requestHash: "h",
430
+ requestHash: n("h"),
180
431
  output: { text: "HELLO" },
181
432
  error: null,
182
433
  scores: null,
@@ -193,21 +444,22 @@ export function describeStoreContract(
193
444
  expect(outs.find((x) => x.id === o.id)?.scores).toEqual([
194
445
  { key: "match", pass: true },
195
446
  ]);
196
- const found = await store.findReusableOutput("h", new Date(0));
447
+ const found = await store.findReusableOutput(n("h"), new Date(0));
197
448
  expect(found?.id).toBe(o.id);
198
449
  expect(found?.output).toEqual({ text: "HELLO" });
199
450
  expect(
200
- await store.findReusableOutput("h", new Date(Date.now() + 60_000)),
451
+ await store.findReusableOutput(n("h"), new Date(Date.now() + 60_000)),
201
452
  ).toBeNull();
202
453
  });
203
454
 
204
455
  it("lists several tests' outputs and reusable hashes in one call, where it can", async () => {
205
456
  const store = await make();
206
- const c = await store.createCase(newCase("s"));
457
+ const n = names();
458
+ const c = await store.createCase(newCase(n("s")));
207
459
  const [r1, r2, r3] = await Promise.all([
208
- store.createRun(newRun("s")),
209
- store.createRun(newRun("s")),
210
- store.createRun(newRun("s")),
460
+ store.createRun(newRun(n("s"))),
461
+ store.createRun(newRun(n("s"))),
462
+ store.createRun(newRun(n("s"))),
211
463
  ]);
212
464
  const base = {
213
465
  caseId: c.id,
@@ -219,38 +471,44 @@ export function describeStoreContract(
219
471
  ms: 12,
220
472
  reused: false,
221
473
  };
222
- await store.createOutput({ ...base, runId: r1.id, requestHash: "a" });
223
- await store.createOutput({ ...base, runId: r2.id, requestHash: "b" });
474
+ await store.createOutput({ ...base, runId: r1.id, requestHash: n("a") });
475
+ await store.createOutput({ ...base, runId: r2.id, requestHash: n("b") });
224
476
  await store.createOutput({
225
477
  ...base,
226
478
  runId: r2.id,
227
- requestHash: "c",
479
+ requestHash: n("c"),
228
480
  reused: true,
229
481
  });
230
482
  await store.createOutput({
231
483
  ...base,
232
484
  runId: r3.id,
233
- requestHash: "d",
485
+ requestHash: n("d"),
234
486
  error: "boom",
235
487
  output: null,
236
488
  });
237
489
  if (store.listOutputsFor) {
238
490
  const outs = await store.listOutputsFor([r1.id, r2.id]);
239
- expect(outs.map((o) => o.requestHash).sort()).toEqual(["a", "b", "c"]);
491
+ expect(outs.map((o) => o.requestHash).sort()).toEqual(
492
+ [n("a"), n("b"), n("c")].sort(),
493
+ );
240
494
  expect(await store.listOutputsFor([])).toEqual([]);
241
495
  }
242
496
  if (store.findReusableHashes) {
243
497
  expect(
244
498
  [
245
499
  ...(await store.findReusableHashes(
246
- ["a", "b", "c", "d", "e"],
500
+ ["a", "b", "c", "d", "e"].map(n),
247
501
  new Date(0),
248
502
  )),
249
503
  ].sort(),
250
- ).toEqual(["a", "b"]);
504
+ ).toEqual([n("a"), n("b")].sort());
251
505
  expect(
252
- (await store.findReusableHashes(["a"], new Date(Date.now() + 60_000)))
253
- .size,
506
+ (
507
+ await store.findReusableHashes(
508
+ [n("a")],
509
+ new Date(Date.now() + 60_000),
510
+ )
511
+ ).size,
254
512
  ).toBe(0);
255
513
  expect((await store.findReusableHashes([], new Date(0))).size).toBe(0);
256
514
  }
@@ -258,10 +516,12 @@ export function describeStoreContract(
258
516
 
259
517
  it("runs a whole test through the runner", async () => {
260
518
  const store = await make();
519
+ const n = names();
520
+ const key = n("contract");
261
521
  const echo: Suite<{ text: string }, { text: string }, { want: string }> =
262
522
  {
263
- key: "contract",
264
- operation: "contract",
523
+ key,
524
+ operation: key,
265
525
  priority: { favor: "quality" },
266
526
  label: "Contract",
267
527
  description: "Uppercases text.",
@@ -284,17 +544,14 @@ export function describeStoreContract(
284
544
  inputFromForm: () => ({ text: "" }),
285
545
  title: (i) => i.text,
286
546
  };
287
- await store.createCase(newCase("contract"));
547
+ await store.createCase(newCase(key));
288
548
  const runner = createRunner({
289
549
  store,
290
550
  suites: [echo],
291
551
  models: { "model-a": { label: "Model A", provider: "acme" } },
292
552
  promptVersion: () => "v1",
293
553
  });
294
- const { run } = await runner.createRun({
295
- suite: "contract",
296
- model: "model-a",
297
- });
554
+ const { run } = await runner.createRun({ suite: key, model: "model-a" });
298
555
  await runner.runEval(run.id);
299
556
  const done = await store.getRun(run.id);
300
557
  expect(done?.status).toBe("SUCCEEDED");
@@ -305,14 +562,24 @@ export function describeStoreContract(
305
562
 
306
563
  /**
307
564
  * The contract every FeedbackStore must meet. `make` must return an empty
308
- * store each time it's called.
565
+ * store each time it's called, unless `opts.scope` is set (see
566
+ * `describeStoreContract`): then every feature the contract rates starts
567
+ * with the scope, and its lists ask for those features only.
309
568
  */
310
569
  export function describeFeedbackStoreContract(
311
570
  name: string,
312
571
  make: () => FeedbackStore | Promise<FeedbackStore>,
572
+ opts: ScopedContractOptions = {},
313
573
  ) {
314
- const rating = (over: Partial<NewRating> = {}): NewRating => ({
315
- operation: "triage",
574
+ const t = testFunctions(opts.test);
575
+ const { describe, it, expect } = t;
576
+ const names = scopeNames(opts.scope);
577
+ const scoped = opts.scope !== undefined;
578
+ const rating = (
579
+ operation: string,
580
+ over: Partial<NewRating> = {},
581
+ ): NewRating => ({
582
+ operation,
316
583
  targetId: "answer-1",
317
584
  raterId: "person-1",
318
585
  rating: "DOWN",
@@ -324,11 +591,14 @@ export function describeFeedbackStoreContract(
324
591
  });
325
592
 
326
593
  describe(`FeedbackStore contract: ${name}`, () => {
594
+ registerCleanup(t, opts);
595
+
327
596
  it("keeps a rating with its reason, input, and output, open", async () => {
328
597
  const store = await make();
329
- const f = await store.rate(rating());
598
+ const op = names()("triage");
599
+ const f = await store.rate(rating(op));
330
600
  expect(f).toMatchObject({
331
- operation: "triage",
601
+ operation: op,
332
602
  rating: "DOWN",
333
603
  reason: "Wrong queue",
334
604
  excerpt: "billing",
@@ -341,35 +611,46 @@ export function describeFeedbackStoreContract(
341
611
 
342
612
  it("keeps one rating per person per answer, and reopens a changed one", async () => {
343
613
  const store = await make();
344
- const first = await store.rate(rating());
614
+ const op = names()("triage");
615
+ const first = await store.rate(rating(op));
345
616
  await store.setFeedbackStatus(first.id, "DISMISSED");
346
- const changed = await store.rate(rating({ rating: "UP" }));
617
+ const changed = await store.rate(rating(op, { rating: "UP" }));
347
618
  expect(changed.id).toBe(first.id);
348
619
  expect(changed.status).toBe("OPEN");
349
620
  expect(changed.reason).toBeNull();
350
- await store.rate(rating({ raterId: "person-2" }));
351
- expect(await store.listFeedback()).toHaveLength(2);
621
+ await store.rate(rating(op, { raterId: "person-2" }));
622
+ expect(
623
+ await store.listFeedback(scoped ? { operation: op } : {}),
624
+ ).toHaveLength(2);
352
625
  });
353
626
 
354
627
  it("takes a rating back", async () => {
355
628
  const store = await make();
356
- await store.rate(rating());
357
- await store.clearRating("person-1", "triage", "answer-1");
358
- expect(await store.listFeedback()).toHaveLength(0);
629
+ const op = names()("triage");
630
+ await store.rate(rating(op));
631
+ await store.clearRating("person-1", op, "answer-1");
632
+ expect(
633
+ await store.listFeedback(scoped ? { operation: op } : {}),
634
+ ).toHaveLength(0);
359
635
  });
360
636
 
361
637
  it("filters by feature, rating, status, and date, newest first", async () => {
362
638
  const store = await make();
363
- const a = await store.rate(rating({ targetId: "a" }));
639
+ const n = names();
640
+ const op = n("triage");
641
+ const mine = scoped ? { operation: op } : {};
642
+ const a = await store.rate(rating(op, { targetId: "a" }));
364
643
  await new Promise((r) => setTimeout(r, 5));
365
- const b = await store.rate(rating({ targetId: "b", rating: "UP" }));
366
- await store.rate(rating({ targetId: "c", operation: "summary" }));
644
+ const b = await store.rate(rating(op, { targetId: "b", rating: "UP" }));
645
+ await store.rate(rating(n("summary"), { targetId: "c" }));
367
646
  expect(
368
- (await store.listFeedback({ operation: "triage" })).map((f) => f.id),
647
+ (await store.listFeedback({ operation: op })).map((f) => f.id),
369
648
  ).toEqual([b.id, a.id]);
370
- expect(await store.listFeedback({ rating: "UP" })).toHaveLength(1);
649
+ expect(await store.listFeedback({ ...mine, rating: "UP" })).toHaveLength(
650
+ 1,
651
+ );
371
652
  await store.setFeedbackStatus(a.id, "CASED", "case-1");
372
- const cased = await store.listFeedback({ status: "CASED" });
653
+ const cased = await store.listFeedback({ ...mine, status: "CASED" });
373
654
  expect(cased.map((f) => [f.id, f.caseId])).toEqual([[a.id, "case-1"]]);
374
655
  expect(
375
656
  await store.listFeedback({ since: new Date(Date.now() + 60_000) }),
@@ -379,14 +660,27 @@ export function describeFeedbackStoreContract(
379
660
  });
380
661
  }
381
662
 
663
+ /** Options for the settings store contract. */
664
+ export type SettingsStoreContractOptions = ScopedContractOptions & {
665
+ /** Settings the store has no column for (see `StoreContractOptions`). */
666
+ without?: "temperature"[];
667
+ };
668
+
382
669
  /**
383
670
  * The contract every SettingsStore must meet. `make` must return an empty
384
- * store each time it's called.
671
+ * store each time it's called, unless `opts.scope` is set (see
672
+ * `describeStoreContract`): then every feature the contract versions
673
+ * starts with the scope. `opts.without` names settings its tables have no
674
+ * column for (see `StoreContractOptions`).
385
675
  */
386
676
  export function describeSettingsStoreContract(
387
677
  name: string,
388
678
  make: () => SettingsStore | Promise<SettingsStore>,
679
+ opts: SettingsStoreContractOptions = {},
389
680
  ) {
681
+ const t = testFunctions(opts.test);
682
+ const { describe, it, expect } = t;
683
+ const names = scopeNames(opts.scope);
390
684
  const settings = (model: string): Settings => ({
391
685
  model,
392
686
  fallbackModel: null,
@@ -402,32 +696,36 @@ export function describeSettingsStoreContract(
402
696
  });
403
697
 
404
698
  describe(`SettingsStore contract: ${name}`, () => {
699
+ registerCleanup(t, opts);
700
+
405
701
  it("has nothing live until the first switch, then numbers versions", async () => {
406
702
  const store = await make();
407
- expect(await store.liveVersion("triage")).toBeNull();
408
- const v1 = await store.switchTo("triage", create("a", null));
409
- const v2 = await store.switchTo("triage", create("b", v1.id));
703
+ const op = names()("triage");
704
+ expect(await store.liveVersion(op)).toBeNull();
705
+ const v1 = await store.switchTo(op, create("a", null));
706
+ const v2 = await store.switchTo(op, create("b", v1.id));
410
707
  expect([v1.number, v2.number]).toEqual([1, 2]);
411
708
  expect(v2).toMatchObject({
412
- operation: "triage",
709
+ operation: op,
413
710
  model: "b",
414
711
  promptVersion: "p1",
415
712
  });
416
- expect((await store.liveVersion("triage"))?.id).toBe(v2.id);
417
- expect((await store.listVersions("triage")).map((v) => v.number)).toEqual(
418
- [2, 1],
419
- );
713
+ expect((await store.liveVersion(op))?.id).toBe(v2.id);
714
+ expect((await store.listVersions(op)).map((v) => v.number)).toEqual([
715
+ 2, 1,
716
+ ]);
420
717
  });
421
718
 
422
719
  it("logs every switch, newest first, with who, why, and evidence", async () => {
423
720
  const store = await make();
424
- const v1 = await store.switchTo("triage", create("a", null));
425
- await store.switchTo("triage", {
721
+ const op = names()("triage");
722
+ const v1 = await store.switchTo(op, create("a", null));
723
+ await store.switchTo(op, {
426
724
  ...create("b", v1.id),
427
725
  kind: "PROMOTE",
428
726
  evidence: { runId: "r1", verdict: "BETTER" },
429
727
  });
430
- const [latest, first] = await store.listChanges("triage");
728
+ const [latest, first] = await store.listChanges(op);
431
729
  expect(latest).toMatchObject({
432
730
  kind: "PROMOTE",
433
731
  fromVersionId: v1.id,
@@ -436,38 +734,41 @@ export function describeSettingsStoreContract(
436
734
  evidence: { runId: "r1", verdict: "BETTER" },
437
735
  });
438
736
  expect(first).toMatchObject({ kind: "CHANGE", fromVersionId: null });
439
- expect(await store.listChanges("triage", { limit: 1 })).toHaveLength(1);
737
+ expect(await store.listChanges(op, { limit: 1 })).toHaveLength(1);
440
738
  });
441
739
 
442
740
  it("makes an earlier version live again without a new one", async () => {
443
741
  const store = await make();
444
- const v1 = await store.switchTo("triage", create("a", null));
445
- const v2 = await store.switchTo("triage", create("b", v1.id));
446
- await store.switchTo("triage", {
742
+ const op = names()("triage");
743
+ const v1 = await store.switchTo(op, create("a", null));
744
+ const v2 = await store.switchTo(op, create("b", v1.id));
745
+ await store.switchTo(op, {
447
746
  versionId: v1.id,
448
747
  kind: "ROLLBACK",
449
748
  reason: "b was worse",
450
749
  by: "person-1",
451
750
  expectLive: v2.id,
452
751
  });
453
- expect((await store.liveVersion("triage"))?.id).toBe(v1.id);
454
- expect(await store.listVersions("triage")).toHaveLength(2);
752
+ expect((await store.liveVersion(op))?.id).toBe(v1.id);
753
+ expect(await store.listVersions(op)).toHaveLength(2);
455
754
  });
456
755
 
457
756
  it("refuses a switch decided against a live version that changed", async () => {
458
757
  const store = await make();
459
- const v1 = await store.switchTo("triage", create("a", null));
460
- await store.switchTo("triage", create("b", v1.id));
758
+ const op = names()("triage");
759
+ const v1 = await store.switchTo(op, create("a", null));
760
+ await store.switchTo(op, create("b", v1.id));
461
761
  await expect(
462
- store.switchTo("triage", create("c", v1.id)),
762
+ store.switchTo(op, create("c", v1.id)),
463
763
  ).rejects.toBeInstanceOf(SettingsConflict);
464
- expect((await store.liveVersion("triage"))?.model).toBe("b");
465
- expect(await store.listVersions("triage")).toHaveLength(2);
764
+ expect((await store.liveVersion(op))?.model).toBe("b");
765
+ expect(await store.listVersions(op)).toHaveLength(2);
466
766
  });
467
767
 
468
768
  it("keeps a version's reasoning setting as named, even a newer one", async () => {
469
769
  const store = await make();
470
- const v1 = await store.switchTo("triage", {
770
+ const op = names()("triage");
771
+ const v1 = await store.switchTo(op, {
471
772
  ...create("a", null),
472
773
  create: {
473
774
  settings: { ...settings("a"), reasoningEffort: "xhigh" },
@@ -475,32 +776,168 @@ export function describeSettingsStoreContract(
475
776
  },
476
777
  });
477
778
  expect(v1.reasoningEffort).toBe("xhigh");
478
- expect((await store.liveVersion("triage"))?.reasoningEffort).toBe(
479
- "xhigh",
480
- );
779
+ expect((await store.liveVersion(op))?.reasoningEffort).toBe("xhigh");
481
780
  });
482
781
 
483
- it("keeps a version's temperature", async () => {
484
- const store = await make();
485
- const v1 = await store.switchTo("triage", {
486
- ...create("a", null),
487
- create: {
488
- settings: { ...settings("a"), temperature: 0.4 },
489
- promptVersion: "p1",
490
- },
782
+ if (opts.without?.includes("temperature")) {
783
+ it("refuses a temperature it has no column for, and keeps none", async () => {
784
+ const store = await make();
785
+ const op = names()("triage");
786
+ await expect(
787
+ store.switchTo(op, {
788
+ ...create("a", null),
789
+ create: {
790
+ settings: { ...settings("a"), temperature: 0.4 },
791
+ promptVersion: "p1",
792
+ },
793
+ }),
794
+ ).rejects.toThrow("temperature");
795
+ expect(await store.liveVersion(op)).toBeNull();
796
+ const v1 = await store.switchTo(op, create("a", null));
797
+ expect(v1.temperature ?? null).toBeNull();
798
+ });
799
+ } else {
800
+ it("keeps a version's temperature", async () => {
801
+ const store = await make();
802
+ const op = names()("triage");
803
+ const v1 = await store.switchTo(op, {
804
+ ...create("a", null),
805
+ create: {
806
+ settings: { ...settings("a"), temperature: 0.4 },
807
+ promptVersion: "p1",
808
+ },
809
+ });
810
+ expect(v1.temperature).toBe(0.4);
811
+ expect((await store.liveVersion(op))?.temperature).toBe(0.4);
812
+ const v2 = await store.switchTo(op, create("b", v1.id));
813
+ expect(v2.temperature ?? null).toBeNull();
491
814
  });
492
- expect(v1.temperature).toBe(0.4);
493
- expect((await store.liveVersion("triage"))?.temperature).toBe(0.4);
494
- const v2 = await store.switchTo("triage", create("b", v1.id));
495
- expect(v2.temperature ?? null).toBeNull();
815
+ }
816
+
817
+ it("keeps every kind of change, with its evidence", async () => {
818
+ const store = await make();
819
+ const op = names()("triage");
820
+ let live = (await store.switchTo(op, create("a", null))).id;
821
+ for (const kind of CHANGE_KINDS.slice(1))
822
+ live = (
823
+ await store.switchTo(op, {
824
+ ...create(kind.toLowerCase(), live),
825
+ kind,
826
+ evidence: kind === "PROMOTE" ? { runId: "r1" } : undefined,
827
+ })
828
+ ).id;
829
+ const changes = await store.listChanges(op);
830
+ expect(changes.map((c) => c.kind)).toEqual([...CHANGE_KINDS].reverse());
831
+ expect(changes.map((c) => c.evidence)).toEqual([
832
+ null,
833
+ null,
834
+ null,
835
+ null,
836
+ { runId: "r1" },
837
+ null,
838
+ ]);
496
839
  });
497
840
 
498
841
  it("keeps each feature's versions and live one apart", async () => {
499
842
  const store = await make();
500
- await store.switchTo("triage", create("a", null));
501
- const other = await store.switchTo("summary", create("x", null));
843
+ const n = names();
844
+ await store.switchTo(n("triage"), create("a", null));
845
+ const other = await store.switchTo(n("summary"), create("x", null));
502
846
  expect(other.number).toBe(1);
503
- expect((await store.liveVersion("triage"))?.model).toBe("a");
847
+ expect((await store.liveVersion(n("triage")))?.model).toBe("a");
848
+ });
849
+ });
850
+ }
851
+
852
+ /**
853
+ * The contract every set of suites should meet, so people confirming
854
+ * answers weeks later (and the pages) can read them: unique keys, a label
855
+ * and help for every top-level field of each suite's input and answer,
856
+ * a description for every check, and starter cases that fit the suite's
857
+ * own schemas. One test per suite, listing what's missing in plain words
858
+ * (`suiteContractProblems`).
859
+ *
860
+ * @param name - What the tests are called, e.g. "our suites".
861
+ * @param suites - Every suite the app registers.
862
+ * @param opts - Test functions other than Vitest's.
863
+ *
864
+ * @example
865
+ * ```ts
866
+ * import { describeSuiteContract } from "@crowandraven/evalkeeper/testing";
867
+ * import { SUITES } from "../lib/suites";
868
+ *
869
+ * describeSuiteContract("our suites", SUITES);
870
+ * ```
871
+ */
872
+ export function describeSuiteContract(
873
+ name: string,
874
+ suites: readonly AnySuite[],
875
+ opts: ContractOptions = {},
876
+ ) {
877
+ const { describe, it, expect } = testFunctions(opts.test);
878
+ describe(`Suite contract: ${name}`, () => {
879
+ it("has unique keys", () => {
880
+ expect(
881
+ suiteContractProblems(suites).filter((p) =>
882
+ p.endsWith("another suite has the same key."),
883
+ ),
884
+ ).toEqual([]);
504
885
  });
886
+ for (const suite of suites)
887
+ it(`${suite.key}: every field, check, and starter can be read`, () => {
888
+ expect(
889
+ suiteContractProblems([suite]),
890
+ "What's missing for people to read this suite",
891
+ ).toEqual([]);
892
+ });
893
+ });
894
+ }
895
+
896
+ /**
897
+ * A read-only check, as a test, that a store mapped onto your own tables
898
+ * reads what's already there: one test per suite that fails listing every
899
+ * case, answer, test, and output that doesn't parse, with counts. It only
900
+ * reads, so it's the check to run first, on a copy of real data. Pass the
901
+ * report from `checkStoreReads` (any store) or `prismaReadCheck` (sees a
902
+ * Prisma table's values before the store fills in defaults).
903
+ *
904
+ * @param name - What the tests are called, e.g. "our answer key".
905
+ * @param check - Makes the report; called once, when the tests run.
906
+ * @param opts - The suite keys to name a test for, and test functions
907
+ * other than Vitest's.
908
+ *
909
+ * @example
910
+ * ```ts
911
+ * import { describeMappedReadCheck } from "@crowandraven/evalkeeper/testing";
912
+ * import { prismaReadCheck } from "@crowandraven/evalkeeper-prisma";
913
+ *
914
+ * describeMappedReadCheck(
915
+ * "our answer key",
916
+ * () => prismaReadCheck(prisma, map, { suites: SUITES }),
917
+ * { suites: SUITES.map((s) => s.key) },
918
+ * );
919
+ * ```
920
+ */
921
+ export function describeMappedReadCheck(
922
+ name: string,
923
+ check: () => Promise<ReadCheckReport>,
924
+ opts: ContractOptions & { suites: readonly string[] },
925
+ ) {
926
+ const { describe, it, expect } = testFunctions(opts.test);
927
+ let report: Promise<ReadCheckReport> | null = null;
928
+ const once = () => (report ??= check());
929
+ describe(`Read check: ${name}`, () => {
930
+ for (const key of opts.suites)
931
+ it(`${key}: every case, answer, test, and output reads`, async () => {
932
+ const found = (await once()).suites.find((s) => s.suite === key);
933
+ expect(found, `The check found no report for ${key}`).toMatchObject({
934
+ suite: key,
935
+ });
936
+ if (!found) return;
937
+ expect(
938
+ found.problems,
939
+ readCheckSummary({ suites: [found] }).join("\n"),
940
+ ).toEqual([]);
941
+ });
505
942
  });
506
943
  }