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


##########
airflow-core/src/airflow/dag_processing/manager.py:
##########
@@ -2277,12 +2421,14 @@ def _create_process(
             )
 
         return DagFileProcessorProcess.start(
-            id=id,
+            id=process_id,
             path=dag_file.absolute_path,
             bundle_path=cast("Path", dag_file.bundle_path),
             bundle_name=dag_file.bundle_name,
             dag_file_rel_path=str(dag_file.rel_path),
             callbacks=callback_to_execute_for_file,
+            callbacks_require_ack=self.api_client is not None,

Review Comment:
   This can come from the work source and doesn't become another mode check.



##########
airflow-core/src/airflow/dag_processing/manager.py:
##########
@@ -956,46 +977,84 @@ def prepare_callback_bundle(self, request: 
CallbackRequest) -> BaseDagBundle | N
                 )
                 if bundle.supports_versioning:
                     bundle.initialize()
-            except Exception:
-                self.log.exception(
-                    "Error preparing bundle %s version %s for callback, 
skipping",
-                    request.bundle_name,
-                    request.bundle_version,
-                )
+            except Exception as error:
+                if self.api_client is not None:
+                    # 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
+
+                    if isinstance(error, DagProcessorRegistrationRetired):
+                        raise
+                    if self.api_client.restart_required:
+                        raise DagProcessorRegistrationRetired(
+                            "The Dag processor registration has ended; restart 
required"
+                        ) from error

Review Comment:
   Could `DagProcessorAPIClient` raise `DagProcessorRegistrationRetired` itself 
once `restart_required` is set, so this can just let it propagate? The same 
applies to the `api_client.restart_required` check in `end()`, which could live 
in `ExecutionAPIWorkSource.flush`.



##########
airflow-core/src/airflow/dag_processing/api_requested_work.py:
##########
@@ -0,0 +1,388 @@
+# 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.
+"""Claim and acknowledgment lifecycle for Dag processor work from the 
Execution API."""
+
+from __future__ import annotations
+
+import time
+from collections import Counter
+from pathlib import Path
+from typing import TYPE_CHECKING, Literal
+
+import attrs
+import httpx2
+
+from airflow.configuration import conf
+from airflow.dag_processing.collection import is_source_discovery_failed
+from airflow.dag_processing.requested_work import RequestedWorkSource, 
get_callback_target
+from airflow.utils.file import find_enclosing_file
+from airflow.utils.log.logging_mixin import LoggingMixin
+
+if TYPE_CHECKING:
+    from collections.abc import Collection
+    from uuid import UUID
+
+    from airflow.api_fastapi.execution_api.datamodels.dag_parsing import 
ProcessorWorkItem
+    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.dag_processing.manager import DagFileInfo
+
+_API_SEND_BUDGET_SECONDS = 1.0

Review Comment:
   This already exists in `dag_processing/manager.py`. Should it be imported 
instead?



