-
Notifications
You must be signed in to change notification settings - Fork 17.6k
Claim callbacks through the Execution API before running them #70927
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
potiuk
wants to merge
2
commits into
apache:main
Choose a base branch
from
potiuk:claim-callbacks-through-the-execution-api
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,28 @@ | ||
| Callbacks are claimed through the Execution API before they run | ||
|
|
||
| A CeleryExecutor worker now claims a callback through the Execution API | ||
| (``POST /execution/callbacks/{callback_id}/run``) before importing and running | ||
| it, transitioning the callback ``QUEUED -> RUNNING``. Previously a callback was | ||
| executed without the worker making any authenticated call first, so the workload | ||
| token minted for it was never validated by the API server. | ||
|
|
||
| **Behaviour changes:** | ||
|
|
||
| - A ``3.4`` worker requires an API server that serves the new endpoint. Mixed | ||
| deployments negotiate the API version, so a worker talking to an older API | ||
| server continues to behave as though the endpoint does not exist. | ||
| - Callbacks now emit an intermediate ``RUNNING`` state, matching the documented | ||
| ``QUEUED -> RUNNING -> SUCCESS/FAILED`` lifecycle. | ||
| - A redelivered or replayed callback message that reaches a callback already | ||
| ``RUNNING`` or in a terminal state is refused rather than executed again. | ||
|
|
||
| * Types of change | ||
|
|
||
| * [ ] Dag changes | ||
| * [ ] Config changes | ||
| * [x] API changes | ||
| * [ ] CLI changes | ||
| * [x] Behaviour changes | ||
| * [ ] Plugin changes | ||
| * [ ] Dependency changes | ||
| * [ ] Code interface changes |
30 changes: 30 additions & 0 deletions
30
airflow-core/src/airflow/api_fastapi/execution_api/datamodels/callback.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,30 @@ | ||
| # 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 uuid import UUID | ||
|
|
||
| from pydantic import BaseModel | ||
|
|
||
| from airflow.utils.state import CallbackState | ||
|
|
||
|
|
||
| class CallbackRunResponse(BaseModel): | ||
| """Returned when a worker claims a callback for execution.""" | ||
|
|
||
| id: UUID | ||
| state: CallbackState |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
82 changes: 82 additions & 0 deletions
82
airflow-core/src/airflow/api_fastapi/execution_api/routes/callbacks.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,82 @@ | ||
| # 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 uuid import UUID | ||
|
|
||
| from cadwyn import VersionedAPIRouter | ||
| from fastapi import HTTPException, Security, status | ||
|
|
||
| from airflow.api_fastapi.common.db.common import SessionDep | ||
| from airflow.api_fastapi.execution_api.datamodels.callback import CallbackRunResponse | ||
| from airflow.api_fastapi.execution_api.security import ExecutionAPIRoute, require_auth | ||
| from airflow.models.callback import Callback | ||
| from airflow.utils.state import CallbackState | ||
|
|
||
| # ``cb:self`` makes the server enforce that the presented workload token was minted for *this* | ||
| # callback id (see ``require_auth``). Combined with ``token:workload``, a worker cannot reach this | ||
| # route without a validly-signed token whose subject is the callback it is claiming. | ||
| router = VersionedAPIRouter( | ||
| route_class=ExecutionAPIRoute, | ||
| dependencies=[ | ||
| Security(require_auth, scopes=["cb:self", "token:workload"]), | ||
| ], | ||
| ) | ||
|
|
||
|
|
||
| @router.post( | ||
| "/{callback_id}/run", | ||
| responses={ | ||
| status.HTTP_404_NOT_FOUND: {"description": "Callback not found"}, | ||
| status.HTTP_409_CONFLICT: {"description": "Callback is not in a claimable state"}, | ||
| }, | ||
| ) | ||
| def run_callback( | ||
| callback_id: UUID, | ||
| session: SessionDep, | ||
| ) -> CallbackRunResponse: | ||
| """ | ||
| Atomically claim a callback for execution and transition it to RUNNING. | ||
|
|
||
| The worker calls this *before* importing and invoking the callback. Its purpose is twofold: | ||
| the ``Security`` dependency forces the API server to validate the worker's token before any | ||
| callback code runs, and the ``QUEUED -> RUNNING`` transition is single-shot, so a redelivered | ||
| or replayed message that reaches a callback already RUNNING or terminal is refused rather than | ||
| executed a second time. | ||
| """ | ||
| callback = session.get(Callback, callback_id, with_for_update=True) | ||
| if callback is None: | ||
| raise HTTPException( | ||
| status_code=status.HTTP_404_NOT_FOUND, | ||
| detail={"reason": "not_found", "message": f"Callback {callback_id} not found"}, | ||
| ) | ||
|
|
||
| if callback.state != CallbackState.QUEUED: | ||
| raise HTTPException( | ||
| status_code=status.HTTP_409_CONFLICT, | ||
| detail={ | ||
| "reason": "conflict", | ||
| "message": ( | ||
| f"Callback {callback_id} is in state {callback.state}; it can only be claimed " | ||
| "while QUEUED." | ||
| ), | ||
| }, | ||
| ) | ||
|
|
||
| callback.state = CallbackState.RUNNING | ||
|
|
||
| return CallbackRunResponse(id=callback.id, state=CallbackState.RUNNING) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
30 changes: 30 additions & 0 deletions
30
airflow-core/src/airflow/api_fastapi/execution_api/versions/v2026_08_01.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,30 @@ | ||
| # 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 cadwyn import VersionChange, endpoint | ||
|
|
||
|
|
||
| class AddCallbackRunEndpoint(VersionChange): | ||
| """Add the callbacks/{callback_id}/run endpoint that a worker uses to claim a callback.""" | ||
|
|
||
| description = __doc__ | ||
|
|
||
| instructions_to_migrate_to_previous_version = ( | ||
| endpoint("/callbacks/{callback_id}/run", ["POST"]).didnt_exist, | ||
| ) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
64 changes: 64 additions & 0 deletions
64
airflow-core/tests/unit/api_fastapi/execution_api/versions/head/test_callbacks.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,64 @@ | ||
| # 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 pytest | ||
|
|
||
| from airflow.models.callback import Callback, CallbackFetchMethod, ExecutorCallback | ||
| from airflow.sdk.definitions.callback import SyncCallback | ||
| from airflow.utils.state import CallbackState | ||
|
|
||
| pytestmark = pytest.mark.db_test | ||
|
|
||
|
|
||
| def _make_callback(session, state: CallbackState) -> Callback: | ||
| cb = ExecutorCallback(SyncCallback("os.getcwd"), fetch_method=CallbackFetchMethod.IMPORT_PATH) | ||
| cb.state = state | ||
| session.add(cb) | ||
| session.commit() | ||
| return cb | ||
|
|
||
|
|
||
| class TestRunCallback: | ||
| def test_claim_transitions_queued_to_running(self, client, session): | ||
| """A QUEUED callback is claimed and moved to RUNNING; the response reports the new state.""" | ||
| cb = _make_callback(session, CallbackState.QUEUED) | ||
|
|
||
| response = client.post(f"/execution/callbacks/{cb.id}/run") | ||
|
|
||
| assert response.status_code == 200 | ||
| assert response.json() == {"id": str(cb.id), "state": "running"} | ||
|
|
||
| session.expire_all() | ||
| assert session.get(Callback, cb.id).state == CallbackState.RUNNING | ||
|
|
||
| def test_returns_404_for_unknown_callback(self, client): | ||
| response = client.post("/execution/callbacks/00000000-0000-0000-0000-000000000000/run") | ||
| assert response.status_code == 404 | ||
|
|
||
| def test_returns_422_for_invalid_uuid(self, client): | ||
| response = client.post("/execution/callbacks/not-a-uuid/run") | ||
| assert response.status_code == 422 | ||
|
|
||
| @pytest.mark.parametrize("state", [CallbackState.RUNNING, CallbackState.SUCCESS, CallbackState.FAILED]) | ||
| def test_a_callback_can_only_be_claimed_once(self, client, session, state): | ||
| """A callback already RUNNING or terminal cannot be claimed again — replay/redelivery is refused.""" | ||
| cb = _make_callback(session, state) | ||
|
|
||
| response = client.post(f"/execution/callbacks/{cb.id}/run") | ||
|
|
||
| assert response.status_code == 409 |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Doesn't this conflict with the executors which already change the state from QUEUED to RUNNING?
LocalExecutorqueues the RUNNING event before callingrun_workload(), so it would be RUNNING before it gets here and thisif not QUEUEDblock would throw an exception, failing the callback by default before it ever gets run. The AWS executors all set the state to RUNNING inself.running_state()as well. I'm pretty sure Celery is the exception here and every other executor would start failing.I suspect the executors need to be updated to not also change the state, or this
if queuedcheck needs to be expanded toif not terminal state, maybe?