You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@airflow.apache.org by "kaxil (via GitHub)" <gi...@apache.org> on 2026/08/11 19:55:35 UTC
[PR] Record Anthropic agent session token usage and cost in XCom [airflow]
kaxil opened a new pull request, #71463:
URL: https://github.com/apache/airflow/pull/71463
<!-- 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)
-->
---
* 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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Record Anthropic agent session token usage and cost in XCom [airflow]
Posted by "kaxil (via GitHub)" <gi...@apache.org>.
kaxil commented on code in PR #71463:
URL: https://github.com/apache/airflow/pull/71463#discussion_r3766972481
##########
providers/anthropic/src/airflow/providers/anthropic/hooks/anthropic.py:
##########
@@ -646,6 +646,40 @@ def get_session(self, session_id: str) -> BetaManagedAgentsSession:
self._require_first_party("Managed Agents")
return self._first_party_conn.beta.sessions.retrieve(session_id)
+ def get_session_usage(self, session_id: str) -> dict[str, Any]:
Review Comment:
Not able to -- `get_session_usage(session_id)` takes the session to look up, and a property cannot take an argument. It is also a network call rather than an attribute read, so a property would hide a round trip behind attribute access.
There is a related no-argument accessor though: `summarize_usage(session)` flattens a session object you already hold, which is what the failure paths use so they do not pay a second retrieve. If the concern was the call looking heavier than it is, that one is the cheap path.
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Record Anthropic agent session token usage and cost in XCom [airflow]
Posted by "Lee-W (via GitHub)" <gi...@apache.org>.
Lee-W commented on code in PR #71463:
URL: https://github.com/apache/airflow/pull/71463#discussion_r3771802449
##########
providers/anthropic/src/airflow/providers/anthropic/operators/agent.py:
##########
@@ -226,24 +237,83 @@ def execute_complete(self, context: Context, event: Any = None) -> str:
self.session_id = event["session_id"]
status = event["status"]
if status == "timeout":
- self._archive_session(self.session_id)
+ self._tear_down(context, self.session_id)
raise AnthropicAgentSessionTimeout(event["message"])
if status == "error":
# The trigger yields "error" when polling gives up while the session may still
# be running; archive it best-effort so its container does not linger.
- self._archive_session(self.session_id)
+ self._tear_down(context, self.session_id)
raise _create_session_error(event["message"], event.get("stop_reason"))
self.log.info("Session %s completed.", self.session_id)
+ self._push_usage(context, self.session_id)
return self.session_id
- def _archive_session(self, session_id: str | None) -> None:
- """Best-effort teardown of the server-side session (frees its container)."""
+ def _tear_down(self, context: Context, session_id: str | None) -> None:
+ """
+ Archive the session and record what it spent, in that order.
+
+ Every failure path needs both. Teardown goes first because it is the
+ time-critical call, and ``sessions.archive`` returns the session carrying its final
+ usage, so recording spend costs no extra request.
+ """
+ archived = self._archive_session(session_id)
+ self._push_usage(context, session_id, session=archived)
+
+ def _push_usage(self, context: Context, session_id: str | None, session: Any = None) -> None:
+ """
+ Push the session's token/cost usage to XCom under ``usage``, best effort.
+
+ Runs on failure as well as success: a session that stopped against its budget is
+ exactly the one whose spend you want recorded. Never allowed to raise -- a usage
+ read that fails must not mask the task's real outcome.
+
+ On the failure paths the session has just been archived, and ``sessions.archive``
+ returns the session with its final usage; pass it as ``session`` so teardown is not
+ delayed by an extra retrieve against an API that may be why the task is failing.
+ """
if not session_id:
return
+ # The whole body is guarded, not just the API call: this runs on the failure path
+ # immediately before re-raising, so anything that throws here -- an unavailable
+ # session, a serialization error, a context without a task instance -- would
+ # replace the exception the task should actually fail with.
+ try:
+ # XCom is cleared at the start of every attempt, so this key only ever holds
+ # the last one. Stamping the attempt makes that visible rather than silently
+ # under-reporting total spend across retries. Built as a new dict rather than
+ # mutating what the hook returned.
+ summary = (
+ self.hook.summarize_usage(session)
+ if session is not None
+ else self.hook.get_session_usage(session_id)
+ )
+ usage = {**summary, "try_number": getattr(context["ti"], "try_number", None)}
+ context["ti"].xcom_push(key="usage", value=usage)
+ cost = usage.get("list_cost")
+ self.log.info(
+ "Session %s used %s input / %s output tokens; list cost %s",
+ session_id,
+ usage.get("input_tokens"),
+ usage.get("output_tokens"),
+ f"{cost['currency']} {cost['amount']} (minor units)" if cost else "unavailable",
+ )
+ except Exception as e:
+ self.log.warning("Could not record usage for session %s: %s", session_id, e)
Review Comment:
```suggestion
self.log.exception("Could not record usage for session %s", session_id)
```
##########
providers/anthropic/tests/unit/anthropic/hooks/test_anthropic.py:
##########
@@ -308,7 +315,100 @@ def test_drops_a_none_budget(self):
assert "budget" not in client.beta.sessions.create.call_args.kwargs
-class TestCreateSessionError:
+class TestGetSessionUsage:
+ """
+ Built on the real SDK usage models rather than mocks.
+
+ Constructing the real model is not on its own a check on field names: it sets
+ ``extra="allow"``, so a misspelling is accepted as an extra field rather than rejected.
+ ``test_usage_fields_exist_on_the_sdk_model`` is what pins the names to the declared
+ schema. Only the session wrapper is a stand-in, since ``get_session_usage`` reads
+ nothing from it but ``.usage``.
+ """
+
+ def test_usage_fields_exist_on_the_sdk_model(self):
+ # The reported breakdown must be fields the SDK actually declares. active_seconds
+ # lived on session.stats rather than session.usage as recently as 0.117.0, and the
+ # floor is an open-ended >= on a beta API -- if a field moves again, summarize_usage
+ # would return it as None (or raise, swallowed into a warning) with no other signal.
+ assert set(BetaManagedAgentsSessionUsage.model_fields) >= {
+ "input_tokens",
+ "output_tokens",
+ "cache_read_input_tokens",
+ "cache_creation",
+ "server_tool_use",
+ "active_seconds",
+ "list_cost",
+ }
+
+ @staticmethod
+ def _create_session(list_cost, cache_creation=None, server_tool_use=None):
+ usage = BetaManagedAgentsSessionUsage(
+ input_tokens=827,
+ output_tokens=17065,
+ cache_read_input_tokens=0,
+ active_seconds=91.2,
+ list_cost=list_cost,
+ cache_creation=cache_creation,
+ server_tool_use=server_tool_use,
+ )
+ return SimpleNamespace(usage=usage)
+
+ def test_flattens_to_json_safe_scalars(self):
+ hook, client = _make_hook()
+ client.beta.sessions.retrieve.return_value = self._create_session(
+ BetaMonetaryAmount(amount="44", currency="USD")
+ )
+ assert hook.get_session_usage("s") == {
Review Comment:
should we make "s" a `session_id` variable? I was confused first seeing "s" and woundering where this "s" came from
##########
providers/anthropic/src/airflow/providers/anthropic/operators/agent.py:
##########
@@ -226,24 +237,83 @@ def execute_complete(self, context: Context, event: Any = None) -> str:
self.session_id = event["session_id"]
status = event["status"]
if status == "timeout":
- self._archive_session(self.session_id)
+ self._tear_down(context, self.session_id)
raise AnthropicAgentSessionTimeout(event["message"])
if status == "error":
# The trigger yields "error" when polling gives up while the session may still
# be running; archive it best-effort so its container does not linger.
- self._archive_session(self.session_id)
+ self._tear_down(context, self.session_id)
raise _create_session_error(event["message"], event.get("stop_reason"))
self.log.info("Session %s completed.", self.session_id)
+ self._push_usage(context, self.session_id)
return self.session_id
- def _archive_session(self, session_id: str | None) -> None:
- """Best-effort teardown of the server-side session (frees its container)."""
+ def _tear_down(self, context: Context, session_id: str | None) -> None:
+ """
+ Archive the session and record what it spent, in that order.
+
+ Every failure path needs both. Teardown goes first because it is the
+ time-critical call, and ``sessions.archive`` returns the session carrying its final
+ usage, so recording spend costs no extra request.
+ """
+ archived = self._archive_session(session_id)
+ self._push_usage(context, session_id, session=archived)
+
+ def _push_usage(self, context: Context, session_id: str | None, session: Any = None) -> None:
+ """
+ Push the session's token/cost usage to XCom under ``usage``, best effort.
+
+ Runs on failure as well as success: a session that stopped against its budget is
+ exactly the one whose spend you want recorded. Never allowed to raise -- a usage
+ read that fails must not mask the task's real outcome.
+
+ On the failure paths the session has just been archived, and ``sessions.archive``
+ returns the session with its final usage; pass it as ``session`` so teardown is not
+ delayed by an extra retrieve against an API that may be why the task is failing.
+ """
if not session_id:
return
+ # The whole body is guarded, not just the API call: this runs on the failure path
+ # immediately before re-raising, so anything that throws here -- an unavailable
+ # session, a serialization error, a context without a task instance -- would
+ # replace the exception the task should actually fail with.
+ try:
+ # XCom is cleared at the start of every attempt, so this key only ever holds
+ # the last one. Stamping the attempt makes that visible rather than silently
+ # under-reporting total spend across retries. Built as a new dict rather than
+ # mutating what the hook returned.
+ summary = (
+ self.hook.summarize_usage(session)
+ if session is not None
+ else self.hook.get_session_usage(session_id)
+ )
+ usage = {**summary, "try_number": getattr(context["ti"], "try_number", None)}
+ context["ti"].xcom_push(key="usage", value=usage)
+ cost = usage.get("list_cost")
+ self.log.info(
+ "Session %s used %s input / %s output tokens; list cost %s",
+ session_id,
+ usage.get("input_tokens"),
+ usage.get("output_tokens"),
+ f"{cost['currency']} {cost['amount']} (minor units)" if cost else "unavailable",
+ )
+ except Exception as e:
+ self.log.warning("Could not record usage for session %s: %s", session_id, e)
+
+ def _archive_session(self, session_id: str | None) -> Any:
Review Comment:
```suggestion
def _archive_session(self, session_id: str | None) -> BetaManagedAgentsSession | None:
```
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Record Anthropic agent session token usage and cost in XCom [airflow]
Posted by "kaxil (via GitHub)" <gi...@apache.org>.
kaxil merged PR #71463:
URL: https://github.com/apache/airflow/pull/71463
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Record Anthropic agent session token usage and cost in XCom [airflow]
Posted by "kaxil (via GitHub)" <gi...@apache.org>.
kaxil commented on code in PR #71463:
URL: https://github.com/apache/airflow/pull/71463#discussion_r3766978085
##########
providers/anthropic/tests/unit/anthropic/hooks/test_anthropic.py:
##########
@@ -308,6 +315,94 @@ def test_drops_a_none_budget(self):
assert "budget" not in client.beta.sessions.create.call_args.kwargs
+class TestGetSessionUsage:
+ """
+ Built on the real SDK usage models rather than mocks.
+
+ Constructing the real model is not on its own a check on field names: it sets
+ ``extra="allow"``, so a misspelling is accepted as an extra field rather than rejected.
+ ``test_usage_fields_exist_on_the_sdk_model`` is what pins the names to the declared
+ schema. Only the session wrapper is a stand-in, since ``get_session_usage`` reads
+ nothing from it but ``.usage``.
+ """
+
+ def test_usage_fields_exist_on_the_sdk_model(self):
+ # The reported breakdown must be fields the SDK actually declares. active_seconds
+ # lived on session.stats rather than session.usage as recently as 0.117.0, and the
+ # floor is an open-ended >= on a beta API -- if a field moves again, summarize_usage
+ # would return it as None (or raise, swallowed into a warning) with no other signal.
+ assert set(BetaManagedAgentsSessionUsage.model_fields) >= {
+ "input_tokens",
+ "output_tokens",
+ "cache_read_input_tokens",
+ "cache_creation",
+ "server_tool_use",
+ "active_seconds",
+ "list_cost",
+ }
+
+ @staticmethod
+ def _session(list_cost, cache_creation=None, server_tool_use=None):
Review Comment:
Applied. It also disambiguates it from the module-level `_session(status, ...)` helper further up the file, which is a different thing entirely.
##########
providers/anthropic/tests/unit/anthropic/operators/test_agent.py:
##########
@@ -34,8 +34,10 @@
pytest.importorskip("anthropic")
-def _context():
- return {"ti": mock.MagicMock()}
+def _context(try_number=1):
Review Comment:
Applied, across all 30 call sites in the file.
##########
providers/anthropic/tests/unit/anthropic/hooks/test_anthropic.py:
##########
@@ -308,6 +315,94 @@ def test_drops_a_none_budget(self):
assert "budget" not in client.beta.sessions.create.call_args.kwargs
+class TestGetSessionUsage:
+ """
+ Built on the real SDK usage models rather than mocks.
+
+ Constructing the real model is not on its own a check on field names: it sets
+ ``extra="allow"``, so a misspelling is accepted as an extra field rather than rejected.
+ ``test_usage_fields_exist_on_the_sdk_model`` is what pins the names to the declared
+ schema. Only the session wrapper is a stand-in, since ``get_session_usage`` reads
+ nothing from it but ``.usage``.
+ """
+
+ def test_usage_fields_exist_on_the_sdk_model(self):
+ # The reported breakdown must be fields the SDK actually declares. active_seconds
+ # lived on session.stats rather than session.usage as recently as 0.117.0, and the
+ # floor is an open-ended >= on a beta API -- if a field moves again, summarize_usage
+ # would return it as None (or raise, swallowed into a warning) with no other signal.
+ assert set(BetaManagedAgentsSessionUsage.model_fields) >= {
+ "input_tokens",
+ "output_tokens",
+ "cache_read_input_tokens",
+ "cache_creation",
+ "server_tool_use",
+ "active_seconds",
+ "list_cost",
+ }
+
+ @staticmethod
+ def _session(list_cost, cache_creation=None, server_tool_use=None):
+ usage = BetaManagedAgentsSessionUsage(
+ input_tokens=827,
+ output_tokens=17065,
+ cache_read_input_tokens=0,
+ active_seconds=91.2,
+ list_cost=list_cost,
+ cache_creation=cache_creation,
+ server_tool_use=server_tool_use,
+ )
+ return SimpleNamespace(usage=usage)
+
+ def test_flattens_to_json_safe_scalars(self):
+ hook, client = _make_hook()
+ client.beta.sessions.retrieve.return_value = self._session(
+ BetaMonetaryAmount(amount="44", currency="USD")
+ )
+ assert hook.get_session_usage("s") == {
+ "input_tokens": 827,
+ "output_tokens": 17065,
+ "cache_read_input_tokens": 0,
+ "cache_creation": None,
+ "server_tool_use": None,
+ "active_seconds": 91.2,
+ "list_cost": {"amount": "44", "currency": "USD"},
+ }
+
+ def test_reports_every_billable_dimension(self):
+ # list_cost is None exactly when a caller must price the run from usage, so the
+ # expensive side (cache writes, server tool calls) cannot be missing.
+ hook, client = _make_hook()
+ client.beta.sessions.retrieve.return_value = self._session(
+ None,
+ cache_creation=BetaManagedAgentsCacheCreationUsage(
+ ephemeral_5m_input_tokens=120, ephemeral_1h_input_tokens=340
+ ),
+ server_tool_use=BetaManagedAgentsServerToolUsage(web_search_requests=3, web_fetch_requests=5),
+ )
+ usage = hook.get_session_usage("s")
Review Comment:
Done -- it now asserts the whole dict. Better than my version: the per-key asserts would not have caught an unexpected extra key, and this pins the exact shape that lands in XCom.
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Record Anthropic agent session token usage and cost in XCom [airflow]
Posted by "kaxil (via GitHub)" <gi...@apache.org>.
kaxil commented on code in PR #71463:
URL: https://github.com/apache/airflow/pull/71463#discussion_r3775433897
##########
providers/anthropic/src/airflow/providers/anthropic/operators/agent.py:
##########
@@ -226,24 +237,83 @@ def execute_complete(self, context: Context, event: Any = None) -> str:
self.session_id = event["session_id"]
status = event["status"]
if status == "timeout":
- self._archive_session(self.session_id)
+ self._tear_down(context, self.session_id)
raise AnthropicAgentSessionTimeout(event["message"])
if status == "error":
# The trigger yields "error" when polling gives up while the session may still
# be running; archive it best-effort so its container does not linger.
- self._archive_session(self.session_id)
+ self._tear_down(context, self.session_id)
raise _create_session_error(event["message"], event.get("stop_reason"))
self.log.info("Session %s completed.", self.session_id)
+ self._push_usage(context, self.session_id)
return self.session_id
- def _archive_session(self, session_id: str | None) -> None:
- """Best-effort teardown of the server-side session (frees its container)."""
+ def _tear_down(self, context: Context, session_id: str | None) -> None:
+ """
+ Archive the session and record what it spent, in that order.
+
+ Every failure path needs both. Teardown goes first because it is the
+ time-critical call, and ``sessions.archive`` returns the session carrying its final
+ usage, so recording spend costs no extra request.
+ """
+ archived = self._archive_session(session_id)
+ self._push_usage(context, session_id, session=archived)
+
+ def _push_usage(self, context: Context, session_id: str | None, session: Any = None) -> None:
+ """
+ Push the session's token/cost usage to XCom under ``usage``, best effort.
+
+ Runs on failure as well as success: a session that stopped against its budget is
+ exactly the one whose spend you want recorded. Never allowed to raise -- a usage
+ read that fails must not mask the task's real outcome.
+
+ On the failure paths the session has just been archived, and ``sessions.archive``
+ returns the session with its final usage; pass it as ``session`` so teardown is not
+ delayed by an extra retrieve against an API that may be why the task is failing.
+ """
if not session_id:
return
+ # The whole body is guarded, not just the API call: this runs on the failure path
+ # immediately before re-raising, so anything that throws here -- an unavailable
+ # session, a serialization error, a context without a task instance -- would
+ # replace the exception the task should actually fail with.
+ try:
+ # XCom is cleared at the start of every attempt, so this key only ever holds
+ # the last one. Stamping the attempt makes that visible rather than silently
+ # under-reporting total spend across retries. Built as a new dict rather than
+ # mutating what the hook returned.
+ summary = (
+ self.hook.summarize_usage(session)
+ if session is not None
+ else self.hook.get_session_usage(session_id)
+ )
+ usage = {**summary, "try_number": getattr(context["ti"], "try_number", None)}
+ context["ti"].xcom_push(key="usage", value=usage)
+ cost = usage.get("list_cost")
+ self.log.info(
+ "Session %s used %s input / %s output tokens; list cost %s",
+ session_id,
+ usage.get("input_tokens"),
+ usage.get("output_tokens"),
+ f"{cost['currency']} {cost['amount']} (minor units)" if cost else "unavailable",
+ )
+ except Exception as e:
+ self.log.warning("Could not record usage for session %s: %s", session_id, e)
Review Comment:
Applied -- `warning(..., e)` was throwing the traceback away, and this is the branch where you would want it.
Two things I did not change, in case you want them changed:
It also lifts the level from WARNING to ERROR. I think that is right (a failed usage push is genuinely unexpected, and the task succeeds either way), but `self.log.warning(..., exc_info=True)` keeps the traceback at the old level if you would rather it not page anyone.
The sibling line in `_archive_session` still has the same `warning("Failed to archive session %s: %s", session_id, e)` shape. I left it deliberately -- archiving fails in expected ways (a session already archived, a race with teardown), so promoting that one to ERROR felt wrong without asking. Happy to match them if you would rather they were consistent.
##########
providers/anthropic/src/airflow/providers/anthropic/operators/agent.py:
##########
@@ -226,24 +237,83 @@ def execute_complete(self, context: Context, event: Any = None) -> str:
self.session_id = event["session_id"]
status = event["status"]
if status == "timeout":
- self._archive_session(self.session_id)
+ self._tear_down(context, self.session_id)
raise AnthropicAgentSessionTimeout(event["message"])
if status == "error":
# The trigger yields "error" when polling gives up while the session may still
# be running; archive it best-effort so its container does not linger.
- self._archive_session(self.session_id)
+ self._tear_down(context, self.session_id)
raise _create_session_error(event["message"], event.get("stop_reason"))
self.log.info("Session %s completed.", self.session_id)
+ self._push_usage(context, self.session_id)
return self.session_id
- def _archive_session(self, session_id: str | None) -> None:
- """Best-effort teardown of the server-side session (frees its container)."""
+ def _tear_down(self, context: Context, session_id: str | None) -> None:
+ """
+ Archive the session and record what it spent, in that order.
+
+ Every failure path needs both. Teardown goes first because it is the
+ time-critical call, and ``sessions.archive`` returns the session carrying its final
+ usage, so recording spend costs no extra request.
+ """
+ archived = self._archive_session(session_id)
+ self._push_usage(context, session_id, session=archived)
+
+ def _push_usage(self, context: Context, session_id: str | None, session: Any = None) -> None:
+ """
+ Push the session's token/cost usage to XCom under ``usage``, best effort.
+
+ Runs on failure as well as success: a session that stopped against its budget is
+ exactly the one whose spend you want recorded. Never allowed to raise -- a usage
+ read that fails must not mask the task's real outcome.
+
+ On the failure paths the session has just been archived, and ``sessions.archive``
+ returns the session with its final usage; pass it as ``session`` so teardown is not
+ delayed by an extra retrieve against an API that may be why the task is failing.
+ """
if not session_id:
return
+ # The whole body is guarded, not just the API call: this runs on the failure path
+ # immediately before re-raising, so anything that throws here -- an unavailable
+ # session, a serialization error, a context without a task instance -- would
+ # replace the exception the task should actually fail with.
+ try:
+ # XCom is cleared at the start of every attempt, so this key only ever holds
+ # the last one. Stamping the attempt makes that visible rather than silently
+ # under-reporting total spend across retries. Built as a new dict rather than
+ # mutating what the hook returned.
+ summary = (
+ self.hook.summarize_usage(session)
+ if session is not None
+ else self.hook.get_session_usage(session_id)
+ )
+ usage = {**summary, "try_number": getattr(context["ti"], "try_number", None)}
+ context["ti"].xcom_push(key="usage", value=usage)
+ cost = usage.get("list_cost")
+ self.log.info(
+ "Session %s used %s input / %s output tokens; list cost %s",
+ session_id,
+ usage.get("input_tokens"),
+ usage.get("output_tokens"),
+ f"{cost['currency']} {cost['amount']} (minor units)" if cost else "unavailable",
+ )
+ except Exception as e:
+ self.log.warning("Could not record usage for session %s: %s", session_id, e)
+
+ def _archive_session(self, session_id: str | None) -> Any:
Review Comment:
Applied, with `BetaManagedAgentsSession` imported under `TYPE_CHECKING`. It lines up with the hook, whose `archive_session` already declares `-> BetaManagedAgentsSession`, so the `Any` was losing type information that existed one call away.
For context: the `-> Any` is not something this PR introduced -- it came in with the original provider, so this tightens existing code.
One heads-up for when you reach #71465: that PR adds `**archive_kwargs` to the same signature, so there it reads
```python
def _archive_session(
self, session_id: str | None, **archive_kwargs: Any
) -> BetaManagedAgentsSession | None:
```
wrapped only because the one-line form runs past the line limit.
##########
providers/anthropic/tests/unit/anthropic/hooks/test_anthropic.py:
##########
@@ -308,7 +315,100 @@ def test_drops_a_none_budget(self):
assert "budget" not in client.beta.sessions.create.call_args.kwargs
-class TestCreateSessionError:
+class TestGetSessionUsage:
+ """
+ Built on the real SDK usage models rather than mocks.
+
+ Constructing the real model is not on its own a check on field names: it sets
+ ``extra="allow"``, so a misspelling is accepted as an extra field rather than rejected.
+ ``test_usage_fields_exist_on_the_sdk_model`` is what pins the names to the declared
+ schema. Only the session wrapper is a stand-in, since ``get_session_usage`` reads
+ nothing from it but ``.usage``.
+ """
+
+ def test_usage_fields_exist_on_the_sdk_model(self):
+ # The reported breakdown must be fields the SDK actually declares. active_seconds
+ # lived on session.stats rather than session.usage as recently as 0.117.0, and the
+ # floor is an open-ended >= on a beta API -- if a field moves again, summarize_usage
+ # would return it as None (or raise, swallowed into a warning) with no other signal.
+ assert set(BetaManagedAgentsSessionUsage.model_fields) >= {
+ "input_tokens",
+ "output_tokens",
+ "cache_read_input_tokens",
+ "cache_creation",
+ "server_tool_use",
+ "active_seconds",
+ "list_cost",
+ }
+
+ @staticmethod
+ def _create_session(list_cost, cache_creation=None, server_tool_use=None):
+ usage = BetaManagedAgentsSessionUsage(
+ input_tokens=827,
+ output_tokens=17065,
+ cache_read_input_tokens=0,
+ active_seconds=91.2,
+ list_cost=list_cost,
+ cache_creation=cache_creation,
+ server_tool_use=server_tool_use,
+ )
+ return SimpleNamespace(usage=usage)
+
+ def test_flattens_to_json_safe_scalars(self):
+ hook, client = _make_hook()
+ client.beta.sessions.retrieve.return_value = self._create_session(
+ BetaMonetaryAmount(amount="44", currency="USD")
+ )
+ assert hook.get_session_usage("s") == {
Review Comment:
Yes -- done, and the confusion had a real cause rather than just a terse name.
`_session()` builds the mocked session with `id = "sess_1"`, while these tests passed `"s"`. The two ids reach the assertions by different routes, so the strings under test carried whichever id the code path happened to interpolate. There is now a module-level `SESSION_ID = "sess_1"` used by both `_session()` and every call site here, so they cannot drift.
Separately, while working in this file I found this PR was renaming `TestCreateSessionError` back to `TestSessionError` -- quietly undoing the rename you asked for earlier in the stack. It was a rebase artifact: inserting `TestGetSessionUsage` directly above it made git anchor the hunk on the old class line and re-add the old name. Fixed here, and I checked the name is now consistent from `main` through to the tip of the stack rather than just in this diff.
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Record Anthropic agent session token usage and cost in XCom [airflow]
Posted by "Lee-W (via GitHub)" <gi...@apache.org>.
Lee-W commented on code in PR #71463:
URL: https://github.com/apache/airflow/pull/71463#discussion_r3765412048
##########
providers/anthropic/src/airflow/providers/anthropic/hooks/anthropic.py:
##########
@@ -646,6 +646,40 @@ def get_session(self, session_id: str) -> BetaManagedAgentsSession:
self._require_first_party("Managed Agents")
return self._first_party_conn.beta.sessions.retrieve(session_id)
+ def get_session_usage(self, session_id: str) -> dict[str, Any]:
Review Comment:
should we make it a property instead?
##########
providers/anthropic/tests/unit/anthropic/hooks/test_anthropic.py:
##########
@@ -308,6 +315,94 @@ def test_drops_a_none_budget(self):
assert "budget" not in client.beta.sessions.create.call_args.kwargs
+class TestGetSessionUsage:
+ """
+ Built on the real SDK usage models rather than mocks.
+
+ Constructing the real model is not on its own a check on field names: it sets
+ ``extra="allow"``, so a misspelling is accepted as an extra field rather than rejected.
+ ``test_usage_fields_exist_on_the_sdk_model`` is what pins the names to the declared
+ schema. Only the session wrapper is a stand-in, since ``get_session_usage`` reads
+ nothing from it but ``.usage``.
+ """
+
+ def test_usage_fields_exist_on_the_sdk_model(self):
+ # The reported breakdown must be fields the SDK actually declares. active_seconds
+ # lived on session.stats rather than session.usage as recently as 0.117.0, and the
+ # floor is an open-ended >= on a beta API -- if a field moves again, summarize_usage
+ # would return it as None (or raise, swallowed into a warning) with no other signal.
+ assert set(BetaManagedAgentsSessionUsage.model_fields) >= {
+ "input_tokens",
+ "output_tokens",
+ "cache_read_input_tokens",
+ "cache_creation",
+ "server_tool_use",
+ "active_seconds",
+ "list_cost",
+ }
+
+ @staticmethod
+ def _session(list_cost, cache_creation=None, server_tool_use=None):
Review Comment:
```suggestion
def _create_session(list_cost, cache_creation=None, server_tool_use=None):
```
##########
providers/anthropic/src/airflow/providers/anthropic/operators/agent.py:
##########
@@ -178,7 +183,11 @@ def execute(self, context: Context) -> str | None:
)
except Exception:
# send_event failed after create_session allocated the container; tear it down.
- self._archive_session(session.id)
+ # The event may still have been accepted server-side, so the agent can already be
+ # spending -- record usage here too rather than leaving this the one failure path
+ # with no cost trail.
+ archived = self._archive_session(session.id)
+ self._push_usage(context, session.id, session=archived)
Review Comment:
should we make this a method? it appears a few times already.
##########
providers/anthropic/tests/unit/anthropic/operators/test_agent.py:
##########
@@ -98,7 +100,7 @@ def test_message_sends_user_message_and_waits(self, mock_hook_prop):
"sess_1", {"type": "user.message", "content": [{"type": "text", "text": "summarize"}]}
)
hook.wait_for_session.assert_called_once()
- context["ti"].xcom_push.assert_called_once_with(key="session_id", value="sess_1")
+ context["ti"].xcom_push.assert_any_call(key="session_id", value="sess_1")
Review Comment:
why do we make this change
##########
providers/anthropic/tests/unit/anthropic/operators/test_agent.py:
##########
@@ -34,8 +34,10 @@
pytest.importorskip("anthropic")
-def _context():
- return {"ti": mock.MagicMock()}
+def _context(try_number=1):
Review Comment:
```suggestion
def _create_context(try_number=1):
```
##########
providers/anthropic/tests/unit/anthropic/operators/test_agent.py:
##########
@@ -260,10 +262,143 @@ def test_budget_is_templated(self):
assert "budget" in AnthropicAgentSessionOperator.template_fields
+class TestUsageXCom:
+ USAGE = {
+ "input_tokens": 827,
+ "output_tokens": 17065,
+ "cache_read_input_tokens": 0,
+ "active_seconds": 91.2,
+ "list_cost": {"amount": "44", "currency": "USD"},
+ }
+
+ @staticmethod
+ def _op(**kwargs):
Review Comment:
```suggestion
def _create_op(**kwargs) -> AnthropicAgentSessionOperator:
```
##########
providers/anthropic/tests/unit/anthropic/hooks/test_anthropic.py:
##########
@@ -308,6 +315,94 @@ def test_drops_a_none_budget(self):
assert "budget" not in client.beta.sessions.create.call_args.kwargs
+class TestGetSessionUsage:
+ """
+ Built on the real SDK usage models rather than mocks.
+
+ Constructing the real model is not on its own a check on field names: it sets
+ ``extra="allow"``, so a misspelling is accepted as an extra field rather than rejected.
+ ``test_usage_fields_exist_on_the_sdk_model`` is what pins the names to the declared
+ schema. Only the session wrapper is a stand-in, since ``get_session_usage`` reads
+ nothing from it but ``.usage``.
+ """
+
+ def test_usage_fields_exist_on_the_sdk_model(self):
+ # The reported breakdown must be fields the SDK actually declares. active_seconds
+ # lived on session.stats rather than session.usage as recently as 0.117.0, and the
+ # floor is an open-ended >= on a beta API -- if a field moves again, summarize_usage
+ # would return it as None (or raise, swallowed into a warning) with no other signal.
+ assert set(BetaManagedAgentsSessionUsage.model_fields) >= {
+ "input_tokens",
+ "output_tokens",
+ "cache_read_input_tokens",
+ "cache_creation",
+ "server_tool_use",
+ "active_seconds",
+ "list_cost",
+ }
+
+ @staticmethod
+ def _session(list_cost, cache_creation=None, server_tool_use=None):
+ usage = BetaManagedAgentsSessionUsage(
+ input_tokens=827,
+ output_tokens=17065,
+ cache_read_input_tokens=0,
+ active_seconds=91.2,
+ list_cost=list_cost,
+ cache_creation=cache_creation,
+ server_tool_use=server_tool_use,
+ )
+ return SimpleNamespace(usage=usage)
+
+ def test_flattens_to_json_safe_scalars(self):
+ hook, client = _make_hook()
+ client.beta.sessions.retrieve.return_value = self._session(
+ BetaMonetaryAmount(amount="44", currency="USD")
+ )
+ assert hook.get_session_usage("s") == {
+ "input_tokens": 827,
+ "output_tokens": 17065,
+ "cache_read_input_tokens": 0,
+ "cache_creation": None,
+ "server_tool_use": None,
+ "active_seconds": 91.2,
+ "list_cost": {"amount": "44", "currency": "USD"},
+ }
+
+ def test_reports_every_billable_dimension(self):
+ # list_cost is None exactly when a caller must price the run from usage, so the
+ # expensive side (cache writes, server tool calls) cannot be missing.
+ hook, client = _make_hook()
+ client.beta.sessions.retrieve.return_value = self._session(
+ None,
+ cache_creation=BetaManagedAgentsCacheCreationUsage(
+ ephemeral_5m_input_tokens=120, ephemeral_1h_input_tokens=340
+ ),
+ server_tool_use=BetaManagedAgentsServerToolUsage(web_search_requests=3, web_fetch_requests=5),
+ )
+ usage = hook.get_session_usage("s")
Review Comment:
should we just assert the whole usage dict insetad?
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Record Anthropic agent session token usage and cost in XCom [airflow]
Posted by "kaxil (via GitHub)" <gi...@apache.org>.
kaxil commented on code in PR #71463:
URL: https://github.com/apache/airflow/pull/71463#discussion_r3766976194
##########
providers/anthropic/tests/unit/anthropic/operators/test_agent.py:
##########
@@ -260,10 +262,143 @@ def test_budget_is_templated(self):
assert "budget" in AnthropicAgentSessionOperator.template_fields
+class TestUsageXCom:
+ USAGE = {
+ "input_tokens": 827,
+ "output_tokens": 17065,
+ "cache_read_input_tokens": 0,
+ "active_seconds": 91.2,
+ "list_cost": {"amount": "44", "currency": "USD"},
+ }
+
+ @staticmethod
+ def _op(**kwargs):
Review Comment:
Taken, but one step further, because the duplication turned out to be the real problem.
`TestBudgetParam` and `TestUsageXCom` each had a byte-identical builder -- one named `_make_op` (from your suggestion on #71462) and this one named `_op`. Renaming this one would have left two copies of the same function in the same file under two different prefixes.
So it is now a single module-level `_create_op(**kwargs) -> AnthropicAgentSessionOperator` with the signature you suggested, and both classes use it. That also settles the prefix: `_create_` matches `_create_session`, `_create_context` and `_create_session_error` from your other comments, so the file has one convention rather than two.
Flagging it because it means #71462 changed too -- the helper is defined there now.
##########
providers/anthropic/src/airflow/providers/anthropic/operators/agent.py:
##########
@@ -178,7 +183,11 @@ def execute(self, context: Context) -> str | None:
)
except Exception:
# send_event failed after create_session allocated the container; tear it down.
- self._archive_session(session.id)
+ # The event may still have been accepted server-side, so the agent can already be
+ # spending -- record usage here too rather than leaving this the one failure path
+ # with no cost trail.
+ archived = self._archive_session(session.id)
+ self._push_usage(context, session.id, session=archived)
Review Comment:
Good catch -- it was four sites, not a few. Extracted `_tear_down(context, session_id)`, which archives and then records usage; all four failure paths call it.
Keeping the order inside the helper is the point: teardown runs first because it is the time-critical call on a failing task, and `sessions.archive` returns the session carrying its final usage, so recording spend costs no extra request. Having that in one place means the ordering cannot drift between paths.
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Record Anthropic agent session token usage and cost in XCom [airflow]
Posted by "kaxil (via GitHub)" <gi...@apache.org>.
kaxil commented on code in PR #71463:
URL: https://github.com/apache/airflow/pull/71463#discussion_r3766980591
##########
providers/anthropic/tests/unit/anthropic/operators/test_agent.py:
##########
@@ -98,7 +100,7 @@ def test_message_sends_user_message_and_waits(self, mock_hook_prop):
"sess_1", {"type": "user.message", "content": [{"type": "text", "text": "summarize"}]}
)
hook.wait_for_session.assert_called_once()
- context["ti"].xcom_push.assert_called_once_with(key="session_id", value="sess_1")
+ context["ti"].xcom_push.assert_any_call(key="session_id", value="sess_1")
Review Comment:
Because this PR adds a second `xcom_push`. The task pushed only `session_id` before; it now pushes `usage` as well, so `assert_called_once_with` fails outright.
Swapping to `assert_any_call` was the minimum fix but it quietly weakened the test -- it would pass no matter how many other pushes happened. Replaced with an assertion on the pushed keys in order:
```python
assert [c.kwargs["key"] for c in context["ti"].xcom_push.call_args_list] == [
"session_id",
"usage",
]
```
That pins exactly two pushes and their order, so it is stricter than what was there before this PR rather than looser. Thanks for pushing on it -- I had accepted the weaker assertion without noticing what it stopped checking.
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org