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


##########
ts-sdk/src/coordinator/runtime.ts:
##########
@@ -361,15 +385,40 @@ async function handleTask(
       state: "removed",
       end_date: new Date().toISOString(),
     };
-    return response;
+    return { response, timedOut: false };
   }
 
-  const ctx = buildContext(details, signal);
+  const timeoutSeconds = executionTimeoutOf(details.ti_context);
+  const timeout = timeoutSeconds === null ? null : 
createExecutionTimeout(timeoutSeconds, signal);
+  // The task sees one signal: aborted by SIGTERM/SIGINT, or at its timeout.
+  const ctx = buildContext(details, timeout ? AbortSignal.any([signal, 
timeout.signal]) : signal);
   const client = createCoordinatorClient(comm, ctx, ti.id, clientLogs);
-  if (task.kind === "handler") {
-    return runHandler(details, task.fn, ctx, client, logs);
-  }
+  // Starts the task's work, its handler call or its operator, and waits for it
+  // under its execution_timeout, which counts from here. The order matters: a
+  // timeout that has already passed fails before the work starts, and the
+  // supervisor's deadline starts right before the work, as the runtime's does.
+  const runTimed: RunTimed = async (start) => {
+    if (timeout === null) return start();
+    if (timeout.seconds < 0) throw new TaskTimeoutError(timeout.seconds);
+    await sendTimeoutToSupervisor(comm, logs, timeout.seconds);
+    return timeout.wait(start());
+  };
+  const response =
+    task.kind === "handler"
+      ? await runHandler(details, task.fn, ctx, client, logs, runTimed)
+      : await runOperatorTask(details, task, ctx, client, logs, runTimed);
+  return { response, timedOut: timeout?.signal.aborted ?? false };

Review Comment:
   The timeout is spread across a nullable `timeout`, a `RunTimed` closure 
passed into both runners, and a `{ response, timedOut }` return that reaches 
into
   `timeout.signal.aborted`. Put this behind the `ExecutionTimeout` object and 
