amoghrajesh opened a new pull request, #77523:
URL: https://github.com/apache/airflow/pull/77523

    <!-- SPDX-License-Identifier: Apache-2.0
         https://www.apache.org/licenses/LICENSE-2.0 -->
   
   <!--
   Thank you for contributing!
   
   Please provide above a brief description of the changes made in this pull 
request.
   Write a good git commit message following this guide: 
https://chris.beams.io/posts/git-commit/
   
   Please make sure that your code changes are covered with tests.
   And in case of new features or big changes remember to adjust the 
documentation.
   
   For user-facing UI changes, please attach before/after screenshots (or a 
short
   screen recording) so reviewers can assess the visual impact.
   
   Feel free to ping (in general) for the review if you do not see reaction for 
a few days
   (72 Hours is the minimum reaction time you can expect from volunteers) - we 
sometimes miss notifications.
   
   In case of an existing issue, reference it using one of the following:
   
   * closes: #ISSUE
   * related: #ISSUE
   -->
   
   ---
   
   ##### Was generative AI tooling used to co-author this PR?
   
   <!--
   If generative AI tooling has been used in the process of authoring this PR, 
please
   change below checkbox to `[X]` followed by the name of the tool, uncomment 
the "Generated-by".
   -->
   
   - [ ] Yes (please specify the tool below)
   
   <!--
   Generated-by: [Tool Name] following [the 
guidelines](https://github.com/apache/airflow/blob/main/contributing-docs/05_pull_requests.rst#gen-ai-assisted-contributions)
   -->
   
   ### What
   
   #77168 upgraded the Kubernetes client to 37, whose models are now pydantic 
`BaseModel`s. That broke serde of `V1Pod` and `V1ResourceRequirements` in the 
Task SDK, which is the path used for XComs. It also broke two CI checks on 
`main`: `test_encode_k8s_v1pod` in the Task SDK tests, and `mypy-task-sdk` in 
static checks. Neither check ran on #77168, so it merged green.
   
   ### Current behaviour
   
   - `serialize` checks for pydantic models before looking up a registered 
serializer. Pods skip the Kubernetes serializer and are stored as a raw 
`model_dump()`, with snake_case keys and every unset field as `None`, instead 
of the Kubernetes API format.
   - mypy fails at `serializers/kubernetes.py:58` because 
`PodGenerator.serialize_pod` only accepts `V1Pod`.
   - kubernetes 37 validates strictly. Pod XComs written by older clients with 
numeric quantities or labels (`"cpu": 1`) or string booleans (`"tty": "true"`) 
fail to load with a `ValidationError`.
   
   ### Proposed change
   
   - A registered serializer now takes precedence over the generic pydantic 
one, so pods are stored in the same format as before.
   - The Kubernetes serializer calls `ApiClient().sanitize_for_serialization` 
directly. This fixes mypy and removes the import of the `cncf.kubernetes` 
provider.
   - The Kubernetes serializer now has a deserializer. On a validation error, 
it converts loosely typed legacy values to the expected types and validates 
once more.
   
   ### Changes of Note
   
   - The retry only fixes the fields pydantic reports as invalid, by following 
each error's location (`loc`). Numbers become strings for `string_type` errors, 
and `"true"`/`"false"` become booleans for `bool_type` errors.
   - For union fields like a probe `port`, pydantic adds the type names to 
`loc`, so the path can't be followed. In that case, and when the data can't be 
fixed, the original `ValidationError` is raised rather than a confusing 
`TypeError`.
   
   ### User implications / backcompat
   
   - Pods are stored in the same format as before kubernetes 37, so switching 
airflow versions in either direction sees no format change.
   - After upgrading, existing pod xcoms load, including those with loosely 
typed values. Before this change, pod xcoms could not be loaded back at all.
   - With `kubernetes < 37`, loading still raises `TypeError`, as before.
   
   ### Testing
   
   End to end: I ran `airflow standalone` in breeze with `kubernetes` `37.0.1` 
and `allowed_deserialization_classes = airflow.* kubernetes.*`, on `main` and 
then on this branch, using this Dag:
   
   - `push_pod` returns a `V1Pod`, and `pull_new_pod` pulls it.
   - `seed_legacy_pod` writes the payload an older Airflow (kubernetes < 37) 
would have stored, with `"cpu": 1`, label `"team": 42` and `"tty": "true"`. 
`pull_legacy_pod` pulls it.
   
   <details>
   <summary>Dag used</summary>
   
   ```python
   from kubernetes.client import models as k8s
   
   from airflow.sdk import DAG, task
   from airflow.sdk.bases.xcom import BaseXCom
   from airflow.sdk.serde import CLASSNAME, DATA, VERSION
   
   LEGACY_POD_XCOM = {
       CLASSNAME: "kubernetes.client.models.v1_pod.V1Pod",
       VERSION: 1,
       DATA: {
           "metadata": {"name": "legacy-pod", "labels": {"team": 42}},
           "spec": {
               "containers": [
                   {
                       "name": "base",
                       "image": "busybox",
                       "resources": {"requests": {"cpu": 1, "memory": "1Gi"}},
                       "tty": "true",
                   }
               ]
           },
       },
   }
   
   with DAG("k8s_pod_xcom", schedule=None, catchup=False):
   
       @task
       def push_pod():
           return k8s.V1Pod(
               metadata=k8s.V1ObjectMeta(name="new-pod", namespace="default"),
               spec=k8s.V1PodSpec(containers=[k8s.V1Container(name="base", 
image="busybox")]),
           )
   
       @task
       def seed_legacy_pod(**context):
           ti = context["ti"]
           BaseXCom._set_xcom_in_db(
               key="legacy_pod", value=LEGACY_POD_XCOM, dag_id=ti.dag_id, 
task_id=ti.task_id, run_id=ti.run_id
           )
   
       @task
       def pull_new_pod(**context):
           return context["ti"].xcom_pull(task_ids="push_pod")
   
       @task
       def pull_legacy_pod(**context):
           return context["ti"].xcom_pull(task_ids="seed_legacy_pod", 
key="legacy_pod")
   
       push_pod() >> pull_new_pod()
       seed_legacy_pod() >> pull_legacy_pod()
   ```
   
   </details>
   
   **1. New pod XCom format**
   
   Before: the pod is stored as a raw pydantic dump, with every field shown, 
most of them `None`.
   
   <img width="1600" height="1000" alt="before_1_xcom_push_pod" 
src="https://github.com/user-attachments/assets/a4c54421-f4e4-4deb-8e79-80d911c4bb12";
 />
   
   
   After: the pod is stored in the Kubernetes API format, as before kubernetes 
37.
   
   <img width="1600" height="1000" alt="after_1_xcom_push_pod" 
src="https://github.com/user-attachments/assets/9713c95a-e0b4-4958-828b-872d6ba02fed";
 />
   
   
   **2. Loading a pod XCom written by an older Airflow**
   
   Before: `pull_legacy_pod` fails with `ValidationError: 3 validation errors 
for V1Pod`.
   
   <img width="1600" height="1500" alt="before_2_pull_legacy_pod_log" 
src="https://github.com/user-attachments/assets/1d0f5a2b-a397-4ce7-b376-e9781f8274c0";
 />
   
   
   After: `pull_legacy_pod` succeeds, and the pod it returns has the converted 
values (`'42'`, `'1'`, `True`).
   
   <img width="1600" height="1000" alt="after_2_pull_legacy_pod_xcom" 
src="https://github.com/user-attachments/assets/16211e4c-c807-48c5-b2e7-2c184347834a";
 />
   
   
   ---
   
   * Read the **[Pull Request 
Guidelines](https://github.com/apache/airflow/blob/main/contributing-docs/05_pull_requests.rst#pull-request-guidelines)**
 for more information. Note: commit author/co-author name and email in commits 
become permanently public when merged.
   * For fundamental code changes, an Airflow Improvement Proposal 
([AIP](https://cwiki.apache.org/confluence/display/AIRFLOW/Airflow+Improvement+Proposals))
 is needed.
   * When adding dependency, check compliance with the [ASF 3rd Party License 
Policy](https://www.apache.org/legal/resolved.html#category-x).
   * For significant user-facing changes create newsfragment: 
`{pr_number}.significant.rst`, in 
[airflow-core/newsfragments](https://github.com/apache/airflow/tree/main/airflow-core/newsfragments).
 You can add this file in a follow-up commit after the PR is created so you 
know the PR number.
   


-- 
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]

Reply via email to