potiuk commented on code in PR #77523:
URL: https://github.com/apache/airflow/pull/77523#discussion_r4676536743
##########
task-sdk/src/airflow/sdk/serde/serializers/kubernetes.py:
##########
@@ -29,11 +29,13 @@
]
if TYPE_CHECKING:
+ import pydantic
+
from airflow.sdk.serde import U
__version__ = 1
-deserializers: list[type[object]] = []
+deserializers = serializers
Review Comment:
**deserializers registration bypasses allowed_deserialization_classes**
Side effect worth calling out: `_register()` adds every `deserializers`
entry to `_extra_allowed`, so with this line `V1Pod` and
`V1ResourceRequirements` now deserialize even when `kubernetes.*` is not in
`[core] allowed_deserialization_classes`. Before this PR that raised
`ImportError`. Other built-in serializers work the same way, so I'm fine with
it, but it's easy to miss. Could you at least add a comment here saying it
happens? Please also note it in the PR description, which currently says the
config is needed. With this change the `conf_vars` on
`test_kubernetes_pod_with_legacy_values` is no longer needed.
*Flagged by both the primary and adversarial reviewers.*
##########
task-sdk/src/airflow/sdk/serde/serializers/kubernetes.py:
##########
@@ -55,10 +57,45 @@ def safe_get_name(pod):
return None
try:
- return PodGenerator.serialize_pod(o), qualname(o), __version__,
True
+ return ApiClient().sanitize_for_serialization(o), qualname(o),
__version__, True
except Exception:
log.warning("Serialization failed for pod %s", safe_get_name(o))
log.debug("traceback for serialization error", exc_info=True)
return "", "", 0, False
return "", "", 0, False
+
+
+def deserialize(cls: type, version: int, data: dict) -> Any:
+ import pydantic
+
+ if version > __version__:
+ raise TypeError(f"serialized version {version} is newer than class
version {__version__}")
+
+ if not hasattr(cls, "model_validate"):
+ raise TypeError(f"do not know how to deserialize {qualname(cls)}")
+
+ try:
+ return cls.model_validate(data)
+ except pydantic.ValidationError as e:
+ try:
+ coerced = _coerce_legacy_values(data, e)
+ except (KeyError, IndexError, TypeError):
+ raise e
+ return cls.model_validate(coerced)
+
+
+def _coerce_legacy_values(data: dict, error: pydantic.ValidationError) -> dict:
+ # kubernetes<37 stored numeric quantities/labels and string booleans that
the
+ # pydantic models of kubernetes>=37 reject in strict mode.
+ for err in error.errors():
+ *path, key = err["loc"]
+ parent: Any = data
+ for part in path:
+ parent = parent[part]
+ value = parent[key]
+ if err["type"] == "string_type" and isinstance(value, (int, float)):
Review Comment:
**bool matches int in string_type coercion**
`bool` is a subclass of `int`, so a boolean in a string field, such as a
legacy label `{"enabled": True}`, is converted to `"True"` (capitalised). It
neither fails nor matches the lowercase `"true"` that the `bool_type` branch
handles in the other direction.
`airflow-core/src/airflow/serialization/decoders.py` guards the same way with
`and not isinstance(..., bool)`. Either exclude it so the original
`ValidationError` stands, or map it to `"true"`/`"false"`.
*Flagged by antigravity (adversarial review); cross-checked.*
##########
task-sdk/src/airflow/sdk/serde/serializers/kubernetes.py:
##########
@@ -55,10 +57,45 @@ def safe_get_name(pod):
return None
try:
- return PodGenerator.serialize_pod(o), qualname(o), __version__,
True
+ return ApiClient().sanitize_for_serialization(o), qualname(o),
__version__, True
except Exception:
log.warning("Serialization failed for pod %s", safe_get_name(o))
log.debug("traceback for serialization error", exc_info=True)
return "", "", 0, False
return "", "", 0, False
+
+
+def deserialize(cls: type, version: int, data: dict) -> Any:
+ import pydantic
+
+ if version > __version__:
+ raise TypeError(f"serialized version {version} is newer than class
version {__version__}")
+
+ if not hasattr(cls, "model_validate"):
+ raise TypeError(f"do not know how to deserialize {qualname(cls)}")
+
+ try:
+ return cls.model_validate(data)
+ except pydantic.ValidationError as e:
+ try:
+ coerced = _coerce_legacy_values(data, e)
+ except (KeyError, IndexError, TypeError):
Review Comment:
**empty loc unpack raises ValueError**
`*path, key = err["loc"]` (line 92) raises `ValueError` when an error's
`loc` is empty. That happens with a root-level error, such as `model_type` when
the data is `None` or not a dict (`decode()` can return `None` data). The
`ValueError` then escapes instead of the original `ValidationError`, which goes
against what the PR description promises. Adding `ValueError` to the caught
tuple fixes it.
*Flagged by both the primary and adversarial reviewers.*
--
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]