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


##########
task-sdk/src/airflow/sdk/execution_time/coordinator.py:
##########
@@ -401,9 +405,16 @@ def extra_for_queue(self, queue: str) -> dict[str, Any] | 
None:
 
 
 @functools.cache
-def get_coordinator_manager() -> CoordinatorManager:
+def get_coordinator_manager(*, validate_handler_bundles: bool = True) -> 
CoordinatorManager:
     """Return the process-wide :class:`CoordinatorManager`, loaded from config 
on first use."""
-    return CoordinatorManager.from_config()
+    return 
CoordinatorManager.from_config(validate_handler_bundles=validate_handler_bundles)
+
+
+def _get_coordinator_manager_for_parsing() -> CoordinatorManager:
+    if _get_bundle_config_source().checks_bundle_names_when_parsing:
+        # Called without arguments to share the cached manager with every 
other caller.
+        return get_coordinator_manager()
+    return get_coordinator_manager(validate_handler_bundles=False)

Review Comment:
   I'd keep the eager check used previously, but let the source decide how to 
do it. Something like this in `from_config`
   
   ```python
   
   if (bundle_name := spec.kwargs.get("task_handler_bundle_name")) is None:
       continue
   if isinstance(bundle_name, str) and 
get_bundle_config_source().is_handler_bundle_valid(bundle_name):
       continue
   raise InvalidCoordinatorError(...)
   ```
   
   
   This way, we don’t need this new function, but can just call 
`get_coordinator_manager` everywhere without `validate_handler_bundles`.
   
   (It’s also awkward this function name has an underscore prefix, but this is 
moot if we rewrite to eliminate the flag and the function.)



