dabla commented on code in PR #62922: URL: https://github.com/apache/airflow/pull/62922#discussion_r4750735076
########## task-sdk/src/airflow/sdk/definitions/iterableoperator.py: ########## @@ -0,0 +1,1895 @@ +# +# 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 asyncio +import copy +import itertools +import os +import threading +import time +from collections import OrderedDict +from collections.abc import ( + AsyncIterator, + Awaitable, + Callable, + Generator, + Iterable, + Iterator, + Mapping, + Sequence, +) +from contextlib import AbstractContextManager, contextmanager +from dataclasses import dataclass +from functools import partial, wraps +from typing import TYPE_CHECKING, Any, ClassVar, TypeVar + +from airflow.sdk import BaseXCom, TaskInstanceState, TriggerRule +from airflow.sdk.bases.operator import BaseOperator, event_loop +from airflow.sdk.bases.skipmixin import SkipMixin +from airflow.sdk.bases.xcom import XComIterable, build_own_coordinate +from airflow.sdk.definitions._internal.fingerprint import InputFingerprint +from airflow.sdk.definitions._internal.mixins import ResolveMixin +from airflow.sdk.definitions.param import process_params +from airflow.sdk.definitions.retry_policy import RetryAction, RetryDecision +from airflow.sdk.definitions.xcom_arg import XComArg +from airflow.sdk.exceptions import ( + AirflowFailException, + AirflowRescheduleException, + AirflowSensorTimeout, + AirflowSkipException, + AirflowTaskTerminated, + AirflowTaskTimeout, + DagRunTriggerException, + DownstreamTasksSkipped, + TaskDeferred, +) +from airflow.sdk.execution_time.context import build_asset_context +from airflow.sdk.execution_time.executor import AsyncAwareExecutor +from airflow.sdk.execution_time.task_runner import ( + CheckpointDeserializationError, + IndexedTaskInstance, + IndexedTaskRunner, + IndexedTaskState, + _push_xcom_if_needed, +) + +if TYPE_CHECKING: + import jinja2 + + from airflow.sdk.definitions._internal.abstractoperator import AbstractOperator + from airflow.sdk.definitions._internal.expandinput import ExpandInput, Resolved + from airflow.sdk.definitions.context import Context + from airflow.sdk.definitions.mappedoperator import MappedOperator + from airflow.sdk.execution_time.context import TaskStateStoreAccessor + from airflow.sdk.execution_time.task_runner import RuntimeTaskInstance + from airflow.sdk.types import Logger + + +# The outcome an indexed task's step returns, kept as it is by keeps_failure_to_its_indexed_task: None is +# the replay's "no checkpoint, run the indexed task". +Outcome = TypeVar("Outcome", bound="IndexedTaskOutcome | None") + +# The trigger rules under which one skipped upstream task instance skips a task, whatever the other +# upstream task instances did (see TriggerRuleDep). A skipped iteration has the same effect on a +# downstream task with one of these rules as a skipped mapped task instance would. +SKIPPED_WITH_A_SKIPPED_UPSTREAM = frozenset( + {TriggerRule.ALL_SUCCESS, TriggerRule.NONE_SKIPPED, TriggerRule.ALL_DONE_MIN_ONE_SUCCESS} +) + + +# Raised by an indexed task, these fail the task without a retry, as the runner does for a task that raises +# them itself (see _run_task_and_map_outcome and _handle_handler_failure). +FAIL_WITHOUT_RETRY = (AirflowFailException, AirflowSensorTimeout, AirflowTaskTerminated) + + +def _retryable(exception: BaseException) -> bool: + """Whether ``exception`` is a failure the runner may retry, judged member by member for a group.""" + match exception: + case BaseExceptionGroup(): + return all(_retryable(exc) for exc in exception.exceptions) + # The classes of FAIL_WITHOUT_RETRY: a class pattern cannot take the tuple. + case AirflowFailException() | AirflowSensorTimeout() | AirflowTaskTerminated(): + return False + case Exception() | AirflowTaskTimeout(): + return True + case _: + return False + + +@dataclass(frozen=True) +class IndexedTaskOutcome: + """ + How one indexed task ended: what it returned, or what it raised. + + Every step of :class:`IndexedTaskLifecycle` ends with one, and :meth:`IndexedTaskOutcomes.record` + takes it. ``task`` is an :class:`UnreadIndex` when the index's input could not be read. + """ + + task: IndexedTaskInstance | UnreadIndex + result: Any = None + exception: BaseException | None = None + + def fail_fast(self) -> AirflowFailException | None: + """ + Return the failure that ends the task at once for an outcome the iteration cannot carry. + + An indexed task is not a task instance of its own: it cannot defer, reschedule, trigger a + DAG run or skip downstream tasks, and a ``BaseException`` that is no ``Exception`` + (``KeyboardInterrupt``, ``SystemExit``) must never be swallowed into a retry. Each of these + fails the whole task without a retry, with a message saying why. Any other exception, an + ``AirflowTaskTimeout`` the operator raised itself included, is the indexed task's own + failure, which :meth:`IndexedTaskOutcomes.record` collects. + """ + indexed_task_name = f"Indexed task {self.task.task_id}[{self.task.index}]" + match self.exception: + case TaskDeferred(): + return AirflowFailException( + f"{indexed_task_name} attempted to defer. Deferrable operators are not supported " + "inside IterableOperator." + ) + case DagRunTriggerException() | DownstreamTasksSkipped(): + return AirflowFailException( + f"{indexed_task_name} raised {type(self.exception).__name__}. Triggering DAG runs " + "(TriggerDagRunOperator) and skipping downstream tasks (ShortCircuitOperator and " + "similar) are not supported inside IterableOperator: an indexed task has no " + "downstream tasks or DAG run of its own for the effect to apply to." + ) + case AirflowRescheduleException(): + return AirflowFailException( + f"{indexed_task_name} attempted to reschedule (raised AirflowRescheduleException). " + "Reschedule-mode sensors are not supported inside IterableOperator: an indexed " + "task has no task instance of its own to reschedule." + ) + case None | Exception() | AirflowTaskTimeout(): + # An AirflowTaskTimeout here is the operator's own, raised off the main thread (the + # parent's never gets here, IndexedTaskLifecycle.run re-raises it), and the runner + # judges it as it does for a plain task that raises it: a failure it retries. + return None + case _: + return AirflowFailException( + f"{indexed_task_name} raised a non-Exception BaseException: " + f"{type(self.exception).__name__}: {self.exception}" + ) + + +def keeps_failure_to_its_indexed_task( + step: Callable[..., Awaitable[Outcome]], +) -> Callable[..., Awaitable[Outcome | IndexedTaskOutcome]]: + """ + Make what an indexed task's step raises that indexed task's outcome, not the end of the task. + + ``step`` is a coroutine method of :class:`IndexedTaskLifecycle`, whose ``task`` the outcome is. + Whatever it raises, a ``BaseException`` included, is returned as that task's + :class:`IndexedTaskOutcome`: the siblings go on, the run counts it with the other outcomes, and a + non-``Exception`` still fails the task at once (see :meth:`IndexedTaskOutcome.fail_fast`). A + cancellation and the parent's ``execution_timeout`` are not the step's outcome and go on unchanged. + """ + + @wraps(step) + async def kept(self: IndexedTaskLifecycle, *args: Any, **kwargs: Any) -> Outcome | IndexedTaskOutcome: + try: + return await step(self, *args, **kwargs) + except (asyncio.CancelledError, AirflowTaskTimeout): + raise + except BaseException as e: + return IndexedTaskOutcome(self.task, exception=e) + + return kept + + +@dataclass(frozen=True) +class CheckpointBatch: + """ + The serialized outcomes of indexed tasks, by index, that one store key holds. + + Batches are numbered in the order they are written, and the number names the key. + """ + + # The task state store is already scoped to the parent task instance (dag, run, task and map + # index), so the key carries no identity, only a namespace that keeps the operator's own entries + # apart from anything user code stores from inside an indexed task (see + # IndexedTaskStateStoreAccessor.RESERVED_PREFIX). + KEY_PREFIX: ClassVar[str] = "_iterable_batch_" + + number: int + # As stored: IndexedTaskState.deserialize restores an entry, and takes one that is not a + # checkpoint for none. + outcomes: Mapping[int, Any] + + @classmethod + def read(cls, store: TaskStateStoreAccessor, number: int) -> CheckpointBatch | None: + """Read the batch numbered ``number``, or None when it is missing or not a batch.""" + return cls._of(number, store.get(f"{cls.KEY_PREFIX}{number}")) + + @classmethod + async def aread(cls, store: TaskStateStoreAccessor, number: int) -> CheckpointBatch | None: + """:meth:`read` from inside the event loop, where the synchronous store call would block it.""" + return cls._of(number, await store.aget(f"{cls.KEY_PREFIX}{number}")) + + @classmethod + def _of(cls, number: int, value: Any) -> CheckpointBatch | None: + if not isinstance(value, Mapping): + return None + try: + return cls(number, {int(index): raw for index, raw in value.items()}) + except (TypeError, ValueError): + return None + + @property + def key(self) -> str: + return f"{self.KEY_PREFIX}{self.number}" + + def to_value(self) -> dict[str, Any]: + """Return the value to store: a JSON object, whose keys are strings.""" + return {str(index): raw for index, raw in self.outcomes.items()} + + def __len__(self) -> int: + return len(self.outcomes) + + +class PendingCheckpoints: + """The outcomes of indexed tasks recorded since the last batch was written, by index.""" + + def __init__(self) -> None: + self._outcomes: dict[int, dict[str, Any]] = {} + + def __len__(self) -> int: + return len(self._outcomes) + + def add(self, index: int, state: IndexedTaskState) -> None: + self._outcomes[index] = state.serialize() + + def batch(self, number: int) -> CheckpointBatch: + """Return the outcomes pending now as the batch to write under ``number``.""" + return CheckpointBatch(number, dict(self._outcomes)) + + def remove(self, written: CheckpointBatch) -> None: + """Drop the outcomes ``written`` holds, but not one recorded again while it was written.""" + for index, raw in written.outcomes.items(): + if self._outcomes.get(index) is raw: + del self._outcomes[index] + + +class EarlierCheckpoints: + """ + The checkpoints earlier attempts of the task instance left, read once when an attempt starts. + + The batches are read in order until the first missing or unreadable one, the latest entry of an + index winning: an index run again after a clear appears in several. + + The values a checkpoint carries (the result and the other pushed XComs) are not kept from that + read: on a large input they are the whole dataset, gigabytes a retry would hold for its full + length. An entry without values is kept as it is; for one with values only the number of its + batch is, and the batch is fetched again when one of its indexed tasks is replayed. The last + :attr:`CACHED_BATCHES` batches fetched stay in memory: batches follow completion order and the + indexed tasks are replayed about in index order, so each batch is fetched about once. A retry + therefore holds :attr:`CACHED_BATCHES` batches plus the indexed tasks in flight, not the dataset. + """ + + #: How many fetched batches stay in memory while their indexed tasks are replayed. Two are enough + #: for the indexed tasks in flight to straddle a batch boundary without fetching a batch twice; + #: each batch more costs a batch of memory and saves no read. + CACHED_BATCHES: ClassVar[int] = 2 + + def __init__(self) -> None: + self._store: TaskStateStoreAccessor | None = None + # The entries without values, as stored. + self._entries: dict[int, Any] = {} + # The batch number of the entries with values. + self._batch_numbers: dict[int, int] = {} + self._cached: OrderedDict[int, Mapping[int, Any]] = OrderedDict() + # A fetch in flight per batch number, which the indexed tasks replayed meanwhile await + # instead of fetching the batch again. + self._fetches: dict[int, asyncio.Future[Mapping[int, Any]]] = {} + #: How many batches were read, which is the number the next batch gets. + self.count = 0 + + def read(self, store: TaskStateStoreAccessor) -> None: + self._store = store + while (batch := CheckpointBatch.read(store, self.count)) is not None: + for index, raw in batch.outcomes.items(): + if IndexedTaskState.holds_values(raw): + self._batch_numbers[index] = batch.number + self._entries.pop(index, None) + else: + self._entries[index] = raw + self._batch_numbers.pop(index, None) + self.count += 1 + + async def state_of(self, index: int) -> IndexedTaskState | None: + """ + Return the checkpoint of ``index``, or None when it has none. + + A checkpoint with values is fetched with its batch; a batch gone since it was read (expired) + leaves the indexed task without a checkpoint, so it runs again. Raises + :class:`CheckpointDeserializationError` when the checkpoint cannot be restored. + """ + if (number := self._batch_numbers.get(index)) is None: + return IndexedTaskState.deserialize(self._entries.get(index)) + return IndexedTaskState.deserialize((await self._outcomes_of(number)).get(index)) + + async def _outcomes_of(self, number: int) -> Mapping[int, Any]: + if (outcomes := self._cached.get(number)) is not None: + self._cached.move_to_end(number) + return outcomes + fetch = self._fetches.get(number) + # A fetch of an earlier pass, whose event loop has closed since (a kill or a deferral during + # the fetch), is never awaited from this one. + if fetch is None or fetch.get_loop() is not asyncio.get_running_loop(): + fetch = self._fetches[number] = asyncio.ensure_future(self._fetch(number)) + fetch.add_done_callback( + lambda done: self._fetches.pop(number, None) if self._fetches.get(number) is done else None + ) + # Shielded: an indexed task cancelled while it waits does not cancel the fetch the others + # wait for. + return await asyncio.shield(fetch) + + async def _fetch(self, number: int) -> Mapping[int, Any]: + if self._store is None: + raise RuntimeError("EarlierCheckpoints.read() must run before a checkpoint is fetched") + batch = await CheckpointBatch.aread(self._store, number) + outcomes = batch.outcomes if batch is not None else {} + self._cached[number] = outcomes + while len(self._cached) > self.CACHED_BATCHES: + self._cached.popitem(last=False) + return outcomes + + +class CheckpointBatches: + """ + Write the checkpoints of a run's indexed tasks a round at a time. + + One key per indexed task would cost one task state store request per index, each through the + supervisor to the API server, and a run over a large input floods both. An indexed task's outcome is + kept pending instead, and the pending outcomes are written as one key, ``_iterable_batch_<n>``, once + they make a round: as many as indexed tasks run at once (``round_size``). Rounds follow completion + order, as the indexed tasks finish in any order, so a slow indexed task holds back no outcome but its + own. What is left when the run's event loop has closed is written by :meth:`flush`, before the + completion marker (see :class:`Checkpoints`). + + The batches are numbered on from the ones earlier attempts left (:meth:`start_at`), so an attempt + never overwrites a batch that was not read. A write that fails keeps its outcomes for the next one, + and one that fails at the end is logged. A hard kill loses the outcomes not written yet, a round at + most unless a write failed before it: those indexed tasks run again on the retry, and as they were + reported when they finished, their success callbacks fire again. + """ + + def __init__(self, store: TaskStateStoreAccessor, *, round_size: int, log: Logger) -> None: + self._store = store + self._round_size = max(round_size, 1) + self._log = log + self._number = 0 + self._pending = PendingCheckpoints() + # Raised by the size of a write that failed, so the next attempt waits for a round more. + self._threshold = self._round_size + # Bound to the run's event loop when first used, as asyncio's primitives are. + self._lock = asyncio.Lock() + + def start_at(self, number: int) -> None: + """Start numbering this attempt's batches at ``number``, after the ones earlier attempts left.""" + self._number = number + + async def add(self, index: int, state: IndexedTaskState) -> None: + """Keep an indexed task's outcome pending, and write the round once it is full.""" + self._pending.add(index, state) + if len(self._pending) >= self._threshold: + await self._write_round() + + async def _write_round(self) -> None: + async with self._lock: + # Another indexed task may have written the round while this one waited for the lock. + if len(self._pending) < self._threshold: + return + batch = self._pending.batch(self._number) + try: + await self._store.aset(batch.key, batch.to_value()) + except Exception: + self._threshold = len(batch) + self._round_size + self._log.warning( + "Could not write the checkpoints of %d indexed tasks, kept for the next write", + len(batch), + exc_info=True, + ) + return + self._written(batch) + + @contextmanager + def flushed(self) -> Generator[None]: + """ + Write the outcomes left when the block ends, however it ends. + + Entered before the run's event loop, so it exits after the loop closed (see :meth:`flush`). + """ + try: + yield + finally: + self.flush() + + def flush(self) -> None: + """ + Write the outcomes left, with the synchronous store call. + + Called once the run's event loop has closed, so no asynchronous call of an indexed task is in + flight, where :class:`Checkpoints` also writes its marker. A write that fails is logged: those + indexed tasks run again on a retry. + """ + if not self._pending: + return + batch = self._pending.batch(self._number) + try: + self._store.set(batch.key, batch.to_value()) + except Exception: + self._log.exception( + "Could not write the checkpoints of %d indexed tasks: a retry runs them again", len(batch) + ) + return + self._written(batch) + + def _written(self, batch: CheckpointBatch) -> None: + self._number += 1 + self._threshold = self._round_size + self._pending.remove(batch) + + +class Checkpoints: + """ + Decide whether one attempt of an IterableOperator may resume from its indexed tasks' checkpoints. + + Checkpoints are only consulted from the second attempt onwards. A completion marker left by a + previous attempt whose iterations all finished means this attempt follows a manual clear when + ``max_tries`` changed since: a clear sets it to ``try_number + retries``, a retry leaves it + alone, and it can go down when the retries were lowered, so any change counts. Every index then + runs again: the stale ``SUCCESS`` checkpoints are ignored, and the rerun's outcomes are written in + batches after them, where the latest entry of an index wins. With ``max_tries`` + unchanged, the iterations finished but the task failed afterwards (the worker died, or + ``post_execute`` or the result push failed), and this retry resumes from the checkpoints that + attempt could trust; only a clear that leaves ``max_tries`` exactly as it was (the retries + lowered by as many attempts as ran since) is taken for such a retry. A marker without + ``max_tries`` counts as a clear. On entry after a clear the marker is replaced by the + attempt the rerun starts at, so that a crash during the rerun resumes from the checkpoints + written since, and only from those: an index the crashed rerun did not reach still holds its + checkpoint from before the clear, which must not be replayed. The marker is written again when + the block exits without an exception, and when every iteration skipped: the task is then + ``SKIPPED``, a final state, and a clear of it must run every iteration again rather than + replay the skips, as a cleared mapped task instance would. An attempt that fails, even with + some iterations skipped, writes no marker, so a retry, or a clear that keeps the task state, + resumes after it: iterations that succeeded or skipped keep that outcome and only the others + run again. A Dag run clear keeps the task state; a task instance clear discards it unless + ``keep_task_state`` is set, and then finds neither marker nor checkpoints, so every iteration + runs again. + + The outcomes are written a round of ``task_concurrency`` at a time (see :class:`CheckpointBatches`), + each round as one ``_iterable_batch_<n>`` key in the ``task_state_store`` table, or behind a + reference with a ``[workers] state_store_backend``: a run makes about ``input length / + task_concurrency`` writes, and a retry about as many reads, instead of one per index, plus one + more per batch whose values it replays (see :class:`EarlierCheckpoints`). The marker + is written after the last batch. A last batch that cannot be written is logged and the marker still + written: the attempt's indexed tasks did finish, and on a retry those without a checkpoint run + again, as they would without the marker. + + The checkpoints themselves are never deleted: one marker write costs the same whatever the indexed + task count, and the store is scoped to the parent task instance, so state an indexed task stored for + itself is never touched. They expire with the store's default retention (``[state_store] + default_retention_days``, 30 days unless configured, 0 disables expiry), which also bounds how + long a task that exhausted its retries keeps them. Keeping them until then is intended: a manual + clear of such a task resumes from the checkpoints instead of re-running every index, and the + marker is what tells a clear-after-success apart from that. Batches expire one by one, so a + clear after that retention may find the earlier ones gone and the later ones not: the reading then + stops at the first one missing, and the indexed tasks it does not cover run again. + """ + + # Same namespace as CheckpointBatch.KEY_PREFIX, for the same reason. + COMPLETION_KEY = "_iterable_completed" + + def __init__(self, context: Context, *, round_size: int, log: Logger) -> None: + self._store = context["task_state_store"] + self._try_number = context["ti"].try_number + self._max_tries = context["ti"].max_tries + self.trust_checkpoints = False + # The attempt from which checkpoints may be resumed; older ones predate a manual clear. + self.since = 0 + self.earlier = EarlierCheckpoints() + self.batches = CheckpointBatches(self._store, round_size=round_size, log=log) + + def __enter__(self) -> Checkpoints: + if self._try_number > 1: + # Read after a clear too: this attempt writes its batches after the ones there. + self.earlier.read(self._store) + self.batches.start_at(self.earlier.count) + marker = self._store.get(self.COMPLETION_KEY) + if ( + isinstance(marker, Mapping) + and marker.get("completed") + and marker.get("max_tries") != self._max_tries + ): + self.since = self._try_number + self._store.set(self.COMPLETION_KEY, {"completed": False, "since": self.since}) + else: + self.trust_checkpoints = True + since = marker.get("since") if isinstance(marker, Mapping) else None + if isinstance(since, int): + self.since = since + return self + + def __exit__(self, exc_type, exc_value, traceback) -> None: + # The outcomes left first, also after a failure: a retry resumes from them, and the marker + # comes after them. + self.batches.flush() + if exc_type is None or issubclass(exc_type, AirflowSkipException): + self._store.set( + self.COMPLETION_KEY, + { + "completed": True, + "try_number": self._try_number, + "max_tries": self._max_tries, + "since": self.since, + }, + ) + + def trusts(self, checkpoint: IndexedTaskState, input_fingerprint: str | None) -> bool: + """ + Whether an indexed task's ``checkpoint`` may settle it: written since the last clear, for its input. + + A checkpoint from before a clear (an older ``try_number`` than :attr:`since`) or for another + input (another ``input_fingerprint``) is not trusted. + """ + return checkpoint.try_number >= self.since and checkpoint.fingerprint == input_fingerprint + + async def read(self, task: IndexedTaskInstance) -> IndexedTaskState | None: + """Return the checkpoint an earlier attempt left for ``task`` (see :class:`EarlierCheckpoints`).""" + return await self.earlier.state_of(task.index) + + async def record(self, task: IndexedTaskInstance, state: IndexedTaskState) -> None: + """Record ``task``'s outcome; it is written with its round (see :class:`CheckpointBatches`).""" + await self.batches.add(task.index, state) + + def flushed(self) -> AbstractContextManager[None]: + """Write the outcomes left when the run's event loop closed (see :meth:`CheckpointBatches.flushed`).""" + return self.batches.flushed() + + +class IndexedTaskInstanceNotStarted(Exception): + """ + The outcome of an indexed task instance pulled before a kill and reached after it. + + Never raised: :meth:`IndexedTaskLifecycle.run` returns it as the instance's outcome, so that + :meth:`IndexedTaskOutcomes.record` counts it apart from the failures. It ran no code, wrote + no checkpoint and fires no callback; the next attempt runs it. + """ + + +@dataclass(frozen=True) +class UnreadIndex: + """ + An index whose input could not be read or rendered, in place of its indexed task instance. + + A ``.map()`` callable runs, and template fields are rendered, when an index is read: what + they raise is that index's outcome, as it is the mapped task instance's under ``.expand()``. + A skip leaves the index out of the result, anything else fails it, and the siblings go on. + No operator was created for it, so unlike a mapped task instance it fires no callback; nor + does it write a checkpoint, so the next attempt reads its input again. + """ + + task_id: str + index: int + + +class IterationState: + """ + What a kill of one run of an iterated task must reach, kept apart from the operator's configuration. + + It holds the indexed operators in flight and those already killed, so that + :meth:`IterableOperator.on_kill` reaches each one once; the stop flag a kill sets, which the + executor consults before starting the next indexed task; and the threads the indexed operators + are killed from. The rest of what a run holds is :class:`IterationRun`'s, which only exists while + the run goes; this exists before it, so that a kill that arrives first still stops the run. + + A copy of the operator (``copy.copy`` in ``prepare_for_execution``, the deep copy of + ``dag.partial_subset``) is another task with nothing in flight and no kill pending, so copying + the state gives a fresh one. The + operator renews it once a run ended, not when one starts: a rerun in the same process starts + clean, while a kill that arrives before the run sets the stop flag on the state the run uses. + """ + + def __init__(self, log: Logger) -> None: + # Keyed by identity: BaseOperator equality compares fields such as task_id, which every + # indexed operator of one iterated task shares, so a set would hold one of them at most. + self._in_flight: dict[int, BaseOperator] = {} + self._lock = threading.Lock() + # The runner calls on_kill() again after the execution timeout that made the run call + # it first, and an indexed operator is killed once. + self._killed: set[int] = set() + # A plain flag and a plain list, not an Event and not guarded by the lock: on_kill() runs in + # the runner's SIGTERM handler, on the main thread, between two bytecodes of whatever the + # loop thread was doing, register() or unregister() under the lock included. A lock the + # handler takes that its own thread holds would hang it, so request_stop() and start_kill() + # take none; take_in_flight() is called from the kill thread instead. + self._stop_requested = False + # The threads on_kill() started to kill the indexed operators in flight; see await_kill. + self._kill_threads: list[threading.Thread] = [] + #: The iterated task's logger, which :meth:`kill` reports an ``on_kill`` failure to. + self._log = log + + def __copy__(self) -> IterationState: + return IterationState(self._log) + + def __deepcopy__(self, memo: dict[int, Any]) -> IterationState: + return IterationState(self._log) + + def register(self, operator: BaseOperator) -> None: + """Note that ``operator`` is executing, so a kill reaches it.""" + with self._lock: + self._in_flight[id(operator)] = operator + + def unregister(self, operator: BaseOperator) -> None: + """Note that ``operator`` is done, one way or another.""" + with self._lock: + self._in_flight.pop(id(operator), None) + + def __contains__(self, operator: object) -> bool: + with self._lock: + return id(operator) in self._in_flight + + def take_in_flight(self) -> list[BaseOperator]: + """Return the indexed operators in flight that were not handed out before, and mark them killed.""" + with self._lock: + operators = [op for key, op in self._in_flight.items() if key not in self._killed] + self._killed.update(map(id, operators)) + return operators + + def request_stop(self) -> None: + """Ask the iteration to start nothing else; see :meth:`stop_requested`. Takes no lock.""" + self._stop_requested = True + + def start_kill(self, kill: Callable[[], None]) -> None: + """ + Run ``kill`` in a thread of its own, kept so that :meth:`await_kill` can wait for it. + + Takes no lock, so it can be called from a signal handler; ``kill`` takes the indexed operators + in flight itself, with :meth:`take_in_flight`, on its thread. + """ + thread = threading.Thread(target=kill, name="iterable-operator-on-kill", daemon=True) + self._kill_threads.append(thread) + thread.start() Review Comment: A follow-up on this one: I replaced the 50 ms polling in 36f14c2636. `on_kill()` now puts the request on a `queue.SimpleQueue`, whose `put()` is documented as reentrant and so safe in a handler that interrupts its own thread, and the killer thread blocks on `get()`. So the thread no longer wakes up while nothing happens, and a kill starts at once instead of after up to 50 ms. The handler still starts no thread: the test that makes `Thread.start` fail under the state's lock passes unchanged, and a probe with a real SIGTERM while the main thread holds that lock killed each operator exactly once in 10 runs. -- 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]
