This is an automated email from the ASF dual-hosted git repository.

hussein-awala pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/airflow.git


The following commit(s) were added to refs/heads/main by this push:
     new c99a11e5306 Resolve HITL review XComs through the configured XCom 
backend (#77198)
c99a11e5306 is described below

commit c99a11e5306d66d40d1a67d5365ef1172f3ab4ec
Author: Hussein Awala <[email protected]>
AuthorDate: Wed Nov 25 12:11:55 2026 +0100

    Resolve HITL review XComs through the configured XCom backend (#77198)
    
    * Resolve HITL review XComs through the configured XCom backend
    
    The HITL review plugin read the review session and agent outputs straight
    from the XCom table. A custom XCom backend that keeps values outside the
    metadata database, such as XComObjectStorageBackend with
    xcom_objectstorage_threshold = 0, stores only a reference there, so the
    plugin could not parse the session and the review tab and API failed,
    while workers, which read through the backend, worked.
    
    * Read HITL review XComs through the backend's load dispatch, off the event 
loop
    
    Route both review XCom readers through XCom._load where the task SDK has it,
    so a backend that implements only store_value/load_value resolves its
    references too; older Airflow versions keep calling deserialize_value.
    
    Make find_session a plain def so FastAPI runs its database and backend reads
    in the threadpool, like the action endpoints.
    
    * Store HITL review outputs and feedback as text wrapped with the Dag id
    
    The plugin now reads review XComs through the XCom backend, and
    XComObjectStorageBackend opens any string that is a URL under its base
    path. Outputs and feedback are text from the model and the reviewer, so a
    reviewer who typed another Dag's XCom path as feedback, or a model output
    that is such a path, had the API server open that file and return it.
    Workers store short values natively, so this held for the feedback a worker
    pushes too, not only for the plugin's write.
    
    The worker and the plugin now write these XComs as {"text", "dag_id"}, and
    the plugin shows only the text of such a value written for the Dag under
    review. Anything else, such as a value written before this change, is shown
    as stored, never what a reference in it resolves to.
    
    Patch the plugin's XCom with raising=False in the reference-backend tests,
    so they fail with the AgentSessionData validation error against the plugin
    on main instead of erroring in setup.
    
    * Address review: name the wrap helpers as verbs, pin the wraps in tests, 
note the XCom shape change
    
    - Rename review_text_xcom/read_review_text_xcom to 
wrap_review_text/unwrap_review_text.
    - Assert the plugin stores submitted feedback wrapped, and that the first 
output push is wrapped.
    - Reword the docs: an output or feedback written by an earlier provider 
shows the reference,
      whenever the review started.
    - Add a changelog note on the new shape of the output and feedback XComs.
---
 providers/common/ai/docs/changelog.rst             |   6 +
 providers/common/ai/docs/hitl_review.rst           |  22 +-
 providers/common/ai/docs/observability.rst         |   2 +-
 .../providers/common/ai/mixins/hitl_review.py      |  28 ++-
 .../providers/common/ai/plugins/hitl_review.py     |  39 ++-
 .../providers/common/ai/utils/hitl_review.py       |  25 ++
 .../unit/common/ai/mixins/test_hitl_review.py      |  16 +-
 .../common/ai/operators/test_agent_hitl_review.py  |  30 ++-
 .../unit/common/ai/plugins/test_hitl_review.py     | 272 ++++++++++++++++++++-
 .../tests/unit/common/ai/utils/test_hitl_review.py |  23 ++
 10 files changed, 423 insertions(+), 40 deletions(-)

diff --git a/providers/common/ai/docs/changelog.rst 
b/providers/common/ai/docs/changelog.rst
index 78996ece22b..f90b283d797 100644
--- a/providers/common/ai/docs/changelog.rst
+++ b/providers/common/ai/docs/changelog.rst
@@ -99,6 +99,12 @@ Changelog
 
   A ``BatchAdapter`` written for the earlier contract keeps working: the new 
members have defaults.
 
+.. note::
+  The HITL review XComs ``airflow_hitl_review_agent_output_<n>`` and
+  ``airflow_hitl_review_human_feedback_<n>`` now hold ``{"text": ..., 
"dag_id": ...}``; in
+  1.2.0 they held the text itself. A task that pulls them reads the text from 
``["text"]``.
+  See :doc:`hitl_review`.
+
 1.2.0
 .....
 
diff --git a/providers/common/ai/docs/hitl_review.rst 
b/providers/common/ai/docs/hitl_review.rst
index 7adb939c771..6027f88a03f 100644
--- a/providers/common/ai/docs/hitl_review.rst
+++ b/providers/common/ai/docs/hitl_review.rst
@@ -318,10 +318,28 @@ All keys use the prefix ``airflow_hitl_review_``.
        feedback, iteration
    * - ``airflow_hitl_review_agent_output_1``, ``_2``, …
      - Worker
-     - Per-iteration AI output (string or JSON)
+     - Per-iteration AI output (string or JSON), as ``{"text": ..., "dag_id": 
...}``
    * - ``airflow_hitl_review_human_feedback_1``, ``_2``, …
      - Plugin, and the worker when it resumes
-     - Per-iteration human feedback text
+     - Per-iteration human feedback text, as ``{"text": ..., "dag_id": ...}``
+
+The plugin reads these XComs through the configured ``[core] xcom_backend``, 
as the
+worker does. A custom backend that keeps values outside the metadata database, 
such as
+``XComObjectStorageBackend`` from the ``common.io`` provider, must therefore 
also be
+installed and configured on the API server, with access to its storage. The 
plugin
+writes its own entries straight to the metadata database, all of them 
dictionaries, so the
+backend must return a dictionary it did not store itself unchanged, as
+``XComObjectStorageBackend`` does.
+
+Outputs and feedback are stored as ``{"text": ..., "dag_id": ...}`` rather 
than as bare
+strings because their text comes from the model and the reviewer: a bare 
string that is a
+path under ``xcom_objectstorage_path`` would be opened by the backend on the 
API server,
+with its storage credentials, even when it holds another Dag's XCom. The 
plugin shows only
+the ``text`` of such a dictionary written for the Dag under review. Any other 
value under
+these keys, such as one written before this format, is shown as stored, never 
what a
+reference in it points to. An output or feedback written by an earlier version 
of the
+provider is therefore shown as the reference, not the text, when the backend 
kept it in its
+storage.
 
 Session lifecycle
 ^^^^^^^^^^^^^^^^^
diff --git a/providers/common/ai/docs/observability.rst 
b/providers/common/ai/docs/observability.rst
index 322fcd584e6..85c3bb00bc5 100644
--- a/providers/common/ai/docs/observability.rst
+++ b/providers/common/ai/docs/observability.rst
@@ -119,7 +119,7 @@ How it works
   provider-reported billing. With a custom XCom backend that keeps large 
values in external
   storage (e.g. ``common.io`` with ``xcom_objectstorage_threshold`` set low), 
the tab cannot
   show those values: the public XCom endpoint it calls returns the reference 
the backend
-  stored in the database, since the API server never runs the backend's
+  stored in the database, since that endpoint never runs the backend's
   ``deserialize_value``. The tab lists the model name, usage or skills kept 
that way with
   their reference (e.g. an ``s3://...`` path) instead of rendering them. A 
model name that is
   itself a URI, such as one vLLM serves from ``--model s3://...``, is listed 
that way too.
diff --git 
a/providers/common/ai/src/airflow/providers/common/ai/mixins/hitl_review.py 
b/providers/common/ai/src/airflow/providers/common/ai/mixins/hitl_review.py
index 73196a8f557..327fc018c9f 100644
--- a/providers/common/ai/src/airflow/providers/common/ai/mixins/hitl_review.py
+++ b/providers/common/ai/src/airflow/providers/common/ai/mixins/hitl_review.py
@@ -37,6 +37,7 @@ from airflow.providers.common.ai.utils.hitl_review import (
     AgentSessionData,
     HumanActionData,
     SessionStatus,
+    wrap_review_text,
 )
 from airflow.providers.common.ai.utils.output_type import 
dump_output_for_display
 from airflow.providers.common.ai.utils.prompt import describe_prompt
@@ -262,7 +263,7 @@ class HITLReviewMixin:
                 )
 
         ti.xcom_push(key=XCOM_AGENT_SESSION, 
value=session.model_dump(mode="json"))
-        ti.xcom_push(key=f"{XCOM_AGENT_OUTPUT_PREFIX}1", value=output_str)
+        ti.xcom_push(key=f"{XCOM_AGENT_OUTPUT_PREFIX}1", 
value=wrap_review_text(output_str, dag_id=ti.dag_id))
 
         self.log.info(
             "Feedback session created for %s/%s/%s (poll every %ds).",
@@ -307,8 +308,14 @@ class HITLReviewMixin:
                 feedback,
             )
             # The HITL Review tab shows each round from these.
-            ti.xcom_push(key=f"{XCOM_AGENT_OUTPUT_PREFIX}{session.iteration}", 
value=session.current_output)
-            
ti.xcom_push(key=f"{XCOM_HUMAN_FEEDBACK_PREFIX}{session.iteration}", 
value=feedback)
+            ti.xcom_push(
+                key=f"{XCOM_AGENT_OUTPUT_PREFIX}{session.iteration}",
+                value=wrap_review_text(session.current_output, 
dag_id=ti.dag_id),
+            )
+            ti.xcom_push(
+                key=f"{XCOM_HUMAN_FEEDBACK_PREFIX}{session.iteration}",
+                value=wrap_review_text(feedback, dag_id=ti.dag_id),
+            )
             session, message_history = self._regenerate_next_round(session, 
feedback, message_history)
         state = self.dump_review_state(message_history)
         retention = (
@@ -383,7 +390,10 @@ class HITLReviewMixin:
             },
         )
         ti.xcom_push(key=XCOM_AGENT_SESSION, 
value=session.model_dump(mode="json"))
-        ti.xcom_push(key=f"{XCOM_AGENT_OUTPUT_PREFIX}{session.iteration}", 
value=session.current_output)
+        ti.xcom_push(
+            key=f"{XCOM_AGENT_OUTPUT_PREFIX}{session.iteration}",
+            value=wrap_review_text(session.current_output, dag_id=ti.dag_id),
+        )
         self.log.info("Waiting for review of iteration %d.", session.iteration)
         raise TaskAwaitingInput(
             method_name="resume_hitl_review",
@@ -468,7 +478,10 @@ class HITLReviewMixin:
 
             if answered_elsewhere:
                 # The HITL Review tab shows the feedback from this XCom.
-                ti.xcom_push(key=f"{XCOM_HUMAN_FEEDBACK_PREFIX}{iteration}", 
value=feedback)
+                ti.xcom_push(
+                    key=f"{XCOM_HUMAN_FEEDBACK_PREFIX}{iteration}",
+                    value=wrap_review_text(feedback, dag_id=ti.dag_id),
+                )
             if iteration >= self.max_hitl_iterations:
                 _push_session(ti, session, 
SessionStatus.MAX_ITERATIONS_EXCEEDED)
                 raise HITLMaxIterationsError("Task exceeded max iterations.")
@@ -587,7 +600,10 @@ class HITLReviewMixin:
                 )
 
                 ti.xcom_push(key=XCOM_AGENT_SESSION, 
value=session.model_dump(mode="json"))
-                ti.xcom_push(key=f"{XCOM_AGENT_OUTPUT_PREFIX}{new_iteration}", 
value=new_output)
+                ti.xcom_push(
+                    key=f"{XCOM_AGENT_OUTPUT_PREFIX}{new_iteration}",
+                    value=wrap_review_text(new_output, dag_id=ti.dag_id),
+                )
 
                 self.log.info("Regenerated output (iteration %d) — waiting for 
review.", new_iteration)
 
diff --git 
a/providers/common/ai/src/airflow/providers/common/ai/plugins/hitl_review.py 
b/providers/common/ai/src/airflow/providers/common/ai/plugins/hitl_review.py
index 9702caa1a2e..c3f251aaac4 100644
--- a/providers/common/ai/src/airflow/providers/common/ai/plugins/hitl_review.py
+++ b/providers/common/ai/src/airflow/providers/common/ai/plugins/hitl_review.py
@@ -64,8 +64,10 @@ if AIRFLOW_V_3_1_PLUS:
         HumanActionType,
         HumanFeedbackRequest,
         SessionStatus,
+        unwrap_review_text,
+        wrap_review_text,
     )
-    from airflow.providers.common.compat.sdk import timezone
+    from airflow.providers.common.compat.sdk import XCom, timezone
     from airflow.sdk import TaskInstanceState
     from airflow.utils.session import create_session
 
@@ -86,6 +88,11 @@ if AIRFLOW_V_3_1_PLUS:
 
     SessionDep = Annotated[Session, Depends(_get_session)]
 
+    def _load_xcom_value(row: XComModel) -> Any:
+        """Resolve an XCom row through the configured XCom backend, the way 
workers read it."""
+        # Where it exists, ``_load`` prefers a backend's ``load_value`` over 
``deserialize_value``.
+        return getattr(XCom, "_load", XCom.deserialize_value)(row)
+
     def _read_xcom(
         session: Session,
         *,
@@ -96,7 +103,7 @@ if AIRFLOW_V_3_1_PLUS:
         region_id: UUID | None,
         key: str,
     ):
-        """Read a single XCom value from the database."""
+        """Read a single XCom value through the configured XCom backend."""
         scope: dict[str, Any] = (
             {"region_id": region_id, "include_node_regions": False} if 
AIRFLOW_V_3_4_PLUS else {}
         )
@@ -112,7 +119,7 @@ if AIRFLOW_V_3_1_PLUS:
         row = session.scalars(read).first()
         if row is None:
             return None
-        return row.value
+        return _load_xcom_value(row)
 
     def _read_xcom_by_prefix(
         session: Session,
@@ -124,7 +131,13 @@ if AIRFLOW_V_3_1_PLUS:
         region_id: UUID | None,
         prefix: str,
     ) -> dict[int, Any]:
-        """Read all iteration-keyed XCom entries matching *prefix* (e.g. 
``airflow_hitl_review_agent_output_``)."""
+        """
+        Read all iteration-keyed XCom entries matching *prefix* (e.g. 
``airflow_hitl_review_agent_output_``).
+
+        Each entry is read through the XCom backend, and its text is taken 
from what ``wrap_review_text``
+        wrapped for this Dag. Any other value, such as one written before 
entries were wrapped, is returned
+        as stored: a reference in it may point to another Dag's XCom, so what 
it resolves to is not shown.
+        """
         if AIRFLOW_V_3_4_PLUS:
             read = XComModel.get_many(
                 run_id=run_id,
@@ -135,9 +148,9 @@ if AIRFLOW_V_3_1_PLUS:
                 include_node_regions=False,
             )
             entity = read.column_descriptions[0]["entity"]
-            query = read.with_only_columns(entity.key, 
entity.value).where(entity.key.like(f"{prefix}%"))
+            query = read.where(entity.key.like(f"{prefix}%"))
         else:
-            query = select(XComModel.key, XComModel.value).where(
+            query = select(XComModel).where(
                 XComModel.dag_id == dag_id,
                 XComModel.run_id == run_id,
                 XComModel.task_id == task_id,
@@ -145,10 +158,11 @@ if AIRFLOW_V_3_1_PLUS:
                 XComModel.key.like(f"{prefix}%"),
             )
         result: dict[int, Any] = {}
-        for key, value in session.execute(query).all():
-            suffix = key[len(prefix) :]
+        for row in session.scalars(query):
+            suffix = row.key[len(prefix) :]
             if suffix.isdigit():
-                result[int(suffix)] = value
+                text = unwrap_review_text(_load_xcom_value(row), dag_id=dag_id)
+                result[int(suffix)] = row.value if text is None else text
         return result
 
     def _write_xcom(
@@ -393,7 +407,7 @@ if AIRFLOW_V_3_1_PLUS:
         response_model=HITLReviewResponse,
         dependencies=[Depends(requires_access_dag(method="GET", 
access_entity=DagAccessEntity.HITL_DETAIL))],
     )
-    async def find_session(
+    def find_session(
         db: SessionDep,
         dag_id: str,
         task_id: str,
@@ -507,7 +521,10 @@ if AIRFLOW_V_3_1_PLUS:
         iteration = sess_data.iteration
         if action == "changes_requested":
             _write_xcom(
-                session, **coordinates, 
key=f"{XCOM_HUMAN_FEEDBACK_PREFIX}{iteration}", value=feedback
+                session,
+                **coordinates,
+                key=f"{XCOM_HUMAN_FEEDBACK_PREFIX}{iteration}",
+                value=wrap_review_text(feedback, dag_id=dag_id),
             )
         if not sess_data.parked:
             # A polling task reads the action from this XCom; a parked one 
gets it on resume.
diff --git 
a/providers/common/ai/src/airflow/providers/common/ai/utils/hitl_review.py 
b/providers/common/ai/src/airflow/providers/common/ai/utils/hitl_review.py
index 416d2cad759..c90b3ed68d4 100644
--- a/providers/common/ai/src/airflow/providers/common/ai/utils/hitl_review.py
+++ b/providers/common/ai/src/airflow/providers/common/ai/utils/hitl_review.py
@@ -59,12 +59,14 @@ XCOM_AGENT_OUTPUT_PREFIX = f"{_XCOM_PREFIX}agent_output_"
 """Per-iteration AI output (append-only, written by worker).
 
 Actual key: ``airflow_hitl_review_agent_output_1``, ``_2``, ...
+Value: ``{"text": "...", "dag_id": "..."}`` (see :func:`wrap_review_text`).
 """
 
 XCOM_HUMAN_FEEDBACK_PREFIX = f"{_XCOM_PREFIX}human_feedback_"
 """Per-iteration human feedback (append-only, written by the plugin, and by 
the worker when it resumes).
 
 Actual key: ``airflow_hitl_review_human_feedback_1``, ``_2``, ...
+Value: ``{"text": "...", "dag_id": "..."}`` (see :func:`wrap_review_text`).
 """
 
 # On Airflow 3.3+ each review round is also a Human-in-the-loop request on the 
task instance, which
@@ -75,6 +77,29 @@ HITL_OPTION_REJECT = "Reject"
 HITL_FEEDBACK_PARAM = "feedback"
 
 
+def wrap_review_text(text: str, *, dag_id: str) -> dict[str, str]:
+    """
+    Wrap an agent output or human feedback for its per-iteration XCom.
+
+    The plugin reads these XComs through the XCom backend, which may open a 
string that looks like a
+    reference to its storage (``XComObjectStorageBackend`` does), and the text 
comes from the model or
+    the reviewer. Wrapped, the text is never such a string, and naming the Dag 
keeps the plugin from
+    showing another Dag's entry that a stored reference resolves to.
+    """
+    return {"text": text, "dag_id": dag_id}
+
+
+def unwrap_review_text(value: Any, *, dag_id: str) -> str | None:
+    """Return the text :func:`wrap_review_text` wrapped for ``dag_id``, or 
``None`` for any other value."""
+    if (
+        isinstance(value, dict)
+        and value.get("dag_id") == dag_id
+        and isinstance(text := value.get("text"), str)
+    ):
+        return text
+    return None
+
+
 class SessionStatus(str, Enum):
     """Lifecycle states of a HITL review session."""
 
diff --git 
a/providers/common/ai/tests/unit/common/ai/mixins/test_hitl_review.py 
b/providers/common/ai/tests/unit/common/ai/mixins/test_hitl_review.py
index 96ffa9b26ff..864202fec73 100644
--- a/providers/common/ai/tests/unit/common/ai/mixins/test_hitl_review.py
+++ b/providers/common/ai/tests/unit/common/ai/mixins/test_hitl_review.py
@@ -48,6 +48,7 @@ from airflow.providers.common.ai.utils.hitl_review import (
     AgentSessionData,
     HumanActionData,
     SessionStatus,
+    wrap_review_text,
 )
 from airflow.providers.standard.exceptions import (
     HITLRejectException,
@@ -286,9 +287,12 @@ class TestHITLReviewMixin:
         output_pushes = {
             c["key"]: c["value"] for c in push_calls if 
c["key"].startswith(XCOM_AGENT_OUTPUT_PREFIX)
         }
-        assert "airflow_hitl_review_agent_output_1" in output_pushes
-        assert "airflow_hitl_review_agent_output_2" in output_pushes
-        assert output_pushes["airflow_hitl_review_agent_output_2"] == 
"Revised: Add more detail"
+        assert output_pushes == {
+            "airflow_hitl_review_agent_output_1": wrap_review_text("Initial", 
dag_id="test_dag"),
+            "airflow_hitl_review_agent_output_2": wrap_review_text(
+                "Revised: Add more detail", dag_id="test_dag"
+            ),
+        }
 
     @patch.object(FakeAgenticOperator, "regenerate_with_feedback")
     @patch("airflow.providers.common.ai.mixins.hitl_review.time.sleep", 
autospec=True)
@@ -611,7 +615,7 @@ class TestParkedReview:
         assert paused.kwargs["state_sha256"] == 
hashlib.sha256(state.encode()).hexdigest()
         assert ctx["task_state_store"].set.call_args.kwargs["retention"] == 
timedelta(hours=2, days=1)
         assert 
AgentSessionData.model_validate(ti.xcoms[XCOM_AGENT_SESSION]).parked is True
-        assert ti.xcoms[f"{XCOM_AGENT_OUTPUT_PREFIX}1"] == "Initial"
+        assert ti.xcoms[f"{XCOM_AGENT_OUTPUT_PREFIX}1"] == 
wrap_review_text("Initial", dag_id="d")
         ti.xcom_pull.assert_not_called()
         (request,) = self._review_requests(mock_supervisor_comms)
         assert request.ti_id == ti.id
@@ -640,8 +644,8 @@ class TestParkedReview:
         assert resumed.regenerate_calls == [("Shorter", ["prompt"])]
         # Pushed before regenerating, so the plugin refuses a second answer 
for the round meanwhile.
         assert status_while_regenerating == [SessionStatus.CHANGES_REQUESTED]
-        assert ti.xcoms[f"{XCOM_HUMAN_FEEDBACK_PREFIX}1"] == "Shorter"
-        assert ti.xcoms[f"{XCOM_AGENT_OUTPUT_PREFIX}2"] == "Revised: Shorter"
+        assert ti.xcoms[f"{XCOM_HUMAN_FEEDBACK_PREFIX}1"] == 
wrap_review_text("Shorter", dag_id="d")
+        assert ti.xcoms[f"{XCOM_AGENT_OUTPUT_PREFIX}2"] == 
wrap_review_text("Revised: Shorter", dag_id="d")
         assert 
AgentSessionData.model_validate(ti.xcoms[XCOM_AGENT_SESSION]).iteration == 2
         assert second.kwargs["iteration"] == 2
         assert second.kwargs["deadline"] == first.kwargs["deadline"]
diff --git 
a/providers/common/ai/tests/unit/common/ai/operators/test_agent_hitl_review.py 
b/providers/common/ai/tests/unit/common/ai/operators/test_agent_hitl_review.py
index 035da44c3ac..b54179bb103 100644
--- 
a/providers/common/ai/tests/unit/common/ai/operators/test_agent_hitl_review.py
+++ 
b/providers/common/ai/tests/unit/common/ai/operators/test_agent_hitl_review.py
@@ -38,6 +38,7 @@ from airflow.providers.common.ai.utils.hitl_review import (
     XCOM_AGENT_OUTPUT_PREFIX,
     XCOM_HUMAN_ACTION,
     XCOM_HUMAN_FEEDBACK_PREFIX,
+    unwrap_review_text,
 )
 from airflow.providers.common.ai.utils.usage_budget import USAGE_BUDGET_KEY, 
TaskStateStoreUsageBudget
 from airflow.providers.standard.exceptions import HITLRejectException, 
HITLTimeoutError
@@ -101,6 +102,11 @@ def _operator(model_fn=_summarizer, **kwargs) -> 
AgentOperator:
     return op
 
 
+def _unwrap_pushed(ctx, key: str) -> str | None:
+    """Return the text the HITL Review tab shows for an output or feedback 
XCom the task pushed."""
+    return unwrap_review_text(ctx["task_instance"].xcoms[key], 
dag_id=ctx["task_instance"].dag_id)
+
+
 @pytest.fixture
 def ctx(review_context) -> Any:
     return review_context
@@ -114,8 +120,8 @@ def 
test_review_resumes_in_a_new_operator_and_returns_the_approved_model(park, c
     second = park(lambda: _operator().resume_hitl_review(ctx, **first.kwargs, 
event=REQUEST_CHANGES))
     result = _operator().resume_hitl_review(ctx, **second.kwargs, 
event=APPROVE)
 
-    assert ctx["task_instance"].xcoms[f"{XCOM_AGENT_OUTPUT_PREFIX}1"] == 
'{"text":"A long summary","words":3}'
-    assert ctx["task_instance"].xcoms[f"{XCOM_AGENT_OUTPUT_PREFIX}2"] == 
'{"text":"Short","words":1}'
+    assert _unwrap_pushed(ctx, f"{XCOM_AGENT_OUTPUT_PREFIX}1") == '{"text":"A 
long summary","words":3}'
+    assert _unwrap_pushed(ctx, f"{XCOM_AGENT_OUTPUT_PREFIX}2") == 
'{"text":"Short","words":1}'
     assert result == Summary(text="Short", words=1)
     assert ctx["task_state_store"].get("common_ai_hitl_review_state") is None
 
@@ -271,17 +277,19 @@ class TestDurable:
         with patch(UPSERT, autospec=True) as upsert:
             third = park(lambda: self._operator(writer).execute(ctx))
 
-        xcoms = ctx["task_instance"].xcoms
         assert third.kwargs["iteration"] == 3
         upsert.assert_called_once()
         # Fetch and first summary, the regeneration, the failed one, and the 
failed one again on retry.
         assert (writer.requests, writer.fetches) == (5, 1)
-        assert [xcoms[f"{XCOM_AGENT_OUTPUT_PREFIX}{n}"] for n in (1, 2, 3)] == 
[
+        assert [_unwrap_pushed(ctx, f"{XCOM_AGENT_OUTPUT_PREFIX}{n}") for n in 
(1, 2, 3)] == [
             "summary 2 after []",
             "summary 3 after ['Shorter']",
             "summary 5 after ['Shorter', 'Add the margin']",
         ]
-        assert [xcoms[f"{XCOM_HUMAN_FEEDBACK_PREFIX}{n}"] for n in (1, 2)] == 
["Shorter", "Add the margin"]
+        assert [_unwrap_pushed(ctx, f"{XCOM_HUMAN_FEEDBACK_PREFIX}{n}") for n 
in (1, 2)] == [
+            "Shorter",
+            "Add the margin",
+        ]
 
     def 
test_the_new_first_output_after_a_reject_replays_on_later_retries(self, park, 
ctx):
         """The reject told the journal to ask the model again; the run that 
did so takes that back."""
@@ -298,7 +306,7 @@ class TestDurable:
         again = park(lambda: self._operator(writer).execute(ctx))
 
         assert again.kwargs["iteration"] == 2
-        assert ctx["task_instance"].xcoms[f"{XCOM_AGENT_OUTPUT_PREFIX}1"] == 
"summary 3 after []"
+        assert _unwrap_pushed(ctx, f"{XCOM_AGENT_OUTPUT_PREFIX}1") == "summary 
3 after []"
         assert (writer.requests, writer.fetches) == (5, 1)
 
     def 
test_a_retry_after_the_review_timed_out_asks_about_the_same_round_again(self, 
park, ctx):
@@ -316,7 +324,7 @@ class TestDurable:
         again = park(lambda: self._operator(writer).execute(ctx))
 
         assert again.kwargs["iteration"] == 2
-        assert ctx["task_instance"].xcoms[f"{XCOM_AGENT_OUTPUT_PREFIX}2"] == 
"summary 3 after ['Shorter']"
+        assert _unwrap_pushed(ctx, f"{XCOM_AGENT_OUTPUT_PREFIX}2") == "summary 
3 after ['Shorter']"
         assert (writer.requests, writer.fetches) == (3, 1)
 
     @pytest.mark.parametrize(
@@ -354,7 +362,7 @@ class TestDurable:
         assert writer.fetches == 1
         assert writer.requests == requests_before_retry + 1
         assert (
-            ctx["task_instance"].xcoms[f"{XCOM_AGENT_OUTPUT_PREFIX}1"]
+            _unwrap_pushed(ctx, f"{XCOM_AGENT_OUTPUT_PREFIX}1")
             == f"summary {requests_before_retry + 1} after []"
         )
         assert _HITL_REVIEW_ANSWERS_KEY not in ctx["task_state_store"].data
@@ -372,7 +380,7 @@ class TestDurable:
         again = park(lambda: self._operator(writer, live=True).execute(ctx))
 
         assert again.kwargs["iteration"] == 1
-        assert ctx["task_instance"].xcoms[f"{XCOM_AGENT_OUTPUT_PREFIX}1"] == 
"summary 4 after []"
+        assert _unwrap_pushed(ctx, f"{XCOM_AGENT_OUTPUT_PREFIX}1") == "summary 
4 after []"
         assert f"{XCOM_HUMAN_FEEDBACK_PREFIX}1" not in 
ctx["task_instance"].xcoms
         assert "is not the one the reviewer asked to change" in caplog.text
 
@@ -420,9 +428,7 @@ class TestDurable:
         assert [key for key in store if "run_2_" in key] == []
         # The regeneration started run 1 over, rather than finding the old 
branch's run 1 there.
         assert "took a different path" not in caplog.text
-        assert (
-            ctx["task_instance"].xcoms[f"{XCOM_AGENT_OUTPUT_PREFIX}2"] == 
"summary 6 after ['Shorter please']"
-        )
+        assert _unwrap_pushed(ctx, f"{XCOM_AGENT_OUTPUT_PREFIX}2") == "summary 
6 after ['Shorter please']"
 
     @pytest.mark.parametrize(
         ("requires_approval", "match"),
diff --git 
a/providers/common/ai/tests/unit/common/ai/plugins/test_hitl_review.py 
b/providers/common/ai/tests/unit/common/ai/plugins/test_hitl_review.py
index 15f02bc8e07..1e59a292ac6 100644
--- a/providers/common/ai/tests/unit/common/ai/plugins/test_hitl_review.py
+++ b/providers/common/ai/tests/unit/common/ai/plugins/test_hitl_review.py
@@ -24,7 +24,8 @@ if not AIRFLOW_V_3_1_PLUS:
     pytest.skip("Human in the loop is only compatible with Airflow >= 3.1.0", 
allow_module_level=True)
 
 import datetime
-from typing import TYPE_CHECKING
+import json
+from typing import TYPE_CHECKING, Any
 from unittest import mock
 from uuid import UUID
 
@@ -51,10 +52,12 @@ from airflow.providers.common.ai.utils.hitl_review import (
     XCOM_HUMAN_FEEDBACK_PREFIX,
     AgentSessionData,
     SessionStatus,
+    wrap_review_text,
 )
 from airflow.providers.common.compat.sdk import timezone
 from airflow.providers.standard.operators.empty import EmptyOperator
 from airflow.providers.standard.operators.python import PythonOperator
+from airflow.sdk.bases.xcom import BaseXCom
 from airflow.utils.session import provide_session
 from airflow.utils.state import TaskInstanceState
 from airflow.utils.types import DagRunType
@@ -136,7 +139,7 @@ def _create_hitl_session(
     _write_xcom(
         session,
         key=f"{XCOM_AGENT_OUTPUT_PREFIX}{iteration}",
-        value=current_output,
+        value=wrap_review_text(current_output, dag_id=dag_id),
         region_id=NO_REGION,
         dag_id=dag_id,
         task_id=task_id,
@@ -311,12 +314,24 @@ class TestReadXcomByPrefix:
                 XCOM_AGENT_OUTPUT_PREFIX,
                 {1: "a", 2: "b", 99: "d"},
             ),
+            (
+                [("1", wrap_review_text("v1", dag_id="d")), ("2", "v2")],
+                XCOM_HUMAN_FEEDBACK_PREFIX,
+                {1: "v1", 2: "v2"},
+            ),
+            (
+                [("1", wrap_review_text("v1", dag_id="other_dag"))],
+                XCOM_AGENT_OUTPUT_PREFIX,
+                {1: {"text": "v1", "dag_id": "other_dag"}},
+            ),
         ],
         ids=[
             "two_iterations",
             "single_iteration",
             "numeric_and_non_numeric",
             "mixed_with_high_iteration",
+            "wrapped_and_unwrapped",
+            "wrapped_for_another_dag",
         ],
     )
     def test_read_xcom_by_prefix_output_combinations(
@@ -1736,6 +1751,259 @@ class TestRejectEndpoint:
         assert response.json()["status"] == "rejected"
 
 
+class _ReferenceXComBackend(BaseXCom):
+    """Keep values outside the metadata database and store a reference there, 
as object-storage backends do."""
+
+    stored: dict[str, Any] = {}
+
+    @staticmethod
+    def deserialize_value(result) -> Any:
+        value = BaseXCom.deserialize_value(result)
+        if isinstance(value, str):
+            return _ReferenceXComBackend.stored.get(value, value)
+        return value
+
+
+class _LoadValueReferenceXComBackend(BaseXCom):
+    """Resolve the same references through ``load_value`` only, as 
``store_value`` backends do."""
+
+    @classmethod
+    def load_value(cls, stored) -> Any:
+        value = super().load_value(stored)
+        if isinstance(value, str):
+            return _ReferenceXComBackend.stored.get(value, value)
+        return value
+
+
+class TestReferenceStoringXComBackend:
+    """Review XComs a custom backend stored as references are read through the 
backend."""
+
+    PARAMS = {"dag_id": TEST_DAG_ID, "run_id": TEST_RUN_ID, "task_id": 
TEST_TASK_ID}
+
+    @pytest.fixture(
+        autouse=True,
+        params=[
+            pytest.param(_ReferenceXComBackend, id="deserialize_value"),
+            pytest.param(
+                _LoadValueReferenceXComBackend,
+                id="load_value",
+                marks=pytest.mark.skipif(
+                    not hasattr(BaseXCom, "load_value"), reason="This Airflow 
version has no load_value hook"
+                ),
+            ),
+        ],
+    )
+    def setup(self, request, monkeypatch, dag_maker, session):
+        monkeypatch.setattr(
+            "airflow.providers.common.ai.plugins.hitl_review.XCom", 
request.param, raising=False
+        )
+        _clear_db()
+        with dag_maker(TEST_DAG_ID, schedule=None, start_date=logical_date, 
serialized=True):
+            EmptyOperator(task_id=TEST_TASK_ID)
+        dag_maker.create_dagrun(run_id=TEST_RUN_ID, 
run_type=DagRunType.MANUAL, logical_date=logical_date)
+        dag_maker.sync_dagbag_to_db()
+        sess = AgentSessionData(
+            status=SessionStatus.PENDING_REVIEW,
+            iteration=2,
+            max_iterations=5,
+            prompt="Summarize",
+            current_output="Second output",
+        )
+        by_reference = {
+            XCOM_AGENT_SESSION: sess.model_dump(mode="json"),
+            f"{XCOM_AGENT_OUTPUT_PREFIX}2": wrap_review_text("Second output", 
dag_id=TEST_DAG_ID),
+        }
+        stored_natively = {
+            f"{XCOM_AGENT_OUTPUT_PREFIX}1": wrap_review_text("First output", 
dag_id=TEST_DAG_ID),
+            f"{XCOM_HUMAN_FEEDBACK_PREFIX}1": wrap_review_text("Add more 
detail", dag_id=TEST_DAG_ID),
+        }
+        for key, value in by_reference.items():
+            reference = f"file:///xcom-store/{key}.json"
+            _ReferenceXComBackend.stored[reference] = value
+            stored_natively[key] = reference
+        for key, value in stored_natively.items():
+            _write_xcom(
+                session,
+                key=key,
+                value=value,
+                region_id=NO_REGION,
+                dag_id=TEST_DAG_ID,
+                task_id=TEST_TASK_ID,
+                run_id=TEST_RUN_ID,
+                map_index=MAP_INDEX,
+            )
+        session.commit()
+        yield
+        _ReferenceXComBackend.stored.clear()
+        _clear_db()
+
+    def test_find_resolves_references(self, test_client):
+        response = test_client.get("/hitl-review/sessions/find", 
params=self.PARAMS)
+
+        assert response.status_code == 200
+        data = response.json()
+        assert data["status"] == "pending_review"
+        assert data["iteration"] == 2
+        assert data["current_output"] == "Second output"
+        assert [(e["role"], e["content"], e["iteration"]) for e in 
data["conversation"]] == [
+            ("assistant", "First output", 1),
+            ("human", "Add more detail", 1),
+            ("assistant", "Second output", 2),
+        ]
+
+    @pytest.mark.parametrize(
+        ("endpoint", "body", "expected_status"),
+        [
+            ("feedback", {"feedback": "Shorter, please"}, "changes_requested"),
+            ("approve", None, "approved"),
+            ("reject", None, "rejected"),
+        ],
+    )
+    def test_action_resolves_references(self, test_client, endpoint, body, 
expected_status):
+        response = test_client.post(f"/hitl-review/sessions/{endpoint}", 
params=self.PARAMS, json=body)
+
+        assert response.status_code == 200
+        data = response.json()
+        assert data["status"] == expected_status
+        assert data["iteration"] == 2
+        assert data["current_output"] == "Second output"
+        assert [e["content"] for e in data["conversation"] if e["role"] == 
"assistant"] == [
+            "First output",
+            "Second output",
+        ]
+
+
+class TestReviewTextHoldingAStoragePath:
+    """An output or feedback that is a path under the backend's storage never 
returns what it points to."""
+
+    PARAMS = {"dag_id": TEST_DAG_ID, "run_id": TEST_RUN_ID, "task_id": 
TEST_TASK_ID}
+    SECRET = "Another Dag's XCom"
+
+    @pytest.fixture(
+        params=[
+            pytest.param(SECRET, id="xcom_value"),
+            pytest.param({"text": SECRET, "dag_id": "other_dag"}, 
id="other_dag_review_text"),
+        ]
+    )
+    def other_dag_xcom(self, request, tmp_path, monkeypatch, dag_maker, 
session):
+        """Use ``XComObjectStorageBackend`` under ``tmp_path``, and return the 
URL of another Dag's XCom file in it."""
+        backend = 
pytest.importorskip("airflow.providers.common.io.xcom.backend")
+        caches = (backend._get_base_path, backend._get_compression, 
backend._get_threshold)
+        other = tmp_path / "other_dag" / "manual_run" / "secret_task" / 
"return_value.json"
+        other.parent.mkdir(parents=True)
+        other.write_text(json.dumps(request.param))
+        _clear_db()
+        with dag_maker(TEST_DAG_ID, schedule=None, start_date=logical_date, 
serialized=True):
+            EmptyOperator(task_id=TEST_TASK_ID)
+        dag_maker.create_dagrun(run_id=TEST_RUN_ID, 
run_type=DagRunType.MANUAL, logical_date=logical_date)
+        dag_maker.sync_dagbag_to_db()
+        _create_hitl_session(iteration=1, current_output="Initial output", 
session=session)
+        session.commit()
+        with conf_vars(
+            {
+                ("common.io", "xcom_objectstorage_path"): f"file://{tmp_path}",
+                # Values stay in the database, so a path the worker pushes is 
stored as is.
+                ("common.io", "xcom_objectstorage_threshold"): "-1",
+            }
+        ):
+            for cache in caches:
+                cache.cache_clear()
+            monkeypatch.setattr(
+                "airflow.providers.common.ai.plugins.hitl_review.XCom",
+                backend.XComObjectStorageBackend,
+                raising=False,
+            )
+            yield f"file://{other}"
+        for cache in caches:
+            cache.cache_clear()
+        _clear_db()
+
+    def test_feedback_submitted_as_a_path(self, test_client, session, 
other_dag_xcom):
+        response = test_client.post(
+            "/hitl-review/sessions/feedback", params=self.PARAMS, 
json={"feedback": other_dag_xcom}
+        )
+
+        assert response.status_code == 200
+        stored = _read_xcom(
+            session,
+            dag_id=TEST_DAG_ID,
+            run_id=TEST_RUN_ID,
+            task_id=TEST_TASK_ID,
+            map_index=MAP_INDEX,
+            region_id=NO_REGION,
+            key=f"{XCOM_HUMAN_FEEDBACK_PREFIX}1",
+        )
+        assert stored == wrap_review_text(other_dag_xcom, dag_id=TEST_DAG_ID)
+        assert self.SECRET not in response.text
+        assert response.json()["conversation"][-1]["content"] == other_dag_xcom
+        found = test_client.get("/hitl-review/sessions/find", 
params=self.PARAMS)
+        assert found.status_code == 200
+        assert self.SECRET not in found.text
+        assert found.json()["conversation"][-1]["content"] == other_dag_xcom
+
+    def _find_after_writing(self, test_client, session, key: str, value: Any):
+        _write_xcom(
+            session,
+            key=key,
+            value=value,
+            region_id=NO_REGION,
+            dag_id=TEST_DAG_ID,
+            task_id=TEST_TASK_ID,
+            run_id=TEST_RUN_ID,
+            map_index=MAP_INDEX,
+        )
+        session.commit()
+        response = test_client.get("/hitl-review/sessions/find", 
params=self.PARAMS)
+        assert response.status_code == 200
+        return response
+
+    @pytest.mark.parametrize(
+        ("prefix", "role"),
+        [
+            pytest.param(XCOM_AGENT_OUTPUT_PREFIX, "assistant", 
id="agent_output"),
+            pytest.param(XCOM_HUMAN_FEEDBACK_PREFIX, "human", 
id="human_feedback"),
+        ],
+    )
+    def test_stored_path_is_shown_as_is(self, test_client, session, 
other_dag_xcom, prefix, role):
+        """A bare path, as an earlier worker pushed a model output or Required 
Actions feedback."""
+        response = self._find_after_writing(test_client, session, 
f"{prefix}1", other_dag_xcom)
+
+        assert self.SECRET not in response.text
+        assert [e["content"] for e in response.json()["conversation"] if 
e["role"] == role] == [
+            other_dag_xcom
+        ]
+
+    @pytest.mark.parametrize(
+        ("prefix", "role"),
+        [
+            pytest.param(XCOM_AGENT_OUTPUT_PREFIX, "assistant", 
id="agent_output"),
+            pytest.param(XCOM_HUMAN_FEEDBACK_PREFIX, "human", 
id="human_feedback"),
+        ],
+    )
+    def test_wrapped_path_is_shown_as_text(self, test_client, session, 
other_dag_xcom, prefix, role):
+        """A model output or Required Actions feedback that is a path, as the 
worker pushes it now."""
+        wrapped = wrap_review_text(other_dag_xcom, dag_id=TEST_DAG_ID)
+
+        response = self._find_after_writing(test_client, session, 
f"{prefix}1", wrapped)
+
+        assert self.SECRET not in response.text
+        assert [e["content"] for e in response.json()["conversation"] if 
e["role"] == role] == [
+            other_dag_xcom
+        ]
+
+    def test_wrapped_text_in_storage_is_resolved(self, test_client, session, 
tmp_path, other_dag_xcom):
+        """From ``xcom_objectstorage_threshold`` up, the row holds a reference 
to the wrapped output, which is shown."""
+        stored = tmp_path / TEST_DAG_ID / TEST_RUN_ID / TEST_TASK_ID / 
"output.json"
+        stored.parent.mkdir(parents=True)
+        stored.write_text(json.dumps(wrap_review_text("Stored output", 
dag_id=TEST_DAG_ID)))
+
+        response = self._find_after_writing(
+            test_client, session, f"{XCOM_AGENT_OUTPUT_PREFIX}1", 
f"file://{stored}"
+        )
+
+        assert [e["content"] for e in response.json()["conversation"]] == 
["Stored output"]
+
+
 class TestConflictOnWrongStatus:
     """Test 409 when session is not pending_review."""
 
diff --git a/providers/common/ai/tests/unit/common/ai/utils/test_hitl_review.py 
b/providers/common/ai/tests/unit/common/ai/utils/test_hitl_review.py
index d0ecd7c6519..e20a4c34147 100644
--- a/providers/common/ai/tests/unit/common/ai/utils/test_hitl_review.py
+++ b/providers/common/ai/tests/unit/common/ai/utils/test_hitl_review.py
@@ -38,6 +38,8 @@ from airflow.providers.common.ai.utils.hitl_review import (
     HumanActionData,
     HumanFeedbackRequest,
     SessionStatus,
+    unwrap_review_text,
+    wrap_review_text,
 )
 
 
@@ -52,6 +54,27 @@ class TestXComConstants:
         assert XCOM_AGENT_OUTPUT_PREFIX.endswith("_")
 
 
+class TestReviewTextXCom:
+    def test_text_is_wrapped_with_the_dag(self):
+        wrapped = 
wrap_review_text("s3://bucket/xcom/other_dag/run/task/key.json", dag_id="d")
+
+        assert wrapped == {"text": 
"s3://bucket/xcom/other_dag/run/task/key.json", "dag_id": "d"}
+        assert unwrap_review_text(wrapped, dag_id="d") == 
"s3://bucket/xcom/other_dag/run/task/key.json"
+
+    @pytest.mark.parametrize(
+        "value",
+        [
+            pytest.param("Plain text", id="unwrapped_text"),
+            pytest.param({"text": "Output", "dag_id": "other_dag"}, 
id="another_dag"),
+            pytest.param({"text": ["Output"], "dag_id": "d"}, 
id="text_not_a_string"),
+            pytest.param({"dag_id": "d"}, id="no_text"),
+            pytest.param(None, id="none"),
+        ],
+    )
+    def test_anything_not_wrapped_for_the_dag_has_no_text(self, value):
+        assert unwrap_review_text(value, dag_id="d") is None
+
+
 class TestConversationEntry:
     def test_from_fields(self):
         entry = ConversationEntry(role="assistant", content="Hello", 
iteration=1)

Reply via email to