##########
airflow-core/src/airflow/dag_processing/manager.py:
##########
@@ -2027,10 +2137,17 @@ def _build_rejection_report(
         stat: DagFileStat,
         refresh_generation: int,
         reason: str,
+        rejected_attempt_id: UUID | None = None,
         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."""
+        """
+        Report a failed parse or an unpublishable result as an import error 
users can see.
+
+        :param rejected_attempt_id: The import whose unpublishable result is 
replaced and claims released.
+        """
+        if rejected_attempt_id is not None:
+            self.work_source.attempt_finished(rejected_attempt_id, 
had_callbacks=False)

Review Comment:
   A builder now releases claims as a side effect. Both callers that pass 
`rejected_attempt_id` could call `self.work_source.attempt_finished(...)` 
themselves and keep this method pure.



##########
airflow-core/src/airflow/dag_processing/manager.py:
##########
@@ -956,46 +977,84 @@ def prepare_callback_bundle(self, request: 
CallbackRequest) -> BaseDagBundle | N
                 )
                 if bundle.supports_versioning:
                     bundle.initialize()
-            except Exception:
-                self.log.exception(
-                    "Error preparing bundle %s version %s for callback, 
skipping",
-                    request.bundle_name,
-                    request.bundle_version,
-                )
+            except Exception as error:
+                if self.api_client is not None:
+                    # 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
+
+                    if isinstance(error, DagProcessorRegistrationRetired):
+                        raise
+                    if self.api_client.restart_required:
+                        raise DagProcessorRegistrationRetired(
+                            "The Dag processor registration has ended; restart 
required"
+                        ) from error
+                if self.work_source.has_callback_claim(request):
+                    self.log.warning(
+                        "Unable to prepare callback bundle; retrying",
+                        bundle_name=request.bundle_name,
+                        bundle_version=request.bundle_version,
+                        target=get_callback_target(request),
+                        error=str(error),
+                    )
+                else:
+                    self.log.exception(
+                        "Error preparing bundle %s version %s for callback, 
skipping",
+                        request.bundle_name,
+                        request.bundle_version,
+                    )
                 return None
         return bundle
 
-    def _add_callback_to_queue(self, request: CallbackRequest) -> None:
+    def _add_callbacks_to_queue(self, callbacks: Iterable[CallbackRequest]) -> 
None:
+        prepared_bundles: dict[str, BaseDagBundle | None] = {}
+        for request in callbacks:
+            self._add_callback_to_queue(request, 
prepared_bundles=prepared_bundles)
+
+    def _add_callback_to_queue(
+        self,
+        request: CallbackRequest,
+        *,
+        prepared_bundles: dict[str, BaseDagBundle | None] | None = None,

Review Comment:
   The only caller always passes `prepared_bundles`, so the None branch is dead.



##########
airflow-core/src/airflow/dag_processing/manager.py:
##########
@@ -1378,6 +1471,7 @@ def _refresh_dag_bundles(self, known_files: dict[str, 
set[DagFileInfo]]):
                 if self.api_client is not None:
                     discovery = self._filter_api_discovery_result(bundle.name, 
discovery)
                 found_files = discovery.files
+

Review Comment:
   ```suggestion
   ```
   
   Same, line added without reasonable benefit.



##########
airflow-core/src/airflow/dag_processing/processor.py:
##########
@@ -103,6 +103,14 @@
     from airflow.sdk.execution_time.supervisor import RequestHandler, 
RequestResult, ResponseSent
     from airflow.typing_compat import Self
 
+_CALLBACK_TARGETS_MISSING_EXIT_CODE = 75
+"""
+Exit status of a callback process that ran no callback because none of their 
Dags or tasks loaded after an
+Execution API request failed.
+
+The supervisor logs every non-zero exit as abnormal, so a Dag that was removed 
still exits with status 0.
+"""
+

Review Comment:
   Should this just use `os.EX_TEMPFAIL`?



##########
airflow-core/src/airflow/dag_processing/api_requested_work.py:
##########
@@ -0,0 +1,388 @@
+# 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.
+"""Claim and acknowledgment lifecycle for Dag processor work from the 
Execution API."""
+
+from __future__ import annotations
+
+import time
+from collections import Counter
+from pathlib import Path
+from typing import TYPE_CHECKING, Literal
+
+import attrs
+import httpx2
+
+from airflow.configuration import conf
+from airflow.dag_processing.collection import is_source_discovery_failed
+from airflow.dag_processing.requested_work import RequestedWorkSource, 
get_callback_target
+from airflow.utils.file import find_enclosing_file
+from airflow.utils.log.logging_mixin import LoggingMixin
+
+if TYPE_CHECKING:
+    from collections.abc import Collection
+    from uuid import UUID
+
+    from airflow.api_fastapi.execution_api.datamodels.dag_parsing import 
ProcessorWorkItem
+    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.dag_processing.manager import DagFileInfo
+
+_API_SEND_BUDGET_SECONDS = 1.0
+_MAX_CALLBACK_RETRY_DELAY = 60.0
+
+
+def get_status_code(error: httpx2.HTTPError) -> int | None:
+    return error.response.status_code if isinstance(error, 
httpx2.HTTPStatusError) else None
+
+
[email protected]
+class DeferredCallback:
+    """A claimed callback that could not be prepared or run, retried until it 
expires."""
+
+    expires_at: float
+    attempts: int = 0
+    next_attempt_time: float = 0.0
+
+
[email protected]
+class PriorityParseClaim:
+    """A priority request served only after an inventory captured following 
the claim."""
+
+    work: ProcessorWorkItem
+    inventory_sequence: int
+    attempt_id: UUID | None = None
+
+
[email protected]
+class ExecutionAPIWorkSource(RequestedWorkSource, LoggingMixin):
+    """Retain claimed work until its terminal outcome can be acknowledged by 
the API."""
+
+    client: DagProcessorAPIClient
+    _callback_claims: dict[int, ProcessorWorkItem] = attrs.field(factory=dict, 
init=False)
+    _deferred_api_callbacks: list[CallbackRequest] = attrs.field(factory=list, 
init=False)
+    _deferred_callback_retries: dict[int, DeferredCallback] = 
attrs.field(factory=dict, init=False)
+    _interrupted_callback_retries: dict[str, DeferredCallback] = 
attrs.field(factory=dict, init=False)
+    """Retries of callbacks an API failure interrupted, by work ID, so later 
attempts share one expiry."""
+    _callback_attempts: dict[UUID, list[ProcessorWorkItem]] = 
attrs.field(factory=dict, init=False)
+    _priority_claims: dict[tuple[str, UUID], PriorityParseClaim] = 
attrs.field(factory=dict, init=False)
+    _pending_work_acks: list[tuple[Literal["callbacks", "priority"], 
ProcessorWorkItem]] = attrs.field(
+        factory=list, init=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 files within the capacity left by active and 
retained work."""
+        # Manager imports stay local: the manager imports this module.
+        from airflow.dag_processing.manager import DagFileInfo
+
+        bundles_by_name = {bundle.name: bundle for bundle in bundles}
+        unavailable = set(unavailable_bundles)
+        available = (
+            capacity
+            - sum(
+                claim.attempt_id in active_attempts or claim.work.bundle_name 
not in unavailable
+                for claim in self._priority_claims.values()
+            )
+            - sum(kind == "priority" for kind, _ in self._pending_work_acks)
+        )
+        if available <= 0:
+            return []
+        # Retain failed-bundle claims for recovery without letting them 
consume healthy bundles' capacity.
+        # Excluding those bundles from new claims also bounds the suspended 
backlog.
+        eligible_bundles = [name for name in bundles_by_name if name not in 
unavailable]
+        try:
+            work = self.client.claim_work("priority", eligible_bundles, 
available)
+        except httpx2.HTTPError as error:
+            self.log.warning(
+                "Unable to claim priority parses; retrying on a later loop",
+                error_type=type(error).__name__,
+                status_code=get_status_code(error),
+            )
+            return []
+        files = []
+        for item in work:
+            self._priority_claims[item.id, item.claim_id] = PriorityParseClaim(
+                work=item, inventory_sequence=inventory_sequence
+            )
+            bundle = bundles_by_name[item.bundle_name]
+            try:
+                path = find_enclosing_file(bundle.path / item.relative_fileloc)
+            except OSError as error:
+                # The next inventory acknowledges the claim if the bundle 
listing cannot see the file either.
+                self.log.warning(
+                    "Unable to resolve priority parse %s in bundle %s: %s",
+                    item.relative_fileloc,
+                    bundle.name,
+                    error,
+                )
+                path = None
+            files.append(
+                DagFileInfo(
+                    rel_path=path.relative_to(bundle.path) if path else 
Path(item.relative_fileloc),
+                    bundle_name=bundle.name,
+                    bundle_path=bundle.path,
+                )
+            )
+        return files
+
+    def fetch_callbacks(self, bundles: Collection[BaseDagBundle], *, limit: 
int) -> list[CallbackRequest]:
+        """Claim callbacks for ready bundles and include requests awaiting 
bundle preparation."""
+        # Callbacks waiting for a retry take no capacity from other bundles. 
Their bundle stops claiming
+        # only once it holds a full batch, so one unavailable version does not 
block the rest.
+        deferred = Counter(
+            request.bundle_name
+            for request in self._deferred_api_callbacks
+            if id(request) in self._deferred_callback_retries
+        )
+        available = (
+            limit
+            - (len(self._callback_claims) - deferred.total())
+            - sum(len(work) for work in self._callback_attempts.values())
+            - sum(kind == "callbacks" for kind, _ in self._pending_work_acks)
+        )
+        if available <= 0:
+            return list(self._deferred_api_callbacks)
+        eligible_bundles = [
+            b.name
+            for b in bundles
+            if (not b.supports_versioning or b.is_initialized) and 
deferred[b.name] < limit
+        ]
+        try:
+            work = self.client.claim_work("callbacks", eligible_bundles, 
available)
+        except httpx2.HTTPError as error:
+            self.log.warning(
+                "Unable to claim callbacks; retrying on a later loop",
+                error_type=type(error).__name__,
+                status_code=get_status_code(error),
+            )
+            return list(self._deferred_api_callbacks)
+        for item in work:
+            self._retain_callback_claim(item)
+        return list(self._deferred_api_callbacks)
+
+    def _retain_callback_claim(self, item: ProcessorWorkItem) -> 
CallbackRequest:
+        if item.callback is None:
+            raise ValueError("Callback claim returned no request")

Review Comment:
   One malformed item from the server crashes the whole manager here. Could 
this log the item and acknowledge it instead?



##########
airflow-core/src/airflow/jobs/dag_processor_job_runner.py:
##########
@@ -49,12 +64,130 @@ def __init__(
     ):
         super().__init__(job)
         self.processor = processor
+        self._last_api_heartbeat = 0.0
+        self._next_api_heartbeat = 0.0
         self.processor.heartbeat = lambda: perform_heartbeat(
             job=self.job,
             heartbeat_callback=self.heartbeat_callback,
             only_if_necessary=True,
         )
 
+    def run_with_api(self, client: DagProcessorAPIClient) -> int | None:
+        """Mirror ``run_job`` metrics and listener ordering while the API owns 
Job persistence."""
+        get_job_heartbeat_timeout()

Review Comment:
   The validated value is discarded, and then `job_heartbeat_timeout` is 
re-read below without validation. Could this store the result and use it in 
both places?



##########
airflow-core/src/airflow/dag_processing/processor.py:
##########
@@ -703,12 +750,16 @@ def _handle_previous_successful_dag_run(
         **dict(
             [
                 register_request_method(DagFileParsingResult, 
_handle_parsing_result),
+                register_request_method(DagCallbacksStarted, 
_handle_callbacks_started),
                 register_request_method(GetPrevSuccessfulDagRun, 
_handle_previous_successful_dag_run),
             ]
         ),
     }
 
     def _handle_request(self, msg, log: FilteringBoundLogger, req_id: int) -> 
None:
+        if isinstance(msg, DagCallbacksStarted):
+            super()._handle_request(msg, log, req_id)
+            return

Review Comment:
   Manager-answered messages can be declared once instead e.g. 
`_local_request_types: ClassVar = (DagCallbacksStarted,)` next to 
`_client_request_types`, so the next one doesn't need its own `isinstance` 
branch.



##########
airflow-core/src/airflow/cli/commands/dag_processor_command.py:
##########
@@ -71,29 +106,75 @@ def _create_dag_processor_job_runner(args: Any) -> 
DagProcessorJobRunner:
 
 
 @enable_memray_trace(component=MemrayTraceComponents.dag_processor)
-def _run_dag_processor_job(job_runner: DagProcessorJobRunner) -> None:
-    run_job(job=job_runner.job, execute_callable=job_runner._execute)
+def _run_dag_processor_job(args: Any) -> None:
+    # Construct the manager and its connection pool after the daemon or 
hot-reload fork.
+    with _create_dag_processor_job_runner(args) as job_runner:
+        if (client := job_runner.processor.api_client) is None:
+            run_job(job=job_runner.job, execute_callable=job_runner._execute)
+        else:
+            job_runner.run_with_api(client)
+
+
+def _get_execution_api_token_file() -> str:
+    token_file = conf.get("dag_processor", "execution_api_token_file", 
fallback=None)
+    if not token_file:
+        raise AirflowConfigException(
+            "[dag_processor] use_execution_api requires a credential: 
configure execution_api_token_file"
+        )
+    return token_file
 
 
-@cli_utils.action_cli
 @providers_configuration_loaded
 def dag_processor(args):
     """Start Airflow Dag Processor Job."""
-    set_component_mp_start_method("dag_processor")
-    job_runner = _create_dag_processor_job_runner(args)
+    if getattr(args, "check_health", False) or getattr(args, "check_ready", 
False):

Review Comment:
   `cli_config` always defines these attributes so I don’t think `getattr` is 
needed here?



##########
airflow-core/src/airflow/dag_processing/api_client.py:
##########
@@ -438,6 +443,44 @@ def get_bundles(self, *, retry: bool = False) -> 
list[DagBundleStateResponse]:
         )
         return [DagBundleStateResponse.model_validate(item) for item in 
response.json()]
 
