@axlsdk/eval 0.17.9 → 0.18.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.cts CHANGED
@@ -5,6 +5,27 @@ type DatasetItem<TInput, TAnnotations = undefined> = {
5
5
  input: TInput;
6
6
  annotations?: TAnnotations;
7
7
  };
8
+ /**
9
+ * What to do when a dataset item's `annotations` contain keys that are absent
10
+ * from the `annotations` schema.
11
+ *
12
+ * Zod object schemas strip unknown keys by default, so an annotation field
13
+ * that isn't declared in the schema is silently dropped before it ever reaches
14
+ * a scorer. A scorer that reads such a field sees `undefined` and quietly
15
+ * degrades to a no-op — the eval still "passes", so the bug is invisible. This
16
+ * is especially easy to hit with file-based datasets, where the JSON is never
17
+ * type-checked.
18
+ *
19
+ * - `'warn'` (default) — log a single `console.warn` per dataset listing the
20
+ * dropped key paths. Non-breaking; surfaces the contract violation.
21
+ * - `'error'` — throw, listing the dropped key paths. The strict path for CI.
22
+ * - `'ignore'` — preserve the silent-strip behavior (skips detection entirely).
23
+ *
24
+ * Only `annotations` are checked, not `input`: stripped input fields flow to
25
+ * the workflow where they surface, whereas stripped annotations vanish into a
26
+ * silent scorer.
27
+ */
28
+ type ExtraKeyPolicy = 'warn' | 'error' | 'ignore';
8
29
  type DatasetConfig<TInput extends z.ZodType, TAnnotations extends z.ZodType = z.ZodType> = {
9
30
  name: string;
10
31
  schema: TInput;
@@ -13,11 +34,28 @@ type DatasetConfig<TInput extends z.ZodType, TAnnotations extends z.ZodType = z.
13
34
  file?: string;
14
35
  /** Base directory for resolving relative file paths. Defaults to cwd. */
15
36
  basePath?: string;
37
+ /**
38
+ * How to handle annotation keys not present in the `annotations` schema
39
+ * (Zod strips them by default). Defaults to `'warn'`. See {@link ExtraKeyPolicy}.
40
+ */
41
+ onExtraAnnotationKeys?: ExtraKeyPolicy;
16
42
  };
17
43
  type Dataset<TInput = unknown, TAnnotations = unknown> = {
18
44
  readonly name: string;
19
45
  readonly schema: z.ZodType;
20
46
  readonly annotationsSchema?: z.ZodType;
47
+ /**
48
+ * Annotation key paths the schema dropped during the most recent
49
+ * `getItems()` call (empty when none were dropped, or when
50
+ * `onExtraAnnotationKeys: 'ignore'`). Populated as a side effect of
51
+ * `getItems()` — read it synchronously right after awaiting, on the same
52
+ * instance; a later `getItems()` overwrites it (calling `getItems()`
53
+ * concurrently on one shared dataset is unsupported). The eval runner folds
54
+ * this into `EvalResult.metadata.droppedAnnotationKeys` so any consumer (the
55
+ * CLI logs it; UIs can render it) sees the same signal. Optional so
56
+ * hand-rolled `Dataset`-shaped objects (test harnesses) remain valid.
57
+ */
58
+ readonly droppedAnnotationKeys?: readonly string[];
21
59
  getItems(): Promise<DatasetItem<TInput, TAnnotations>[]>;
22
60
  };
23
61
  declare function dataset<TInput extends z.ZodType, TAnnotations extends z.ZodType>(config: DatasetConfig<TInput, TAnnotations>): Dataset<z.infer<TInput>, z.infer<TAnnotations>>;
@@ -41,16 +79,51 @@ type ScorerContext = {
41
79
  signal?: AbortSignal;
42
80
  };
43
81
  type ScorerFn<TOutput, TInput, TAnnotations> = (output: TOutput, input: TInput, annotations?: TAnnotations) => number | ScorerResult;
