Skip to content

Fix connection resolution in CLI by setting server process context in decorators - #61036

Merged
potiuk merged 5 commits into
apache:mainfrom
uplsh580:dagprocessor/bundle-name-flag
Jul 1, 2026
Merged

potiuk merged 5 commits into
apache:mainfrom
uplsh580:dagprocessor/bundle-name-flag

Conversation

@uplsh580

@uplsh580 uplsh580 commented Jan 25, 2026 •

Copy link
Copy Markdown
Contributor

Related Issues

Issue: #61033

Summary

This PR ensures that Airflow CLI commands are executed with the server process context by default.
This is achieved by setting the _AIRFLOW_PROCESS_CONTEXT environment variable to "server" within the core CLI decorators (action_cli and suppress_logs_and_warning).

Rationale

Previously, commands like airflow dag-processor -B <bundle_name> failed with an AirflowNotFoundException when initializing bundles that require database connections (e.g., GitDagBundle).

The failure occurred because:

  1. The -B flag triggers bundle validation (validate_dag_bundle_arg in _create_dag_processor_job_runner) during the command initialization phase.
    @enable_memray_trace(component=MemrayTraceComponents.dag_processor)
    @cli_utils.action_cli
    @providers_configuration_loaded
    def dag_processor(args):
    """Start Airflow Dag Processor Job."""
    job_runner = _create_dag_processor_job_runner(args)

    def _create_dag_processor_job_runner(args: Any) -> DagProcessorJobRunner:
    """Create DagFileProcessorProcess instance."""
    if args.bundle_name:
    cli_utils.validate_dag_bundle_arg(args.bundle_name)
    return DagProcessorJobRunner(
    job=Job(),
    processor=DagFileProcessorManager(
    max_runs=args.num_runs,
    bundle_names_to_parse=args.bundle_name,
    ),
    )

    def validate_dag_bundle_arg(bundle_names: list[str]) -> None:
    """Make sure only known bundles are passed as arguments."""
    known_bundles = {b.name for b in DagBundlesManager().get_all_dag_bundles()}
    unknown_bundles: set[str] = set(bundle_names) - known_bundles
    if unknown_bundles:
    raise SystemExit(f"Bundles not found: {', '.join(unknown_bundles)}")
  2. At this early stage, the server context was not yet set, causing the Task SDK to skip MetastoreBackend and fail to resolve connections from the metadata database.

By moving the context setting to the decorator level, we ensure that all CLI management commands have the necessary privileges to access database-backed secrets before any validation or execution logic runs.

Key Changes

  • airflow/utils/cli.py:
    • Set _AIRFLOW_PROCESS_CONTEXT = "server" in action_cli decorator when check_db is True.
    • Set _AIRFLOW_PROCESS_CONTEXT = "server" in suppress_logs_and_warning decorator.
  • airflow/cli/commands/connection_command.py: Removed redundant manual environment settings in connections_get and connections_test.

Test plan

  1. Configure a DAG bundle that requires a connection (e.g., GitDagBundle).
  2. Run airflow dag-processor -B <bundle_name>.
  3. Verify the command starts successfully without AirflowNotFoundException.
  4. Run existing connection commands (e.g., airflow connections get) to ensure no regressions.

Was generative AI tooling used to co-author this PR?
  • Yes (please specify the tool below)
  • Gemini 3 flash

  • Read the Pull Request Guidelines for more information. Note: commit author/co-author name and email in commits become permanently public when merged.
  • For fundamental code changes, an Airflow Improvement Proposal (AIP) is needed.
  • When adding dependency, check compliance with the ASF 3rd Party License Policy.
  • For significant user-facing changes create newsfragment: {pr_number}.significant.rst or {issue_number}.significant.rst, in airflow-core/newsfragments.

@uplsh580

uplsh580 commented Jan 25, 2026 •

Copy link
Copy Markdown
Contributor Author

Validation

Issue case - airflow dag-processor -B bundle1

image

airflow dag-processor

image

airflow connections get

image

@uplsh580

Copy link
Copy Markdown
Contributor Author

Could you please verify if this approach aligns with the project's long-term architectural goals regarding component isolation and database access?

I believe this change is consistent with our future direction for the following reasons:

  1. Administrative Identity: CLI tools are inherently administrative and designed for system management. Even as we move towards greater component isolation, these management commands require a 'Server' identity to resolve credentials and initialize system components effectively.
  2. Architectural Consistency: This PR utilizes the existing _AIRFLOW_PROCESS_CONTEXT abstraction defined for Airflow 3. Centralizing this setting within the core CLI decorators ensures the correct context is established at the initial entry point, preventing early initialization failures during bundle validation.
  3. Security Isolation: Importantly, this does not compromise the isolation of user code. The actual task execution and DAG parsing remain strictly restricted, as the Task SDK's Supervisor and the DAG processor explicitly override the context to client for child processes to prevent inheriting server privileges:

