@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.
@@ -200,17 +200,31 @@ type ScoreValue = boolean | number | readonly string[];
200
200
  /** bigint inputs are converted only if exactly representable as finite binary64 scores. */
201
201
  type ScoreInput = ScoreValue | bigint;
202
202
  type ResultStatus = 'ok' | 'error' | 'skipped' | 'not_applicable';
203
- type Outcome = ({
203
+ type Outcome = {
204
+ calculate: true;
205
+ status?: 'ok';
206
+ value?: null;
207
+ errorCode?: null;
208
+ payload?: never;
209
+ reasoning?: never;
210
+ errorMessage?: never;
211
+ metadata?: never;
212
+ evaluatorTraceId?: null;
213
+ evaluatedAt?: null;
214
+ } | ({
215
+ calculate?: false;
204
216
  status?: 'ok';
205
217
  value: ScoreInput;
206
218
  errorCode?: never;
207
219
  } & PayloadOptions<Omit<ResultPayload, 'errorMessage'> & {
208
220
  errorMessage?: null;
209
221
  }>) | ({
222
+ calculate?: false;
210
223
  status: 'error';
211
224
  value?: never;
212
225
  errorCode?: string;
213
226
  } & PayloadOptions<ResultPayload>) | ({
227
+ calculate?: false;
214
228
  status: 'skipped' | 'not_applicable';
215
229
  value?: never;
216
230
  errorCode?: never;
@@ -243,6 +257,8 @@ declare class EvaluationItem {
243
257
  }
244
258
  /** An evaluator outcome pinned to an exact scorer version. `ok` does not imply passing. */
245
259
  declare class EvaluationResult {
260
+ /** Request a server-calculated composite instead of reporting a value. */
261
+ readonly calculate: boolean;
246
262
  readonly item: EvaluationItem | string;
247
263
  readonly scorerVersionId: string;
248
264
  readonly itemId: string;
@@ -327,8 +343,34 @@ interface ScorerConfigs {
327
343
  categorical: CategoricalScorerConfig;
328
344
  }
329
345
  type ScorerKind = keyof ScorerConfigs;
346
+ type ScorerCalculation = 'reported' | 'composite';
347
+ interface ScorerCompositionInput {
348
+ alias: string;
349
+ scorerVersionId: string;
350
+ }
351
+ /** Server-evaluated formula with 1–16 pinned reported inputs; nested composites are unsupported. */
352
+ interface ScorerComposition {
353
+ expression: string;
354
+ inputs: readonly ScorerCompositionInput[];
355
+ }
356
+ /** Pinned input configuration alongside the source scorer's latest version. */
357
+ type ScorerInput = { [K in ScorerKind]: {
358
+ alias: string;
359
+ scorerVersionId: string;
360
+ definitionId: string;
361
+ name: string;
362
+ kind: K;
363
+ version: number;
364
+ config: ScorerConfigs[K];
365
+ latestVersionId: string | null;
366
+ latestVersion: number | null;
367
+ }; }[ScorerKind];
330
368
  type ScorerConfig = ScorerConfigs[ScorerKind];
331
369
  interface ScorerRecord {
370
+ calculation: ScorerCalculation;
371
+ composition: ScorerComposition | null;
372
+ inputScorers: ScorerInput[];
373
+ dependentCompositeCount: number;
332
374
  id: string;
333
375
  name: string;
334
376
  description: string;
@@ -342,6 +384,8 @@ interface ScorerRecord {
342
384
  createdBy: JSONObject | null;
343
385
  }
344
386
  interface VersionRecord {
387
+ calculation: ScorerCalculation;
388
+ composition: ScorerComposition | null;
345
389
  id: string;
346
390
  definitionId: string;
347
391
  version: number;
@@ -367,6 +411,8 @@ interface ScorerVersionPage {
367
411
  }
368
412
  type ScorerOrder = 'name' | '-name' | 'kind' | '-kind' | 'created_at' | '-created_at' | 'updated_at' | '-updated_at' | 'current_version' | '-current_version';
369
413
  interface ScorerListOptions extends PageOptions {
414
+ calculation?: ScorerCalculation;
415
+ inputDefinitionId?: string;
370
416
  search?: string;
371
417
  kind?: ScorerKind;
372
418
  archived?: boolean;
@@ -384,10 +430,17 @@ type CreateScorerOptions = { [K in ScorerKind]: {
384
430
  name: string;
385
431
  kind: K;
386
432
  config: ScorerConfigs[K];
433
+ calculation?: ScorerCalculation;
434
+ composition?: ScorerComposition | null;
387
435
  description?: string | null;
388
436
  tags?: readonly string[];
389
437
  }; }[ScorerKind];
390
- /** Versioned scorer definitions. Evaluator execution remains caller-owned. */
438
+ type ValidateCompositionOptions = { [K in ScorerKind]: {
439
+ kind: K;
440
+ composition: ScorerComposition;
441
+ config?: ScorerConfigs[K];
442
+ }; }[ScorerKind];
443
+ /** Versioned scorer definitions. Reported evaluators run in the caller; composites calculate on the server. */
391
444
  declare class Scorers {
392
445
  #private;
393
446
  constructor(transport: Transport);
@@ -397,12 +450,16 @@ declare class Scorers {
397
450
  get(scorerId: string, request?: RequestOptions): Promise<Scorer>;
398
451
  list(options?: ScorerListOptions): Promise<ScorerPage>;
399
452
  update(scorerId: string, options: ScorerMetadata, request?: RequestOptions): Promise<Scorer>;
453
+ /** Composite versions require a complete composition, even when only changing output config. */
400
454
  createVersion(scorerId: string, options: {
401
455
  config: ScorerConfig;
456
+ composition?: ScorerComposition | null;
402
457
  baseVersion?: number;
403
458
  name?: string;
404
459
  description?: string | null;
405
460
  }, request?: RequestOptions): Promise<Scorer>;
461
+ /** Validate syntax and types without saving, using llm_analytics:read access. Omit config for syntax/type checks only. */
462
+ validateComposition(options: ValidateCompositionOptions, request?: RequestOptions): Promise<boolean>;
406
463
  getVersion(scorerId: string, versionId: string, request?: RequestOptions): Promise<ScorerVersion>;
407
464
  listVersions(scorerId: string, options?: RequestOptions & {
408
465
  limit?: number;
@@ -447,6 +504,9 @@ interface ItemReceipt {
447
504
  interface ResultReceipt extends ItemReceipt {
448
505
  itemId: string;
449
506
  scorerVersionId: string;
507
+ /** Stored outcome; null when an older backend omits it for a reported result. */
508
+ status: ResultStatus | null;
509
+ errorCode: string | null;
450
510
  }
451
511
  interface UploadReceipt {
452
512
  items: ItemReceipt[];
@@ -477,6 +537,11 @@ declare class Experiment {
477
537
  /** Original creation options, suitable for createExperiment(submission). Large counts may be bigint. */
478
538
  get submission(): ExperimentOptions | undefined;
479
539
  uploadResult(options: EvaluationResultOptions, request?: RequestOptions): Promise<UploadReceipt>;
540
+ /**
541
+ * Keeps composite items and their supplied inputs in one request, preserving order.
542
+ * Interleaved items may form an indivisible group; oversized groups fail before any I/O.
543
+ * Ingestion-only keys must supply every pinned input, including on retries.
544
+ */
480
545
  uploadResults(results: readonly EvaluationResult[], request?: RequestOptions): Promise<BulkUploadReceipt>;
481
546
  complete(request?: RequestOptions): Promise<ExperimentReceipt>;
482
547
  fail(request?: RequestOptions): Promise<ExperimentReceipt>;
@@ -496,5 +561,5 @@ declare class OfflineEvaluations {
496
561
  close(): void;
497
562
  }
498
563
  //#endregion
499
- export { type BooleanScorerConfig, BulkUploadError, type BulkUploadReceipt, type CategoricalScorerConfig, type CategoricalScorerOption, type CreateDatasetItemOptions, type CreateScorerOptions, type Dataset, type DatasetItem, type DatasetItemPage, type DatasetListOptions, type DatasetMetadata, type DatasetOrder, type DatasetPage, type DatasetRevision, type DatasetRevisionPage, DatasetSnapshot, Datasets, EvaluationAPIError, type EvaluationCount, type EvaluationErrorFields, EvaluationItem, type EvaluationItemOptions, EvaluationResult, type EvaluationResultOptions, Experiment, ExperimentCreationAbortedError, type ExperimentOptions, type ExperimentReceipt, type ItemIdentifiers, type ItemListOptions, type ItemPayload, type ItemReceipt, type JSONObject, type JSONValue, type NumericPassingRule, type NumericScorerConfig, OfflineEvaluations, type OfflineEvaluationsOptions, type PageOptions, type Persistence, type RequestOptions, type ResultPayload, type ResultReceipt, type ResultStatus, type ScoreInput, type ScoreValue, type Scorer, type ScorerConfig, type ScorerConfigs, type ScorerKind, type ScorerListOptions, type ScorerMetadata, type ScorerOrder, type ScorerPage, type ScorerVersion, type ScorerVersionPage, Scorers, type UpdateDatasetItemOptions, type UploadReceipt };
564
+ export { type BooleanScorerConfig, BulkUploadError, type BulkUploadReceipt, type CategoricalScorerConfig, type CategoricalScorerOption, type CreateDatasetItemOptions, type CreateScorerOptions, type Dataset, type DatasetItem, type DatasetItemPage, type DatasetListOptions, type DatasetMetadata, type DatasetOrder, type DatasetPage, type DatasetRevision, type DatasetRevisionPage, DatasetSnapshot, Datasets, EvaluationAPIError, type EvaluationCount, type EvaluationErrorFields, EvaluationItem, type EvaluationItemOptions, EvaluationResult, type EvaluationResultOptions, Experiment, ExperimentCreationAbortedError, type ExperimentOptions, type ExperimentReceipt, type ItemIdentifiers, type ItemListOptions, type ItemPayload, type ItemReceipt, type JSONObject, type JSONValue, type NumericPassingRule, type NumericScorerConfig, OfflineEvaluations, type OfflineEvaluationsOptions, type PageOptions, type Persistence, type RequestOptions, type ResultPayload, type ResultReceipt, type ResultStatus, type ScoreInput, type ScoreValue, type Scorer, type ScorerCalculation, type ScorerComposition, type ScorerCompositionInput, type ScorerConfig, type ScorerConfigs, type ScorerInput, type ScorerKind, type ScorerListOptions, type ScorerMetadata, type ScorerOrder, type ScorerPage, type ScorerVersion, type ScorerVersionPage, Scorers, type UpdateDatasetItemOptions, type UploadReceipt, type ValidateCompositionOptions };
500
565
  //# sourceMappingURL=index.d.ts.map
@@ -747,6 +747,7 @@ var EvaluationResult = class EvaluationResult {
747
747
  keys(options, [
748
748
  "item",
749
749
  "scorerVersionId",
750
+ "calculate",
750
751
  "status",
751
752
  "value",
752
753
  "errorCode",
@@ -758,6 +759,9 @@ var EvaluationResult = class EvaluationResult {
758
759
  this.item = options.item instanceof EvaluationItem ? options.item : uuid(options.item);
759
760
  this.itemId = typeof this.item === "string" ? this.item : this.item.id;
760
761
  this.scorerVersionId = uuid(options.scorerVersionId);
762
+ if (options.calculate !== void 0 && typeof options.calculate !== "boolean") throw new TypeError("calculate must be a boolean.");
763
+ this.calculate = options.calculate === true;
764
+ 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.");
761
765
  const status = options.status ?? "ok";
762
766
  if (![
763
767
  "ok",
@@ -769,10 +773,13 @@ var EvaluationResult = class EvaluationResult {
769
773
  if (status !== "error" && options.errorCode != null) throw new TypeError("Only error results can contain an error code.");
770
774
  const body = {
771
775
  item_id: this.itemId,
772
- scorer_version_id: this.scorerVersionId,
773
- status
776
+ scorer_version_id: this.scorerVersionId
774
777
  };
775
- if (status === "ok") body.value = score(options.value);
778
+ if (this.calculate) body.calculate = true;
779
+ else {
780
+ body.status = status;
781
+ if (status === "ok") body.value = score(options.value);
782
+ }
776
783
  if (options.errorCode != null) body.error_code = identifier(options.errorCode, 128);
777
784
  if (options.evaluatorTraceId != null) body.evaluator_trace_id = identifier(options.evaluatorTraceId);
778
785
  if (options.evaluatedAt != null) body.evaluated_at = timestamp(options.evaluatedAt);
@@ -797,6 +804,7 @@ var EvaluationResult = class EvaluationResult {
797
804
  keys(data, [
798
805
  "item_id",
799
806
  "scorer_version_id",
807
+ "calculate",
800
808
  "status",
801
809
  "value",
802
810
  "error_code",
@@ -810,6 +818,7 @@ var EvaluationResult = class EvaluationResult {
810
818
  return new EvaluationResult(defined({
811
819
  item: options.item ?? itemId,
812
820
  scorerVersionId: data.scorer_version_id,
821
+ calculate: data.calculate,
813
822
  status: data.status,
814
823
  value: valueInput,
815
824
  errorCode: data.error_code,
@@ -840,6 +849,73 @@ const CONFIG_KEYS = {
840
849
  minSelections: "min_selections",
841
850
  maxSelections: "max_selections"
842
851
  };
852
+ function calculation(value) {
853
+ if (value !== "reported" && value !== "composite") throw new TypeError("Unsupported scorer calculation.");
854
+ return value;
855
+ }
856
+ function alias(value) {
857
+ const name = text(value);
858
+ if (name.trim() !== name || !/^[a-z][a-z0-9_]{0,31}$/.test(name) || [
859
+ "number",
860
+ "min",
861
+ "max",
862
+ "abs",
863
+ "and",
864
+ "or",
865
+ "not",
866
+ "if",
867
+ "else",
868
+ "in",
869
+ "is",
870
+ "lambda",
871
+ "for",
872
+ "await"
873
+ ].includes(name)) throw new TypeError("Invalid composite input alias.");
874
+ return name;
875
+ }
876
+ function composition(value, fromWire = false) {
877
+ const data = object(value);
878
+ const expression = text(data.expression);
879
+ if (!expression.trim() || Array.from(expression).length > 1024) throw new TypeError("A formula must contain 1–1024 characters.");
880
+ if (!Array.isArray(data.inputs) || data.inputs.length < 1 || data.inputs.length > 16) throw new TypeError("A composite requires 1–16 reported inputs.");
881
+ const inputs = Array.from(data.inputs, (entry) => {
882
+ const input = object(entry);
883
+ return {
884
+ alias: alias(input.alias),
885
+ scorerVersionId: uuid(input[fromWire ? "scorer_version_id" : "scorerVersionId"])
886
+ };
887
+ });
888
+ if (new Set(inputs.map((input) => input.alias)).size !== inputs.length) throw new TypeError("Composite input aliases must be unique.");
889
+ return {
890
+ expression,
891
+ inputs
892
+ };
893
+ }
894
+ function compositionBody(value) {
895
+ const parsed = composition(value);
896
+ return {
897
+ expression: parsed.expression,
898
+ inputs: parsed.inputs.map((input) => ({
899
+ alias: input.alias,
900
+ scorer_version_id: input.scorerVersionId
901
+ }))
902
+ };
903
+ }
904
+ function scoring(data) {
905
+ const selected = calculation(data.calculation === void 0 ? "reported" : data.calculation);
906
+ if (selected === "composite") return {
907
+ calculation: selected,
908
+ composition: composition(data.composition, true)
909
+ };
910
+ if (data.composition != null) throw new TypeError("Reported scorers cannot contain a composition.");
911
+ return {
912
+ calculation: selected,
913
+ composition: null
914
+ };
915
+ }
916
+ function compositeConfig(value) {
917
+ if (value.step != null) throw new TypeError("Numeric composite scorers do not accept a step.");
918
+ }
843
919
  function kind(value) {
844
920
  if (value !== "boolean" && value !== "numeric" && value !== "categorical") throw new TypeError("Unsupported scorer kind.");
845
921
  return value;
@@ -901,6 +977,9 @@ function scorer(data, project, id) {
901
977
  if (id !== void 0 && identity !== id || integer(data.team) !== project) throw new TypeError("Mismatched scorer scope.");
902
978
  return {
903
979
  id: identity,
980
+ ...scoring(data),
981
+ inputScorers: inputScorers(data.input_scorers === void 0 ? [] : data.input_scorers),
982
+ dependentCompositeCount: data.dependent_composite_count === void 0 ? 0 : integer(data.dependent_composite_count, 0),
904
983
  name: text(data.name),
905
984
  description: text(data.description),
906
985
  archived: boolean(data.archived),
@@ -919,6 +998,7 @@ function version(data, scorerId, versionId) {
919
998
  if (uuid(data.definition_id) !== scorerId || versionId !== void 0 && versionId !== id) throw new TypeError("Mismatched scorer version.");
920
999
  return {
921
1000
  id,
1001
+ ...scoring(data),
922
1002
  definitionId: scorerId,
923
1003
  version: integer(data.version),
924
1004
  ...parsedConfig(data.kind, data.config),
@@ -926,6 +1006,22 @@ function version(data, scorerId, versionId) {
926
1006
  createdBy: nullable(data.created_by, responseMetadata)
927
1007
  };
928
1008
  }
1009
+ function inputScorers(value) {
1010
+ if (!Array.isArray(value)) throw new TypeError("Expected input scorer metadata.");
1011
+ return Array.from(value, (entry) => {
1012
+ const row = object(entry);
1013
+ return {
1014
+ alias: alias(row.alias),
1015
+ scorerVersionId: uuid(row.scorer_version_id),
1016
+ definitionId: uuid(row.definition_id),
1017
+ name: text(row.name),
1018
+ version: integer(row.version),
1019
+ ...parsedConfig(row.kind, row.config),
1020
+ latestVersionId: nullable(row.latest_version_id, uuid),
1021
+ latestVersion: nullable(row.latest_version, integer)
1022
+ };
1023
+ });
1024
+ }
929
1025
  function fields(options) {
930
1026
  return defined({
931
1027
  name: options.name === void 0 ? void 0 : identifier(options.name, 400),
@@ -934,7 +1030,7 @@ function fields(options) {
934
1030
  tags: options.tags === void 0 ? void 0 : tags(options.tags)
935
1031
  });
936
1032
  }
937
- /** Versioned scorer definitions. Evaluator execution remains caller-owned. */
1033
+ /** Versioned scorer definitions. Reported evaluators run in the caller; composites calculate on the server. */
938
1034
  var Scorers = class {
939
1035
  #transport;
940
1036
  #base;
@@ -951,18 +1047,29 @@ var Scorers = class {
951
1047
  "kind",
952
1048
  "config",
953
1049
  "description",
954
- "tags"
1050
+ "tags",
1051
+ "calculation",
1052
+ "composition"
955
1053
  ]);
1054
+ const selectedCalculation = calculation(options.calculation === void 0 ? "reported" : options.calculation);
1055
+ if (selectedCalculation === "composite" !== (options.composition != null)) throw new TypeError("Provide composition only for a composite scorer.");
956
1056
  const selectedKind = kind(options.kind);
1057
+ const outputConfig = config(options.config, true);
1058
+ if (selectedCalculation === "composite") compositeConfig(outputConfig);
957
1059
  const body = encode(json({
958
1060
  ...fields(options),
959
1061
  name: identifier(options.name, 400),
960
1062
  kind: selectedKind,
961
- config: config(options.config, true)
1063
+ config: outputConfig,
1064
+ ...selectedCalculation === "composite" ? {
1065
+ calculation: selectedCalculation,
1066
+ composition: compositionBody(options.composition)
1067
+ } : {}
962
1068
  }));
963
1069
  return this.#request("POST", this.#base, (data) => {
964
1070
  const result = scorer(data, this.#transport.projectId);
965
1071
  if (result.kind !== selectedKind) throw new TypeError("Mismatched scorer kind.");
1072
+ if (result.calculation !== selectedCalculation) throw new TypeError("Mismatched scorer calculation.");
966
1073
  return result;
967
1074
  }, {
968
1075
  ...request,
@@ -993,6 +1100,8 @@ var Scorers = class {
993
1100
  ...defined({
994
1101
  search: options.search === void 0 ? void 0 : text(options.search),
995
1102
  kind: options.kind === void 0 ? void 0 : kind(options.kind),
1103
+ calculation: options.calculation === void 0 ? void 0 : calculation(options.calculation),
1104
+ input_definition_id: options.inputDefinitionId === void 0 ? void 0 : uuid(options.inputDefinitionId),
996
1105
  archived: options.archived === void 0 ? void 0 : String(boolean(options.archived)),
997
1106
  order_by: options.orderBy
998
1107
  })
@@ -1019,24 +1128,54 @@ var Scorers = class {
1019
1128
  body: encode(json(fields(options)))
1020
1129
  });
1021
1130
  }
1131
+ /** Composite versions require a complete composition, even when only changing output config. */
1022
1132
  async createVersion(scorerId, options, request = {}) {
1023
1133
  keys(options, [
1024
1134
  "config",
1135
+ "composition",
1025
1136
  "baseVersion",
1026
1137
  "name",
1027
1138
  "description"
1028
1139
  ]);
1029
1140
  const id = uuid(scorerId);
1141
+ const outputConfig = config(options.config, true);
1142
+ if (options.composition != null) compositeConfig(outputConfig);
1030
1143
  const body = encode(json({
1031
1144
  ...fields(options),
1032
- config: config(options.config, true),
1033
- ...defined({ base_version: options.baseVersion === void 0 ? void 0 : integer(options.baseVersion) })
1145
+ config: outputConfig,
1146
+ ...defined({
1147
+ composition: options.composition == null ? void 0 : compositionBody(options.composition),
1148
+ base_version: options.baseVersion === void 0 ? void 0 : integer(options.baseVersion)
1149
+ })
1034
1150
  }));
1035
1151
  return this.#request("POST", `${this.#base}${id}/new_version/`, (data) => scorer(data, this.#transport.projectId, id), {
1036
1152
  ...request,
1037
1153
  body
1038
1154
  });
1039
1155
  }
1156
+ /** Validate syntax and types without saving, using llm_analytics:read access. Omit config for syntax/type checks only. */
1157
+ async validateComposition(options, request = {}) {
1158
+ keys(options, [
1159
+ "kind",
1160
+ "composition",
1161
+ "config"
1162
+ ]);
1163
+ const outputConfig = options.config === void 0 ? void 0 : config(options.config, true);
1164
+ if (outputConfig) compositeConfig(outputConfig);
1165
+ const body = encode(json(defined({
1166
+ kind: kind(options.kind),
1167
+ composition: compositionBody(options.composition),
1168
+ config: outputConfig
1169
+ })));
1170
+ return this.#request("POST", `${this.#base}validate_composition/`, (data) => {
1171
+ if (data.valid !== true) throw new TypeError("Expected successful formula validation.");
1172
+ return true;
1173
+ }, {
1174
+ ...request,
1175
+ body,
1176
+ retrySafe: true
1177
+ });
1178
+ }
1040
1179
  async getVersion(scorerId, versionId, request = {}) {
1041
1180
  const id = uuid(scorerId), selected = uuid(versionId);
1042
1181
  return this.#request("GET", `${this.#base}${id}/versions/${selected}/`, (data) => version(data, id, selected), request);
@@ -1314,15 +1453,27 @@ function uploadReceipt(data, submitted) {
1314
1453
  const items = data.items.map(itemReceipt);
1315
1454
  const results = data.results.map((value) => {
1316
1455
  const row = object(value);
1456
+ const hasOutcome = Object.hasOwn(row, "status") || Object.hasOwn(row, "error_code");
1457
+ if (hasOutcome && (typeof row.status !== "string" || ![
1458
+ "ok",
1459
+ "error",
1460
+ "skipped",
1461
+ "not_applicable"
1462
+ ].includes(row.status) || !Object.hasOwn(row, "error_code"))) throw new TypeError("Invalid stored result outcome.");
1463
+ const errorCode = hasOutcome ? nullable(row.error_code, (value) => identifier(value, 128)) : null;
1464
+ if (errorCode !== null && row.status !== "error") throw new TypeError("Only an error outcome can contain an error code.");
1317
1465
  return {
1318
1466
  ...itemReceipt(row),
1319
1467
  itemId: uuid(row.item_id),
1320
- scorerVersionId: uuid(row.scorer_version_id)
1468
+ scorerVersionId: uuid(row.scorer_version_id),
1469
+ status: hasOutcome ? row.status : null,
1470
+ errorCode
1321
1471
  };
1322
1472
  });
1323
1473
  const expectedItems = new Set(submitted.map((r) => r.itemId)), actualItems = new Set(items.map((i) => i.id));
1324
1474
  if (actualItems.size !== items.length || actualItems.size !== expectedItems.size || [...expectedItems].some((id) => !actualItems.has(id))) throw new TypeError("Incomplete item acknowledgments.");
1325
1475
  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.");
1476
+ if (results.some((result, index) => submitted[index].calculate && result.status === null)) throw new TypeError("A composite acknowledgment must include its stored outcome.");
1326
1477
  return {
1327
1478
  items,
1328
1479
  results
@@ -1331,6 +1482,26 @@ function uploadReceipt(data, submitted) {
1331
1482
  function uploadBody(items, results) {
1332
1483
  return `{"items":[${items.join(",")}],"results":[${results.join(",")}]}`;
1333
1484
  }
1485
+ function groupEnds(results) {
1486
+ const first = /* @__PURE__ */ new Map(), last = /* @__PURE__ */ new Map(), compositeItems = /* @__PURE__ */ new Set();
1487
+ results.forEach((result, index) => {
1488
+ if (!first.has(result.itemId)) first.set(result.itemId, index);
1489
+ last.set(result.itemId, index + 1);
1490
+ if (result.calculate) compositeItems.add(result.itemId);
1491
+ });
1492
+ const spans = new Map([...compositeItems].map((id) => [first.get(id), last.get(id)]));
1493
+ const ends = [];
1494
+ let index = 0;
1495
+ while (index < results.length) {
1496
+ let end = index + 1;
1497
+ while (index < end) {
1498
+ end = Math.max(end, spans.get(index) ?? index + 1);
1499
+ index++;
1500
+ }
1501
+ ends.push(end);
1502
+ }
1503
+ return ends;
1504
+ }
1334
1505
  function chunks(input) {
1335
1506
  if (!Array.isArray(input)) throw new TypeError("uploadResults expects a finite array of EvaluationResult declarations.");
1336
1507
  const original = Array.from(input), identities = /* @__PURE__ */ new Set(), declarations = /* @__PURE__ */ new Map();
@@ -1348,31 +1519,39 @@ function chunks(input) {
1348
1519
  const prepared = original.map((r) => typeof r.item === "string" && declarations.has(r.itemId) ? EvaluationResult.fromJSON(r.toJSON(), { item: declarations.get(r.itemId) }) : r);
1349
1520
  const output = [];
1350
1521
  let start = 0, size = bytes(uploadBody([], [])), encodedItems = [], encodedResults = [], itemIds = /* @__PURE__ */ new Set();
1351
- for (let index = 0; index < prepared.length; index++) {
1352
- const result = prepared[index], resultBody = resultJSON(result), declaration = declarations.get(result.itemId);
1353
- let itemBody = declaration && !itemIds.has(result.itemId) ? itemJSON(declaration) : void 0;
1354
- let extra = bytes(resultBody) + (encodedResults.length ? 1 : 0) + (itemBody === void 0 ? 0 : bytes(itemBody) + (encodedItems.length ? 1 : 0));
1355
- if (encodedResults.length && (encodedResults.length >= 1e3 || encodedItems.length + (itemBody === void 0 ? 0 : 1) > 1e3 || size + extra > 5242880)) {
1522
+ let groupStart = 0;
1523
+ for (const end of groupEnds(prepared)) {
1524
+ const group = prepared.slice(groupStart, end);
1525
+ const groupResults = group.map(resultJSON);
1526
+ const groupItems = /* @__PURE__ */ new Map();
1527
+ for (const result of group) {
1528
+ const declaration = declarations.get(result.itemId);
1529
+ if (declaration) groupItems.set(result.itemId, itemJSON(declaration));
1530
+ }
1531
+ const resultBytes = groupResults.reduce((total, body) => total + bytes(body), 0);
1532
+ let newItems, extra;
1533
+ while (true) {
1534
+ newItems = [...groupItems].filter(([id]) => !itemIds.has(id)).map(([, body]) => body);
1535
+ extra = resultBytes + groupResults.length - (encodedResults.length ? 0 : 1);
1536
+ if (newItems.length) extra += newItems.reduce((total, body) => total + bytes(body), 0) + newItems.length - (encodedItems.length ? 0 : 1);
1537
+ if (encodedResults.length + groupResults.length <= 1e3 && encodedItems.length + newItems.length <= 1e3 && size + extra <= 5242880) break;
1538
+ if (!encodedResults.length) throw new TypeError("One result or composite item group exceeds the upload request limit.");
1356
1539
  output.push({
1357
1540
  start,
1358
- results: prepared.slice(start, index),
1541
+ results: prepared.slice(start, groupStart),
1359
1542
  body: uploadBody(encodedItems, encodedResults)
1360
1543
  });
1361
- start = index;
1544
+ start = groupStart;
1362
1545
  size = bytes(uploadBody([], []));
1363
1546
  encodedItems = [];
1364
1547
  encodedResults = [];
1365
1548
  itemIds = /* @__PURE__ */ new Set();
1366
- itemBody = declaration ? itemJSON(declaration) : void 0;
1367
- extra = bytes(resultBody) + (itemBody === void 0 ? 0 : bytes(itemBody));
1368
- }
1369
- if (size + extra > 5242880) throw new TypeError("One item/result pair exceeds the request byte limit.");
1370
- if (itemBody !== void 0) {
1371
- itemIds.add(result.itemId);
1372
- encodedItems.push(itemBody);
1373
1549
  }
1374
- encodedResults.push(resultBody);
1550
+ for (const id of groupItems.keys()) itemIds.add(id);
1551
+ encodedItems.push(...newItems);
1552
+ encodedResults.push(...groupResults);
1375
1553
  size += extra;
1554
+ groupStart = end;
1376
1555
  }
1377
1556
  if (encodedResults.length) output.push({
1378
1557
  start,
@@ -1439,6 +1618,11 @@ var Experiment = class {
1439
1618
  retrySafe: true
1440
1619
  }), (data) => uploadReceipt(data, chunk.results));
1441
1620
  }
1621
+ /**
1622
+ * Keeps composite items and their supplied inputs in one request, preserving order.
1623
+ * Interleaved items may form an indivisible group; oversized groups fail before any I/O.
1624
+ * Ingestion-only keys must supply every pinned input, including on retries.
1625
+ */
1442
1626
  async uploadResults(results, request = {}) {
1443
1627
  const prepared = chunks(results);
1444
1628
  return this.#queue.run(async () => {