ashb commented on code in PR #58992: URL: https://github.com/apache/airflow/pull/58992#discussion_r2588242993
########## task-sdk/src/airflow/sdk/serialization/serializers/bignum.py: ########## @@ -0,0 +1,59 @@ +# +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +from __future__ import annotations + +from typing import TYPE_CHECKING + +from airflow.utils.module_loading import qualname + +if TYPE_CHECKING: + import decimal + + from airflow.sdk.serialization.serde import U + + +serializers = ["decimal.Decimal"] +deserializers = serializers + +__version__ = 1 + + +def serialize(o: object) -> tuple[U, str, int, bool]: + from decimal import Decimal + + if not isinstance(o, Decimal): + return "", "", 0, False + name = qualname(o) + _, _, exponent = o.as_tuple() + if isinstance(exponent, int) and exponent >= 0: # No digits after the decimal point. + return int(o), name, __version__, True + # Technically lossy due to floating point errors, but the best we + # can do without implementing a custom encode function. + return float(o), name, __version__, True Review Comment: I know you didnt change the, just move it, but i wonder why it doesn't stringify the value - since thats what we do on deser ########## airflow-core/src/airflow/serialization/stringify.py: ########## @@ -0,0 +1,131 @@ +# +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +from __future__ import annotations + +from typing import Any, TypeVar + +T = TypeVar("T", bool, float, int, dict, list, str, tuple, set) + +CLASSNAME = "__classname__" +VERSION = "__version__" +DATA = "__data__" +OLD_TYPE = "__type" +OLD_DATA = "__var" +OLD_DICT = "dict" +DEFAULT_VERSION = 0 + +_primitives = (int, bool, float, str) +_builtin_collections = (frozenset, list, set, tuple) + + +def _convert(old: dict) -> dict: + """Convert an old style serialization to new style.""" + if OLD_TYPE in old and OLD_DATA in old: + # Return old style dicts directly as they do not need wrapping + if old[OLD_TYPE] == OLD_DICT: + return old[OLD_DATA] + return {CLASSNAME: old[OLD_TYPE], VERSION: DEFAULT_VERSION, DATA: old[OLD_DATA]} + + return old + + +def decode(d: dict[str, Any]) -> tuple[str, int, Any]: + """Extract classname, version, and data from a serialized dict.""" + classname = d[CLASSNAME] + version = d[VERSION] + + if not isinstance(classname, str) or not isinstance(version, int): + raise ValueError(f"cannot decode {d!r}") + + data = d.get(DATA) + + return classname, version, data + + +def _stringify_builtin_collection(classname: str, value: Any): + if classname in ("builtins.tuple", "builtins.set", "builtins.frozenset"): + if isinstance(value, (list, tuple, set, frozenset)): + items = [str(stringify(v)) for v in value] + return f"({','.join(items)})" + return None + + +def stringify(o: T | None) -> object: + """ + Convert a serialized object to a human readable representation. + + Matches the behavior of deserialize(full=False) exactly: + - Returns objects as-is for primitives, collections, plain dicts + - Only returns string when encountering a serialized object (__classname__) + """ + if o is None: + return o + + if isinstance(o, _primitives): + return o + + # tuples, sets are included here for backwards compatibility + if isinstance(o, _builtin_collections): + col = [stringify(d) for d in o] + if isinstance(o, tuple): + return tuple(col) + + if isinstance(o, set): + return set(col) + + return col + + if not isinstance(o, dict): + # if o is not a dict, then it's already deserialized + # in this case we should return it as is + return o + + o = _convert(o) + + # plain dict and no type hint + if CLASSNAME not in o or VERSION not in o: + return {str(k): stringify(v) for k, v in o.items()} + + classname, version, value = decode(o) + + if not classname: + raise TypeError("classname cannot be empty") + + # Early detection for `airflow.` classes. These classes will need full deserialization, not just stringification + if isinstance(classname, str) and classname.startswith("airflow."): + raise ValueError( Review Comment: What does this mean for the API? What behaviour does it cause? -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
