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

jason810496 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 e52bd980ff9 Check task loops of language SDKs in the Dag processor 
(#76803)
e52bd980ff9 is described below

commit e52bd980ff973abcbb66a38e934e7641d2bda60a
Author: Jason(Zhe-You) Liu <[email protected]>
AuthorDate: Fri Nov 20 21:43:55 2026 +0700

    Check task loops of language SDKs in the Dag processor (#76803)
    
    * Check task loops of language SDKs in the Dag processor
    
    A language SDK's Dag never passes through Python's authoring checks, so the
    Dag processor now applies them to it, giving every language the same errors
    and the same graph. A gate's reason is masked in the supervisor, which holds
    every value a task registered for masking, whatever language the task runs 
in.
    
    Core keeps finding a gate by its LoopGateOperator name and keeps sending a
    fixed-count gate to a worker, so a language SDK's loop runs without changing
    the Python path. ADR-0017 and the SDK loop ADRs are amended to match.
    
    * Mask a gate's reason before cutting it to the byte limit
    
    A secret crossing byte 512 was cut first and left a fragment the masker
    could not match. The supervisor now masks the whole reason, then cuts it.
    
    * Mask a gate's reason in the error raised at max_iterations
    
    The error reaches failure callbacks and emails, which do not mask, so the
    gate masks the reason it puts in the message. Also test that a mapped task
    group cannot expand over a loop task from outside the loop.
    
    * Share the loop group walk and note the gate task type in ADR-0003
---
 .../lang-sdk/0017-task-loops-across-lang-sdks.md   |  75 ++--
 .../airflow/dag_processing/lang_sdk_processor.py   |   2 +
 .../src/airflow/dag_processing/loop_checks.py      | 174 ++++++++++
 .../src/airflow/models/task_coordinates.py         |  11 +-
 .../unit/dag_processing/test_lang_sdk_processor.py |  15 +
 .../tests/unit/dag_processing/test_loop_checks.py  | 379 +++++++++++++++++++++
 go-sdk/adr/0009-task-loop-authoring-interface.md   |   4 +-
 java-sdk/adr/0003-task-loop-authoring-interface.md |   5 +-
 .../src/airflow/sdk/definitions/_internal/loop.py  |   2 +
 .../src/airflow/sdk/execution_time/supervisor.py   |  38 ++-
 .../task_sdk/execution_time/test_supervisor.py     |  75 ++++
 ts-sdk/adr/0003-task-loop-authoring-interface.md   |   6 +-
 12 files changed, 737 insertions(+), 49 deletions(-)

diff --git a/airflow-core/adr/lang-sdk/0017-task-loops-across-lang-sdks.md 
b/airflow-core/adr/lang-sdk/0017-task-loops-across-lang-sdks.md
index 18f9af5e1c2..c83d71b748c 100644
--- a/airflow-core/adr/lang-sdk/0017-task-loops-across-lang-sdks.md
+++ b/airflow-core/adr/lang-sdk/0017-task-loops-across-lang-sdks.md
@@ -38,15 +38,16 @@ Proposed.
 ## Decision
 
 1. **Iteration creation stays in core for every language.** Regions, instance 
creation, rerun trajectories and the scope of every XCom read are core's. An 
SDK emits a loop group and runs one callable; it never creates an instance and 
never decides which iteration a read belongs to.
-2. **A loop is a task group with four more serialized fields** — 
`max_iterations`, `has_until`, `terminal_task_id` and `gate_task_id`. The gate 
is found by `gate_task_id` and never by an operator class name, which 
[ADR-0007](0007-taskflow-across-language-boundary.md) decision B already 
rejected: a gate emitted by another SDK cannot honestly claim 
`LoopGateOperator`.
-3. **Loop validation and normalization belong to the Dag processor**, so every 
language gets the same errors: one terminal task, no nested loop, no loop 
inside a mapped task group, no `expand` over a body task from outside, and 
every body-to-outside edge rewired to leave from the gate. An SDK may repeat 
any check for earlier feedback; core's answer is the one that counts.
-4. **A fixed-count loop runs no user code.** With `has_until: false` the 
scheduler completes the gate itself, so counting needs no worker in any 
language. A gate carrying a callback, an inlet or an outlet still goes to a 
worker, by the rule `TaskInstance.is_task_schedulable` already applies to 
`EmptyOperator`. Only a Python Dag reaches that case, since no SDK emits task 
callbacks.
+2. **A loop is a task group with four more serialized fields**: 
`max_iterations`, `has_until`, `terminal_task_id` and `gate_task_id`. Core 
finds the gate by its task type, `LoopGateOperator`, as it finds Python's, so 
every SDK serializes its gate with `task_type: "LoopGateOperator"` and core's 
gate handling stays as it is. This is the one exception to 
[ADR-0007](0007-taskflow-across-language-boundary.md) decision B: the name says 
what core does with the task, not which class runs it.
+3. **Loop validation and normalization belong to the Dag processor**, so every 
language gets the same errors. It refuses a loop without exactly one terminal 
task, a nested loop, a loop inside a mapped task group, an `expand` over a body 
task from outside, a Dag result inside a loop, a `gate_task_id` that is not a 
task of the loop, and a `LoopGateOperator` task that is no loop's gate. A gate 
is refused as well when it is not typed `LoopGateOperator`, is mapped, empty or 
started from a tri [...]
+4. **A fixed-count loop's gate runs on a worker**, as Python's does. With 
`has_until: false` the SDK runs no callable and sends `stop` as `index >= 
max_iterations`, so the scheduler keeps no loop logic of its own.
 5. **The decision travels on `SucceedTask.loop_decision`**, which the 
supervisor schema already carries. An SDK sends `{stop, reason}`; core 
revalidates it and fails the gate when `stop` is false at `max_iterations`.
 6. **The loop context arrives on `TIRunContext.loop`** — `index`, 
`max_iterations`, `terminal_task_id`, `terminal_is_mapped` and the region 
fields. No SDK counts iterations or resolves a trajectory.
 7. **Loops add no XCom call of their own.** Reading the previous iteration is 
the existing call with `previous_iteration: true`; reading every iteration is 
ADR-0016 decision 8's lazy sequence, ordered iteration first, then map index.
-8. **The reason is masked in the supervisor**, once for every language. Python 
redacts it in the task
-   process today, but the supervisor already holds whatever a task added 
through `MaskSecret`, so
-   moving the redaction there leaves each SDK one existing call rather than a 
masker of its own.
+8. **The reason is masked in the supervisor**, for every language. The 
supervisor already holds
+   whatever a task added through `MaskSecret`, so an SDK needs one existing 
call and no masker of its
+   own. Python also masks the reason in the task process, so its callbacks and 
listeners see the
+   masked text.
 
 ## Context
 
@@ -66,10 +67,10 @@ SDK's own, and is recorded in that SDK's own ADR directory.
 | Process | Language | Its share of a loop |
 |---|---|---|
 | Dag processor | Python | Validates the loop and rewires the edges out of the 
body. |
-| Scheduler | Python | Creates iteration 1, and completes a fixed-count gate 
with no worker. |
+| Scheduler | Python | Creates iteration 1. |
 | API server, Execution API | Python | Sends `TIRunContext.loop`; on the 
gate's success, validates the decision and creates the next iteration in the 
same transaction. |
-| Supervisor | Python, in the worker process | Masks the reason; forwards 
every XCom request with the caller's iteration already pinned by its token. |
-| SDK runtime | the SDK's own language | Runs the body handlers and the 
`until` callable, and returns the decision. |
+| Supervisor | Python, in the worker process | Masks the reason and cuts it to 
the byte limit; forwards every XCom request with the caller's iteration already 
pinned by its token. |
+| SDK runtime | the SDK's own language | Runs the body handlers and the gate, 
and returns the decision: `until`'s, or `index >= max_iterations` for a 
fixed-count loop. |
 
 ## Authoring interface
 
@@ -102,7 +103,7 @@ declares, so it is injected. Each follows its own SDK, and 
none invents a rule f
 ## What an SDK emits
 
 A loop group is an ordinary serialized task group with one more key. The gate 
is an ordinary task
-of that group.
+of that group, serialized with `task_type: "LoopGateOperator"` (decision 2).
 
 ```jsonc
 "refine": {
@@ -121,7 +122,7 @@ of that group.
 }
 ```
 
-`has_until` is the only thing that says whether a worker runs the gate. The 
callable itself is never
+`has_until` says whether the gate runs `until` or only counts. The callable 
itself is never
 serialized: the gate re-enters the SDK's own bundle to find it, the way a 
`map()` callable is found
 by ADR-0016 decision 6.
 
@@ -133,21 +134,21 @@ mirrors it. An SDK implements this ADR against the 
protocol as it stands.
 | Where | What | Means |
 |---|---|---|
 | `TIRunContext.loop` | `node_id`, `index`, `max_iterations`, 
`terminal_task_id`, `terminal_is_mapped`, `region_id`, `trajectory`, 
`forked_from_region_id`, `resumes_from_index` | The iteration this task runs 
in. Absent when the task is not in a loop. |
-| `SucceedTask.loop_decision`, `TaskState.loop_decision` | 
`LoopDecisionPayload {stop, reason}` | What the gate decided. `reason` is at 
most 512 bytes of UTF-8 and holds no NUL; the payload model rejects the rest. |
+| `SucceedTask.loop_decision`, `TaskState.loop_decision` | 
`LoopDecisionPayload {stop, reason}` | What the gate decided. `reason` is at 
most 512 bytes of UTF-8 and holds no NUL. The supervisor masks the reason, then 
cuts a longer one and warns in the task log, so an SDK does not have to enforce 
the limit; the payload model rejects a NUL. A Python gate masks the reason and 
checks the limit itself, and fails the task on a longer one. |
 | `GetXCom`, `GetXComCount`, `GetXComSequenceItem`, `GetXComSequenceSlice` | 
`previous_iteration: bool` | Reads the iteration before this one instead of 
this one. |
 | `MaskSecret` | `value`, `name` | Already how a task process tells the 
supervisor what to redact. |
 | Serialized Dag, `task_group.loop` | `max_iterations`, `has_until`, 
`terminal_task_id`, `gate_task_id` | Declared in `serialization/schema.json`, 
so an SDK's Dag validates with no schema change. |
+| Serialized Dag, the gate task | `task_type: "LoopGateOperator"` | How core 
finds the gate, as it finds Python's. |
 
 ### What changes
 
-No field is added or removed, so **no new Execution API version is needed**. 
The decisions above are
-core-internal, and two of them subtract from the wire rather than add to it.
+No field is added or removed, so **no new Execution API version is needed**. 
Decision 3 changes core,
+decision 8 changes the Task SDK supervisor, and the rest need no change.
 
 | Decision | Change |
 |---|---|
-| 2 | Gate identification stops reading `task_instance.operator == 
"LoopGateOperator"` and resolves `gate_task_id` off the serialized group 
instead. Five modules: the two task-instance route modules, 
`jobs/scheduler_job_runner.py`, `serialization/definitions/dag.py` and 
`models/taskinstance.py`. |
-| 4 | A gate with `has_until: false` and no callback, inlet or outlet 
completes in the scheduler, so it sends no `ti_run` and no `SucceedTask` at 
all. |
-| 8 | `redact(reason)` moves out of the task process 
(`execution_time/loop.py`) into the supervisor, beside the redaction it already 
does for logs. |
+| 3 | The Dag processor runs the loop checks and rewires the edges out of the 
body for a Dag a language SDK serialized. A Python Dag is already checked and 
rewired by the Task SDK. |
+| 8 | The supervisor masks the reason and cuts it to the byte limit, beside 
the redaction it already does for logs. Python's task process keeps masking it 
(`execution_time/loop.py`). |
 
 ## One loop, end to end
 
@@ -173,7 +174,7 @@ Three iterations of `refine` — `improve` and `evaluate` in 
the body, `accurate
     │
     └─ gate (L,1) ────────▶ binding: the terminal result of (L,1)
                             until(result) → { stop: false, reason }
-                            supervisor redacts reason
+                            supervisor masks and cuts reason
                             SucceedTask{loop_decision} ──────────▶ lock DagRun 
+ gate
                                                                    
validate_loop_decision
                                                                    store the 
reason XCom
@@ -203,8 +204,8 @@ Three things the picture fixes:
   decision 3 rewired that edge at parse time.
 - **The next iteration is created by the API server**, inside the transaction 
that accepts the
   decision, not by the SDK and not by a second call.
-- **A fixed-count loop skips the whole middle column.** With `has_until: 
false` the scheduler
-  completes each gate itself (decision 4), so no worker is involved in 
deciding anything.
+- **A fixed-count loop runs the same columns.** Its gate binds nothing and 
runs no callable; it sends
+  `stop` once `index` reaches `max_iterations` (decision 4).
 
 ## What an SDK runtime does
 
@@ -215,20 +216,23 @@ Nothing here is language-specific.
    `previous` is the existing XCom call with `previous_iteration: true`, and 
is absent at `index` 1.
    It is one accessor, not two: a mapped terminal makes it ADR-0016's sequence 
rather than a plain
    value, which is what Python's single `loop.previous` property does.
-3. On the gate, read this iteration's terminal result — one value, or 
ADR-0016's sequence when
-   `terminal_is_mapped` is true — and run `until`.
+3. On the gate, read this iteration's terminal result (one value, or 
ADR-0016's sequence when
+   `terminal_is_mapped` is true) and run `until`. A fixed-count gate reads 
nothing and decides
+   `stop` as `index >= max_iterations`.
 4. Send the result on `SucceedTask.loop_decision`. A `stop` of false at 
`max_iterations` is core's to
    reject, so the SDK sends what the callable returned. A secret the reason 
might carry is registered
-   with `MaskSecret` as it would be for a log line; the SDK does not redact.
+   with `MaskSecret` as it would be for a log line. The supervisor masks the 
reason (decision 8), so
+   the SDK does not have to redact it.
 5. A callable that throws fails the gate like any other task body, and the 
loop stops there.
 
 ## Consequences
 
 - **A loop costs an SDK one context object, one wire field and one callable.** 
Everything else is
   reuse: the group it is built on, the XCom calls, and the sequence ADR-0016 
already defines.
-- **A fixed-count loop is available before an SDK implements anything, once 
decision 4 lands.** It
-  leaves no code to run, so `has_until: false` then works as soon as the SDK 
can emit the group.
-  Until it lands, such a gate is still sent to a worker.
+- **A fixed-count loop still needs a runtime gate.** It is the smallest gate 
an SDK can run: no
+  binding and no callable, only `index >= max_iterations`.
+- **An SDK's gate carries a Python class name.** Decision 2 keeps core's gate 
handling, and so the
+  Python path, unchanged. The UI shows the gate as `LoopGateOperator` in every 
language.
 - **A gate's decision is advice, not authority.** Core revalidates, so a buggy 
or malicious SDK
   cannot run past `max_iterations`.
 - **Edges out of the body are rewired, not rejected.** Decision 3 keeps 
Python's behaviour, so a Dag
@@ -238,15 +242,10 @@ Nothing here is language-specific.
   where an author first sees it; the Task SDK's parse-time checks stay as the 
faster feedback.
 - **Mapping inside a loop needs no further decision.** The terminal task may 
be mapped, and
   `terminal_is_mapped` is the only thing a runtime reads to know it.
-- **No new Execution API version, but core goes first.** Every field a loop 
needs shipped with
-  `2026-10-30`, so nothing here waits on a protocol change. Decision 2 still 
has to land before any
-  SDK's loop runs at all: while a gate is found by `LoopGateOperator`, an 
SDK-emitted gate's success
-  creates no next iteration. Decision 4 has to land before a fixed-count loop 
skips the worker. The
-  rest are independent and can land in any order.
-- **A Python fixed-count gate stops behaving like a task.** Decision 4 
completes it in the scheduler,
-  so it takes no pool slot, ignores its `queue` and never retries. A gate with 
`until`, or one
-  carrying a callback, an inlet or an outlet, is unaffected.
-- **Python's reason is redacted one process later.** Decision 8 moves `redact` 
from the task process
-  to the supervisor, which is a behaviour change for Python tasks even though 
no field moves: a task
-  that masks a value and then puts it in a reason is covered by the 
`MaskSecret` it already sends, but
-  one that redacts by hand before returning is unaffected either way.
+- **No new Execution API version.** Every field a loop needs shipped with 
`2026-10-30`, and core
+  already drives a gate named `LoopGateOperator`. Decision 3 changes core and 
decision 8 changes the
+  supervisor. They are independent and can land in any order.
+- **A Python gate fails an over-long reason, and the supervisor cuts one from 
any other language.**
+  Python masks the reason, then fails the task when more than 512 bytes 
remain, so an author sees the
+  error at once. Another runtime does not need to know the limit: the 
supervisor masks the reason,
+  cuts it to 512 bytes and warns in the task log.
diff --git a/airflow-core/src/airflow/dag_processing/lang_sdk_processor.py 
b/airflow-core/src/airflow/dag_processing/lang_sdk_processor.py
index 9e753e61059..aafb8c7d41a 100644
--- a/airflow-core/src/airflow/dag_processing/lang_sdk_processor.py
+++ b/airflow-core/src/airflow/dag_processing/lang_sdk_processor.py
@@ -38,6 +38,7 @@ from airflow import settings
 from airflow.configuration import conf
 from airflow.dag_processing.dagbag import _get_bundle_team_name, 
_validate_executor_fields
 from airflow.dag_processing.importer_routing import get_claiming_importer
+from airflow.dag_processing.loop_checks import normalize_loops
 from airflow.dag_processing.processor import (
     BaseDagFileProcessorProcess,
     DagFileParseRequest,
@@ -431,6 +432,7 @@ class 
LangSDKDagFileProcessorProcess(BaseDagFileProcessorProcess):
             try:
                 deserialized = 
DagSerialization.validate_serialized_dag(dag.data)
                 self._apply_team_rules(dag.data, deserialized)
+                normalize_loops(dag.data, deserialized)
             except DeserializationError as e:
                 message = f"Cannot load the serialized Dag: {e}"
             except Exception as e:
diff --git a/airflow-core/src/airflow/dag_processing/loop_checks.py 
b/airflow-core/src/airflow/dag_processing/loop_checks.py
new file mode 100644
index 00000000000..f0af4c04777
--- /dev/null
+++ b/airflow-core/src/airflow/dag_processing/loop_checks.py
@@ -0,0 +1,174 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Check and normalize the task loops of a Dag a language SDK serialized.
+
+Python checks a loop where the author writes it. A language SDK may check too, 
but the Dag processor is
+what decides, so every language gets the same errors and the same graph.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Iterable
+from typing import TYPE_CHECKING, Any
+
+from airflow._shared.dagnode.cycle import detect_cycle
+from airflow.models.task_coordinates import LOOP_GATE_OPERATOR, 
enclosing_loop, enclosing_loop_of_group
+from airflow.serialization.definitions.mappedoperator import 
SerializedMappedOperator
+from airflow.serialization.definitions.taskgroup import 
SerializedLoopTaskGroup, SerializedMappedTaskGroup
+from airflow.serialization.enums import Encoding
+
+if TYPE_CHECKING:
+    from airflow.serialization.definitions.dag import SerializedDAG
+    from airflow.serialization.definitions.taskgroup import SerializedTaskGroup
+
+
+def normalize_loops(data: dict[str, Any], dag: SerializedDAG) -> None:
+    """
+    Raise ``ValueError`` for a loop core cannot run, and make each loop's gate 
its only way out.
+
+    A task serialized as a gate outside a loop is refused too, in a Dag with 
no loop as well.
+
+    *dag* is *data* deserialized. The edges are changed in *data*, which is 
what gets stored: the
+    terminal task is put before the gate, and an edge from a body task to a 
task outside the loop
+    leaves from the gate instead, as Python's ``create_loop`` does.
+    """
+    groups = dag.task_group.get_task_group_dict().values()
+    loops = [group for group in groups if isinstance(group, 
SerializedLoopTaskGroup)]
+    if not loops:
+        _check_gates_are_in_their_loops(dag)
+        return
+    downstream = {
+        task[Encoding.VAR]["task_id"]: 
set(task[Encoding.VAR].get("downstream_task_ids", []))
+        for task in data["dag"]["tasks"]
+    }
+    members_by_loop = [(loop, _check_loop(loop, dag, downstream)) for loop in 
loops]
+    _check_gates_are_in_their_loops(dag)
+    _check_expansions_over_loop_tasks(dag, groups)
+    for loop, members in members_by_loop:
+        _rewire_edges_out(loop, members, downstream)
+    # The Dag as sent was checked for a cycle; the edges changed here can 
still close one.
+    if (task_id := detect_cycle(downstream, downstream.__getitem__)) is not 
None:
+        raise ValueError(f"Making each loop's gate its only way out makes a 
cycle through {task_id!r}")
+    for task in data["dag"]["tasks"]:
+        edges = downstream[task[Encoding.VAR]["task_id"]]
+        if edges:
+            task[Encoding.VAR]["downstream_task_ids"] = sorted(edges)
+        else:
+            task[Encoding.VAR].pop("downstream_task_ids", None)
+
+
+def _check_gates_are_in_their_loops(dag: SerializedDAG) -> None:
+    """Raise for a task serialized as a gate that is not the gate of its 
loop."""
+    for task in dag.task_dict.values():
+        if task.task_type != LOOP_GATE_OPERATOR:
+            continue
+        loop = enclosing_loop(task)
+        if loop is None or loop.gate_task_id != task.task_id:
+            raise ValueError(f"Task {task.task_id!r} is serialized as 
{LOOP_GATE_OPERATOR} but gates no loop")
+
+
+def _check_loop(
+    loop: SerializedLoopTaskGroup, dag: SerializedDAG, downstream: dict[str, 
set[str]]
+) -> set[str]:
+    """Raise unless *loop* is one core can run, and return the ids of the 
tasks it holds."""
+    parent = loop.parent_group
+    while parent is not None:
+        if isinstance(parent, SerializedLoopTaskGroup):
+            raise ValueError(
+                f"Loop {loop.group_id!r} is inside loop {parent.group_id!r}; 
loops cannot be nested"
+            )
+        if isinstance(parent, SerializedMappedTaskGroup):
+            raise ValueError(f"Loop {loop.group_id!r} cannot be inside mapped 
task group {parent.group_id!r}")
+        parent = parent.parent_group
+    tasks = list(loop.iter_tasks())
+    members = {task.task_id for task in tasks}
+    if loop.gate_task_id not in members:
+        raise ValueError(
+            f"Loop {loop.group_id!r} names gate {loop.gate_task_id!r}, which 
is not a task of it"
+        )
+    gate = dag.get_task(loop.gate_task_id)
+    # Core finds a gate by its task type, so a gate serialized under another 
type would never end its loop.
+    if gate.task_type != LOOP_GATE_OPERATOR:
+        raise ValueError(
+            f"The gate {loop.gate_task_id!r} of loop {loop.group_id!r} has to 
be serialized as "
+            f"{LOOP_GATE_OPERATOR}, not {gate.task_type}"
+        )
+    # The gate has to sit directly in its loop group. One gate instance makes 
one decision per iteration,
+    # so a mapped gate, or one under a mapped task group, would make several.
+    if loop.gate_task_id not in loop.children:
+        raise ValueError(
+            f"The gate {loop.gate_task_id!r} of loop {loop.group_id!r} has to 
be a direct child of the loop"
+        )
+    if isinstance(gate, SerializedMappedOperator):
+        raise ValueError(f"The gate {loop.gate_task_id!r} of loop 
{loop.group_id!r} cannot be mapped")
+    # The scheduler completes an empty task without running it, so the gate 
would decide nothing.
+    if gate.inherits_from_empty_operator:
+        raise ValueError(f"The gate {loop.gate_task_id!r} of loop 
{loop.group_id!r} cannot be empty")
+    # A trigger event completes the task with no decision, which would end the 
loop after one pass.
+    if gate.start_from_trigger:
+        raise ValueError(
+            f"The gate {loop.gate_task_id!r} of loop {loop.group_id!r} cannot 
start from a trigger"
+        )
+    for task in tasks:
+        if task.returns_dag_result:
+            raise ValueError(
+                f"Task {task.task_id!r} is inside loop {loop.group_id!r} and 
cannot be a Dag result"
+            )
+    body = members - {loop.gate_task_id}
+    leaves = sorted(task_id for task_id in body if not downstream[task_id] & 
body)
+    if leaves != [loop.terminal_task_id]:
+        raise ValueError(
+            f"The body of loop {loop.group_id!r} has to end in exactly one 
task, its terminal task "
+            f"{loop.terminal_task_id!r}, but it ends in {leaves}"
+        )
+    return members
+
+
+# TODO: Share these loop checks between Python and language SDK Dags;
+# tracked at https://github.com/apache/airflow/issues/76903
+def _check_expansions_over_loop_tasks(dag: SerializedDAG, groups: 
Iterable[SerializedTaskGroup]) -> None:
+    """Raise for a mapped task or group that expands over a task of a loop it 
is not in."""
+    consumers: list[tuple[str | None, SerializedLoopTaskGroup | None, Any]] = [
+        (task.task_id, enclosing_loop(task), task.iter_mapped_dependencies())
+        for task in dag.task_dict.values()
+        if isinstance(task, SerializedMappedOperator)
+    ]
+    consumers.extend(
+        (group.group_id, enclosing_loop_of_group(group), 
group.iter_mapped_dependencies())
+        for group in groups
+        if isinstance(group, SerializedMappedTaskGroup)
+    )
+    for consumer_id, consumer_loop, producers in consumers:
+        for producer in producers:
+            loop = enclosing_loop(producer)
+            if loop is not None and (consumer_loop is None or 
consumer_loop.group_id != loop.group_id):
+                raise ValueError(
+                    f"{consumer_id!r} cannot expand over {producer.task_id!r}, 
a task in loop "
+                    f"{loop.group_id!r}; only tasks in the same loop can 
expand over its output"
+                )
+
+
+def _rewire_edges_out(
+    loop: SerializedLoopTaskGroup, members: set[str], downstream: dict[str, 
set[str]]
+) -> None:
+    gate = loop.gate_task_id
+    downstream[loop.terminal_task_id].add(gate)
+    for task_id in members - {gate}:
+        outside = downstream[task_id] - members
+        downstream[task_id] -= outside
+        downstream[gate] |= outside
diff --git a/airflow-core/src/airflow/models/task_coordinates.py 
b/airflow-core/src/airflow/models/task_coordinates.py
index 83a0b842c10..769018846f9 100644
--- a/airflow-core/src/airflow/models/task_coordinates.py
+++ b/airflow-core/src/airflow/models/task_coordinates.py
@@ -41,7 +41,11 @@ from airflow.models.dynamic_region import (
 )
 from airflow.models.taskinstance import TaskInstance
 from airflow.serialization.definitions.mappedoperator import is_mapped
-from airflow.serialization.definitions.taskgroup import 
SerializedLoopTaskGroup, SerializedMappedTaskGroup
+from airflow.serialization.definitions.taskgroup import (
+    SerializedLoopTaskGroup,
+    SerializedMappedTaskGroup,
+    SerializedTaskGroup,
+)
 from airflow.utils.state import TaskInstanceState
 
 if TYPE_CHECKING:
@@ -129,7 +133,10 @@ class SchedulingTI(TaskCoordinate, Protocol):
 
 
 def enclosing_loop(task: SerializedOperator) -> SerializedLoopTaskGroup | None:
-    group = task.task_group
+    return enclosing_loop_of_group(task.task_group)
+
+
+def enclosing_loop_of_group(group: SerializedTaskGroup | None) -> 
SerializedLoopTaskGroup | None:
     while group is not None:
         if isinstance(group, SerializedLoopTaskGroup):
             return group
diff --git a/airflow-core/tests/unit/dag_processing/test_lang_sdk_processor.py 
b/airflow-core/tests/unit/dag_processing/test_lang_sdk_processor.py
index 8be3221b378..a355c8efff0 100644
--- a/airflow-core/tests/unit/dag_processing/test_lang_sdk_processor.py
+++ b/airflow-core/tests/unit/dag_processing/test_lang_sdk_processor.py
@@ -872,3 +872,18 @@ def 
test_tasks_in_the_default_pool_move_to_the_teams_pool(mock_bundles_manager):
         "load": "custom",
         "fan_out": "default_pool_team_a",
     }
+
+
+@patch("airflow.dag_processing.lang_sdk_processor.normalize_loops", 
autospec=True)
+def test_a_dag_with_a_loop_core_cannot_run_is_an_import_error(mock_normalize):
+    mock_normalize.side_effect = [ValueError("loop is broken"), None]
+    broken, ok = _serialize_dag("broken"), _serialize_dag("ok")
+    proc = _make_process()
+
+    proc._handle_request(
+        DagFileParsingResult(fileloc="/b/dag.native", serialized_dags=[broken, 
ok]), MagicMock(), 1
+    )
+
+    assert [call.args[0] for call in mock_normalize.call_args_list] == 
[broken.data, ok.data]
+    assert [dag.dag_id for dag in proc.parsing_result.serialized_dags] == 
["ok"]
+    assert proc.parsing_result.import_errors == {"dag.native": "ValueError: 
loop is broken"}
diff --git a/airflow-core/tests/unit/dag_processing/test_loop_checks.py 
b/airflow-core/tests/unit/dag_processing/test_loop_checks.py
new file mode 100644
index 00000000000..5450802a1d1
--- /dev/null
+++ b/airflow-core/tests/unit/dag_processing/test_loop_checks.py
@@ -0,0 +1,379 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+from __future__ import annotations
+
+import copy
+import re
+
+import pytest
+
+from airflow.dag_processing.loop_checks import normalize_loops
+from airflow.sdk import DAG, BaseOperator, task, task_group
+from airflow.sdk.definitions._internal.loop import LoopGateOperator, 
create_loop
+from airflow.serialization.serialized_objects import DagSerialization
+
+
+def _serialize_loop_dag() -> dict:
+    """``body.first >> body.terminal`` in a loop whose gate leads to 
``outside``, serialized."""
+
+    @task_group
+    def body():
+        BaseOperator(task_id="first") >> BaseOperator(task_id="terminal")
+
+    with DAG("looped", schedule=None) as dag:
+        create_loop(body, max_iterations=2) >> BaseOperator(task_id="outside")
+    return DagSerialization.to_dict(dag)
+
+
+def _get_downstream(data: dict) -> dict[str, list[str]]:
+    return {
+        task["__var"]["task_id"]: task["__var"].get("downstream_task_ids", [])
+        for task in data["dag"]["tasks"]
+    }
+
+
+def _set_downstream(data: dict, task_id: str, downstream: list[str]) -> None:
+    task = next(task for task in data["dag"]["tasks"] if 
task["__var"]["task_id"] == task_id)
+    task["__var"]["downstream_task_ids"] = downstream
+
+
+def _normalize(data: dict) -> None:
+    normalize_loops(data, DagSerialization.validate_serialized_dag(data))
+
+
+def test_a_loop_edge_out_of_the_body_is_moved_to_leave_from_the_gate():
+    data = _serialize_loop_dag()
+    # As an SDK that leaves rewiring to core sends it: the terminal leads 
straight out of the loop.
+    _set_downstream(data, "body.terminal", ["outside"])
+    _set_downstream(data, "body.__loop_gate", [])
+
+    _normalize(data)
+
+    assert _get_downstream(data) == {
+        "body.first": ["body.terminal"],
+        "body.terminal": ["body.__loop_gate"],
+        "body.__loop_gate": ["outside"],
+        "outside": [],
+    }
+
+
[email protected](
+    "send",
+    [
+        pytest.param(lambda data: None, id="as-python-stores-it"),
+        pytest.param(lambda data: _set_downstream(data, "outside", []), 
id="empty-edge-list"),
+    ],
+)
+def 
test_a_loop_already_wired_through_its_gate_is_left_as_python_stores_it(send):
+    data = _serialize_loop_dag()
+    expected = copy.deepcopy(data)
+    send(data)
+
+    _normalize(data)
+
+    assert data == expected
+
+
+def _name_another_terminal(data: dict) -> None:
+    
data["dag"]["task_group"]["children"]["body"][1]["loop"]["terminal_task_id"] = 
"body.first"
+
+
+def _name_a_missing_gate(data: dict) -> None:
+    data["dag"]["task_group"]["children"]["body"][1]["loop"]["gate_task_id"] = 
"body.missing"
+
+
+def _end_in_two_tasks(data: dict) -> None:
+    _set_downstream(data, "body.first", [])
+
+
+def _set_task_field(data: dict, task_id: str, key: str, value) -> None:
+    task = next(task for task in data["dag"]["tasks"] if 
task["__var"]["task_id"] == task_id)
+    task["__var"][key] = value
+
+
+def _close_a_cycle_through_the_gate(data: dict) -> None:
+    # No cycle as sent; putting the terminal before the gate closes one.
+    _set_downstream(data, "body.terminal", ["outside"])
+    _set_downstream(data, "body.__loop_gate", ["body.first"])
+
+
[email protected](
+    ("break_loop", "error"),
+    [
+        pytest.param(_name_another_terminal, "has to end in exactly one task", 
id="wrong-terminal"),
+        pytest.param(_end_in_two_tasks, "but it ends in ['body.first', 
'body.terminal']", id="two-leaves"),
+        pytest.param(_name_a_missing_gate, "which is not a task of it", 
id="missing-gate"),
+        pytest.param(_close_a_cycle_through_the_gate, "makes a cycle", 
id="cycle-after-rewiring"),
+        pytest.param(
+            lambda data: _set_task_field(data, "body.__loop_gate", 
"task_type", "TypeScriptOperator"),
+            "has to be serialized as LoopGateOperator, not TypeScriptOperator",
+            id="gate-of-another-type",
+        ),
+        pytest.param(
+            lambda data: _set_task_field(data, "body.__loop_gate", 
"_is_empty", True),
+            "The gate 'body.__loop_gate' of loop 'body' cannot be empty",
+            id="empty-gate",
+        ),
+        pytest.param(
+            lambda data: _set_task_field(data, "body.__loop_gate", 
"start_from_trigger", True),
+            "The gate 'body.__loop_gate' of loop 'body' cannot start from a 
trigger",
+            id="trigger-started-gate",
+        ),
+        pytest.param(
+            lambda data: _set_task_field(data, "body.first", "task_type", 
"LoopGateOperator"),
+            "'body.first' is serialized as LoopGateOperator but gates no loop",
+            id="body-task-typed-as-gate",
+        ),
+        pytest.param(
+            lambda data: _set_task_field(data, "body.terminal", 
"returns_dag_result", True),
+            "'body.terminal' is inside loop 'body' and cannot be a Dag result",
+            id="dag-result-in-loop",
+        ),
+    ],
+)
+def test_a_loop_core_cannot_run_is_refused(break_loop, error):
+    data = _serialize_loop_dag()
+    break_loop(data)
+
+    with pytest.raises(ValueError, match=re.escape(error)):
+        _normalize(data)
+
+
+def _serialize_expand_over_a_loop_task(producer_id: str) -> dict:
+    @task
+    def produce():
+        return [1]
+
+    @task
+    def consume(value):
+        return value
+
+    @task_group
+    def body():
+        produce()
+
+    with DAG("expand_outside", schedule=None) as dag:
+        create_loop(body, max_iterations=2)
+        consume.expand(value=dag.get_task(producer_id).output)
+    return DagSerialization.to_dict(dag)
+
+
+def _serialize_mapped_group_over_a_loop_task() -> dict:
+    @task
+    def produce():
+        return [1]
+
+    @task
+    def work(value):
+        return value
+
+    @task_group
+    def body():
+        produce()
+
+    @task_group
+    def consume(value):
+        work(value)
+
+    with DAG("mapped_group_outside", schedule=None) as dag:
+        create_loop(body, max_iterations=2)
+        consume.expand(value=dag.get_task("body.produce").output)
+    return DagSerialization.to_dict(dag)
+
+
+def _serialize_loop_in_a_mapped_group() -> dict:
+    @task
+    def work(value):
+        return value
+
+    @task_group
+    def mapped(value):
+        @task_group
+        def inner():
+            work(value)
+
+        inner()
+
+    with DAG("loop_in_mapped", schedule=None) as dag:
+        mapped.expand(value=[1, 2])
+    data = DagSerialization.to_dict(dag)
+    # Python refuses to build this, so the loop is added as an SDK would have 
written it.
+    inner = 
data["dag"]["task_group"]["children"]["mapped"][1]["children"]["mapped.inner"][1]
+    inner["loop"] = {
+        "max_iterations": 2,
+        "has_until": False,
+        "terminal_task_id": "mapped.inner.work",
+        "gate_task_id": "mapped.inner.work",
+    }
+    return data
+
+
+def _serialize_mapped_gate() -> dict:
+    @task
+    def work(value):
+        return value
+
+    @task_group
+    def body():
+        work.expand(value=[1, 2])
+
+    with DAG("mapped_gate", schedule=None) as dag:
+        create_loop(body, max_iterations=2)
+    data = DagSerialization.to_dict(dag)
+    # Swap the roles, so the mapped task is the gate and the loop is otherwise 
one core can run.
+    loop = data["dag"]["task_group"]["children"]["body"][1]["loop"]
+    loop["gate_task_id"], loop["terminal_task_id"] = "body.work", 
"body.__loop_gate"
+    _set_task_field(data, "body.work", "task_type", "LoopGateOperator")
+    _set_task_field(data, "body.__loop_gate", "task_type", "EmptyOperator")
+    _set_downstream(data, "body.work", [])
+    return data
+
+
+def _serialize_gate_in_a_subgroup(*, mapped: bool) -> dict:
+    @task
+    def work(value=None):
+        return value
+
+    @task_group
+    def body():
+        @task_group
+        def inner(value=None):
+            work(value)
+
+        if mapped:
+            inner.expand(value=[1, 2])
+        else:
+            inner()
+
+    with DAG("gate_in_subgroup", schedule=None) as dag:
+        create_loop(body, max_iterations=2)
+    data = DagSerialization.to_dict(dag)
+    # Swap the roles, so the task in the subgroup is the gate and the loop is 
otherwise one core can run.
+    loop = data["dag"]["task_group"]["children"]["body"][1]["loop"]
+    loop["gate_task_id"], loop["terminal_task_id"] = "body.inner.work", 
"body.__loop_gate"
+    _set_task_field(data, "body.inner.work", "task_type", "LoopGateOperator")
+    _set_task_field(data, "body.__loop_gate", "task_type", "EmptyOperator")
+    _set_downstream(data, "body.inner.work", [])
+    return data
+
+
+def _serialize_nested_loop() -> dict:
+    @task_group
+    def inner():
+        BaseOperator(task_id="terminal")
+
+    @task_group
+    def outer():
+        create_loop(inner, max_iterations=2) >> 
LoopGateOperator(task_id="gate")
+
+    with DAG("nested", schedule=None) as dag:
+        outer()
+    data = DagSerialization.to_dict(dag)
+    # Python refuses to build this, so the outer loop is added as an SDK would 
have written it.
+    data["dag"]["task_group"]["children"]["outer"][1]["loop"] = {
+        "max_iterations": 3,
+        "has_until": False,
+        "terminal_task_id": "outer.inner.__loop_gate",
+        "gate_task_id": "outer.gate",
+    }
+    return data
+
+
+def _serialize_gate_outside_any_loop() -> dict:
+    with DAG("no_loop", schedule=None) as dag:
+        BaseOperator(task_id="alone")
+    data = DagSerialization.to_dict(dag)
+    _set_task_field(data, "alone", "task_type", "LoopGateOperator")
+    return data
+
+
[email protected](
+    ("serialize", "error"),
+    [
+        pytest.param(
+            lambda: _serialize_expand_over_a_loop_task("body.produce"),
+            "'consume' cannot expand over 'body.produce', a task in loop 
'body'",
+            id="expand-from-outside",
+        ),
+        pytest.param(
+            lambda: _serialize_expand_over_a_loop_task("body.__loop_gate"),
+            "'consume' cannot expand over 'body.__loop_gate', a task in loop 
'body'",
+            id="expand-over-the-gate-from-outside",
+        ),
+        pytest.param(
+            _serialize_mapped_group_over_a_loop_task,
+            "'consume' cannot expand over 'body.produce', a task in loop 
'body'",
+            id="mapped-group-expands-from-outside",
+        ),
+        pytest.param(
+            _serialize_loop_in_a_mapped_group,
+            "Loop 'mapped.inner' cannot be inside mapped task group 'mapped'",
+            id="inside-a-mapped-group",
+        ),
+        pytest.param(
+            _serialize_mapped_gate,
+            "The gate 'body.work' of loop 'body' cannot be mapped",
+            id="mapped-gate",
+        ),
+        pytest.param(
+            lambda: _serialize_gate_in_a_subgroup(mapped=True),
+            "The gate 'body.inner.work' of loop 'body' has to be a direct 
child of the loop",
+            id="gate-in-a-mapped-group",
+        ),
+        pytest.param(
+            lambda: _serialize_gate_in_a_subgroup(mapped=False),
+            "The gate 'body.inner.work' of loop 'body' has to be a direct 
child of the loop",
+            id="gate-in-a-subgroup",
+        ),
+        pytest.param(
+            _serialize_gate_outside_any_loop,
+            "'alone' is serialized as LoopGateOperator but gates no loop",
+            id="gate-in-a-dag-with-no-loop",
+        ),
+        pytest.param(
+            _serialize_nested_loop,
+            "Loop 'outer.inner' is inside loop 'outer'",
+            id="nested-loop",
+        ),
+    ],
+)
+def test_a_loop_placement_core_cannot_run_is_refused(serialize, error):
+    with pytest.raises(ValueError, match=re.escape(error)):
+        _normalize(serialize())
+
+
+def test_a_mapped_task_can_expand_over_a_task_of_its_own_loop():
+    @task
+    def produce():
+        return [1]
+
+    @task
+    def consume(value):
+        return value
+
+    @task_group
+    def body():
+        consume.expand(value=produce())
+
+    with DAG("expand_inside", schedule=None) as dag:
+        create_loop(body, max_iterations=2)
+    data = DagSerialization.to_dict(dag)
+
+    _normalize(data)
+
+    assert _get_downstream(data)["body.consume"] == ["body.__loop_gate"]
diff --git a/go-sdk/adr/0009-task-loop-authoring-interface.md 
b/go-sdk/adr/0009-task-loop-authoring-interface.md
index 6ba0b1e2d78..9d946f1d26d 100644
--- a/go-sdk/adr/0009-task-loop-authoring-interface.md
+++ b/go-sdk/adr/0009-task-loop-authoring-interface.md
@@ -207,8 +207,8 @@ type XComSequence interface {
 
 ## Consequences
 
-- **A fixed-count loop needs no runtime support.** `Loop(3)` emits `has_until: 
false`, which core
-  completes without a worker (ADR-0017 decision 4).
+- **A fixed-count loop's gate only counts.** `Loop(3)` emits `has_until: 
false`, and its gate runs on
+  a worker and ends the loop once `Index` reaches `MaxIterations` (ADR-0017 
decision 4).
 - **The gate is an ordinary task.** `airflow.Until` takes `TaskOption`, so 
`airflow.TaskSpec{Queue: ...}`
   lands on it, and its task_id defaults to the Go function name under the 
group's prefix.
   `TaskSpec{TaskID: "accurate_enough"}` is how it gets a snake_case id, as for 
any task. A loop with
diff --git a/java-sdk/adr/0003-task-loop-authoring-interface.md 
b/java-sdk/adr/0003-task-loop-authoring-interface.md
index ad788fc34db..0c854160b11 100644
--- a/java-sdk/adr/0003-task-loop-authoring-interface.md
+++ b/java-sdk/adr/0003-task-loop-authoring-interface.md
@@ -276,8 +276,9 @@ public class LoopTaskRef<T> extends TaskRef<T> {}
 
 ## Consequences
 
-- **A fixed-count loop needs no runtime support.** A `@Airflow.Loop` with no 
`@Airflow.Until` emits
-  `has_until: false`, which core completes without a worker (ADR-0017 decision 
4).
+- **A fixed-count loop's gate only counts.** A `@Airflow.Loop` with no 
`@Airflow.Until` emits
+  `has_until: false`, and its gate runs on a worker and ends the loop once 
`index` reaches
+  `maxIterations` (ADR-0017 decision 4).
 - **Neither surface names the terminal.** Both take the body's single leaf and 
serialize the same
   `terminal_task_id`. The annotation surface binds it into the gate as well, 
which is what buys the
   compile-time check; the interface surface has no wiring to bind it with.
diff --git a/task-sdk/src/airflow/sdk/definitions/_internal/loop.py 
b/task-sdk/src/airflow/sdk/definitions/_internal/loop.py
index e3c138ae5a4..607aa708e95 100644
--- a/task-sdk/src/airflow/sdk/definitions/_internal/loop.py
+++ b/task-sdk/src/airflow/sdk/definitions/_internal/loop.py
@@ -133,6 +133,8 @@ def _find_loop(group: TaskGroup | None) -> LoopTaskGroup | 
None:
     return None
 
 
+# TODO: Share these loop checks between Python and language SDK Dags;
+# tracked at https://github.com/apache/airflow/issues/76903
 def check_expansions_over_loop_tasks(dag: Any) -> None:
     """
     Raise if a mapped task or task group expands over a loop task without 
being in that loop.
diff --git a/task-sdk/src/airflow/sdk/execution_time/supervisor.py 
b/task-sdk/src/airflow/sdk/execution_time/supervisor.py
index 16ff5893ef2..db5494cf40a 100644
--- a/task-sdk/src/airflow/sdk/execution_time/supervisor.py
+++ b/task-sdk/src/airflow/sdk/execution_time/supervisor.py
@@ -65,10 +65,12 @@ import structlog
 from pydantic import BaseModel, TypeAdapter
 
 from airflow.sdk._shared.logging.structlog import reconfigure_logger
+from airflow.sdk._shared.secrets_masker import redact
 from airflow.sdk.api.client import Client, ServerResponseError
 from airflow.sdk.api.datamodels._generated import (
     AssetResponse,
     ConnectionResponse,
+    LoopDecisionPayload,
     TaskInstance,
     TaskInstanceState,
     TerminalStateNonSuccess,
@@ -1876,7 +1878,7 @@ class ActivitySubprocess(WatchedSubprocess):
                     when=msg.end_date or datetime.now(tz=UTC),
                     rendered_map_index=self._rendered_map_index,
                     retry_reason=msg.retry_reason,
-                    loop_decision=msg.loop_decision,
+                    loop_decision=_redact_loop_decision(msg.loop_decision, 
self.process_log),
                 )
             elif isinstance(msg, SucceedTask):
                 self.client.task_instances.succeed(
@@ -1885,7 +1887,7 @@ class ActivitySubprocess(WatchedSubprocess):
                     task_outlets=msg.task_outlets,
                     outlet_events=msg.outlet_events,
                     rendered_map_index=self._rendered_map_index,
-                    loop_decision=msg.loop_decision,
+                    loop_decision=_redact_loop_decision(msg.loop_decision, 
self.process_log),
                     external_clear_target=msg.external_clear_target,
                 )
             elif isinstance(msg, RetryTask):
@@ -3098,6 +3100,37 @@ def _configure_logging(log_path: str, client: Client) -> 
tuple[FilteringBoundLog
     return logger, log_file_descriptor
 
 
+def _redact_loop_decision(
+    decision: LoopDecisionPayload | None, log: FilteringBoundLogger
+) -> LoopDecisionPayload | None:
+    """
+    Mask a loop gate's reason, then cut it to the byte limit, before it is 
stored and shown in the UI.
+
+    The supervisor holds every value the task registered with ``MaskSecret``, 
so it masks the reason
+    of a gate written in any language. Masking runs first, so a secret that 
crosses the limit is masked
+    whole and no fragment of it survives the cut.
+    """
+    if decision is None or decision.reason is None:
+        return decision
+    reason = str(redact(decision.reason))
+    # Imported here: the module loads the authoring classes, which the 
supervisor otherwise never needs.
+    from airflow.sdk.definitions._internal.loop import 
LOOP_DECISION_REASON_MAX_BYTES
+
+    # A language SDK runtime is not told the limit, and a mask longer than the 
secret it hides can push
+    # a reason past it. Cutting here keeps the API server from rejecting the 
gate.
+    encoded = reason.encode()
+    if len(encoded) > LOOP_DECISION_REASON_MAX_BYTES:
+        log.warning(
+            "Loop decision reason exceeds the byte limit and is cut to it",
+            reason_bytes=len(encoded),
+            max_reason_bytes=LOOP_DECISION_REASON_MAX_BYTES,
+        )
+        reason = 
encoded[:LOOP_DECISION_REASON_MAX_BYTES].decode(errors="ignore")
+    if reason == decision.reason:
+        return decision
+    return decision.model_copy(update={"reason": reason})
+
+
 def _fail_task_before_runtime(
     *, ti: TaskInstance, client: Client, logger: FilteringBoundLogger, error: 
TaskLaunchError
 ) -> int:
@@ -3109,7 +3142,6 @@ def _fail_task_before_runtime(
     retryable *error* puts the task up for retry while it has retries left. 
Returns the process exit
     code, 1.
     """
-    from airflow.sdk._shared.secrets_masker import redact
     from airflow.sdk.log import upload_to_remote
 
     try:
diff --git a/task-sdk/tests/task_sdk/execution_time/test_supervisor.py 
b/task-sdk/tests/task_sdk/execution_time/test_supervisor.py
index 53d16ef597e..9b57102f96a 100644
--- a/task-sdk/tests/task_sdk/execution_time/test_supervisor.py
+++ b/task-sdk/tests/task_sdk/execution_time/test_supervisor.py
@@ -4954,6 +4954,81 @@ class TestHandleRequest:
             **{"retry_reason": None, "loop_decision": None, **extra},
         )
 
+    @pytest.mark.parametrize(
+        "message",
+        [
+            TaskState(state=TaskInstanceState.FAILED, 
end_date=timezone.parse("2024-10-31T12:00:00Z")),
+            SucceedTask(end_date=timezone.parse("2024-10-31T12:00:00Z")),
+        ],
+        ids=["task_state", "succeed_task"],
+    )
+    def test_loop_decision_reason_is_masked_before_it_is_sent(self, 
watched_subprocess, mocker, message):
+        """The supervisor masks a gate's reason for a runtime of every 
language."""
+        watched_subprocess, _ = watched_subprocess
+        mocker.patch(
+            "airflow.sdk.execution_time.supervisor.redact",
+            autospec=True,
+            side_effect=lambda value: value.replace("hunter2", "***"),
+        )
+        decision = LoopDecisionPayload(stop=False, reason="password hunter2 
rejected")
+
+        
watched_subprocess._send_terminal_state_msg(message.model_copy(update={"loop_decision":
 decision}))
+
+        method = "finish" if isinstance(message, TaskState) else "succeed"
+        sent = getattr(watched_subprocess.client.task_instances, 
method).call_args.kwargs["loop_decision"]
+        assert sent == LoopDecisionPayload(stop=False, reason="password *** 
rejected")
+
+    @pytest.mark.parametrize(
+        ("reason", "sent", "cut_from_bytes"),
+        [
+            pytest.param("a" * 513, "a" * 512, 513, id="over-limit"),
+            pytest.param("\u00e9" * 257, "\u00e9" * 256, 514, 
id="cut-on-a-character-boundary"),
+            pytest.param("a" * 512, "a" * 512, None, id="at-limit"),
+            pytest.param(None, None, None, id="no-reason"),
+        ],
+    )
+    def test_loop_decision_reason_is_cut_only_over_the_limit(
+        self, watched_subprocess, reason, sent, cut_from_bytes
+    ):
+        """
+        A language SDK runtime is not told the limit, so the supervisor cuts a 
longer reason to it and
+        warns in the task log. It leaves a reason at the limit, or no reason, 
as it is.
+        """
+        watched_subprocess, _ = watched_subprocess
+        process_log = watched_subprocess.process_log
+
+        watched_subprocess._send_terminal_state_msg(
+            SucceedTask(
+                end_date=timezone.parse("2024-10-31T12:00:00Z"),
+                loop_decision=LoopDecisionPayload(stop=True, reason=reason),
+            )
+        )
+
+        loop_decision = 
watched_subprocess.client.task_instances.succeed.call_args.kwargs["loop_decision"]
+        assert loop_decision == LoopDecisionPayload(stop=True, reason=sent)
+        if cut_from_bytes is None:
+            process_log.warning.assert_not_called()
+        else:
+            process_log.warning.assert_called_once_with(
+                "Loop decision reason exceeds the byte limit and is cut to it",
+                reason_bytes=cut_from_bytes,
+                max_reason_bytes=512,
+            )
+
+    @pytest.mark.enable_redact
+    def test_loop_decision_reason_is_masked_before_it_is_cut(self, 
watched_subprocess):
+        """A secret that crosses the byte limit is masked whole, not cut into 
an unmasked fragment."""
+        watched_subprocess, _ = watched_subprocess
+        mask_secret("s3cr3t-API-key-value")
+        decision = LoopDecisionPayload(stop=True, reason="x" * 500 + 
"s3cr3t-API-key-value" + "y" * 20)
+
+        watched_subprocess._send_terminal_state_msg(
+            SucceedTask(end_date=timezone.parse("2024-10-31T12:00:00Z"), 
loop_decision=decision)
+        )
+
+        sent = 
watched_subprocess.client.task_instances.succeed.call_args.kwargs["loop_decision"]
+        assert sent == LoopDecisionPayload(stop=True, reason="x" * 500 + "***" 
+ "y" * 9)
+
 
 @pytest.mark.parametrize(
     ("test_method", "excluded_message_types"),
diff --git a/ts-sdk/adr/0003-task-loop-authoring-interface.md 
b/ts-sdk/adr/0003-task-loop-authoring-interface.md
index bd6e1abf3b9..48be08d76c9 100644
--- a/ts-sdk/adr/0003-task-loop-authoring-interface.md
+++ b/ts-sdk/adr/0003-task-loop-authoring-interface.md
@@ -178,11 +178,13 @@ interface LoopContext {
 
 ## Consequences
 
-- **A fixed-count loop needs no runtime support.** `loop({ maxIterations })` 
emits `has_until: false`,
-  which core completes without a worker (ADR-0017 decision 4).
+- **A fixed-count loop's gate only counts.** `loop({ maxIterations })` emits 
`has_until: false`, and its
+  gate runs on a worker and ends the loop once `index` reaches `maxIterations` 
(ADR-0017 decision 4).
 - **The gate is an ordinary task.** `LoopOptions` extends `TaskSpec`, so 
`queue` and `retries` land on
   it, and its id defaults to the handler's function name under the group's 
prefix. A fixed-count loop
   has no handler to take a name from, so its gate is `__loop_gate`, as 
Python's is.
+  It serializes as `LoopGateOperator`, the type core finds gates by, and the 
Dag processor rejects a
+  gate serialized under any other type.
 - **The body's single leaf is checked twice**: by the SDK when the Dag is 
read, for the faster
   message, and by the Dag processor, which decides (ADR-0017 decision 3). A 
nested loop and a loop
   inside a mapped task group are rejected the same way.

Reply via email to