82
+ /**
83
+ * Applicability predicate for a conditional scorer. Returns `true` if this
84
+ * scorer should run for the given item, `false` to skip it.
85
+ *
86
+ * The eval runner runs every scorer against every item, so a scorer that only
87
+ * applies to a subset (a refusal judge for refusal-expected items, a constraint
88
+ * judge for constrained items, …) declares its scope here. A skipped item is
89
+ * counted as NEITHER `scored` NOR `failed` — it's excluded from the mean AND
90
+ * from the failure-rate denominator, so a conditional scorer stays honest to
91
+ * both. The predicate runs BEFORE the scorer body, so an inapplicable
92
+ * `llmScorer` never makes its provider call.
93
+ *
94
+ * Signature mirrors {@link ScorerFn} (`output, input, annotations`). Applicability
95
+ * usually keys off `input`/`annotations` (e.g. a flag or exercise type), but
96
+ * `output` is available too (e.g. "only score outputs that refused"). A
97
+ * predicate that THROWS is a bug, not a skip — it's recorded as a scorer
98
+ * failure, never silently swallowed.
99
+ *
100
+ * The contract is `=> boolean`: return `true` to run, `false` to skip. The
101
+ * runtime is defensively lenient — it coerces with `!verdict`, so a stray falsy
102
+ * value (a predicate that forgot to `return`) skips rather than crashes — but
103
+ * authors should return a real boolean. When deriving from a truthy value,
104
+ * coerce it yourself: `(o, i, a) => !!a.constraints?.length`, not
105
+ * `=> a.constraints?.length` (which is `number | undefined`, a type error). A
106
+ * predicate that accidentally never returns therefore skips EVERY item — but
107
+ * that surfaces conspicuously as a non-zero `skipped` count (the Studio "N/A"
108
+ * chip), not as a silently green mean.
109
+ */
110
+ type ScorerApplies<TOutput, TInput, TAnnotations> = (output: TOutput, input: TInput, annotations?: TAnnotations) => boolean;
44
111
  type ScorerConfig<TOutput = unknown, TInput = unknown, TAnnotations = unknown> = {
45
112
  name: string;
46
113
  description: string;
47
114
  score: ScorerFn<TOutput, TInput, TAnnotations>;
115
+ /** Optional applicability predicate — see {@link ScorerApplies}. When it
116
+ * returns `false`, the scorer is skipped for that item (counted as neither
117
+ * scored nor failed). Omit to run on every item (the default). */
118
+ applies?: ScorerApplies<TOutput, TInput, TAnnotations>;
48
119
  };
49
120
  type Scorer<TOutput = unknown, TInput = unknown, TAnnotations = unknown> = {
50
121
  readonly name: string;
51
122
  readonly description: string;
52
123
  readonly isLlm: boolean;
53
124
  score(output: TOutput, input: TInput, annotations?: TAnnotations, context?: ScorerContext): number | ScorerResult | Promise<number | ScorerResult>;
125
+ /** See {@link ScorerApplies}. Evaluated by the runner before {@link score}. */
126
+ applies?: ScorerApplies<TOutput, TInput, TAnnotations>;
54
127
  };
55
128
  declare function scorer<TOutput = unknown, TInput = unknown, TAnnotations = unknown>(config: ScorerConfig<TOutput, TInput, TAnnotations>): Scorer<TOutput, TInput, TAnnotations>;
56
129
 
@@ -79,6 +152,11 @@ type LlmScorerConfig = {
79
152
  stop?: string[];
80
153
  /** Provider-specific escape hatch — merged last into the raw API request. */
81
154
  providerOptions?: Record<string, unknown>;
155
+ /** Optional applicability predicate — see {@link ScorerApplies}. When it
156
+ * returns `false`, the judge is skipped for that item and NO provider call is
157
+ * made (the conditional-LLM-judge cost/rate-limit win). The item counts as
158
+ * neither scored nor failed. */
159
+ applies?: ScorerApplies<unknown, unknown, unknown>;
82
160
  };
