amoghrajesh commented on code in PR #58992:
URL: https://github.com/apache/airflow/pull/58992#discussion_r2584999817
##########
airflow-core/src/airflow/api_fastapi/core_api/routes/public/xcom.py:
##########
@@ -100,16 +100,25 @@ def get_xcom_entry(
item = copy.copy(result)
if deserialize:
- # We use `airflow.serialization.serde` for deserialization here
because custom XCom backends (with their own
- # serializers/deserializers) are only used on the worker side during
task execution.
-
- # However, the XCom value is *always* stored in the metadata database
as a valid JSON object.
- # Therefore, for purposes such as UI display or returning API
responses, deserializing with
- # `airflow.serialization.serde` is safe and recommended.
- from airflow.serialization.serde import deserialize as
serde_deserialize
-
- # full=False ensures that the `item` is deserialized without loading
the classes, and it returns a stringified version
- item.value = serde_deserialize(XComModel.deserialize_value(item),
full=False)
+ # Custom XCom backends may store references (eg: object storage paths)
in the database.
+ # The custom XCom backend's deserialize_value() resolves these to
actual values, but that is only
+ # used on workers during task execution. The API reads directly from
the database and uses
+ # stringify() to convert DB values (references or serialized data) to
human readable
+ # format for UI display or for API users.
+ import json
+
+ from airflow.serialization.stringify import stringify as stringify_xcom
+
+ try:
+ parsed_value = json.loads(result.value)
+ except (ValueError, TypeError):
+ # Already deserialized (e.g., set via Task Execution API)
+ parsed_value = result.value
+
+ try:
+ item.value = stringify_xcom(parsed_value)
+ except ValueError:
Review Comment:
Thrown when an airflow class is detected. We will need task sdk installed in
order to deserialize that one
##########
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(
+ f"Cannot stringify Airflow class '{classname}'. "
+ f"Use XComModel.deserialize_value() to deserialize Airflow
classes."
+ )
Review Comment:
Undecided between if I should be even more specific with `airlfow.sdk`
detection here.
--
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]