diff --git a/airflow-core/docs/administration-and-deployment/dag-bundles.rst b/airflow-core/docs/administration-and-deployment/dag-bundles.rst index a6aa833df784..08f73d376a4f 100644 --- a/airflow-core/docs/administration-and-deployment/dag-bundles.rst +++ b/airflow-core/docs/administration-and-deployment/dag-bundles.rst @@ -276,6 +276,15 @@ Some caveats: files it listed before, from the refreshed source; if only recording the refresh fails, it parses the bundle's current files. In both cases it retries the refresh after the bundle's :ref:`config:dag_processor__refresh_interval`, or sooner when a reparse is requested. + When the Dag processor publishes its results through the Execution API, a failed listing instead + pauses the bundle's parsing until a listing succeeds. The processor retries after about one + :ref:`config:dag_processor__bundle_refresh_check_interval` and doubles the wait after each further + failure, up to the bundle's ``refresh_interval``. A successful listing resets the wait. + Parsing also stays paused until the API server accepts the new listing. While the server cannot + be reached or answers 408, 429 or a 5xx error, the processor sends it again with a backoff of up to + :ref:`config:workers__execution_api_retry_wait_max`. If the listing is too large to send, or the + server rejects it as too large, the processor waits for the bundle's ``refresh_interval`` before + refreshing and listing it again. * A new version does not mean the new Dags are running, because bundles are refreshed before their Dags are parsed. * The version and the import-error count together cannot confirm that a particular commit parsed, diff --git a/airflow-core/src/airflow/dag_processing/api_client.py b/airflow-core/src/airflow/dag_processing/api_client.py index 673c1353ae1e..b2c3007b046a 100644 --- a/airflow-core/src/airflow/dag_processing/api_client.py +++ b/airflow-core/src/airflow/dag_processing/api_client.py @@ -26,12 +26,20 @@ from pathlib import Path from time import monotonic from typing import Any +from urllib.parse import quote from uuid import UUID import httpx2 import structlog from uuid6 import uuid7 +from airflow.api_fastapi.execution_api.datamodels.dag_parsing import ( + DagBundleInventoryBody, + DagBundleInventoryResponse, + DagBundleStateResponse, + DagParseResultBody, + DagParseResultResponse, +) from airflow.api_fastapi.execution_api.datamodels.job import ( DagParseTokenBody, DagParseTokenResponse, @@ -82,6 +90,21 @@ def get_error_reason(error: httpx2.HTTPStatusError) -> str | None: return detail.get("reason") if isinstance(detail, dict) else None +def is_transient_api_error(error: BaseException) -> bool: + """Whether resending a failed Execution API request may succeed: no response, or 408, 429 or 5xx.""" + if isinstance(error, httpx2.HTTPStatusError): + status_code = error.response.status_code + return status_code in (408, 429) or status_code >= 500 + return isinstance(error, httpx2.RequestError) + + +def _is_retryable_at_once(error: BaseException) -> bool: + """Whether the Task SDK would retry the failure, unless it timed out, which a resend at once would repeat.""" + if isinstance(error, httpx2.HTTPStatusError): + return error.response.status_code >= 500 + return isinstance(error, httpx2.RequestError) and not isinstance(error, httpx2.TimeoutException) + + class DagProcessorAPIClient(Client): """ Register one processor process and use its Job token for subsequent API requests. @@ -131,6 +154,7 @@ def __init__( self._restart_required = False self._bundle_context: ContextVar[str | None] = ContextVar("dag_processor_bundle", default=None) self._parse_context: ContextVar[DagParseContext | None] = ContextVar("dag_parse", default=None) + self._retry_without_waiting: ContextVar[bool] = ContextVar("dag_processor_retry", default=False) self._job_id: int | None = None self._completion_state: TerminalJobState | None = None self._completed = False @@ -168,14 +192,27 @@ def use_parse(self, context: DagParseContext) -> Iterator[DagProcessorAPIClient] finally: self._parse_context.reset(selected) - def _get_parse_token(self, context: DagParseContext, *, retry: bool) -> str: + @contextmanager + def use_immediate_retries(self) -> Iterator[DagProcessorAPIClient]: + """ + Replace the Task SDK's waiting retries for manager requests with one immediate retry. + + A timed-out request is not retried, so a hanging API holds the caller for one timeout. + """ + selected = self._retry_without_waiting.set(True) + try: + yield self + finally: + self._retry_without_waiting.reset(selected) + + def _get_parse_token(self, context: DagParseContext, *, retry: bool, timeout: httpx2.Timeout) -> str: if context.token is not None and monotonic() < context.expires_at: if monotonic() < context.renew_at: return context.token try: self._exchange_parse_token(context, retry=False, timeout=self._get_bounded_timeout()) except (httpx2.HTTPError, ValueError) as error: - if isinstance(error, httpx2.HTTPStatusError) and error.response.status_code < 500: + if isinstance(error, httpx2.HTTPStatusError) and not is_transient_api_error(error): raise context.renew_at = monotonic() + 30 log.warning( @@ -186,12 +223,12 @@ def _get_parse_token(self, context: DagParseContext, *, retry: bool) -> str: ) if monotonic() < context.expires_at: return context.token - return self._exchange_parse_token(context, retry=retry) + return self._exchange_parse_token(context, retry=retry, timeout=timeout) def _exchange_parse_token( self, context: DagParseContext, *, retry: bool, timeout: httpx2.Timeout | None = None ) -> str: - self._ensure_job_token(retry=retry) + self._ensure_job_token(retry=retry, timeout=timeout) started_at = monotonic() response = super().request( "POST", @@ -304,10 +341,18 @@ def _get_bounded_timeout(self) -> httpx2.Timeout: } ) - def _ensure_job_token(self, *, retry: bool) -> None: + def _get_response_timeout(self) -> httpx2.Timeout: + """Fail fast while the API is unreachable, but let a slow read or write complete.""" + bounded = self._get_bounded_timeout() + return httpx2.Timeout( + connect=bounded.connect, read=self.timeout.read, write=self.timeout.write, pool=bounded.pool + ) + + def _ensure_job_token(self, *, retry: bool, timeout: httpx2.Timeout | None = None) -> None: self._require_job_id() + timeout = timeout or (None if retry else self._get_bounded_timeout()) if monotonic() >= self._expires_at: - self._register_job(retry=retry, timeout=None if retry else self._get_bounded_timeout()) + self._register_job(retry=retry, timeout=timeout) return if self.restart_required or monotonic() < self._retry_renewal_at: return @@ -324,15 +369,21 @@ def _ensure_job_token(self, *, retry: bool) -> None: restart_required=self.restart_required, ) if monotonic() >= self._expires_at: - self._register_job(retry=retry, timeout=None if retry else self._get_bounded_timeout()) + self._register_job(retry=retry, timeout=timeout) def request(self, *args, retry: bool = True, **kwargs) -> httpx2.Response: """Use a parsing credential for subprocess requests, and the Job credential for manager work.""" self._check_can_run() + retry_at_once = retry and self._retry_without_waiting.get() + retry = retry and not retry_at_once try: headers = httpx2.Headers(kwargs.get("headers")) if context := self._parse_context.get(): - kwargs["auth"] = BearerAuth(self._get_parse_token(context, retry=retry)) + # Avoid retry sleeps on the manager loop; required credentials use the runtime request's timeout. + retry = retry_at_once = False + timeout = kwargs.get("timeout", httpx2.USE_CLIENT_DEFAULT) + timeout = self.timeout if timeout is httpx2.USE_CLIENT_DEFAULT else httpx2.Timeout(timeout) + kwargs["auth"] = BearerAuth(self._get_parse_token(context, retry=retry, timeout=timeout)) headers["Airflow-Dag-Bundle"] = context.request.bundle_name else: self._ensure_job_token(retry=retry) @@ -341,7 +392,15 @@ def request(self, *args, retry: bool = True, **kwargs) -> httpx2.Response: if kwargs.get("content") is not None: headers.setdefault("Content-Type", "application/json") kwargs["headers"] = headers - return super().request(*args, retry=retry, **kwargs) + if not retry_at_once: + return super().request(*args, retry=retry, **kwargs) + try: + return super().request(*args, retry=False, **kwargs) + except httpx2.HTTPError as error: + if not _is_retryable_at_once(error): + raise + log.warning("Retrying a failed Execution API request", error_type=type(error).__name__) + return super().request(*args, retry=False, **kwargs) except httpx2.HTTPStatusError as error: if error.response.status_code == 403 and get_error_reason(error) == "job_closed": self._restart_required = True @@ -356,6 +415,40 @@ def heartbeat(self) -> JobState: response = self.request("POST", f"jobs/{job_id}/heartbeat", retry=False, headers=_JOB_API_HEADERS) return JobHeartbeatResponse.model_validate_json(response.content).state + def publish_parse_result(self, body: DagParseResultBody) -> DagParseResultResponse: + """Publish once; the manager retains the request and schedules acknowledgment recovery.""" + response = self.request( + "POST", + f"jobs/{self._require_job_id()}/parse-results", + content=body.model_dump_json(), + headers=_JOB_API_HEADERS, + retry=False, + timeout=self._get_response_timeout(), + ) + return DagParseResultResponse.model_validate_json(response.content) + + def get_bundles(self, *, retry: bool = False) -> list[DagBundleStateResponse]: + """Read the bundle catalog once, or with the Task SDK's retries where waiting is acceptable.""" + response = self.request( + "GET", + f"jobs/{self._require_job_id()}/bundles", + headers=_JOB_API_HEADERS, + retry=retry, + timeout=self._get_response_timeout(), + ) + return [DagBundleStateResponse.model_validate(item) for item in response.json()] + + def publish_inventory(self, bundle_name: str, body: DagBundleInventoryBody) -> DagBundleInventoryResponse: + response = self.request( + "POST", + f"jobs/{self._require_job_id()}/bundles/{quote(bundle_name, safe='')}/inventory", + content=body.model_dump_json(), + headers=_JOB_API_HEADERS, + retry=False, + timeout=self._get_response_timeout(), + ) + return DagBundleInventoryResponse.model_validate_json(response.content) + def complete_job(self, state: TerminalJobState) -> None: """Complete this Job, retaining its identity and outcome across lost acknowledgments.""" body = JobCompleteBody(state=state) @@ -411,3 +504,7 @@ def send(self, msg: Any, **kwargs: Any) -> Any: # mask_secret has already masked the value in this process. return None raise TypeError(f"{type(msg).__name__} is not answered in the Dag processor manager process") + + async def asend(self, msg: Any, **kwargs: Any) -> Any: + # The manager runs no other coroutines, so a blocking lookup delays nothing else. + return self.send(msg, **kwargs) diff --git a/airflow-core/src/airflow/dag_processing/bundles/base.py b/airflow-core/src/airflow/dag_processing/bundles/base.py index 1a76e459a8b4..0e8f6dc6fa07 100644 --- a/airflow-core/src/airflow/dag_processing/bundles/base.py +++ b/airflow-core/src/airflow/dag_processing/bundles/base.py @@ -200,7 +200,8 @@ def _debug_candidates(candidates, found): recently_used, ) - def _remove_stale_bundle_versions_for_bundle(self, bundle_name: str): + def remove_stale_bundle_versions_for_bundle(self, bundle_name: str): + """Remove one bundle's stale versions without constructing the bundle.""" log.info("checking bundle for stale versions. bundle_name=%s", bundle_name) found = self._find_all_tracking_files(bundle_name=bundle_name) if not found: @@ -226,7 +227,7 @@ def remove_stale_bundle_versions(self): for bundle in bundles: if not bundle.supports_versioning: continue - self._remove_stale_bundle_versions_for_bundle(bundle_name=bundle.name) + self.remove_stale_bundle_versions_for_bundle(bundle_name=bundle.name) @dataclass(frozen=True) diff --git a/airflow-core/src/airflow/dag_processing/bundles/manager.py b/airflow-core/src/airflow/dag_processing/bundles/manager.py index fe74ffff7ab9..4086e8985a27 100644 --- a/airflow-core/src/airflow/dag_processing/bundles/manager.py +++ b/airflow-core/src/airflow/dag_processing/bundles/manager.py @@ -22,6 +22,7 @@ import os import warnings from collections import defaultdict +from contextlib import nullcontext from pathlib import Path from typing import TYPE_CHECKING, Any, NamedTuple, cast @@ -40,7 +41,8 @@ from airflow.utils.session import NEW_SESSION, create_session, provide_session if TYPE_CHECKING: - from collections.abc import Iterable + from collections.abc import Callable, Collection, Iterable + from contextlib import AbstractContextManager from sqlalchemy.engine import CursorResult from sqlalchemy.orm import Session @@ -312,8 +314,16 @@ def _sign_bundle_url(url: str, bundle_name: str) -> str: class DagBundlesManager(LoggingMixin): """Manager for DAG bundles.""" - def __init__(self, *args, **kwargs): + def __init__( + self, + *args, + bundle_names: Collection[str] | None = None, + bundle_context: Callable[[str], AbstractContextManager] | None = None, + **kwargs, + ): super().__init__(*args, **kwargs) + self._bundle_names = bundle_names + self._bundle_context = bundle_context or (lambda _: nullcontext()) self._bundle_config: dict[str, _InternalBundleConfig] = {} self.parse_config() @@ -333,6 +343,8 @@ def parse_config(self) -> None: return for bundle_config in bundle_config_list: + if self._bundle_names is not None and bundle_config.name not in self._bundle_names: + continue if bundle_config.team_name and not conf.getboolean("core", "multi_team"): raise AirflowConfigException( "Section `dag_processor` key `dag_bundle_config_list` " @@ -401,7 +413,8 @@ def _extract_and_sign_template(bundle_name: str) -> tuple[str | None, dict]: raise _bundle_item_exc(f"Team '{config.team_name}' does not exist") try: - new_template, new_params = _extract_and_sign_template(name) + with self._bundle_context(name): + new_template, new_params = _extract_and_sign_template(name) except Exception as e: self.log.exception("Error creating bundle '%s': %s", name, e) continue @@ -694,9 +707,10 @@ def get_bundle( cfg_bundle = self._bundle_config.get(name) if not cfg_bundle: raise ValueError(f"Requested bundle '{name}' is not configured.") - return cfg_bundle.bundle_class( - name=name, version=version, version_data=version_data, **cfg_bundle.kwargs - ) + with self._bundle_context(name): + return cfg_bundle.bundle_class( + name=name, version=version, version_data=version_data, **cfg_bundle.kwargs + ) @classmethod def is_bundle_configured(cls, name: str) -> bool: @@ -716,7 +730,9 @@ def get_all_dag_bundles(self) -> Iterable[BaseDagBundle]: """ for name, cfg in self._bundle_config.items(): try: - yield cfg.bundle_class(name=name, version=None, **cfg.kwargs) + with self._bundle_context(name): + bundle = cfg.bundle_class(name=name, version=None, **cfg.kwargs) + yield bundle except Exception as e: self.log.exception("Error creating bundle '%s': %s", name, e) # Skip this bundle and continue with others diff --git a/airflow-core/src/airflow/dag_processing/manager.py b/airflow-core/src/airflow/dag_processing/manager.py index aad8c6ba7d01..a2e08ef92a5d 100644 --- a/airflow-core/src/airflow/dag_processing/manager.py +++ b/airflow-core/src/airflow/dag_processing/manager.py @@ -29,16 +29,20 @@ import signal import sys import time -from collections import Counter, OrderedDict, defaultdict +from collections import Counter, OrderedDict, defaultdict, deque +from contextlib import AbstractContextManager, nullcontext from copy import deepcopy -from dataclasses import dataclass, field +from dataclasses import dataclass, field, replace from datetime import datetime, timedelta from operator import attrgetter, itemgetter from pathlib import Path from typing import TYPE_CHECKING, Any, Literal, NamedTuple, cast +from uuid import UUID import attrs +import httpx2 import structlog +from pydantic import ValidationError from sqlalchemy import select, update from sqlalchemy.exc import OperationalError from sqlalchemy.orm import load_only @@ -48,6 +52,14 @@ from airflow._shared.observability.metrics import stats from airflow._shared.observability.metrics.stats import normalize_name_for_stats from airflow._shared.timezones import timezone +from airflow.api_fastapi.execution_api.datamodels.dag_parsing import ( + MAX_PUBLICATION_BYTES, + DagBundleInventoryBody, + DagParseResultBody, + ParseSourceCode, + ParseWarning, +) +from airflow.api_fastapi.execution_api.datamodels.job import FILELOC_MAX_LENGTH, DagParseTokenBody from airflow.api_fastapi.execution_api.in_process import InProcessExecutionAPI from airflow.callbacks.callback_requests import DagCallbackRequest from airflow.configuration import conf @@ -67,6 +79,7 @@ DagFileProcessorProcess, DagParseSource, ) +from airflow.dag_processing.requested_work import DatabaseRequestedWorkSource, RequestedWorkSource from airflow.models.asset import remove_references_to_deleted_dags from airflow.models.dag import DagModel from airflow.models.dagbag import DagPriorityParsingRequest @@ -76,6 +89,7 @@ from airflow.models.errors import ParseImportError from airflow.observability.metrics import stats_utils from airflow.sdk import SecretCache +from airflow.sdk.execution_time import task_runner from airflow.sdk.importers import DagImportError, get_importer_registry from airflow.sdk.log import init_log_file, logging_processors from airflow.typing_compat import assert_never @@ -103,15 +117,46 @@ from sqlalchemy.sql import Select from airflow.callbacks.callback_requests import CallbackRequest + from airflow.dag_processing.api_client import DagProcessorAPIClient from airflow.dag_processing.bundles.base import BaseDagBundle from airflow.sdk.api.client import Client +# The budget limits when another send starts; an in-flight request retains its read/write timeout. +_API_SEND_BUDGET_SECONDS = 1.0 +_MAX_REJECTION_REASON_LENGTH = 1024 +_REJECTED_CONTENT_REASONS = frozenset({"dag_owned_by_another_bundle", "plugin_not_granted"}) + + +def _is_rejected_content(status_code: int, reason: str | None) -> bool: + """Whether the API refused a result for what it contains, so sending it again cannot succeed.""" + return status_code in (413, 422) or (status_code in (403, 409) and reason in _REJECTED_CONTENT_REASONS) + + +def _compute_retry_delay(attempts: int) -> float: + """Seconds to wait after the given number of failed sends, using the Execution API retry bounds.""" + return min( + conf.getfloat("workers", "execution_api_retry_wait_max"), + max(conf.getfloat("workers", "execution_api_retry_wait_min"), 2 ** (attempts - 1)), + ) + + +def _get_api_path_error(path: str) -> str | None: + """Return why the API cannot accept ``path`` as a bundle-relative location, or ``None`` if it can.""" + if len(path) > FILELOC_MAX_LENGTH: + return f"Definition location exceeds {FILELOC_MAX_LENGTH} characters" + try: + DagParseTokenBody.validate_relative_fileloc(path) + except ValueError as error: + return str(error) + return None + class BundleState(NamedTuple): """Persisted refresh state for a DAG bundle.""" last_refreshed: datetime | None version: str | None + revision: UUID | None = None @attrs.define @@ -124,6 +169,31 @@ class DagFileStat: last_duration: float | None = None run_count: int = 0 last_num_of_db_queries: int = 0 + last_attempt_time: datetime | None = None + + +@attrs.define +class PendingDagPublication: + """A completed import retained until publication succeeds or exhausts its retries.""" + + body: DagParseResultBody + stat: DagFileStat + refresh_generation: int + attempts: int = 0 + next_attempt_time: float = 0.0 + is_rejection_report: bool = False + """Whether this replaces a result the API refused, so a further refusal is final.""" + + +@attrs.define +class PendingBundleInventory: + """A bundle listing retained until the API accepts it; the bundle's files wait for its revision.""" + + body: DagBundleInventoryBody + found_files: set[DagFileInfo] + source: DagParseSource + attempts: int = 0 + next_attempt_time: float = 0.0 @dataclass(frozen=True) @@ -268,6 +338,7 @@ class DagFileProcessorManager(LoggingMixin): _bundle_parse_sources: dict[str, DagParseSource] = attrs.field(factory=dict, init=False) _bundle_refresh_generations: dict[str, int] = attrs.field(factory=lambda: defaultdict(int), init=False) _bundles_waiting_for_refresh: set[str] = attrs.field(factory=set, init=False) + _dispatch_sequence: int = attrs.field(default=0, init=False) _bundles_needing_refresh: set[str] = attrs.field(factory=set, init=False) _bundle_refresh_retry_at: dict[str, float] = attrs.field(factory=dict, init=False) """Monotonic retry deadlines for bundles whose failed refresh or listing left a usable source.""" @@ -276,6 +347,12 @@ class DagFileProcessorManager(LoggingMixin): _bundle_name_to_team_name: dict[str, str | None] = attrs.field(factory=dict, init=False) _processors: dict[DagFileInfo, BaseDagFileProcessorProcess] = attrs.field(factory=dict, init=False) + _pending_publications: dict[DagFileInfo, PendingDagPublication] = attrs.field(factory=dict, init=False) + _pending_inventories: dict[str, PendingBundleInventory] = attrs.field(factory=dict, init=False) + _bundle_inventory_retry_times: dict[str, float] = attrs.field(factory=dict, init=False) + _bundle_listing_retry_delays: dict[str, float] = attrs.field(factory=dict, init=False) + _bundles_missing_from_catalog: set[str] = attrs.field(factory=set, init=False) + _catalog_retry_at: float = attrs.field(default=0.0, init=False) _parsing_start_time: float | None = attrs.field(default=None, init=False) _num_run: int = attrs.field(default=0, init=False) @@ -310,8 +387,19 @@ class DagFileProcessorManager(LoggingMixin): ) """Resolved once per process so file discovery and the deactivation scan use the same value.""" - _api_server: InProcessExecutionAPI = attrs.field(init=False, factory=InProcessExecutionAPI) - """API server to interact with Metadata DB""" + api_client: DagProcessorAPIClient | None = None + """ + Registered HTTP client for this manager's API requests, used instead of the in-process API. + + Bundle credentials and parse-time requests then go through it, on behalf of the bundle they are for. + """ + + work_source: RequestedWorkSource = attrs.field( + default=attrs.Factory(lambda self: self._create_requested_work_source(), takes_self=True) + ) + + _api_server: InProcessExecutionAPI | None = attrs.field(init=False, default=None) + """In-process API server, created only when there is no :attr:`api_client`.""" def register_exit_signals(self): """Register signals that stop child processes.""" @@ -325,9 +413,17 @@ def _get_team_names(self, bundle_names: Collection[str]) -> dict[str, str | None return {} missing = [name for name in bundle_names if name not in self._bundle_name_to_team_name] if missing: - queried = DagBundleModel.get_team_names(missing) - for name in missing: - self._bundle_name_to_team_name[name] = queried.get(name) + try: + if self.api_client is not None: + queried = {bundle.name: bundle.team_name for bundle in self.api_client.get_bundles()} + else: + queried = DagBundleModel.get_team_names(missing) + except httpx2.HTTPError: + # Team names only tag metrics, so parsing continues and the lookup is retried later. + self.log.warning("Unable to look up the teams of bundles %s; retrying later", missing) + else: + for name in missing: + self._bundle_name_to_team_name[name] = queried.get(name) return {name: self._bundle_name_to_team_name.get(name) for name in bundle_names} def _get_team_name(self, bundle_name: str) -> str | None: @@ -342,11 +438,34 @@ def _exit_gracefully(self, signum, frame): self.log.debug("Finished terminating DAG processors.") sys.exit(os.EX_OK) + def _create_bundle_manager(self) -> DagBundlesManager: + if self.api_client is None: + return DagBundlesManager() + return DagBundlesManager( + bundle_names=self.bundle_names_to_parse, + bundle_context=self.api_client.use_bundle, + ) + + def _create_requested_work_source(self) -> RequestedWorkSource: + if self.api_client is not None: + return RequestedWorkSource() + return DatabaseRequestedWorkSource(self._claim_priority_files, self._fetch_callbacks_from_db) + def sync_bundles(self) -> None: """Sync configured DAG bundles to the metadata database.""" + if self.api_client is not None: + provisioned = {bundle.name for bundle in self.api_client.get_bundles(retry=True)} + configured = set( + self.bundle_names_to_parse or self._create_bundle_manager().get_all_bundle_names() + ) + if missing := configured - provisioned: + raise ValueError( + f"Bundles must be provisioned before starting the processor: {sorted(missing)}" + ) + return # When this processor only parses a subset of bundles, it does not see the full # bundle configuration and must not deactivate bundles owned by other processors. - dag_bundle_manager = DagBundlesManager() + dag_bundle_manager = self._create_bundle_manager() dag_bundle_manager.sync_bundles_to_db(deactivate_missing=not self.bundle_names_to_parse) # Best-effort legacy repair: a failure here must not crash DFP startup. # Affected Dags self-heal on the next successful parse. @@ -357,7 +476,7 @@ def sync_bundles(self) -> None: def get_all_bundles(self) -> list[BaseDagBundle]: """Return configured DAG bundles filtered by ``bundle_names_to_parse`` if provided.""" - return list(DagBundlesManager().get_all_dag_bundles()) + return list(self._create_bundle_manager().get_all_dag_bundles()) def run(self): """ @@ -366,15 +485,20 @@ def run(self): By processing them in separate processes, we can get parallelism and isolation from potentially harmful user code. """ - self.before_run() try: - return self._run_parsing_loop() + self.before_run() + # Startup may wait for the API to come back; the parsing loop must not sleep between retries. + with nullcontext() if self.api_client is None else self.api_client.use_immediate_retries(): + return self._run_parsing_loop() finally: self.after_run() def before_run(self) -> None: """Set up state required before the parsing loop starts. Default implementation; override to customize.""" - self.prepare_server_process_context() + if self.api_client is None: + self.prepare_server_process_context() + else: + self.prepare_api_secrets_context(self.api_client) self.prepare_process_context() self.register_exit_signals() self.log.info("Processing files using up to %s processes at a time ", self._parallelism) @@ -386,13 +510,21 @@ def before_run(self) -> None: gc.freeze() def after_run(self) -> None: - """Tear down state after the parsing loop exits. Default no-op; override to customize.""" + """Tear down state after the parsing loop exits. Default implementation; override to customize.""" + if self.api_client is None: + return + # Runtime API-client imports stay local so managers using the in-process API do not load it. + from airflow.dag_processing.api_client import DagProcessorSecretsComms + + if isinstance(getattr(task_runner, "SUPERVISOR_COMMS", None), DagProcessorSecretsComms): + del task_runner.SUPERVISOR_COMMS def warm_importers(self) -> None: """Build each bundle's Dag importers, so parse processes forked later share them.""" for bundle in self._dag_bundles: try: - get_importer_registry(bundle.name).warm_importers() + with self._use_bundle(bundle.name): + get_importer_registry(bundle.name).warm_importers() except Exception: # The importer fails again when the bundle is listed, which reports it per refresh. self.log.exception("Error loading Dag importers for bundle %s", bundle.name) @@ -401,8 +533,7 @@ def prepare_server_process_context(self) -> None: """ Mark this process as running in "server" context so MetastoreBackend is available. - Override to a no-op in subclasses that do not require direct DB access (e.g. API-backed - deployments under AIP-92). + Called only without an HTTP client; API mode uses ``prepare_api_secrets_context`` instead. """ # TODO: Temporary until AIP-92 removes DB access from DagProcessorManager. # The manager needs MetastoreBackend to retrieve connections from the database @@ -414,6 +545,28 @@ def prepare_server_process_context(self) -> None: # Related: https://github.com/apache/airflow/pull/57459 os.environ["_AIRFLOW_PROCESS_CONTEXT"] = "server" + def prepare_api_secrets_context(self, api_client: DagProcessorAPIClient) -> None: + """ + Resolve this process's own connection and variable lookups through ``api_client``. + + Bundle code runs in this process, for example a Git bundle reading its connection. Its secret + lookups use the API. Python parse processes replace + ``SUPERVISOR_COMMS`` with their own channel before running any Dag code. + """ + # Runtime API-client imports stay local so managers using the in-process API do not load it. + from airflow.dag_processing.api_client import DagProcessorSecretsComms + + # SDK cache keys do not carry the bundle identity used to authorize these requests. + SecretCache.reset() + os.environ["_AIRFLOW_PROCESS_CONTEXT"] = "client" + task_runner.SUPERVISOR_COMMS = DagProcessorSecretsComms(api_client) # type: ignore[assignment] + + def _use_bundle(self, bundle_name: str) -> AbstractContextManager[object]: + """Make API requests on behalf of the bundle; a no-op with the in-process API.""" + if self.api_client is None: + return nullcontext() + return self.api_client.use_bundle(bundle_name) + def prepare_process_context(self) -> None: """Initialize transport-neutral process state (selector, stats) before the parsing loop starts.""" # Initialization is delayed until here to avoid fork issues in some @@ -444,6 +597,8 @@ def load_dag_bundles(self) -> None: def _scan_stale_dags(self): """Scan and deactivate DAGs which are no longer present in files.""" + if self.api_client is not None: + return now = time.monotonic() elapsed_time_since_refresh = now - self._last_deactivate_stale_dags_time if elapsed_time_since_refresh > self.parsing_cleanup_interval: @@ -471,6 +626,12 @@ def _cleanup_stale_bundle_versions(self): def cleanup_stale_bundle_versions(self) -> None: """Clean up stale DAG bundle version usage records.""" + if self.api_client is not None: + manager = BundleUsageTrackingManager() + for bundle in self._dag_bundles: + if bundle.supports_versioning: + manager.remove_stale_bundle_versions_for_bundle(bundle.name) + return BundleUsageTrackingManager().remove_stale_bundle_versions() @provide_session @@ -566,7 +727,8 @@ def deactivate_stale_dags( def _run_parsing_loop(self): # initialize cache to mutualize calls to Variable.get in DAGs # needs to be done before this process is forked to create the DAG parsing processes. - SecretCache.init() + if self.api_client is None: + SecretCache.init() poll_time = 0.0 @@ -597,6 +759,7 @@ def _run_parsing_loop(self): self._collect_results() + self._publish_pending_results() for callback in self.fetch_callbacks(): self._add_callback_to_queue(callback) self._scan_stale_dags() @@ -652,12 +815,17 @@ def _queue_requested_files_for_parsing(self) -> None: self.log.info("Bundles being force refreshed: %s", ", ".join(self._force_refresh_bundles)) def claim_priority_files(self) -> list[DagFileInfo]: - """ - Fetch and claim files requested for priority parsing. - - Default implementation reads from the metadata DB; override to source requests from an API. - """ - return self._claim_priority_files() + """Fetch and claim files requested for priority parsing.""" + active_attempts = {process.id for process in self._processors.values()} + active_attempts.update(pending.body.attempt_id for pending in self._pending_publications.values()) + return self.work_source.claim_priority_files( + self._dag_bundles, + capacity=self._parallelism, + unavailable_bundles=self._bundles_needing_refresh + | {bundle.name for bundle in self._dag_bundles if not bundle.is_initialized}, + active_attempts=active_attempts, + inventory_sequence=self._dispatch_sequence + 1, + ) def request_bundle_refresh(self, bundle_names: str | Iterable[str]) -> None: """ @@ -709,12 +877,8 @@ def _claim_priority_files(self, *, session: Session = NEW_SESSION) -> list[DagFi return files def fetch_callbacks(self) -> list[CallbackRequest]: - """ - Fetch and claim callbacks for this manager's bundles. - - Default implementation reads from the metadata DB; override to source callbacks from an API. - """ - return self._fetch_callbacks_from_db() + """Fetch and claim callbacks for this manager's bundles.""" + return self.work_source.fetch_callbacks(self._dag_bundles, limit=self.max_callbacks_per_loop) @provide_session @retry_db_transaction @@ -783,21 +947,18 @@ def prepare_callback_bundle(self, request: CallbackRequest) -> BaseDagBundle | N self.log.error("Bundle %s is not initialized, skipping callback", request.bundle_name) return None return loaded - try: - bundle = DagBundlesManager().get_bundle( - name=request.bundle_name, - version=request.bundle_version, - version_data=request.version_data, - ) - except ValueError: - self.log.error("Bundle %s no longer configured, skipping callback", request.bundle_name) - return None - if bundle.supports_versioning: + with self._use_bundle(request.bundle_name): try: - bundle.initialize() + bundle = self._create_bundle_manager().get_bundle( + name=request.bundle_name, + version=request.bundle_version, + version_data=request.version_data, + ) + if bundle.supports_versioning: + bundle.initialize() except Exception: self.log.exception( - "Error initializing bundle %s version %s for callback, skipping", + "Error preparing bundle %s version %s for callback, skipping", request.bundle_name, request.bundle_version, ) @@ -874,6 +1035,109 @@ def update_bundle_state( values["version"] = version session.execute(update(DagBundleModel).where(DagBundleModel.name == bundle_name).values(**values)) + def _publish_bundle_inventory(self, bundle_name: str, known_files: dict[str, set[DagFileInfo]]) -> None: + if self.api_client is None: + raise ValueError("Inventory publication requires an API client") + pending = self._pending_inventories[bundle_name] + if len(pending.body.model_dump_json().encode()) > MAX_PUBLICATION_BYTES: + self.log.error( + "Bundle %s inventory exceeds the %s-byte publication limit; retaining the previous inventory", + bundle_name, + MAX_PUBLICATION_BYTES, + ) + self._defer_unusable_bundle_inventory(bundle_name) + return + # Runtime API-client imports stay local so managers using the in-process API do not load it. + from airflow.dag_processing.api_client import is_transient_api_error + + try: + receipt = self.api_client.publish_inventory(bundle_name, pending.body) + except httpx2.HTTPError as error: + status_code = error.response.status_code if isinstance(error, httpx2.HTTPStatusError) else None + if is_transient_api_error(error): + pending.attempts += 1 + pending.next_attempt_time = time.monotonic() + _compute_retry_delay(pending.attempts) + self.log.warning( + "Unable to publish inventory for %s; retrying on a later refresh", bundle_name + ) + return + if status_code == 409: + del self._pending_inventories[bundle_name] + self.request_bundle_refresh(bundle_name) + elif status_code == 413: + self._defer_unusable_bundle_inventory(bundle_name) + else: + # The Job, its bundle grants or the API contract no longer match this processor, so a + # resend cannot succeed; restarting registers again and reads the catalog again. + raise + self.log.warning( + "Inventory publication was rejected for %s", bundle_name, status_code=status_code + ) + return + del self._pending_inventories[bundle_name] + self._bundle_inventory_retry_times.pop(bundle_name, None) + self._bundle_parse_sources[bundle_name] = attrs.evolve( + pending.source, bundle_revision=receipt.revision + ) + self._bundle_versions[bundle_name] = pending.source.bundle_version + self._bundle_failed_sources[bundle_name] = frozenset(pending.body.failed_sources) + known_files[bundle_name] = pending.found_files + + def _discard_unusable_bundle_source(self, bundle_name: str) -> None: + self._pending_inventories.pop(bundle_name, None) + self._bundle_inventory_retry_times.pop(bundle_name, None) + self._bundle_refresh_retry_at.pop(bundle_name, None) + self._bundle_parse_sources.pop(bundle_name, None) + self._force_refresh_bundles.discard(bundle_name) + self._bundles_waiting_for_refresh.discard(bundle_name) + + def _defer_unusable_bundle_inventory(self, bundle_name: str) -> None: + refresh_interval = next( + (bundle.refresh_interval for bundle in self._dag_bundles if bundle.name == bundle_name), + self.bundle_refresh_check_interval, + ) + self._discard_unusable_bundle_source(bundle_name) + self._bundle_inventory_retry_times[bundle_name] = time.monotonic() + max( + refresh_interval, self.bundle_refresh_check_interval, _compute_retry_delay(1) + ) + + def _delay_bundle_listing_retry(self, bundle_name: str, *, check_started_at: float) -> None: + """ + Retry a failed listing soon, then double the wait up to the refresh interval while it fails. + + The wait counts from ``check_started_at``, the start of the refresh check that listed the + bundle, because the next periodic check is timed from there too. + """ + refresh_interval = next( + (bundle.refresh_interval for bundle in self._dag_bundles if bundle.name == bundle_name), + self.bundle_refresh_check_interval, + ) + first_delay = max(self.bundle_refresh_check_interval, _compute_retry_delay(1)) + previous_delay = self._bundle_listing_retry_delays.get(bundle_name) + delay = ( + first_delay + if previous_delay is None + else min(max(refresh_interval, first_delay), previous_delay * 2) + ) + self._bundle_listing_retry_delays[bundle_name] = delay + self._bundle_inventory_retry_times[bundle_name] = check_started_at + delay + + def _publish_pending_inventories(self, known_files: dict[str, set[DagFileInfo]]) -> bool: + deadline = time.monotonic() + _API_SEND_BUDGET_SECONDS + attempted = False + for bundle_name in list(self._pending_inventories): + now = time.monotonic() + if now >= deadline: + break + if now < self._pending_inventories[bundle_name].next_attempt_time: + continue + with self._use_bundle(bundle_name): + self._publish_bundle_inventory(bundle_name, known_files) + attempted = True + if bundle_name in self._pending_inventories: + self._pending_inventories[bundle_name] = self._pending_inventories.pop(bundle_name) + return attempted + def _invalidate_bundle_parse_source(self, bundle_name: str) -> None: # Initialization or refresh may change files even when the provider raises afterwards. self._bundle_refresh_generations[bundle_name] += 1 @@ -895,7 +1159,19 @@ def _refresh_dag_bundles(self, known_files: dict[str, set[DagFileInfo]]): next_check = self._bundles_last_refreshed + self.bundle_refresh_check_interval now_seconds = time.monotonic() periodic_check_due = now_seconds >= next_check - urgent_bundles = self._force_refresh_bundles | self._bundles_waiting_for_refresh + due_inventories = { + name + for name, pending in self._pending_inventories.items() + if now_seconds >= pending.next_attempt_time + } + requested_bundles = self._force_refresh_bundles | self._bundles_waiting_for_refresh + if now_seconds < self._catalog_retry_at: + # A requested refresh needs the catalog; wait for the next periodic read instead of every loop. + requested_bundles = set() + unrefreshable_bundles = self._pending_inventories.keys() | { + name for name, retry_at in self._bundle_inventory_retry_times.items() if now_seconds < retry_at + } + urgent_bundles = (requested_bundles - unrefreshable_bundles) | due_inventories if not periodic_check_due and not urgent_bundles: self.log.debug( "Not time to check if DAG Bundles need refreshed yet - skipping. Next check in %.2f seconds", @@ -906,167 +1182,251 @@ def _refresh_dag_bundles(self, known_files: dict[str, set[DagFileInfo]]): if periodic_check_due: self._bundles_last_refreshed = now_seconds + catalog: dict[str, BundleState] | None = None + if self.api_client is not None and self._dag_bundles: + try: + bundles = self.api_client.get_bundles() + catalog = { + bundle.name: BundleState(bundle.last_refreshed, bundle.version, bundle.revision) + for bundle in bundles + } + self._bundle_name_to_team_name = {bundle.name: bundle.team_name for bundle in bundles} + missing_bundles = {bundle.name for bundle in self._dag_bundles} - catalog.keys() + for bundle_name in sorted(missing_bundles - self._bundles_missing_from_catalog): + self.log.warning( + "Bundle missing from API catalog; parsing paused", bundle_name=bundle_name + ) + self._bundles_missing_from_catalog = missing_bundles + self._catalog_retry_at = 0.0 + except httpx2.HTTPError: + self.log.warning("Unable to read the bundle catalog; retrying on a later refresh") + self._catalog_retry_at = now_seconds + self.bundle_refresh_check_interval + any_refreshed = False - active_bundles = {file.bundle_name for file in self._processors if file.bundle_version is None} + active_bundles = { + file.bundle_name + for file in self._processors.keys() | self._pending_publications.keys() + if file.bundle_version is None + } for bundle in self._dag_bundles: if not periodic_check_due and bundle.name not in urgent_bundles: continue - if bundle.name not in urgent_bundles and now_seconds < self._bundle_refresh_retry_at.get( - bundle.name, 0 - ): - continue - # TODO: AIP-66 handle errors in the case of incomplete cloning? And test this. - # What if the cloning/refreshing took too long(longer than the dag processor timeout) - if not bundle.is_initialized: - self._invalidate_bundle_parse_source(bundle.name) + with self._use_bundle(bundle.name): + if catalog is not None and bundle.name not in catalog: + self._discard_unusable_bundle_source(bundle.name) + continue + if now_seconds < self._bundle_inventory_retry_times.get(bundle.name, 0): + continue + if bundle.name in self._pending_inventories: + # A listing still waiting for the API must be published before the bundle is listed again. + continue + if self.api_client is not None and catalog is None: + continue + if bundle.name not in urgent_bundles and now_seconds < self._bundle_refresh_retry_at.get( + bundle.name, 0 + ): + continue + # TODO: AIP-66 handle errors in the case of incomplete cloning? And test this. + # What if the cloning/refreshing took too long(longer than the dag processor timeout) + if not bundle.is_initialized: + self._invalidate_bundle_parse_source(bundle.name) + try: + bundle.initialize() + any_refreshed = True + except Exception as e: + self.log.exception("Error initializing bundle %s: %s", bundle.name, e) + self._bundles_needing_refresh.add(bundle.name) + continue try: - bundle.initialize() - any_refreshed = True - except Exception as e: - self.log.exception("Error initializing bundle %s: %s", bundle.name, e) - self._bundles_needing_refresh.add(bundle.name) + bundle_state = ( + catalog.get(bundle.name) + if catalog is not None + else self.get_bundle_state(bundle.name) + ) + except Exception: + self.log.exception("Error fetching state for bundle %s", bundle.name) + continue + if bundle_state is None: + self.log.warning("Bundle model not found for %s", bundle.name) + continue + elapsed_time_since_refresh = ( + now - (bundle_state.last_refreshed or utc_epoch()) + ).total_seconds() + if bundle.supports_versioning: + # we will also check the version of the bundle to see if another DAG processor has seen + # a new version + pre_refresh_version = self._bundle_versions.get(bundle.name) + # Use `is None` (not falsy) so an empty-string version is treated as a valid cached value. + if pre_refresh_version is None: + pre_refresh_version, _ = unpack_bundle_version(bundle.get_current_version(), bundle) + current_version_matches_db = pre_refresh_version == bundle_state.version + else: + # With no versioning, it always "matches" + current_version_matches_db = True + + previously_seen = bundle.name in self._bundle_versions + if ( + bundle.name not in self._bundles_waiting_for_refresh + and bundle.name not in self._bundles_needing_refresh + and bundle.name in self._bundle_parse_sources + and self.should_skip_refresh( + bundle=bundle, + elapsed_time_since_refresh=elapsed_time_since_refresh, + current_version_matches_db=current_version_matches_db, + previously_seen=previously_seen, + ) + ): + self.log.debug("Not time to refresh bundle %s", bundle.name) continue - try: - bundle_state = self.get_bundle_state(bundle.name) - except Exception: - self.log.exception("Error fetching state for bundle %s", bundle.name) - continue - if bundle_state is None: - self.log.warning("Bundle model not found for %s", bundle.name) - continue - elapsed_time_since_refresh = (now - (bundle_state.last_refreshed or utc_epoch())).total_seconds() - if bundle.supports_versioning: - # we will also check the version of the bundle to see if another DAG processor has seen - # a new version - pre_refresh_version = self._bundle_versions.get(bundle.name) - # Use `is None` (not falsy) so an empty-string version is treated as a valid cached value. - if pre_refresh_version is None: - pre_refresh_version, _ = unpack_bundle_version(bundle.get_current_version(), bundle) - current_version_matches_db = pre_refresh_version == bundle_state.version - else: - # With no versioning, it always "matches" - current_version_matches_db = True - - previously_seen = bundle.name in self._bundle_versions - if ( - bundle.name not in self._bundles_waiting_for_refresh - and bundle.name not in self._bundles_needing_refresh - and bundle.name in self._bundle_parse_sources - and self.should_skip_refresh( - bundle=bundle, - elapsed_time_since_refresh=elapsed_time_since_refresh, - current_version_matches_db=current_version_matches_db, - previously_seen=previously_seen, - ) - ): - self.log.debug("Not time to refresh bundle %s", bundle.name) - continue - if bundle.refresh_changes_source and bundle.name in active_bundles: - # Forced refreshes wait too: refreshing under an import would discard its result. - self._bundles_waiting_for_refresh.add(bundle.name) - continue + if bundle.refresh_changes_source and bundle.name in active_bundles: + # Forced refreshes wait too: refreshing under an import would discard its result. + self._bundles_waiting_for_refresh.add(bundle.name) + continue - self._bundles_waiting_for_refresh.discard(bundle.name) - self._bundle_refresh_retry_at.pop(bundle.name, None) - self.log.info("Refreshing bundle %s", bundle.name) + self._bundles_waiting_for_refresh.discard(bundle.name) + self._bundle_refresh_retry_at.pop(bundle.name, None) + self.log.info("Refreshing bundle %s", bundle.name) - previous_source = self._bundle_parse_sources.get(bundle.name) - if bundle.refresh_changes_source: - self._invalidate_bundle_parse_source(bundle.name) - try: - bundle.refresh() - any_refreshed = True - except Exception as error: - self.log.exception("Error refreshing bundle %s", bundle.name) - source_unchanged = not bundle.refresh_changes_source or ( - isinstance(error, DagBundleRefreshError) and error.source_unchanged - ) - if source_unchanged and previous_source is not None: - self._bundle_parse_sources[bundle.name] = attrs.evolve( - previous_source, - refresh_generation=self._bundle_refresh_generations[bundle.name], + previous_source = self._bundle_parse_sources.get(bundle.name) + if bundle.refresh_changes_source: + self._invalidate_bundle_parse_source(bundle.name) + try: + bundle.refresh() + any_refreshed = True + except Exception as error: + self.log.exception("Error refreshing bundle %s", bundle.name) + source_unchanged = not bundle.refresh_changes_source or ( + isinstance(error, DagBundleRefreshError) and error.source_unchanged ) - self._force_refresh_bundles.discard(bundle.name) - self._bundle_refresh_retry_at[bundle.name] = time.monotonic() + bundle.refresh_interval - if bundle.name not in self._bundles_needing_refresh: + if source_unchanged and previous_source is not None: + self._bundle_parse_sources[bundle.name] = attrs.evolve( + previous_source, + refresh_generation=self._bundle_refresh_generations[bundle.name], + ) + self._force_refresh_bundles.discard(bundle.name) + self._bundle_refresh_retry_at[bundle.name] = ( + time.monotonic() + bundle.refresh_interval + ) + if bundle.name not in self._bundles_needing_refresh: + self.log.warning( + "Refresh failed without changing the source; continuing to parse bundle", + bundle_name=bundle.name, + ) + elif previous_source is not None or bundle.name not in self._bundles_needing_refresh: self.log.warning( - "Refresh failed without changing the source; continuing to parse bundle", - bundle_name=bundle.name, + "Parsing paused until bundle refresh succeeds", bundle_name=bundle.name ) - elif previous_source is not None or bundle.name not in self._bundles_needing_refresh: - self.log.warning("Parsing paused until bundle refresh succeeds", bundle_name=bundle.name) - self._bundles_needing_refresh.add(bundle.name) - continue + self._bundles_needing_refresh.add(bundle.name) + continue - self._bundles_needing_refresh.discard(bundle.name) - self._force_refresh_bundles.discard(bundle.name) + self._bundles_needing_refresh.discard(bundle.name) + self._force_refresh_bundles.discard(bundle.name) - if bundle.supports_versioning: - version_after_refresh, version_data_after_refresh = unpack_bundle_version( - bundle.get_current_version(), bundle + if bundle.supports_versioning: + version_after_refresh, version_data_after_refresh = unpack_bundle_version( + bundle.get_current_version(), bundle + ) + else: + version_after_refresh = None + version_data_after_refresh = None + + self._bundle_parse_sources[bundle.name] = DagParseSource( + bundle_version=version_after_refresh, + version_data=deepcopy(version_data_after_refresh), + refresh_generation=self._bundle_refresh_generations[bundle.name], ) - else: - version_after_refresh = None - version_data_after_refresh = None - self._bundle_parse_sources[bundle.name] = DagParseSource( - bundle_version=version_after_refresh, - version_data=deepcopy(version_data_after_refresh), - refresh_generation=self._bundle_refresh_generations[bundle.name], - ) + if bundle.supports_versioning: + # We can short-circuit the rest of this if (1) bundle was seen before by + # this dag processor and (2) the version of the bundle did not change + # after refreshing it + if ( + self.api_client is None + and previously_seen + and pre_refresh_version == version_after_refresh + ): + self.log.debug( + "Bundle %s version not changed after refresh: %s", + bundle.name, + version_after_refresh, + ) + try: + self.update_bundle_state(bundle.name, last_refreshed=now, version=None) + except Exception: + self.log.exception("Error persisting state for bundle %s", bundle.name) + self._delay_draining_refresh_retry(bundle, known_files.get(bundle.name, ())) + continue - if bundle.supports_versioning: - # We can short-circuit the rest of this if (1) bundle was seen before by - # this dag processor and (2) the version of the bundle did not change - # after refreshing it - if previously_seen and pre_refresh_version == version_after_refresh: - self.log.debug( - "Bundle %s version not changed after refresh: %s", - bundle.name, - version_after_refresh, + self.log.info( + "Version changed for %s, new version: %s", bundle.name, version_after_refresh ) - try: - self.update_bundle_state(bundle.name, last_refreshed=now, version=None) - except Exception: - self.log.exception("Error persisting state for bundle %s", bundle.name) + try: + discovery = self._find_files_in_bundle(bundle) + except Exception: + # Keep the bundle's known files and Dags, and leave its version unadvanced so the + # next refresh lists it again. + self.log.exception("Error listing Dag definitions in bundle %s", bundle.name) + if self.api_client is not None: + self._discard_unusable_bundle_source(bundle.name) + self._delay_bundle_listing_retry(bundle.name, check_started_at=now_seconds) + else: self._delay_draining_refresh_retry(bundle, known_files.get(bundle.name, ())) continue + self._bundle_listing_retry_delays.pop(bundle.name, None) - self.log.info("Version changed for %s, new version: %s", bundle.name, version_after_refresh) - try: - discovery = self._find_files_in_bundle(bundle) - except Exception: - # Keep the bundle's known files and Dags, and leave its version unadvanced so the - # next refresh lists it again. - self.log.exception("Error listing Dag definitions in bundle %s", bundle.name) - self._delay_draining_refresh_retry(bundle, known_files.get(bundle.name, ())) - continue + if self.api_client is not None: + discovery = self._filter_api_discovery_result(bundle.name, discovery) + found_files = discovery.files + if self.api_client is not None: + self._dispatch_sequence += 1 + try: + inventory = DagBundleInventoryBody( + attempt_id=uuid7(), + dispatch_sequence=self._dispatch_sequence, + expected_revision=bundle_state.revision, + version=version_after_refresh, + files=sorted(self._get_observed_filelocs(found_files)), + failed_sources=sorted(discovery.failed_sources), + ) + except ValidationError: + # Handled like a failed listing, so the API never sees a partial inventory. + self.log.exception("Bundle %s has a listing the API cannot accept", bundle.name) + self._defer_unusable_bundle_inventory(bundle.name) + continue + self._pending_inventories[bundle.name] = PendingBundleInventory( + body=inventory, + found_files=found_files, + source=self._bundle_parse_sources.pop(bundle.name), + ) + continue - # Persistence failure must not skip file scanning (bundle is already refreshed locally). - # _bundle_versions is only advanced on success to stay consistent with the DB. - try: - self.update_bundle_state(bundle.name, last_refreshed=now, version=version_after_refresh) - except Exception: - self.log.exception("Error persisting state for bundle %s", bundle.name) - self._delay_draining_refresh_retry(bundle, discovery.files) - else: - self._bundle_versions[bundle.name] = version_after_refresh + # Persistence failure must not skip file scanning (bundle is already refreshed locally). + # _bundle_versions is only advanced on success to stay consistent with the DB. + try: + self.update_bundle_state(bundle.name, last_refreshed=now, version=version_after_refresh) + except Exception: + self.log.exception("Error persisting state for bundle %s", bundle.name) + self._delay_draining_refresh_retry(bundle, discovery.files) + else: + self._bundle_versions[bundle.name] = version_after_refresh - found_files = discovery.files - self._bundle_failed_sources[bundle.name] = discovery.failed_sources - known_files[bundle.name] = found_files + self._bundle_failed_sources[bundle.name] = discovery.failed_sources + known_files[bundle.name] = found_files - # Subclass overrides may keep the original signatures, so failed sources go through instance state. - self.deactivate_deleted_dags(bundle_name=bundle.name, present=found_files) - self.clear_orphaned_import_errors( - bundle_name=bundle.name, - observed_filelocs=self._get_observed_filelocs(found_files), - ) + # Subclass overrides may keep the original signatures, so failed sources go through instance state. + self.deactivate_deleted_dags(bundle_name=bundle.name, present=found_files) + self.clear_orphaned_import_errors( + bundle_name=bundle.name, + observed_filelocs=self._get_observed_filelocs(found_files), + ) + if self.api_client is not None: + any_refreshed = self._publish_pending_inventories(known_files) or any_refreshed if any_refreshed: # Bundle-to-team assignments can only change on bundle refresh, so clear the cache. - self._bundle_name_to_team_name = {} + if self.api_client is None: + self._bundle_name_to_team_name = {} self.handle_removed_files(known_files=known_files) self._resort_file_queue() self._add_new_files_to_queue(known_files=known_files) @@ -1118,6 +1478,26 @@ def _find_files_in_bundle(self, bundle: BaseDagBundle) -> DagBundleDiscoveryResu } return DagBundleDiscoveryResult(files=files, failed_sources=frozenset(failed_sources)) + def _filter_api_discovery_result( + self, bundle_name: str, discovery: DagBundleDiscoveryResult + ) -> DagBundleDiscoveryResult: + invalid_paths = set() + for path in sorted(self._get_observed_filelocs(discovery.files) | discovery.failed_sources): + if (error := _get_api_path_error(path)) is not None: + invalid_paths.add(path) + self.log.warning( + "Skipping source with an unrepresentable API path", + bundle_name=bundle_name, + relative_fileloc=path, + error=error, + ) + files = { + replace(file, definition_locs=file.definition_locs - invalid_paths) + for file in discovery.files + if str(file.rel_path) not in invalid_paths + } + return DagBundleDiscoveryResult(files=files, failed_sources=discovery.failed_sources - invalid_paths) + @staticmethod def _get_observed_filelocs(present: set[DagFileInfo]) -> set[str]: """Return the bundle-relative locations of the files and of the definitions found in them.""" @@ -1354,6 +1734,9 @@ def remove_orphaned_file_stats(self, present: set[DagFileInfo]): stats_to_remove = {file for file in self._file_stats if file.presence_key not in present_keys} for file in stats_to_remove: del self._file_stats[file] + for file in list(self._pending_publications): + if file.presence_key not in present_keys: + del self._pending_publications[file] def terminate_orphan_processes(self, present: set[DagFileInfo]): """Stop processors that are working on deleted files.""" @@ -1383,13 +1766,12 @@ def terminate_orphan_processes(self, present: set[DagFileInfo]): processor.close() self._file_stats.pop(file, None) - @provide_session def handle_parsing_result( self, file: DagFileInfo, proc: BaseDagFileProcessorProcess, *, - session: Session = NEW_SESSION, + session: Session | None = None, ) -> None: """ Post-process a single finished parse result. @@ -1399,10 +1781,8 @@ def handle_parsing_result( Extracted from ``_collect_results`` to keep result handling and persistence separate. - Owns its own DB session via ``@provide_session`` so subclasses that - forward results without touching the metadata DB (e.g. AIP-92 API-backed - deployments) can override this method without inheriting a session - created by the caller. + API mode queues results without opening a database session. DB mode + creates a session only for persistence unless the caller supplies one. If persistence fails, the error is logged and the previous persisted DAG/import-error counts are preserved while a minimal timestamp update @@ -1442,42 +1822,307 @@ def handle_parsing_result( team_name=team_name, ) - if proc.parsing_result is not None: - try: - self.persist_parsing_result( - bundle_name=file.bundle_name, - bundle_version=proc.parse_source.bundle_version, - version_data=( - dict(proc.parse_source.version_data) - if proc.parse_source.version_data is not None - else None - ), - parsing_result=proc.parsing_result, - run_duration=run_duration, - relative_fileloc=str(file.rel_path), - session=session, - ) - except Exception: - self.log.exception( - "Failed to persist parsing result for %s in bundle %s; " - "keeping previous persisted stats while throttling retries. " - "Other files in this cycle are still processed.", - str(file.rel_path), - file.bundle_name, - ) - current_stat = self._file_stats[file] - self._file_stats[file] = DagFileStat( - num_dags=current_stat.num_dags, - import_errors=current_stat.import_errors, - last_finish_time=finish_time, - last_duration=run_duration, - run_count=current_stat.run_count + 1, - last_num_of_db_queries=current_stat.last_num_of_db_queries, - ) + try: + if self.api_client is not None and not is_callback_only: + if proc.parsing_result is not None and proc.api_request_error is None: + self._pending_publications[file] = self._build_pending_publication( + file, proc, run_duration, next_stat + ) + else: + self._queue_failed_parse_result( + file, + proc, + run_duration, + next_stat, + reason="the parsing process exited without a result", + ) return + if proc.parsing_result is not None: + with create_session() if session is None else nullcontext(session) as session: + self.persist_parsing_result( + bundle_name=file.bundle_name, + bundle_version=proc.parse_source.bundle_version, + version_data=( + dict(proc.parse_source.version_data) + if proc.parse_source.version_data is not None + else None + ), + parsing_result=proc.parsing_result, + run_duration=run_duration, + relative_fileloc=str(file.rel_path), + session=session, + ) + except Exception: + self.log.exception( + "Failed to persist parsing result for %s in bundle %s; " + "keeping previous persisted stats while throttling retries. " + "Other files in this cycle are still processed.", + str(file.rel_path), + file.bundle_name, + ) + self._record_failed_publication(file, next_stat) + return self._file_stats[file] = next_stat + def _queue_failed_parse_result( + self, + file: DagFileInfo, + proc: BaseDagFileProcessorProcess, + run_duration: float, + stat: DagFileStat, + *, + reason: str, + ) -> None: + source = proc.parse_source + if source.refresh_generation != self._bundle_refresh_generations.get(file.bundle_name, 0): + self._add_files_to_queue([file], mode="front") + return + if proc.api_request_error is not None: + # The Task SDK answers a failed request as a missing value, so the Dags may hold a fallback. + reason = f"an Execution API request failed while parsing: {proc.api_request_error}" + try: + self._pending_publications[file] = self._build_rejection_report( + file, + bundle_version=source.bundle_version, + bundle_revision=source.bundle_revision, + parse_duration=run_duration, + stat=stat, + refresh_generation=source.refresh_generation, + reason=reason, + attempt_id=proc.id, + dispatch_sequence=proc.dispatch_sequence, + ) + except ValidationError: + self.log.exception("Unable to report failed parse for %s; preserving previous result", file) + self._record_failed_publication(file, stat) + + def _record_failed_publication(self, file: DagFileInfo, stat: DagFileStat) -> None: + self._file_stats[file] = attrs.evolve( + self._file_stats[file], + last_attempt_time=timezone.utcnow(), + last_duration=stat.last_duration, + run_count=stat.run_count, + ) + + def _publish_pending_results(self, *, deadline: float | None = None) -> None: + """Publish queued results until the deadline, stopping early while the API is unavailable.""" + if self.api_client is None: + return + # Runtime API-client imports stay local so managers using the in-process API do not load it. + from airflow.dag_processing.api_client import ( + DagProcessorRegistrationRetired, + get_error_reason, + is_transient_api_error, + ) + + if deadline is None: + deadline = time.monotonic() + _API_SEND_BUDGET_SECONDS + files = deque(self._pending_publications) + while files and time.monotonic() < deadline: + file = files.popleft() + pending = self._pending_publications[file] + if pending.refresh_generation != self._bundle_refresh_generations.get(file.bundle_name, 0): + del self._pending_publications[file] + self._add_files_to_queue([file], mode="front") + continue + if time.monotonic() < pending.next_attempt_time: + continue + pending.attempts += 1 + try: + self.api_client.publish_parse_result(pending.body) + except DagProcessorRegistrationRetired: + # Every later send would be refused too; the results stay pending until the manager stops. + raise + except Exception as error: + status_error = error if isinstance(error, httpx2.HTTPStatusError) else None + reason = get_error_reason(status_error) if status_error is not None else None + if reason == "source_changed": + # Another processor's inventory moved the revision; refreshing fetches it. + self.log.info( + "Bundle %s changed before %s was published; reparsing", file.bundle_name, file + ) + del self._pending_publications[file] + self.request_bundle_refresh(file.bundle_name) + self._add_files_to_queue([file], mode="front") + return + retries = conf.getint("workers", "execution_api_retries") + if is_transient_api_error(error) and pending.attempts < retries: + pending.next_attempt_time = time.monotonic() + _compute_retry_delay(pending.attempts) + self.log.warning("Unable to publish %s; retrying on a later loop", file) + del self._pending_publications[file] + self._pending_publications[file] = pending + return + if ( + status_error is not None + and not pending.is_rejection_report + and _is_rejected_content(status_error.response.status_code, reason) + ): + self.log.warning("The API server rejected the parsing result for %s", file) + status_code = status_error.response.status_code + detail = f"HTTP {status_code}: {reason}" if reason else f"HTTP {status_code}" + if reason == "invalid_dag": + message = status_error.response.json()["detail"].get("message") + if isinstance(message, str): + detail += f": {message}" + try: + self._pending_publications[file] = self._build_rejection_report( + file, + bundle_version=pending.body.bundle_version, + bundle_revision=pending.body.bundle_revision, + parse_duration=pending.body.parse_duration, + stat=pending.stat, + refresh_generation=pending.refresh_generation, + reason=f"the API server rejected it ({detail})", + ) + except ValidationError: + self.log.exception("Unable to report rejected parsing result for %s", file) + self._record_failed_publication(file, pending.stat) + del self._pending_publications[file] + continue + files.append(file) + continue + self.log.exception("Failed to publish parsing result for %s", file) + self._record_failed_publication(file, pending.stat) + else: + self._file_stats[file] = pending.stat + del self._pending_publications[file] + + def _build_pending_publication( + self, file: DagFileInfo, proc: BaseDagFileProcessorProcess, run_duration: float, stat: DagFileStat + ) -> PendingDagPublication: + source = proc.parse_source + try: + body = self._build_parse_result(file, proc, run_duration) + except ValidationError as error: + # The API validates with the same model, so sending the result could only be refused. + details = "; ".join( + f"{'.'.join(map(str, item['loc']))}: {item['msg']}" if item["loc"] else item["msg"] + for item in error.errors(include_url=False, include_input=False) + ) + reason = f"it is not a valid Dag publication ({details})" + else: + if len(body.model_dump_json().encode()) <= MAX_PUBLICATION_BYTES: + return PendingDagPublication( + body=body, stat=stat, refresh_generation=source.refresh_generation + ) + reason = f"it exceeds the {MAX_PUBLICATION_BYTES // (1024 * 1024)} MiB publication limit" + return self._build_rejection_report( + file, + bundle_version=source.bundle_version, + bundle_revision=source.bundle_revision, + parse_duration=run_duration, + stat=stat, + refresh_generation=source.refresh_generation, + reason=reason, + ) + + def _build_rejection_report( + self, + file: DagFileInfo, + *, + bundle_version: str | None, + bundle_revision: UUID | None, + parse_duration: float, + stat: DagFileStat, + refresh_generation: int, + reason: str, + attempt_id: UUID | None = None, + dispatch_sequence: int | None = None, + ) -> PendingDagPublication: + """Report a failed parse or an unpublishable result as an import error users can see.""" + if dispatch_sequence is None: + self._dispatch_sequence += 1 + dispatch_sequence = self._dispatch_sequence + if len(reason) > _MAX_REJECTION_REASON_LENGTH: + reason = reason[:_MAX_REJECTION_REASON_LENGTH] + "..." + relative_fileloc = str(file.rel_path) + import_errors = {relative_fileloc: f"The parsing result was not published: {reason}."} + return PendingDagPublication( + body=DagParseResultBody( + attempt_id=attempt_id if attempt_id is not None else uuid7(), + dispatch_sequence=dispatch_sequence, + bundle_name=file.bundle_name, + relative_fileloc=relative_fileloc, + bundle_version=bundle_version, + bundle_revision=bundle_revision, + parse_duration=parse_duration, + serialized_dags=[], + source_codes=[], + dag_source_indexes={}, + import_errors=import_errors, + result_unavailable=True, + ), + stat=attrs.evolve(stat, num_dags=0, import_errors=len(import_errors)), + refresh_generation=refresh_generation, + is_rejection_report=True, + ) + + def _build_parse_result( + self, file: DagFileInfo, proc: BaseDagFileProcessorProcess, run_duration: float + ) -> DagParseResultBody: + result = proc.parsing_result + if result is None or self.api_client is None: + raise ValueError("API publication requires a client and completed parse result") + import_errors = result.import_errors or {} + # The inventory skipped these container members, and the API refuses a result that names them. + dropped_paths = { + path + for path in ( + *import_errors, + *result.parsed_definitions, + *(dag.relative_fileloc for dag in result.serialized_dags), + ) + if isinstance(path, str) and _get_api_path_error(path) is not None + } + if dropped_paths: + self.log.warning( + "Not publishing definitions with an unrepresentable API path", + relative_fileloc=str(file.rel_path), + locations=sorted(dropped_paths), + ) + serialized_dags = [dag for dag in result.serialized_dags if dag.relative_fileloc not in dropped_paths] + published_dag_ids = {dag.dag_id for dag in serialized_dags} + warnings = [ + ParseWarning( + **{ + key: warning[key] if isinstance(warning, dict) else getattr(warning, key) + for key in ("dag_id", "warning_type", "message") + } + ) + for warning in result.warnings or [] + ] + # The API accepts warnings only for published Dags; a Dag that failed to serialize has an import error. + warnings = [warning for warning in warnings if warning.dag_id in published_dag_ids] + source_codes: list[ParseSourceCode] = [] + source_indexes: dict[tuple[str | None, str], int] = {} + dag_source_indexes = {} + for dag in serialized_dags: + source = result.dag_source_codes.get(dag.dag_id) + source_key = (source.source_code, source.language) if source else (None, "python") + if source_key not in source_indexes: + source_indexes[source_key] = len(source_codes) + source_codes.append(ParseSourceCode(source_code=source_key[0], language=source_key[1])) + dag_source_indexes[dag.dag_id] = source_indexes[source_key] + return DagParseResultBody( + attempt_id=proc.id, + dispatch_sequence=proc.dispatch_sequence, + bundle_name=file.bundle_name, + relative_fileloc=str(file.rel_path), + bundle_version=proc.parse_source.bundle_version, + bundle_revision=proc.parse_source.bundle_revision, + version_data=( + dict(proc.parse_source.version_data) if proc.parse_source.version_data is not None else None + ), + parse_duration=run_duration, + serialized_dags=[dag.data for dag in serialized_dags], + import_errors={path: error for path, error in import_errors.items() if path not in dropped_paths}, + parsed_definitions=[path for path in result.parsed_definitions if path not in dropped_paths], + warnings=warnings, + source_codes=source_codes, + dag_source_indexes=dag_source_indexes, + ) + def persist_parsing_result( self, *, @@ -1583,8 +2228,12 @@ def _get_logger_for_dag_file(self, dag_file: DagFileInfo): @functools.cached_property def client(self) -> Client: + if self.api_client is not None: + return self.api_client + from airflow.sdk.api.client import Client + self._api_server = InProcessExecutionAPI() client = Client(base_url=None, token="", dry_run=True, transport=self._api_server.transport) # Mypy is wrong -- the setter accepts a string on the property setter! `URLType = URL | str` client.base_url = "http://in-process.invalid./" @@ -1671,10 +2320,12 @@ def _start_new_processes(self): self._readmit_files_with_source() bundle_to_team = self._get_team_names({file.bundle_name for file in self._file_queue}) - while self._parallelism > len(self._processors) and self._file_queue: + while ( + self._parallelism > len(self._processors) + len(self._pending_publications) and self._file_queue + ): file, _ = self._file_queue.popitem(last=False) # Stop creating duplicate processor i.e. processor with the same filepath - if file in self._processors: + if file in self._processors or file in self._pending_publications: if file in self._priority_files: self._files_awaiting_source[file] = None continue @@ -1690,6 +2341,8 @@ def _start_new_processes(self): self._files_awaiting_source[file] = None else: self._priority_files.discard(file) + self._dispatch_sequence += 1 + processor.dispatch_sequence = self._dispatch_sequence stats.incr( "dag_processing.processes", tags=prune_dict( @@ -1734,6 +2387,7 @@ def _add_new_files_to_queue(self, known_files: dict[str, set[DagFileInfo]]): tracked_presence_keys = {file.presence_key for file in self._file_queue} tracked_presence_keys.update(file.presence_key for file in self._file_stats) tracked_presence_keys.update(file.presence_key for file in self._processors) + tracked_presence_keys.update(file.presence_key for file in self._pending_publications) tracked_presence_keys.update(file.presence_key for file in self._files_awaiting_source) for files in known_files.values(): for file in files: @@ -1786,7 +2440,7 @@ def _sort_by_mtime(self, files: Iterable[DagFileInfo]): modified_datetime = datetime.fromtimestamp(modified_timestamp, tz=timezone.utc) files_with_mtime[file] = modified_timestamp stat = file_stats_by_presence_key.get(file.presence_key) - last_time = stat.last_finish_time if stat else None + last_time = (stat.last_attempt_time or stat.last_finish_time) if stat else None if not last_time: continue if modified_datetime > last_time: @@ -1814,7 +2468,7 @@ def processed_recently(self, now, file): ), None, ) - last_time = stat.last_finish_time if stat else None + last_time = (stat.last_attempt_time or stat.last_finish_time) if stat else None if not last_time: return False elapsed_ss = (now - last_time).total_seconds() @@ -1847,6 +2501,7 @@ def prepare_file_queue(self, known_files: dict[str, set[DagFileInfo]]): # If the file path is already being processed, or if a file was # processed recently, wait until the next batch in_progress_keys = {file.presence_key for file in self._processors} + in_progress_keys.update(file.presence_key for file in self._pending_publications) in_progress_keys.update(file.presence_key for file in self._files_awaiting_source) now = timezone.utcnow() @@ -1858,7 +2513,7 @@ def prepare_file_queue(self, known_files: dict[str, set[DagFileInfo]]): for file in bundle_files: files.append(file) stat = file_stats_by_presence_key.get(file.presence_key) - last_time = stat.last_finish_time if stat else None + last_time = (stat.last_attempt_time or stat.last_finish_time) if stat else None if last_time and (now - last_time).total_seconds() < self._file_process_interval: recently_processed.add(file) @@ -1955,7 +2610,16 @@ def _kill_timed_out_processors(self): run_count=self._file_stats[file].run_count + 1, last_num_of_db_queries=0, ) - self._file_stats[file] = stat + if self.api_client is not None and not processor.had_callbacks: + self._queue_failed_parse_result( + file, + processor, + duration, + stat, + reason=f"the parsing process exceeded its timeout of {self.processor_timeout} seconds", + ) + else: + self._file_stats[file] = stat # Clean up `self._processors` after iterating over it for proc in processors_to_remove: @@ -2008,6 +2672,10 @@ def max_runs_reached(self): return False if self._priority_files: return False + if self._pending_publications: + return False + if self._pending_inventories: + return False if any( file not in self._callback_to_execute for file in [*self._file_queue, *self._files_awaiting_source] diff --git a/airflow-core/src/airflow/dag_processing/processor.py b/airflow-core/src/airflow/dag_processing/processor.py index 77249738c8c6..199b12edbb44 100644 --- a/airflow-core/src/airflow/dag_processing/processor.py +++ b/airflow-core/src/airflow/dag_processing/processor.py @@ -21,12 +21,15 @@ import importlib import logging import os +import sys import traceback from collections.abc import Callable, Mapping, Sequence from pathlib import Path from typing import TYPE_CHECKING, Annotated, Any, BinaryIO, ClassVar, Literal, cast +from uuid import UUID import attrs +import httpx2 from pydantic import BaseModel, Field, TypeAdapter from airflow._shared.observability.metrics import stats @@ -91,6 +94,7 @@ from structlog.typing import FilteringBoundLogger + from airflow.dag_processing.api_client import DagParseContext from airflow.sdk.api.client import Client from airflow.sdk.bases.operator import BaseOperator from airflow.sdk.definitions.context import Context @@ -597,6 +601,7 @@ class DagParseSource: bundle_version: str | None = None version_data: Mapping[str, Any] | None = None refresh_generation: int = 0 + bundle_revision: UUID | None = None @classmethod def for_callback(cls, bundle_version: str | None) -> Self: @@ -621,6 +626,7 @@ class BaseDagFileProcessorProcess(WatchedSubprocess, LoggingMixin): """The file's parse log, which the process closes. Without one, the output is discarded.""" parsing_result: DagFileParsingResult | None = None parse_source: DagParseSource = attrs.field(factory=DagParseSource) + dispatch_sequence: int = 0 had_callbacks: bool = False # Track if this process was started with callbacks to prevent stale DAG detection false positives client: Client | None = None @@ -632,6 +638,9 @@ class BaseDagFileProcessorProcess(WatchedSubprocess, LoggingMixin): bundle_name: str dag_file_rel_path: str + _api_parse_context: DagParseContext | None = attrs.field(init=False, default=None) + api_request_error: str | None = attrs.field(init=False, default=None) + """The Execution API request that failed while parsing; Dag code may then have used a fallback value.""" def _get_target_loggers(self) -> tuple[FilteringBoundLogger, ...]: base = super()._get_target_loggers() @@ -662,10 +671,15 @@ def _handle_parsing_result( self.parsing_result = msg return None, {} + def _handle_previous_successful_dag_run( + self, msg: GetPrevSuccessfulDagRun, log: FilteringBoundLogger, req_id: int + ) -> RequestResult: + # The run is looked up by task instance, and a parse process is not one, so the answer is always empty. + return PrevSuccessfulDagRunResult(), {"exclude_unset": True} + _client_request_types: ClassVar[tuple[type[BaseModel], ...]] = ( DeleteVariable, GetConnection, - GetPrevSuccessfulDagRun, GetPreviousDagRun, GetPreviousTI, GetTICount, @@ -686,7 +700,12 @@ def _handle_parsing_result( "dict[type[BaseModel], RequestHandler[BaseDagFileProcessorProcess]]", WatchedSubprocess._get_shared_request_handlers(*_client_request_types, MaskSecret), ), - **dict([register_request_method(DagFileParsingResult, _handle_parsing_result)]), + **dict( + [ + register_request_method(DagFileParsingResult, _handle_parsing_result), + register_request_method(GetPrevSuccessfulDagRun, _handle_previous_successful_dag_run), + ] + ), } def _handle_request(self, msg, log: FilteringBoundLogger, req_id: int) -> None: @@ -699,7 +718,34 @@ def _handle_request(self, msg, log: FilteringBoundLogger, req_id: int) -> None: ), ) return - super()._handle_request(msg, log, req_id) + # The HTTP client pulls in the Execution API versions. A DagProcessorAPIClient can only exist once + # its module is loaded, so the database-backed mode never has to import it. + api_client_module = sys.modules.get("airflow.dag_processing.api_client") + if api_client_module is None or not isinstance(self.client, api_client_module.DagProcessorAPIClient): + super()._handle_request(msg, log, req_id) + return + from airflow.api_fastapi.execution_api.datamodels.job import DagParseTokenBody + from airflow.dag_processing.api_client import DagParseContext + + if self._api_parse_context is None: + self._api_parse_context = DagParseContext( + request=DagParseTokenBody( + attempt_id=self.id, + bundle_name=self.bundle_name, + relative_fileloc=self.dag_file_rel_path, + ) + ) + with self.client.use_parse(self._api_parse_context): + try: + super()._handle_request(msg, log, req_id) + except Exception as error: + failure = ( + f"HTTP {error.response.status_code}" + if isinstance(error, httpx2.HTTPStatusError) + else type(error).__name__ + ) + self.api_request_error = f"{type(msg).__name__} ({failure})" + raise def _reject_request(self, msg, log: FilteringBoundLogger, req_id: int) -> None: log.error("Unhandled request", msg=msg) diff --git a/airflow-core/src/airflow/dag_processing/requested_work.py b/airflow-core/src/airflow/dag_processing/requested_work.py new file mode 100644 index 000000000000..c1814b6e0912 --- /dev/null +++ b/airflow-core/src/airflow/dag_processing/requested_work.py @@ -0,0 +1,139 @@ +# 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 + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from collections.abc import Callable, Collection, Sequence + from uuid import UUID + + from airflow.callbacks.callback_requests import CallbackRequest + from airflow.dag_processing.bundles.base import BaseDagBundle + from airflow.dag_processing.manager import DagFileInfo + + +class RequestedWorkSource: + """Supply requested parses and callbacks, and track their delivery lifecycle.""" + + requires_acknowledgment = False + + def claim_priority_files( + self, + bundles: Collection[BaseDagBundle], + *, + capacity: int, + unavailable_bundles: Collection[str], + active_attempts: Collection[UUID], + inventory_sequence: int, + ) -> list[DagFileInfo]: + """Claim priority parses using the manager's current dispatch context.""" + return [] + + def fetch_callbacks(self, bundles: Collection[BaseDagBundle], *, limit: int) -> list[CallbackRequest]: + """Claim callbacks for the configured bundles.""" + return [] + + def attempt_finished(self, attempt_id: UUID, *, had_callbacks: bool) -> None: + """ + Finish claims for this attempt's work kind. + + Callback completion must not release priority claims. Ordinary parses finish only after + publication reaches a terminal outcome or the parse fails without producing a result. + """ + + def flush(self, *, deadline: float | None = None) -> None: + """Deliver pending acknowledgments within the supplied time budget.""" + + def has_outstanding_work(self) -> bool: + """Return whether claimed work or acknowledgments remain pending.""" + return False + + def callbacks_started(self, attempt_id: UUID, callbacks: Sequence[CallbackRequest]) -> None: + """Assign the supplied callbacks to a processing attempt.""" + + def parse_started(self, file: DagFileInfo, attempt_id: UUID) -> None: + """Assign priority requests for this file to a processing attempt.""" + + def is_priority_ready(self, file: DagFileInfo, inventory_sequence: int) -> bool: + """Return whether the inventory is recent enough for this file's requests.""" + return True + + def has_priority_request(self, file: DagFileInfo) -> bool: + """Return whether the source holds a priority request for this file.""" + return False + + def has_callback_claim(self, request: CallbackRequest) -> bool: + """Return whether the source holds a claim for this callback.""" + return False + + def has_callback_attempt(self, attempt_id: UUID) -> bool: + """Return whether callbacks are assigned to this processing attempt.""" + return False + + def is_callback_preparation_ready(self, request: CallbackRequest) -> bool: + """Return whether preparation of this callback's bundle may be retried.""" + return True + + def callback_deferred(self, request: CallbackRequest) -> None: + """Retain a callback whose bundle could not be prepared.""" + + def callback_queued(self, request: CallbackRequest) -> None: + """Record that a callback is ready for dispatch.""" + + def callback_discarded(self, request: CallbackRequest) -> None: + """Finish a callback that cannot be executed.""" + + def inventory_published( + self, + bundle_name: str, + *, + sequence: int, + files: Collection[str], + failed_sources: Collection[str], + ) -> None: + """Reconcile priority requests against the bundle's accepted inventory.""" + + def bundle_unusable(self, bundle_name: str, *, active_attempts: Collection[UUID]) -> None: + """Finish requests for an unusable bundle unless their attempts are still active.""" + + +class DatabaseRequestedWorkSource(RequestedWorkSource): + """Use the manager's existing transactional database claim operations.""" + + def __init__( + self, + claim_priority_files: Callable[[], list[DagFileInfo]], + fetch_callbacks: Callable[[], list[CallbackRequest]], + ) -> None: + self._claim_priority_files = claim_priority_files + self._fetch_callbacks = fetch_callbacks + + def claim_priority_files( + self, + bundles: Collection[BaseDagBundle], + *, + capacity: int, + unavailable_bundles: Collection[str], + active_attempts: Collection[UUID], + inventory_sequence: int, + ) -> list[DagFileInfo]: + return self._claim_priority_files() + + def fetch_callbacks(self, bundles: Collection[BaseDagBundle], *, limit: int) -> list[CallbackRequest]: + return self._fetch_callbacks() diff --git a/airflow-core/tests/unit/api_fastapi/execution_api/test_dag_processor_client.py b/airflow-core/tests/unit/api_fastapi/execution_api/test_dag_processor_client.py index 0c7484acffd1..8faafcfccd8d 100644 --- a/airflow-core/tests/unit/api_fastapi/execution_api/test_dag_processor_client.py +++ b/airflow-core/tests/unit/api_fastapi/execution_api/test_dag_processor_client.py @@ -247,6 +247,8 @@ def test_lost_registration_and_completion_responses_over_http(api_url, provision request=DagParseTokenBody(attempt_id=uuid7(), bundle_name="bundle-a", relative_fileloc="dag.py") ) with processor.use_parse(context): + with pytest.raises(httpx2.ReadError): + processor.variables.get("parse-token-key") assert processor.variables.get("parse-token-key").value == "value" with pytest.raises(httpx2.HTTPStatusError) as error: processor.post(f"jobs/{job_id}/heartbeat") diff --git a/airflow-core/tests/unit/dag_processing/bundles/test_base.py b/airflow-core/tests/unit/dag_processing/bundles/test_base.py index 444087791a4f..dd8bdc2322c7 100644 --- a/airflow-core/tests/unit/dag_processing/bundles/test_base.py +++ b/airflow-core/tests/unit/dag_processing/bundles/test_base.py @@ -305,7 +305,7 @@ def test_that_stale_bundles_are_removed( assert len(bundle_folders) == 5 num += 1 with time_machine.travel(h0 + timedelta(hours=when_hours), tick=False): - BundleUsageTrackingManager()._remove_stale_bundle_versions_for_bundle(bundle_name=bundle_name) + BundleUsageTrackingManager().remove_stale_bundle_versions_for_bundle(bundle_name=bundle_name) lock_files = list(bundle_tracking_dir.iterdir()) assert len(lock_files) == expected_remaining bundle_folders = list(b.versions_dir.iterdir()) diff --git a/airflow-core/tests/unit/dag_processing/bundles/test_dag_bundle_manager.py b/airflow-core/tests/unit/dag_processing/bundles/test_dag_bundle_manager.py index aef28b989ced..6accd346553c 100644 --- a/airflow-core/tests/unit/dag_processing/bundles/test_dag_bundle_manager.py +++ b/airflow-core/tests/unit/dag_processing/bundles/test_dag_bundle_manager.py @@ -277,6 +277,42 @@ def clear_db(): clear_db_dag_bundles() +@pytest.mark.parametrize("operation", ["get", "list", "sync"]) +@pytest.mark.db_test +@conf_vars({("core", "load_examples"): "False"}) +def test_bundle_construction_and_url_resolution_use_the_bundle_context(clear_db, operation): + active = [] + seen = [] + + @contextlib.contextmanager + def bundle_context(name): + active.append(name) + try: + yield + finally: + active.pop() + + def read_secret(*args, **kwargs): + seen.append(active[-1]) + + config = [*BASIC_BUNDLE_CONFIG, {"name": "excluded", "classpath": "missing.Bundle", "kwargs": {}}] + with ( + conf_vars({("dag_processor", "dag_bundle_config_list"): json.dumps(config)}), + patch.object(BasicBundle, "__init__", autospec=True, side_effect=read_secret), + patch.object(BasicBundle, "view_url_template", autospec=True, side_effect=read_secret), + ): + manager = DagBundlesManager(bundle_names=["my-test-bundle"], bundle_context=bundle_context) + if operation == "get": + manager.get_bundle("my-test-bundle") + elif operation == "list": + list(manager.get_all_dag_bundles()) + else: + manager.sync_bundles_to_db(deactivate_missing=False) + assert seen + assert set(seen) == {"my-test-bundle"} + assert active == [] + + @pytest.mark.db_test @conf_vars({("core", "LOAD_EXAMPLES"): "False"}) def test_sync_bundles_to_db(clear_db, session): diff --git a/airflow-core/tests/unit/dag_processing/conftest.py b/airflow-core/tests/unit/dag_processing/conftest.py new file mode 100644 index 000000000000..6b5acec2fcd9 --- /dev/null +++ b/airflow-core/tests/unit/dag_processing/conftest.py @@ -0,0 +1,67 @@ +# 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 httpx2 +import jwt +import pytest + + +@pytest.fixture +def make_job_token(): + def create(**claims): + return jwt.encode( + {"iat": 0, "exp": 300, "scope": "dag_processor", "job_id": 1, **claims}, + "processor-client-unit-test-signing-key", + ) + + return create + + +@pytest.fixture +def make_registration_response(make_job_token): + def create(*, job_id=1, token=None, expires_in=300, **kwargs): + return httpx2.Response( + 201, + json={ + "job_id": job_id, + "token": token or make_job_token(job_id=job_id), + "expires_in": expires_in, + }, + **kwargs, + ) + + return create + + +@pytest.fixture +def make_parse_token_response(make_job_token): + def create(*, expires_in=60, **claims): + token = make_job_token( + **{ + "scope": "dag_parse", + "sub": "00000000-0000-0000-0000-000000000001", + "session_id": "00000000-0000-0000-0000-000000000002", + "dag_bundles": ["bundle-a"], + "relative_fileloc": "dag.py", + "exp": 60, + **claims, + } + ) + return httpx2.Response(200, json={"token": token, "expires_in": expires_in}) + + return create diff --git a/airflow-core/tests/unit/dag_processing/test_api_client.py b/airflow-core/tests/unit/dag_processing/test_api_client.py index 48c947b43224..78f7a0aec71d 100644 --- a/airflow-core/tests/unit/dag_processing/test_api_client.py +++ b/airflow-core/tests/unit/dag_processing/test_api_client.py @@ -16,16 +16,21 @@ # under the License. from __future__ import annotations +import asyncio import json import runpy from contextvars import Context from unittest import mock import httpx2 -import jwt import pytest from tenacity import wait_none +from uuid6 import uuid7 +from airflow.api_fastapi.execution_api.datamodels.dag_parsing import ( + DagBundleInventoryBody, + DagParseResultBody, +) from airflow.api_fastapi.execution_api.datamodels.job import DagParseTokenBody, JobState, TerminalJobState from airflow.dag_processing import api_client from airflow.dag_processing.api_client import ( @@ -37,24 +42,9 @@ ) from airflow.sdk.api.client import API_RETRIES, Client from airflow.sdk.api.datamodels import _generated +from airflow.sdk.execution_time import task_runner from airflow.sdk.execution_time.comms import GetVariable, GetXCom, MaskSecret, VariableResult - -SECRET = "processor-client-unit-test-signing-key" - - -def make_job_token(**claims): - return jwt.encode( - {"iat": 0, "exp": 300, "scope": "dag_processor", "job_id": 1, **claims}, - SECRET, - ) - - -def make_registration_response(*, job_id=1, token=None, expires_in=300, **kwargs): - return httpx2.Response( - 201, - json={"job_id": job_id, "token": token or make_job_token(job_id=job_id), "expires_in": expires_in}, - **kwargs, - ) +from airflow.sdk.execution_time.secrets.execution_api import ExecutionAPISecretsBackend @pytest.fixture @@ -105,7 +95,9 @@ def handle(request): client.close() -def test_registration_and_runtime_use_distinct_credentials(make_client): +def test_registration_and_runtime_use_distinct_credentials( + make_client, make_job_token, make_registration_response +): client, requests = make_client( make_registration_response(headers={"Refreshed-API-Token": "wrong-token"}), httpx2.Response(200, json={"state": "restarting"}, headers={"Refreshed-API-Token": "wrong-token"}), @@ -142,7 +134,42 @@ def test_unread_non_json_error_body_is_a_plain_status_error(make_client): client.register_job(retry=False) -def test_registration_identity_survives_response_loss_but_not_a_process_restart(make_client): +@pytest.mark.parametrize( + ("status_code", "transient"), + [ + (400, False), + (404, False), + (409, False), + (413, False), + (408, True), + (429, True), + (500, True), + (503, True), + ], +) +def test_only_408_429_and_5xx_responses_are_transient(status_code, transient): + request = httpx2.Request("POST", "http://api/jobs/1/parse-results") + error = httpx2.HTTPStatusError( + "Failed", request=request, response=httpx2.Response(status_code, request=request) + ) + assert api_client.is_transient_api_error(error) is transient + + +@pytest.mark.parametrize( + ("error", "transient"), + [ + (httpx2.ConnectError("Refused"), True), + (httpx2.ReadTimeout("Timed out"), True), + (ValueError("Bad"), False), + ], +) +def test_request_errors_without_a_response_are_transient(error, transient): + assert api_client.is_transient_api_error(error) is transient + + +def test_registration_identity_survives_response_loss_but_not_a_process_restart( + make_client, make_registration_response +): first, requests = make_client(httpx2.ReadError("Lost acknowledgment"), make_registration_response()) second, _ = make_client() @@ -156,7 +183,7 @@ def test_registration_identity_survives_response_loss_but_not_a_process_restart( @pytest.mark.parametrize("succeeds", [False, True]) @pytest.mark.parametrize("status", [401, 403]) def test_registration_reloads_a_rotated_credential_after_authentication_failure( - make_client, token_file, status, succeeds + make_client, token_file, status, succeeds, make_registration_response ): def rotate(request): token_file.write_text("session-2") @@ -193,7 +220,7 @@ def test_registration_errors_do_not_start_another_job(make_client, status): assert len(requests) == 1 -def test_registration_retry_after_a_crashed_job_keeps_its_identity(make_client): +def test_registration_retry_after_a_crashed_job_keeps_its_identity(make_client, make_registration_response): client, requests = make_client( httpx2.Response(409, json={"detail": {"reason": "job_running"}}), make_registration_response(), @@ -209,7 +236,9 @@ def test_registration_retry_after_a_crashed_job_keeps_its_identity(make_client): assert requests[0].content == requests[1].content -def test_rotation_is_detected_within_the_cache_interval(make_client, token_file, clock): +def test_rotation_is_detected_within_the_cache_interval( + make_client, token_file, clock, make_job_token, make_registration_response +): client, requests = make_client( make_registration_response(), httpx2.Response(204), @@ -233,7 +262,7 @@ def test_rotation_is_detected_within_the_cache_interval(make_client, token_file, assert requests[3].headers["Authorization"] == f"Bearer {make_job_token(iat=30, exp=330)}" -def test_job_token_renewal_uses_monotonic_time(make_client, clock, time_machine): +def test_job_token_renewal_uses_monotonic_time(make_client, clock, time_machine, make_registration_response): client, requests = make_client( make_registration_response(), httpx2.Response(204), make_registration_response(), httpx2.Response(204) ) @@ -250,7 +279,7 @@ def test_job_token_renewal_uses_monotonic_time(make_client, clock, time_machine) @pytest.mark.parametrize("status", [401, 403, 404, 409]) -def test_runtime_errors_do_not_renew_credentials(make_client, status): +def test_runtime_errors_do_not_renew_credentials(make_client, status, make_registration_response): client, requests = make_client(make_registration_response(), httpx2.Response(status)) client.register_job() @@ -263,7 +292,9 @@ def test_runtime_errors_do_not_renew_credentials(make_client, status): @pytest.mark.parametrize("expired", [False, True]) @pytest.mark.parametrize("failure", [httpx2.ReadError("Unavailable"), httpx2.Response(503)]) -def test_heartbeat_does_not_retry_transport_failures(make_client, clock, expired, failure): +def test_heartbeat_does_not_retry_transport_failures( + make_client, clock, expired, failure, make_registration_response +): client, requests = make_client(make_registration_response(), failure) client.register_job() if expired: @@ -277,7 +308,9 @@ def test_heartbeat_does_not_retry_transport_failures(make_client, clock, expired @pytest.mark.parametrize("registered", [False, True]) @pytest.mark.parametrize("missing", [False, True]) -def test_unreadable_credentials_fail_closed(make_client, token_file, clock, registered, missing): +def test_unreadable_credentials_fail_closed( + make_client, token_file, clock, registered, missing, make_registration_response +): client, requests = make_client(make_registration_response()) if registered: client.register_job() @@ -293,7 +326,7 @@ def test_unreadable_credentials_fail_closed(make_client, token_file, clock, regi assert len(requests) == int(registered) -def test_renewal_cannot_replace_the_job(make_client): +def test_renewal_cannot_replace_the_job(make_client, make_job_token, make_registration_response): client, _ = make_client(make_registration_response(), make_registration_response(job_id=2)) client.register_job() @@ -305,7 +338,7 @@ def test_renewal_cannot_replace_the_job(make_client): @pytest.mark.parametrize("expires_in", [0, -1, "soon"]) -def test_invalid_job_token_lifetimes_are_not_adopted(make_client, expires_in): +def test_invalid_job_token_lifetimes_are_not_adopted(make_client, expires_in, make_registration_response): client, _ = make_client(make_registration_response(expires_in=expires_in)) with pytest.raises(ValueError, match="expires_in"): @@ -332,7 +365,9 @@ def test_runtime_operations_require_registration(make_client, operation): assert requests == [] -def test_completion_recovers_a_lost_acknowledgment_with_the_same_token_and_outcome(make_client): +def test_completion_recovers_a_lost_acknowledgment_with_the_same_token_and_outcome( + make_client, make_registration_response +): client, requests = make_client( make_registration_response(), httpx2.ReadError("Lost acknowledgment"), httpx2.Response(204) ) @@ -348,7 +383,7 @@ def test_completion_recovers_a_lost_acknowledgment_with_the_same_token_and_outco def test_completion_retries_remain_possible_after_transport_retries_are_exhausted( - make_client, token_file, clock + make_client, token_file, clock, make_job_token, make_registration_response ): client, requests = make_client( make_registration_response(), @@ -369,7 +404,9 @@ def test_completion_retries_remain_possible_after_transport_retries_are_exhauste @pytest.mark.parametrize("status", [204, 401, 403, 404]) -def test_completion_stops_normal_work_even_when_acknowledgment_is_uncertain(make_client, status): +def test_completion_stops_normal_work_even_when_acknowledgment_is_uncertain( + make_client, status, make_registration_response +): client, requests = make_client(make_registration_response(), httpx2.Response(status)) client.register_job() if status == 204: @@ -397,7 +434,9 @@ def test_invalid_reload_interval_is_rejected(make_client, interval): @pytest.mark.parametrize( "failure", [httpx2.ReadTimeout("Unavailable"), httpx2.Response(503), httpx2.Response(403)] ) -def test_failed_early_renewal_keeps_using_the_valid_token(make_client, clock, operation, failure): +def test_failed_early_renewal_keeps_using_the_valid_token( + make_client, clock, operation, failure, make_job_token, make_registration_response +): response_body = {"state": "running"} if operation == "heartbeat" else {"key": "key", "value": "value"} client, requests = make_client( make_registration_response(), @@ -427,7 +466,9 @@ def test_failed_early_renewal_keeps_using_the_valid_token(make_client, clock, op @pytest.mark.parametrize("missing", [False, True]) -def test_unreadable_rotated_file_does_not_discard_a_valid_token(make_client, token_file, clock, missing): +def test_unreadable_rotated_file_does_not_discard_a_valid_token( + make_client, token_file, clock, missing, make_registration_response +): client, requests = make_client( make_registration_response(), httpx2.Response(200, json={"state": "running"}) ) @@ -439,7 +480,9 @@ def test_unreadable_rotated_file_does_not_discard_a_valid_token(make_client, tok assert len(requests) == 2 -def test_renewal_that_outlasts_the_token_requires_synchronous_recovery(make_client, clock): +def test_renewal_that_outlasts_the_token_requires_synchronous_recovery( + make_client, clock, make_registration_response +): def time_out(request): clock.return_value = 300 raise httpx2.ReadTimeout("Outlasted the token") @@ -456,7 +499,9 @@ def time_out(request): @pytest.mark.parametrize("complete", [False, True]) -def test_retired_registration_signals_restart_without_blocking_valid_requests(make_client, clock, complete): +def test_retired_registration_signals_restart_without_blocking_valid_requests( + make_client, clock, complete, make_job_token, make_registration_response +): client, requests = make_client( make_registration_response(), httpx2.Response(409, json={"detail": {"reason": "registration_retired"}}), @@ -490,7 +535,7 @@ def test_other_conflicts_are_not_mistaken_for_retirement(make_client, payload): assert not client.restart_required -def test_closed_job_signals_restart(make_client): +def test_closed_job_signals_restart(make_client, make_registration_response): client, _ = make_client( make_registration_response(), httpx2.Response(403, json={"detail": {"reason": "job_closed", "message": "replaced"}}), @@ -506,7 +551,9 @@ def test_closed_job_signals_restart(make_client): @pytest.mark.parametrize( "payload", [{"detail": "Invalid auth token"}, {"detail": {"reason": "bundle_not_granted"}}] ) -def test_other_authorization_failures_are_not_mistaken_for_a_closed_job(make_client, payload): +def test_other_authorization_failures_are_not_mistaken_for_a_closed_job( + make_client, payload, make_registration_response +): client, _ = make_client(make_registration_response(), httpx2.Response(403, json=payload)) client.register_job() @@ -516,7 +563,7 @@ def test_other_authorization_failures_are_not_mistaken_for_a_closed_job(make_cli assert not client.restart_required -def test_sdk_helpers_keep_bundle_context_for_reads_and_writes(make_client): +def test_sdk_helpers_keep_bundle_context_for_reads_and_writes(make_client, make_registration_response): client, requests = make_client( make_registration_response(), httpx2.Response(200, json={"key": "key", "value": "value"}), @@ -546,7 +593,9 @@ def test_sdk_helpers_keep_bundle_context_for_reads_and_writes(make_client): assert json.loads(requests[2].content)["val"] == "new" -def test_bundle_context_preserves_headers_and_restores_context_on_error(make_client): +def test_bundle_context_preserves_headers_and_restores_context_on_error( + make_client, make_registration_response +): client, requests = make_client( make_registration_response(), httpx2.Response(204), @@ -588,7 +637,9 @@ def test_empty_bundle_context_is_rejected(make_client): @pytest.mark.parametrize("lost_acknowledgment", [False, True]) -def test_completion_renews_an_expired_token_if_the_job_is_still_open(make_client, clock, lost_acknowledgment): +def test_completion_renews_an_expired_token_if_the_job_is_still_open( + make_client, clock, lost_acknowledgment, make_job_token, make_registration_response +): failures = ( [httpx2.ReadError("Lost acknowledgment") for _ in range(API_RETRIES)] if lost_acknowledgment else [] ) @@ -614,7 +665,9 @@ def test_completion_renews_an_expired_token_if_the_job_is_still_open(make_client } -def test_completion_does_not_claim_success_when_expired_registration_is_retired(make_client, clock): +def test_completion_does_not_claim_success_when_expired_registration_is_retired( + make_client, clock, make_registration_response +): client, requests = make_client( make_registration_response(), httpx2.Response(409, json={"detail": {"reason": "registration_retired"}}), @@ -632,7 +685,9 @@ def test_completion_does_not_claim_success_when_expired_registration_is_retired( @pytest.mark.parametrize("succeeds", [False, True]) @pytest.mark.parametrize("status", [401, 403]) -def test_completion_recovers_if_the_token_expires_during_the_request(make_client, clock, status, succeeds): +def test_completion_recovers_if_the_token_expires_during_the_request( + make_client, clock, status, succeeds, make_registration_response +): def expire(request): clock.return_value += 300 return httpx2.Response(status) @@ -673,7 +728,7 @@ def test_control_contracts_do_not_require_new_sdk_models(monkeypatch, token_file assert isinstance(client._registration, api_client.JobRegisterBody) -def test_secrets_comms_answers_lookups_for_the_selected_bundle(make_client): +def test_secrets_comms_answers_lookups_for_the_selected_bundle(make_client, make_registration_response): client, requests = make_client( make_registration_response(), httpx2.Response(200, json={"key": "my_key", "value": "my_value"}) ) @@ -698,6 +753,72 @@ def test_secrets_comms_ignores_masking_and_rejects_other_messages(make_client): assert requests == [] +def test_secrets_comms_answers_async_lookups(make_client, make_registration_response, monkeypatch): + client, _ = make_client( + make_registration_response(), httpx2.Response(200, json={"key": "my_key", "value": "my_value"}) + ) + client.register_job() + monkeypatch.setattr(task_runner, "SUPERVISOR_COMMS", DagProcessorSecretsComms(client), raising=False) + + with client.use_bundle("bundle-a"): + value = asyncio.run(ExecutionAPISecretsBackend().aget_variable("my_key")) + + assert value == "my_value" + + +@pytest.mark.parametrize( + ("failures", "recovers"), + [ + pytest.param([httpx2.ReadError("Connection reset")], True, id="reset"), + pytest.param([httpx2.Response(503)], True, id="unavailable"), + pytest.param([httpx2.Response(503), httpx2.Response(503)], False, id="still-unavailable"), + pytest.param([httpx2.ReadTimeout("No response")], False, id="timeout"), + pytest.param([httpx2.Response(429)], False, id="throttled"), + pytest.param([httpx2.Response(400, json={"detail": "Bad request"})], False, id="rejected"), + ], +) +def test_immediate_retries_replace_waiting_retries( + make_client, failures, recovers, make_registration_response +): + client, requests = make_client( + make_registration_response(), + *failures, + httpx2.Response(200, json={"key": "my_key", "value": "my_value"}), + ) + client.register_job() + + with client.use_immediate_retries(): + if recovers: + assert client.get("variables/my_key").json()["value"] == "my_value" + else: + with pytest.raises(httpx2.HTTPError): + client.get("variables/my_key") + + retried = recovers or len(failures) > 1 + assert len(requests) == (3 if retried else 2) + + +def test_parse_requests_keep_one_attempt_with_immediate_retries( + make_client, make_registration_response, make_parse_token_response +): + client, requests = make_client( + make_registration_response(), + make_parse_token_response(), + httpx2.Response(503), + httpx2.Response(200, json={"key": "key", "value": "value"}), + ) + client.register_job() + + with ( + client.use_immediate_retries(), + client.use_parse(make_parse_context()), + pytest.raises(httpx2.HTTPStatusError), + ): + client.get("variables/key") + + assert len(requests) == 3 + + def make_parse_context(**kwargs): return DagParseContext( request=DagParseTokenBody( @@ -711,25 +832,9 @@ def make_parse_context(**kwargs): ) -def make_parse_token_response(*, expires_in=60, **claims): - token = jwt.encode( - { - "scope": "dag_parse", - "sub": "00000000-0000-0000-0000-000000000001", - "session_id": "00000000-0000-0000-0000-000000000002", - "job_id": 1, - "dag_bundles": ["bundle-a"], - "relative_fileloc": "dag.py", - "iat": 0, - "exp": 60, - **claims, - }, - SECRET, - ) - return httpx2.Response(200, json={"token": token, "expires_in": expires_in}) - - -def test_parse_requests_exchange_once_and_restore_the_manager_credential(make_client): +def test_parse_requests_exchange_once_and_restore_the_manager_credential( + make_client, make_job_token, make_registration_response, make_parse_token_response +): exchanged = make_parse_token_response() client, requests = make_client( make_registration_response(), @@ -758,7 +863,9 @@ def test_parse_requests_exchange_once_and_restore_the_manager_credential(make_cl assert requests[2].headers["Airflow-Dag-Bundle"] == "bundle-a" -def test_parse_exchange_recovers_a_lost_response_without_changing_attempt(make_client): +def test_parse_exchange_recovers_a_lost_response_without_changing_attempt( + make_client, make_registration_response, make_parse_token_response +): client, requests = make_client( make_registration_response(), httpx2.ReadError("exchange acknowledgment lost"), @@ -767,13 +874,74 @@ def test_parse_exchange_recovers_a_lost_response_without_changing_attempt(make_c ) client.register_job() with client.use_parse(make_parse_context()): + with pytest.raises(httpx2.ReadError): + client.get("variables/key") client.get("variables/key") assert requests[1].content == requests[2].content assert len(requests) == 4 -def test_interleaved_parses_keep_distinct_file_credentials(make_client): +@pytest.mark.parametrize( + ("request_kwargs", "expected_timeout"), + [ + pytest.param({}, httpx2.Timeout(5), id="client-default"), + pytest.param({"timeout": 2.5}, httpx2.Timeout(2.5), id="explicit-timeout"), + pytest.param({"timeout": None}, httpx2.Timeout(None), id="disabled-timeout"), + pytest.param( + {"timeout": httpx2.Timeout(4, connect=2)}, + httpx2.Timeout(4, connect=2), + id="per-phase-timeout", + ), + ], +) +def test_parse_requests_make_one_attempt_with_the_request_timeout( + make_client, request_kwargs, expected_timeout, make_registration_response, make_parse_token_response +): + client, requests = make_client( + make_registration_response(), make_parse_token_response(), httpx2.Response(503), timeout=5 + ) + client.register_job() + + with client.use_parse(make_parse_context()), pytest.raises(httpx2.HTTPStatusError): + client.get("variables/key", **request_kwargs) + + assert len(requests) == 3 + assert requests[1].extensions["timeout"] == expected_timeout.as_dict() + assert requests[2].extensions["timeout"] == expected_timeout.as_dict() + + +@pytest.mark.parametrize(("expired", "tick"), [("parse", 60), ("job", 300)]) +def test_required_token_renewals_use_the_runtime_request_timeout( + make_client, clock, expired, tick, make_registration_response, make_parse_token_response +): + client, requests = make_client( + make_registration_response(), + make_parse_token_response(), + httpx2.Response(200), + *([make_registration_response()] if expired == "job" else []), + make_parse_token_response(), + httpx2.Response(200), + timeout=5, + ) + client.register_job() + + with client.use_parse(make_parse_context()): + client.get("variables/key") + clock.return_value = tick + client.get("variables/key", timeout=2.5) + + assert [request.url.path for request in requests[3:]] == [ + *(["/execution/jobs"] if expired == "job" else []), + "/execution/jobs/1/parse-token", + "/execution/variables/key", + ] + assert all(request.extensions["timeout"] == httpx2.Timeout(2.5).as_dict() for request in requests[3:]) + + +def test_interleaved_parses_keep_distinct_file_credentials( + make_client, make_registration_response, make_parse_token_response +): first_response = make_parse_token_response() second_response = make_parse_token_response( sub="00000000-0000-0000-0000-000000000003", @@ -809,7 +977,9 @@ def test_interleaved_parses_keep_distinct_file_credentials(make_client): @pytest.mark.parametrize("renew_at", [48, 61]) -def test_parse_credential_renews_with_the_same_file_and_attempt(make_client, clock, renew_at): +def test_parse_credential_renews_with_the_same_file_and_attempt( + make_client, clock, renew_at, make_registration_response, make_parse_token_response +): client, requests = make_client( make_registration_response(), make_parse_token_response(), @@ -833,11 +1003,17 @@ def test_parse_credential_renews_with_the_same_file_and_attempt(make_client, clo @pytest.mark.parametrize( "failure", - [httpx2.ReadError("unavailable"), httpx2.Response(503), httpx2.Response(200, json={"token": "invalid"})], + [ + httpx2.ReadError("unavailable"), + httpx2.Response(408), + httpx2.Response(429), + httpx2.Response(503), + httpx2.Response(200, json={"token": "invalid"}), + ], ) @pytest.mark.parametrize("recovers_at_expiry", [False, True]) def test_failed_early_parse_renewal_keeps_the_valid_token_until_expiry( - make_client, clock, failure, recovers_at_expiry + make_client, clock, failure, recovers_at_expiry, make_registration_response, make_parse_token_response ): token = make_parse_token_response() client, requests = make_client( @@ -879,7 +1055,9 @@ def test_failed_early_parse_renewal_keeps_the_valid_token_until_expiry( assert len(requests) == 7 -def test_parse_renewal_that_outlasts_the_token_requires_synchronous_recovery(make_client, clock): +def test_parse_renewal_that_outlasts_the_token_requires_synchronous_recovery( + make_client, clock, make_registration_response, make_parse_token_response +): def expire(request): clock.return_value = 60 return httpx2.Response(503) @@ -903,7 +1081,9 @@ def expire(request): @pytest.mark.parametrize("reason", ["job_closed", "bundle_not_granted"]) -def test_early_parse_renewal_does_not_hide_authorization_errors(make_client, clock, reason): +def test_early_parse_renewal_does_not_hide_authorization_errors( + make_client, clock, reason, make_registration_response, make_parse_token_response +): client, requests = make_client( make_registration_response(), make_parse_token_response(), @@ -924,7 +1104,9 @@ def test_early_parse_renewal_does_not_hide_authorization_errors(make_client, clo @pytest.mark.parametrize("expires_in", [0, -1, "soon"]) -def test_invalid_exchanged_lifetimes_never_reach_a_runtime_endpoint(make_client, expires_in): +def test_invalid_exchanged_lifetimes_never_reach_a_runtime_endpoint( + make_client, expires_in, make_registration_response, make_parse_token_response +): client, requests = make_client( make_registration_response(), make_parse_token_response(expires_in=expires_in) ) @@ -938,7 +1120,9 @@ def test_invalid_exchanged_lifetimes_never_reach_a_runtime_endpoint(make_client, assert context.token is None -def test_exchange_failure_restores_context_and_signals_a_closed_job(make_client): +def test_exchange_failure_restores_context_and_signals_a_closed_job( + make_client, make_job_token, make_registration_response +): client, requests = make_client( make_registration_response(), httpx2.Response(403, json={"detail": {"reason": "job_closed"}}), @@ -951,3 +1135,97 @@ def test_exchange_failure_restores_context_and_signals_a_closed_job(make_client) assert client.restart_required assert client.heartbeat() == JobState.RESTARTING assert requests[-1].headers["Authorization"] == f"Bearer {make_job_token()}" + + +@pytest.mark.parametrize("expired", [False, True]) +@pytest.mark.parametrize("failure", [httpx2.ReadTimeout("Lost response"), httpx2.Response(503)]) +def test_publication_attempt_does_not_sleep_through_heartbeats( + make_client, clock, expired, failure, make_registration_response +): + body = DagParseResultBody( + attempt_id=uuid7(), + dispatch_sequence=1, + bundle_name="bundle-a", + relative_fileloc="dag.py", + parse_duration=0.1, + serialized_dags=[], + source_codes=[], + dag_source_indexes={}, + ) + responses = [make_registration_response()] + if expired: + responses.append(make_registration_response()) + responses.extend( + [ + failure, + httpx2.Response(200, json={"state": "running"}), + httpx2.Response( + 200, json={"attempt_id": str(body.attempt_id), "accepted_at": "2026-10-05T12:00:00Z"} + ), + ] + ) + client, requests = make_client(*responses) + client.register_job() + if expired: + clock.return_value = 300 + with pytest.raises(httpx2.HTTPError): + client.publish_parse_result(body) + assert len(requests) == (3 if expired else 2) + publication_timeout = requests[-1].extensions["timeout"] + assert publication_timeout["connect"] <= 1 + assert publication_timeout["pool"] <= 1 + assert publication_timeout["read"] == client.timeout.read > 1 + if expired: + assert all(value <= 1 for value in requests[1].extensions["timeout"].values()) + assert client.heartbeat() == JobState.RUNNING + assert client.publish_parse_result(body).attempt_id == body.attempt_id + assert requests[-1].content == requests[-3].content + + +def test_inventory_waits_for_a_slow_write_but_connects_quickly(make_client, make_registration_response): + client, requests = make_client( + make_registration_response(), + httpx2.Response( + 200, + json={ + "attempt_id": str(uuid7()), + "accepted_at": "2026-10-05T12:00:00Z", + "revision": str(uuid7()), + }, + ), + ) + client.register_job() + + client.publish_inventory( + "bundle-a", + DagBundleInventoryBody(attempt_id=uuid7(), dispatch_sequence=1, expected_revision=None, files=[]), + ) + + timeout = requests[-1].extensions["timeout"] + assert timeout["connect"] <= 1 + assert timeout["read"] == client.timeout.read > 1 + + +@pytest.mark.parametrize("retry", [False, True]) +def test_catalog_read_waits_for_a_slow_response_and_retries_only_when_asked( + make_client, retry, make_registration_response +): + catalog = [ + {"name": "bundle-a", "version": None, "last_refreshed": None, "revision": None, "team_name": None} + ] + client, requests = make_client( + make_registration_response(), httpx2.Response(503), httpx2.Response(200, json=catalog) + ) + client.register_job() + + if retry: + assert [bundle.name for bundle in client.get_bundles(retry=True)] == ["bundle-a"] + else: + with pytest.raises(httpx2.HTTPStatusError): + client.get_bundles() + + assert len(requests) == (3 if retry else 2) + timeout = requests[-1].extensions["timeout"] + assert timeout["connect"] <= 1 + assert timeout["pool"] <= 1 + assert timeout["read"] == client.timeout.read > 1 diff --git a/airflow-core/tests/unit/dag_processing/test_manager.py b/airflow-core/tests/unit/dag_processing/test_manager.py index d10ea3c1c2e2..de6e69b0b4c4 100644 --- a/airflow-core/tests/unit/dag_processing/test_manager.py +++ b/airflow-core/tests/unit/dag_processing/test_manager.py @@ -23,21 +23,25 @@ import os import random import re +import runpy import selectors import shutil import signal +import sys import textwrap import time import zipfile from collections import Counter, OrderedDict, defaultdict from concurrent.futures import ThreadPoolExecutor -from contextlib import contextmanager +from contextlib import contextmanager, nullcontext from datetime import datetime, timedelta from pathlib import Path from socket import socket, socketpair from unittest import mock from unittest.mock import MagicMock +from uuid import UUID +import httpx2 import msgspec import pytest import structlog @@ -49,11 +53,23 @@ from airflow._shared.observability.metrics.statsd_logger import SafeStatsdLogger from airflow._shared.timezones import timezone +from airflow.api_fastapi.execution_api.datamodels.dag_parsing import ( + MAX_PUBLICATION_BYTES, + DagBundleInventoryBody, + DagBundleInventoryResponse, + DagBundleStateResponse, + DagParseResultBody, + ParseSourceCode, +) from airflow.api_fastapi.execution_api.datamodels.taskinstance import TaskInstance as TIDataModel from airflow.callbacks.callback_requests import DagCallbackRequest, TaskCallbackRequest +from airflow.dag_processing.api_client import ( + DagProcessorAPIClient, + DagProcessorSecretsComms, +) from airflow.dag_processing.bundles.base import BaseDagBundle, BundleVersion, DagBundleRefreshError from airflow.dag_processing.bundles.local import LocalDagBundle -from airflow.dag_processing.bundles.manager import DagBundlesManager +from airflow.dag_processing.bundles.manager import DagBundlesManager, _load_bundle_config_snapshot from airflow.dag_processing.collection import update_dag_parsing_results_in_db from airflow.dag_processing.dagbag import DagBag from airflow.dag_processing.lang_sdk_processor import LangSDKDagFileProcessorProcess @@ -64,6 +80,9 @@ DagFileInfo, DagFileProcessorManager, DagFileStat, + PendingBundleInventory, + PendingDagPublication, + _compute_retry_delay, ) from airflow.dag_processing.processor import ( DagFileParseRequest, @@ -82,7 +101,8 @@ from airflow.models.serialized_dag import SerializedDagModel from airflow.models.team import Team from airflow.providers.standard.operators.empty import EmptyOperator -from airflow.sdk import DAG as SdkDAG, BaseOperator +from airflow.sdk import DAG as SdkDAG, BaseOperator, Connection, SecretCache +from airflow.sdk.execution_time import task_runner from airflow.sdk.importers import DagDefinition, DagImporterRegistry, DagImportError, DagSourceCode from airflow.serialization.serialized_objects import DagSerialization, LazyDeserializedDAG from airflow.utils.net import get_hostname @@ -2416,6 +2436,26 @@ def test_max_runs_waits_for_an_active_regular_parse_after_counts_reach_the_limit manager._processors.clear() assert manager.max_runs_reached() + @pytest.mark.parametrize("pending", ["publication", "inventory"]) + def test_max_runs_waits_for_pending_api_work_after_counts_reach_the_limit(self, pending): + client = mock.create_autospec(DagProcessorAPIClient, instance=True) + manager = DagFileProcessorManager(max_runs=1, api_client=client) + manager._num_run = 1 + file = _get_file_infos(["dag.py"])[0] + manager._file_stats[file] = DagFileStat(run_count=1) + if pending == "publication": + manager._pending_publications[file] = mock.create_autospec(PendingDagPublication, instance=True) + else: + manager._pending_inventories[file.bundle_name] = mock.create_autospec( + PendingBundleInventory, instance=True + ) + + assert not manager.max_runs_reached() + + manager._pending_publications.clear() + manager._pending_inventories.clear() + assert manager.max_runs_reached() + @mock.patch.object(DagFileProcessorManager, "persist_parsing_result", autospec=True) @mock.patch.object(DagFileProcessorManager, "_create_process", autospec=True) @conf_vars( @@ -2465,13 +2505,17 @@ def test_forced_refresh_blocks_dispatch_with_a_valid_source(self, create): assert list(manager._files_awaiting_source) == [file] @pytest.mark.parametrize("force", [False, True], ids=["periodic", "forced"]) + @pytest.mark.parametrize("api_mode", [False, True]) @mock.patch("airflow.dag_processing.manager.emit_metrics", autospec=True) @mock.patch("airflow.dag_processing.manager.time.perf_counter", autospec=True) @mock.patch.object(DagFileProcessorManager, "persist_parsing_result", autospec=True) @mock.patch.object(DagFileProcessorManager, "_create_process", autospec=True) @conf_vars({("dag_processor", "file_parsing_sort_mode"): "alphabetical"}) - def test_parse_time_spans_refresh_drain_until_dispatch(self, create, persist, perf_counter, emit, force): - manager = DagFileProcessorManager(max_runs=1) + def test_parse_time_spans_refresh_drain_until_dispatch( + self, create, persist, perf_counter, emit, api_mode, force + ): + client = mock.create_autospec(DagProcessorAPIClient, instance=True) if api_mode else None + manager = DagFileProcessorManager(max_runs=1, api_client=client) manager._parallelism = 2 blocked = DagFileInfo(bundle_name="blocked", rel_path=Path("blocked.py")) healthy = DagFileInfo(bundle_name="healthy", rel_path=Path("healthy.py")) @@ -2595,6 +2639,7 @@ def test_paused_bundle_does_not_suppress_healthy_bundle_metrics( manager._collect_results() assert emit.call_count == 2 + @pytest.mark.parametrize("api_mode", [False, True]) @mock.patch("airflow.dag_processing.manager.emit_metrics", autospec=True) @mock.patch("airflow.dag_processing.manager.time.perf_counter", autospec=True) @mock.patch.object(DagFileProcessorManager, "persist_parsing_result", autospec=True) @@ -2606,17 +2651,20 @@ def test_paused_bundle_does_not_suppress_healthy_bundle_metrics( } ) def test_parse_time_emits_when_processors_finish_in_alternating_cycles( - self, create, persist, perf_counter, emit + self, create, persist, perf_counter, emit, api_mode ): - manager = DagFileProcessorManager(max_runs=-1) + client = mock.create_autospec(DagProcessorAPIClient, instance=True) if api_mode else None + manager = DagFileProcessorManager(max_runs=-1, api_client=client) manager._parallelism = 2 first, second = _get_file_infos(["first.py", "second.py"]) manager._bundle_parse_sources[first.bundle_name] = DagParseSource() known_files = {first.bundle_name: {first, second}} processors = [mock.create_autospec(DagFileProcessorProcess, instance=True) for _ in range(5)] for processor in processors: - processor.start_time = 0 + processor.id = uuid7() processor.had_callbacks = False + processor.api_request_error = None + processor.start_time = 0 processor.is_ready = False processor.parsing_result = DagFileParsingResult(fileloc="file.py", serialized_dags=[]) self._configure_mock_processes(create, *processors) @@ -2627,6 +2675,8 @@ def test_parse_time_emits_when_processors_finish_in_alternating_cycles( for count, completed in enumerate((first, second, first), start=1): manager._processors[completed].is_ready = True manager._collect_results() + if api_mode: + manager._publish_pending_results() assert len(manager._processors) == 1 perf_counter.return_value = 10 * (count + 1) @@ -3381,12 +3431,18 @@ def test_priority_request_waits_for_an_active_processor_of_the_same_file(self, c assert not manager._files_awaiting_source assert not manager._priority_files + @pytest.mark.parametrize("api_mode", [False, True]) @mock.patch("airflow.dag_processing.manager.time.monotonic", autospec=True) @mock.patch.object(DagFileProcessorManager, "_create_process", autospec=True) @mock.patch.object(DagFileProcessorManager, "persist_parsing_result", autospec=True) - def test_periodic_refresh_drains_imports_before_admitting_more(self, persist, create, monotonic): + def test_periodic_refresh_drains_imports_before_admitting_more( + self, persist, create, monotonic, api_mode + ): monotonic.return_value = 300 - manager = DagFileProcessorManager(max_runs=1, bundle_refresh_check_interval=300) + client = mock.create_autospec(DagProcessorAPIClient, instance=True) if api_mode else None + if client is not None: + client.publish_inventory.return_value.revision = uuid7() + manager = DagFileProcessorManager(max_runs=1, bundle_refresh_check_interval=300, api_client=client) bundle = self._make_refresh_bundle(supports_versioning=True, current_version="v2") bundle.refresh_interval = 300 manager._bundle_versions[bundle.name] = "v1" @@ -3395,6 +3451,7 @@ def test_periodic_refresh_drains_imports_before_admitting_more(self, persist, cr queued = DagFileInfo(bundle_name=bundle.name, rel_path=Path("queued.py")) processor, _ = self.mock_processor(start_time=monotonic.return_value - 1) processor.had_callbacks = False + processor.dispatch_sequence = 1 processor.parse_source = DagParseSource(bundle_version="v1") processor.parsing_result = DagFileParsingResult(fileloc="active.py", serialized_dags=[]) manager._processors[active] = processor @@ -3409,8 +3466,15 @@ def test_periodic_refresh_drains_imports_before_admitting_more(self, persist, cr assert manager._bundles_waiting_for_refresh == {bundle.name} manager._collect_results() - persist.assert_called_once() - assert persist.call_args.kwargs["bundle_version"] == "v1" + if api_mode: + persist.assert_not_called() + self._refresh_with_mocked_state(manager, bundle, BundleState(last_refreshed=None, version="v1")) + bundle.refresh.assert_not_called() + manager._publish_pending_results() + assert client.publish_parse_result.call_args.args[0].bundle_version == "v1" + else: + persist.assert_called_once() + assert persist.call_args.kwargs["bundle_version"] == "v1" self._refresh_with_mocked_state( manager, bundle, BundleState(last_refreshed=timezone.utcnow(), version="v1") ) @@ -3483,7 +3547,7 @@ def test_refresh_drains_unversioned_callbacks_before_admitting_more(self, create assert not manager._bundles_waiting_for_refresh def test_handle_parsing_result_provides_its_own_session_when_caller_omits(self): - """``handle_parsing_result`` is wrapped in ``@provide_session`` so subclasses overriding it can run without a caller-supplied session.""" + """DB-mode persistence gets a session when the caller does not supply one.""" manager = DagFileProcessorManager(max_runs=1) file = DagFileInfo(bundle_name="testing", rel_path=Path("abc.txt"), bundle_path=TEST_DAGS_FOLDER) manager._file_stats[file] = DagFileStat() @@ -3519,7 +3583,8 @@ def test_handle_parsing_result_throttles_retry_when_first_persist_fails(self, se assert manager._file_stats[file].num_dags == 0 assert manager._file_stats[file].import_errors == 0 assert manager._file_stats[file].run_count == 1 - assert manager._file_stats[file].last_finish_time is not None + assert manager._file_stats[file].last_finish_time is None + assert manager._file_stats[file].last_attempt_time is not None assert manager._file_stats[file].last_duration is not None assert manager.processed_recently(timezone.utcnow(), file) is True @@ -3560,7 +3625,12 @@ def test_handle_parsing_result_updates_stats_after_successful_persist(self, sess assert manager._file_stats[file].last_finish_time > original_stat.last_finish_time assert manager._file_stats[file].num_dags == 0 - def test_collect_results_processes_remaining_files_when_one_persist_fails(self, session): + @pytest.mark.parametrize("failure", ["persist", "commit"]) + @mock.patch("sqlalchemy.orm.Session.commit", autospec=True) + @mock.patch.object(DagFileProcessorManager, "persist_parsing_result", autospec=True) + def test_collect_results_processes_remaining_files_when_one_persist_fails( + self, mock_persist, mock_commit, session, failure + ): manager = DagFileProcessorManager(max_runs=1) file_a = DagFileInfo(bundle_name="testing", rel_path=Path("a.py"), bundle_path=TEST_DAGS_FOLDER) file_b = DagFileInfo(bundle_name="testing", rel_path=Path("b.py"), bundle_path=TEST_DAGS_FOLDER) @@ -3587,18 +3657,21 @@ def test_collect_results_processes_remaining_files_when_one_persist_fails(self, stat_a_before = manager._file_stats[file_a] stat_b_before = manager._file_stats[file_b] - with mock.patch.object( - manager, - "persist_parsing_result", - side_effect=[RuntimeError("boom"), None], - ): - manager._collect_results() + if failure == "persist": + mock_persist.side_effect = [RuntimeError("persist failed"), None] + else: + mock_commit.side_effect = [RuntimeError("commit failed"), None] + manager._collect_results() + + assert mock_persist.call_count == 2 + assert mock_commit.call_count == (1 if failure == "persist" else 2) assert manager._file_stats[file_a] is not stat_a_before assert manager._file_stats[file_a].num_dags == stat_a_before.num_dags assert manager._file_stats[file_a].import_errors == stat_a_before.import_errors assert manager._file_stats[file_a].run_count == stat_a_before.run_count + 1 - assert manager._file_stats[file_a].last_finish_time is not None + assert manager._file_stats[file_a].last_finish_time == stat_a_before.last_finish_time + assert manager._file_stats[file_a].last_attempt_time is not None assert manager._file_stats[file_b] is not stat_b_before assert manager._file_stats[file_b].run_count == 2 assert len(manager._processors) == 0 @@ -4855,12 +4928,14 @@ def test_add_callback_skips_when_bundle_unconfigured(self, mock_bundle_manager): assert not manager._callback_to_execute - def test_fetch_callbacks_delegates_to_private_method(self): + @mock.patch.object(DagFileProcessorManager, "_fetch_callbacks_from_db", autospec=True) + def test_fetch_callbacks_delegates_to_private_method(self, private): manager = DagFileProcessorManager(max_runs=1) expected: list = [mock.sentinel.callback] - with mock.patch.object(manager, "_fetch_callbacks_from_db", return_value=expected) as private: - assert manager.fetch_callbacks() is expected - private.assert_called_once_with() + private.return_value = expected + + assert manager.fetch_callbacks() is expected + private.assert_called_once_with(manager) @mock.patch("airflow.dag_processing.manager.DagBundlesManager") def test_reassign_called_once_at_startup_not_on_refresh(self, mock_bundle_manager): @@ -5663,7 +5738,25 @@ def _refresh_with_mocked_state(self, manager, bundle, initial_state, *, force=Fa manager._force_refresh_bundles = {bundle.name} if force else set() mock_get = mock.patch.object(manager, "get_bundle_state", return_value=initial_state) mock_update = mock.patch.object(manager, "update_bundle_state") + mock_catalog = ( + mock.patch.object( + manager.api_client, + "get_bundles", + return_value=[ + DagBundleStateResponse( + name=bundle.name, + last_refreshed=initial_state.last_refreshed, + version=initial_state.version, + revision=initial_state.revision, + team_name=None, + ) + ], + ) + if manager.api_client is not None + else nullcontext() + ) with ( + mock_catalog, mock_get as patched_get, mock_update as patched_update, mock.patch.object( @@ -6188,6 +6281,358 @@ def test_a_sweep_pays_the_fixed_cost_once_per_call(self, session, testing_dag_bu f"({SWEEP_CALLS} x {fixed} fixed + {SWEEP_FILES} x {per_dag} per Dag)." ) + @pytest.mark.parametrize(("publication_fails", "expected_num_dags"), [(False, 0), (True, 2)]) + @mock.patch.object(DagFileProcessorManager, "persist_parsing_result", autospec=True) + @mock.patch.object(DagFileProcessorManager, "_create_process", autospec=True) + def test_api_publication_uses_dispatch_identity_without_local_persistence( + self, create, persist, session, publication_fails, expected_num_dags + ): + client = mock.create_autospec(DagProcessorAPIClient, instance=True) + manager = DagFileProcessorManager(max_runs=1, api_client=client) + manager._bundle_parse_sources["testing"] = DagParseSource(bundle_version="v1") + file = _get_file_infos(["dag.py"])[0] + manager._file_stats[file] = DagFileStat(num_dags=2) + manager._file_queue[file] = None + proc, read_end = self.mock_processor() + proc.had_callbacks = False + proc.parsing_result = DagFileParsingResult(fileloc="dag.py", serialized_dags=[]) + proc.parse_source = manager._bundle_parse_sources["testing"] + create.return_value = proc + if publication_fails: + client.publish_parse_result.side_effect = RuntimeError("publication failed") + try: + manager._start_new_processes() + create.assert_called_once_with(manager, file, source=proc.parse_source) + manager.handle_parsing_result(file, proc, session=session) + client.publish_parse_result.assert_not_called() + manager._publish_pending_results() + body = client.publish_parse_result.call_args.args[0] + assert body.attempt_id == proc.id + assert body.dispatch_sequence == proc.dispatch_sequence == 1 + assert body.bundle_version == "v1" + assert body.relative_fileloc == "dag.py" + assert body.serialized_dags == [] + assert manager._file_stats[file].run_count == 1 + assert manager._file_stats[file].num_dags == expected_num_dags + persist.assert_not_called() + finally: + read_end.close() + proc.close() + + def test_api_publication_reports_a_result_the_api_would_refuse(self, session): + client = mock.create_autospec(DagProcessorAPIClient, instance=True) + manager = DagFileProcessorManager(max_runs=1, api_client=client) + file = _get_file_infos(["dag.py"])[0] + dag = SdkDAG("published", schedule=None) + dag.fileloc = "/worker/dag.py" + dag.relative_fileloc = "dag.py" + # Mutating the set skips the SDK's constructor check, so only the API model rejects the tag. + dag.tags.add("x" * 101) + revision = uuid7() + proc, read_end = self.mock_processor() + proc.had_callbacks = False + proc.dispatch_sequence = 1 + proc.parse_source = DagParseSource(bundle_version="v1", bundle_revision=revision) + proc.parsing_result = DagFileParsingResult( + fileloc=dag.fileloc, serialized_dags=[LazyDeserializedDAG.from_dag(dag)] + ) + try: + manager.handle_parsing_result(file, proc, session=session) + manager._publish_pending_results() + finally: + read_end.close() + proc.close() + + report = client.publish_parse_result.call_args.args[0] + assert report.serialized_dags == [] + assert (report.bundle_version, report.bundle_revision) == ("v1", revision) + assert report.import_errors == { + "dag.py": "The parsing result was not published: it is not a valid Dag publication " + "(Value error, Dag tags must be strings of at most 100 characters)." + } + assert manager._file_stats[file].import_errors == 1 + assert not manager._pending_publications + + @pytest.mark.parametrize("source_available", [True, False]) + def test_api_publication_carries_diagnostics_and_explicit_source_availability(self, source_available): + client = mock.create_autospec(DagProcessorAPIClient, instance=True) + manager = DagFileProcessorManager(max_runs=1, api_client=client) + file = _get_file_infos(["dag.py"])[0] + dag = SdkDAG("published", schedule=None) + dag.fileloc = "/worker/dag.py" + dag.relative_fileloc = "dag.py" + proc, read_end = self.mock_processor() + proc.dispatch_sequence = 1 + warning = {"dag_id": dag.dag_id, "warning_type": "python:deprecated", "message": "warning"} + unserialized_warning = {"dag_id": "failed", "warning_type": "python:deprecated", "message": "warning"} + proc.parsing_result = DagFileParsingResult( + fileloc=dag.fileloc, + serialized_dags=[LazyDeserializedDAG.from_dag(dag)], + warnings=[warning, unserialized_warning], + parsed_definitions=["dag.py"], + import_errors={"dag.py": "import error"}, + dag_source_codes={dag.dag_id: DagSourceCode(source_code="captured", language="python")} + if source_available + else {}, + ) + try: + body = manager._build_parse_result(file, proc, 0.5) + assert [published.model_dump() for published in body.warnings] == [warning] + assert body.import_errors == {"dag.py": "import error"} + assert body.parsed_definitions == ["dag.py"] + assert body.source_codes[body.dag_source_indexes[dag.dag_id]].source_code == ( + "captured" if source_available else None + ) + finally: + read_end.close() + proc.close() + + @pytest.mark.parametrize("with_valid_member", [True, False], ids=["beside-valid-member", "only-member"]) + def test_api_publication_drops_container_members_with_unrepresentable_paths( + self, with_valid_member, caplog + ): + client = mock.create_autospec(DagProcessorAPIClient, instance=True) + manager = DagFileProcessorManager(max_runs=1, api_client=client) + file = _get_file_infos(["archive.zip"])[0] + invalid_location = r"archive.zip/sub\invalid.py" + invalid_error_location = r"archive.zip/sub\broken.py" + locations = ["archive.zip/valid.py", invalid_location] if with_valid_member else [invalid_location] + dags = [] + for index, location in enumerate(locations): + dag = SdkDAG(f"dag_{index}", schedule=None) + dag.fileloc = f"/worker/{location}" + dag.relative_fileloc = location + dags.append(dag) + import_errors = {invalid_error_location: "import error"} + if with_valid_member: + import_errors["archive.zip/broken.py"] = "import error" + proc, read_end = self.mock_processor() + proc.dispatch_sequence = 1 + proc.parsing_result = DagFileParsingResult( + fileloc="/worker/archive.zip", + serialized_dags=[LazyDeserializedDAG.from_dag(dag) for dag in dags], + warnings=[ + {"dag_id": dag.dag_id, "warning_type": "python:deprecated", "message": "warning"} + for dag in dags + ], + parsed_definitions=locations, + import_errors=import_errors, + dag_source_codes={ + dag.dag_id: DagSourceCode(source_code=dag.dag_id, language="python") for dag in dags + }, + ) + try: + body = manager._build_parse_result(file, proc, 0.5) + finally: + read_end.close() + proc.close() + + published = ["dag_0"] if with_valid_member else [] + assert [dag["dag"]["dag_id"] for dag in body.serialized_dags] == published + assert body.parsed_definitions == locations[:-1] + assert body.import_errors == ({"archive.zip/broken.py": "import error"} if with_valid_member else {}) + assert [warning.dag_id for warning in body.warnings] == published + assert [source.source_code for source in body.source_codes] == published + assert { + "event": "Not publishing definitions with an unrepresentable API path", + "relative_fileloc": "archive.zip", + "locations": [invalid_error_location, invalid_location], + } in caplog + + @pytest.mark.parametrize("different_language", [False, True]) + def test_api_publication_deduplicates_factory_source(self, different_language): + client = mock.create_autospec(DagProcessorAPIClient, instance=True) + manager = DagFileProcessorManager(max_runs=1, api_client=client) + file = _get_file_infos(["factory.py"])[0] + source_text = "#" * (42 * 1024) + dags = [] + sources = {} + for index in range(400): + dag = SdkDAG(f"factory_{index}", schedule=None) + dag.fileloc = "/worker/factory.py" + dag.relative_fileloc = "factory.py" + dags.append(LazyDeserializedDAG.from_dag(dag)) + sources[dag.dag_id] = DagSourceCode( + source_code=source_text, language="sql" if different_language and index == 0 else "python" + ) + proc, read_end = self.mock_processor() + proc.dispatch_sequence = 1 + proc.parsing_result = DagFileParsingResult( + fileloc="/worker/factory.py", serialized_dags=dags, dag_source_codes=sources + ) + try: + body = manager._build_parse_result(file, proc, 0.5) + finally: + read_end.close() + proc.close() + + assert len(source_text.encode()) * len(dags) > MAX_PUBLICATION_BYTES + assert len(body.model_dump_json().encode()) < MAX_PUBLICATION_BYTES + assert len(body.source_codes) == (2 if different_language else 1) + assert set(body.dag_source_indexes) == set(sources) + for dag_id, source in sources.items(): + published = body.source_codes[body.dag_source_indexes[dag_id]] + assert (published.source_code, published.language) == (source.source_code, source.language) + + @conf_vars({("workers", "execution_api_retries"): "1"}) + @pytest.mark.parametrize("failure", [413, 422, 403, 500, "timeout"]) + def test_rejected_publication_preserves_previous_success_stats(self, time_machine, failure): + time_machine.move_to("2026-10-05T12:00:00Z", tick=False) + client = mock.create_autospec(DagProcessorAPIClient, instance=True) + request = httpx2.Request("POST", "http://api/jobs/1/parse-results") + client.publish_parse_result.side_effect = ( + httpx2.ReadTimeout("Lost response", request=request) + if failure == "timeout" + else httpx2.HTTPStatusError("Rejected", request=request, response=httpx2.Response(failure)) + ) + manager = DagFileProcessorManager(max_runs=1, api_client=client) + file = _get_file_infos(["dag.py"])[0] + previous = timezone.utcnow() - timedelta(seconds=manager.stale_dag_threshold + 1) + manager._file_stats[file] = DagFileStat(num_dags=1, last_finish_time=previous) + dag = SdkDAG("published", schedule=None) + dag.fileloc = "/worker/dag.py" + dag.relative_fileloc = "dag.py" + proc, read_end = self.mock_processor() + proc.dispatch_sequence = 1 + proc.parsing_result = DagFileParsingResult( + fileloc=dag.fileloc, serialized_dags=[LazyDeserializedDAG.from_dag(dag)] + ) + try: + manager.handle_parsing_result(file, proc) + manager._publish_pending_results() + assert manager._file_stats[file].last_finish_time == previous + assert manager._file_stats[file].num_dags == 1 + assert manager.processed_recently(timezone.utcnow(), file) + assert not manager._pending_publications + finally: + read_end.close() + proc.close() + + @pytest.mark.parametrize("status_code", [None, 408, 429]) + def test_publication_retries_leave_the_loop_responsive(self, mocker, status_code): + client = mock.create_autospec(DagProcessorAPIClient, instance=True) + error = ( + httpx2.ReadTimeout("Lost acknowledgment") + if status_code is None + else _make_status_error(status_code) + ) + client.publish_parse_result.side_effect = [error, None, None] + heartbeat_observations = [] + with selectors.DefaultSelector() as selector: + manager = DagFileProcessorManager( + max_runs=1, + api_client=client, + selector=selector, + heartbeat=lambda: heartbeat_observations.append(client.publish_parse_result.call_count), + ) + for method in ( + "_refresh_dag_bundles", + "_queue_requested_files_for_parsing", + "_scan_stale_dags", + "_cleanup_stale_bundle_versions", + "print_stats", + ): + mocker.patch.object(DagFileProcessorManager, method, autospec=True) + mocker.patch.object(DagFileProcessorManager, "fetch_callbacks", autospec=True, return_value=[]) + for file in _get_file_infos(["a.py", "b.py"]): + proc, read_end = self.mock_processor() + proc.dispatch_sequence = 1 + proc.parsing_result = DagFileParsingResult(fileloc=str(file.rel_path), serialized_dags=[]) + try: + manager.handle_parsing_result(file, proc) + finally: + read_end.close() + proc.close() + assert not manager.max_runs_reached() + manager._run_parsing_loop() + calls = client.publish_parse_result.call_args_list + assert [call.args[0].relative_fileloc for call in calls] == ["a.py", "b.py", "a.py"] + assert calls[0].args[0] is calls[2].args[0] + assert {0, 1}.issubset(heartbeat_observations) + assert not manager._pending_publications + assert all(stat.run_count == 1 for stat in manager._file_stats.values()) + + @pytest.mark.parametrize("change", ["refresh", "delete"]) + def test_pending_publication_is_discarded_when_source_changes(self, change): + client = mock.create_autospec(DagProcessorAPIClient, instance=True) + manager = DagFileProcessorManager(max_runs=1, api_client=client) + file = _get_file_infos(["dag.py"])[0] + proc, read_end = self.mock_processor() + proc.dispatch_sequence = 1 + proc.parsing_result = DagFileParsingResult(fileloc="dag.py", serialized_dags=[]) + try: + manager.handle_parsing_result(file, proc) + if change == "refresh": + manager._invalidate_bundle_parse_source("testing") + else: + manager.remove_orphaned_file_stats(present=set()) + manager._publish_pending_results() + client.publish_parse_result.assert_not_called() + assert not manager._pending_publications + assert list(manager._file_queue) == ([file] if change == "refresh" else []) + finally: + read_end.close() + proc.close() + + @mock.patch.object(DagFileProcessorManager, "_create_process", autospec=True) + def test_pending_publications_bound_admission_and_prevent_reimports(self, create): + client = mock.create_autospec(DagProcessorAPIClient, instance=True) + manager = DagFileProcessorManager(max_runs=1, api_client=client, parallelism=1) + manager._file_parsing_sort_mode = "alphabetical" + file, other = _get_file_infos(["dag.py", "other.py"]) + proc, read_end = self.mock_processor() + proc.dispatch_sequence = 1 + proc.parsing_result = DagFileParsingResult(fileloc="dag.py", serialized_dags=[]) + manager._bundle_parse_sources["testing"] = DagParseSource() + try: + manager.handle_parsing_result(file, proc) + manager.prepare_file_queue(known_files={"testing": {file, other}}) + assert list(manager._file_queue) == [other] + manager._start_new_processes() + create.assert_not_called() + assert list(manager._file_queue) == [other] + manager._parallelism = 2 + manager._file_queue = OrderedDict.fromkeys([file]) + manager._start_new_processes() + create.assert_not_called() + finally: + read_end.close() + proc.close() + + @mock.patch("airflow.dag_processing.manager.time", autospec=True) + @mock.patch.object(DagFileProcessorManager, "_get_observed_filelocs", autospec=True) + def test_unusable_inventory_preserves_version_and_recovers_after_refresh(self, observed, clock): + clock.monotonic.return_value = 100 + observed.return_value = {f"{index}.py" for index in range(100001)} + client = mock.create_autospec(DagProcessorAPIClient, instance=True) + manager = DagFileProcessorManager( + max_runs=1, api_client=client, parallelism=1, bundle_refresh_check_interval=0 + ) + bundle = self._make_refresh_bundle() + bundle.refresh_interval = 3600 + manager._bundles_waiting_for_refresh.add(bundle.name) + manager._bundle_versions[bundle.name] = "previous" + + self._refresh_with_mocked_state( + manager, bundle, BundleState(last_refreshed=None, version=None), force=True + ) + + bundle.refresh.assert_called_once() + client.publish_inventory.assert_not_called() + assert bundle.name not in manager._bundle_parse_sources + assert bundle.name not in manager._pending_inventories + assert manager._bundle_versions[bundle.name] == "previous" + assert not manager._force_refresh_bundles + assert not manager._bundles_waiting_for_refresh + + observed.return_value = set() + client.publish_inventory.return_value.revision = uuid7() + clock.monotonic.return_value += bundle.refresh_interval + self._refresh_with_mocked_state(manager, bundle, BundleState(last_refreshed=None, version=None)) + assert bundle.name in manager._bundle_parse_sources + assert manager._bundle_versions[bundle.name] is None + assert not manager._pending_inventories + class TestMultiTeamMetrics: """Tests for team_name tag on dag processing metrics in multi-team mode.""" @@ -6584,3 +7029,961 @@ def test_normalized_file_path_for_stats_does_not_warn(caplog): assert result == "dags_test_test_dag.py" assert caplog.entries == [] + + +API_CLIENT_BUNDLES = [ + { + "name": name, + "classpath": "airflow.dag_processing.bundles.local.LocalDagBundle", + "kwargs": {"path": "/"}, + } + for name in ("bundle_a", "bundle_b") +] + + +def _read_bundle_connection() -> None: + Connection.get("bundle_conn") + + +class TestDagFileProcessorManagerWithAPIClient: + """With an API client, bundle code resolves its connections through it, for the bundle it belongs to.""" + + @pytest.fixture + def api_requests(self) -> list[httpx2.Request]: + return [] + + @pytest.fixture + def api_client(self, tmp_path, api_requests, make_registration_response): + token_file = tmp_path / "processor.jwt" + token_file.write_text("session-token") + + def handle(request: httpx2.Request) -> httpx2.Response: + api_requests.append(request) + if request.url.path.endswith("/jobs"): + return make_registration_response() + if request.url.path.endswith("/bundles"): + return httpx2.Response( + 200, + json=[ + { + "name": bundle["name"], + "version": None, + "last_refreshed": None, + "revision": None, + "team_name": None, + } + for bundle in API_CLIENT_BUNDLES + ], + ) + return httpx2.Response( + 200, + json={ + "conn_id": "bundle_conn", + "conn_type": "http", + "host": None, + "schema": None, + "login": None, + "password": None, + "port": None, + "extra": None, + }, + ) + + with DagProcessorAPIClient( + base_url="http://api/execution/", + token_file=token_file, + hostname="processor-1", + transport=httpx2.MockTransport(handle), + ) as client: + client.register_job() + yield client + + @pytest.fixture + def make_manager(self, api_client): + managers = [] + + def make(**kwargs) -> DagFileProcessorManager: + manager = DagFileProcessorManager(max_runs=1, api_client=api_client, **kwargs) + manager.prepare_api_secrets_context(api_client) + managers.append(manager) + return manager + + yield make + for manager in managers: + manager.after_run() + + @pytest.fixture(autouse=True) + def restore_process_context(self): + # Starting an API-mode manager sets _AIRFLOW_PROCESS_CONTEXT for the whole process. + with mock.patch.dict(os.environ): + yield + + @pytest.fixture(autouse=True) + def configured_bundles(self): + with conf_vars( + { + ("dag_processor", "dag_bundle_config_list"): json.dumps(API_CLIENT_BUNDLES), + ("core", "load_examples"): "False", + } + ): + _load_bundle_config_snapshot.cache_clear() + yield + _load_bundle_config_snapshot.cache_clear() + + @staticmethod + def _get_connection_bundles(api_requests: list[httpx2.Request]) -> list[str]: + return [ + request.headers["Airflow-Dag-Bundle"] + for request in api_requests + if request.url.path.startswith("/execution/connections/") + ] + + def test_uses_the_api_client_instead_of_the_in_process_api(self, make_manager, api_client): + manager = make_manager() + + assert manager.client is api_client + assert manager._api_server is None + + @conf_vars({("secrets", "use_cache"): "True"}) + def test_api_mode_does_not_share_sdk_secret_cache_between_bundles(self, make_manager, monkeypatch): + monkeypatch.setattr(SecretCache, "_cache", {"inherited": "secret"}) + manager = make_manager() + manager.heartbeat = mock.Mock(spec=lambda: None, side_effect=SystemExit) + with pytest.raises(SystemExit): + manager._run_parsing_loop() + assert SecretCache._cache is None + + @mock.patch("airflow.dag_processing.manager.get_importer_registry", autospec=True) + def test_importer_warmup_selects_its_bundle(self, registry, make_manager, api_requests): + manager = make_manager(bundle_names_to_parse=["bundle_b"]) + manager._dag_bundles = manager.get_all_bundles() + registry.return_value.warm_importers.side_effect = _read_bundle_connection + manager.warm_importers() + assert self._get_connection_bundles(api_requests) == ["bundle_b"] + + @mock.patch.object( + DagFileProcessorManager, + "prepare_process_context", + autospec=True, + side_effect=ValueError("startup failed"), + ) + def test_startup_failure_clears_the_api_secrets_context(self, prepare, api_client): + manager = DagFileProcessorManager(max_runs=1, api_client=api_client) + with pytest.raises(ValueError, match="startup failed"): + manager.run() + assert not hasattr(task_runner, "SUPERVISOR_COMMS") + + @mock.patch("airflow.dag_processing.manager.gc", autospec=True) + def test_run_resolves_secrets_through_the_api_client_instead_of_the_database(self, _, api_client): + manager = DagFileProcessorManager(max_runs=1, api_client=api_client) + with ( + mock.patch.object(manager, "prepare_server_process_context", autospec=True) as server_context, + mock.patch.object(manager, "prepare_process_context", autospec=True), + mock.patch.object(manager, "register_exit_signals", autospec=True), + mock.patch.object(manager, "prepare_bundles", autospec=True), + mock.patch.object(manager, "_symlink_latest_log_directory", autospec=True), + mock.patch.object(manager, "warm_importers", autospec=True), + ): + manager.before_run() + server_context.assert_not_called() + assert isinstance(task_runner.SUPERVISOR_COMMS, DagProcessorSecretsComms) + + manager.after_run() + + assert not hasattr(task_runner, "SUPERVISOR_COMMS") + + @pytest.mark.parametrize( + ("bundle_names_to_parse", "expected"), + [(None, ["bundle_a", "bundle_b"]), (["bundle_b"], ["bundle_b"])], + ) + @mock.patch("airflow.dag_processing.bundles.local.LocalDagBundle.__init__", autospec=True) + def test_creates_each_bundle_for_its_bundle( + self, mock_bundle, make_manager, api_requests, bundle_names_to_parse, expected + ): + def create(bundle, *, name, **kwargs): + _read_bundle_connection() + bundle.name = name + + mock_bundle.side_effect = create + + bundles = make_manager(bundle_names_to_parse=bundle_names_to_parse).get_all_bundles() + + assert [bundle.name for bundle in bundles] == expected + assert self._get_connection_bundles(api_requests) == expected + + def test_refreshes_each_bundle_for_its_bundle(self, make_manager, api_requests): + manager = make_manager() + bundle = MagicMock(spec=BaseDagBundle) + bundle.name = "bundle_b" + bundle.is_initialized = False + + def initialize(): + _read_bundle_connection() + raise OSError("clone failed") + + bundle.initialize.side_effect = initialize + manager._dag_bundles = [bundle] + + manager._refresh_dag_bundles(known_files={}) + + assert self._get_connection_bundles(api_requests) == ["bundle_b"] + + @mock.patch.object(DagBundlesManager, "get_bundle", autospec=True) + def test_prepares_a_callback_bundle_for_its_bundle(self, mock_get_bundle, make_manager, api_requests): + def create(_, name, version=None, version_data=None): + _read_bundle_connection() + bundle = MagicMock(spec=BaseDagBundle) + bundle.supports_versioning = False + return bundle + + mock_get_bundle.side_effect = create + request = DagCallbackRequest( + filepath="dag.py", + dag_id="dag_id", + run_id="run_id", + bundle_name="bundle_b", + bundle_version="v1", + context_from_server=None, + is_failure_callback=False, + ) + + assert make_manager().prepare_callback_bundle(request) is not None + assert self._get_connection_bundles(api_requests) == ["bundle_b"] + + +@mock.patch.object( + DagFileProcessorManager, + "_find_files_in_bundle", + autospec=True, + return_value=DagBundleDiscoveryResult(files=set()), +) +@conf_vars({("core", "multi_team"): "True"}) +def test_refresh_reads_one_fresh_catalog_per_pass(find_files, tmp_path): + client = mock.create_autospec(DagProcessorAPIClient, instance=True) + manager = DagFileProcessorManager(max_runs=1, api_client=client, bundle_refresh_check_interval=0) + states = [] + known_files = {} + for name in ("a", "b", "c"): + bundle = _make_bundle(tmp_path) + bundle.name = name + bundle.is_initialized = True + bundle.supports_versioning = False + bundle.refresh_interval = 300 + manager._dag_bundles.append(bundle) + manager._bundle_versions[name] = None + manager._bundle_parse_sources[name] = DagParseSource() + known_files[name] = set() + states.append( + DagBundleStateResponse( + name=name, version=None, last_refreshed=timezone.utcnow(), revision=uuid7(), team_name=None + ) + ) + client.get_bundles.return_value = states + client.publish_inventory.return_value.revision = uuid7() + manager._refresh_dag_bundles(known_files) + client.get_bundles.assert_called_once_with() + find_files.assert_not_called() + + states[0] = states[0].model_copy( + update={"last_refreshed": None, "team_name": "new_team", "revision": uuid7()} + ) + states.pop() + manager._refresh_dag_bundles(known_files) + assert client.get_bundles.call_count == 2 + find_files.assert_called_once_with(manager, manager._dag_bundles[0]) + assert client.publish_inventory.call_args.args[1].expected_revision == states[0].revision + assert manager._bundle_name_to_team_name == {"a": "new_team", "b": None} + manager._dag_bundles[2].refresh.assert_not_called() + + file = DagFileInfo(bundle_name="b", rel_path=Path("a.py")) + known_files["b"] = {file} + pending_body = DagBundleInventoryBody( + attempt_id=uuid7(), dispatch_sequence=3, expected_revision=states[0].revision, files=[] + ) + manager._pending_inventories["a"] = PendingBundleInventory(pending_body, set(), DagParseSource()) + client.get_bundles.side_effect = httpx2.ConnectError("API unavailable") + manager._refresh_dag_bundles(known_files) + assert client.get_bundles.call_count == 3 + assert known_files["b"] == {file} + assert client.publish_inventory.call_args.args[1] is pending_body + assert find_files.call_count == 1 + + +@pytest.mark.parametrize("catalog_failed", [False, True]) +@pytest.mark.parametrize("has_pending_inventory", [False, True]) +@mock.patch("airflow.dag_processing.manager.time", autospec=True) +@mock.patch.object(DagFileProcessorManager, "_find_files_in_bundle", autospec=True) +def test_catalog_omission_releases_source_and_allows_recovery( + find_files, clock, catalog_failed, has_pending_inventory, tmp_path +): + clock.monotonic.return_value = 100 + (tmp_path / "a.py").touch() + client = mock.create_autospec(DagProcessorAPIClient, instance=True) + manager = DagFileProcessorManager(max_runs=1, api_client=client, bundle_refresh_check_interval=10) + bundles = {} + files = {} + for name in ("missing", "ready"): + bundle = _make_bundle(tmp_path) + bundle.name = name + bundle.is_initialized = True + bundle.supports_versioning = False + bundle.refresh_interval = 300 + bundles[name] = bundle + file = DagFileInfo(bundle_name=name, rel_path=Path("a.py"), bundle_path=tmp_path) + files[name] = {file} + manager._bundle_versions[name] = None + manager._bundle_parse_sources[name] = DagParseSource() + manager._dag_bundles = list(bundles.values()) + previous_files = files.copy() + previous_versions = manager._bundle_versions.copy() + ready_source = manager._bundle_parse_sources["ready"] + missing_source = manager._bundle_parse_sources["missing"] + pending_body = DagBundleInventoryBody( + attempt_id=uuid7(), dispatch_sequence=1, expected_revision=None, files=["a.py"] + ) + if has_pending_inventory: + manager._pending_inventories["missing"] = PendingBundleInventory( + pending_body, files["missing"], missing_source + ) + manager._bundle_parse_sources.pop("missing") + manager._force_refresh_bundles.add("missing") + manager._bundles_waiting_for_refresh.add("missing") + ready_state = DagBundleStateResponse( + name="ready", version=None, last_refreshed=timezone.utcnow(), revision=None, team_name=None + ) + client.get_bundles.return_value = [ready_state] + if catalog_failed: + client.get_bundles.side_effect = httpx2.ConnectError("Catalog unavailable") + client.publish_inventory.side_effect = _make_status_error(503) + + manager._refresh_dag_bundles(files) + + client.get_bundles.assert_called_once_with() + find_files.assert_not_called() + assert files == previous_files + assert manager._bundle_versions == previous_versions + assert manager._bundle_parse_sources["ready"] is ready_source + if catalog_failed: + assert manager._force_refresh_bundles == {"missing"} + assert manager._bundles_waiting_for_refresh == {"missing"} + if has_pending_inventory: + client.publish_inventory.assert_called_once_with("missing", pending_body) + assert manager._pending_inventories["missing"].body is pending_body + else: + client.publish_inventory.assert_not_called() + assert manager._bundle_parse_sources["missing"] is missing_source + return + + client.publish_inventory.assert_not_called() + assert not manager._pending_inventories + assert not manager._force_refresh_bundles + assert not manager._bundles_waiting_for_refresh + assert manager._get_dispatch_source(next(iter(files["missing"]))) is None + manager._refresh_dag_bundles(files) + client.get_bundles.assert_called_once_with() + + clock.monotonic.return_value = 110 + client.get_bundles.return_value = [ready_state, ready_state.model_copy(update={"name": "missing"})] + client.publish_inventory.side_effect = None + revision = uuid7() + client.publish_inventory.return_value.revision = revision + find_files.return_value = DagBundleDiscoveryResult(files=files["missing"]) + manager._refresh_dag_bundles(files) + + bundles["missing"].refresh.assert_called_once() + bundles["ready"].refresh.assert_not_called() + assert manager._bundle_parse_sources["missing"].bundle_revision == revision + assert files == previous_files + assert manager._bundle_versions == previous_versions + + +@mock.patch.object(DagFileProcessorManager, "_find_files_in_bundle", autospec=True) +def test_api_inventory_preserves_failed_sources_without_discovered_files(find_files, tmp_path): + client = mock.create_autospec(DagProcessorAPIClient, instance=True) + client.get_bundles.return_value = [ + DagBundleStateResponse( + name="testing", version=None, last_refreshed=None, revision=None, team_name=None + ) + ] + client.publish_inventory.return_value.revision = uuid7() + manager = DagFileProcessorManager(max_runs=1, api_client=client, bundle_refresh_check_interval=0) + bundle = _make_bundle(tmp_path) + bundle.is_initialized = True + bundle.supports_versioning = False + manager._dag_bundles = [bundle] + find_files.return_value = DagBundleDiscoveryResult( + files=set(), failed_sources=frozenset({"unreadable.zip"}) + ) + known_files = {} + + manager._refresh_dag_bundles(known_files) + + body = client.publish_inventory.call_args.args[1] + assert body.files == [] + assert body.failed_sources == ["unreadable.zip"] + assert known_files == {"testing": set()} + assert manager._bundle_failed_sources["testing"] == frozenset({"unreadable.zip"}) + + +@pytest.mark.parametrize("status_code", [408, 409, 429, 503]) +def test_api_inventory_failure_preserves_known_files(status_code): + client = mock.create_autospec(DagProcessorAPIClient, instance=True) + manager = DagFileProcessorManager(max_runs=1, api_client=client) + body = DagBundleInventoryBody( + attempt_id=uuid7(), + dispatch_sequence=1, + expected_revision=uuid7(), + files=[], + failed_sources=["archive.zip"], + ) + manager._bundle_failed_sources["testing"] = frozenset({"previous.zip"}) + manager._pending_inventories["testing"] = PendingBundleInventory(body, set(), DagParseSource()) + original_body = body.model_dump_json() + known_files = {"testing": set(_get_file_infos(["previous.py"]))} + previous = known_files.copy() + response = httpx2.Response(status_code, request=httpx2.Request("POST", "http://api/inventory")) + client.publish_inventory.side_effect = httpx2.HTTPStatusError( + "Unavailable", request=response.request, response=response + ) + manager._publish_bundle_inventory("testing", known_files) + assert known_files == previous + assert manager._bundle_failed_sources["testing"] == frozenset({"previous.zip"}) + assert not manager._bundle_parse_sources + if status_code == 409: + assert not manager._pending_inventories + assert "testing" in manager._force_refresh_bundles + else: + assert manager._pending_inventories["testing"].body is body + revision = uuid7() + client.publish_inventory.side_effect = None + client.publish_inventory.return_value = DagBundleInventoryResponse( + attempt_id=body.attempt_id, accepted_at=timezone.utcnow(), revision=revision + ) + manager._publish_bundle_inventory("testing", known_files) + assert client.publish_inventory.call_args.args[1] is body + assert body.model_dump_json() == original_body + assert known_files == {"testing": set()} + assert manager._bundle_parse_sources["testing"].bundle_revision == revision + assert manager._bundle_failed_sources["testing"] == frozenset({"archive.zip"}) + + +@pytest.mark.parametrize("status_code", [None, 408, 429, 503]) +@conf_vars( + {("workers", "execution_api_retry_wait_min"): "2", ("workers", "execution_api_retry_wait_max"): "3"} +) +@mock.patch("airflow.dag_processing.manager.time", autospec=True) +def test_pending_inventory_retries_back_off(clock, status_code, tmp_path): + client = mock.create_autospec(DagProcessorAPIClient, instance=True) + client.get_bundles.return_value = [ + DagBundleStateResponse( + name="testing", version=None, last_refreshed=None, revision=None, team_name=None + ) + ] + client.publish_inventory.side_effect = ( + httpx2.ConnectError("API unavailable") if status_code is None else _make_status_error(status_code) + ) + clock.monotonic.return_value = 100 + manager = DagFileProcessorManager(max_runs=1, api_client=client, bundle_refresh_check_interval=3600) + manager._bundles_last_refreshed = 100 + manager._dag_bundles.append(_make_bundle(tmp_path)) + body = DagBundleInventoryBody(attempt_id=uuid7(), dispatch_sequence=1, expected_revision=None, files=[]) + manager._pending_inventories["testing"] = PendingBundleInventory(body, set(), DagParseSource()) + + for now, expected_sends, retry_at in [(100, 1, 102), (101, 1, 102), (102, 2, 104), (103, 2, 104)]: + clock.monotonic.return_value = now + manager._refresh_dag_bundles({}) + assert client.publish_inventory.call_count == expected_sends + assert client.get_bundles.call_count == expected_sends + assert manager._pending_inventories["testing"].next_attempt_time == retry_at + + revision = uuid7() + client.publish_inventory.side_effect = None + client.publish_inventory.return_value = DagBundleInventoryResponse( + attempt_id=body.attempt_id, accepted_at=timezone.utcnow(), revision=revision + ) + clock.monotonic.return_value = 104 + manager._refresh_dag_bundles({}) + assert client.publish_inventory.call_count == 3 + assert not manager._pending_inventories + assert manager._bundle_parse_sources["testing"].bundle_revision == revision + + +@pytest.mark.parametrize("rejection", ["local_limit", "server_limit"]) +@mock.patch("airflow.dag_processing.manager.MAX_PUBLICATION_BYTES", 1024) +@mock.patch("airflow.dag_processing.manager.time", autospec=True) +@mock.patch.object(DagFileProcessorManager, "_create_process", autospec=True) +def test_oversized_inventory_preserves_previous_inventory_and_other_bundle_progress( + create, clock, rejection, tmp_path +): + clock.monotonic.return_value = 100 + client = mock.create_autospec(DagProcessorAPIClient, instance=True) + client.get_bundles.return_value = [ + DagBundleStateResponse(name=name, version=None, last_refreshed=None, revision=None, team_name=None) + for name in ("oversized", "ready") + ] + manager = DagFileProcessorManager(max_runs=1, api_client=client, bundle_refresh_check_interval=10) + old_file, ready_file = [ + DagFileInfo(bundle_name=name, rel_path=Path("a.py"), bundle_path=tmp_path) + for name in ("oversized", "ready") + ] + (tmp_path / "a.py").touch() + known_files = {"oversized": {old_file}} + manager._bundle_versions["oversized"] = "previous" + manager._force_refresh_bundles.add("oversized") + for name, files in ( + ("oversized", [f"{index}/{'é' * 80}.py" for index in range(6)] if rejection == "local_limit" else []), + ("ready", ["a.py"]), + ): + bundle = _make_bundle(tmp_path) + bundle.name = name + bundle.refresh_interval = 300 + manager._dag_bundles.append(bundle) + body = DagBundleInventoryBody( + attempt_id=uuid7(), dispatch_sequence=1, expected_revision=None, version="new", files=files + ) + if name == "oversized" and rejection == "local_limit": + assert len(body.model_dump_json()) < 1024 < len(body.model_dump_json().encode()) + manager._pending_inventories[name] = PendingBundleInventory( + body, + {ready_file} if name == "ready" else set(), + DagParseSource(bundle_version="new"), + ) + + def publish(bundle_name, body): + if bundle_name == "oversized": + assert rejection == "server_limit", "The oversized inventory must be rejected before sending" + raise _make_status_error(413) + return DagBundleInventoryResponse( + attempt_id=body.attempt_id, accepted_at=timezone.utcnow(), revision=uuid7() + ) + + client.publish_inventory.side_effect = publish + manager._refresh_dag_bundles(known_files) + manager._start_new_processes() + + assert known_files == {"oversized": {old_file}, "ready": {ready_file}} + assert manager._bundle_versions == {"oversized": "previous", "ready": "new"} + assert not manager._pending_inventories + assert not manager._force_refresh_bundles + assert set(manager._bundle_parse_sources) == {"ready"} + assert list(manager._files_awaiting_source) == [old_file] + create.assert_called_once_with(manager, ready_file, source=manager._bundle_parse_sources["ready"]) + calls = client.get_bundles.call_count + manager._refresh_dag_bundles(known_files) + assert client.get_bundles.call_count == calls + + +@pytest.mark.parametrize("auth_status", [401, 403]) +def test_oversized_inventory_byte_boundary_preserves_auth_failures(auth_status): + client = mock.create_autospec(DagProcessorAPIClient, instance=True) + manager = DagFileProcessorManager(max_runs=1, api_client=client) + body = DagBundleInventoryBody( + attempt_id=uuid7(), dispatch_sequence=1, expected_revision=None, files=["é.py"] + ) + pending = PendingBundleInventory(body, set(), DagParseSource()) + manager._pending_inventories["testing"] = pending + client.publish_inventory.return_value = DagBundleInventoryResponse( + attempt_id=body.attempt_id, accepted_at=timezone.utcnow(), revision=uuid7() + ) + size = len(body.model_dump_json().encode()) + with mock.patch("airflow.dag_processing.manager.MAX_PUBLICATION_BYTES", size): + manager._publish_bundle_inventory("testing", {}) + client.publish_inventory.assert_called_once() + manager._pending_inventories["testing"] = pending + with mock.patch("airflow.dag_processing.manager.MAX_PUBLICATION_BYTES", size - 1): + manager._publish_bundle_inventory("testing", {}) + client.publish_inventory.assert_called_once() + assert not manager._pending_inventories + assert not manager._bundle_parse_sources + manager._pending_inventories["testing"] = pending + client.publish_inventory.side_effect = _make_status_error(auth_status) + with pytest.raises(httpx2.HTTPStatusError): + manager._publish_bundle_inventory("testing", {}) + + +def test_publication_for_a_changed_source_refreshes_and_reparses(): + client = mock.create_autospec(DagProcessorAPIClient, instance=True) + manager = DagFileProcessorManager(max_runs=1, api_client=client) + file = _get_file_infos(["a.py"])[0] + manager._pending_publications[file] = PendingDagPublication( + body=mock.create_autospec(DagParseResultBody, instance=True), stat=DagFileStat(), refresh_generation=0 + ) + manager._pending_publications[file].body.attempt_id = uuid7() + response = httpx2.Response( + 409, + json={"detail": {"reason": "source_changed"}}, + request=httpx2.Request("POST", "http://api/parse-results"), + ) + client.publish_parse_result.side_effect = httpx2.HTTPStatusError( + "Rejected", request=response.request, response=response + ) + + manager._publish_pending_results() + + assert not manager._pending_publications + assert manager._force_refresh_bundles == {"testing"} + assert list(manager._file_queue) == [file] + + +@conf_vars({("core", "multi_team"): "True"}) +def test_api_team_lookup_failure_is_retried_without_stopping_the_processor(): + client = mock.create_autospec(DagProcessorAPIClient, instance=True) + client.get_bundles.side_effect = [ + httpx2.ConnectError("unavailable"), + [ + DagBundleStateResponse( + name="testing", version=None, last_refreshed=None, revision=None, team_name="team_a" + ) + ], + ] + manager = DagFileProcessorManager(max_runs=1, api_client=client) + + assert manager._get_team_names({"testing"}) == {"testing": None} + assert manager._get_team_names({"testing"}) == {"testing": "team_a"} + + +def _make_pending_publication( + file: DagFileInfo, *, attempt_id: UUID | None = None, import_errors: dict[str, str] | None = None +) -> PendingDagPublication: + dag = SdkDAG(f"dag_in_{file.rel_path.stem}", schedule=None) + dag.fileloc = f"/worker/{file.rel_path}" + dag.relative_fileloc = str(file.rel_path) + return PendingDagPublication( + body=DagParseResultBody( + attempt_id=attempt_id or uuid7(), + dispatch_sequence=1, + bundle_name=file.bundle_name, + relative_fileloc=str(file.rel_path), + parse_duration=0.1, + serialized_dags=[LazyDeserializedDAG.from_dag(dag).data], + source_codes=[ParseSourceCode(source_code="# source", language="python")], + dag_source_indexes={dag.dag_id: 0}, + import_errors=import_errors or {}, + ), + stat=DagFileStat(num_dags=1, run_count=1, last_finish_time=timezone.utcnow()), + refresh_generation=0, + ) + + +def _make_status_error( + status_code: int, reason: str | None = None, *, message: str | None = None +) -> httpx2.HTTPStatusError: + response = httpx2.Response( + status_code, + json={"detail": {"reason": reason, "message": message}} if reason else None, + request=httpx2.Request("POST", "http://api/parse-results"), + ) + return httpx2.HTTPStatusError("Rejected", request=response.request, response=response) + + +def test_publication_sends_every_ready_result_within_the_loop_budget(): + client = mock.create_autospec(DagProcessorAPIClient, instance=True) + manager = DagFileProcessorManager(max_runs=1, api_client=client) + files = _get_file_infos(["a.py", "b.py"]) + for file in files: + manager._pending_publications[file] = _make_pending_publication(file) + + manager._publish_pending_results(deadline=time.monotonic()) + client.publish_parse_result.assert_not_called() + + manager._publish_pending_results() + sent = [call.args[0].relative_fileloc for call in client.publish_parse_result.call_args_list] + assert sent == ["a.py", "b.py"] + assert not manager._pending_publications + assert all(manager._file_stats[file].num_dags == 1 for file in files) + + +@conf_vars({("workers", "execution_api_retries"): "1"}) +@pytest.mark.parametrize( + ("error", "message"), + [ + (_make_status_error(409, "dag_owned_by_another_bundle"), "HTTP 409: dag_owned_by_another_bundle"), + (_make_status_error(403, "plugin_not_granted"), "HTTP 403: plugin_not_granted"), + (_make_status_error(413), "HTTP 413"), + (_make_status_error(422), "HTTP 422"), + ( + _make_status_error(422, "invalid_dag", message="Unknown role: missing_role"), + "HTTP 422: invalid_dag: Unknown role: missing_role", + ), + ], +) +def test_result_the_api_refuses_is_replaced_by_an_import_error(error, message): + client = mock.create_autospec(DagProcessorAPIClient, instance=True) + client.publish_parse_result.side_effect = [error, None] + manager = DagFileProcessorManager(max_runs=1, api_client=client) + manager._dispatch_sequence = 7 + file = _get_file_infos(["a.py"])[0] + original = _make_pending_publication( + file, + attempt_id=uuid7(), + import_errors={"a.py/member.py": "member failed"}, + ) + manager._pending_publications[file] = original + + manager._publish_pending_results() + + report = client.publish_parse_result.call_args_list[1].args[0] + assert report.attempt_id != original.body.attempt_id + assert report.dispatch_sequence == 8 + assert report.serialized_dags == [] + assert report.source_codes == [] + assert report.dag_source_indexes == {} + assert report.import_errors == { + "a.py": f"The parsing result was not published: the API server rejected it ({message}).", + } + assert report.result_unavailable + assert not manager._pending_publications + assert manager._file_stats[file].num_dags == 0 + assert manager._file_stats[file].import_errors == 1 + + +@conf_vars({("workers", "execution_api_retries"): "1"}) +def test_server_failure_after_publication_retries_preserves_previous_result(): + client = mock.create_autospec(DagProcessorAPIClient, instance=True) + client.publish_parse_result.side_effect = [_make_status_error(500), None] + manager = DagFileProcessorManager(max_runs=1, api_client=client) + file = _get_file_infos(["a.py"])[0] + previous = DagFileStat(num_dags=2, last_finish_time=DEFAULT_DATE) + manager._file_stats[file] = previous + pending = _make_pending_publication(file, attempt_id=uuid7()) + manager._pending_publications[file] = pending + + manager._publish_pending_results() + + client.publish_parse_result.assert_called_once_with(pending.body) + assert not manager._pending_publications + assert manager._file_stats[file].num_dags == previous.num_dags + assert manager._file_stats[file].last_finish_time == previous.last_finish_time + assert manager._file_stats[file].last_attempt_time is not None + + +def test_rejected_result_with_unrepresentable_diagnostic_does_not_stop_other_files(): + client = mock.create_autospec(DagProcessorAPIClient, instance=True) + client.publish_parse_result.side_effect = [_make_status_error(422), None] + manager = DagFileProcessorManager(max_runs=1, api_client=client) + long_file, short_file = _get_file_infos(["directory/" * 110 + "a.py", "b.py"]) + manager._file_stats[long_file] = DagFileStat(num_dags=2, last_finish_time=DEFAULT_DATE) + for file in (long_file, short_file): + manager._pending_publications[file] = _make_pending_publication(file) + + manager._publish_pending_results() + + assert not manager._pending_publications + assert manager._file_stats[long_file].num_dags == 2 + assert manager._file_stats[long_file].last_finish_time == DEFAULT_DATE + assert manager._file_stats[long_file].last_attempt_time is not None + assert manager._file_stats[short_file].num_dags == 1 + assert [call.args[0].relative_fileloc for call in client.publish_parse_result.call_args_list] == [ + str(long_file.rel_path), + "b.py", + ] + + +@pytest.mark.parametrize( + ("attempts", "expected_delay"), + [ + pytest.param(1, 3, id="minimum"), + pytest.param(3, 4, id="exponential"), + pytest.param(5, 10, id="maximum"), + ], +) +@conf_vars( + {("workers", "execution_api_retry_wait_min"): "3", ("workers", "execution_api_retry_wait_max"): "10"} +) +def test_retry_delay_doubles_within_the_configured_bounds(attempts, expected_delay): + assert _compute_retry_delay(attempts) == expected_delay + + +@pytest.mark.parametrize("status_code", [408, 429]) +@pytest.mark.parametrize("recovers", [False, True]) +@conf_vars( + { + ("workers", "execution_api_retries"): "3", + ("workers", "execution_api_retry_wait_min"): "2", + ("workers", "execution_api_retry_wait_max"): "3", + } +) +@mock.patch("airflow.dag_processing.manager.time.monotonic", autospec=True) +def test_transient_publication_retries_preserve_identity_until_terminal_outcome(clock, status_code, recovers): + client = mock.create_autospec(DagProcessorAPIClient, instance=True) + error = _make_status_error(status_code) + client.publish_parse_result.side_effect = [error, error, None if recovers else error] + manager = DagFileProcessorManager(max_runs=1, api_client=client) + manager._dispatch_sequence = 7 + file = _get_file_infos(["a.py"])[0] + previous = DagFileStat(num_dags=2, last_finish_time=DEFAULT_DATE) + manager._file_stats[file] = previous + pending = _make_pending_publication(file) + pending.body.dispatch_sequence = manager._dispatch_sequence + pending.body.bundle_version = "v1" + pending.body.bundle_revision = uuid7() + original_body = pending.body.model_dump_json() + manager._pending_publications[file] = pending + + for now, expected_sends, retry_at in [(100, 1, 102), (101, 1, 102), (102, 2, 104), (103, 2, 104)]: + clock.return_value = now + manager._publish_pending_results() + assert client.publish_parse_result.call_count == expected_sends + assert manager._pending_publications[file] is pending + assert pending.next_attempt_time == retry_at + assert manager._file_stats[file] is previous + + clock.return_value = 104 + manager._publish_pending_results() + manager._publish_pending_results() + + assert client.publish_parse_result.call_count == 3 + assert all(call.args[0] is pending.body for call in client.publish_parse_result.call_args_list) + assert pending.body.model_dump_json() == original_body + assert manager._dispatch_sequence == 7 + assert not manager._pending_publications + if recovers: + assert manager._file_stats[file] is pending.stat + else: + assert manager._file_stats[file].num_dags == previous.num_dags + assert manager._file_stats[file].last_finish_time == previous.last_finish_time + assert manager._file_stats[file].last_attempt_time is not None + + +@mock.patch("airflow.dag_processing.manager.MAX_PUBLICATION_BYTES", 32 * 1024) +@pytest.mark.parametrize("oversized_field", ["import_errors", "version_data", "parsed_definitions"]) +def test_rejection_report_discards_oversized_parse_metadata(oversized_field): + limit = 32 * 1024 + client = mock.create_autospec(DagProcessorAPIClient, instance=True) + client.publish_parse_result.side_effect = [_make_status_error(413), None] + manager = DagFileProcessorManager(max_runs=1, api_client=client) + file = _get_file_infos(["a.py"])[0] + original = _make_pending_publication(file) + original.body.bundle_version = "v1" + original.body.bundle_revision = uuid7() + oversized = { + "import_errors": {"a.py/member.py": "é" * limit}, + "version_data": {"metadata": "é" * limit}, + "parsed_definitions": ["a.py/member.py"] * limit, + } + setattr(original.body, oversized_field, oversized[oversized_field]) + assert len(original.body.model_dump_json().encode()) > limit + manager._pending_publications[file] = original + + manager._publish_pending_results() + + report = client.publish_parse_result.call_args_list[1].args[0] + assert len(report.model_dump_json().encode()) < limit + assert DagParseResultBody.model_validate_json(report.model_dump_json()) == report + assert report.bundle_version == original.body.bundle_version + assert report.bundle_revision == original.body.bundle_revision + assert report.version_data is None + assert report.parsed_definitions == [] + assert list(report.import_errors) == ["a.py"] + assert manager._file_stats[file].import_errors == 1 + assert not manager._pending_publications + + +@mock.patch("airflow.dag_processing.manager.MAX_PUBLICATION_BYTES", 32 * 1024) +def test_rejection_report_bounds_server_validation_message(): + client = mock.create_autospec(DagProcessorAPIClient, instance=True) + message = "Unknown role: " + "é" * (32 * 1024) + client.publish_parse_result.side_effect = [_make_status_error(422, "invalid_dag", message=message), None] + manager = DagFileProcessorManager(max_runs=1, api_client=client) + file = _get_file_infos(["a.py"])[0] + manager._pending_publications[file] = _make_pending_publication(file) + + manager._publish_pending_results() + + report = client.publish_parse_result.call_args_list[1].args[0] + assert "Unknown role: é" in report.import_errors["a.py"] + assert len(report.model_dump_json().encode()) < 32 * 1024 + + +def test_direct_manager_does_not_import_api_client(monkeypatch, mocker): + monkeypatch.setitem(sys.modules, "airflow.dag_processing.api_client", None) + namespace = runpy.run_path(sys.modules[DagFileProcessorManager.__module__].__file__) + manager_class = namespace["DagFileProcessorManager"] + bundle_manager = mocker.patch.object(manager_class, "_create_bundle_manager", autospec=True) + bundle_manager.return_value.get_bundle.side_effect = ValueError("missing bundle") + manager = manager_class(max_runs=1) + + manager._publish_pending_results() + manager.after_run() + request = DagCallbackRequest( + filepath="a.py", + dag_id="dag1", + run_id="run1", + is_failure_callback=False, + bundle_name="testing", + bundle_version="v1", + ) + assert manager.prepare_callback_bundle(request) is None + + +@pytest.mark.parametrize("reason", ["bundle_inactive", "publication_superseded", None]) +def test_refusal_unrelated_to_content_is_not_reported_as_an_import_error(reason): + client = mock.create_autospec(DagProcessorAPIClient, instance=True) + client.publish_parse_result.side_effect = _make_status_error(409, reason) + manager = DagFileProcessorManager(max_runs=1, api_client=client) + file = _get_file_infos(["a.py"])[0] + manager._pending_publications[file] = _make_pending_publication(file) + + manager._publish_pending_results() + + client.publish_parse_result.assert_called_once() + assert not manager._pending_publications + + +def test_refused_import_error_report_is_not_replaced_again(): + client = mock.create_autospec(DagProcessorAPIClient, instance=True) + client.publish_parse_result.side_effect = _make_status_error(413) + manager = DagFileProcessorManager(max_runs=1, api_client=client) + file = _get_file_infos(["a.py"])[0] + manager._pending_publications[file] = _make_pending_publication(file) + + manager._publish_pending_results() + + assert client.publish_parse_result.call_count == 2 + assert not manager._pending_publications + assert manager._file_stats[file].num_dags == 0 + + +@mock.patch("airflow.dag_processing.manager.MAX_PUBLICATION_BYTES", 1024 * 1024) +def test_result_over_the_publication_limit_is_reported_without_sending_it(): + client = mock.create_autospec(DagProcessorAPIClient, instance=True) + manager = DagFileProcessorManager(max_runs=1, api_client=client) + file = _get_file_infos(["a.py"])[0] + dag = SdkDAG("large", schedule=None, doc_md="x" * 1024 * 1024) + dag.fileloc = "/worker/a.py" + dag.relative_fileloc = "a.py" + proc = mock.create_autospec(DagFileProcessorProcess, instance=True) + proc.id = uuid7() + proc.start_time = time.monotonic() + proc.had_callbacks = False + proc.api_request_error = None + proc.dispatch_sequence = 1 + proc.parse_source = DagParseSource() + proc.parsing_result = DagFileParsingResult( + fileloc="a.py", serialized_dags=[LazyDeserializedDAG.from_dag(dag)] + ) + + manager.handle_parsing_result(file, proc) + + pending = manager._pending_publications[file] + assert pending.is_rejection_report + assert pending.body.serialized_dags == [] + assert pending.body.import_errors == { + "a.py": "The parsing result was not published: it exceeds the 1 MiB publication limit." + } + assert pending.body.result_unavailable + client.publish_parse_result.assert_not_called() + + +@pytest.mark.parametrize("method", ["claim_priority_files", "fetch_callbacks"]) +def test_internal_api_manager_leaves_requested_work_for_activation(method, mocker): + client = mock.create_autospec(DagProcessorAPIClient, instance=True) + database_method = ( + "_claim_priority_files" if method == "claim_priority_files" else "_fetch_callbacks_from_db" + ) + # The default work source binds these methods when the manager is built. + read_database = mocker.patch.object(DagFileProcessorManager, database_method, autospec=True) + manager = DagFileProcessorManager(max_runs=1, api_client=client) + + assert getattr(manager, method)() == [] + read_database.assert_not_called() diff --git a/airflow-core/tests/unit/dag_processing/test_manager_api_failures.py b/airflow-core/tests/unit/dag_processing/test_manager_api_failures.py new file mode 100644 index 000000000000..8eba529e9784 --- /dev/null +++ b/airflow-core/tests/unit/dag_processing/test_manager_api_failures.py @@ -0,0 +1,351 @@ +# 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 signal +from pathlib import Path +from unittest import mock + +import httpx2 +import pytest +from sqlalchemy import select +from uuid6 import uuid7 + +from airflow.api_fastapi.execution_api.datamodels.dag_parsing import ( + DagBundleStateResponse, + DagParseResultBody, + ParseSourceCode, +) +from airflow.api_fastapi.execution_api.datamodels.token import DagProcessorClaims, DagProcessorToken +from airflow.api_fastapi.execution_api.routes.dag_parsing import publish_parse_result +from airflow.dag_processing.api_client import DagProcessorAPIClient, DagProcessorRegistrationRetired +from airflow.dag_processing.manager import ( + DagFileInfo, + DagFileProcessorManager, + DagFileStat, + PendingDagPublication, +) +from airflow.dag_processing.processor import DagFileParsingResult, DagFileProcessorProcess, DagParseSource +from airflow.jobs.job import Job, JobState +from airflow.models.dag import DagModel +from airflow.models.dag_processor_publication_receipt import DagProcessorPublicationReceipt +from airflow.models.dagbundle import DagBundleModel +from airflow.models.errors import ParseImportError +from airflow.sdk import DAG, timezone +from airflow.serialization.serialized_objects import LazyDeserializedDAG + +from tests_common.test_utils.config import conf_vars + + +@pytest.mark.db_test +@pytest.mark.parametrize("outcome", ["no_result", "timeout"]) +@pytest.mark.parametrize("lose_acknowledgment", [False, True]) +@conf_vars({("workers", "execution_api_retries"): "2"}) +@mock.patch("airflow.dag_processing.manager.time", autospec=True) +def test_failed_parse_publishes_an_error_and_ages_out_prior_dags( + clock, session, time_machine, outcome, lose_acknowledgment +): + time_machine.move_to("2026-10-05T12:00:00Z", tick=False) + clock.monotonic.return_value = 100.0 + suffix = uuid7().hex + bundle_name = f"failed_parse_{suffix}" + dag_id = f"failed_parse_{suffix}" + session_id = uuid7() + revision = uuid7() + job = Job(job_type="DagProcessorJob", state=JobState.RUNNING) + job.session_id = session_id + job.registration_id = uuid7() + job.bundle_names = [bundle_name] + bundle = DagBundleModel(name=bundle_name, version="v1") + bundle.parse_revision = revision + session.add_all([job, bundle]) + session.flush() + token = DagProcessorToken( + id=session_id, + claims=DagProcessorClaims(exp=1, job_id=job.id, dag_bundles=frozenset({bundle_name})), + ) + dag = DAG(dag_id, schedule=None) + dag.fileloc = "/worker/a.py" + dag.relative_fileloc = "a.py" + body = DagParseResultBody( + attempt_id=uuid7(), + dispatch_sequence=1, + bundle_name=bundle_name, + relative_fileloc="a.py", + bundle_version="v1", + bundle_revision=revision, + parse_duration=0.1, + serialized_dags=[LazyDeserializedDAG.from_dag(dag).data], + source_codes=[ParseSourceCode(source_code="# captured source", language="python")], + dag_source_indexes={dag_id: 0}, + ) + publish_parse_result(job.id, body, session=session, token=token) + assert session.get(DagModel, dag_id).is_stale is False + previous_finish = timezone.utcnow() + client = mock.create_autospec(DagProcessorAPIClient, instance=True) + client.get_bundles.return_value = [] + + def publish(body): + receipt = publish_parse_result(job.id, body, session=session, token=token) + if lose_acknowledgment and client.publish_parse_result.call_count == 1: + raise httpx2.ReadTimeout("Lost publication acknowledgment") + return receipt + + client.publish_parse_result.side_effect = publish + manager = DagFileProcessorManager(max_runs=1, api_client=client, processor_timeout=10) + manager._dispatch_sequence = 2 + time_machine.shift(manager.stale_dag_threshold + 1) + file = DagFileInfo(bundle_name=bundle_name, rel_path=Path("a.py")) + previous_stat = DagFileStat(num_dags=1, last_finish_time=previous_finish) + manager._file_stats[file] = previous_stat + processor = mock.create_autospec(DagFileProcessorProcess, instance=True) + processor.id = uuid7() + processor.pid = 123 + processor.dispatch_sequence = 2 + processor.start_time = 89 if outcome == "timeout" else 99 + processor.is_ready = True + processor.had_callbacks = False + processor.api_request_error = None + processor.parsing_result = None + processor.parse_source = DagParseSource(bundle_version="v1", bundle_revision=revision) + manager._processors[file] = processor + + if outcome == "timeout": + manager._kill_timed_out_processors() + processor.kill.assert_called_once_with(signal.SIGKILL) + else: + manager._collect_results() + processor.close.assert_called_once_with() + assert not manager._processors + pending = manager._pending_publications[file] + assert pending.body.attempt_id == processor.id + assert pending.body.dispatch_sequence == processor.dispatch_sequence + assert manager._dispatch_sequence == processor.dispatch_sequence + assert pending.body.bundle_name == bundle_name + assert pending.body.relative_fileloc == "a.py" + assert pending.body.bundle_version == "v1" + assert pending.body.bundle_revision == revision + assert pending.body.parse_duration == (11 if outcome == "timeout" else 1) + assert pending.body.serialized_dags == [] + assert pending.body.import_errors == {"a.py": mock.ANY} + assert 0 < len(pending.body.import_errors["a.py"]) < 2048 + assert manager._file_stats[file] is previous_stat + + manager._publish_pending_results() + session.expire_all() + receipt = session.scalar( + select(DagProcessorPublicationReceipt).where(DagProcessorPublicationReceipt.job_id == job.id) + ) + accepted_at = receipt.accepted_at + if lose_acknowledgment: + assert manager._pending_publications[file] is pending + assert manager._file_stats[file] is previous_stat + clock.monotonic.return_value = pending.next_attempt_time + time_machine.shift(10) + manager._publish_pending_results() + session.expire_all() + assert receipt.accepted_at == accepted_at + + assert not manager._pending_publications + assert manager._file_stats[file].num_dags == 0 + assert manager._file_stats[file].import_errors == 1 + assert manager._file_stats[file].run_count == 1 + assert session.get(DagModel, dag_id).is_stale is True + error = session.scalar(select(ParseImportError).where(ParseImportError.bundle_name == bundle_name)) + assert error is not None + assert error.filename == "a.py" + assert error.stacktrace == pending.body.import_errors["a.py"] + assert receipt.attempt_id == processor.id + assert receipt.dispatch_sequence == processor.dispatch_sequence + assert client.publish_parse_result.call_args_list == [mock.call(pending.body)] * ( + 2 if lose_acknowledgment else 1 + ) + + +@pytest.mark.parametrize("outcome", ["callback", "refreshed"]) +@mock.patch("airflow.settings.Session", autospec=True, side_effect=AssertionError("Unexpected DB session")) +@mock.patch("airflow.dag_processing.manager.time", autospec=True) +def test_timeout_does_not_publish_for_callbacks_or_obsolete_sources(clock, session_factory, outcome): + clock.monotonic.return_value = 100.0 + client = mock.create_autospec(DagProcessorAPIClient, instance=True) + client.get_bundles.return_value = [] + manager = DagFileProcessorManager(max_runs=1, api_client=client, processor_timeout=10) + file = DagFileInfo(bundle_name="testing", rel_path=Path("a.py")) + processor = mock.create_autospec(DagFileProcessorProcess, instance=True) + processor.id = uuid7() + processor.pid = 123 + processor.dispatch_sequence = 1 + processor.start_time = 89 + processor.had_callbacks = outcome == "callback" + processor.api_request_error = None + processor.parsing_result = None + processor.parse_source = DagParseSource(bundle_revision=uuid7()) + manager._processors[file] = processor + manager._bundle_refresh_generations[file.bundle_name] = 1 if outcome == "refreshed" else 0 + + manager._kill_timed_out_processors() + + assert not manager._pending_publications + manager._publish_pending_results() + processor.kill.assert_called_once_with(signal.SIGKILL) + processor.close.assert_called_once_with() + assert not manager._processors + client.publish_parse_result.assert_not_called() + session_factory.assert_not_called() + assert list(manager._file_queue) == ([file] if outcome == "refreshed" else []) + + +@pytest.mark.parametrize("outcome", ["no_result", "timeout"]) +@mock.patch("airflow.dag_processing.manager.time", autospec=True) +def test_failed_parse_with_unrepresentable_diagnostic_does_not_stop_other_files(clock, time_machine, outcome): + time_machine.move_to("2026-10-05T12:00:00Z", tick=False) + clock.monotonic.return_value = 100.0 + client = mock.create_autospec(DagProcessorAPIClient, instance=True) + client.get_bundles.return_value = [] + manager = DagFileProcessorManager(max_runs=1, api_client=client, processor_timeout=10) + long_file, short_file = [ + DagFileInfo(bundle_name="testing", rel_path=Path(path)) + for path in ("directory/" * 110 + "a.py", "b.py") + ] + manager._file_stats[long_file] = DagFileStat(num_dags=1) + for file in (long_file, short_file): + processor = mock.create_autospec(DagFileProcessorProcess, instance=True) + processor.id = uuid7() + processor.pid = 123 + processor.dispatch_sequence = 1 + processor.start_time = 89 + processor.is_ready = True + processor.had_callbacks = False + processor.api_request_error = None + processor.parsing_result = None + processor.parse_source = DagParseSource() + manager._processors[file] = processor + processes = list(manager._processors.values()) + + if outcome == "timeout": + manager._kill_timed_out_processors() + else: + manager._collect_results() + manager._publish_pending_results() + + assert not manager._processors + assert not manager._pending_publications + assert manager._file_stats[long_file].num_dags == 1 + assert manager._file_stats[long_file].last_finish_time is None + assert manager._file_stats[long_file].last_attempt_time is not None + assert manager._file_stats[short_file].import_errors == 1 + client.publish_parse_result.assert_called_once() + assert client.publish_parse_result.call_args.args[0].relative_fileloc == "b.py" + for processor in processes: + processor.close.assert_called_once_with() + + +def test_startup_catalog_read_waits_out_an_unavailable_api(): + client = mock.create_autospec(DagProcessorAPIClient, instance=True) + client.get_bundles.return_value = [ + DagBundleStateResponse(name="a", version=None, last_refreshed=None, revision=None, team_name=None) + ] + manager = DagFileProcessorManager(max_runs=1, api_client=client, bundle_names_to_parse=["a"]) + + manager.sync_bundles() + + client.get_bundles.assert_called_once_with(retry=True) + + +@mock.patch.object(DagFileProcessorManager, "after_run", autospec=True) +@mock.patch.object(DagFileProcessorManager, "_run_parsing_loop", autospec=True) +@mock.patch.object(DagFileProcessorManager, "before_run", autospec=True) +def test_only_the_parsing_loop_retries_without_waiting(before_run, run_parsing_loop, after_run, tmp_path): + with DagProcessorAPIClient( + base_url="http://unused/", token_file=tmp_path / "processor.jwt", hostname="processor-1" + ) as client: + retries_at_once = [] + for phase in (before_run, run_parsing_loop, after_run): + phase.side_effect = lambda _: retries_at_once.append(client._retry_without_waiting.get()) + + DagFileProcessorManager(max_runs=1, api_client=client).run() + + assert retries_at_once == [False, True, False] + + +_API_REQUEST_FAILURE = "an Execution API request failed while parsing: GetVariable (HTTP 503)" + + +@pytest.mark.parametrize( + ("outcome", "api_request_error", "reason"), + [ + ("no_result", None, "the parsing process exited without a result"), + ("timeout", None, "the parsing process exceeded its timeout of 10 seconds"), + ("parsed", "GetVariable (HTTP 503)", _API_REQUEST_FAILURE), + ("no_result", "GetVariable (HTTP 503)", _API_REQUEST_FAILURE), + ("timeout", "GetVariable (HTTP 503)", _API_REQUEST_FAILURE), + ], +) +@mock.patch("airflow.dag_processing.manager.time", autospec=True) +def test_failed_parse_is_reported_at_once_as_an_unavailable_result( + clock, time_machine, outcome, api_request_error, reason +): + time_machine.move_to("2026-10-05T12:00:00Z", tick=False) + clock.monotonic.return_value = 100.0 + client = mock.create_autospec(DagProcessorAPIClient, instance=True) + manager = DagFileProcessorManager(max_runs=1, api_client=client, processor_timeout=10) + file = DagFileInfo(bundle_name="testing", rel_path=Path("a.py")) + manager._file_stats[file] = DagFileStat(num_dags=1, last_finish_time=timezone.utcnow()) + processor = mock.create_autospec(DagFileProcessorProcess, instance=True) + processor.id = uuid7() + processor.pid = 123 + processor.dispatch_sequence = 1 + processor.start_time = 89 if outcome == "timeout" else 99 + processor.is_ready = True + processor.had_callbacks = False + processor.api_request_error = api_request_error + processor.parsing_result = ( + DagFileParsingResult(fileloc="a.py", serialized_dags=[]) if outcome == "parsed" else None + ) + processor.parse_source = DagParseSource() + manager._processors[file] = processor + + if outcome == "timeout": + manager._kill_timed_out_processors() + processor.kill.assert_called_once_with(signal.SIGKILL) + else: + manager._collect_results() + + processor.close.assert_called_once_with() + body = manager._pending_publications[file].body + assert body.serialized_dags == [] + assert body.import_errors == {"a.py": f"The parsing result was not published: {reason}."} + assert body.result_unavailable + + +def test_retired_registration_stops_publication(): + client = mock.create_autospec(DagProcessorAPIClient, instance=True) + client.publish_parse_result.side_effect = DagProcessorRegistrationRetired("Restart required") + manager = DagFileProcessorManager(max_runs=1, api_client=client) + for name in ("a.py", "b.py"): + file = DagFileInfo(bundle_name="testing", rel_path=Path(name)) + manager._pending_publications[file] = PendingDagPublication( + body=mock.create_autospec(DagParseResultBody, instance=True), + stat=DagFileStat(), + refresh_generation=0, + ) + + with pytest.raises(DagProcessorRegistrationRetired): + manager._publish_pending_results() + + client.publish_parse_result.assert_called_once() + assert len(manager._pending_publications) == 2 diff --git a/airflow-core/tests/unit/dag_processing/test_manager_api_inventory.py b/airflow-core/tests/unit/dag_processing/test_manager_api_inventory.py new file mode 100644 index 000000000000..d26fa90517b9 --- /dev/null +++ b/airflow-core/tests/unit/dag_processing/test_manager_api_inventory.py @@ -0,0 +1,453 @@ +# 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 + +from contextlib import nullcontext +from pathlib import Path +from unittest import mock + +import httpx2 +import pytest +from uuid6 import uuid7 + +from airflow._shared.timezones import timezone +from airflow.api_fastapi.execution_api.datamodels.dag_parsing import ( + DagBundleInventoryBody, + DagBundleInventoryResponse, + DagBundleStateResponse, +) +from airflow.dag_processing.api_client import DagProcessorAPIClient +from airflow.dag_processing.bundles.base import BaseDagBundle, BundleVersion +from airflow.dag_processing.manager import ( + DagBundleDiscoveryResult, + DagFileInfo, + DagFileProcessorManager, + PendingBundleInventory, +) +from airflow.dag_processing.processor import DagParseSource + +from tests_common.test_utils.config import conf_vars + + +@pytest.fixture(autouse=True) +def freeze_time(time_machine): + time_machine.move_to("2026-10-28T12:00:00Z", tick=False) + + +def _create_bundle(tmp_path, name): + bundle = mock.create_autospec(BaseDagBundle, instance=True) + bundle.name = name + bundle.path = tmp_path + bundle.is_initialized = True + bundle.supports_versioning = False + bundle.refresh_changes_source = True + bundle.refresh_interval = 3600 + return bundle + + +def _create_client(bundles): + client = mock.create_autospec(DagProcessorAPIClient, instance=True) + client.use_bundle.side_effect = lambda name: nullcontext() + client.get_bundles.return_value = [ + DagBundleStateResponse( + name=bundle.name, version=None, last_refreshed=None, revision=uuid7(), team_name=None + ) + for bundle in bundles + ] + return client + + +@pytest.mark.parametrize("already_pending", [False, True], ids=["first-send", "retry"]) +@conf_vars( + {("workers", "execution_api_retry_wait_min"): "1", ("workers", "execution_api_retry_wait_max"): "1"} +) +@mock.patch("airflow.dag_processing.manager.time", autospec=True) +@mock.patch.object( + DagFileProcessorManager, + "_find_files_in_bundle", + autospec=True, + return_value=DagBundleDiscoveryResult(files=set()), +) +def test_slow_inventory_sends_yield_and_rotate_to_later_bundles(find_files, clock, already_pending, tmp_path): + clock.monotonic.return_value = 100.0 + bundles = [_create_bundle(tmp_path, name) for name in ("a", "b", "c")] + client = _create_client(bundles) + manager = DagFileProcessorManager(max_runs=-1, api_client=client, bundle_refresh_check_interval=5) + manager._dag_bundles = bundles + original_bodies = {} + if already_pending: + for sequence, state in enumerate(client.get_bundles.return_value, start=1): + body = DagBundleInventoryBody( + attempt_id=uuid7(), dispatch_sequence=sequence, expected_revision=state.revision, files=[] + ) + manager._pending_inventories[state.name] = PendingBundleInventory(body, set(), DagParseSource()) + original_bodies[state.name] = body + + def publish_with_timeout(bundle_name, body): + clock.monotonic.return_value += 5.0 + raise httpx2.ReadTimeout("Inventory response timed out") + + client.publish_inventory.side_effect = publish_with_timeout + for index, now in enumerate((100.0, 106.0, 112.0), start=1): + clock.monotonic.return_value = now + manager._refresh_dag_bundles({}) + assert client.publish_inventory.call_count == index + assert clock.monotonic.return_value == now + 5.0 + for name, body in original_bodies.items(): + assert manager._pending_inventories[name].body is body + original_bodies.update({name: pending.body for name, pending in manager._pending_inventories.items()}) + + assert [call.args[0] for call in client.publish_inventory.call_args_list] == ["a", "b", "c"] + assert set(manager._pending_inventories) == {"a", "b", "c"} + assert all(pending.attempts == 1 for pending in manager._pending_inventories.values()) + if already_pending: + find_files.assert_not_called() + for bundle in bundles: + assert bundle.refresh.call_count == (0 if already_pending else 1) + + +@pytest.mark.parametrize("rejection", ["http_413", "local_size_limit"]) +@mock.patch("airflow.dag_processing.manager.MAX_PUBLICATION_BYTES", 1024) +@mock.patch("airflow.dag_processing.manager.time", autospec=True) +@mock.patch.object(DagFileProcessorManager, "_find_files_in_bundle", autospec=True) +def test_rejected_inventory_waits_before_refresh_and_recovers(find_files, clock, rejection, caplog, tmp_path): + clock.monotonic.return_value = 100.0 + bundle = _create_bundle(tmp_path, "testing") + client = _create_client([bundle]) + state = client.get_bundles.return_value[0] + state.last_refreshed = timezone.utcnow() + manager = DagFileProcessorManager(max_runs=-1, api_client=client, bundle_refresh_check_interval=5) + manager._dag_bundles = [bundle] + manager._bundle_versions[bundle.name] = "previous" + manager._bundle_parse_sources[bundle.name] = DagParseSource(bundle_revision=state.revision) + manager.request_bundle_refresh(bundle.name) + previous_file, new_file = [ + DagFileInfo(bundle_name=bundle.name, rel_path=Path(name), bundle_path=tmp_path) + for name in ("previous.py", "new.py") + ] + previous_file.absolute_path.touch() + new_file.absolute_path.touch() + known_files = {bundle.name: {previous_file}} + observed = {new_file} + if rejection == "local_size_limit": + observed = { + DagFileInfo( + bundle_name=bundle.name, rel_path=Path(f"{index}/{'é' * 80}.py"), bundle_path=tmp_path + ) + for index in range(6) + } + else: + response = httpx2.Response(413, request=httpx2.Request("POST", "http://api/inventory")) + client.publish_inventory.side_effect = httpx2.HTTPStatusError( + "Proxy body limit", request=response.request, response=response + ) + find_files.return_value = DagBundleDiscoveryResult(files=observed) + + manager._refresh_dag_bundles(known_files) + + assert known_files == {bundle.name: {previous_file}} + assert manager._bundle_versions[bundle.name] == "previous" + assert bundle.name not in manager._bundle_parse_sources + assert not manager._pending_inventories + bundle.refresh.assert_called_once_with() + find_files.assert_called_once_with(manager, bundle) + sends = int(rejection == "http_413") + assert client.publish_inventory.call_count == sends + if rejection == "http_413": + assert { + "event": "Inventory publication was rejected for testing", + "status_code": 413, + "log_level": "warning", + } in caplog + + manager.request_bundle_refresh(bundle.name) + for now in (105.0, 3699.0): + clock.monotonic.return_value = now + manager._refresh_dag_bundles(known_files) + bundle.refresh.assert_called_once_with() + find_files.assert_called_once_with(manager, bundle) + assert client.publish_inventory.call_count == sends + assert known_files == {bundle.name: {previous_file}} + + revision = uuid7() + + def accept_inventory(bundle_name, body): + return DagBundleInventoryResponse( + attempt_id=body.attempt_id, accepted_at=timezone.utcnow(), revision=revision + ) + + find_files.return_value = DagBundleDiscoveryResult(files={new_file}) + client.publish_inventory.side_effect = accept_inventory + clock.monotonic.return_value = 3700.0 + manager._refresh_dag_bundles(known_files) + + assert bundle.refresh.call_count == 2 + assert find_files.call_count == 2 + assert client.publish_inventory.call_count == sends + 1 + assert known_files == {bundle.name: {new_file}} + assert manager._bundle_versions[bundle.name] is None + assert manager._bundle_parse_sources[bundle.name].bundle_revision == revision + assert not manager._pending_inventories + assert not manager._bundle_inventory_retry_times + + clock.monotonic.return_value = 3705.0 + manager._refresh_dag_bundles(known_files) + assert bundle.refresh.call_count == 2 + + +@mock.patch("airflow.dag_processing.manager.time", autospec=True) +@mock.patch.object(DagFileProcessorManager, "_find_files_in_bundle", autospec=True) +def test_failed_listing_retries_with_backoff_and_resets_after_success(find_files, clock, tmp_path): + bundle = _create_bundle(tmp_path, "testing") + bundle.refresh_interval = 30 + client = _create_client([bundle]) + client.get_bundles.return_value[0].last_refreshed = timezone.utcnow() + client.publish_inventory.side_effect = lambda bundle_name, body: DagBundleInventoryResponse( + attempt_id=body.attempt_id, accepted_at=timezone.utcnow(), revision=uuid7() + ) + manager = DagFileProcessorManager(max_runs=-1, api_client=client, bundle_refresh_check_interval=5) + manager._dag_bundles = [bundle] + dag_file = DagFileInfo(bundle_name=bundle.name, rel_path=Path("dag.py"), bundle_path=tmp_path) + dag_file.absolute_path.touch() + known_files: dict[str, set[DagFileInfo]] = {bundle.name: set()} + find_files.side_effect = OSError("Listing failed") + + def refresh(): + # A refresh takes time, as a git fetch would, so the listing fails after the check started. + clock.monotonic.return_value += 1 + + bundle.refresh.side_effect = refresh + + def refresh_at(now): + clock.monotonic.return_value = now + manager._refresh_dag_bundles(known_files) + + now = 100 + for delay in (5, 10, 20, 30, 30): + listings = find_files.call_count + refresh_at(now) + assert find_files.call_count == listings + 1 + assert manager._bundle_inventory_retry_times[bundle.name] == now + delay + assert bundle.name not in manager._bundle_parse_sources + for check in range(now + 5, now + delay, 5): + refresh_at(check) + assert find_files.call_count == listings + 1 + now += delay + assert bundle.refresh.call_count == find_files.call_count + + find_files.side_effect = None + find_files.return_value = DagBundleDiscoveryResult(files={dag_file}) + refresh_at(now) + assert known_files == {bundle.name: {dag_file}} + assert bundle.name in manager._bundle_parse_sources + + find_files.side_effect = OSError("Listing failed") + manager.request_bundle_refresh(bundle.name) + refresh_at(now + 1) + assert manager._bundle_inventory_retry_times[bundle.name] == now + 1 + 5 + + +@pytest.mark.parametrize("invalid_path", [r"bad\dag.py", "a" * 2001], ids=["backslash", "too-long"]) +@pytest.mark.parametrize( + "valid_members", + [None, {"archive.zip/valid.py"}, set()], + ids=["standalone", "container-with-valid-member", "container-with-only-invalid-member"], +) +@mock.patch("airflow.dag_processing.manager.time", autospec=True) +@mock.patch.object(DagFileProcessorManager, "_find_files_in_bundle", autospec=True) +def test_invalid_inventory_paths_do_not_pause_valid_sources( + find_files, clock, invalid_path, valid_members, caplog, tmp_path +): + clock.monotonic.return_value = 100.0 + bundle = _create_bundle(tmp_path, "testing") + client = _create_client([bundle]) + client.get_bundles.return_value[0].last_refreshed = timezone.utcnow() + manager = DagFileProcessorManager(max_runs=-1, api_client=client, bundle_refresh_check_interval=5) + manager._dag_bundles = [bundle] + manager.request_bundle_refresh(bundle.name) + valid_file = DagFileInfo(bundle_name=bundle.name, rel_path=Path("valid.py"), bundle_path=tmp_path) + valid_file.absolute_path.touch() + container = valid_members is not None + invalid_location = f"archive.zip/{invalid_path}" if container else invalid_path + if container: + invalid_file = DagFileInfo( + bundle_name=bundle.name, + rel_path=Path("archive.zip"), + bundle_path=tmp_path, + definition_locs=frozenset({*valid_members, invalid_location}), + ) + invalid_file.absolute_path.touch() + else: + invalid_file = DagFileInfo(bundle_name=bundle.name, rel_path=Path(invalid_path), bundle_path=tmp_path) + find_files.return_value = DagBundleDiscoveryResult( + files={valid_file, invalid_file}, failed_sources=frozenset({"failed.zip", invalid_path}) + ) + revision = uuid7() + client.publish_inventory.side_effect = lambda bundle_name, body: DagBundleInventoryResponse( + attempt_id=body.attempt_id, accepted_at=timezone.utcnow(), revision=revision + ) + known_files = {bundle.name: {invalid_file}} + + manager._refresh_dag_bundles(known_files) + + body = client.publish_inventory.call_args.args[1] + expected_files = {valid_file, invalid_file} if container else {valid_file} + assert body.files == (["archive.zip", *sorted(valid_members), "valid.py"] if container else ["valid.py"]) + assert body.failed_sources == ["failed.zip"] + assert known_files == {bundle.name: expected_files} + assert {file: file.definition_locs for file in known_files[bundle.name]} == { + file: file.definition_locs - {invalid_location} for file in expected_files + } + assert set(manager._file_queue) == expected_files + assert manager._bundle_parse_sources[bundle.name].bundle_revision == revision + assert not manager._bundle_inventory_retry_times + assert { + "event": "Skipping source with an unrepresentable API path", + "bundle_name": bundle.name, + "relative_fileloc": invalid_location, + } in caplog + + clock.monotonic.return_value = 105.0 + manager._refresh_dag_bundles(known_files) + bundle.refresh.assert_called_once_with() + find_files.assert_called_once_with(manager, bundle) + client.publish_inventory.assert_called_once() + + +@pytest.mark.parametrize("refresh_cooldown", [False, True]) +@mock.patch("airflow.dag_processing.manager.time", autospec=True) +@mock.patch.object( + DagFileProcessorManager, + "_find_files_in_bundle", + autospec=True, + return_value=DagBundleDiscoveryResult(files=set()), +) +def test_missing_catalog_bundle_warns_once_until_it_reappears( + find_files, clock, caplog, tmp_path, refresh_cooldown +): + bundle = _create_bundle(tmp_path, "testing") + client = _create_client([bundle]) + catalog = client.get_bundles.return_value + manager = DagFileProcessorManager(max_runs=-1, api_client=client, bundle_refresh_check_interval=5) + manager._dag_bundles = [bundle] + manager._bundle_versions[bundle.name] = None + manager._bundle_parse_sources[bundle.name] = DagParseSource(bundle_revision=catalog[0].revision) + if refresh_cooldown: + manager._bundle_refresh_retry_at[bundle.name] = 1000.0 + + def accept_inventory(bundle_name, body): + return DagBundleInventoryResponse( + attempt_id=body.attempt_id, accepted_at=timezone.utcnow(), revision=uuid7() + ) + + client.publish_inventory.side_effect = accept_inventory + diagnostic = { + "event": "Bundle missing from API catalog; parsing paused", + "bundle_name": bundle.name, + "log_level": "warning", + } + for now, present, warns in ( + (100.0, False, True), + (105.0, False, False), + (110.0, True, False), + (115.0, False, True), + (120.0, False, False), + ): + caplog.clear() + clock.monotonic.return_value = now + client.get_bundles.return_value = catalog if present else [] + manager._refresh_dag_bundles({}) + assert (diagnostic in caplog) is warns + if warns: + assert sum(entry["event"] == diagnostic["event"] for entry in caplog.entries) == 1 + assert (bundle.name in manager._bundle_parse_sources) is present + assert bundle.name not in manager._bundle_refresh_retry_at + + find_files.assert_called_once_with(manager, bundle) + + +@mock.patch.object(DagFileProcessorManager, "update_bundle_state", autospec=True) +@mock.patch.object( + DagFileProcessorManager, + "_find_files_in_bundle", + autospec=True, + return_value=DagBundleDiscoveryResult(files=set()), +) +def test_unchanged_versioned_bundle_refresh_publishes_an_inventory(find_files, update_bundle_state, tmp_path): + bundle = _create_bundle(tmp_path, "testing") + bundle.supports_versioning = True + bundle.get_current_version.return_value = BundleVersion(version="v1") + client = _create_client([bundle]) + state = client.get_bundles.return_value[0] + state.version = "v1" + receipt_revision = uuid7() + client.publish_inventory.side_effect = lambda bundle_name, body: DagBundleInventoryResponse( + attempt_id=body.attempt_id, accepted_at=timezone.utcnow(), revision=receipt_revision + ) + manager = DagFileProcessorManager(max_runs=-1, api_client=client, bundle_refresh_check_interval=5) + manager._dag_bundles = [bundle] + manager._bundle_versions[bundle.name] = "v1" + manager._bundle_parse_sources[bundle.name] = DagParseSource( + bundle_version="v1", bundle_revision=state.revision + ) + manager.request_bundle_refresh(bundle.name) + + manager._refresh_dag_bundles({}) + + bundle.refresh.assert_called_once_with() + update_bundle_state.assert_not_called() + body = client.publish_inventory.call_args.args[1] + assert body.version == "v1" + assert body.expected_revision == state.revision + source = manager._bundle_parse_sources[bundle.name] + assert source.bundle_version == "v1" + assert source.bundle_revision == receipt_revision + + +@pytest.mark.parametrize("blocked_by", ["inventory_cooldown", "pending_inventory", "failed_catalog_read"]) +@mock.patch("airflow.dag_processing.manager.time", autospec=True) +def test_requested_refresh_of_a_blocked_bundle_waits_for_the_periodic_catalog_read( + clock, blocked_by, tmp_path +): + clock.monotonic.return_value = 100.0 + bundle = _create_bundle(tmp_path, "testing") + client = _create_client([bundle]) + manager = DagFileProcessorManager(max_runs=-1, api_client=client, bundle_refresh_check_interval=5) + manager._dag_bundles = [bundle] + if blocked_by == "inventory_cooldown": + manager._bundle_inventory_retry_times[bundle.name] = 1000.0 + elif blocked_by == "pending_inventory": + body = DagBundleInventoryBody( + attempt_id=uuid7(), dispatch_sequence=1, expected_revision=None, files=[] + ) + manager._pending_inventories[bundle.name] = PendingBundleInventory( + body, set(), DagParseSource(), next_attempt_time=1000.0 + ) + else: + client.get_bundles.side_effect = httpx2.ConnectError("API unavailable") + manager._refresh_dag_bundles({}) + manager.request_bundle_refresh(bundle.name) + + for now in (101.0, 102.0, 104.0): + clock.monotonic.return_value = now + manager._refresh_dag_bundles({}) + + assert client.get_bundles.call_count == 1 + clock.monotonic.return_value = 105.0 + manager._refresh_dag_bundles({}) + assert client.get_bundles.call_count == 2 + bundle.refresh.assert_not_called() diff --git a/airflow-core/tests/unit/dag_processing/test_manager_api_isolation.py b/airflow-core/tests/unit/dag_processing/test_manager_api_isolation.py new file mode 100644 index 000000000000..5b748a340148 --- /dev/null +++ b/airflow-core/tests/unit/dag_processing/test_manager_api_isolation.py @@ -0,0 +1,206 @@ +# 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. +"""API-mode manager paths that must not reach the metadata database.""" + +from __future__ import annotations + +import json +import textwrap +from contextlib import nullcontext +from unittest import mock + +import httpx2 +import pytest +from sqlalchemy.engine import Engine +from uuid6 import uuid7 + +from airflow import settings +from airflow._shared.timezones import timezone +from airflow.api_fastapi.execution_api.datamodels.dag_parsing import ( + DagBundleInventoryResponse, + DagBundleStateResponse, + DagParseResultResponse, +) +from airflow.dag_processing.api_client import DagProcessorAPIClient +from airflow.dag_processing.bundles.base import BaseDagBundle +from airflow.dag_processing.bundles.manager import _load_bundle_config_snapshot +from airflow.dag_processing.manager import DagFileProcessorManager + +from tests_common.test_utils.config import conf_vars + + +def _create_client(*bundle_names: str): + client = mock.create_autospec(DagProcessorAPIClient, instance=True) + client.use_bundle.side_effect = lambda name: nullcontext() + client.get_bundles.return_value = [ + DagBundleStateResponse(name=name, version=None, last_refreshed=None, revision=None, team_name=None) + for name in bundle_names + ] + return client + + +def _create_bundle(name: str, *, supports_versioning: bool = False): + bundle = mock.create_autospec(BaseDagBundle, instance=True) + bundle.name = name + bundle.is_initialized = True + bundle.supports_versioning = supports_versioning + return bundle + + +@pytest.fixture +def database_calls(monkeypatch): + """Make every metadata-database entry point record its use and fail.""" + calls = [] + + def forbid(name): + def record(*args, **kwargs): + calls.append(name) + raise RuntimeError(f"Unexpected database access through {name}") + + return record + + monkeypatch.setattr(settings, "Session", forbid("settings.Session")) + monkeypatch.setattr(settings, "NonScopedSession", forbid("settings.NonScopedSession")) + monkeypatch.setattr(Engine, "connect", forbid("Engine.connect")) + monkeypatch.setattr(Engine, "raw_connection", forbid("Engine.raw_connection")) + return calls + + +@mock.patch.object(DagFileProcessorManager, "deactivate_stale_dags", autospec=True) +def test_stale_dag_scan_does_not_deactivate_dags(deactivate): + manager = DagFileProcessorManager(max_runs=1, api_client=_create_client(), parsing_cleanup_interval=0) + + manager._scan_stale_dags() + + deactivate.assert_not_called() + + +@mock.patch.object(DagFileProcessorManager, "get_bundle_state", autospec=True, return_value=None) +def test_unreadable_catalog_does_not_read_bundle_state_or_refresh(get_bundle_state): + client = _create_client() + client.get_bundles.side_effect = httpx2.ConnectError("API unavailable") + manager = DagFileProcessorManager(max_runs=1, api_client=client, bundle_refresh_check_interval=0) + bundle = _create_bundle("testing") + manager._dag_bundles = [bundle] + + manager._refresh_dag_bundles({}) + + get_bundle_state.assert_not_called() + bundle.refresh.assert_not_called() + + +@pytest.mark.parametrize( + ("provisioned", "expectation"), + [ + pytest.param(["a", "b"], nullcontext(), id="all-provisioned"), + pytest.param(["a"], pytest.raises(ValueError, match=r"\['b'\]"), id="missing-bundle"), + ], +) +@mock.patch("airflow.dag_processing.manager.DagBundlesManager", autospec=True) +def test_sync_bundles_checks_provisioning_without_writing_bundles(bundles_manager, provisioned, expectation): + client = _create_client(*provisioned) + manager = DagFileProcessorManager(max_runs=1, api_client=client, bundle_names_to_parse=["a", "b"]) + + with expectation: + manager.sync_bundles() + + client.get_bundles.assert_called_once() + bundles_manager.return_value.sync_bundles_to_db.assert_not_called() + + +@mock.patch("airflow.dag_processing.manager.BundleUsageTrackingManager", autospec=True) +def test_stale_bundle_version_cleanup_is_scoped_to_loaded_versioned_bundles(tracking_manager): + manager = DagFileProcessorManager(max_runs=1, api_client=_create_client()) + manager._dag_bundles = [_create_bundle("versioned", supports_versioning=True), _create_bundle("plain")] + + manager.cleanup_stale_bundle_versions() + + tracking_manager.return_value.remove_stale_bundle_versions_for_bundle.assert_called_once_with("versioned") + tracking_manager.return_value.remove_stale_bundle_versions.assert_not_called() + + +@mock.patch.object(DagFileProcessorManager, "register_exit_signals", autospec=True) +@mock.patch("airflow.dag_processing.manager.gc", autospec=True) +def test_parsing_loop_publishes_through_the_api_without_database_calls( + gc, register_exit_signals, database_calls, tmp_path, monkeypatch +): + """ + One full ``run()`` of an API-mode manager, observed in the manager process only. + + Removing the API-mode guard in ``_scan_stale_dags`` or ``sync_bundles`` fails this test. It + does not cover the guard for an unreadable catalog in ``_refresh_dag_bundles``, because the + catalog read succeeds here, nor the one in ``cleanup_stale_bundle_versions``, whose + database-mode fallback lists bundles without querying the database; the tests above cover both. + """ + dags = tmp_path / "dags" + dags.mkdir() + (dags / "api_mode_dag.py").write_text( + textwrap.dedent( + """ + from airflow.sdk import DAG + + with DAG("api_mode_dag", schedule=None): + pass + """ + ) + ) + bundle_config = { + "name": "api_mode", + "classpath": "airflow.dag_processing.bundles.local.LocalDagBundle", + "kwargs": {"path": str(dags), "refresh_interval": 0}, + } + client = _create_client("api_mode") + client.publish_inventory.side_effect = lambda bundle_name, body: DagBundleInventoryResponse( + attempt_id=body.attempt_id, accepted_at=timezone.utcnow(), revision=uuid7() + ) + published = [] + + def publish_parse_result(body): + published.append(body) + return DagParseResultResponse(attempt_id=body.attempt_id, accepted_at=timezone.utcnow()) + + client.publish_parse_result.side_effect = publish_parse_result + # run() sets this for the whole process; monkeypatch restores the previous value on teardown. + monkeypatch.setenv("_AIRFLOW_PROCESS_CONTEXT", "client") + + with conf_vars( + { + ("dag_processor", "dag_bundle_config_list"): json.dumps([bundle_config]), + ("core", "load_examples"): "False", + ("logging", "dag_processor_child_process_log_directory"): str(tmp_path / "logs"), + } + ): + _load_bundle_config_snapshot.cache_clear() + manager = DagFileProcessorManager( + max_runs=1, api_client=client, parsing_cleanup_interval=0, stale_bundle_cleanup_interval=1 + ) + try: + manager.run() + finally: + manager.terminate() + manager.end() + _load_bundle_config_snapshot.cache_clear() + + assert database_calls == [] + assert [(body.relative_fileloc, len(body.serialized_dags), body.import_errors) for body in published] == [ + ("api_mode_dag.py", 1, {}) + ] + assert client.publish_inventory.call_args_list + assert all( + call.args[0] == "api_mode" and call.args[1].files == ["api_mode_dag.py"] + for call in client.publish_inventory.call_args_list + ) diff --git a/airflow-core/tests/unit/dag_processing/test_manager_api_results.py b/airflow-core/tests/unit/dag_processing/test_manager_api_results.py new file mode 100644 index 000000000000..a5138e506fc9 --- /dev/null +++ b/airflow-core/tests/unit/dag_processing/test_manager_api_results.py @@ -0,0 +1,72 @@ +# 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 time +from pathlib import Path +from unittest import mock + +import pytest +from uuid6 import uuid7 + +from airflow.dag_processing.api_client import DagProcessorAPIClient +from airflow.dag_processing.manager import DagFileInfo, DagFileProcessorManager +from airflow.dag_processing.processor import DagFileParsingResult, DagFileProcessorProcess, DagParseSource + + +@pytest.mark.parametrize("outcome", ["parsed", "callback", "failed", "stale", "stale_failure"]) +@mock.patch("airflow.settings.Session", autospec=True, side_effect=AssertionError("Unexpected DB session")) +def test_api_result_collection_does_not_create_database_session( + session_factory, outcome, tmp_path, time_machine +): + time_machine.move_to("2026-10-05T12:00:00Z", tick=False) + client = mock.create_autospec(DagProcessorAPIClient, instance=True) + manager = DagFileProcessorManager(max_runs=1, api_client=client) + file = DagFileInfo(bundle_name="testing", rel_path=Path("a.py"), bundle_path=tmp_path) + processor = mock.create_autospec(DagFileProcessorProcess, instance=True) + processor.id = uuid7() + processor.dispatch_sequence = 1 + processor.is_ready = True + processor.start_time = time.monotonic() + processor.had_callbacks = outcome == "callback" + processor.api_request_error = None + processor.parse_source = DagParseSource(bundle_revision=uuid7()) + processor.parsing_result = ( + DagFileParsingResult(fileloc="a.py", serialized_dags=[]) if outcome in {"parsed", "stale"} else None + ) + source_changed = outcome in {"stale", "stale_failure"} + manager._bundle_refresh_generations[file.bundle_name] = 1 if source_changed else 0 + manager._processors[file] = processor + + manager._collect_results() + + session_factory.assert_not_called() + processor.close.assert_called_once_with() + assert not manager._processors + if outcome in {"parsed", "failed"}: + body = manager._pending_publications[file].body + assert body.attempt_id == processor.id + assert body.dispatch_sequence == processor.dispatch_sequence + assert body.bundle_revision == processor.parse_source.bundle_revision + assert body.import_errors == ({"a.py": mock.ANY} if outcome == "failed" else {}) + manager._publish_pending_results() + client.publish_parse_result.assert_called_once() + else: + assert not manager._pending_publications + client.publish_parse_result.assert_not_called() + assert list(manager._file_queue) == ([file] if source_changed else []) + assert manager._file_stats[file].run_count == (0 if outcome == "callback" or source_changed else 1) diff --git a/airflow-core/tests/unit/dag_processing/test_processor.py b/airflow-core/tests/unit/dag_processing/test_processor.py index 6e6707057bba..d40ec9c7d07b 100644 --- a/airflow-core/tests/unit/dag_processing/test_processor.py +++ b/airflow-core/tests/unit/dag_processing/test_processor.py @@ -18,6 +18,7 @@ from __future__ import annotations import inspect +import json import logging import os import pathlib @@ -29,11 +30,12 @@ from collections.abc import Callable, Iterable from socket import socket, socketpair from typing import TYPE_CHECKING, Any, BinaryIO -from unittest.mock import MagicMock, PropertyMock, patch +from unittest.mock import ANY, MagicMock, PropertyMock, patch +import httpx2 import pytest import structlog -from pydantic import TypeAdapter +from pydantic import TypeAdapter, ValidationError from sqlalchemy import select from structlog.typing import FilteringBoundLogger @@ -51,6 +53,7 @@ EmailRequest, TaskCallbackRequest, ) +from airflow.dag_processing.api_client import DagProcessorAPIClient from airflow.dag_processing.dagbag import DagBag from airflow.dag_processing.manager import DagFileProcessorManager, process_parse_results from airflow.dag_processing.processor import ( @@ -87,6 +90,7 @@ TICount, ToSupervisor, ToTask, + VariableResult, XComResult, XComSequenceSliceResult, ) @@ -2445,7 +2449,11 @@ def test_registered_message_types(self): @pytest.mark.parametrize( "message_type", - sorted(set(typing.get_args(typing.get_args(ToManager)[0])) - {DagFileParsingResult}, key=str), + sorted( + set(typing.get_args(typing.get_args(ToManager)[0])) + - {DagFileParsingResult, comms.GetPrevSuccessfulDagRun}, + key=str, + ), ids=lambda message_type: message_type.__name__, ) def test_reuses_shared_request_handlers(self, message_type): @@ -2511,15 +2519,144 @@ def test_dispatch_parsing_result(self, send_msg, proc): send_msg.assert_called_once_with(proc, None, request_id=42, error=None) @patch.object(DagFileProcessorProcess, "send_msg", autospec=True) - def test_previous_successful_run_uses_process_id(self, send_msg, proc): - proc.client.task_instances.get_previous_successful_dagrun.return_value = ( - comms.PrevSuccessfulDagRunResult() - ) + def test_previous_successful_run_is_answered_locally(self, send_msg, proc): proc._handle_request( comms.GetPrevSuccessfulDagRun(ti_id=uuid.uuid4()), structlog.get_logger(), req_id=42 ) - proc.client.task_instances.get_previous_successful_dagrun.assert_called_once_with(proc.id) + assert not proc.client.mock_calls + send_msg.assert_called_once_with( + proc, comms.PrevSuccessfulDagRunResult(), request_id=42, error=None, exclude_unset=True + ) + + @patch.object(supervisor.WatchedSubprocess, "_handle_request", autospec=True) + def test_default_mode_requests_do_not_load_the_api_client(self, handle_request, proc, monkeypatch): + monkeypatch.setitem(sys.modules, "airflow.dag_processing.api_client", None) + msg = GetVariable(key="my_key") + + proc._handle_request(msg, structlog.get_logger(), req_id=42) + + handle_request.assert_called_once_with(proc, msg, ANY, 42) + + @patch.object(DagFileProcessorProcess, "send_msg", autospec=True) + def test_api_client_requests_are_made_for_the_files_bundle( + self, send_msg, proc, tmp_path, make_registration_response, make_parse_token_response + ): + token_file = tmp_path / "processor.jwt" + token_file.write_text("session-token") + parse_response = make_parse_token_response( + sub=str(proc.id), dag_bundles=[proc.bundle_name], relative_fileloc=proc.dag_file_rel_path + ) + parse_token = parse_response.json()["token"] + requests = [] + + def handle(request): + requests.append(request) + if request.url.path.endswith("/jobs"): + return make_registration_response() + if request.url.path.endswith("/parse-token"): + return parse_response + return httpx2.Response(200, json={"key": "my_key", "value": "my_value"}) + + with DagProcessorAPIClient( + base_url="http://api/execution/", + token_file=token_file, + hostname="processor-1", + transport=httpx2.MockTransport(handle), + ) as client: + client.register_job() + proc.client = client + proc._handle_request(GetVariable(key="my_key"), structlog.get_logger(), req_id=42) + proc._handle_request(GetVariable(key="my_key"), structlog.get_logger(), req_id=43) + + assert requests[-1].url.path == "/execution/variables/my_key" + assert requests[-1].headers["Airflow-Dag-Bundle"] == "mybundle" + assert requests[-1].headers["Authorization"] == f"Bearer {parse_token}" + assert json.loads(requests[1].content) == { + "attempt_id": str(proc.id), + "bundle_name": proc.bundle_name, + "relative_fileloc": proc.dag_file_rel_path, + } + assert sum(request.url.path.endswith("/parse-token") for request in requests) == 1 + assert send_msg.call_count == 2 + send_msg.assert_any_call( + proc, + VariableResult(key="my_key", value="my_value"), + request_id=42, + error=None, + exclude_unset=True, + ) + + @pytest.mark.parametrize( + ("variable_response", "expected_error"), + [ + pytest.param( + httpx2.ReadError("Connection reset"), "GetVariable (ReadError)", id="transport-error" + ), + pytest.param(httpx2.Response(503), "GetVariable (HTTP 503)", id="unavailable"), + pytest.param( + httpx2.Response(400, json={"detail": "Bad request"}), "GetVariable (HTTP 400)", id="bad" + ), + pytest.param(httpx2.Response(200, text=""), "GetVariable (ValidationError)", id="not-json"), + pytest.param(httpx2.Response(404, json={"detail": {"reason": "not_found"}}), None, id="missing"), + pytest.param(httpx2.Response(403, json={"detail": {"reason": "denied"}}), None, id="denied"), + ], + ) + @patch.object(DagFileProcessorProcess, "send_msg", autospec=True) + def test_unanswered_api_requests_mark_the_parse( + self, + send_msg, + proc, + tmp_path, + make_registration_response, + make_parse_token_response, + variable_response, + expected_error, + ): + token_file = tmp_path / "processor.jwt" + token_file.write_text("session-token") + parse_response = make_parse_token_response( + sub=str(proc.id), dag_bundles=[proc.bundle_name], relative_fileloc=proc.dag_file_rel_path + ) + + def handle(request): + if request.url.path.endswith("/jobs"): + return make_registration_response() + if request.url.path.endswith("/parse-token"): + return parse_response + if isinstance(variable_response, Exception): + raise variable_response + return variable_response + + with DagProcessorAPIClient( + base_url="http://api/execution/", + token_file=token_file, + hostname="processor-1", + transport=httpx2.MockTransport(handle), + ) as client: + client.register_job() + proc.client = client + if expected_error: + with pytest.raises((httpx2.HTTPError, ValidationError)): + proc._handle_request(GetVariable(key="my_key"), structlog.get_logger(), req_id=42) + send_msg.assert_not_called() + else: + proc._handle_request(GetVariable(key="my_key"), structlog.get_logger(), req_id=42) + send_msg.assert_called_once() + + assert proc.api_request_error == expected_error + + @patch.object(DagFileProcessorProcess, "send_msg", autospec=True) + def test_local_parse_messages_do_not_require_a_token_exchange(self, send_msg, proc, tmp_path): + with DagProcessorAPIClient( + base_url="http://unused/", token_file=tmp_path / "missing-token", hostname="processor-1" + ) as client: + proc.client = client + proc._handle_request( + comms.GetPrevSuccessfulDagRun(ti_id=uuid.uuid4()), structlog.get_logger(), req_id=42 + ) + + assert client.job_id is None send_msg.assert_called_once_with( proc, comms.PrevSuccessfulDagRunResult(), request_id=42, error=None, exclude_unset=True ) diff --git a/airflow-core/tests/unit/dag_processing/test_requested_work.py b/airflow-core/tests/unit/dag_processing/test_requested_work.py new file mode 100644 index 000000000000..8dbbeacd8b71 --- /dev/null +++ b/airflow-core/tests/unit/dag_processing/test_requested_work.py @@ -0,0 +1,141 @@ +# 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 + +from pathlib import Path +from unittest import mock + +import pytest +from uuid6 import uuid7 + +from airflow.api_fastapi.execution_api.datamodels.dag_parsing import DagParseResultBody +from airflow.callbacks.callback_requests import DagCallbackRequest +from airflow.dag_processing.api_client import DagProcessorAPIClient +from airflow.dag_processing.bundles.base import BaseDagBundle +from airflow.dag_processing.manager import DagFileInfo, DagFileProcessorManager, PendingDagPublication +from airflow.dag_processing.processor import DagFileProcessorProcess +from airflow.dag_processing.requested_work import DatabaseRequestedWorkSource, RequestedWorkSource + + +def test_default_source_does_not_claim_or_retain_work(): + source = RequestedWorkSource() + file = DagFileInfo(rel_path=Path("example.py"), bundle_name="test") + request = DagCallbackRequest( + filepath="example.py", + dag_id="example", + run_id="test", + is_failure_callback=False, + bundle_name="test", + bundle_version=None, + ) + attempt_id = uuid7() + + assert ( + source.claim_priority_files( + [], capacity=1, unavailable_bundles=set(), active_attempts=set(), inventory_sequence=1 + ) + == [] + ) + assert source.fetch_callbacks([], limit=1) == [] + source.callbacks_started(attempt_id, [request]) + source.parse_started(file, attempt_id) + source.callback_deferred(request) + source.callback_queued(request) + source.callback_discarded(request) + source.inventory_published("test", sequence=1, files=["example.py"], failed_sources=[]) + source.bundle_unusable("test", active_attempts={attempt_id}) + source.attempt_finished(attempt_id, had_callbacks=False) + source.flush() + + assert not source.requires_acknowledgment + assert not source.has_outstanding_work() + assert not source.has_priority_request(file) + assert not source.has_callback_claim(request) + assert not source.has_callback_attempt(attempt_id) + assert source.is_priority_ready(file, 0) + assert source.is_callback_preparation_ready(request) + + +def test_database_source_delegates_claims_without_applying_api_limits(): + claim_priority = mock.create_autospec(lambda: []) + fetch_callbacks = mock.create_autospec(lambda: []) + source = DatabaseRequestedWorkSource(claim_priority, fetch_callbacks) + + assert ( + source.claim_priority_files( + [], capacity=0, unavailable_bundles={"test"}, active_attempts={uuid7()}, inventory_sequence=2 + ) + is claim_priority.return_value + ) + assert source.fetch_callbacks([], limit=0) is fetch_callbacks.return_value + + claim_priority.assert_called_once_with() + fetch_callbacks.assert_called_once_with() + assert not source.requires_acknowledgment + + +@pytest.mark.parametrize("use_api_client", [False, True]) +def test_manager_uses_injected_source_with_dispatch_context(use_api_client): + source = mock.create_autospec(RequestedWorkSource, instance=True) + client = mock.create_autospec(DagProcessorAPIClient, instance=True) if use_api_client else None + manager = DagFileProcessorManager( + max_runs=1, parallelism=3, max_callbacks_per_loop=5, api_client=client, work_source=source + ) + bundles = [] + for name, initialized in [("ready", True), ("refreshing", True), ("uninitialized", False)]: + bundle = mock.create_autospec(BaseDagBundle, instance=True) + bundle.name = name + bundle.is_initialized = initialized + bundles.append(bundle) + manager._dag_bundles = bundles + manager._bundles_needing_refresh = {"refreshing"} + manager._bundles_waiting_for_refresh = {"ready"} + manager._dispatch_sequence = 7 + file = DagFileInfo(rel_path=Path("running.py"), bundle_name="ready") + processor = mock.create_autospec(DagFileProcessorProcess, instance=True) + processor.id = uuid7() + manager._processors[file] = processor + pending = mock.create_autospec(PendingDagPublication, instance=True) + pending.body = mock.create_autospec(DagParseResultBody, instance=True) + pending.body.attempt_id = uuid7() + manager._pending_publications[file] = pending + + assert manager.claim_priority_files() is source.claim_priority_files.return_value + assert manager.fetch_callbacks() is source.fetch_callbacks.return_value + + source.claim_priority_files.assert_called_once_with( + bundles, + capacity=3, + unavailable_bundles={"refreshing", "uninitialized"}, + active_attempts={processor.id, pending.body.attempt_id}, + inventory_sequence=8, + ) + source.fetch_callbacks.assert_called_once_with(bundles, limit=5) + + +@mock.patch.object(DagFileProcessorManager, "_claim_priority_files", autospec=True) +@mock.patch.object(DagFileProcessorManager, "_fetch_callbacks_from_db", autospec=True) +def test_manager_defaults_to_database_source(fetch_callbacks, claim_priority): + manager = DagFileProcessorManager(max_runs=1) + + assert isinstance(manager.work_source, DatabaseRequestedWorkSource) + assert manager.claim_priority_files() is claim_priority.return_value + assert manager.fetch_callbacks() is fetch_callbacks.return_value + + claim_priority.assert_called_once_with(manager) + fetch_callbacks.assert_called_once_with(manager) diff --git a/generated/known_sdk_imports_in_core.txt b/generated/known_sdk_imports_in_core.txt index 920b73e44784..70312a40de01 100644 --- a/generated/known_sdk_imports_in_core.txt +++ b/generated/known_sdk_imports_in_core.txt @@ -7,7 +7,7 @@ airflow-core/src/airflow/dag_processing/api_client.py::3 airflow-core/src/airflow/dag_processing/dagbag.py::3 airflow-core/src/airflow/dag_processing/importer_routing.py::1 airflow-core/src/airflow/dag_processing/lang_sdk_processor.py::6 -airflow-core/src/airflow/dag_processing/manager.py::5 +airflow-core/src/airflow/dag_processing/manager.py::6 airflow-core/src/airflow/dag_processing/processor.py::14 airflow-core/src/airflow/exceptions.py::1 airflow-core/src/airflow/executors/base_executor.py::3 diff --git a/task-sdk/src/airflow/sdk/execution_time/cache.py b/task-sdk/src/airflow/sdk/execution_time/cache.py index 0c220fd795cf..1d1910bf93f6 100644 --- a/task-sdk/src/airflow/sdk/execution_time/cache.py +++ b/task-sdk/src/airflow/sdk/execution_time/cache.py @@ -97,7 +97,7 @@ def init(cls): @classmethod def reset(cls): - """Use for test purposes only.""" + """Detach this process from the shared cache, including entries inherited across a fork.""" cls._cache = None @classmethod