83
161
  declare function llmScorer(config: LlmScorerConfig): Scorer;
84
162
 
@@ -86,10 +164,53 @@ type EvalConfig = {
86
164
  workflow: string;
87
165
  dataset: Dataset<unknown, unknown>;
88
166
  scorers: Scorer<unknown, unknown, unknown>[];
167
+ /** Item-level worker-pool size (how many dataset items run in parallel). Default 5. */
89
168
  concurrency?: number;
169
+ /**
170
+ * Per-item scorer fan-out — how many of an item's scorers run concurrently.
171
+ * Default 5 (matches `concurrency`; scorers are parallel-by-default). The
172
+ * worst-case number of concurrent scorer calls is `concurrency × scorerConcurrency`,
173
+ * so lower `concurrency` if a rate-limited judge model needs a tighter ceiling.
174
+ */
175
+ scorerConcurrency?: number;
90
176
  budget?: string;
177
+ /**
178
+ * Opt-in source-side trust gate. When set (0–1), `runEval` flags the run as
179
+ * `summary.degraded` if any scorer's failure rate exceeds tolerance, and the
180
+ * CLI exits non-zero. Enforcement is **type-aware**: deterministic scorers
181
+ * tolerate ZERO failures (a deterministic scorer that throws is a bug, not
182
+ * noise), while LLM scorers use this rate (a flaky judge / rate-limit storm).
183
+ *
184
+ * Failure rate = `failed / (scored + failed)` per scorer, where `scored` is
185
+ * the number of items that produced a valid numeric score and `failed` is the
186
+ * number whose scorer ran and threw / returned out-of-range. `0` means "any
187
+ * LLM failure degrades the run". Invalid values (non-finite, <0, >1) are
188
+ * ignored with a `console.warn`.
189
+ *
190
+ * Distinct from the gate-side `--max-scorer-error-rate` compare flag: this one
191
+ * fires at run/produce time (catch a thinned sample before it's saved), the
192
+ * other at consume/gate time (refuse to certify a thinned baseline/candidate).
193
+ */
194
+ failOnScorerErrorRate?: number;
91
195
  metadata?: Record<string, unknown>;
92
196
  };
