{"record":{"id":"4bf9d4818e4c04ff","repo":"apache/beam","slug":"expected-a-single-element-got-asarray-length","errorCode":null,"errorMessage":"Expected a single element, got ${asArray.length}","messagePattern":"Expected a single element, got (.+?)","errorType":"exception","errorClass":"Error","httpStatus":null,"severity":"error","filePath":"sdks/typescript/src/apache_beam/transforms/pardo.ts","lineNumber":432,"sourceCode":"\nexport function singletonSideInput<T>(\n  pcoll: PCollection<T>,\n  defaultValue: T | undefined = undefined,\n): SideInputParam<T, Iterable<T>, T> {\n  return new SideInputParam<T, Iterable<T>, T>(pcoll, {\n    accessPattern: \"beam:side_input:iterable:v1\",\n    toValue: (iter: Iterable<T>) => {\n      const asArray = Array.from(iter);\n      if (\n        asArray.length === 0 &&\n        defaultValue !== null &&\n        defaultValue !== undefined\n      ) {\n        return defaultValue;\n      } else if (asArray.length === 1) {\n        return asArray[0];\n      } else {\n        throw new Error(\"Expected a single element, got \" + asArray.length);\n      }\n    },\n  });\n}\n\n// TODO: (Extension) Map side inputs.\n\n/**\n * The superclass of all metric accessors, such as counters and distributions.\n */\nexport class Metric<T> extends ParDoUpdateParam<T> {\n  constructor(\n    readonly metricType: string,\n    readonly name: string,\n  ) {\n    super(\"metric\");\n  }\n}","sourceCodeStart":414,"sourceCodeEnd":450,"githubUrl":"https://github.com/apache/beam/blob/12126d8942aaf848030c478b4c6a28c6af861c66/sdks/typescript/src/apache_beam/transforms/pardo.ts#L414-L450","documentation":"This error is thrown by a singleton side input view in pardo.ts when the side input PCollection materialized to a list whose length is neither 0 nor 1. A singleton side input (via pvalue.AsSingleton) promises exactly one element per window; if the underlying PCollection emits more than one element in the current window, the view cannot pick one, so the library throws. Empty lists are allowed only when a defaultValue was supplied.","triggerScenarios":"Calling `pcoll.applyAsSideInput()` / `context.requireSideInput(AsSingleton(pcoll))` when the side-input PCollection emits 2+ elements in a window, and no defaultValue was given.","commonSituations":"Developers assume a key/window has one record but it actually has several (e.g. joining a one-row-per-user PCollection where a duplicate user exists, or applying AsSingleton to an unfiltered multi-element collection).","solutions":["Pass a defaultValue to AsSingleton only if empty is acceptable — it does not fix multi-element cases.","Filter or dedupe the side-input PCollection so it produces exactly one element per window (e.g. pardo.Map or Combine to a single value).","Use AsIter or AsMultimap side inputs if multiple elements per window are legitimate.","Add logging/counting before the pipeline stage to confirm the side input's element count per window."],"exampleFix":"// before\nconst threshold = context.requireSideInput(pvalue.AsSingleton(scores));\n\n// after: guarantee exactly one element per window\nconst maxScore = scores.apply(\"max\", combiners.Combine(CombineFns.maxFn()));\nconst threshold = context.requireSideInput(pvalue.AsSingleton(maxScore));","handlingStrategy":"validation","validationCode":"// ensure the side input yields one element per window before use\nconst count = await beam.pvalue.AsSingleton && /* design-time: */\n// dedupe/combine upstream so exactly one element remains per window\nconst single = elems.apply(\"toSingle\", beam.combiners.Combine(fn => fn.maxBy(x => x.ts)));","typeGuard":null,"tryCatchPattern":null,"preventionTips":["Always wrap multi-element PCollections in Combine/Reduce before using AsSingleton.","Prefer AsIter/AsMap when cardinality is not exactly one.","Document the assumed cardinality of side inputs at their creation site."],"tags":["side-input","cardinality","pipeline-runtime"],"backgroundTag":"invalid-argument-value","analyzedSha":"12126d8942aaf848030c478b4c6a28c6af861c66","analyzedAt":"2026-09-13T01:50:10.254Z","contentChangedAt":"2026-09-13T01:50:10.254Z","schemaVersion":2},"datasetVersion":"2026-09-20T03:17:13.778Z"}