You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@airflow.apache.org by "ashb (via GitHub)" <gi...@apache.org> on 2026/10/15 15:42:02 UTC
[PR] Allow loop gates to add human-readable decisions [airflow]
ashb opened a new pull request, #74806:
URL: https://github.com/apache/airflow/pull/74806
As it landed on main, a loop's gate only recorded a go/no-go decision for
the next iteration, meaning the UI could show that a loop stopped after N
iterations, but a user would have to go to the logs to find out why,
exactly, the loop ended when it did.
This adds a `LoopDecision` object that lets an `until` callable include
human-readable text to show alongside its decision.
As well as introducing this new type, it also changes how the decision
makes it to the server. Prior to this change, the decision was shipped to
the API server via a specially named XCom value, in a normal SetXCom
request, which was then read when the gate's TISuccessState request
arrived. That "worked", but was inherently fragile: a separate write
with its own locking, validation and cleanup on every non-success path.
The decision now travels on the gate's terminal state update. The server
acts on it in the transaction that marks the gate finished, so the
stop/continue signal never needs storing. A gate that fails because until
stayed false at max_iterations sends its reason with the failure, which is
when an explanation helps most.
Only the reason is persisted, as an XCom on the gate's attempt that the
server writes in that same transaction. Keying it to the attempt means
each try keeps its own reason, and a cleared or retried gate starts with
none, so no clear path has to remember to delete a stale one. Task state
was considered instead, but it is keyed by the iteration rather than the
attempt, so a reason outlived the clears and tries it described, and
clear_on_success and retention could remove it. The server writes the
XCom directly to the metadata DB (not to a configured backend, so the UI
can always show it), and the reserved `_airflow_loop_` prefix stops users
and tasks forging it. The XCom list endpoint leaves those keys out when
asked, which the UI does.
<!-- 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] Allow loop gates to add human-readable decisions [airflow]
Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #74806:
URL: https://github.com/apache/airflow/pull/74806#issuecomment-6214471966
### Backport failed to create: v3-4-test. View the failure log <a href='https://github.com/apache/airflow/actions/runs/38893651203'> Run details </a>
Note: As of [Merging PRs targeted for Airflow 3.X](https://github.com/apache/airflow/blob/main/dev/README_AIRFLOW3_DEV.md#merging-prs-targeted-for-airflow-3x)
the committer who merges the PR is responsible for backporting the PRs that are bug fixes (generally speaking) to the maintenance branches.
In matter of doubt please ask in [#release-management](https://apache-airflow.slack.com/archives/C03G9H97MM2) Slack channel.
<table>
<tr>
<th>Status</th>
<th>Branch</th>
<th>Result</th>
</tr>
<tr>
<td>❌</td>
<td>v3-4-test</td>
<td><a href="https://github.com/apache/airflow/commit/4c4bab01e0635933fde25f8be14613112d1e2b05"><img src='https://img.shields.io/badge/Commit-4c4bab0-red' alt='Commit Link'></a></td>
</tr>
</table>
You can attempt to backport this manually by running:
```bash
cherry_picker 4c4bab0 v3-4-test
```
This should apply the commit to the v3-4-test branch and leave the commit in conflict state marking
the files that need manual conflict resolution.
After you have resolved the conflicts, you can continue the backport process by running:
```bash
cherry_picker --continue
```
If you don't have cherry-picker installed, see the [installation guide](https://github.com/apache/airflow/blob/main/dev/README.md#how-to-backport-pr-with-cherry-picker-cli).
--
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] Allow loop gates to add human-readable decisions [airflow]
Posted by "kaxil (via GitHub)" <gi...@apache.org>.
kaxil commented on code in PR #74806:
URL: https://github.com/apache/airflow/pull/74806#discussion_r4289941598
##########
airflow-core/docs/authoring-and-scheduling/loops.rst:
##########
@@ -330,8 +351,9 @@ In the Grid, select the loop's task group in a Dag run to open its Task Instance
tab. The **Iteration** filter narrows the table to one iteration, or shows
**All iterations**, and the **Iteration** column shows which iteration each task
instance belongs to. The gate's state and logs explain why the loop continued,
-stopped, or failed. Each task's tries and logs remain accessible within its
-iteration.
+stopped, or failed. When ``until`` returned a ``LoopDecision`` with a reason, the
+Iteration filter shows that reason next to the iteration. Each task's tries and
Review Comment:
I don't think the Iteration filter shows the reason. `LoopOptionLabel` isn't touched here, and the only places that read `decision_reason` are the Outcome stat on the loop's group page (final iteration, once the loop is done) and the "Decision" stat in a task instance header. Should this sentence point at those instead?
##########
task-sdk/src/airflow/sdk/execution_time/loop.py:
##########
@@ -76,29 +78,50 @@ def _result(self, *, previous_iteration: bool) -> Any:
def execute_loop_gate(gate: LoopGateOperator, context: Context) -> None:
- # task_runner imports LoopContextAccessor from this module.
- from airflow.sdk.execution_time.task_runner import SUPERVISOR_COMMS
-
loop = context["loop"]
+ ti = cast("RuntimeTaskInstance", context["ti"])
+ reason: str | None = None
if gate.until is None:
stop = loop.index + 1 >= loop.max_iterations
else:
- stop = gate.until(**determine_kwargs(gate.until, (), context))
- if not isinstance(stop, bool):
- raise AirflowFailException(f"until must return a bool, got {type(stop).__name__}")
- if not stop and loop.index + 1 >= loop.max_iterations:
- raise LoopMaxIterationsExceeded(
- f"Loop condition remained false at max_iterations={loop.max_iterations}"
+ match result := gate.until(**determine_kwargs(gate.until, (), context)):
+ case bool():
+ stop = result
+ case LoopDecision(stop=bool(), reason=None | str()):
+ stop, reason = result.stop, result.reason or None
+ case LoopDecision(stop=bool()):
+ raise AirflowFailException(
+ f"LoopDecision reason must be a str or None, got {type(result.reason).__name__}"
+ )
+ case LoopDecision():
+ raise AirflowFailException(
+ f"LoopDecision stop must be a bool, got {type(result.stop).__name__}"
+ )
+ case _:
+ raise AirflowFailException(
+ f"until must return a bool or LoopDecision, got {type(result).__name__}"
+ )
+ if reason is not None:
+ # Mask here, where mask_secret() registered the value: the API server showing it later does not.
+ reason = cast("str", redact(reason))
+ try:
+ size = len(reason.encode())
Review Comment:
A NUL character in the reason passes this check and `LoopDecisionPayload._check_reason_size`, but Postgres JSONB rejects `\u0000` when the server writes the XCom. Since that write now runs in the same transaction as the gate's state update, the gate's terminal state update fails with it, not just the reason. Could we reject NUL here next to the size check, and in the server validator too?
##########
airflow-core/pyproject.toml:
##########
@@ -135,7 +135,8 @@ dependencies = [
'pendulum>=3.1.0',
"pluggy>=1.5.0",
"psutil>=5.8.0",
- "pydantic>=2.11.0",
+ # 2.12 adds Field(exclude_if=...), which API responses use to omit absent optional fields
+ "pydantic>=2.12.0",
Review Comment:
Is omitting `decision_reason` worth raising the core pydantic floor? `exclude_if` has one user (`LoopIterationSummary.decision_reason`), the sibling fields on that model serialize `null`, and `OmitsMissingRegion` in `api_fastapi/common/region.py` already omits fields with a `model_serializer` under the current floor. If we keep the bump, the comment's "API responses use" overstates it a bit for now.
##########
airflow-core/src/airflow/example_dags/example_task_loops.py:
##########
@@ -38,7 +38,8 @@ def evaluate(estimate):
evaluate(improve())
def accurate_enough(*, loop):
- return loop.result["error"] < 0.000001
+ error = loop.result["error"]
+ return LoopDecision(stop=error < 0.000001, reason=f"error {error:.2g}, needs < 1e-06")
Review Comment:
Nit: this gets pulled into the docs via `exampleinclude`, so people will copy it. A `threshold = 1e-6` used in both the comparison and the message (`needs < {threshold:g}`) keeps the two from drifting.
--
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] Allow loop gates to add human-readable decisions [airflow]
Posted by "bbovenzi (via GitHub)" <gi...@apache.org>.
bbovenzi commented on code in PR #74806:
URL: https://github.com/apache/airflow/pull/74806#discussion_r4286307529
##########
airflow-core/src/airflow/ui/src/pages/GroupTaskInstance/useLoopOutcomeStats.tsx:
##########
@@ -42,13 +42,23 @@ export const useLoopOutcomeStats = ({
return [];
}
+ // A running loop's newest pass has not decided yet, so an older pass's reason would misdescribe it.
+ const finalReason = summary.status === "running" ? undefined : summary.iterations.at(-1)?.decision_reason;
+
return [
{
label: translate("loop.outcome"),
value: (
- <Text color={summary.status === "failed" ? "fg.error" : undefined}>
- {reasonSentence(translate, summary)}
- </Text>
+ <>
+ <Text color={summary.status === "failed" ? "fg.error" : undefined}>
+ {reasonSentence(translate, summary)}
+ </Text>
+ {finalReason === undefined ? undefined : (
+ <Text color="fg.muted" maxWidth="md" overflowWrap="anywhere" whiteSpace="pre-line">
+ {finalReason}
Review Comment:
We probably just want to limit this to one line and then have the full reason in a tooltip.
--
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] Allow loop gates to add human-readable decisions [airflow]
Posted by "ashb (via GitHub)" <gi...@apache.org>.
ashb commented on code in PR #74806:
URL: https://github.com/apache/airflow/pull/74806#discussion_r4292202639
##########
airflow-core/docs/authoring-and-scheduling/loops.rst:
##########
@@ -330,8 +351,9 @@ In the Grid, select the loop's task group in a Dag run to open its Task Instance
tab. The **Iteration** filter narrows the table to one iteration, or shows
**All iterations**, and the **Iteration** column shows which iteration each task
instance belongs to. The gate's state and logs explain why the loop continued,
-stopped, or failed. Each task's tries and logs remain accessible within its
-iteration.
+stopped, or failed. When ``until`` returned a ``LoopDecision`` with a reason, the
+Iteration filter shows that reason next to the iteration. Each task's tries and
Review Comment:
Yeah, I couldn't make it work (I was trying to, but it didn't fit the space). Will remove.
--
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] Allow loop gates to add human-readable decisions [airflow]
Posted by "ashb (via GitHub)" <gi...@apache.org>.
ashb commented on code in PR #74806:
URL: https://github.com/apache/airflow/pull/74806#discussion_r4287320353
##########
airflow-core/src/airflow/ui/src/pages/GroupTaskInstance/useLoopOutcomeStats.tsx:
##########
@@ -42,13 +42,23 @@ export const useLoopOutcomeStats = ({
return [];
}
+ // A running loop's newest pass has not decided yet, so an older pass's reason would misdescribe it.
+ const finalReason = summary.status === "running" ? undefined : summary.iterations.at(-1)?.decision_reason;
+
return [
{
label: translate("loop.outcome"),
value: (
- <Text color={summary.status === "failed" ? "fg.error" : undefined}>
- {reasonSentence(translate, summary)}
- </Text>
+ <>
+ <Text color={summary.status === "failed" ? "fg.error" : undefined}>
+ {reasonSentence(translate, summary)}
+ </Text>
+ {finalReason === undefined ? undefined : (
+ <Text color="fg.muted" maxWidth="md" overflowWrap="anywhere" whiteSpace="pre-line">
+ {finalReason}
Review Comment:
<img width="1262" height="759" alt="compare-1-loop-page" src="https://github.com/user-attachments/assets/0ff515e6-f015-471e-8563-868d589c2e03" />
WDYT of this @bbovenzi ?
--
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] Allow loop gates to add human-readable decisions [airflow]
Posted by "kaxil (via GitHub)" <gi...@apache.org>.
kaxil merged PR #74806:
URL: https://github.com/apache/airflow/pull/74806
--
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] Allow loop gates to add human-readable decisions [airflow]
Posted by "bbovenzi (via GitHub)" <gi...@apache.org>.
bbovenzi commented on PR #74806:
URL: https://github.com/apache/airflow/pull/74806#issuecomment-6197934865
UX makes sense to me. We may surface this in more places later. Let'e see
--
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] Allow loop gates to add human-readable decisions [airflow]
Posted by "ashb (via GitHub)" <gi...@apache.org>.
ashb commented on code in PR #74806:
URL: https://github.com/apache/airflow/pull/74806#discussion_r4292125795
##########
airflow-core/pyproject.toml:
##########
@@ -135,7 +135,8 @@ dependencies = [
'pendulum>=3.1.0',
"pluggy>=1.5.0",
"psutil>=5.8.0",
- "pydantic>=2.11.0",
+ # 2.12 adds Field(exclude_if=...), which API responses use to omit absent optional fields
+ "pydantic>=2.12.0",
Review Comment:
Actually I wont. OmitsRegion can't use exclude_if is it looks at/affects two fields (region_id and region_index), so isn't convertible.
Still, I think it is reasonable to update the min version here. LMK if you disagree
--
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] Allow loop gates to add human-readable decisions [airflow]
Posted by "ashb (via GitHub)" <gi...@apache.org>.
ashb commented on code in PR #74806:
URL: https://github.com/apache/airflow/pull/74806#discussion_r4292019802
##########
airflow-core/pyproject.toml:
##########
@@ -135,7 +135,8 @@ dependencies = [
'pendulum>=3.1.0',
"pluggy>=1.5.0",
"psutil>=5.8.0",
- "pydantic>=2.11.0",
+ # 2.12 adds Field(exclude_if=...), which API responses use to omit absent optional fields
+ "pydantic>=2.12.0",
Review Comment:
I'll pull this out in to its own pr though
--
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] Allow loop gates to add human-readable decisions [airflow]
Posted by "ashb (via GitHub)" <gi...@apache.org>.
ashb commented on code in PR #74806:
URL: https://github.com/apache/airflow/pull/74806#discussion_r4292004912
##########
airflow-core/pyproject.toml:
##########
@@ -135,7 +135,8 @@ dependencies = [
'pendulum>=3.1.0',
"pluggy>=1.5.0",
"psutil>=5.8.0",
- "pydantic>=2.11.0",
+ # 2.12 adds Field(exclude_if=...), which API responses use to omit absent optional fields
+ "pydantic>=2.12.0",
Review Comment:
2.12 is over 1 year old at this point, so yes, it's worth it
--
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] Allow loop gates to add human-readable decisions [airflow]
Posted by "kaxil (via GitHub)" <gi...@apache.org>.
kaxil commented on code in PR #74806:
URL: https://github.com/apache/airflow/pull/74806#discussion_r4294140487
##########
airflow-core/pyproject.toml:
##########
@@ -135,7 +135,8 @@ dependencies = [
'pendulum>=3.1.0',
"pluggy>=1.5.0",
"psutil>=5.8.0",
- "pydantic>=2.11.0",
+ # 2.12 adds Field(exclude_if=...), which API responses use to omit absent optional fields
+ "pydantic>=2.12.0",
Review Comment:
Naah, that's fine
--
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