+    def claim_work(
+        self, kind: Literal["callbacks", "priority"], bundle_names: list[str], 
limit: int
+    ) -> list[ProcessorWorkItem]:
+        if not bundle_names:
+            return []
+        body = self._pending_claims.setdefault(
+            kind,
+            ProcessorWorkClaimBody(
+                claim_id=uuid7(),
+                claim_sequence=self._claim_sequences.get(kind, 0) + 1,
+                bundle_names=bundle_names,
+                limit=min(limit, 100),

Review Comment:
   The 100 duplicates ProcessorWorkClaimBody’s `le=100`. Probably better to 
centrailize the logic onto the class, or at least share a constant?



##########
airflow-core/src/airflow/config_templates/config.yml:
##########
@@ -3314,6 +3314,44 @@ dag_processor:
          - how often to refresh DAGs from those sources
          - how many files to parse concurrently
   options:
+    use_execution_api:
+      description: |
+        When enabled,
+        ``airflow dag-processor`` uses the authenticated Execution API for its 
Job lifecycle,
+        bundle metadata and secrets, parse-time requests, result publication, 
and callback
+        and priority-request delivery. The API URL comes from
+        ``[core] execution_api_server_url``. Configure credentials separately 
using
+        ``[dag_processor] execution_api_token_file``.
+
+        Provision the bundle catalog on a trusted host before starting the 
processor.
+        The processor does not need metadata database credentials, the Fernet 
key, or
+        API signing keys. Remove those credentials from its deployment and 
block database
+        network access to enforce isolation; enabling this option does not 
remove them.
+        When disabled, use the in-process API and database-backed Job 
lifecycle.
+      version_added: 3.5.0
+      type: boolean
+      default: "False"
+      example: ~
+    execution_api_token_file:
+      description: |
+        Path to a session token written by ``airflow dag-processor-token``. 
Each processor
+        needs its own session token. This is the credential source for 
processors with
+        ``[dag_processor] use_execution_api`` enabled; setting a token file 
does not enable
+        API mode. The file is reread periodically to detect externally rotated 
session tokens
+        and when renewing the separate Job credential.
+      version_added: 3.5.0
+      type: string
+      default: ~
+      example: "/run/airflow/dag-processor.jwt"
+    health_check_file:
+      description: |
+        Local heartbeat file written by a Dag processor using the Execution 
API.
+        Use a separate writable file for each processor. ``airflow 
dag-processor --check-health``
+        checks its loop heartbeat; ``--check-ready`` also checks the last 
successful API heartbeat.
+      version_added: 3.5.0
+      type: string
+      default: "{AIRFLOW_HOME}/dag_processor_health.json"
+      example: ~

Review Comment:
   The description says to use a separate file per processor, but the default 
is shared by every processor on one `AIRFLOW_HOME`. Could the default include 
something per-processor, or the description say explicitly that the default is 
unsafe with more than one processor?



##########
airflow-core/src/airflow/cli/commands/dag_processor_command.py:
##########
@@ -71,29 +106,75 @@ def _create_dag_processor_job_runner(args: Any) -> 
DagProcessorJobRunner:
 
 
 @enable_memray_trace(component=MemrayTraceComponents.dag_processor)
-def _run_dag_processor_job(job_runner: DagProcessorJobRunner) -> None:
-    run_job(job=job_runner.job, execute_callable=job_runner._execute)
+def _run_dag_processor_job(args: Any) -> None:
+    # Construct the manager and its connection pool after the daemon or 
hot-reload fork.
+    with _create_dag_processor_job_runner(args) as job_runner:
+        if (client := job_runner.processor.api_client) is None:
+            run_job(job=job_runner.job, execute_callable=job_runner._execute)
+        else:
+            job_runner.run_with_api(client)
+
+
+def _get_execution_api_token_file() -> str:
+    token_file = conf.get("dag_processor", "execution_api_token_file", 
fallback=None)
+    if not token_file:
+        raise AirflowConfigException(
+            "[dag_processor] use_execution_api requires a credential: 
configure execution_api_token_file"
+        )
+    return token_file
 
 
-@cli_utils.action_cli
 @providers_configuration_loaded
 def dag_processor(args):
     """Start Airflow Dag Processor Job."""
-    set_component_mp_start_method("dag_processor")
-    job_runner = _create_dag_processor_job_runner(args)
+    if getattr(args, "check_health", False) or getattr(args, "check_ready", 
False):
+        if not conf.getboolean("dag_processor", "use_execution_api"):
+            raise SystemExit("Local health probes require Dag processor API 
mode")
+        return check_processor_health(readiness=getattr(args, "check_ready", 
False))
+    if not conf.getboolean("dag_processor", "use_execution_api"):
+        return _run_with_action_log(_start_dag_processor, args)
+    _get_execution_api_token_file()
+    if getattr(args, "verbose", False):
+        cli_utils.set_verbose_logging()
+    return _start_dag_processor(args)
+
+
+def _run_with_action_log(func: Callable[[Any], Any], args: Any) -> Any:
+    # The action log names its event after the decorated function; keep the 
command's own name.
+    def dag_processor(args):
+        return func(args)
 
+    return cli_utils.action_cli(dag_processor)(args)

Review Comment:
   Defining an inner function named `dag_processor` so that `action_cli` logs 
the right event name is fragile. Could `action_cli` accept an explicit event 
name instead?



##########
airflow-core/src/airflow/cli/commands/dag_processor_command.py:
##########
@@ -19,19 +19,30 @@
 from __future__ import annotations
 
 import logging
-from typing import Any
+from contextlib import contextmanager
+from typing import TYPE_CHECKING, Any
 
 from airflow.cli.commands.daemon_utils import run_command_with_daemon_option
 from airflow.configuration import conf
-from airflow.dag_processing.bundles.manager import 
get_configured_bundle_team_names
+from airflow.dag_processing.bundles.manager import (
+    _load_bundle_config_snapshot,

Review Comment:
   Could `bundles.manager` expose a public helper for the configured bundle 
names, used by `validate_dag_bundle_arg` in both modes?



##########
airflow-core/src/airflow/dag_processing/manager.py:
##########
@@ -1077,11 +1136,28 @@ def _publish_bundle_inventory(self, bundle_name: str, 
known_files: dict[str, set
         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
+            pending.source,
+            bundle_revision=receipt.revision,
+            inventory_sequence=pending.body.dispatch_sequence,
         )
         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
+        self._bundle_failed_sources[bundle_name] = 
frozenset(pending.body.failed_sources)

Review Comment:
   This is just line swap (probably leftover from multiple implementation 
iterations). Can be reverted to keep diff small. Nit.



##########
airflow-core/src/airflow/dag_processing/api_client.py:
##########
@@ -438,6 +443,44 @@ def get_bundles(self, *, retry: bool = False) -> 
list[DagBundleStateResponse]:
         )
         return [DagBundleStateResponse.model_validate(item) for item in 
response.json()]
 
+    def claim_work(
+        self, kind: Literal["callbacks", "priority"], bundle_names: list[str], 
limit: int
+    ) -> list[ProcessorWorkItem]:
+        if not bundle_names:
+            return []
+        body = self._pending_claims.setdefault(

Review Comment:
   A replay after a failed claim reuses the first body's `bundle_names` and 
`limit`, even if the caller now passes different ones. A short comment that 
this is intentional for idempotent replay would help.



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

To unsubscribe, e-mail: [email protected]

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

Reply via email to