197
+ /**
198
+ * One scorer whose failure rate tripped `EvalConfig.failOnScorerErrorRate`.
199
+ * Surfaced on `EvalSummary.degraded` so consumers (CLI exit code, Studio
200
+ * banner) can refuse to trust the mean without re-deriving the rate.
201
+ */
202
+ type DegradedScorer = {
203
+ scorer: string;
204
+ /** Observed failure rate `failed / (scored + failed)` (0 when nothing ran). */
205
+ rate: number;
206
+ /** The tolerance that was exceeded (0 for deterministic scorers). */
207
+ limit: number;
208
+ type: 'llm' | 'deterministic';
209
+ /** Items that produced a valid numeric score. */
210
+ scored: number;
211
+ /** Items whose scorer ran and failed (threw / out-of-range). */
212
+ failed: number;
213
+ };
93
214
  type EvalResult = {
94
215
  id: string;
95
216
  /**
@@ -108,6 +229,13 @@ type EvalResult = {
108
229
  * that need a single "primary" workflow should use `workflows[0]`.
109
230
  * - `scorerTypes: Record<string, 'llm' | 'deterministic'>`
110
231
  * - `runGroupId?: string`, `runIndex?: number` for multi-run groups
232
+ * - `droppedAnnotationKeys?: string[]` — annotation key paths the dataset
233
+ * schema stripped (present only when non-empty). Mirrors the dataset's
234
+ * `console.warn`; lets any consumer surface the same signal.
235
+ * - `scorerFiltered?: boolean` + `scorersRun?: string[]` — set when the CLI
236
+ * `--scorers` flag ran a subset of scorers. A guard so a filtered run isn't
237
+ * silently used as a full baseline (`compare` warns / refuses to gate on it).
238
+ * Distinct from the multi-run "partial" concept (see {@link EvalComparisonPartial}).
111
239
  */
112
240
  metadata: Record<string, unknown>;
113
241
  timestamp: string;
@@ -121,6 +249,14 @@ type ScorerDetail = {
121
249
  metadata?: Record<string, unknown>;
122
250
  duration?: number;
123
251
  cost?: number;
252
+ /**
253
+ * `true` when the scorer's `applies` predicate returned `false` for this item,
254
+ * so the scorer was deliberately skipped (NOT run). Distinct from a `null`
255
+ * score WITH a `duration` (ran-and-failed) and from a `null` score with
256
+ * neither field (skipped by cancellation). A skipped item is excluded from the
257
+ * mean AND from the failure-rate denominator — see `scorerCounts`.
258
+ */
259
+ skipped?: boolean;
124
260
  };
125
261
  type EvalItem = {
126
262
  input: unknown;
@@ -150,6 +286,29 @@ type EvalSummary = {
150
286
  max: number;
151
287
  p50: number;
152
288
  p95: number;
289
+ /**
290
+ * Number of items that produced a valid numeric score — the sample size
291
+ * the `mean` actually covers. Optional so pre-existing artifacts (and
292
+ * hand-rolled summaries) stay valid; absent ⇒ recompute from `items`.
293
+ * Named `scored` (NOT `n`) to avoid collision with
294
+ * `EvalComparison.scorers[].n` (paired-diff count).
295
+ */
296
+ scored?: number;
297
+ /**
298
+ * Number of items whose scorer RAN and failed (threw or returned
299
+ * out-of-range). Distinct from items skipped by cancellation, which land
300
+ * in neither bucket — so `scored + failed` is the honest "attempted"
301
+ * denominator and may be `<` the eligible item count. A non-zero `failed`
302
+ * means the `mean` was computed over a thinned sample.
303
+ */
304
+ failed?: number;
305
+ /**
306
+ * Number of items for which this scorer's `applies` predicate returned
307
+ * `false` — deliberately skipped, NOT run. Counted in neither `scored` nor
308
+ * `failed`, so it never inflates the failure rate. Optional so pre-existing
309
+ * artifacts stay valid; absent ⇒ recompute from `items` (0 if no skips).
310
+ */
311
+ skipped?: number;
153
312
  }>;
154
313
  timing?: {
155
314
  mean: number;
@@ -158,6 +317,14 @@ type EvalSummary = {
158
317
  p50: number;
159
318
  p95: number;
160
319
  };
320
+ /**
321
+ * Populated by `runEval` ONLY when `EvalConfig.failOnScorerErrorRate` is set
322
+ * and one or more scorers exceeded tolerance. `runEval` never throws on this
323
+ * — it returns the (still-useful) result with this flag set, and the CLI /
324
+ * consumer decides whether to fail. Absent / empty ⇒ no degradation gate
325
+ * tripped (either not configured or all scorers within tolerance).
326
+ */
327
+ degraded?: DegradedScorer[];
161
328
  };
162
329
  /**
163
330
  * Sample-size context for one side of a comparison.
@@ -214,8 +381,39 @@ type EvalComparison = {
214
381
  significant?: boolean;
215
382
  pRegression?: number;
216
383
  pImprovement?: number;
217
- /** Number of paired item differences used for CI computation. */
384
+ /**
385
+ * Paired sample size — the count of items scored on BOTH sides (the only
386
+ * items a difference exists for). Always set, including `0`/`1`. The CI /
387
+ * `significant` / `pRegression` / `pImprovement` fields are populated only
388
+ * when `n >= 2`. NOTE the asymmetry: `delta` is the difference of the two
389
+ * INDEPENDENT per-side means (each over `{baseline,candidate}Scored`
390
+ * items), whereas the CI is paired over these `n` — so when `n` is much
391
+ * smaller than the per-side scored counts (different skips/failures per
392
+ * side), the delta and the CI rest on different samples.
393
+ */
218
394
  n?: number;
395
+ /**
396
+ * Per-side scorer success/failure counts over the SAME truncated pool the
397
+ * means and CI are computed from (not a separately-recomputed raw set), so
398
+ * a gate reads numbers consistent with what the table displays. Raw counts
399
+ * (consumer divides) keep this truncation-consistent. A non-zero
400
+ * `*Failed` means that side's mean rests on a thinned sample — the gate-side
401
+ * `--max-scorer-error-rate` flag refuses to certify when it's over tolerance.
402
+ */
403
+ baselineScored?: number;
404
+ baselineFailed?: number;
405
+ candidateScored?: number;
406
+ candidateFailed?: number;
407
+ /**
408
+ * Per-side `applies`-skipped (N/A) counts over the same truncated pool.
409
+ * Skips are excluded from both the mean and the failure-rate denominator,
410
+ * so they never move the delta — but a side that skipped items scored a
411
+ * different subset than a side that didn't, so surfacing the count lets a
412
+ * consumer explain a delta that's really a sample mismatch rather than a
413
+ * regression.
414
+ */
415
+ baselineSkipped?: number;
416
+ candidateSkipped?: number;
219
417
  }>;
220
418
  timing?: {
221
419
  baselineMean: number;
@@ -297,6 +495,48 @@ declare function runEval(config: EvalConfig, executeWorkflow: (input: unknown, r
297
495
  }>, runtime: AxlRuntime, options?: RunEvalOptions): Promise<EvalResult>;
298
496
 
299
497
  declare function evalCompare(baseline: EvalResult | EvalResult[], candidate: EvalResult | EvalResult[], options?: EvalCompareOptions): EvalComparison;
498
+ /**
499
+ * Decide whether a comparison should be REFUSED under a gate-side scorer
500
+ * failure-rate limit (`axl-eval compare --max-scorer-error-rate`). Pure and
501
+ * testable — returns a human-readable refusal reason, or `null` to allow.
502
+ *
503
+ * Type-aware via the baseline's `scorerTypes` metadata: a scorer EXPLICITLY
504
+ * marked `'deterministic'` tolerates ZERO failures (a deterministic throw is a
505
+ * bug); everything else — including an unknown/absent type on a pre-`scorerTypes`
506
+ * artifact — uses the LLM `limit`. Defaulting unknown types to LLM (the
507
+ * permissive tier) is deliberate: classifying an old artifact's scorers as
508
+ * deterministic would hard-fail them on the first flake, contradicting the
509
+ * `--max-scorer-error-rate <n>` the user passed. Scorer NAMES are identical
510
+ * across sides (enforced by `evalCompare`), so reading types from the baseline
511
+ * is sufficient.
512
+ *
513
+ * Also refuses a scorer that produced ZERO scored items on a side — a mean over
514
+ * an empty sample can't be certified. Counts come from the same truncated pool
515
+ * `evalCompare` used for the means/CI (`baseline/candidateScored/Failed`).
516
+ */
517
+ declare function evaluateScorerErrorRateGate(comparison: EvalComparison, maxScorerErrorRate: number): string | null;
518
+
519
+ /** A scorer's failure-rate verdict against a tolerance — see {@link evaluateScorerTolerance}. */
520
+ type ScorerToleranceVerdict = {
521
+ /** `scored + failed` — the attempted denominator (excludes cancelled/never-run). */
522
+ attempted: number;
523
+ /** `failed / attempted`, or `0` when nothing was attempted. */
524
+ rate: number;
525
+ /** Over tolerance AND something was actually attempted. */
526
+ exceeds: boolean;
527
+ /** Nothing was attempted (`attempted === 0`) — no basis to certify a rate. */
528
+ zeroSample: boolean;
529
+ };
530
+ /**
531
+ * Single source of truth for the type-aware failure-rate decision, shared by the
532
+ * source-side gate (`runEval` → `summary.degraded`) and the gate-side compare
533
+ * gate (`evalCompare` consumers). Deterministic scorers tolerate ZERO failures
534
+ * (a deterministic throw is a bug, not noise); LLM scorers tolerate up to `limit`
535
+ * (`failed / attempted`). `exceeds` is never true when nothing was attempted —
536
+ * callers decide their own policy for `zeroSample` (the runner skips it; the
537
+ * compare gate refuses to certify a zero-sample scorer).
538
+ */
539
+ declare function evaluateScorerTolerance(scored: number, failed: number, type: 'llm' | 'deterministic', limit: number): ScorerToleranceVerdict;
300
540
 
301
541
  type BootstrapCIResult = {
302
542
  /** Lower bound of the confidence interval. */
@@ -323,7 +563,12 @@ declare function pairedBootstrapCI(differences: number[], options?: {
323
563
  }): BootstrapCIResult;
324
564
 
325
565
  type RescoreOptions = {
566
+ /** Item-level worker-pool size (how many saved items rescore in parallel). Default 5. */
326
567
  concurrency?: number;
568
+ /** Per-item scorer fan-out (how many scorers run concurrently within one item).
569
+ * Default 5 — matches `EvalConfig.scorerConcurrency`. Worst-case concurrent
570
+ * judge calls is `concurrency × scorerConcurrency`. */
571
+ scorerConcurrency?: number;
327
572
  /** Abort signal forwarded into ScorerContext so in-flight LLM scorer calls can
328
573
  * be cancelled mid-flight. Also checked between items to short-circuit
329
574
  * remaining work. Mirrors `RunEvalOptions.signal`. */
@@ -353,6 +598,13 @@ type MultiRunSummary = {
353
598
  std: number;
354
599
  min: number;
355
600
  max: number;
601
+ /** Total valid scores summed across all runs in the group. */
602
+ scored?: number;
603
+ /** Total ran-and-failed scorer invocations summed across all runs. */
604
+ failed?: number;
605
+ /** Total `applies`-skipped (N/A) items summed across all runs. Excluded
606
+ * from both the mean and the failure-rate denominator. */
607
+ skipped?: number;
356
608
  }>;
357
609
  timing?: {
358
610
  mean: number;
@@ -364,4 +616,4 @@ type MultiRunSummary = {
364
616
  */
365
617
  declare function aggregateRuns(runs: EvalResult[]): MultiRunSummary;
366
618
 
367
- export { type BootstrapCIResult, type Dataset, type DatasetConfig, type DatasetItem, type EvalCompareOptions, type EvalComparison, type EvalComparisonPartial, type EvalConfig, type EvalImprovement, type EvalItem, type EvalProgressEvent, type EvalRegression, type EvalResult, type EvalSummary, type LlmScorerConfig, type MultiRunSummary, type RescoreOptions, type RunEvalOptions, type Scorer, type ScorerConfig, type ScorerContext, type ScorerDetail, type ScorerFn, type ScorerResult, aggregateRuns, dataset, defineEval, evalCompare, llmScorer, normalizeScorerResult, pairedBootstrapCI, rescore, runEval, scorer };
619
+ export { type BootstrapCIResult, type Dataset, type DatasetConfig, type DatasetItem, type DegradedScorer, type EvalCompareOptions, type EvalComparison, type EvalComparisonPartial, type EvalConfig, type EvalImprovement, type EvalItem, type EvalProgressEvent, type EvalRegression, type EvalResult, type EvalSummary, type ExtraKeyPolicy, type LlmScorerConfig, type MultiRunSummary, type RescoreOptions, type RunEvalOptions, type Scorer, type ScorerApplies, type ScorerConfig, type ScorerContext, type ScorerDetail, type ScorerFn, type ScorerResult, type ScorerToleranceVerdict, aggregateRuns, dataset, defineEval, evalCompare, evaluateScorerErrorRateGate, evaluateScorerTolerance, llmScorer, normalizeScorerResult, pairedBootstrapCI, rescore, runEval, scorer };