{"record":{"id":"bc24c6209b5048e6","repo":"apache/beam","slug":"shardedkey-type-constraint-violated-valid-object-instance","errorCode":null,"errorMessage":"ShardedKey type-constraint violated. Valid object instance must be of type 'ShardedKey'. Instead, an instance of '%s' was received.","messagePattern":"ShardedKey type-constraint violated\\. Valid object instance must be of type 'ShardedKey'\\. Instead, an instance of '(.+?)' was received\\.","errorType":"validation","errorClass":"CompositeTypeHintError","httpStatus":null,"severity":"error","filePath":"sdks/python/apache_beam/typehints/sharded_key_type.py","lineNumber":53,"sourceCode":"\nclass ShardedKeyTypeConstraint(typehints.TypeConstraint,\n                               metaclass=typehints.GetitemConstructor):\n  def __init__(self, key_type):\n    typehints.validate_composite_type_param(\n        key_type, error_msg_prefix='Parameter to ShardedKeyType hint')\n    self.key_type = typehints.normalize(key_type)\n\n  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 {}","sourceCodeStart":35,"sourceCodeEnd":71,"githubUrl":"https://github.com/apache/beam/blob/12126d8942aaf848030c478b4c6a28c6af861c66/sdks/python/apache_beam/typehints/sharded_key_type.py#L35-L71","documentation":"ShardedKeyType.type_check verifies that the runtime instance is actually a ShardedKey object before checking its inner key type. Any non-ShardedKey instance reaching a PCollection keyed with ShardedKey[K] raises CompositeTypeHintError. This guards the sharded-key encoding used by GroupByKey with sharding.","triggerScenarios":"A PCollection declared with type hint ShardedKey[...] receives, during runtime type-checking, an element that is a plain key, tuple, or other object not constructed via ShardedKey().","commonSituations":"Users build sharded keys manually as tuples (key, shard) instead of ShardedKey(key, shard), or a downstream map emits the unwrapped key back into a collection still hinted as ShardedKey.","solutions":["Construct keys with ShardedKey(key, shard_id) instead of tuples or plain values.","Fix the PCollection type hint if the data is no longer sharded (remove ShardedKey[...] from with_output_types).","Unwrap with .key/.shard_id before feeding elements into a collection expected to hold raw keys."],"exampleFix":"// before\nemitted = ShardedKeyHinted | beam.Map(lambda kv: (kv[0], kv[1]))\n// after\nfrom apache_beam.typehints.sharded_key_type import ShardedKey\nemitted = ShardedKeyHinted | beam.Map(lambda sk: ShardedKey(sk.key, sk.shard_id))","handlingStrategy":"type-guard","validationCode":"from apache_beam.typehints.sharded_key_type import ShardedKey\nassert all(isinstance(k, ShardedKey) for k in sample_elements), 'elements must be ShardedKey'","typeGuard":"def is_sharded_key(v) -> bool:\n    from apache_beam.typehints.sharded_key_type import ShardedKey\n    return isinstance(v, ShardedKey)","tryCatchPattern":"try:\n    run_pipeline(pipeline)\nexcept apache_beam.typehints.TypeCheckError as e:\n    log.error('element does not match ShardedKey hint: %s', e)","preventionTips":["Always build sharded keys via ShardedKey(key, shard_id), never tuples.","Keep with_output_types(ShardedKey[K]) in sync with what the producing DoFn emits.","Unit-test the producing DoFn with typehint checks enabled."],"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"}