uranusjr commented on code in PR #76539:
URL: https://github.com/apache/airflow/pull/76539#discussion_r4676769155


##########
ts-sdk/src/coordinator/runtime.ts:
##########
@@ -366,8 +382,18 @@ async function handleTask(
 
   const ctx = buildContext(details, signal);
   const client = createCoordinatorClient(comm, ctx, ti.id, clientLogs);
-  if (task.kind === "handler") {
-    return runHandler(details, task.fn, ctx, client, logs);
+  const loop = details.ti_context.loop;
+  const scope: TaskScope = {
+    ctx,
+    client,
+    ...(loop != null && { loop: createLoopSource(loop, client) }),
+  };
+  const allIterationsArgs = readsAllIterations(task.dag, ti.task_id);
+  if (task.kind === BundleTaskKind.HANDLER) {
+    return runHandler(details, task.fn, scope, client, logs, 
allIterationsArgs);
+  }
+  if (task.kind === BundleTaskKind.LOOP_GATE) {

Review Comment:
   I wonder if this is a good time to introduce some kind of operator-ish 
structure here. Python uses operators to implement this, and it’s probably a 
better layer than this (at the same level as task handlers).This would also 
match how HITL can be implemented.
   
   Not sure, more of a design question.



##########
ts-sdk/src/sdk/dag.ts:
##########
@@ -1285,6 +1442,260 @@ export class Dag {
     return Object.freeze(group);
   }
 
+  #placeLoop(group: TaskGroupRef, args: readonly unknown[]): LoopRef {
+    const { groupId } = group;
+    const label = `Loop "${groupId}" of Dag "${this.dagId}"`;
+    if (this.#finalized) {
+      throw new Error(
+        `${label} was declared after the Dag was read; declare every loop 
while the module is ` +
+          "loading",
+      );
+    }
+    if (this.#loops.has(groupId)) {
+      throw new Error(`${label} was already declared; call loop() once per 
task group`);
+    }
+    const [first] = args;
+    const until = typeof first === "function" ? (first as 
UntilCallable<never>) : undefined;
+    const expected = until === undefined ? 1 : 3;
+    // TypeScript already says so, but from plain JavaScript a dropped 
argument would leave the
+    // gate without the inputs or the bound it was meant to have.
+    if (args.length !== expected) {
+      throw new Error(
+        until === undefined
+          ? `${label} takes either loop({ maxIterations }) or loop(until, 
inputs, ` +
+              `{ maxIterations }), not ${args.length} arguments of which the 
first is ` +
+              describeValue(first)
+          : `${label} takes loop(until, inputs, { maxIterations }), not 
${args.length} arguments`,
+      );
+    }
+    const options: unknown = args[expected - 1];
+    if (!isPlainRecord(options)) {
+      throw new Error(`The options of ${label} must be an object holding 
maxIterations`);
+    }
+    const { maxIterations, ...gateSpec } = options;
+    if (
+      typeof maxIterations !== "number" ||
+      !Number.isSafeInteger(maxIterations) ||
+      maxIterations <= 0
+    ) {
+      throw new Error(
+        `maxIterations of ${label} must be a positive integer, not 
${describeValue(maxIterations)}`,
+      );
+    }
+    for (const key of LOOP_GATE_REJECTED_OPTIONS) {
+      if (gateSpec[key] !== undefined) {
+        throw new Error(
+          `The options of ${label} cannot set ${key}: it would change when the 
gate runs, and the ` +
+            "gate has to run after every iteration",
+        );
+      }
+    }
+    // The gate is named after its handler, as a task is, and Python's 
fallback stands in for a
+    // handler that has no name Airflow accepts, or for no handler at all. A 
`taskId` the author
+    // gave is used as it is, so a clash with it is theirs to fix.
+    const named = readFunctionName(until);
+    const gateName =
+      named !== undefined && LOOP_GATE_NAME.test(named) ? named : 
DEFAULT_LOOP_GATE_ID;
+    const gateId =
+      typeof gateSpec["taskId"] === "string" ? undefined : 
this.#getUniqueGateId(groupId, gateName);
+    const handler = until ?? (async () => undefined);

Review Comment:
   This only need to exist to satisfy `#addTask` and is never called. A sign 
that the abstraction level is wrong?



##########
ts-sdk/src/sdk/dag.ts:
##########
@@ -1285,6 +1442,260 @@ export class Dag {
     return Object.freeze(group);
   }
 
+  #placeLoop(group: TaskGroupRef, args: readonly unknown[]): LoopRef {
+    const { groupId } = group;
+    const label = `Loop "${groupId}" of Dag "${this.dagId}"`;
+    if (this.#finalized) {
+      throw new Error(
+        `${label} was declared after the Dag was read; declare every loop 
while the module is ` +
+          "loading",
+      );
+    }
+    if (this.#loops.has(groupId)) {
+      throw new Error(`${label} was already declared; call loop() once per 
task group`);
+    }
+    const [first] = args;
+    const until = typeof first === "function" ? (first as 
UntilCallable<never>) : undefined;
+    const expected = until === undefined ? 1 : 3;
+    // TypeScript already says so, but from plain JavaScript a dropped 
argument would leave the
+    // gate without the inputs or the bound it was meant to have.
+    if (args.length !== expected) {
+      throw new Error(
+        until === undefined
+          ? `${label} takes either loop({ maxIterations }) or loop(until, 
inputs, ` +
+              `{ maxIterations }), not ${args.length} arguments of which the 
first is ` +
+              describeValue(first)
+          : `${label} takes loop(until, inputs, { maxIterations }), not 
${args.length} arguments`,
+      );
+    }
+    const options: unknown = args[expected - 1];
+    if (!isPlainRecord(options)) {
+      throw new Error(`The options of ${label} must be an object holding 
maxIterations`);
+    }
+    const { maxIterations, ...gateSpec } = options;
+    if (
+      typeof maxIterations !== "number" ||
+      !Number.isSafeInteger(maxIterations) ||
+      maxIterations <= 0
+    ) {
+      throw new Error(
+        `maxIterations of ${label} must be a positive integer, not 
${describeValue(maxIterations)}`,
+      );
+    }
+    for (const key of LOOP_GATE_REJECTED_OPTIONS) {
+      if (gateSpec[key] !== undefined) {
+        throw new Error(
+          `The options of ${label} cannot set ${key}: it would change when the 
gate runs, and the ` +
+            "gate has to run after every iteration",
+        );
+      }
+    }
+    // The gate is named after its handler, as a task is, and Python's 
fallback stands in for a
+    // handler that has no name Airflow accepts, or for no handler at all. A 
`taskId` the author
+    // gave is used as it is, so a clash with it is theirs to fix.
+    const named = readFunctionName(until);
+    const gateName =
+      named !== undefined && LOOP_GATE_NAME.test(named) ? named : 
DEFAULT_LOOP_GATE_ID;
+    const gateId =
+      typeof gateSpec["taskId"] === "string" ? undefined : 
this.#getUniqueGateId(groupId, gateName);
+    const handler = until ?? (async () => undefined);
+    const factory = (
+      gateId === undefined
+        ? this.#addTask(groupId, handler, gateSpec as TaskOptions)
+        : this.#addTask(groupId, gateId, handler, gateSpec as TaskOptions)
+    ) as (inputs?: unknown) => TaskRef;
+    const gate = until === undefined ? factory() : factory(args[1]);
+    const record = this.#tasks.get(gate.taskId)!;
+    this.#tasks.set(gate.taskId, { ...record, loopGate: { groupId } });
+    if (gateId !== undefined) this.#gateNames.set(groupId, gateName);
+    this.#loops.set(
+      groupId,
+      Object.freeze({
+        groupId,
+        maxIterations,
+        hasUntil: until !== undefined,
+        gateTaskId: gate.taskId,
+      }),
+    );
+    const placed: LoopRef = {
+      dagId: this.dagId,
+      groupId,
+      all: <TReturn>(task: TaskRef<TReturn>) =>
+        this.#readAllIterations(groupId, task) as 
TaskRef<XComSequence<TReturn>>,
+      before: (...downstream) => {
+        group.before(...downstream);
+        return placed;
+      },
+      after: (...upstream) => {
+        group.after(...upstream);
+        return placed;
+      },
+    };
+    conditionTasks.set(placed, group);
+    return Object.freeze(placed);
+  }
+
+  /**
+   * `taskId`, or `taskId__N` with N one past the highest in use when a task 
of `groupId` already
+   * has it, as Python's `get_unique_task_id` names the gate of a loop.
+   */
+  #getUniqueGateId(groupId: string, taskId: string): string {
+    const taken = [...this.#tasks.keys()];
+    const fullId = this.#childId(groupId, taskId);
+    if (!taken.includes(fullId)) return taskId;
+    const numbered = /__\d+$/;
+    const stem = fullId.replace(numbered, "");
+    const numbers = taken.flatMap((id) => {
+      const rest = id.startsWith(`${stem}__`) ? id.slice(stem.length + 2) : "";
+      return /^\d+$/.test(rest) ? [Number(rest)] : [];
+    });
+    return `${taskId.replace(numbered, "")}__${Math.max(0, ...numbers) + 1}`;
+  }
+
+  /**
+   * Move a gate named after its handler off `taskId`, an id a body task 
declared after `loop()` is
+   * about to take. Python picks the gate's id once the body exists, so the 
gate gets the id it
+   * would have had if the body had been declared first.
+   */
+  #moveGateOff(groupId: string | undefined, taskId: string): void {

Review Comment:
   Renaming a created task across `#tasks`, `#inputs` and the group's `taskIds` 
is fragile. Every future map keyed by task id has to remember to join in. 
Python picks the gate id once the body exists. The TS equivalent is to pick the 
id, or create the gate, in `#finalize()`. Then this method, `#gateNames` and 
`renameKey` aren't needed.



##########
ts-sdk/src/sdk/dag.ts:
##########
@@ -347,7 +450,12 @@ export function isTaskRef(value: unknown): value is 
TaskRef {
   return hasBrand(value, "TaskRef");
 }
 
-const conditionTasks = new WeakMap<object, TaskRef>();
+// What a placed construct stands for at either end of an edge: a condition or 
branch its deciding
+// task, a loop its group.
+const conditionTasks = new WeakMap<object, Node>();

Review Comment:
   Probably can use a rename.



##########
scripts/ci/lang_sdk_serialization/check_go_sdk.py:
##########
@@ -55,7 +55,16 @@
 
 
 def main() -> int:
-    command = [sys.executable, str(COMPARE), "--sdk", "go", "--supports", 
"all", "--", *SERIALIZER]
+    command = [
+        sys.executable,
+        str(COMPARE),
+        "--sdk",
+        "go",
+        "--supports",
+        
"branch,switch,edge_labels,group_options,trigger_dag_run,literal_inputs",

Review Comment:
   Would it be a good idea to have an `--exclude` flag instead? (Or something 
like `--support=all,-loops`)



##########
ts-sdk/src/coordinator/client.ts:
##########
@@ -403,7 +500,10 @@ export function createCoordinatorClient(
       const msg: SetXCom = {
         type: "SetXCom",
         ...resolveXComTarget(opts, ctx),
-        value: opts.value,
+        // Awaited only for a sequence, so a push without one leaves before 
the next call does.

Review Comment:
   ```suggestion
   ```



##########
ts-sdk/adr/0003-task-loop-authoring-interface.md:
##########
@@ -21,7 +21,7 @@
 
 ## Status
 
-Proposed.
+Accepted, as it was implemented.

Review Comment:
   ```suggestion
   Accepted.
   ```



##########
airflow-core/docs/authoring-and-scheduling/language-sdks/typescript.rst:
##########
@@ -893,6 +943,10 @@ Limitations
   run when the Dag processor reads them.
 * **Some CLI commands do not take a Dag declared in TypeScript.** ``airflow 
dags test``, ``tasks test`` and
   ``tasks render`` refuse it, and ``airflow dags reserialize`` skips it.
+* **An XCom read cannot return every iteration of a loop.** From outside a 
loop, the ``TaskHandler`` of a
+  Python Dag's stub task and ``getClient().getXCom()`` in any TypeScript task 
fail on a loop task's XCom, since
+  the runtime has no way to ask for every iteration. Read the loop's output in 
a Python task, or declare the
+  Dag in TypeScript and pass the loop's ``all()`` as an input.

Review Comment:
   This is not quite true since this PR adds `GetXComSequence*`, and core 
decides on its own whether a sequence read from outside the loop covers all 
iterations.



##########
ts-sdk/src/coordinator/xcom-sequence.ts:
##########
@@ -0,0 +1,156 @@
+/*!
+ * 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.
+ */
+
+// The runtime side of `XComSequence`: every read is a supervisor call, and the
+// server decides which producer rows are live and how they are ordered.
+
+import type { CoordinatorClient, XComSequenceOpts } from "./client.js";
+import type { XComSequence } from "../sdk/xcom-sequence.js";
+
+/** The clients that handed a task a sequence, so a push from any other skips 
looking for one. */
+const clientsWithSequences = new WeakSet<CoordinatorClient>();

Review Comment:
   Is the performance gain significant? This feels a bit premature.



##########
ts-sdk/src/coordinator/runtime.ts:
##########
@@ -379,42 +405,160 @@ async function handleTask(
   };
   try {
     switch (task.kind) {
-      case "operator":
+      case BundleTaskKind.OPERATOR:
         return await runOperator(
           task.operator,
-          buildOperatorContext({ details, dag: task.dag, ctx, client, logs, 
fail }),
+          buildOperatorContext({
+            details,
+            dag: task.dag,
+            ctx,
+            client,
+            logs,
+            fail,
+            scope,
+            ...(allIterationsArgs && { allIterationsArgs }),
+          }),
         );
     }
   } catch (err) {
     return fail((err as Error).message ?? String(err));
   }
 }
 
-/** Run the author's handler: bind its arguments, call it, push what it 
returns. */
-async function runHandler(
+/**
+ * The arguments task `taskId` reads every iteration of a loop task through, 
as `all()` recorded them
+ * in this bundle's Dag. None for a Python Dag's task, whose graph this bundle 
does not hold.
+ */
+function readsAllIterations(dag: Dag | undefined, taskId: string): 
ReadonlySet<string> | undefined {
+  return dag === undefined ? undefined : getAllIterationsArgNames(dag, taskId);
+}
+
+/** Bind a handler's arguments, or the failure to report when they cannot be 
bound. */
+async function bindArgs(
   details: StartupDetails,
   handler: TaskFunction,
-  ctx: TaskContext,
+  scope: TaskScope,
   client: CoordinatorClient,
   logs: LogChannel,
-): Promise<RuntimeSucceedTask | RuntimeRetryTask | RuntimeTaskState> {
-  let bound: BoundArgs;
+  allIterationsArgs?: ReadonlySet<string>,
+): Promise<BoundArgs | RuntimeRetryTask | RuntimeTaskState> {
   try {
-    bound = await resolveArgs(details.ti_context?.arg_bindings, {
+    return await resolveArgs(details.ti_context?.arg_bindings, {
       client,
-      signal: ctx.signal,
+      signal: scope.ctx.signal,
       logs,
       argNames: getArgNames(handler),
+      ...(allIterationsArgs && { allIterationsArgs }),
     });
   } catch (err) {
     // Before the handler ran, so nothing it might have written is at stake.
     const message = (err as Error).message ?? String(err);
     logs.error("Cannot bind this task's call arguments", {
+      task_id: scope.ctx.taskId,
+      error: message,
+    });
+    return buildFailureResponse(details, message);
+  }
+}
+
+/**
+ * Run a loop's gate: decide whether another iteration follows, and send core 
the decision.
+ *
+ * The gate pushes no return value. Core creates the next iteration in the 
same transaction that
+ * accepts the decision (ADR-0017 decision 5). A `stop` of false at the last 
iteration fails the gate
+ * here without a retry, as Python does, and the decision goes with the 
failure so its reason is kept.
+ */
+async function runLoopGate(
+  details: StartupDetails,
+  gate: { readonly fn: TaskFunction; readonly hasUntil: boolean },
+  scope: TaskScope,
+  client: CoordinatorClient,
+  logs: LogChannel,
+  allIterationsArgs?: ReadonlySet<string>,
+): Promise<RuntimeSucceedTask | RuntimeRetryTask | RuntimeTaskState> {
+  const { ctx } = scope;
+  const loop = details.ti_context.loop;
+  if (loop == null) {
+    const message =
+      `Task "${ctx.taskId}" is the gate of a loop, but Airflow ran it with no 
loop context; ` +
+      "the Dag version it ran against does not declare the loop";
+    logs.error("Task failed", { task_id: ctx.taskId, error: message });
+    return buildFailureResponse(details, message, { retry: false });
+  }
+  if (!gate.hasUntil) {
+    return succeedGate(loop, { stop: loop.index >= loop.max_iterations }, 
ctx.taskId, logs);
+  }
+  const bound = await bindArgs(details, gate.fn, scope, client, logs, 
allIterationsArgs);
+  if (!("args" in bound)) return bound;
+  let returned: unknown;
+  try {
+    returned = await runInTaskScope(scope, () => gate.fn(bound.args as never));
+  } catch (err) {
+    const message = (err as Error).message ?? String(err);
+    logs.error("Task failed", {
       task_id: ctx.taskId,
       error: message,
+      stack: (err as Error).stack ?? null,
+      bound_args: bound.names,
     });
     return buildFailureResponse(details, message);
   }
+  let decision: LoopDecisionPayload;
+  try {
+    decision = toLoopDecisionPayload(returned);
+  } catch (err) {
+    // The handler would return the same value again, so a retry cannot help, 
as Python's
+    // AirflowFailException for a malformed LoopDecision has it.
+    const message = (err as Error).message;
+    logs.error("Task failed", { task_id: ctx.taskId, error: message });
+    return buildFailureResponse(details, message, { retry: false });
+  }
+  if (!decision.stop && loop.index >= loop.max_iterations) {
+    // Python raises LoopMaxIterationsExceeded, an AirflowFailException, which 
is never retried. The
+    // message only reaches the task log, where the supervisor masks the 
reason as Python's redact does.
+    const reason = decision.reason === undefined ? "" : `: ${decision.reason}`;
+    const message = `Loop condition remained false at 
max_iterations=${loop.max_iterations}${reason}`;
+    logs.error("Task failed", { task_id: ctx.taskId, error: message });
+    return buildFailureResponse(details, message, { retry: false, 
loopDecision: decision });
+  }

Review Comment:
   This departs from Language SDK ADR-0017 Step 4. The note in TypeScript 
ADR-0003 acknowledges it and leaves the former ADR unchanged. We should amend 
it similar to #76803 for the gate type.



##########
scripts/ci/lang_sdk_serialization/serialize_python.py:
##########
@@ -114,6 +133,25 @@ def build_dag(case: dict[str, Any]) -> DAG:
     return dag
 
 
+def close_loop(group: LoopTaskGroup, until: str | None) -> None:
+    """Give a filled loop group its gate, as ``create_loop`` does once the 
body is built."""
+    (terminal,) = group.get_leaves()
+
+    def decide() -> bool:
+        return True
+
+    gate = LoopGateOperator(
+        task_id=get_unique_task_id(until or "__loop_gate", dag=group.dag, 
task_group=group),
+        until=decide if until else None,
+        dag=group.dag,
+        task_group=group,
+    )
+    terminal >> gate
+    group.terminal_task_id = terminal.task_id
+    group.gate_task_id = gate.task_id
+    redirect_outside_edges_to_gate(group, gate)

Review Comment:
   This copies `create_loop` using private imports. Factor the logic out?



##########
ts-sdk/src/coordinator/runtime.ts:
##########
@@ -379,42 +405,160 @@ async function handleTask(
   };
   try {
     switch (task.kind) {
-      case "operator":
+      case BundleTaskKind.OPERATOR:
         return await runOperator(
           task.operator,
-          buildOperatorContext({ details, dag: task.dag, ctx, client, logs, 
fail }),
+          buildOperatorContext({
+            details,
+            dag: task.dag,
+            ctx,
+            client,
+            logs,
+            fail,
+            scope,
+            ...(allIterationsArgs && { allIterationsArgs }),
+          }),
         );
     }
   } catch (err) {
     return fail((err as Error).message ?? String(err));
   }
 }
 
-/** Run the author's handler: bind its arguments, call it, push what it 
returns. */
-async function runHandler(
+/**
+ * The arguments task `taskId` reads every iteration of a loop task through, 
as `all()` recorded them
+ * in this bundle's Dag. None for a Python Dag's task, whose graph this bundle 
does not hold.
+ */
+function readsAllIterations(dag: Dag | undefined, taskId: string): 
ReadonlySet<string> | undefined {
+  return dag === undefined ? undefined : getAllIterationsArgNames(dag, taskId);
+}
+
+/** Bind a handler's arguments, or the failure to report when they cannot be 
bound. */
+async function bindArgs(
   details: StartupDetails,
   handler: TaskFunction,
-  ctx: TaskContext,
+  scope: TaskScope,
   client: CoordinatorClient,
   logs: LogChannel,
-): Promise<RuntimeSucceedTask | RuntimeRetryTask | RuntimeTaskState> {
-  let bound: BoundArgs;
+  allIterationsArgs?: ReadonlySet<string>,
+): Promise<BoundArgs | RuntimeRetryTask | RuntimeTaskState> {
   try {
-    bound = await resolveArgs(details.ti_context?.arg_bindings, {
+    return await resolveArgs(details.ti_context?.arg_bindings, {
       client,
-      signal: ctx.signal,
+      signal: scope.ctx.signal,
       logs,
       argNames: getArgNames(handler),
+      ...(allIterationsArgs && { allIterationsArgs }),
     });
   } catch (err) {
     // Before the handler ran, so nothing it might have written is at stake.
     const message = (err as Error).message ?? String(err);
     logs.error("Cannot bind this task's call arguments", {
+      task_id: scope.ctx.taskId,
+      error: message,
+    });
+    return buildFailureResponse(details, message);
+  }
+}
+
+/**
+ * Run a loop's gate: decide whether another iteration follows, and send core 
the decision.
+ *
+ * The gate pushes no return value. Core creates the next iteration in the 
same transaction that
+ * accepts the decision (ADR-0017 decision 5). A `stop` of false at the last 
iteration fails the gate
+ * here without a retry, as Python does, and the decision goes with the 
failure so its reason is kept.
+ */
+async function runLoopGate(
+  details: StartupDetails,
+  gate: { readonly fn: TaskFunction; readonly hasUntil: boolean },
+  scope: TaskScope,
+  client: CoordinatorClient,
+  logs: LogChannel,
+  allIterationsArgs?: ReadonlySet<string>,
+): Promise<RuntimeSucceedTask | RuntimeRetryTask | RuntimeTaskState> {
+  const { ctx } = scope;
+  const loop = details.ti_context.loop;
+  if (loop == null) {
+    const message =
+      `Task "${ctx.taskId}" is the gate of a loop, but Airflow ran it with no 
loop context; ` +
+      "the Dag version it ran against does not declare the loop";
+    logs.error("Task failed", { task_id: ctx.taskId, error: message });
+    return buildFailureResponse(details, message, { retry: false });
+  }
+  if (!gate.hasUntil) {
+    return succeedGate(loop, { stop: loop.index >= loop.max_iterations }, 
ctx.taskId, logs);
+  }
+  const bound = await bindArgs(details, gate.fn, scope, client, logs, 
allIterationsArgs);
+  if (!("args" in bound)) return bound;
+  let returned: unknown;
+  try {
+    returned = await runInTaskScope(scope, () => gate.fn(bound.args as never));
+  } catch (err) {
+    const message = (err as Error).message ?? String(err);
+    logs.error("Task failed", {
       task_id: ctx.taskId,
       error: message,
+      stack: (err as Error).stack ?? null,
+      bound_args: bound.names,
     });
     return buildFailureResponse(details, message);
   }
+  let decision: LoopDecisionPayload;
+  try {
+    decision = toLoopDecisionPayload(returned);
+  } catch (err) {
+    // The handler would return the same value again, so a retry cannot help, 
as Python's
+    // AirflowFailException for a malformed LoopDecision has it.
+    const message = (err as Error).message;
+    logs.error("Task failed", { task_id: ctx.taskId, error: message });
+    return buildFailureResponse(details, message, { retry: false });
+  }
+  if (!decision.stop && loop.index >= loop.max_iterations) {
+    // Python raises LoopMaxIterationsExceeded, an AirflowFailException, which 
is never retried. The
+    // message only reaches the task log, where the supervisor masks the 
reason as Python's redact does.
+    const reason = decision.reason === undefined ? "" : `: ${decision.reason}`;
+    const message = `Loop condition remained false at 
max_iterations=${loop.max_iterations}${reason}`;
+    logs.error("Task failed", { task_id: ctx.taskId, error: message });
+    return buildFailureResponse(details, message, { retry: false, 
loopDecision: decision });
+  }
+  return succeedGate(loop, decision, ctx.taskId, logs);
+}
+
+/** Log a gate's decision and send it to core on the gate's success. */
+function succeedGate(
+  loop: WireLoopContext,
+  decision: LoopDecisionPayload,
+  taskId: string,
+  logs: LogChannel,
+): RuntimeSucceedTask {
+  // The reason is left out: this runtime cannot redact it, and the supervisor 
masks it on its way
+  // to the UI, where it is shown next to the iteration.

Review Comment:
   This contradicts with the comments above. (Or below? Not sure how GitHub 
orders comments in the new layout. The one around line 517.)



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to