kaxil commented on code in PR #77198:
URL: https://github.com/apache/airflow/pull/77198#discussion_r4649474567
##########
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:
The page says to upgrade the API server no later than the workers, so until
a worker is upgraded it keeps pushing bare strings, and a review that starts
after the API server upgrade shows the reference too. Maybe "an output or
feedback written by an earlier version of the provider"?
##########
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:
These keys now hold a dict instead of a string, so a downstream task that
pulls them gets a different shape. Could this get a `.. note::` in
`changelog.rst`, like the one for the LLM operators' output change?
##########
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:
Nit: `review_text_xcom` reads as a noun. `wrap_review_text`, with
`unwrap_review_text` for the reader? Same for `_shown` in
`test_agent_hitl_review.py`.
##########
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:
This still passes with the plugin's wrap removed (`value=feedback` in
`_record_action`). Both fixture files are ones the read side rejects anyway, so
the response shows the URL either way. The wrap only matters when the path
resolves to a value wrapped for this Dag, so a `{"text": SECRET, "dag_id":
TEST_DAG_ID}` case would catch it, or the test could assert the stored row
equals `review_text_xcom(other_dag_xcom, dag_id=TEST_DAG_ID)`?
##########
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:
`output_1` is only checked for presence, so reverting the wrap on the first
output push (the polling path) keeps this green. Same equality check as
`output_2`?
--
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]