@superbased/sdk 0.0.1-placeholder.0 → 0.1.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 (118) hide show
  1. package/NOTICE +4 -0
  2. package/README.md +434 -5
  3. package/dist/cjs/admit.d.ts +139 -0
  4. package/dist/cjs/admit.js +442 -0
  5. package/dist/cjs/admit.js.map +1 -0
  6. package/dist/cjs/attrs.d.ts +113 -0
  7. package/dist/cjs/attrs.js +183 -0
  8. package/dist/cjs/attrs.js.map +1 -0
  9. package/dist/cjs/config.d.ts +202 -0
  10. package/dist/cjs/config.js +386 -0
  11. package/dist/cjs/config.js.map +1 -0
  12. package/dist/cjs/context.d.ts +102 -0
  13. package/dist/cjs/context.js +234 -0
  14. package/dist/cjs/context.js.map +1 -0
  15. package/dist/cjs/control.d.ts +99 -0
  16. package/dist/cjs/control.js +243 -0
  17. package/dist/cjs/control.js.map +1 -0
  18. package/dist/cjs/cost.d.ts +108 -0
  19. package/dist/cjs/cost.js +211 -0
  20. package/dist/cjs/cost.js.map +1 -0
  21. package/dist/cjs/destination.d.ts +125 -0
  22. package/dist/cjs/destination.js +357 -0
  23. package/dist/cjs/destination.js.map +1 -0
  24. package/dist/cjs/experiments.d.ts +237 -0
  25. package/dist/cjs/experiments.js +678 -0
  26. package/dist/cjs/experiments.js.map +1 -0
  27. package/dist/cjs/export.d.ts +84 -0
  28. package/dist/cjs/export.js +328 -0
  29. package/dist/cjs/export.js.map +1 -0
  30. package/dist/cjs/index.d.ts +168 -0
  31. package/dist/cjs/index.js +581 -0
  32. package/dist/cjs/index.js.map +1 -0
  33. package/dist/cjs/instrument.d.ts +88 -0
  34. package/dist/cjs/instrument.js +397 -0
  35. package/dist/cjs/instrument.js.map +1 -0
  36. package/dist/cjs/package.json +1 -0
  37. package/dist/cjs/policy.d.ts +77 -0
  38. package/dist/cjs/policy.js +252 -0
  39. package/dist/cjs/policy.js.map +1 -0
  40. package/dist/cjs/prompts.d.ts +175 -0
  41. package/dist/cjs/prompts.js +476 -0
  42. package/dist/cjs/prompts.js.map +1 -0
  43. package/dist/cjs/propagation.d.ts +34 -0
  44. package/dist/cjs/propagation.js +151 -0
  45. package/dist/cjs/propagation.js.map +1 -0
  46. package/dist/cjs/req.d.ts +10 -0
  47. package/dist/cjs/req.js +3 -0
  48. package/dist/cjs/req.js.map +1 -0
  49. package/dist/cjs/runtime.d.ts +44 -0
  50. package/dist/cjs/runtime.js +67 -0
  51. package/dist/cjs/runtime.js.map +1 -0
  52. package/dist/cjs/scores.d.ts +102 -0
  53. package/dist/cjs/scores.js +226 -0
  54. package/dist/cjs/scores.js.map +1 -0
  55. package/dist/cjs/spans.d.ts +193 -0
  56. package/dist/cjs/spans.js +398 -0
  57. package/dist/cjs/spans.js.map +1 -0
  58. package/dist/cjs/vendor.d.ts +33 -0
  59. package/dist/cjs/vendor.js +67 -0
  60. package/dist/cjs/vendor.js.map +1 -0
  61. package/dist/esm/admit.d.ts +139 -0
  62. package/dist/esm/admit.js +432 -0
  63. package/dist/esm/admit.js.map +1 -0
  64. package/dist/esm/attrs.d.ts +113 -0
  65. package/dist/esm/attrs.js +179 -0
  66. package/dist/esm/attrs.js.map +1 -0
  67. package/dist/esm/config.d.ts +202 -0
  68. package/dist/esm/config.js +364 -0
  69. package/dist/esm/config.js.map +1 -0
  70. package/dist/esm/context.d.ts +102 -0
  71. package/dist/esm/context.js +221 -0
  72. package/dist/esm/context.js.map +1 -0
  73. package/dist/esm/control.d.ts +99 -0
  74. package/dist/esm/control.js +230 -0
  75. package/dist/esm/control.js.map +1 -0
  76. package/dist/esm/cost.d.ts +108 -0
  77. package/dist/esm/cost.js +202 -0
  78. package/dist/esm/cost.js.map +1 -0
  79. package/dist/esm/destination.d.ts +125 -0
  80. package/dist/esm/destination.js +346 -0
  81. package/dist/esm/destination.js.map +1 -0
  82. package/dist/esm/experiments.d.ts +237 -0
  83. package/dist/esm/experiments.js +666 -0
  84. package/dist/esm/experiments.js.map +1 -0
  85. package/dist/esm/export.d.ts +84 -0
  86. package/dist/esm/export.js +314 -0
  87. package/dist/esm/export.js.map +1 -0
  88. package/dist/esm/index.d.ts +168 -0
  89. package/dist/esm/index.js +500 -0
  90. package/dist/esm/index.js.map +1 -0
  91. package/dist/esm/instrument.d.ts +88 -0
  92. package/dist/esm/instrument.js +391 -0
  93. package/dist/esm/instrument.js.map +1 -0
  94. package/dist/esm/policy.d.ts +77 -0
  95. package/dist/esm/policy.js +240 -0
  96. package/dist/esm/policy.js.map +1 -0
  97. package/dist/esm/prompts.d.ts +175 -0
  98. package/dist/esm/prompts.js +460 -0
  99. package/dist/esm/prompts.js.map +1 -0
  100. package/dist/esm/propagation.d.ts +34 -0
  101. package/dist/esm/propagation.js +145 -0
  102. package/dist/esm/propagation.js.map +1 -0
  103. package/dist/esm/req.d.ts +10 -0
  104. package/dist/esm/req.js +2 -0
  105. package/dist/esm/req.js.map +1 -0
  106. package/dist/esm/runtime.d.ts +44 -0
  107. package/dist/esm/runtime.js +59 -0
  108. package/dist/esm/runtime.js.map +1 -0
  109. package/dist/esm/scores.d.ts +102 -0
  110. package/dist/esm/scores.js +219 -0
  111. package/dist/esm/scores.js.map +1 -0
  112. package/dist/esm/spans.d.ts +193 -0
  113. package/dist/esm/spans.js +378 -0
  114. package/dist/esm/spans.js.map +1 -0
  115. package/dist/esm/vendor.d.ts +33 -0
  116. package/dist/esm/vendor.js +61 -0
  117. package/dist/esm/vendor.js.map +1 -0
  118. package/package.json +121 -4
