@posthog/ai 8.19.3 → 8.20.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/README.md CHANGED
@@ -178,7 +178,7 @@ Model identifiers must be nonempty strings of at most 255 characters and are pre
178
178
  trimming. Explicit models survive serialization, retries, and recovery. Changing a model requires
179
179
  a new item UUID because model attribution is part of the immutable execution declaration.
180
180
 
181
- `scorers` provides create/get/list/update/createVersion/getVersion/listVersions. Configurations
181
+ `scorers` provides create/get/list/update/createVersion/getVersion/listVersions/validateComposition. Configurations
182
182
  are typed by `kind`: `boolean`, `numeric`, or `categorical`. Store `currentVersionId` to pin a
183
183
  configuration. Metadata updates do not create versions; explicit `createVersion` does, including
184
184
  when the configuration is unchanged. Optional `baseVersion` detects conflicting version writes.
@@ -186,10 +186,84 @@ Scorer names are not unique. A result with `status: 'ok'` means the evaluator su
186
186
  may still fail the pinned scorer's passing rule. Other statuses are `error`, `skipped`, and
187
187
  `not_applicable`, and carry no score.
188
188
 
189
+ ### Composite scorers
190
+
191
+ Composite scorers calculate an item score on the server from exact, pinned versions of reported
192
+ scorers. This requires the composite scorer backend rollout. Ordinary scorer requests and uploads
193
+ remain compatible with older backends.
194
+
195
+ ```ts
196
+ import { EvaluationItem, EvaluationResult } from '@posthog/ai/evaluations'
197
+
198
+ const quality = await evaluations.scorers.get(qualityScorerId)
199
+ const safety = await evaluations.scorers.get(safetyScorerId)
200
+ const composition = {
201
+ expression: 'quality * number(safe)',
202
+ inputs: [
203
+ { alias: 'quality', scorerVersionId: quality.currentVersionId },
204
+ { alias: 'safe', scorerVersionId: safety.currentVersionId },
205
+ ],
206
+ }
207
+ // Validation checks syntax, input access, and types without saving a scorer.
208
+ await evaluations.scorers.validateComposition({ kind: 'numeric', composition, config: { min: 0, max: 1 } })
209
+ const combined = await evaluations.scorers.create({
210
+ name: 'Safe answer quality',
211
+ kind: 'numeric',
212
+ config: { min: 0, max: 1 },
213
+ calculation: 'composite',
214
+ composition,
215
+ })
216
+ const experiment = await evaluations.createExperiment({
217
+ name: 'Combined quality',
218
+ expectedItemCount: 1,
219
+ expectedResultCount: 3,
220
+ })
221
+ const item = new EvaluationItem({ input: 'Question', output: 'Answer' })
222
+ const receipt = await experiment.uploadResults([
223
+ new EvaluationResult({ item, scorerVersionId: quality.currentVersionId, value: 0.8 }),
224
+ new EvaluationResult({ item, scorerVersionId: safety.currentVersionId, value: true }),
225
+ new EvaluationResult({ item, scorerVersionId: combined.currentVersionId, calculate: true }),
226
+ ])
227
+ // An acknowledged calculation may have failed; inspect its stored outcome.
228
+ const outcome = receipt.chunks[0].results[2]
229
+ if (outcome.status === 'error') console.error(outcome.errorCode)
230
+ await experiment.complete()
231
+ ```
232
+
233
+ The example uses numeric quality and Boolean safety scorers. Boolean inputs retain their raw
234
+ polarity; categorical inputs are lists of keys, usable as `"safe" in categories`. Formulas support
235
+ arithmetic, comparisons, membership, Boolean operators, conditionals, `number`, `min`, `max`, and
236
+ `abs`. They accept 1–16 inputs and up to 1,024 characters. Aliases must be unique lowercase
237
+ identifiers (`[a-z][a-z0-9_]{0,31}`), cannot be formula keywords/functions, and must occur in the
238
+ expression. Nested composites and numeric composite `step` values are unsupported.
239
+
240
+ Calculation mode and output kind are fixed after creation. Pass the complete `composition` to
241
+ `createVersion`, alongside `config` and optionally `baseVersion`. Source updates never change
242
+ existing pins: `inputScorers` exposes both pinned config and latest-version metadata.
243
+ `list({ calculation: 'composite', inputDefinitionId })` finds dependent composites.
244
+ Omitting `config` from `validateComposition` checks syntax and types only; runtime values and
245
+ output bounds are checked during ingestion. The SDK never evaluates formulas or discovers inputs.
246
+
247
+ Use `calculate: true` without a value, payload, error, evaluator trace, or evaluation time.
248
+ Ingestion-only keys must supply every pinned input in the same upload, including on exact retries.
249
+ Reusing stored inputs without resubmitting them requires both `evaluation:read` and
250
+ `llm_analytics:read`. Bulk uploads preserve caller order and keep all supplied results for a
251
+ composite-bearing item together, including intervening results. Group each item's results together
252
+ in large batches: an indivisible group exceeding 1,000 items/results or 5 MiB rejects the entire
253
+ bulk call before any request is sent.
254
+
255
+ Receipts expose stored `status` and `errorCode`. Input errors propagate as `composite_input_error`;
256
+ formula or output-rule failures use `composite_formula_error`. Accepted composite errors count
257
+ toward `expectedResultCount`, while derived results add no uploaded-result billing usage.
258
+ Exact retries return stored outcomes, subject to current access checks. Older reported receipts
259
+ without outcomes expose `status: null` and `errorCode: null`. Save and restore calculation
260
+ declarations with the same serialization and recovery methods as reported results.
261
+
189
262
  | Operation | Credential and scope |
