{"record":{"id":"6546961f7910b3e3","repo":"Unity-Technologies/ml-agents","slug":"key-is-a-type-key","errorCode":null,"errorMessage":"{key} is a {type(key)}","messagePattern":"\\{key\\} is a \\{type\\(key\\)\\}","errorType":"exception","errorClass":"KeyError","httpStatus":null,"severity":"error","filePath":"ml-agents/mlagents/trainers/buffer.py","lineNumber":297,"sourceCode":"            f.reset_field()\n        self.last_brain_info = None\n        self.last_take_action_outputs = None\n\n    @staticmethod\n    def _check_key(key):\n        if isinstance(key, BufferKey):\n            return\n        if isinstance(key, tuple):\n            key0, key1 = key\n            if isinstance(key0, ObservationKeyPrefix):\n                if isinstance(key1, int):\n                    return\n                raise KeyError(f\"{key} has type ({type(key0)}, {type(key1)})\")\n            if isinstance(key0, RewardSignalKeyPrefix):\n                if isinstance(key1, str):\n                    return\n                raise KeyError(f\"{key} has type ({type(key0)}, {type(key1)})\")\n        raise KeyError(f\"{key} is a {type(key)}\")\n\n    @staticmethod\n    def _encode_key(key: AgentBufferKey) -> str:\n        \"\"\"\n        Convert the key to a string representation so that it can be used for serialization.\n        \"\"\"\n        if isinstance(key, BufferKey):\n            return key.value\n        prefix, suffix = key\n        return f\"{prefix.value}:{suffix}\"\n\n    @staticmethod\n    def _decode_key(encoded_key: str) -> AgentBufferKey:\n        \"\"\"\n        Convert the string representation back to a key after serialization.\n        \"\"\"\n        # Simple case: convert the string directly to a BufferKey\n        try:","sourceCodeStart":279,"sourceCodeEnd":315,"githubUrl":"https://github.com/Unity-Technologies/ml-agents/blob/3ecb446f75d1e7400eb404c562dc005d3164cffc/ml-agents/mlagents/trainers/buffer.py#L279-L315","documentation":"The final fallback branch of AgentBuffer._check_key: the key is neither a valid tuple nor a recognized key type, so this KeyError is raised reporting the key's type. All buffer accessors route through this validation when CHECK_KEY_TYPES_AT_RUNTIME is enabled.","triggerScenarios":"Passing a bare string, list, or any non-tuple object as an AgentBufferKey to __getitem__, __setitem__, __delitem__, __contains__ or check_length — e.g. buffer['VectorObservation'] instead of a key object.","commonSituations":"Treating the buffer like a plain dict of column-name strings, migrating code from older ml-agents versions where string keys were accepted, or loading keys from JSON/YAML without conversion.","solutions":["Wrap plain strings in the proper key class, e.g. AgentGroupKey or ObservationKeyPrefix-based keys","Check CHECK_KEY_TYPES_AT_RUNTIME usage and construct keys via the library's factory functions","Convert serialized strings back with AgentBuffer._decode_key before use"],"exampleFix":"// before\nfield = buffer['VectorObservation']\n// after\nfrom mlagents.trainers.buffer import AgentBuffer\nfield = buffer[(ObservationKeyPrefix('VectorObservation'), 0)]","handlingStrategy":"type-guard","validationCode":"def is_agent_buffer_key(key):\n    if isinstance(key, tuple) and len(key) == 2:\n        k0, k1 = key\n        if isinstance(k0, ObservationKeyPrefix):\n            return isinstance(k1, int)\n        if isinstance(k0, RewardSignalKeyPrefix):\n            return isinstance(k1, str)\n    return False\nif not is_agent_buffer_key(key): raise TypeError(key)","typeGuard":"def is_agent_buffer_key(key) -> bool:\n    if isinstance(key, tuple) and len(key) == 2:\n        k0, k1 = key\n        return (isinstance(k0, ObservationKeyPrefix) and isinstance(k1, int)) or \\\n               (isinstance(k0, RewardSignalKeyPrefix) and isinstance(k1, str))\n    return False","tryCatchPattern":"try:\n    field = buffer[key]\nexcept KeyError:\n    raise TypeError(f\"{key!r} is not a valid AgentBufferKey; use key classes from mlagents.trainers.buffer\")","preventionTips":["Never pass bare strings or dicts as buffer keys","Convert legacy string keys via AgentBuffer._decode_key","Wrap buffer access in a helper that validates keys once"],"tags":["keyerror","type-mismatch","ml-agents","buffer"],"backgroundTag":"invalid-buffer-key-type","analyzedSha":"3ecb446f75d1e7400eb404c562dc005d3164cffc","analyzedAt":"2026-09-02T16:33:12.832Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-09T21:17:11.164Z"}