{"record":{"id":"ae5576f6706d7b72","repo":"apache/beam","slug":"input-to-groupbykey-must-be-a-pcollection-with-elements-core","errorCode":null,"errorMessage":"Input to GroupByKey must be a PCollection with elements compatible with KV[A, B]","messagePattern":"Input to GroupByKey must be a PCollection with elements compatible with KV\\[A, B\\]","errorType":"validation","errorClass":"TypeCheckError","httpStatus":null,"severity":"error","filePath":"sdks/python/apache_beam/transforms/core.py","lineNumber":3467,"sourceCode":"  Processes an input PCollection consisting of key/value pairs represented as a\n  tuple pair. The result is a PCollection where values having a common key are\n  grouped together.  For example (a, 1), (b, 2), (a, 3) will result into\n  (a, [1, 3]), (b, [2]).\n\n  The implementation here is used only when run on the local direct runner.\n  \"\"\"\n  def __init__(self, label=None):\n    self._replaced_by_gbek = False\n    self._inside_gbek = False\n    super().__init__(label)\n\n  class ReifyWindows(DoFn):\n    def process(\n        self, element, window=DoFn.WindowParam, timestamp=DoFn.TimestampParam):\n      try:\n        k, v = element\n      except TypeError:\n        raise TypeCheckError(\n            'Input to GroupByKey must be a PCollection with '\n            'elements compatible with KV[A, B]')\n\n      return [(k, WindowedValue(v, timestamp, [window]))]\n\n    def infer_output_type(self, input_type):\n      key_type, value_type = trivial_inference.key_value_types(input_type)\n      return typehints.KV[\n          key_type, typehints.WindowedValue[value_type]]  # type: ignore[misc]\n\n  def get_windowing(self, inputs):\n    # Switch to the continuation trigger associated with the current trigger.\n    windowing = inputs[0].windowing\n    triggerfn = windowing.triggerfn.get_continuation_trigger()\n    return Windowing(\n        windowfn=windowing.windowfn,\n        triggerfn=triggerfn,\n        accumulation_mode=windowing.accumulation_mode,","sourceCodeStart":3449,"sourceCodeEnd":3485,"githubUrl":"https://github.com/apache/beam/blob/12126d8942aaf848030c478b4c6a28c6af861c66/sdks/python/apache_beam/transforms/core.py#L3449-L3485","documentation":"GroupByKey requires its input elements to be key-value pairs. Beam's ReifyWindows DoFn attempts to unpack each element as (k, v); if the element is not a 2-tuple/KV, it raises TypeCheckError telling the user the input PCollection elements must be compatible with KV[A, B].","triggerScenarios":"Applying beam.GroupByKey() to a PCollection of non-pair elements, e.g. plain ints, strings, or 3-tuples produced by an earlier Map without keying.","commonSituations":"Forgetting to add a Map(lambda x: (x['key'], x)) keying step before GroupByKey, or a schema change in upstream data that alters tuple arity.","solutions":["Key the input first: pcoll | beam.Map(lambda x: (x.key, x)) before GroupByKey","Ensure upstream transforms emit 2-tuples / beam.KV elements","Add explicit type hints (input type beam.KV[K, V]) so the mismatch is caught earlier with a clearer message"],"exampleFix":"// before\n(pc | beam.Map(lambda x: x.value)) | beam.GroupByKey()\n// after\n(pc | beam.Map(lambda x: (x.key, x.value))) | beam.GroupByKey()","handlingStrategy":"validation","validationCode":"from apache_beam.typehints import typehints\npcoll = pcoll | beam.Map(key_fn).with_input_types(beam.typehints.KV[K, V])","typeGuard":"def is_kv_element(el) -> bool:\n    try:\n        k, v = el\n        return True\n    except (TypeError, ValueError):\n        return False","tryCatchPattern":"try:\n    keyed = pcoll | beam.GroupByKey()\nexcept TypeCheckError as e:\n    if 'must be a PCollection with elements compatible with KV' in str(e):\n        keyed = pcoll | beam.Map(lambda x: (x['key'], x)) | beam.GroupByKey()\n    else:\n        raise","preventionTips":["Always key data explicitly with beam.Map before GroupByKey","Apply beam.KV type hints so errors surface at graph construction","Validate element shape in integration tests with a small bounded pipeline"],"tags":["python","apache-beam","groupbykey","type-error"],"backgroundTag":"type-mismatch","analyzedSha":"12126d8942aaf848030c478b4c6a28c6af861c66","analyzedAt":"2026-09-13T01:50:10.254Z","contentChangedAt":"2026-09-13T01:50:10.254Z","schemaVersion":2},"datasetVersion":"2026-09-14T16:17:12.679Z"}