{"record":{"id":"a06fb4ae68d60622","repo":"apache/beam","slug":"s-hint-s-type-constraint-violated-all-ss-should-be-of-type-s","errorCode":null,"errorMessage":"%s hint %s-type constraint violated. All %ss should be of type %s. Instead: %s","messagePattern":"(.+?) hint (.+?)-type constraint violated\\. All (.+?)s should be of type (.+?)\\. Instead: (.+?)","errorType":"exception","errorClass":"CompositeTypeHintError","httpStatus":null,"severity":"error","filePath":"sdks/python/apache_beam/typehints/typehints.py","lineNumber":1175,"sourceCode":"            is_consistent_with(sub.key_type, self.key_type) and\n            is_consistent_with(sub.value_type, self.value_type))\n      elif hasattr(sub, '__origin__'):\n        # Handle collection subtypes using ABC\n        if issubclass(sub.__origin__, abc.Mapping):\n          args = getattr(sub, '__args__', None)\n          if args and len(args) == 2:\n            return (\n                is_consistent_with(args[0], self.key_type) and\n                is_consistent_with(args[1], self.value_type))\n          return True\n      return False\n\n    def _raise_type_error(self, is_key, instance, inner_error_message=''):\n      type_desc = 'key' if is_key else 'value'\n      expected_type = self.key_type if is_key else self.value_type\n\n      if inner_error_message:\n        raise CompositeTypeHintError(\n            '%s hint %s-type constraint violated. All %ss should be of type '\n            '%s. Instead: %s' % (\n                repr(self),\n                type_desc,\n                type_desc,\n                repr(expected_type),\n                inner_error_message,\n            ))\n      else:\n        raise CompositeTypeHintError(\n            '%s hint %s-type constraint violated. All %ss should be of '\n            'type %s. Instead, %s is of type %s.' % (\n                repr(self),\n                type_desc,\n                type_desc,\n                repr(expected_type),\n                instance,\n                instance.__class__.__name__,","sourceCodeStart":1157,"sourceCodeEnd":1193,"githubUrl":"https://github.com/apache/beam/blob/12126d8942aaf848030c478b4c6a28c6af861c66/sdks/python/apache_beam/typehints/typehints.py#L1157-L1193","documentation":"Raised when a runtime type-check (type_check=True pipelines or direct assertions) finds that a key of a Dict/Mapping instance violates the declared key-type constraint. The inner_error_message branch is used when the key itself failed a composite (nested) constraint, so the inner error text is appended instead of a simple class name. It is a CompositeTypeHintError, i.e. a nested validation failure.","triggerScenarios":"A dict whose keys are not of the declared key_type is passed through an op annotated with Dict[K, V] while type checking is enabled (e.g. beam.Map with .with_output_types(Dict[str, int]) returning {1: ...}), or a nested composite key type fails its own constraint.","commonSituations":"Pipeline options enable type_check=True (default in newer Beam versions); a DoFn yields dicts built from heterogeneous data where keys are ints but the hint says str; converting data from JSON whose keys are always strings while the hint expects ints.","solutions":["Coerce keys to the declared key type before yielding/returning the mapping (e.g. str(k))","Correct the type hint to match the actual key type: Dict[int, V] if keys are ints","Disable/relax runtime type checking via --type_check=none if the violation is intentional (last resort)"],"exampleFix":"// before\np | beam.Map(lambda d: {i: v for i, v in enumerate(d)}).with_output_types(Dict[str, str])\n// after\np | beam.Map(lambda d: {str(i): v for i, v in enumerate(d)}).with_output_types(Dict[str, str])","handlingStrategy":"type-guard","validationCode":"import collections.abc\nok = isinstance(d, collections.abc.Mapping) and all(isinstance(k, str) for k in d)\n# ok must be True before passing data through a Dict[str, V] annotated op","typeGuard":"def matches_dict_hint(d, key_type, value_type):\n    return isinstance(d, collections.abc.Mapping) and all(\n        isinstance(k, key_type) for k in d.keys())","tryCatchPattern":"from apache_beam.typehints.exceptions import CompositeTypeHintError\ntry:\n    typecheck.validate(hint, instance)\nexcept CompositeTypeHintError as e:\n    log.error('key type violation: %s', e)","preventionTips":["Keep key types consistent at data boundaries (e.g. always str keys from JSON)","Run pipelines with --type_check=strict in CI to catch violations early","Coerce key types where data enters the pipeline"],"tags":["python","apache-beam","type-hints","dict","runtime-type-check"],"backgroundTag":"type-mismatch","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"}