Your feedback on whether this centralization is the preferred way to handle CLI context would be greatly appreciated.

@uplsh580
uplsh580 force-pushed the dagprocessor/bundle-name-flag branch from 7a9160e to f9184ba Compare January 25, 2026 12:10
@uplsh580
uplsh580 marked this pull request as ready for review January 25, 2026 13:25
@potiuk

potiuk commented Jan 26, 2026

Copy link
Copy Markdown
Member

I think we are going to get rid of _AIRFLOW_PROCESS_CONTEXT altogether - correct @amoghrajesh @bugraoz93 ? - so rather than moving it around, I would wait for completing the isolation process, where if needed we pass the necessary context to "shared" library from the calling process via some parameter during the initialization.

Some of the cli methods are shared between airflow-ctl and airflow regular CLI commands, and this will be the main distinction that will determine whether the DB calls are made or CLI calls - and then, it will not be necessary to have an enviironment variable to pass the context. This is - as I see it - a bit of a hack to make it possible to use the same code in two places - and the current shared library context is taking another - more long term - approach, similarly the initialization will be more of a deliberate process where just "importing" airflow is not going to to do much - there will be a deliberate initialization code that will depend on which component is running the initialization and passign the right "context" via this initialization to the shared code seems to be a better approach.

Maybe we can merge it as a temporary measure, but I don't see it as even mid-term sustainable approach.

@bugraoz93

bugraoz93 commented Jan 26, 2026 •

Copy link
Copy Markdown
Contributor

Thanks, @potiuk! You summarised it pretty clearly. We will have deprecations on the CLI and will start this pretty soon. In CLI, there will be isolation work on remote commands defined in AIP-81. Deprecation and migration are on the way. Airflow CLI will mainly be used for always server-side triggers and actions rather than anything we can safely provide from the API.

The voting will start later today or tomorrow. There are incoming dev call, and I wanted to align the voting so we can maybe go over it all together with everyone in the call to see if there are any concerns which most of the part already agreed on in AIP-81, but we now have a more concrete plan on how to achieve it in AIP-94 and will be voted from entire community.
https://cwiki.apache.org/confluence/pages/viewpage.action?pageId=382175838

I would be on the safe side and won't put much effort into something we won't maintain eventually and not needed. I really like any improvement, but some can create more maintenance effort than we put into solving the actual problem that won't be there after 3-5 minor release according to how fast we can migrate, but I believe we have a good foundation to work on over CI/CD and more 🙌

For the TaskSDK side, @amoghrajesh can have a clearer answer

@amoghrajesh

Copy link
Copy Markdown
Contributor

Thanks @potiuk!

Yeah we want to get rid of using that env variable entirely in long term but for dag processor and such, it will be dependent also on AIP92 (entirely decoupling dag processor and triggerer from core and having API first communication for those too). So this would be a good temporary solution until then

@uranusjr

Copy link
Copy Markdown
Member

The logic looks right to me, but I don’t like how a decorator magically modifies the global state (an environment variable) that leaks out after it exits. If we’re to do this, the environment varialbe needs to be restored when the context ends.

@uplsh580
uplsh580 force-pushed the dagprocessor/bundle-name-flag branch from ae74302 to d3455f9 Compare January 27, 2026 10:38
@uplsh580

Copy link
Copy Markdown
Contributor Author

Validation

Issue case - airflow dag-processor -B bundle1

image

airflow dag-processor

스크린샷 2026-01-27 오후 7 54 00

airflow connections get GITHUB__SAMPLE

image

@uplsh580

Copy link
Copy Markdown
Contributor Author

@uranusjr Thanks for the feedback. I've updated the logic to ensure the environment variable is restored when the context ends, avoiding any global state leakage. I appreciate the suggestion!

@uplsh580
uplsh580 force-pushed the dagprocessor/bundle-name-flag branch from d3455f9 to fbbbc2a Compare January 27, 2026 11:37
@potiuk

potiuk commented Feb 14, 2026

Copy link
Copy Markdown
Member

@uranusjr -> are you ok with it ?

@potiuk potiuk added the ready for maintainer review Set by triage when all criteria pass, or by the fork CI reconciler when fork CI is green. label Mar 11, 2026
Comment thread airflow-core/src/airflow/utils/cli.py Resolved
potiuk
potiuk previously requested changes Mar 12, 2026

@potiuk potiuk left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The PR addresses a real bug where the dag-processor CLI fails when bundle validation needs database connections before the process context is set. However, the approach of unconditionally setting _AIRFLOW_PROCESS_CONTEXT="server" in all CLI commands via broad decorators is too aggressive and raises correctness concerns.