190
263
  | -------------------------------------- | -------------------------------------------------------------------- |
191
264
  | Dataset reads/writes | Personal key: `dataset:read` / `dataset:write` |
192
265
  | Scorer reads/writes | Personal key: `llm_analytics:read` / `llm_analytics:write` |
266
+ | Formula validation | Personal key: `llm_analytics:read` |
193
267
  | Experiment create/upload/complete/fail | Personal or project secret key: `offline_evaluation_ingestion:write` |
194
268
  | Experiment tags | Personal key: `evaluation:read` / `evaluation:write` |
195
269
 
@@ -3,7 +3,7 @@ let _google_adk = require("@google/adk");
3
3
  let uuid = require("uuid");
4
4
  let _posthog_core = require("@posthog/core");
5
5
  //#region package.json
6
- var version = "8.19.3";
6
+ var version = "8.20.1";
7
7
  //#endregion
8
8
  //#region src/typeGuards.ts
9
9
  const isObject = (value) => {
@@ -2,7 +2,7 @@ import { BasePlugin } from "@google/adk";
2
2
  import { v4 } from "uuid";
3
3
  import { toJsonSafeValue, uuidv7 } from "@posthog/core";
4
4
  //#region package.json
5
- var version = "8.19.3";
5
+ var version = "8.20.1";
6
6
  //#endregion
7
7
  //#region src/typeGuards.ts
8
8
  const isObject = (value) => {
@@ -415,7 +415,7 @@ function addDefaults(params) {
415
415
  }
416
416
  //#endregion
417
417
  //#region package.json
418
- var version = "8.19.3";
418
+ var version = "8.20.1";
419
419
  //#endregion
420
420
  //#region src/serializeError.ts
421
421
  const DEFAULT_MAX_DEPTH = 3;
@@ -388,7 +388,7 @@ function addDefaults(params) {
388
388
  }
389
389
  //#endregion
390
390
  //#region package.json
391
- var version = "8.19.3";
391
+ var version = "8.20.1";
392
392
  //#endregion
393
393
  //#region src/serializeError.ts
394
394
  const DEFAULT_MAX_DEPTH = 3;
@@ -3,7 +3,7 @@ let _anthropic_ai_claude_agent_sdk = require("@anthropic-ai/claude-agent-sdk");
3
3
  let uuid = require("uuid");
4
4
  let _posthog_core = require("@posthog/core");
5
5
  //#region package.json
6
- var version = "8.19.3";
6
+ var version = "8.20.1";
7
7
  //#endregion
8
8
  //#region src/captureAiEvent.ts
9
9
  /** @internal */
@@ -2,7 +2,7 @@ import { SYSTEM_PROMPT_DYNAMIC_BOUNDARY, query as query$1 } from "@anthropic-ai/
2
2
  import { v4 } from "uuid";
3
3
  import { toJsonSafeValue, uuidv7 } from "@posthog/core";
4
4
  //#region package.json
5
- var version = "8.19.3";
5
+ var version = "8.20.1";
6
6
  //#endregion
7
7
  //#region src/captureAiEvent.ts
8
8
  /** @internal */
@@ -748,6 +748,7 @@ var EvaluationResult = class EvaluationResult {
748
748
  keys(options, [
749
749
  "item",
750
750
  "scorerVersionId",
751
+ "calculate",
751
752
  "status",
752
753
  "value",
753
754
  "errorCode",
@@ -759,6 +760,9 @@ var EvaluationResult = class EvaluationResult {
759
760
  this.item = options.item instanceof EvaluationItem ? options.item : uuid(options.item);
760
761
  this.itemId = typeof this.item === "string" ? this.item : this.item.id;
761
762
  this.scorerVersionId = uuid(options.scorerVersionId);
763
+ if (options.calculate !== void 0 && typeof options.calculate !== "boolean") throw new TypeError("calculate must be a boolean.");
764
+ this.calculate = options.calculate === true;
765
+ if (this.calculate && (options.value != null || options.status !== void 0 && options.status !== "ok" || options.errorCode != null || options.evaluatorTraceId != null || options.evaluatedAt != null || ["payload", ...Object.keys(RESULT_FIELDS)].some((key) => options[key] !== void 0))) throw new TypeError("A calculation accepts only item, scorerVersionId, and calculate: true.");
762
766
  const status = options.status ?? "ok";
763
767
  if (![
764
768
  "ok",
@@ -770,10 +774,13 @@ var EvaluationResult = class EvaluationResult {
770
774
  if (status !== "error" && options.errorCode != null) throw new TypeError("Only error results can contain an error code.");
771
775
  const body = {
772
776
  item_id: this.itemId,
773
- scorer_version_id: this.scorerVersionId,
774
- status
777
+ scorer_version_id: this.scorerVersionId
775
778
  };
776
- if (status === "ok") body.value = score(options.value);
779
+ if (this.calculate) body.calculate = true;
780
+ else {
781
+ body.status = status;
782
+ if (status === "ok") body.value = score(options.value);
783
+ }
777
784
  if (options.errorCode != null) body.error_code = identifier(options.errorCode, 128);
778
785
  if (options.evaluatorTraceId != null) body.evaluator_trace_id = identifier(options.evaluatorTraceId);
779
786
  if (options.evaluatedAt != null) body.evaluated_at = timestamp(options.evaluatedAt);
@@ -798,6 +805,7 @@ var EvaluationResult = class EvaluationResult {
798
805
  keys(data, [
799
806
  "item_id",
800
807
  "scorer_version_id",
808
+ "calculate",
801
809
  "status",
802
810
  "value",
803
811
  "error_code",
@@ -811,6 +819,7 @@ var EvaluationResult = class EvaluationResult {
811
819
  return new EvaluationResult(defined({
812
820
  item: options.item ?? itemId,
813
821
  scorerVersionId: data.scorer_version_id,
822
+ calculate: data.calculate,
814
823
  status: data.status,
815
824
  value: valueInput,
816
825
  errorCode: data.error_code,
@@ -841,6 +850,73 @@ const CONFIG_KEYS = {
841
850
  minSelections: "min_selections",
842
851
  maxSelections: "max_selections"
843
852
  };
853
+ function calculation(value) {
854
+ if (value !== "reported" && value !== "composite") throw new TypeError("Unsupported scorer calculation.");
855
+ return value;
856
+ }
857
+ function alias(value) {
858
+ const name = text(value);
859
+ if (name.trim() !== name || !/^[a-z][a-z0-9_]{0,31}$/.test(name) || [
860
+ "number",
861
+ "min",
862
+ "max",
863
+ "abs",
864
+ "and",
865
+ "or",
866
+ "not",
867
+ "if",
868
+ "else",
869
+ "in",
870
+ "is",
871
+ "lambda",
872
+ "for",
873
+ "await"
874
+ ].includes(name)) throw new TypeError("Invalid composite input alias.");
875
+ return name;
876
+ }
877
+ function composition(value, fromWire = false) {
878
+ const data = object(value);
879
+ const expression = text(data.expression);
880
+ if (!expression.trim() || Array.from(expression).length > 1024) throw new TypeError("A formula must contain 1–1024 characters.");
881
+ if (!Array.isArray(data.inputs) || data.inputs.length < 1 || data.inputs.length > 16) throw new TypeError("A composite requires 1–16 reported inputs.");
882
+ const inputs = Array.from(data.inputs, (entry) => {
883
+ const input = object(entry);
884
+ return {
885
+ alias: alias(input.alias),
886
+ scorerVersionId: uuid(input[fromWire ? "scorer_version_id" : "scorerVersionId"])
887
+ };
888
+ });
889
+ if (new Set(inputs.map((input) => input.alias)).size !== inputs.length) throw new TypeError("Composite input aliases must be unique.");
890
+ return {
891
+ expression,
892
+ inputs
893
+ };
894
+ }
895
+ function compositionBody(value) {
896
+ const parsed = composition(value);
897
+ return {
898
+ expression: parsed.expression,
899
+ inputs: parsed.inputs.map((input) => ({
900
+ alias: input.alias,
901
+ scorer_version_id: input.scorerVersionId
902
+ }))
903
+ };
904
+ }
905
+ function scoring(data) {
906
+ const selected = calculation(data.calculation === void 0 ? "reported" : data.calculation);
907
+ if (selected === "composite") return {
908
+ calculation: selected,
909
+ composition: composition(data.composition, true)
910
+ };
911
+ if (data.composition != null) throw new TypeError("Reported scorers cannot contain a composition.");
912
+ return {
913
+ calculation: selected,
914
+ composition: null
915
+ };
916
+ }
917
+ function compositeConfig(value) {
918
+ if (value.step != null) throw new TypeError("Numeric composite scorers do not accept a step.");
919
+ }
844
920
  function kind(value) {
845
921
  if (value !== "boolean" && value !== "numeric" && value !== "categorical") throw new TypeError("Unsupported scorer kind.");
846
922
  return value;
@@ -902,6 +978,9 @@ function scorer(data, project, id) {
902
978
  if (id !== void 0 && identity !== id || integer(data.team) !== project) throw new TypeError("Mismatched scorer scope.");
903
979
  return {
904
980
  id: identity,
981
+ ...scoring(data),
982
+ inputScorers: inputScorers(data.input_scorers === void 0 ? [] : data.input_scorers),
983
+ dependentCompositeCount: data.dependent_composite_count === void 0 ? 0 : integer(data.dependent_composite_count, 0),
905
984
  name: text(data.name),
906
985
  description: text(data.description),
907
986
  archived: boolean(data.archived),
@@ -920,6 +999,7 @@ function version(data, scorerId, versionId) {
920
999
  if (uuid(data.definition_id) !== scorerId || versionId !== void 0 && versionId !== id) throw new TypeError("Mismatched scorer version.");
921
1000
  return {
922
1001
  id,
1002
+ ...scoring(data),
923
1003
  definitionId: scorerId,
924
1004
  version: integer(data.version),
925
1005
  ...parsedConfig(data.kind, data.config),
@@ -927,6 +1007,22 @@ function version(data, scorerId, versionId) {
927
1007
  createdBy: nullable(data.created_by, responseMetadata)
928
1008
  };
929
1009
  }
1010
+ function inputScorers(value) {
1011
+ if (!Array.isArray(value)) throw new TypeError("Expected input scorer metadata.");
1012
+ return Array.from(value, (entry) => {
1013
+ const row = object(entry);
1014
+ return {
1015
+ alias: alias(row.alias),
1016
+ scorerVersionId: uuid(row.scorer_version_id),
1017
+ definitionId: uuid(row.definition_id),
1018
+ name: text(row.name),
1019
+ version: integer(row.version),
1020
+ ...parsedConfig(row.kind, row.config),
1021
+ latestVersionId: nullable(row.latest_version_id, uuid),
1022
+ latestVersion: nullable(row.latest_version, integer)
1023
+ };
1024
+ });
1025
+ }
930
1026
  function fields(options) {
931
1027
  return defined({
932
1028
  name: options.name === void 0 ? void 0 : identifier(options.name, 400),
@@ -935,7 +1031,7 @@ function fields(options) {
935
1031
  tags: options.tags === void 0 ? void 0 : tags(options.tags)
936
1032
  });
937
1033
  }
938
- /** Versioned scorer definitions. Evaluator execution remains caller-owned. */
1034
+ /** Versioned scorer definitions. Reported evaluators run in the caller; composites calculate on the server. */
939
1035
  var Scorers = class {
940
1036
  #transport;
941
1037
  #base;
@@ -952,18 +1048,29 @@ var Scorers = class {
952
1048
  "kind",
953
1049
  "config",
954
1050
  "description",
955
- "tags"
1051
+ "tags",
1052
+ "calculation",
1053
+ "composition"
956
1054
  ]);
1055
+ const selectedCalculation = calculation(options.calculation === void 0 ? "reported" : options.calculation);
1056
+ if (selectedCalculation === "composite" !== (options.composition != null)) throw new TypeError("Provide composition only for a composite scorer.");
957
1057
  const selectedKind = kind(options.kind);
1058
+ const outputConfig = config(options.config, true);
1059
+ if (selectedCalculation === "composite") compositeConfig(outputConfig);
958
1060
  const body = encode(json({
959
1061
  ...fields(options),
960
1062
  name: identifier(options.name, 400),
961
1063
  kind: selectedKind,
962
- config: config(options.config, true)
1064
+ config: outputConfig,
1065
+ ...selectedCalculation === "composite" ? {
1066
+ calculation: selectedCalculation,
1067
+ composition: compositionBody(options.composition)
1068
+ } : {}
963
1069
  }));
964
1070
  return this.#request("POST", this.#base, (data) => {
965
1071
  const result = scorer(data, this.#transport.projectId);
966
1072
  if (result.kind !== selectedKind) throw new TypeError("Mismatched scorer kind.");
1073
+ if (result.calculation !== selectedCalculation) throw new TypeError("Mismatched scorer calculation.");
967
1074
  return result;
968
1075
  }, {
969
1076
  ...request,
@@ -994,6 +1101,8 @@ var Scorers = class {
994
1101
  ...defined({
995
1102
  search: options.search === void 0 ? void 0 : text(options.search),
996
1103
  kind: options.kind === void 0 ? void 0 : kind(options.kind),
1104
+ calculation: options.calculation === void 0 ? void 0 : calculation(options.calculation),
1105
+ input_definition_id: options.inputDefinitionId === void 0 ? void 0 : uuid(options.inputDefinitionId),
997
1106
  archived: options.archived === void 0 ? void 0 : String(boolean(options.archived)),
998
1107
  order_by: options.orderBy
999
1108
  })
@@ -1020,24 +1129,54 @@ var Scorers = class {
1020
1129
  body: encode(json(fields(options)))
1021
1130
  });
1022
1131
  }
1132
+ /** Composite versions require a complete composition, even when only changing output config. */
1023
1133
  async createVersion(scorerId, options, request = {}) {
1024
1134
  keys(options, [
1025
1135
  "config",
1136
+ "composition",
1026
1137
  "baseVersion",
1027
1138
  "name",
1028
1139
  "description"
1029
1140
  ]);
1030
1141
  const id = uuid(scorerId);
1142
+ const outputConfig = config(options.config, true);
1143
+ if (options.composition != null) compositeConfig(outputConfig);
1031
1144
  const body = encode(json({
1032
1145
  ...fields(options),
1033
- config: config(options.config, true),
1034
- ...defined({ base_version: options.baseVersion === void 0 ? void 0 : integer(options.baseVersion) })
1146
+ config: outputConfig,
1147
+ ...defined({
1148
+ composition: options.composition == null ? void 0 : compositionBody(options.composition),
1149
+ base_version: options.baseVersion === void 0 ? void 0 : integer(options.baseVersion)
1150
+ })
1035
1151
  }));
1036
1152
  return this.#request("POST", `${this.#base}${id}/new_version/`, (data) => scorer(data, this.#transport.projectId, id), {
1037
1153
  ...request,
1038
1154
  body
1039
1155
  });
1040
1156
  }
1157
+ /** Validate syntax and types without saving, using llm_analytics:read access. Omit config for syntax/type checks only. */
1158
+ async validateComposition(options, request = {}) {
1159
+ keys(options, [
1160
+ "kind",
1161
+ "composition",
1162
+ "config"
1163
+ ]);
1164
+ const outputConfig = options.config === void 0 ? void 0 : config(options.config, true);
1165
+ if (outputConfig) compositeConfig(outputConfig);
1166
+ const body = encode(json(defined({
1167
+ kind: kind(options.kind),
1168
+ composition: compositionBody(options.composition),
1169
+ config: outputConfig
1170
+ })));
1171
+ return this.#request("POST", `${this.#base}validate_composition/`, (data) => {
1172
+ if (data.valid !== true) throw new TypeError("Expected successful formula validation.");
1173
+ return true;
1174
+ }, {
1175
+ ...request,
1176
+ body,
1177
+ retrySafe: true
1178
+ });
1179
+ }
1041
1180
  async getVersion(scorerId, versionId, request = {}) {
1042
1181
  const id = uuid(scorerId), selected = uuid(versionId);
1043
1182
  return this.#request("GET", `${this.#base}${id}/versions/${selected}/`, (data) => version(data, id, selected), request);
@@ -1315,15 +1454,27 @@ function uploadReceipt(data, submitted) {
1315
1454
  const items = data.items.map(itemReceipt);
1316
1455
  const results = data.results.map((value) => {
1317
1456
  const row = object(value);
1457
+ const hasOutcome = Object.hasOwn(row, "status") || Object.hasOwn(row, "error_code");
1458
+ if (hasOutcome && (typeof row.status !== "string" || ![
1459
+ "ok",
1460
+ "error",
1461
+ "skipped",
1462
+ "not_applicable"
1463
+ ].includes(row.status) || !Object.hasOwn(row, "error_code"))) throw new TypeError("Invalid stored result outcome.");
1464
+ const errorCode = hasOutcome ? nullable(row.error_code, (value) => identifier(value, 128)) : null;
1465
+ if (errorCode !== null && row.status !== "error") throw new TypeError("Only an error outcome can contain an error code.");
1318
1466
  return {
1319
1467
  ...itemReceipt(row),
1320
1468
  itemId: uuid(row.item_id),
1321
- scorerVersionId: uuid(row.scorer_version_id)
1469
+ scorerVersionId: uuid(row.scorer_version_id),
1470
+ status: hasOutcome ? row.status : null,
1471
+ errorCode
1322
1472
  };
1323
1473
  });
1324
1474
  const expectedItems = new Set(submitted.map((r) => r.itemId)), actualItems = new Set(items.map((i) => i.id));
1325
1475
  if (actualItems.size !== items.length || actualItems.size !== expectedItems.size || [...expectedItems].some((id) => !actualItems.has(id))) throw new TypeError("Incomplete item acknowledgments.");
1326
1476
  if (results.length !== submitted.length || results.some((r, i) => r.itemId !== submitted[i].itemId || r.scorerVersionId !== submitted[i].scorerVersionId) || new Set(results.map((r) => r.id)).size !== results.length) throw new TypeError("Incomplete result acknowledgments.");
1477
+ if (results.some((result, index) => submitted[index].calculate && result.status === null)) throw new TypeError("A composite acknowledgment must include its stored outcome.");
1327
1478
  return {
1328
1479
  items,
1329
1480
  results
@@ -1332,6 +1483,26 @@ function uploadReceipt(data, submitted) {
1332
1483
  function uploadBody(items, results) {
1333
1484
  return `{"items":[${items.join(",")}],"results":[${results.join(",")}]}`;
1334
1485
  }
1486
+ function groupEnds(results) {
1487
+ const first = /* @__PURE__ */ new Map(), last = /* @__PURE__ */ new Map(), compositeItems = /* @__PURE__ */ new Set();
1488
+ results.forEach((result, index) => {
1489
+ if (!first.has(result.itemId)) first.set(result.itemId, index);
1490
+ last.set(result.itemId, index + 1);
1491
+ if (result.calculate) compositeItems.add(result.itemId);
1492
+ });
1493
+ const spans = new Map([...compositeItems].map((id) => [first.get(id), last.get(id)]));
1494
+ const ends = [];
1495
+ let index = 0;
1496
+ while (index < results.length) {
1497
+ let end = index + 1;
1498
+ while (index < end) {
1499
+ end = Math.max(end, spans.get(index) ?? index + 1);
1500
+ index++;
1501
+ }
1502
+ ends.push(end);
1503
+ }
1504
+ return ends;
1505
+ }
1335
1506
  function chunks(input) {
1336
1507
  if (!Array.isArray(input)) throw new TypeError("uploadResults expects a finite array of EvaluationResult declarations.");
1337
1508
  const original = Array.from(input), identities = /* @__PURE__ */ new Set(), declarations = /* @__PURE__ */ new Map();
@@ -1349,31 +1520,39 @@ function chunks(input) {
1349
1520
  const prepared = original.map((r) => typeof r.item === "string" && declarations.has(r.itemId) ? EvaluationResult.fromJSON(r.toJSON(), { item: declarations.get(r.itemId) }) : r);
1350
1521
  const output = [];
1351
1522
  let start = 0, size = bytes(uploadBody([], [])), encodedItems = [], encodedResults = [], itemIds = /* @__PURE__ */ new Set();
1352
- for (let index = 0; index < prepared.length; index++) {
1353
- const result = prepared[index], resultBody = resultJSON(result), declaration = declarations.get(result.itemId);
1354
- let itemBody = declaration && !itemIds.has(result.itemId) ? itemJSON(declaration) : void 0;
1355
- let extra = bytes(resultBody) + (encodedResults.length ? 1 : 0) + (itemBody === void 0 ? 0 : bytes(itemBody) + (encodedItems.length ? 1 : 0));
1356
- if (encodedResults.length && (encodedResults.length >= 1e3 || encodedItems.length + (itemBody === void 0 ? 0 : 1) > 1e3 || size + extra > 5242880)) {
1523
+ let groupStart = 0;
1524
+ for (const end of groupEnds(prepared)) {
1525
+ const group = prepared.slice(groupStart, end);
1526
+ const groupResults = group.map(resultJSON);
1527
+ const groupItems = /* @__PURE__ */ new Map();
1528
+ for (const result of group) {
1529
+ const declaration = declarations.get(result.itemId);
1530
+ if (declaration) groupItems.set(result.itemId, itemJSON(declaration));
1531
+ }
1532
+ const resultBytes = groupResults.reduce((total, body) => total + bytes(body), 0);
1533
+ let newItems, extra;
1534
+ while (true) {
1535
+ newItems = [...groupItems].filter(([id]) => !itemIds.has(id)).map(([, body]) => body);
1536
+ extra = resultBytes + groupResults.length - (encodedResults.length ? 0 : 1);
1537
+ if (newItems.length) extra += newItems.reduce((total, body) => total + bytes(body), 0) + newItems.length - (encodedItems.length ? 0 : 1);
1538
+ if (encodedResults.length + groupResults.length <= 1e3 && encodedItems.length + newItems.length <= 1e3 && size + extra <= 5242880) break;
1539
+ if (!encodedResults.length) throw new TypeError("One result or composite item group exceeds the upload request limit.");
1357
1540
  output.push({
1358
1541
  start,
1359
- results: prepared.slice(start, index),
1542
+ results: prepared.slice(start, groupStart),
1360
1543
  body: uploadBody(encodedItems, encodedResults)
1361
1544
  });
1362
- start = index;
1545
+ start = groupStart;
1363
1546
  size = bytes(uploadBody([], []));
1364
1547
  encodedItems = [];
1365
1548
  encodedResults = [];
1366
1549
  itemIds = /* @__PURE__ */ new Set();
1367
- itemBody = declaration ? itemJSON(declaration) : void 0;
1368
- extra = bytes(resultBody) + (itemBody === void 0 ? 0 : bytes(itemBody));
1369
- }
1370
- if (size + extra > 5242880) throw new TypeError("One item/result pair exceeds the request byte limit.");
1371
- if (itemBody !== void 0) {
1372
- itemIds.add(result.itemId);
1373
- encodedItems.push(itemBody);
1374
1550
  }
1375
- encodedResults.push(resultBody);
1551
+ for (const id of groupItems.keys()) itemIds.add(id);
1552
+ encodedItems.push(...newItems);
1553
+ encodedResults.push(...groupResults);
1376
1554
  size += extra;
1555
+ groupStart = end;
1377
1556
  }
1378
1557
  if (encodedResults.length) output.push({
1379
1558
  start,
@@ -1440,6 +1619,11 @@ var Experiment = class {
1440
1619
  retrySafe: true
1441
1620
  }), (data) => uploadReceipt(data, chunk.results));
1442
1621
  }
1622
+ /**
1623
+ * Keeps composite items and their supplied inputs in one request, preserving order.
1624
+ * Interleaved items may form an indivisible group; oversized groups fail before any I/O.
1625
+ * Ingestion-only keys must supply every pinned input, including on retries.
1626
+ */
1443
1627
  async uploadResults(results, request = {}) {
1444
1628
  const prepared = chunks(results);
1445
1629
  return this.#queue.run(async () => {