jason810496 commented on code in PR #76826:
URL: https://github.com/apache/airflow/pull/76826#discussion_r4675200795


##########
airflow-core/src/airflow/api_fastapi/execution_api/routes/xcoms.py:
##########
@@ -608,15 +693,18 @@ def get_xcom(
                 ),
             },
         )
+    if map_index is None:
+        slice_url = request.url.replace(path=f"{request.url.path}/slice")

Review Comment:
   The redirect URL is absolute and keeps the scheme the api-server sees.
   
   Setup: a TLS load balancer at `https://airflow.example.com` forwards plain 
http to the api-server. Workers use `execution_api_server_url = 
https://airflow.example.com/execution/`, and `--proxy-headers` is off by 
default.
   
   I ran the route behind a TLS proxy stub:
   
   | Setup | `Location` | Slice read |
   |---|---|---|
   | TLS, current | 
`http://airflow.example.com/execution/xcoms/dag/run/mapped/my%20key/slice?...` 
| `Authorization` dropped, so 401 |
   | TLS + `/airflow` prefix, current | same | 404 at the proxy |
   | TLS, relative | `my%20key/slice?...` | 200 with token |
   | TLS + `/airflow` prefix, relative | `my%20key/slice?...` | 200 with token |
   
   httpx drops `Authorization` on an https to http hop, and `BearerAuth` 
doesn't run again.
   
   No other route builds a redirect from `request.url`. The login routes 
redirect to configured URLs like `[api] base_url`. `simple/routes/login.py` 
also notes the request scheme needs `--proxy-headers`.
   
   A relative `Location` resolves against the URL the worker sent, so it works 
behind any proxy. A path-only `/execution/...` would still lose the prefix.
   
   ```suggestion
           slice_url = f"{quote(key, safe='')}/slice"
           if request.url.query:
               slice_url += f"?{request.url.query}"
   ```
   
   This needs `from urllib.parse import quote`.



##########
task-sdk/src/airflow/sdk/api/client.py:
##########
@@ -717,7 +742,7 @@ def _get_mapped_slice_or_none(
 
         This is for a server that reads map index -1 for an omitted map index,
         and so finds nothing for a mapped task. A server that resolves it by
-        how the task is defined never answers a mapped task as not found.
+        how the task is defined redirects a mapped task's read instead.

Review Comment:
   This fallback only helps servers before 2027-02-28. Newer servers redirect a 
mapped read instead.
   
   It still runs on every 404, though. With this PR's server, 
`xcom_pull(task_ids="t")` on a missing key makes a second `/slice` call. That 
call always returns `[]`.
   
   Cadwyn sends the matched version back in the `Airflow-API-Version` response 
header, so the caller could gate on it:
   
   ```python
           except ServerResponseError as e:
               if e.response.status_code != HTTPStatus.NOT_FOUND:
                   raise
               mapped = None
               if e.response.headers.get("Airflow-API-Version", "") < 
"2027-02-28":
                   mapped = self._get_mapped_slice_or_none(
                       dag_id,
                       run_id,
                       task_id,
                       key,
                       map_index,
                       include_prior_dates=include_prior_dates,
                       previous_iteration=previous_iteration,
                   )
               if mapped is not None:
                   return mapped
   ```
   
   I tried this with the `task_sdk_client` contract fixture. The 404 carries 
`Airflow-API-Version: 2027-02-28`, and the extra `/slice` call goes away. The 
mocked fallback tests in `test_client.py` still pass, since they send no 
version header.



##########
task-sdk/src/airflow/sdk/api/client.py:
##########
@@ -198,14 +198,15 @@ def getuser() -> str:
 
 def get_json_error(response: httpx2.Response):
     """Raise a ServerResponseError if we can extract error info from the 
error."""
-    err = ServerResponseError.from_response(response)
-    if err:
+    if err := ServerResponseError.from_response(response):
         raise err
 
 
 def raise_on_4xx_5xx(response: httpx2.Response):
     try:
-        return get_json_error(response) or response.raise_for_status()
+        get_json_error(response)
+        if not response.is_redirect:  # Followed by httpx, or handled by the 
caller.

Review Comment:
   This skips `raise_for_status()` for any 3xx, on every endpoint.
   
   Only the XCom Get follows redirects. Before, a proxy 3xx on `ti.finish` or 
heartbeat raised `HTTPStatusError`. Now it returns as success, and the state 
update is lost silently.
   
   Could we skip only the slice redirect?
   
   ```suggestion
           if not _is_xcom_slice_redirect(response):
   ```
   
   ```python
   def _is_xcom_slice_redirect(response: httpx2.Response) -> bool:
       if response.status_code != HTTPStatus.TEMPORARY_REDIRECT or "location" 
not in response.headers:
           return False
       target = response.request.url.join(response.headers["location"])
       return target.path == _build_xcom_slice_path(response.request.url.path)
   ```
   
   httpx runs response hooks before it follows the redirect, so the hook reads 
`Location` itself. I checked it with a mock transport:
   
   | Request | Result |
   |---|---|
   | XCom Get, absolute `Location` | 200, slice returned |
   | XCom Get, relative `Location` | 200, slice returned |
   | `PATCH task-instances/...` gets a 302 | `HTTPStatusError` |
   
   With this, the contract tests pass. 
`test_xcom_get_does_not_read_another_redirect_as_a_slice` would expect 
`HTTPStatusError` instead of `ValidationError`, which fails earlier.



##########
airflow-core/src/airflow/api_fastapi/execution_api/routes/xcoms.py:
##########
@@ -554,28 +579,88 @@ def head_xcom(
     response.headers["Content-Range"] = f"map_indexes {count}"
 
 
+def _resolve_omitted_map_index(
+    *,
+    dag_id: str,
+    run_id: str,
+    task_id: str,
+    params: GetXcomFilterParams,
+    resolver: TaskCoordinateResolver,
+    caller: TaskInstance | None,
+) -> int | None:
+    """
+    Return the map index to read for an omitted one, or None for every 
instance.
+
+    A mapped operator, or a task in a mapped task group, reads every instance,
+    however many it expanded to. The task is looked up in the Dag version its
+    run uses, or the caller's own if the caller is in the same run, as reads of
+    a given map index do.
+
+    Everything else reads -1: an unmapped task, one that cannot be found, a 
read
+    with ``offset`` or ``include_prior_dates``, and older API versions.
+    """
+    if params.offset is not None or params.include_prior_dates:
+        return -1
+    if not ResolveOmittedXComMapIndexByTaskDefinition.is_applied:
+        return -1
+    if caller is not None and (caller.dag_id, caller.run_id) == (dag_id, 
run_id):
+        dag_version_id = caller.dag_version_id
+    else:
+        dag_version_id = None
+    try:
+        task = resolver.get_task(dag_id, run_id, task_id, 
dag_version_id=dag_version_id)

Review Comment:
   This loads the producer's Dag on every Get that omits the map index, 
including plain Python tasks.
   
   `execution_api/AGENTS.md` asks to gate Dag loads on hot paths. Mapped tasks 
and tasks in mapped groups always have regional instances.
   
   Could we return -1 early when `resolver.has_regions(dag_id, run_id, 
task_id)` is false so we won't load the serialized Dag?



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