{"record":{"id":"2502a8e00f20f13c","repo":"apache/beam","slug":"s-type-constraint-violated-the-type-of-key-in-shardedkey-is","errorCode":null,"errorMessage":"%s type-constraint violated. The type of key in 'ShardedKey' is incorrect. Expected an instance of type '%s', instead received an instance of type '%s'.","messagePattern":"(.+?) type-constraint violated\\. The type of key in 'ShardedKey' is incorrect\\. Expected an instance of type '(.+?)', instead received an instance of type '(.+?)'\\.","errorType":"validation","errorClass":"CompositeTypeHintError","httpStatus":null,"severity":"error","filePath":"sdks/python/apache_beam/typehints/sharded_key_type.py","lineNumber":61,"sourceCode":"  def _inner_types(self):\n    yield self.key_type\n\n  def _consistent_with_check_(self, sub):\n    return (\n        isinstance(sub, self.__class__) and\n        typehints.is_consistent_with(sub.key_type, self.key_type))\n\n  def type_check(self, instance):\n    if not isinstance(instance, ShardedKey):\n      raise typehints.CompositeTypeHintError(\n          \"ShardedKey type-constraint violated. Valid object instance \"\n          \"must be of type 'ShardedKey'. Instead, an instance of '%s' \"\n          \"was received.\" % (instance.__class__.__name__))\n\n    try:\n      typehints.check_constraint(self.key_type, instance.key)\n    except (typehints.CompositeTypeHintError, typehints.SimpleTypeHintError):\n      raise typehints.CompositeTypeHintError(\n          \"%s type-constraint violated. The type of key in 'ShardedKey' \"\n          \"is incorrect. Expected an instance of type '%s', \"\n          \"instead received an instance of type '%s'.\" %\n          (repr(self), repr(self.key_type), instance.key.__class__.__name__))\n\n  def match_type_variables(self, concrete_type):\n    if isinstance(concrete_type, ShardedKeyTypeConstraint):\n      return typehints.match_type_variables(\n          self.key_type, concrete_type.key_type)\n    return {}\n\n  def __eq__(self, other):\n    return isinstance(\n        other, ShardedKeyTypeConstraint) and self.key_type == other.key_type\n\n  def __hash__(self):\n    return hash(self.key_type)\n","sourceCodeStart":43,"sourceCodeEnd":79,"githubUrl":"https://github.com/apache/beam/blob/12126d8942aaf848030c478b4c6a28c6af861c66/sdks/python/apache_beam/typehints/sharded_key_type.py#L43-L79","documentation":"After confirming the instance is a ShardedKey, ShardedKeyType.type_check validates the inner key against self.key_type via check_constraint. If the key's type does not match the declared ShardedKey[K] parameter, it re-raises as CompositeTypeHintError describing the expected and actual key types.","triggerScenarios":"A ShardedKey instance whose .key is of the wrong type reaches a runtime type check, e.g. a ShardedKey containing a str while the hint is ShardedKey[int] — typically from mismatched upstream/downstream typing.","commonSituations":"Mixing key encodings across pipeline stages (string IDs vs int IDs), or sharding a differently-typed key after a reshape and re-annotating with the old ShardedKey hint.","solutions":["Align the key type with the declared hint, converting explicitly (e.g. int(sk.key)).","Update the PCollection's with_output_types annotation to the actual key type (ShardedKey[str]).","Audit the DoFn that creates the ShardedKey to ensure it produces the documented key type."],"exampleFix":"// before\nout | beam.Map(lambda k: ShardedKey(str(k), 1)).with_output_types(ShardedKey[int])\n// after\nout | beam.Map(lambda k: ShardedKey(int(k), 1)).with_output_types(ShardedKey[int])","handlingStrategy":"validation","validationCode":"from apache_beam.typehints import check_constraint, ShardedKey\ncheck_constraint(ShardedKey[int], ShardedKey(42, 1))  # raises before pipeline run if key type is wrong","typeGuard":"def is_sharded_key_of(v, key_type) -> bool:\n    from apache_beam.typehints.sharded_key_type import ShardedKey\n    return isinstance(v, ShardedKey) and isinstance(v.key, key_type)","tryCatchPattern":"try:\n    run_pipeline(pipeline)\nexcept apache_beam.typehints.TypeCheckError as e:\n    log.error('ShardedKey inner key type mismatch: %s', e)","preventionTips":["Convert keys explicitly at boundaries between stages with different key encodings.","Declare ShardedKey hints only where the key type is guaranteed.","Test producing transforms with runtime type checks on."],"tags":["python","apache-beam","type-hints","runtime-validation"],"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"}