@@ -0,0 +1,666 @@
1
+ /**
2
+ * Datasets and experiments (W3-2; contract `contracts/experiments.md`, lane
3
+ * B7; the same flow as the Python SDK's `run_experiment`).
4
+ *
5
+ * `runExperiment({ dataset, task, evaluators })`:
6
+ * 1. finds the dataset by name or id on each destination side (online
7
+ * first, then this machine), or uploads inline items as a literal
8
+ * snapshot of `datasetName` (created on the machine; on the org it must
9
+ * exist). Inline items without `datasetName` run in-process only and
10
+ * nothing is posted;
11
+ * 2. creates a run on each side (`POST /v1/sdk/experiments`, machine
12
+ * `/api/obs/eval/experiments`), which freezes a snapshot unless
13
+ * `snapshotVersion` pins one, and reads that snapshot's items. Under `both`
14
+ * the task runs once: the other side's items are matched by client id,
15
+ * then by input;
16
+ * 3. runs `task` on each item in its own trace (a CHAIN root span stamped
17
+ * `sbo.experiment.run_id` / `sbo.experiment.item_id`), then the
18
+ * evaluators in-process;
19
+ * 4. posts each item's result (output under captureContent, scores, error)
20
+ * to each run as it finishes; the server also stores each score on the
21
+ * item's trace;
22
+ * 5. finishes the runs and reads their totals.
23
+ *
24
+ * An experiment is an explicit batch job, so unlike the tracing calls a
25
+ * dataset that cannot be found or a run that cannot be created rejects with
26
+ * {@link ExperimentError}, and `failUnder` rejects with
27
+ * {@link ExperimentGateFailed} (and sets `process.exitCode = 1`) when the
28
+ * pass rate is below it. A task or evaluator that throws is recorded on its
29
+ * item; the run goes on. CI credentials need the `sdk:eval` scope.
30
+ */
31
+ import { createHash } from "node:crypto";
32
+ import { context, trace } from "@opentelemetry/api";
33
+ import { K } from "./attrs.js";
34
+ import { apiTimeout, call, newId, noTargetReason, retryable, targets } from "./control.js";
35
+ import { contentText, destinationKnown, runtime, truncateContent } from "./runtime.js";
36
+ import { getCurrentTraceId, Kind, setInput, setOutput, withSpan } from "./spans.js";
37
+ /** The experiment could not be set up (dataset, run creation). */
38
+ export class ExperimentError extends Error {
39
+ constructor(message) {
40
+ super(message);
41
+ this.name = "ExperimentError";
42
+ }
43
+ }
44
+ /**
45
+ * A destination refused a dataset or experiment call for want of a scope
46
+ * (403 `insufficient_scope`): a member SDK key from `observer sdk sign-in`
47
+ * deliberately lacks `sdk:eval`, which every org dataset and experiment route
48
+ * needs. runExperiment skips that destination with an entry in `errors` and
49
+ * carries on with the other one; it never rejects for this.
50
+ */
51
+ class SideSkipped extends ExperimentError {
52
+ }
53
+ function scopeRefused(r) {
54
+ return r.status === 403 && r.error === "insufficient_scope";
55
+ }
56
+ function skipReason(side, what, r) {
57
+ return `${side}: skipped, ${what} refused: ${describe(r)} (an SDK key from sign-in has no sdk:eval scope; run experiments on the org with a CI credential that has it)`;
58
+ }
59
+ /**
60
+ * The `failUnder` gate failed (a CI gate): the pass rate is below it, or,
61
+ * strict (the default), `reasons` says why the gate could not pass at all.
62
+ */
63
+ export class ExperimentGateFailed extends Error {
64
+ result;
65
+ failUnder;
66
+ reasons;
67
+ constructor(result, failUnder, reasons = []) {
68
+ super(reasons.length
69
+ ? `experiment ${JSON.stringify(result.name)}: the failUnder gate cannot pass: ${reasons.join("; ")} (strict; pass strict: false to gate on the pass rate alone)`
70
+ : `experiment ${JSON.stringify(result.name)}: pass rate ${result.passRate.toFixed(3)} is below ${failUnder.toFixed(3)}`);
71
+ this.result = result;
72
+ this.failUnder = failUnder;
73
+ this.reasons = reasons;
74
+ this.name = "ExperimentGateFailed";
75
+ }
76
+ }
77
+ /**
78
+ * The `failUnder` gate (contract experiments.md 4.2, review E-12): `reasons`
79
+ * are why a strict gate fails before the rate is compared (nothing scored, a
80
+ * skipped destination, results not accepted); `failed` applies them when
81
+ * `strict`, then the rate. A run that scored nothing is not failed when not
82
+ * strict. Python: gate_problems / gate_fails.
83
+ */
84
+ export function experimentGate(r, failUnder, strict = true) {
85
+ const reasons = [];
86
+ if (r.scored === 0)
87
+ reasons.push("no item was scored (no evaluator returned a score)");
88
+ for (const side of r.skippedSides)
89
+ reasons.push(`the ${side} destination was skipped`);
90
+ if (r.failedPosts)
91
+ reasons.push(`${r.failedPosts} result(s) were not accepted, so the recorded pass rate covers only part of the run`);
92
+ if (failUnder === undefined || failUnder === null)
93
+ return { failed: false, reasons };
94
+ if (strict && reasons.length)
95
+ return { failed: true, reasons };
96
+ return { failed: r.scored > 0 && !(r.passRate >= failUnder), reasons };
97
+ }
98
+ function obj(v) {
99
+ return v !== null && typeof v === "object" && !Array.isArray(v) ? v : {};
100
+ }
101
+ const idOf = (v) => (typeof v === "string" || typeof v === "number" ? String(v) : "");
102
+ function describe(r) {
103
+ return `${r.target}: ${r.status ? `HTTP ${r.status} ` : ""}${r.error}${r.message ? `: ${r.message}` : ""}`;
104
+ }
105
+ const enc = encodeURIComponent;
106
+ /** Find a dataset by name or id on one target. */
107
+ async function findDataset(t, nameOrId, opts) {
108
+ const timeoutMs = apiTimeout(opts);
109
+ const list = await call(t, "GET", { online: `/datasets?name=${enc(nameOrId)}`, local: "/api/obs/eval/datasets" }, { timeoutMs, quiet404: true });
110
+ if (scopeRefused(list))
111
+ return { id: "", name: "", error: skipReason(t.name, "dataset list", list), skipped: true };
112
+ if (list.ok) {
113
+ const rows = (Array.isArray(obj(list.body).datasets) ? obj(list.body).datasets : Array.isArray(list.body) ? list.body : []);
114
+ const hit = rows.map(obj).find((d) => d.name === nameOrId || idOf(d.id) === nameOrId);
115
+ if (hit)
116
+ return { id: idOf(hit.id), name: String(hit.name ?? nameOrId), error: "" };
117
+ }
118
+ const one = await call(t, "GET", { online: `/datasets/${enc(nameOrId)}`, local: `/api/obs/eval/datasets/${enc(nameOrId)}` }, { timeoutMs, quiet404: true });
119
+ if (one.ok) {
120
+ const d = obj(obj(one.body).dataset ?? one.body);
121
+ if (idOf(d.id))
122
+ return { id: idOf(d.id), name: String(d.name ?? nameOrId), error: "" };
123
+ }
124
+ return { id: "", name: "", error: list.ok ? `${t.name}: no dataset named ${JSON.stringify(nameOrId)}` : describe(list) };
125
+ }
126
+ function parseItem(x) {
127
+ return {
128
+ item: {
129
+ id: idOf(x.item_id ?? x.id) || undefined,
130
+ input: x.input,
131
+ expectedOutput: x.expected ?? x.expected_output,
132
+ metadata: Object.keys(obj(x.metadata)).length ? obj(x.metadata) : undefined,
133
+ },
134
+ hasContent: x.has_content !== false,
135
+ };
136
+ }
137
+ /**
138
+ * Compact JSON with object keys sorted at every level (`undefined` as null):
139
+ * the same text Python's canonical form gives, so both SDKs derive the same
140
+ * item id.
141
+ */
142
+ function canonical(v) {
143
+ if (v === undefined || v === null)
144
+ return "null";
145
+ if (Array.isArray(v))
146
+ return `[${v.map(canonical).join(",")}]`;
147
+ if (typeof v === "object") {
148
+ const o = v;
149
+ return `{${Object.keys(o)
150
+ .sort()
151
+ .map((k) => `${JSON.stringify(k)}:${canonical(o[k])}`)
152
+ .join(",")}}`;
153
+ }
154
+ return JSON.stringify(v) ?? "null";
155
+ }
156
+ /**
157
+ * The default id of a literal item: derived from its content (review E-75),
158
+ * so a re-run with changed inputs makes new items on the machine instead of
159
+ * matching the previous run's `item-00001`. Python gives the same id
160
+ * (sdk-behaviour-cases.json `literal_item_ids`).
161
+ */
162
+ export function literalItemId(input, expected, metadata) {
163
+ return "item-" + createHash("sha256").update(canonical([input, expected, metadata]), "utf8").digest("hex").slice(0, 16);
164
+ }
165
+ /**
166
+ * Inline items as the literal upload rows `{id, input, expected, metadata?}`.
167
+ * A missing id is {@link literalItemId} of the content; the same content
168
+ * twice gets `-2`, `-3`, ... (E-75; Python's `_literal`).
169
+ */
170
+ export function literalRows(ds) {
171
+ const seen = new Map();
172
+ return ds.map((it) => {
173
+ const expected = it.expectedOutput ?? it.expected;
174
+ let id = it.id === undefined || it.id === null || it.id === "" ? "" : String(it.id);
175
+ if (!id) {
176
+ id = literalItemId(it.input, expected, it.metadata);
177
+ const n = (seen.get(id) ?? 0) + 1;
178
+ seen.set(id, n);
179
+ if (n > 1)
180
+ id = `${id}-${n}`;
181
+ }
182
+ const row = { id, input: it.input, expected };
183
+ if (it.metadata)
184
+ row.metadata = it.metadata;
185
+ return row;
186
+ });
187
+ }
188
+ /** Read a snapshot's items on one target (all pages); `runId`: the run's own items on the machine. */
189
+ async function readItems(t, datasetId, version, opts, runId = "") {
190
+ const items = [];
191
+ const rawItems = [];
192
+ let skipped = 0;
193
+ let cursor = "";
194
+ for (let page = 0; page < 1000; page++) {
195
+ const q = `limit=500${cursor ? `&cursor=${enc(cursor)}` : ""}`;
196
+ const r = await call(t, "GET", {
197
+ online: `/datasets/${enc(datasetId)}/snapshots/${version}/items?${q}`,
198
+ // run=: the run's pinned set (a literal upload), else every item up to its version (R-B22, E-75).
199
+ local: `/api/obs/eval/datasets/${enc(datasetId)}/items?${q}${version ? `&version=${version}` : ""}${runId ? `&run=${enc(runId)}` : ""}`,
200
+ }, { timeoutMs: apiTimeout(opts) });
201
+ if (!r.ok)
202
+ return { items, raw: rawItems, skipped, error: describe(r), scopeRefused: scopeRefused(r) ? r : undefined };
203
+ const body = obj(r.body);
204
+ for (const raw of (Array.isArray(body.items) ? body.items : [])) {
205
+ const { item, hasContent } = parseItem(obj(raw));
206
+ if (hasContent) {
207
+ items.push(item);
208
+ rawItems.push(obj(raw));
209
+ }
210
+ else
211
+ skipped += 1;
212
+ }
213
+ cursor = typeof body.next_cursor === "string" ? body.next_cursor : "";
214
+ if (!cursor)
215
+ break;
216
+ }
217
+ return { items, raw: rawItems, skipped, error: "" };
218
+ }
219
+ /**
220
+ * Fetch a dataset's items: by name or id, from a snapshot `version` (default
221
+ * the latest), from the first destination that has it (the org first under
222
+ * `both`). Rejects with {@link ExperimentError} when no destination has it
223
+ * (or none is usable), as Python's `get_dataset` raises (review R-C34);
224
+ * `errors` lists what an earlier destination answered when a later one had
225
+ * it.
226
+ */
227
+ export async function getDataset(nameOrId, opts = {}) {
228
+ const errors = [];
229
+ await destinationKnown();
230
+ const ts = targets("read", opts);
231
+ if (!ts.length)
232
+ errors.push(noTargetReason());
233
+ for (const t of ts) {
234
+ const ds = await findDataset(t, nameOrId, opts);
235
+ if (!ds.id) {
236
+ errors.push(ds.error);
237
+ continue;
238
+ }
239
+ let version = opts.version ?? 0;
240
+ if (!version && t.name === "online") {
241
+ const d = await call(t, "GET", `/datasets/${enc(ds.id)}`, { timeoutMs: apiTimeout(opts) });
242
+ const snaps = (Array.isArray(obj(d.body).snapshots) ? obj(d.body).snapshots : []);
243
+ version = Math.max(0, ...snaps.map((x) => Number(obj(x).version) || 0));
244
+ if (!version)
245
+ version = Number(obj(obj(d.body).dataset).latest_snapshot) || 0;
246
+ }
247
+ const r = await readItems(t, ds.id, version, opts);
248
+ if (r.error) {
249
+ errors.push(r.error);
250
+ continue;
251
+ }
252
+ return { id: ds.id, name: ds.name, version, items: r.items, skippedNoContent: r.skipped, target: t.name, errors };
253
+ }
254
+ const why = errors.filter((e) => e);
255
+ throw new ExperimentError(`dataset ${JSON.stringify(nameOrId)} not found${why.length ? `: ${why.join("; ")}` : ""}`);
256
+ }
257
+ function evaluatorMeta(e, i) {
258
+ if (typeof e === "function")
259
+ return { name: e.name || `evaluator_${i + 1}`, version: "1", run: e };
260
+ return { name: e.name || `evaluator_${i + 1}`, version: e.version || "1", run: (a) => e.evaluate(a) };
261
+ }
262
+ function normalize(name, r) {
263
+ if (r === null || r === undefined)
264
+ return null;
265
+ if (typeof r === "object") {
266
+ if (r.value === undefined || r.value === null)
267
+ return null;
268
+ return { name: r.name || name, value: r.value, comment: r.comment };
269
+ }
270
+ return { name, value: r };
271
+ }
272
+ async function mapLimit(items, limit, fn) {
273
+ const out = new Array(items.length);
274
+ let next = 0;
275
+ const workers = Array.from({ length: Math.max(1, Math.min(limit, items.length)) }, async () => {
276
+ while (next < items.length) {
277
+ const i = next++;
278
+ out[i] = await fn(items[i], i);
279
+ }
280
+ });
281
+ await Promise.all(workers);
282
+ return out;
283
+ }
284
+ const keyOf = (input) => {
285
+ try {
286
+ return JSON.stringify(input, Object.keys(obj(input)).sort()) ?? String(input);
287
+ }
288
+ catch {
289
+ return String(input);
290
+ }
291
+ };
292
+ function routes(id = "", version = 0) {
293
+ const i = enc(id);
294
+ return {
295
+ datasets: { online: "/datasets", local: "/api/obs/eval/datasets" },
296
+ snapshot: { online: `/datasets/${i}/snapshots`, local: `/api/obs/eval/datasets/${i}/items` },
297
+ experiments: { online: "/experiments", local: "/api/obs/eval/experiments" },
298
+ results: { online: `/experiments/${i}/results`, local: `/api/obs/eval/experiments/${i}/results` },
299
+ finish: { online: `/experiments/${i}/finish`, local: `/api/obs/eval/experiments/${i}/finish` },
300
+ run: { online: `/experiments/${i}`, local: `/api/obs/eval/experiments/${i}` },
301
+ version,
302
+ };
303
+ }
304
+ /** Put literal items where a run can see them: [dataset id, snapshot version, the machine's ids of exactly these items (empty on the org)]. */
305
+ async function uploadLiteral(t, datasetName, items, timeoutMs) {
306
+ let id = "";
307
+ if (t.name === "local") {
308
+ const made = await call(t, "POST", routes().datasets, { body: { name: datasetName }, timeoutMs });
309
+ if (scopeRefused(made))
310
+ throw new SideSkipped(skipReason(t.name, "dataset create", made));
311
+ if (!made.ok)
312
+ throw new ExperimentError(`local: dataset create: ${describe(made)}`);
313
+ id = idOf(obj(obj(made.body).dataset ?? made.body).id);
314
+ if (!id)
315
+ throw new ExperimentError("local: dataset create answered no id");
316
+ }
317
+ else {
318
+ const found = await findDataset(t, datasetName, { timeoutMs });
319
+ if (found.skipped)
320
+ throw new SideSkipped(found.error);
321
+ if (!found.id)
322
+ throw new ExperimentError(`online: dataset ${JSON.stringify(datasetName)} does not exist on the org (create it on the dashboard first)`);
323
+ id = found.id;
324
+ }
325
+ const r = await call(t, "POST", routes(id).snapshot, { body: { items }, timeoutMs });
326
+ if (scopeRefused(r))
327
+ throw new SideSkipped(skipReason(t.name, "dataset snapshot", r));
328
+ if (!r.ok)
329
+ throw new ExperimentError(`${t.name}: dataset snapshot: ${describe(r)}`);
330
+ const raw = obj(r.body).item_ids;
331
+ const pinned = t.name === "local" && Array.isArray(raw) ? raw.filter((x) => typeof x === "string" || typeof x === "number").map(String) : [];
332
+ return [id, Number(obj(r.body).version ?? obj(r.body).snapshot_version) || 0, pinned];
333
+ }
334
+ /**
335
+ * Run `task` over a dataset and score each output.
336
+ *
337
+ * ```ts
338
+ * const res = await runExperiment({
339
+ * name: "prompt-v7",
340
+ * dataset: "golden-qa",
341
+ * task: async (input) => answer(input),
342
+ * evaluators: [function exact_match({ output, expectedOutput }) { return output === expectedOutput; }],
343
+ * failUnder: 0.9,
344
+ * });
345
+ * ```
346
+ */
347
+ export async function runExperiment(opts) {
348
+ const name = opts.name || opts.task.name || "experiment";
349
+ const result = {
350
+ runId: "",
351
+ runs: {},
352
+ name,
353
+ datasetId: "",
354
+ snapshotVersion: 0,
355
+ items: [],
356
+ summary: {},
357
+ passRate: NaN,
358
+ scored: 0,
359
+ recorded: false,
360
+ skippedNoContent: 0,
361
+ errors: [],
362
+ skippedSides: [],
363
+ failedPosts: 0,
364
+ server: {},
365
+ };
366
+ const evaluators = (opts.evaluators ?? []).map(evaluatorMeta);
367
+ const scorers = evaluators.map((e) => ({ name: e.name, version: e.version }));
368
+ const timeoutMs = apiTimeout(opts);
369
+ await destinationKnown();
370
+ const sides = targets("read", opts); // online first, then this machine
371
+ const runs = [];
372
+ let items = [];
373
+ // 1. The dataset on each side.
374
+ const ds = opts.dataset;
375
+ if (Array.isArray(ds)) {
376
+ const literal = literalRows(ds);
377
+ items = literal.map((r) => ({ id: String(r.id), input: r.input, expectedOutput: r.expected, metadata: r.metadata }));
378
+ if (opts.datasetName) {
379
+ // A degraded online uploads nothing: the run stays in-process and says
380
+ // why (contract section 6; as Python).
381
+ if (!sides.length)
382
+ result.errors.push(`dataset ${JSON.stringify(opts.datasetName)} not uploaded, the run is in-process only: ${noTargetReason()}`);
383
+ for (const t of sides) {
384
+ try {
385
+ const [id, version, pinned] = await uploadLiteral(t, opts.datasetName, literal, timeoutMs);
386
+ runs.push({ target: t, datasetId: id, version, id: "", itemIds: new Map(), pinned });
387
+ }
388
+ catch (err) {
389
+ if (!(err instanceof SideSkipped))
390
+ throw err;
391
+ result.errors.push(err.message);
392
+ result.skippedSides.push(t.name);
393
+ }
394
+ }
395
+ }
396
+ }
397
+ else {
398
+ const ref = typeof ds === "string" ? ds : ds.id;
399
+ if (!sides.length)
400
+ throw new ExperimentError(`dataset ${JSON.stringify(ref)}: ${noTargetReason()}`);
401
+ let skipped = 0;
402
+ for (const t of sides) {
403
+ const found = typeof ds !== "string" && ds.target && ds.target !== t.name && ds.name ? await findDataset(t, ds.name, opts) : await findDataset(t, ref, opts);
404
+ if (found.skipped) {
405
+ result.errors.push(found.error);
406
+ result.skippedSides.push(t.name);
407
+ skipped += 1;
408
+ }
409
+ else if (found.id)
410
+ runs.push({ target: t, datasetId: found.id, version: opts.snapshotVersion ?? opts.datasetVersion ?? 0, id: "", itemIds: new Map(), pinned: [] });
411
+ }
412
+ if (!runs.length && !skipped)
413
+ throw new ExperimentError(`dataset ${JSON.stringify(ref)} not found on any destination`);
414
+ }
415
+ // 2. A run on each side, and its snapshot's items. A side that refuses
416
+ // for want of a scope is skipped (SideSkipped), the others go on.
417
+ const started = [];
418
+ // One idempotency id per runExperiment call (review E-79): every side's
419
+ // create carries it, and a create retried after no answer, a 429 or a 5xx
420
+ // carries it again, so the side answers the run the first attempt opened
421
+ // instead of opening a second one (contract experiments.md 4.1).
422
+ const createId = newId();
423
+ for (const r of runs) {
424
+ const create = { id: createId, name, dataset_id: r.datasetId, snapshot_version: r.version, metadata: opts.metadata ?? {}, scorers };
425
+ if (r.pinned.length)
426
+ create.item_ids = r.pinned;
427
+ let created = await call(r.target, "POST", routes().experiments, { body: create, timeoutMs });
428
+ if (retryable(created))
429
+ created = await call(r.target, "POST", routes().experiments, { body: create, timeoutMs });
430
+ if (scopeRefused(created)) {
431
+ result.errors.push(skipReason(r.target.name, "experiment create", created));
432
+ result.skippedSides.push(r.target.name);
433
+ continue;
434
+ }
435
+ if (!created.ok)
436
+ throw new ExperimentError(`${r.target.name}: experiment create: ${describe(created)}`);
437
+ const body = obj(created.body);
438
+ r.id = idOf(body.id);
439
+ if (!r.id)
440
+ throw new ExperimentError(`${r.target.name}: experiment create answered no id`);
441
+ r.version = Number(body.snapshot_version) || r.version;
442
+ const read = await readItems(r.target, r.datasetId, r.version, opts, r.target.name === "local" ? r.id : "");
443
+ if (read.scopeRefused) {
444
+ result.errors.push(skipReason(r.target.name, "dataset items", read.scopeRefused));
445
+ result.skippedSides.push(r.target.name);
446
+ continue;
447
+ }
448
+ if (read.error)
449
+ throw new ExperimentError(`${r.target.name}: dataset items: ${read.error}`);
450
+ result.runs[r.target.name] = r.id;
451
+ const n = started.length;
452
+ started.push(r);
453
+ if (n === 0 && !Array.isArray(ds)) {
454
+ items = read.items;
455
+ result.skippedNoContent = read.skipped;
456
+ items.forEach((it, i) => r.itemIds.set(i, it.id ?? ""));
457
+ }
458
+ else {
459
+ // Match this side's items to ours: by client id, then by input.
460
+ const byClient = new Map();
461
+ const byInput = new Map();
462
+ for (const it of read.raw) {
463
+ const id = idOf(it.item_id ?? it.id);
464
+ if (it.client_id)
465
+ byClient.set(idOf(it.client_id), id);
466
+ const k = keyOf(it.input);
467
+ byInput.set(k, [...(byInput.get(k) ?? []), id]);
468
+ }
469
+ let unmatched = 0;
470
+ items.forEach((it, i) => {
471
+ const hit = (it.id && byClient.get(it.id)) || byInput.get(keyOf(it.input))?.shift();
472
+ if (hit)
473
+ r.itemIds.set(i, hit);
474
+ else
475
+ unmatched += 1;
476
+ });
477
+ if (unmatched)
478
+ result.errors.push(`${r.target.name}: ${unmatched} item(s) have no match there; their results go to ${started[0].target.name} only`);
479
+ }
480
+ }
481
+ runs.splice(0, runs.length, ...started);
482
+ if (runs.length) {
483
+ result.runId = runs[0].id;
484
+ result.datasetId = runs[0].datasetId;
485
+ result.snapshotVersion = runs[0].version;
486
+ }
487
+ // 3-4. Run, evaluate, post each result.
488
+ const firstRunId = runs[0]?.id ?? "";
489
+ result.items = await mapLimit(items, opts.maxConcurrency ?? 4, async (item, idx) => {
490
+ const ir = { item, traceId: "", output: undefined, error: "", scores: [], postError: "" };
491
+ const itemId = runs[0]?.itemIds.get(idx) || item.id || "";
492
+ const attrs = {};
493
+ if (firstRunId)
494
+ attrs[K.experimentRunId] = firstRunId;
495
+ if (itemId)
496
+ attrs[K.experimentItemId] = itemId;
497
+ // Each item is its own trace, even when runExperiment runs inside a span.
498
+ await context
499
+ .with(trace.deleteSpan(context.active()), () => withSpan(`experiment ${name}`, { kind: Kind.CHAIN, attributes: attrs }, async (span) => {
500
+ ir.traceId = getCurrentTraceId();
501
+ setInput(span, item.input);
502
+ try {
503
+ ir.output = await opts.task(item.input, item);
504
+ setOutput(span, ir.output);
505
+ }
506
+ catch (err) {
507
+ ir.error = (err instanceof Error ? `${err.name}: ${err.message}` : String(err)).slice(0, 500);
508
+ throw err; // the span records it; the item keeps the error
509
+ }
510
+ }))
511
+ .catch(() => undefined);
512
+ const wire = [];
513
+ if (!ir.error) {
514
+ const args = {
515
+ input: item.input,
516
+ output: ir.output,
517
+ expectedOutput: item.expectedOutput,
518
+ expected: item.expectedOutput,
519
+ metadata: item.metadata ?? {},
520
+ item,
521
+ };
522
+ for (const ev of evaluators) {
523
+ try {
524
+ const raw = await ev.run(args);
525
+ for (const one of Array.isArray(raw) ? raw : [raw]) {
526
+ const sc = normalize(ev.name, one);
527
+ if (!sc)
528
+ continue;
529
+ ir.scores.push(sc);
530
+ wire.push({ name: sc.name, value: sc.value, ...(sc.comment ? { comment: sc.comment } : {}), scorer: { name: ev.name, version: ev.version } });
531
+ }
532
+ }
533
+ catch (err) {
534
+ ir.scores.push({ name: ev.name, value: "", error: (err instanceof Error ? err.message : String(err)).slice(0, 300) });
535
+ }
536
+ }
537
+ }
538
+ for (const r of runs) {
539
+ const sideItem = r.itemIds.get(idx);
540
+ if (!sideItem)
541
+ continue;
542
+ const row = { item_id: sideItem, scores: wire };
543
+ if (ir.traceId)
544
+ row.trace_id = ir.traceId;
545
+ if (ir.error)
546
+ row.error = ir.error;
547
+ if (runtime.captureContent && ir.output !== undefined)
548
+ row.output = truncateContent(contentText(ir.output));
549
+ const resp = await call(r.target, "POST", routes(r.id).results, { body: { results: [row] }, timeoutMs });
550
+ const rejected = (Array.isArray(obj(resp.body).rejected) ? obj(resp.body).rejected : []);
551
+ const why = !resp.ok ? describe(resp) : rejected.length ? `${String(obj(rejected[0]).error)}: ${String(obj(rejected[0]).message ?? "")}` : "";
552
+ if (why) {
553
+ ir.postError = ir.postError ? `${ir.postError}; ${r.target.name}: ${why}` : `${r.target.name}: ${why}`;
554
+ result.failedPosts += 1;
555
+ }
556
+ }
557
+ return ir;
558
+ });
559
+ // Local summary.
560
+ const sums = {};
561
+ for (const it of result.items) {
562
+ for (const sc of it.scores) {
563
+ if (sc.error)
564
+ continue;
565
+ const v = typeof sc.value === "boolean" ? (sc.value ? 1 : 0) : typeof sc.value === "number" ? sc.value : NaN;
566
+ if (!Number.isFinite(v))
567
+ continue;
568
+ sums[sc.name] ??= { sum: 0, count: 0 };
569
+ sums[sc.name].sum += v;
570
+ sums[sc.name].count += 1;
571
+ }
572
+ }
573
+ for (const [k, v] of Object.entries(sums))
574
+ result.summary[k] = { mean: v.sum / v.count, count: v.count };
575
+ const refused = result.items.filter((i) => i.postError);
576
+ if (refused.length)
577
+ result.errors.push(`${refused.length} result(s) not accepted; first: ${refused[0].postError}`);
578
+ // 5. Finish and read the totals.
579
+ let finished = 0;
580
+ for (const r of runs) {
581
+ const fin = await call(r.target, "POST", routes(r.id).finish, { body: {}, timeoutMs });
582
+ if (!fin.ok && fin.status !== 409)
583
+ result.errors.push(`${r.target.name}: finish: ${describe(fin)}`);
584
+ else
585
+ finished += 1;
586
+ const got = await call(r.target, "GET", routes(r.id).run, { timeoutMs });
587
+ if (got.ok)
588
+ result.server[r.target.name] = obj(got.body);
589
+ }
590
+ result.recorded = runs.length > 0 && finished === runs.length;
591
+ const totals = experimentTotals(result.items, runs.map((r) => result.server[r.target.name]).filter((b) => !!b), opts.failUnder);
592
+ result.passRate = totals.passRate;
593
+ result.scored = totals.scored;
594
+ const strict = opts.strict ?? true;
595
+ const gate = experimentGate(result, opts.failUnder, strict);
596
+ if (opts.failUnder !== undefined && strict && gate.reasons.length) {
597
+ for (const r of gate.reasons)
598
+ result.errors.push(`gate: ${r}`);
599
+ if (typeof process !== "undefined")
600
+ process.exitCode = 1;
601
+ throw new ExperimentGateFailed(result, opts.failUnder, gate.reasons);
602
+ }
603
+ if (opts.failUnder !== undefined && result.scored === 0) {
604
+ const msg = "no scores: no item was scored (no evaluator ran), so failUnder was not applied (strict: false)";
605
+ result.errors.push(msg);
606
+ try {
607
+ console.warn(`@superbased/sdk: experiment ${JSON.stringify(name)}: ${msg}`);
608
+ }
609
+ catch {
610
+ // ignore
611
+ }
612
+ }
613
+ if (opts.failUnder !== undefined && gate.failed) {
614
+ if (typeof process !== "undefined")
615
+ process.exitCode = 1;
616
+ throw new ExperimentGateFailed(result, opts.failUnder);
617
+ }
618
+ return result;
619
+ }
620
+ const FAIL_LABELS = new Set(["fail", "false", "no", "bad"]);
621
+ /** B7's pass rule (contract 4.2): boolean true, a number >= 0.5, a label not fail/false/no/bad. */
622
+ export function scorePasses(v) {
623
+ if (typeof v === "boolean")
624
+ return v;
625
+ if (typeof v === "number")
626
+ return v >= 0.5;
627
+ return !FAIL_LABELS.has(v.trim().toLowerCase());
628
+ }
629
+ /** Items that count toward a pass rate: a task error, or a score an evaluator returned (one that threw is no score). */
630
+ function scoredItems(items) {
631
+ return items.filter((i) => i.error || i.scores.some((sc) => !sc.error));
632
+ }
633
+ const isCount = (v) => typeof v === "number" && Number.isInteger(v) && v >= 0;
634
+ /**
635
+ * A run's pass rate and scored count (contract experiments.md 4.2), as
636
+ * Python's ExperimentResult computes them: the first side whose totals say
637
+ * something was scored, else the local tally over scored items (an item
638
+ * passes with no task error and every returned score passing). A side's
639
+ * `pass_rate` with `total` 0 (an older server's 0 for "nothing scored") is
640
+ * not a rate. NaN when nothing was scored. `gateFailed`: the rate is below
641
+ * `failUnder`; never for a run that scored nothing.
642
+ */
643
+ export function experimentTotals(items, sides = [], failUnder) {
644
+ const local = scoredItems(items);
645
+ let scored = local.length;
646
+ for (const b of sides) {
647
+ if (isCount(b.total) && (b.total > 0 || !local.length)) {
648
+ scored = b.total;
649
+ break;
650
+ }
651
+ }
652
+ for (const b of sides) {
653
+ if (typeof b.pass_rate !== "number")
654
+ continue;
655
+ if (isCount(b.total) && b.total === 0)
656
+ continue;
657
+ return { scored, passRate: b.pass_rate, gateFailed: gate(scored, b.pass_rate, failUnder) };
658
+ }
659
+ const passed = local.filter((i) => !i.error && i.scores.every((sc) => sc.error || scorePasses(sc.value))).length;
660
+ const passRate = local.length ? passed / local.length : NaN;
661
+ return { scored, passRate, gateFailed: gate(scored, passRate, failUnder) };
662
+ }
663
+ function gate(scored, passRate, failUnder) {
664
+ return failUnder !== undefined && scored > 0 && !(passRate >= failUnder);
665
+ }
666
+ //# sourceMappingURL=experiments.js.map