Dev-iL commented on code in PR #77523:
URL: https://github.com/apache/airflow/pull/77523#discussion_r4677525638
##########
task-sdk/src/airflow/sdk/serde/serializers/kubernetes.py:
##########
@@ -55,10 +60,46 @@ 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:
+ if version > __version__:
+ raise TypeError(f"serialized version {version} is newer than class
version {__version__}")
+
+ if not is_pydantic_model(cls):
+ raise TypeError(f"do not know how to deserialize {qualname(cls)}")
+ model = cast("type[pydantic.BaseModel]", cls)
+
+ try:
+ return model.model_validate(data)
+ except pydantic.ValidationError as e:
+ try:
+ coerced = _coerce_legacy_values(data, e)
+ except (KeyError, TypeError, ValueError):
+ raise e
+ return model.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, bool):
+ parent[key] = str(value).lower()
+ elif err["type"] == "string_type" and isinstance(value, (int, float)):
+ parent[key] = str(value)
+ elif err["type"] == "bool_type" and str(value).lower() in ("true",
"false"):
+ parent[key] = str(value).lower() == "true"
+ return data
Review Comment:
At `kubernetes.py:72`, the dispatcher can pass `None`, and `issubclass(cls,
pydantic.BaseModel)` lets mypy verify the `model_validate` calls and the return
type. At `kubernetes.py:95`, the location can contain both string keys and list
indices. Check each container and key before indexing it, and limit
string-to-bool conversion to actual strings. This replacement also lets you
remove the `Any`, `cast`, and `is_pydantic_model` imports.
```suggestion
def deserialize(cls: type, version: int, data: object) -> pydantic.BaseModel:
if version > __version__:
raise TypeError(f"serialized version {version} is newer than class
version {__version__}")
if not issubclass(cls, pydantic.BaseModel):
raise TypeError(f"do not know how to deserialize {qualname(cls)}")
try:
return cls.model_validate(data)
except pydantic.ValidationError as e:
if not isinstance(data, dict):
raise
try:
_coerce_legacy_values(data, e)
except (KeyError, TypeError, ValueError):
raise e
return cls.model_validate(data)
def _coerce_legacy_values(data: dict[str, object], error:
pydantic.ValidationError) -> None:
# 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():
value: object = err["input"]
replacement: str | bool
if err["type"] == "string_type" and isinstance(value, bool):
replacement = str(value).lower()
elif err["type"] == "string_type" and isinstance(value, (int,
float)):
replacement = str(value)
elif err["type"] == "bool_type" and isinstance(value, str) and
value.lower() in ("true", "false"):
replacement = value.lower() == "true"
else:
continue
*path, key = err["loc"]
parent: object = data
for part in path:
if isinstance(parent, dict) and isinstance(part, str):
parent = parent[part]
elif isinstance(parent, list) and isinstance(part, int) and 0 <=
part < len(parent):
parent = parent[part]
else:
raise TypeError("validation location does not match the
payload")
if isinstance(parent, dict) and isinstance(key, str):
parent[key] = replacement
elif isinstance(parent, list) and isinstance(key, int) and 0 <= key
< len(parent):
parent[key] = replacement
else:
raise TypeError("validation location does not match the payload")
```
---
Drafted-by: Codex (GPT-6.2), reviewed by @Dev-iL before posting.
<!-- manifest-dev:review-pr -->
##########
task-sdk/tests/task_sdk/serde/test_serde.py:
##########
@@ -335,6 +336,15 @@ def test_serder_dataclass(self):
d = deserialize(e)
assert i.x == getattr(d, "x", None)
+ def test_kubernetes_pod_with_legacy_values(self):
+ encoded = {
+ CLASSNAME: qualname(k8s.V1Pod),
+ VERSION: 1,
+ DATA: {"metadata": {"name": "foo", "labels": {"a": 1}}},
+ }
+
+ assert deserialize(encoded) ==
k8s.V1Pod(metadata=k8s.V1ObjectMeta(name="foo", labels={"a": "1"}))
Review Comment:
The registry test at `test_serde.py:339` exercises `V1Pod`. It would pass if
`V1ResourceRequirements` were dropped from the registry. Add this test
alongside it to cover the stored format, round-trip, and legacy numeric
quantities for standalone resource requirements.
```python
def test_kubernetes_resource_requirements(self):
expected = k8s.V1ResourceRequirements(requests={"cpu": "1"})
encoded = serialize(expected)
assert encoded[DATA] == {"requests": {"cpu": "1"}}
assert deserialize(encoded) == expected
assert deserialize({**encoded, DATA: {"requests": {"cpu": 1}}}) ==
expected
```
---
Drafted-by: Codex (GPT-6.2), reviewed by @Dev-iL before posting.
<!-- manifest-dev:review-pr -->
##########
task-sdk/src/airflow/sdk/serde/serializers/kubernetes.py:
##########
@@ -55,10 +60,46 @@ 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:
+ if version > __version__:
+ raise TypeError(f"serialized version {version} is newer than class
version {__version__}")
+
+ if not is_pydantic_model(cls):
+ raise TypeError(f"do not know how to deserialize {qualname(cls)}")
+ model = cast("type[pydantic.BaseModel]", cls)
+
+ try:
+ return model.model_validate(data)
Review Comment:
`model_validate` at `kubernetes.py:81` rejects a legacy pod when
`status.nodeAllocatableResourceClaimStatuses[0].resources` was set. Kubernetes
36.0.3 writes that field, and the pinned 37.0.1 reader returns
`extra_forbidden`. Version 37 uses `mapping` and `overhead`. If migrating that
status schema is outside this patch, replace the broad upgrade claim with this
wording.
> Pod XComs use the Kubernetes API field names again. The reader coerces
legacy scalar values for fields Kubernetes 37 still recognizes. Payloads
containing fields removed from Kubernetes 37, such as
`status.nodeAllocatableResourceClaimStatuses[].resources`, still fail
validation.
---
Drafted-by: Codex (GPT-6.2), reviewed by @Dev-iL before posting.
<!-- manifest-dev:review-pr -->
--
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]