jason810496 commented on code in PR #76539:
URL: https://github.com/apache/airflow/pull/76539#discussion_r4615783692
##########
ts-sdk/src/sdk/dag.ts:
##########
@@ -1255,6 +1367,178 @@ 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)}`,
+ );
+ }
+ // 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.
+ const named = readFunctionName(until);
+ const gateId =
+ typeof gateSpec["taskId"] === "string"
+ ? undefined
+ : named !== undefined && LOOP_GATE_NAME.test(named)
+ ? named
+ : DEFAULT_LOOP_GATE_ID;
+ const handler = until ?? (async () => undefined);
Review Comment:
I went with Python's numbering instead: a clashing gate id gets a `__1`
suffix, like `get_unique_task_id`. See
[`c6660afaf22`](https://github.com/apache/airflow/pull/76539/commits/c6660afaf22eff4cad2e1e7abf4c84f1f141a9ca)
and
[`59b6513b7b9`](https://github.com/apache/airflow/pull/76539/commits/59b6513b7b90af515eb62c026f60c2cc9dc9637a).
A clash with an explicit `taskId` still fails.
##########
airflow-core/docs/authoring-and-scheduling/language-sdks/typescript.rst:
##########
@@ -376,6 +376,48 @@ Exactly one case runs, and there is no default: a decider
that returns anything
returned and what it could have returned. To run several tasks together on one
outcome, put them behind a
single task, or give each its own ``dag.if``.
+Task loops
+~~~~~~~~~~
+
+``loop`` runs a task group again and again, up to ``maxIterations``, until its
handler says stop. The handler
+runs after every iteration as the loop's gate task, and ``getLoop()`` gives a
task its iteration and the
+previous iteration's result:
+
+.. code-block:: typescript
+
+ import { getLoop, type LoopDecision, type XComSequence } from
"@apache-airflow/ts-sdk";
Review Comment:
Fixed in
[`c2ceac20f3e`](https://github.com/apache/airflow/pull/76539/commits/c2ceac20f3e8cb67a20a036ca5db359dc55cf4fd):
the example now declares `report` and `cleanup`, so the import is used.
##########
task-sdk/src/airflow/sdk/execution_time/loop.py:
##########
@@ -121,8 +120,7 @@ def execute_loop_gate(gate: LoopGateOperator, context:
Context) -> None:
f"until must return a bool or LoopDecision, got
{type(result).__name__}"
)
if reason is not None:
- # Mask here, where we can know what the task has masked.
- reason = cast("str", redact(reason))
+ # The supervisor masks the reason, for a gate of every language.
Review Comment:
Fixed on the core PR in
[`092fc9c5f67`](https://github.com/apache/airflow/pull/76803/commits/092fc9c5f676528b869c3a5fd5fc0db526d29c8f),
with a test that the message is masked.
##########
ts-sdk/tests/coordinator/serde.test.ts:
##########
@@ -50,7 +50,10 @@ function place(
upstream: readonly TaskRef[] = [],
spec?: TaskSpec,
) {
- const factory = scope.task(taskId, async (_args: WiredArgs) => undefined,
spec);
+ const handler = async (_args: WiredArgs) => undefined;
+ // A group's task() returns a factory of loop task references, so each side
is called apart.
Review Comment:
Both are back to one `scope.task(...)` call in
[`c4e3c5c18a9`](https://github.com/apache/airflow/pull/76539/commits/c4e3c5c18a978685faeda6fa4b4f2bac8e781926).
##########
ts-sdk/example/src/loop.ts:
##########
@@ -0,0 +1,93 @@
+/*!
+ * 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.
+ */
+
+// Task loops declared in TypeScript: a task group that runs again and again
+// until a gate says stop. The TypeScript spelling of the Python example
+// `example_task_loops.py`.
+//
+// `refine` is Newton's method for the square root of two. Each iteration
+// improves the previous estimate and measures its error, and the loop stops
+// once the error is small enough, or at ten iterations. `accumulate` only
+// counts, so it needs no handler to decide.
+
+import { Dag, getLoop, type LoopDecision, type XComSequence } from
"@apache-airflow/ts-sdk";
+
+type Metrics = { estimate: number; error: number };
+
+export const dag = new Dag("typescript_loop_example", {
+ schedule: "@daily",
+ catchup: false,
+ tags: ["typescript", "loop"],
+ description: "Task loops declared in TypeScript: one decided by a handler,
one by a count.",
+ queue: "typescript",
+});
+
+const refine = dag.taskGroup("refine");
+
+const improve = refine.task(async function improve(): Promise<number> {
+ // The terminal task's result of the iteration before; null at the first.
+ const estimate = (await getLoop()).getPrevious<Metrics>()?.estimate ?? 1.0;
+ return (estimate + 2.0 / estimate) / 2.0;
+});
Review Comment:
Agreed, applied in
[`58cee602796`](https://github.com/apache/airflow/pull/76539/commits/58cee602796870612873b01a438a5c5ecb16b7ab).
The docs example uses the same style now.
##########
ts-sdk/example/src/loop.ts:
##########
@@ -0,0 +1,93 @@
+/*!
+ * 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.
+ */
+
+// Task loops declared in TypeScript: a task group that runs again and again
+// until a gate says stop. The TypeScript spelling of the Python example
+// `example_task_loops.py`.
+//
+// `refine` is Newton's method for the square root of two. Each iteration
+// improves the previous estimate and measures its error, and the loop stops
+// once the error is small enough, or at ten iterations. `accumulate` only
+// counts, so it needs no handler to decide.
+
+import { Dag, getLoop, type LoopDecision, type XComSequence } from
"@apache-airflow/ts-sdk";
+
+type Metrics = { estimate: number; error: number };
+
+export const dag = new Dag("typescript_loop_example", {
+ schedule: "@daily",
+ catchup: false,
+ tags: ["typescript", "loop"],
+ description: "Task loops declared in TypeScript: one decided by a handler,
one by a count.",
+ queue: "typescript",
+});
+
+const refine = dag.taskGroup("refine");
+
+const improve = refine.task(async function improve(): Promise<number> {
+ // The terminal task's result of the iteration before; null at the first.
+ const estimate = (await getLoop()).getPrevious<Metrics>()?.estimate ?? 1.0;
+ return (estimate + 2.0 / estimate) / 2.0;
+});
+
+const evaluate = refine.task(async function evaluate({
+ estimate,
+}: {
+ estimate: number;
+}): Promise<Metrics> {
+ return { estimate, error: Math.abs(estimate * estimate - 2) };
+});
+
+// The gate. It reads the terminal task as wired data, so the compiler checks
+// it against what `evaluate` returns.
+async function accurateEnough({ result }: { result: Metrics }):
Promise<LoopDecision> {
+ const threshold = 0.000001;
+ if (result.error < threshold) {
+ return { stop: true, reason: `converged with error
${result.error.toPrecision(2)}` };
+ }
+ return { stop: false, reason: `error ${result.error.toPrecision(2)}, needs <
${threshold}` };
+}
+
+const report = dag.task(async function report({ history }: { history:
XComSequence<Metrics> }) {
+ const last = await history.at(-1);
+ return {
+ iterations: await history.length(),
+ estimate: last.estimate,
+ errors: (await history.slice()).map((metrics) => metrics.error),
+ };
+});
+
+const finished = dag.task(async function finished() {
+ console.log("Refinement finished.");
+});
+
+const evaluated = evaluate({ estimate: improve() });
Review Comment:
Applied in
[`58cee602796`](https://github.com/apache/airflow/pull/76539/commits/58cee602796870612873b01a438a5c5ecb16b7ab),
in the docs example too.
##########
ts-sdk/example/src/loop.ts:
##########
@@ -0,0 +1,93 @@
+/*!
+ * 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.
+ */
+
+// Task loops declared in TypeScript: a task group that runs again and again
+// until a gate says stop. The TypeScript spelling of the Python example
+// `example_task_loops.py`.
+//
+// `refine` is Newton's method for the square root of two. Each iteration
+// improves the previous estimate and measures its error, and the loop stops
+// once the error is small enough, or at ten iterations. `accumulate` only
+// counts, so it needs no handler to decide.
+
+import { Dag, getLoop, type LoopDecision, type XComSequence } from
"@apache-airflow/ts-sdk";
+
+type Metrics = { estimate: number; error: number };
+
+export const dag = new Dag("typescript_loop_example", {
+ schedule: "@daily",
+ catchup: false,
+ tags: ["typescript", "loop"],
+ description: "Task loops declared in TypeScript: one decided by a handler,
one by a count.",
+ queue: "typescript",
+});
+
+const refine = dag.taskGroup("refine");
+
+const improve = refine.task(async function improve(): Promise<number> {
+ // The terminal task's result of the iteration before; null at the first.
+ const estimate = (await getLoop()).getPrevious<Metrics>()?.estimate ?? 1.0;
+ return (estimate + 2.0 / estimate) / 2.0;
+});
+
+const evaluate = refine.task(async function evaluate({
+ estimate,
+}: {
+ estimate: number;
+}): Promise<Metrics> {
+ return { estimate, error: Math.abs(estimate * estimate - 2) };
+});
Review Comment:
Applied in
[`58cee602796`](https://github.com/apache/airflow/pull/76539/commits/58cee602796870612873b01a438a5c5ecb16b7ab).
##########
airflow-core/src/airflow/dag_processing/loop_checks.py:
##########
@@ -0,0 +1,168 @@
+# 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
+from airflow.serialization.definitions.mappedoperator import
SerializedMappedOperator
+from airflow.serialization.definitions.taskgroup import
SerializedLoopTaskGroup, SerializedMappedTaskGroup
+
+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["__var"]["task_id"]: set(task["__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["__var"]["task_id"]]
+ if edges:
+ task["__var"]["downstream_task_ids"] = sorted(edges)
+ else:
+ task["__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 = _find_loop(task.task_group)
+ 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}"
+ )
+ # One gate instance makes one decision per iteration.
+ if isinstance(gate, SerializedMappedOperator):
+ raise ValueError(f"The gate {loop.gate_task_id!r} of loop
{loop.group_id!r} cannot be mapped")
+ 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
+
+
+def _find_loop(group: SerializedTaskGroup | None) -> SerializedLoopTaskGroup |
None:
+ while group is not None:
+ if isinstance(group, SerializedLoopTaskGroup):
+ return group
+ group = group.parent_group
+ 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: 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, _find_loop(task.task_group),
task.iter_mapped_dependencies())
+ for task in dag.task_dict.values()
+ if isinstance(task, SerializedMappedOperator)
+ ]
+ consumers.extend(
Review Comment:
Added in
[`092fc9c5f67`](https://github.com/apache/airflow/pull/76803/commits/092fc9c5f676528b869c3a5fd5fc0db526d29c8f)
on the core PR.
##########
ts-sdk/example/src/loop.ts:
##########
@@ -0,0 +1,93 @@
+/*!
+ * 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.
+ */
+
+// Task loops declared in TypeScript: a task group that runs again and again
+// until a gate says stop. The TypeScript spelling of the Python example
+// `example_task_loops.py`.
+//
+// `refine` is Newton's method for the square root of two. Each iteration
+// improves the previous estimate and measures its error, and the loop stops
+// once the error is small enough, or at ten iterations. `accumulate` only
+// counts, so it needs no handler to decide.
+
+import { Dag, getLoop, type LoopDecision, type XComSequence } from
"@apache-airflow/ts-sdk";
+
+type Metrics = { estimate: number; error: number };
+
+export const dag = new Dag("typescript_loop_example", {
+ schedule: "@daily",
+ catchup: false,
+ tags: ["typescript", "loop"],
+ description: "Task loops declared in TypeScript: one decided by a handler,
one by a count.",
+ queue: "typescript",
+});
+
+const refine = dag.taskGroup("refine");
+
+const improve = refine.task(async function improve(): Promise<number> {
+ // The terminal task's result of the iteration before; null at the first.
+ const estimate = (await getLoop()).getPrevious<Metrics>()?.estimate ?? 1.0;
+ return (estimate + 2.0 / estimate) / 2.0;
+});
+
+const evaluate = refine.task(async function evaluate({
+ estimate,
+}: {
+ estimate: number;
+}): Promise<Metrics> {
+ return { estimate, error: Math.abs(estimate * estimate - 2) };
+});
+
+// The gate. It reads the terminal task as wired data, so the compiler checks
+// it against what `evaluate` returns.
+async function accurateEnough({ result }: { result: Metrics }):
Promise<LoopDecision> {
+ const threshold = 0.000001;
+ if (result.error < threshold) {
+ return { stop: true, reason: `converged with error
${result.error.toPrecision(2)}` };
+ }
+ return { stop: false, reason: `error ${result.error.toPrecision(2)}, needs <
${threshold}` };
+}
+
+const report = dag.task(async function report({ history }: { history:
XComSequence<Metrics> }) {
+ const last = await history.at(-1);
+ return {
+ iterations: await history.length(),
+ estimate: last.estimate,
+ errors: (await history.slice()).map((metrics) => metrics.error),
+ };
+});
+
+const finished = dag.task(async function finished() {
+ console.log("Refinement finished.");
+});
+
+const evaluated = evaluate({ estimate: improve() });
+const refinement = refine.loop(accurateEnough, { result: evaluated }, {
maxIterations: 10 });
+// Outside the loop, the loop's all() reads every iteration's Metrics.
+report({ history: refinement.all(evaluated) });
+// Order only: after the whole loop, not after one iteration.
+refinement.before(finished());
+
+const accumulate = dag.taskGroup("accumulate");
+
+accumulate.task(async function increment(): Promise<number> {
+ return ((await getLoop()).getPrevious<number>() ?? 0) + 1;
+})();
Review Comment:
Applied in
[`58cee602796`](https://github.com/apache/airflow/pull/76539/commits/58cee602796870612873b01a438a5c5ecb16b7ab).
--
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]