hussein-awala commented on code in PR #77198:
URL: https://github.com/apache/airflow/pull/77198#discussion_r4693207849


##########
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. A review that started on an earlier version of the 
provider

Review Comment:
   Right, the upgrade order makes that case the common one. fc20e15 uses your 
wording: "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."



##########
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": 
...}``

Review Comment:
   Added a `.. note::` in fc20e15 saying the two keys now hold `{"text": ..., 
"dag_id": ...}` and that a task pulling them reads `["text"]`.



##########
providers/common/ai/tests/unit/common/ai/plugins/test_hitl_review.py:
##########
@@ -1736,6 +1751,249 @@ def test_reject_returns_session(self, test_client):
         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": review_text_xcom("Second output", 
dag_id=TEST_DAG_ID),
+        }
+        stored_natively = {
+            f"{XCOM_AGENT_OUTPUT_PREFIX}1": review_text_xcom("First output", 
dag_id=TEST_DAG_ID),
+            f"{XCOM_HUMAN_FEEDBACK_PREFIX}1": review_text_xcom("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, other_dag_xcom):

Review Comment:
   Right. The test now asserts the stored row equals 
`wrap_review_text(other_dag_xcom, dag_id=TEST_DAG_ID)`. A `{"text": SECRET, 
"dag_id": TEST_DAG_ID}` fixture case would also fail 
`test_stored_path_is_shown_as_is`, which shows a bare legacy path resolving to 
the same Dag's value on purpose. With `value=feedback` in `_record_action`, 
both cases of the test now fail.



##########
providers/common/ai/tests/unit/common/ai/mixins/test_hitl_review.py:
##########
@@ -288,7 +289,9 @@ def 
test_changes_requested_calls_regenerate_and_pushes_new_output(
         }
         assert "airflow_hitl_review_agent_output_1" in output_pushes

Review Comment:
   Done. The test now compares all output pushes, with `output_1` equal to 
`wrap_review_text("Initial", dag_id="test_dag")`, and it fails with the wrap 
removed from the first push.



##########
providers/common/ai/src/airflow/providers/common/ai/utils/hitl_review.py:
##########
@@ -75,6 +77,29 @@
 HITL_FEEDBACK_PARAM = "feedback"
 
 
+def review_text_xcom(text: str, *, dag_id: str) -> dict[str, str]:

Review Comment:
   Renamed to `wrap_review_text` / `unwrap_review_text`, and `_shown` to 
`_unwrap_pushed`, in fc20e15.



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