add a null object for "no timeout", so `handleTask` doesn't need any `timeout 
=== null` branches.



##########
ts-sdk/src/coordinator/runtime.ts:
##########
@@ -378,14 +427,21 @@ async function handleTask(
     return buildFailureResponse(details, message);
   };
   try {
-    switch (task.kind) {
-      case "operator":
-        return await runOperator(
-          task.operator,
-          buildOperatorContext({ details, dag: task.dag, ctx, client, logs, 
fail }),
-        );
-    }
+    return await runTimed(() =>
+      runOperator(
+        task.operator,
+        buildOperatorContext({ details, dag: task.dag, ctx, client, logs, fail 
}),
+      ),
+    );
   } catch (err) {
+    if (err instanceof TaskTimeoutError) {
+      logs.error("Task timed out", {
+        task_id: ctx.taskId,
+        error: err.message,
+        stack: err.stack ?? null,
+      });
+      return buildFailureResponse(details, err.message);
+    }

Review Comment:
   This and `runHandler` below both check `instanceof TaskTimeoutError` to pick 
the log line. Factor this out.



##########
ts-sdk/src/coordinator/runtime.ts:
##########
@@ -423,7 +480,11 @@ async function runHandler(
     // The scope is installed around the call, not awaited inside it: the store
     // follows the handler across every `await` it makes, so `getContext()` and
     // `getClient()` work at any depth without the handler being handed either.
-    const result = await runInTaskScope({ ctx, client }, () => 
handler(bound.args as never));
+    // A handler that times out never gets here, even if it returns: its result
+    // is not pushed, and the task fails with the timeout.

Review Comment:
   ```suggestion
   ```



##########
ts-sdk/src/coordinator/runtime.ts:
##########
@@ -361,15 +385,40 @@ async function handleTask(
       state: "removed",
       end_date: new Date().toISOString(),
     };
-    return response;
+    return { response, timedOut: false };
   }
 
-  const ctx = buildContext(details, signal);
+  const timeoutSeconds = executionTimeoutOf(details.ti_context);
+  const timeout = timeoutSeconds === null ? null : 
createExecutionTimeout(timeoutSeconds, signal);
+  // The task sees one signal: aborted by SIGTERM/SIGINT, or at its timeout.
+  const ctx = buildContext(details, timeout ? AbortSignal.any([signal, 
timeout.signal]) : signal);
   const client = createCoordinatorClient(comm, ctx, ti.id, clientLogs);
-  if (task.kind === "handler") {
-    return runHandler(details, task.fn, ctx, client, logs);
-  }
+  // Starts the task's work, its handler call or its operator, and waits for it
+  // under its execution_timeout, which counts from here. The order matters: a
+  // timeout that has already passed fails before the work starts, and the
+  // supervisor's deadline starts right before the work, as the runtime's does.
+  const runTimed: RunTimed = async (start) => {
+    if (timeout === null) return start();
+    if (timeout.seconds < 0) throw new TaskTimeoutError(timeout.seconds);

Review Comment:
   The user sees "Task timed out after -1 seconds". A better message should be 
possible.



##########
ts-sdk/src/coordinator/runtime.ts:
##########
@@ -215,6 +235,10 @@ export async function startCoordinator(
     await comm?.close();
     await logs?.close();
   }
+  // A task that timed out may have left work running that ignored its signal,
+  // which would keep the process alive. Its outcome is already reported, so 
end
+  // the process as it would end once that work finished.
+  if (timedOut) (opts.exitProcess ?? process.exit)(0);

Review Comment:
   If `sendSupervisorResponse` throws after a timeout, the `finally` runs but 
the exit is skipped. Move the exit into `finally` instead.



##########
ts-sdk/src/coordinator/execution-timeout.ts:
##########
@@ -0,0 +1,110 @@
+/*!
+ * 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.
+ */
+
+// A task's `execution_timeout`, enforced inside the runtime so the task can 
stop
+// at the timeout and fail with it. The supervisor keeps its own deadline for a
+// process that cannot stop itself, such as one stuck in a synchronous loop.
+
+import { TaskTimeoutError } from "../sdk/task.js";
+
+// setTimeout fires at once for a delay past this (about 24.8 days), so a 
longer
+// timeout re-arms the timer in steps of at most this.
+const MAX_TIMER_MS = 2 ** 31 - 1;
+
+// What the timer resolves with: no value a task returns can equal it.

Review Comment:
   ```suggestion
   ```
   
   A symbol is pretty self-explainatory.



##########
ts-sdk/src/coordinator/runtime.ts:
##########
@@ -361,15 +385,40 @@ async function handleTask(
       state: "removed",
       end_date: new Date().toISOString(),
     };
-    return response;
+    return { response, timedOut: false };
   }
 
-  const ctx = buildContext(details, signal);
+  const timeoutSeconds = executionTimeoutOf(details.ti_context);
+  const timeout = timeoutSeconds === null ? null : 
createExecutionTimeout(timeoutSeconds, signal);
+  // The task sees one signal: aborted by SIGTERM/SIGINT, or at its timeout.
+  const ctx = buildContext(details, timeout ? AbortSignal.any([signal, 
timeout.signal]) : signal);
   const client = createCoordinatorClient(comm, ctx, ti.id, clientLogs);
-  if (task.kind === "handler") {
-    return runHandler(details, task.fn, ctx, client, logs);
-  }
+  // Starts the task's work, its handler call or its operator, and waits for it
+  // under its execution_timeout, which counts from here. The order matters: a
+  // timeout that has already passed fails before the work starts, and the
+  // supervisor's deadline starts right before the work, as the runtime's does.

Review Comment:
   This can be shorter.



##########
ts-sdk/tests/coordinator/integration.test.ts:
##########
@@ -1890,4 +1895,243 @@ describe("coordinator runtime integration", () => {
       });
     });
   });
+
+  describe("execution timeout", () => {
+    /** A handler that waits for its signal, records why it fired, then 
rethrows that reason. */
+    function waitForAbort(seen: { reason?: unknown }): () => Promise<never> {
+      return () =>
+        new Promise((_, reject) => {
+          const { signal } = getContext();
+          signal.addEventListener("abort", () => {
+            seen.reason = signal.reason;
+            reject(signal.reason as Error);
+          });
+        });
+    }
+
+    it("aborts the signal at the timeout and fails for retry with the timeout 
as the reason", async () => {
+      const seen: { reason?: unknown } = {};
+      testDag.task("slow", waitForAbort(seen))();
+
+      const result = await driveSupervisor(
+        makeStartupDetails("slow", "test_dag", "r1", {
+          execution_timeout: 0.05,
+          should_retry: true,
+        }),
+      );
+
+      expect(seen.reason).toBeInstanceOf(TaskTimeoutError);
+      expect(result.firstResponse!.body).toMatchObject({
+        type: "RetryTask",
+        retry_reason: "Task timed out after 0.05 seconds",
+      });
+      expect(result.runtimeRequests).toEqual([
+        {
+          type: "SetExecutionTimeout",
+          body: expect.objectContaining({ timeout_seconds: 0.05 }) as unknown,
+        },
+      ]);
+      expect(result.logRecords.some((r) => r["event"] === "[ts-sdk.runtime] 
Task timed out")).toBe(
+        true,
+      );
+      // Its outcome is reported, so nothing the task left running keeps the 
process alive.
+      expect(result.exitCodes).toEqual([0]);
+    });
+
+    it("fails without retry when the task has none left", async () => {
+      testDag.task("slow", waitForAbort({}))();
+
+      const result = await driveSupervisor(
+        makeStartupDetails("slow", "test_dag", "r1", { execution_timeout: 0.05 
}),
+      );
+
+      expect(result.firstResponse!.body).toMatchObject({ type: "TaskState", 
state: "failed" });
+    });
+
+    it("does not let a handler that returns after the timeout succeed or push 
its result", async () => {
+      testDag.task("returns_late", async () => {
+        const { signal } = getContext();
+        await new Promise((resolve) => signal.addEventListener("abort", 
resolve));
+        return "too late";
+      })();
+
+      const result = await driveSupervisor(
+        makeStartupDetails("returns_late", "test_dag", "r1", {
+          execution_timeout: 0.05,
+          should_retry: true,
+        }),
+      );
+
+      expect(result.firstResponse!.body).toMatchObject({ type: "RetryTask" });
+      expect(requestsOf(result, "SetXCom")).toEqual([]);
+    });
+
+    it("succeeds as before when the handler finishes in time", async () => {
+      testDag.task("quick", async () => "fast")();
+
+      const result = await driveSupervisor(
+        makeStartupDetails("quick", "test_dag", "r1", { execution_timeout: 5 
}),
+      );
+
+      expect(result.firstResponse!.body).toMatchObject({ type: "SucceedTask" 
});
+      expect(result.runtimeRequests.map((r) => 
r.type)).toEqual(["SetExecutionTimeout", "SetXCom"]);
+      expect(result.exitCodes).toEqual([]);
+    });
+
+    it.each([
+      ["no", {}],
+      ["a zero", { execution_timeout: 0 }],
+    ])(
+      "neither times the handler nor sends the supervisor a timeout for %s 
timeout",
+      async (_, ctx) => {
+        let signal: AbortSignal | undefined;
+        testDag.task("untimed", async () => {
+          signal = getContext().signal;
+        })();
+
+        const result = await driveSupervisor(makeStartupDetails("untimed", 
"test_dag", "r1", ctx));
+
+        expect(result.firstResponse!.body).toMatchObject({ type: "SucceedTask" 
});
+        expect(result.runtimeRequests).toEqual([]);
+        expect(signal!.aborted).toBe(false);
+      },
+    );
+
+    it("fails a task whose timeout has already passed without running it", 
async () => {
+      let ran = false;
+      testDag.task("late_start", async () => {
+        ran = true;
+      })();
+
+      const result = await driveSupervisor(
+        makeStartupDetails("late_start", "test_dag", "r1", {
+          execution_timeout: -1,
+          should_retry: true,
+        }),
+      );
+
+      expect(ran).toBe(false);
+      expect(result.firstResponse!.body).toMatchObject({
+        type: "RetryTask",
+        retry_reason: "Task timed out after -1 seconds",
+      });
+    });
+
+    it("still enforces the timeout when the supervisor rejects 
SetExecutionTimeout", async () => {
+      testDag.task("slow", waitForAbort({}))();
+
+      const result = await driveSupervisor(
+        makeStartupDetails("slow", "test_dag", "r1", { execution_timeout: 0.05 
}),
+        (msgType) =>
+          msgType === "SetExecutionTimeout"
+            ? { body: { type: "ErrorResponse", error: "API_SERVER_ERROR" } }
+            : null,
+      );
+
+      expect(result.firstResponse!.body).toMatchObject({ type: "TaskState", 
state: "failed" });
+      expect(
+        result.logRecords.some(
+          (r) => r["event"] === "[ts-sdk.runtime] Supervisor did not take 
SetExecutionTimeout",
+        ),
+      ).toBe(true);
+    });
+
+    it("still enforces the timeout when SetExecutionTimeout cannot be sent", 
async () => {
+      const request = CommChannel.prototype.request;
+      vi.spyOn(CommChannel.prototype, "request").mockImplementation(function (
+        this: CommChannel,
+        body,
+        opts,
+      ) {
+        return (body as { type?: string }).type === "SetExecutionTimeout"
+          ? Promise.reject(new Error("Response timed out: no response"))
+          : request.call(this, body, opts);
+      });
+      testDag.task("slow", waitForAbort({}))();
+
+      const result = await driveSupervisor(
+        makeStartupDetails("slow", "test_dag", "r1", { execution_timeout: 0.05 
}),
+      );
+
+      expect(result.firstResponse!.body).toMatchObject({ type: "TaskState", 
state: "failed" });
+      expect(
+        result.logRecords.find(
+          (r) => r["event"] === "[ts-sdk.runtime] Could not send 
SetExecutionTimeout",
+        ),
+      ).toMatchObject({ error: "Response timed out: no response" });
+    });
+
+    it("reports the timeout at once when the supervisor's SIGTERM comes during 
cleanup", async () => {
+      testDag.task("ignores_signal", async () => {
+        // Past the timeout, as the supervisor's deadline would be, but long 
before
+        // the runtime's own cleanup wait would end.
+        setTimeout(() => process.emit("SIGTERM"), 100);
+        await new Promise((resolve) => setTimeout(resolve, 60_000).unref());
+      })();
+      const started = Date.now();
+
+      const result = await driveSupervisor(
+        makeStartupDetails("ignores_signal", "test_dag", "r1", {
+          execution_timeout: 0.05,
+          should_retry: true,
+        }),
+      );
+
+      expect(Date.now() - started).toBeLessThan(5000);
+      expect(result.firstResponse!.body).toMatchObject({
+        type: "RetryTask",
+        retry_reason: "Task timed out after 0.05 seconds",
+      }); // The handler is still waiting, but the process does not wait for 
it.

Review Comment:
   This comment does not work here. Misplaced by formatter?



##########
ts-sdk/src/coordinator/runtime.ts:
##########
@@ -75,6 +87,8 @@ export interface StartCoordinatorOptions {
   logsAddr?: string;
   /** Source argv. Defaults to `process.argv`. */
   argv?: readonly string[];
+  /** Ends the process after a task times out. Defaults to `process.exit`; 
tests replace it. */
+  exitProcess?: (code: number) => void;

Review Comment:
   This does not match `exitProcess` on RuntimeAbortOptions. Not a giant deal 
(they are distinct interfaces), but there’s no reason to differ.



##########
airflow-core/docs/authoring-and-scheduling/language-sdks/typescript.rst:
##########
@@ -567,6 +567,13 @@ A value the handler returns becomes the task's 
``return_value`` XCom, as with Py
 downstream task receives. An uncaught exception or a rejected promise fails 
the task, and retries it if the task
 has retries.
 
+When a task's ``executionTimeout`` passes, ``signal`` is aborted with a 
``TaskTimeoutError`` as its ``reason``. The
+handler then has until Airflow sends SIGTERM, ``killed_task_cleanup_time`` 
after the timeout, to finish. When it

Review Comment:
   Either link to the config reference, or at least spell out the full 
configuration ``[core] killed_task_cleanup_time``.



-- 
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