{"record":{"id":"f5f2858e90c79e64","repo":"huggingface/smolagents","slug":"falling-back-to-insecure-pickle-serialization-thi","errorCode":null,"errorMessage":"Falling back to insecure pickle serialization. This is a security risk and will be removed in a future version. Consider using only safe serializable types (primitives, lists, dicts, numpy arrays, PIL images, datetime objects, dataclasses).","messagePattern":"Falling back to insecure pickle serialization\\. This is a security risk and will be removed in a future version\\. Consider using only safe serializable types \\(primitives, lists, dicts, numpy arrays, PIL images, datetime objects, dataclasses\\)\\.","errorType":"console","errorClass":"FutureWarning","httpStatus":null,"severity":"warning","filePath":"src/smolagents/serialization.py","lineNumber":280,"sourceCode":"            str: Serialized string (\"safe:...\" for JSON, \"pickle:...\" for pickle)\n\n        Raises:\n            SerializationError: If allow_pickle=False and object cannot be safely serialized\n        \"\"\"\n        if not allow_pickle:\n            # Safe ONLY mode - no pickle fallback\n            json_safe = SafeSerializer.to_json_safe(obj)  # Raises SerializationError if fails\n            return SafeSerializer.SAFE_PREFIX + json.dumps(json_safe)\n        else:\n            # Try safe first, fallback to pickle\n            try:\n                json_safe = SafeSerializer.to_json_safe(obj)\n                return SafeSerializer.SAFE_PREFIX + json.dumps(json_safe)\n            except SerializationError:\n                # Warn about insecure pickle usage\n                import warnings\n\n                warnings.warn(\n                    \"Falling back to insecure pickle serialization. \"\n                    \"This is a security risk and will be removed in a future version. \"\n                    \"Consider using only safe serializable types (primitives, lists, dicts, \"\n                    \"numpy arrays, PIL images, datetime objects, dataclasses).\",\n                    FutureWarning,\n                    stacklevel=2,\n                )\n                # Fallback to pickle (with prefix)\n                try:\n                    return \"pickle:\" + base64.b64encode(pickle.dumps(obj)).decode()\n                except (pickle.PicklingError, TypeError, AttributeError) as e:\n                    raise SerializationError(f\"Cannot serialize object: {e}\") from e\n\n    @staticmethod\n    def loads(data: str, allow_pickle: bool = False) -> Any:\n        \"\"\"\n        Deserialize string with format detection.\n","sourceCodeStart":262,"sourceCodeEnd":298,"githubUrl":"https://github.com/huggingface/smolagents/blob/30bb1161095dbae2271e6bc3cc4c219cc3897a57/src/smolagents/serialization.py#L262-L298","documentation":"smolagents' safe serializer (dumps) first tries SafeSerializer.to_json_safe; if that raises SerializationError it falls back to base64 pickle, emitting this FutureWarning because pickle fallback is insecure and slated for removal. The pickled payload is prefixed so loads can detect it.","triggerScenarios":"Calling serialization.dumps (directly or via agent.to_dict/save) on objects containing types outside the safe set — arbitrary classes, generators, locks, DB handles, custom objects without dataclass support.","commonSituations":"Tool outputs containing arbitrary Python objects; agent memory holding non-serializable artifacts; environments where FutureWarning-as-error (pytest -W error) turns this into a test failure.","solutions":["Convert non-safe objects to primitives/lists/dicts/dataclasses before serializing","Represent images as PIL Images, arrays as numpy arrays, timestamps as datetime — all safe","Refactor to avoid pickling untrusted-looking state; treat the warning as a design signal","As a stopgap, catch/filter FutureWarning, but plan migration since pickle fallback will be removed"],"exampleFix":"# before\nresult = {'obj': SomeCustomClass()}\ndata = dumps(result)  # warns, pickles\n\n# after\nfrom dataclasses import dataclass\n@dataclass\nclass SomeCustomClass:\n    x: int\nresult = {'obj': SomeCustomClass(3)}\ndata = dumps(result)","handlingStrategy":"fallback","validationCode":"from smolagents.serialization import SafeSerializer\ndef safe_payload(obj):\n    try:\n        return SafeSerializer.to_json_safe(obj)\n    except Exception:\n        raise ValueError('convert to primitives/dicts/dataclasses before serializing')","typeGuard":"from dataclasses import is_dataclass\nfrom datetime import datetime\nSAFE = (str, int, float, bool, list, dict, tuple, datetime)\ndef is_safe_serializable(obj) -> bool:\n    return is_dataclass(obj) or isinstance(obj, SAFE)","tryCatchPattern":"import warnings\nwith warnings.catch_warnings():\n    warnings.filterwarnings('error', FutureWarning, message='.*pickle.*')\n    try:\n        data = dumps(obj)\n    except FutureWarning:\n        data = dumps(sanitize(obj))  # convert to safe types and retry","preventionTips":["Keep agent state to primitives/dicts/lists/dataclasses","Convert custom objects before storing in tool outputs","Treat the pickle warning as a build error in CI"],"tags":["smolagents","serialization","pickle","security"],"backgroundTag":"unsafe-pickle-serialization","analyzedSha":"30bb1161095dbae2271e6bc3cc4c219cc3897a57","analyzedAt":"2026-08-28T18:52:54.169Z","schemaVersion":2},"datasetVersion":"2026-08-28T21:17:43.275Z"}