##########
shared/configuration/src/airflow_shared/configuration/parser.py:
##########
@@ -237,6 +244,40 @@ def create_provider_cfg_config_fallback_defaults(
     return config_parser
 
 
+def get_dynamic_option_reader(
+    parser: AirflowConfigParser, section: str, key: str
+) -> Callable[[], str | None] | None:
+    """
+    Select the configured command or secret for a canonical, unaliased option 
without reading it.
+
+    A selected reader returns its own result, including an empty or missing 
value. Reload callers
+    must distinguish a failed read from the defaults that ``get()`` could 
otherwise return. Read
+    errors are safe to log: a failed command reports only its exit status, and 
secrets backend
+    errors are not included.
+    """
+
+    def read_secret(path: str) -> str | None:
+        try:
+            return parser._get_config_value_from_secret_backend(path)
+        except Exception:
+            raise AirflowConfigException("Could not read the value from the 
secrets backend") from None
+
+    env_var = parser._env_var_name(section, key)
+    if env_var in os.environ or (section, key) not in 
parser.sensitive_config_values:
+        return None
+    if (command := os.environ.get(f"{env_var}_CMD")) is not None:
+        return lambda: run_command(command, redact=True)
+    if (secret := os.environ.get(f"{env_var}_SECRET")) is not None:
+        return lambda: read_secret(secret)
+    if ConfigParser.has_option(parser, section, key):
+        return None
+    if ConfigParser.has_option(parser, section, f"{key}_cmd"):
+        return lambda: run_command(ConfigParser.get(parser, section, 
f"{key}_cmd"), redact=True)
+    if ConfigParser.has_option(parser, section, f"{key}_secret"):
+        return lambda: read_secret(ConfigParser.get(parser, section, 
f"{key}_secret"))
+    return None

Review Comment:
   This is too similar to `_get_env_var_option` and stuff implemented for 
`get()` calls. Refactor please.



##########
airflow-core/src/airflow/dag_processing/manager.py:
##########
@@ -608,8 +649,19 @@ def _scan_stale_dags(self):
                 if stat.last_finish_time
             }
             self.deactivate_stale_dags(last_parsed=last_parsed)
+            self._bundle_lifecycle.cleanup()
             self._last_deactivate_stale_dags_time = time.monotonic()
 
+    @provide_session
+    def _clear_inactive_bundle_import_errors(self, *, session: Session = 
NEW_SESSION) -> None:
+        inactive_bundles = 
select(DagBundleModel.name).where(DagBundleModel.active.is_(False))
+        inactive_error = ParseImportError.bundle_name.in_(inactive_bundles)
+        ids = session.scalars(
+            
select(ParseImportError.id).where(inactive_error).order_by(ParseImportError.id).limit(500)
+        ).all()
+        if ids:
+            
session.execute(delete(ParseImportError).where(ParseImportError.id.in_(ids), 
inactive_error))

Review Comment:
   This sweep exists to repair a race after it happens, but I think we can 
prevent the late write instead.
   
   When a parse result's import errors are written, check DagBundleModel first, 
and skip the errors if the bundle is inactive. Take the row with 
`with_for_update(key_share=True)`. Deactivation updates the same row, so a late 
writer either commits first, or waits and then sees the bundle is inactive.
   This way, we keep the one-off delete at deactivation as on main.



##########
airflow-core/src/airflow/dag_processing/bundles/manager.py:
##########
@@ -113,35 +127,327 @@ def _bundle_item_exc(msg):
 class _BundleConfigSnapshot(NamedTuple):
     """The configured Dag bundles, as names only and as full configs."""
 
-    configs: tuple[_ExternalBundleConfig, ...]
+    configs: dict[str, _ExternalBundleConfig]
     names: frozenset[str]
+    team_names: dict[str, str | None]
+
+
+def _find_changed_bundle(adopted: _BundleConfigSnapshot, candidate: 
_BundleConfigSnapshot) -> str | None:
+    if candidate is adopted:
+        return None
+    return next(
+        (
+            name
+            for name in adopted.configs.keys() & candidate.configs.keys()
+            if adopted.configs[name] != candidate.configs[name]
+        ),
+        None,
+    )
 
 
[email protected]
-def _load_bundle_config_snapshot() -> _BundleConfigSnapshot:
-    """Read and validate the configured Dag bundles, without importing their 
classes."""
-    bundle_config_list = _read_bundle_config_list()
-    if not bundle_config_list:
-        return _BundleConfigSnapshot(configs=(), names=frozenset())
-    if conf.getboolean("core", "LOAD_EXAMPLES"):
+def _bundle_definition_changed(name: str) -> AirflowConfigException:
+    return _bundle_item_exc(
+        f"Configuration for bundle '{name}' has changed. Rejecting the entire "
+        "configuration list and keeping the last accepted list. "
+        "Revert this entry or use a new bundle name."
+    )
+
+
+def _create_bundle_config_snapshot(bundle_config_list: 
list[_ExternalBundleConfig]) -> _BundleConfigSnapshot:
+    """Validate the configured Dag bundles, without importing their classes."""
+    team_names = {cfg.name: cfg.team_name for cfg in bundle_config_list}
+    if bundle_config_list and conf.getboolean("core", "LOAD_EXAMPLES"):
         _add_example_dag_bundle(bundle_config_list)
         _add_provider_example_dags_to_bundle(bundle_config_list)
     return _BundleConfigSnapshot(
-        configs=tuple(bundle_config_list),
+        configs={cfg.name: cfg for cfg in bundle_config_list},
         names=frozenset(cfg.name for cfg in bundle_config_list),
+        team_names=team_names,
+    )
+
+
+def _build_internal_bundle_config(config: _ExternalBundleConfig) -> 
_InternalBundleConfig:
+    if config.team_name and not conf.getboolean("core", "multi_team"):
+        raise AirflowConfigException(
+            "Section `dag_processor` key `dag_bundle_config_list` "
+            "cannot have a team name when multi-team mode is disabled."
+            "To enable multi-team, you need to update section `core` key 
`multi_team` in your config."
+        )
+    return _InternalBundleConfig(
+        bundle_class=import_string(config.classpath),
+        kwargs=config.kwargs,
+        team_name=config.team_name,
+        importers=config.importers,
     )
 
 
+class _BaseBundleLifecycle:
+    """How a Dag processor keeps its bundles in step with the bundle 
configuration source."""
+
+    def __init__(self, processor: DagFileProcessorManager) -> None:
+        self.processor = processor
+
+    def check_supported(self) -> None:
+        """Raise if the processor cannot run with this source."""
+
+    def reconcile(self, known_files: dict[str, set[DagFileInfo]]) -> None:
+        """Apply bundle additions and removals to the processor and the 
database."""
+
+    def cleanup(self) -> None:
+        """Remove state left behind by removed bundles; run after the 
stale-Dag scan."""
+
+    def remove_stale_bundle_versions(self) -> None:
+        """Remove stale local versions of the bundles this processor may clean 
up."""
+        manager = BundleUsageTrackingManager()
+        for bundle in self.processor._dag_bundles:
+            if bundle.supports_versioning:
+                manager.remove_stale_bundle_versions_for_bundle(bundle.name)
+
+
+class _StaticBundleLifecycle(_BaseBundleLifecycle):
+    """The bundle list is fixed for the lifetime of the processor."""
+
+    def remove_stale_bundle_versions(self) -> None:
+        if self.processor.api_client is None:
+            BundleUsageTrackingManager().remove_stale_bundle_versions()
+        else:
+            super().remove_stale_bundle_versions()
+
+
+class _ReloadingBundleLifecycle(_BaseBundleLifecycle):
+    """The processor adds and removes bundles as the configured command or 
secret changes."""
+
+    def check_supported(self) -> None:
+        if self.processor.api_client is not None:
+            raise AirflowConfigException(
+                "Reloading dag_bundle_config_list through a command or secret 
is not supported "
+                "with an HTTP-backed Dag processor. Use a literal bundle 
configuration or a "
+                "database-backed Dag processor."
+            )
+
+    def reconcile(self, known_files: dict[str, set[DagFileInfo]]) -> None:
+        self.processor._reconcile_bundles(known_files)
+
+    def cleanup(self) -> None:
+        # A processor that has not seen a removal yet can write import errors 
after deactivation.
+        if not self.processor.bundle_names_to_parse:
+            self.processor._clear_inactive_bundle_import_errors()
+
+
+class _BaseBundleConfigSource(ABC):
+    """The bundle configuration of this process, chosen once per process."""
+
+    lifecycle_class: ClassVar[type[_BaseBundleLifecycle]]
+
+    checks_bundle_names_when_parsing: ClassVar[bool]
+    """Whether a parsing process may validate bundle names by reading this 
source itself."""
+
+    @abstractmethod
+    def current(self) -> _BundleConfigSnapshot:
+        """Return the accepted list, which is checked without importing bundle 
classes."""
+
+    @abstractmethod
+    def loadable(self) -> _BundleConfigSnapshot:
+        """Return the newest accepted list whose bundle classes load in this 
process."""
+
+    @abstractmethod
+    def refresh(self, adopted: _BundleConfigSnapshot | None = None) -> None:
+        """
+        Read the list again if the check interval has passed.
+
+        The new list may not change the definition of a bundle in *adopted*, 
which defaults to the
+        accepted list.
+        """
+
+    @abstractmethod
+    def find_loadable(self, name: str) -> _ExternalBundleConfig | None:
+        """Find a loadable bundle by *name*, reading the list again unless the 
name missed recently."""
+
+    @abstractmethod
+    def parse_context(
+        self,
+        name: str,
+        *,
+        manager: Callable[[], DagBundlesManager] | None = None,
+    ) -> BundleParseContext | None:
+        """
+        Return the accepted parse settings for *name*.
+
+        ``None`` means parsing processes and workers read the configuration 
directly.
+        """
+
+    @abstractmethod
+    def get_bundle_teams(self) -> dict[str, str | None]:
+        """Get the team of each bundle that should be processed, without 
reading a command or secret."""
+
+
+class _StaticBundleConfigSource(_BaseBundleConfigSource):
+    """``dag_bundle_config_list`` set literally, read on first use."""
+
+    lifecycle_class = _StaticBundleLifecycle
+    checks_bundle_names_when_parsing = True
+
+    @functools.cached_property
+    def _accepted(self) -> _BundleConfigSnapshot:
+        return _create_bundle_config_snapshot(_read_bundle_config_list())
+
+    def current(self) -> _BundleConfigSnapshot:
+        return self._accepted
+
+    def loadable(self) -> _BundleConfigSnapshot:
+        return self._accepted
+
+    def refresh(self, adopted: _BundleConfigSnapshot | None = None) -> None:
+        pass
+
+    def find_loadable(self, name: str) -> _ExternalBundleConfig | None:
+        return self._accepted.configs.get(name)
+
+    def parse_context(
+        self,
+        name: str,
+        *,
+        manager: Callable[[], DagBundlesManager] | None = None,
+    ) -> BundleParseContext | None:
+        return None
+
+    def get_bundle_teams(self) -> dict[str, str | None]:
+        return dict(self._accepted.team_names)
+
+
+class _ReloadingBundleConfigSource(_BaseBundleConfigSource):
+    """
+    The output of ``dag_bundle_config_list_cmd`` or 
``dag_bundle_config_list_secret``.
+
+    It is read again at most once per ``bundle_refresh_check_interval``, plus 
once per interval for
+    each missing bundle name. A list that changes the definition of an adopted 
bundle is rejected
+    as a whole.
+    """
+
+    lifecycle_class = _ReloadingBundleLifecycle
+    # Parsing processes receive the accepted settings instead of running the 
command again.
+    checks_bundle_names_when_parsing = False
+    _loadable: _BundleConfigSnapshot
+
+    def __init__(self, read_raw: Callable[[], str | None]) -> None:
+        self._read_raw = read_raw
+        self._last_read = 0.0
+        self._unloadable: _BundleConfigSnapshot | None = None
+        self._missed_at: dict[str, float] = {}
+
+    @functools.cached_property
+    def _accepted(self) -> _BundleConfigSnapshot:
+        self._last_read = time.monotonic()
+        # The first list is not checked, so a bundle class that cannot be 
imported fails the
+        # managers as it does with a static list.
+        self._loadable = 
_create_bundle_config_snapshot(_read_bundle_config_list(self._read_raw))
+        return self._loadable
+
+    def current(self) -> _BundleConfigSnapshot:
+        return self._accepted
+
+    def loadable(self) -> _BundleConfigSnapshot:
+        accepted = self._accepted
+        loadable = self._loadable
+        if accepted is loadable or accepted is self._unloadable:
+            return loadable
+        try:
+            for name, config in accepted.configs.items():
+                if loadable.configs.get(name) != config:
+                    _build_internal_bundle_config(config)
+        except Exception:
+            log.exception("Could not load the new Dag bundles; keeping the 
last loadable list")
+            self._unloadable = accepted
+            return loadable
+        self._loadable = accepted
+        return accepted
+
+    def refresh(self, adopted: _BundleConfigSnapshot | None = None) -> None:
+        accepted = self._accepted
+        if time.monotonic() - self._last_read >= conf.getint(
+            "dag_processor", "bundle_refresh_check_interval"
+        ):
+            self._read(accepted if adopted is None else adopted)
+
+    def find_loadable(self, name: str) -> _ExternalBundleConfig | None:
+        if (config := self.loadable().configs.get(name)) is not None:
+            return config
+        now = time.monotonic()
+        interval = conf.getint("dag_processor", 
"bundle_refresh_check_interval")
+        self._missed_at = {missed: at for missed, at in 
self._missed_at.items() if now - at < interval}
+        if name in self._missed_at:
+            return None
+        # A bundle whose class failed to load was never used, so a corrected 
definition is allowed.
+        self._read(self.loadable())
+        if (config := self.loadable().configs.get(name)) is None:
+            self._missed_at[name] = now
+        return config
+
+    def parse_context(
+        self,
+        name: str,
+        *,
+        manager: Callable[[], DagBundlesManager] | None = None,
+    ) -> BundleParseContext | None:
+        if manager is not None:
+            config = manager()._get_bundle_config(name)
+            return BundleParseContext(importers=deepcopy(config.importers), 
team_name=config.team_name)
+        if (external := self.find_loadable(name)) is not None:
+            return BundleParseContext(importers=deepcopy(external.importers), 
team_name=external.team_name)
+        raise ValueError(f"Requested bundle '{name}' is not configured.")

Review Comment:
   If the Dag processor needs its adopted view, put 
`get_bundle_parse_context(name)` on the manager, which already holds the 
private `_snapshot`, and drop `manager` from the interface.



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