Key Issues

  1. Overly broad scope: action_cli is used by dozens of CLI commands. Setting server context unconditionally means commands like airflow info, airflow cheat-sheet, airflow plugins list, etc. all get server-level privileges to access MetastoreBackend — even though they don't need it and previously didn't have it. This violates the principle of least privilege.

  2. Double-setting in stacked decorators: Commands like pool_set, connections_add, dag_test, etc. use both @action_cli and @suppress_logs_and_warning. With this PR, the env var would be set/saved/restored twice in nested fashion. While technically not broken due to the save/restore pattern, it's unnecessary overhead and confusing.

  3. Inconsistency with check_db gating: The PR description says _AIRFLOW_PROCESS_CONTEXT should be set "when check_db is True" in action_cli, but the actual code sets it unconditionally (outside the if check_db: block). This means even @action_cli(check_db=False) commands get server context.

Suggested Alternative

Instead of setting server context in these broad decorators, consider a more targeted fix:

  • Set _AIRFLOW_PROCESS_CONTEXT="server" in _create_dag_processor_job_runner() before calling validate_dag_bundle_arg(), or
  • Move it to validate_dag_bundle_arg() itself, or
  • Create a dedicated @server_context decorator that can be applied selectively to commands that need it.

This would fix the actual bug without granting server privileges to every CLI command.

@uplsh580
uplsh580 force-pushed the dagprocessor/bundle-name-flag branch from fbbbc2a to 5634206 Compare March 13, 2026 16:01
@uplsh580
uplsh580 requested a review from dheerajturaga as a code owner March 13, 2026 16:01
@uplsh580
uplsh580 force-pushed the dagprocessor/bundle-name-flag branch from 5634206 to 0816c6e Compare March 13, 2026 16:02
@potiuk
potiuk marked this pull request as draft March 13, 2026 21:32
@potiuk

potiuk commented Mar 13, 2026 •

Copy link
Copy Markdown
Member

@uplsh580 Converting to draft — this PR doesn't yet meet our Pull Request quality criteria.

  • ❌ Build docs: Failing: CI image checks / Build documentation (--docs-only). Run breeze build-docs locally to reproduce. See Build docs docs.
  • ❌ Other failing CI checks: Failing: CI image checks / Build documentation (--spellcheck-only). Run prek run --from-ref main locally to reproduce. See static checks docs.
  • ⚠️ Unresolved review comments: This PR has 1 unresolved review thread from maintainers: @potiuk (MEMBER): 1 unresolved thread. Please review and resolve all inline review comments before requesting another review. You can resolve a conversation by clicking 'Resolve conversation' on each thread after addressing the feedback. See pull request guidelines.

Note: Your branch is 437 commits behind main. Please rebase and push again to get up-to-date CI results.

See the linked criteria for how to fix each item, then mark the PR "Ready for review". This is not a rejection — just an invitation to bring the PR up to standard. No rush.


Note: This comment was drafted by an AI-assisted triage tool and may contain mistakes. Once you have addressed the points above, an Apache Airflow maintainer — a real person — will take the next look at your PR. We use this two-stage triage process so that our maintainers' limited time is spent where it matters most: the conversation with you.

@potiuk potiuk removed the ready for maintainer review Set by triage when all criteria pass, or by the fork CI reconciler when fork CI is green. label Mar 13, 2026
@uplsh580
uplsh580 force-pushed the dagprocessor/bundle-name-flag branch 3 times, most recently from 6f6b6d7 to 7f42ec5 Compare March 14, 2026 00:23
@uplsh580
uplsh580 force-pushed the dagprocessor/bundle-name-flag branch from 7f42ec5 to 2edc081 Compare March 14, 2026 04:10
@uplsh580
uplsh580 marked this pull request as ready for review March 14, 2026 05:09
@uplsh580

uplsh580 commented Mar 14, 2026 •

Copy link
Copy Markdown
Contributor Author

Validation

airflow dag-processor -B bundle1 with connection in db

image image

airflow dag-processor -B bundle1 with CONN ENV

image image

@potiuk
potiuk dismissed their stale review April 2, 2026 16:44

Dismiss

@potiuk potiuk added the ready for maintainer review Set by triage when all criteria pass, or by the fork CI reconciler when fork CI is green. label Apr 2, 2026
@potiuk potiuk added ready for maintainer review Set by triage when all criteria pass, or by the fork CI reconciler when fork CI is green. and removed ready for maintainer review Set by triage when all criteria pass, or by the fork CI reconciler when fork CI is green. labels May 26, 2026
@potiuk
potiuk merged commit 46186d2 into apache:main Jul 1, 2026
139 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:CLI ready for maintainer review Set by triage when all criteria pass, or by the fork CI reconciler when fork CI is green.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants