fix(assets): reduce task success asset registration lock contention
Closes #66853
Summary
- Commit the task-instance state update and log entry before asset registration in
ti_update_state(), releasing thetask_instancerow lock before asset scheduling work runs. - Replace the alias-event ORM relationship append with a direct association-table insert so long-running aliases do not lazy-load large
asset_eventscollections on the task completion path. - Keep HTTP 204 after task success is durable if post-commit asset registration fails, but log the failure and increment
asset.registration_failuresso dropped registration work is observable. Durable retry/reconciliation is intentionally out of scope for this lock-contention fix. - Gate post-commit asset registration on the committed outcome, so a success payload that is forced into a durable
FAILEDtask-instance state does not emit asset events.
Evidence
Sanitized measurements from the affected deployment showed the task completion path under load with 80+ concurrent successful task completions, asset-registration queries left idle in transaction for minutes, blocked SELECT ... FOR UPDATE calls on task_instance, and apiserver OOMKills while those requests piled up.
Changes
airflow-core/src/airflow/api_fastapi/execution_api/routes/task_instances.py: early task-state commit, post-commit asset registration, committed-state guard, andasset.registration_failuresmetric on registration failure.airflow-core/src/airflow/assets/manager.py: direct alias association insert, with an explicit note thatasset_alias_model.asset_eventsis intentionally left unsynced in the current session because this path does not read it again before commit.airflow-core/tests/unit/api_fastapi/execution_api/versions/head/test_task_instances.py: regression coverage for 204 task-state durability, asset-registration failure metric emission, and the forced-failure path that commitsFAILEDand skips asset registration.airflow-core/tests/unit/assets/test_manager.py: engine-level SQL listener coverage proving alias registration does not emit a lazy-loadSELECTon the alias-event association path. This was red-checked locally against the old ORM.append()implementation.shared/observability/src/airflow_shared/observability/metrics/metrics_template.yaml: metric registry entry forasset.registration_failures.scripts/ci/prek/check_connection_doc_labels.py: skip volatile generated dependency directories while scanning source/docs for connection labels, so all-files static checks do not race with UInode_moduleschurn.
Validation
prek run --files airflow-core/src/airflow/api_fastapi/execution_api/routes/task_instances.py airflow-core/src/airflow/assets/manager.py airflow-core/tests/unit/api_fastapi/execution_api/versions/head/test_task_instances.py airflow-core/tests/unit/assets/test_manager.py scripts/ci/prek/check_connection_doc_labels.py scripts/tests/ci/prek/test_check_connection_doc_labels.py shared/observability/src/airflow_shared/observability/metrics/metrics_template.yaml airflow-core/src/airflow/config_templates/airflow_local_settings.py scripts/ci/prek/check_partition_mapper_defaults_in_sync.pyprek run --from-ref upstream/main --to-ref HEAD(substantive hooks passed; the workspaceidentityhook reports the checked file list as modified when run over this uncommitted PR range).venv/bin/python scripts/ci/prek/run_mypy_full_dist_local_venv_or_breeze_in_ci.py airflow-coreuv run --frozen --no-sync pytest --with-db-init airflow-core/tests/unit/api_fastapi/execution_api/versions/head/test_task_instances.py airflow-core/tests/unit/assets/test_manager.py -qPYTHONPATH=scripts/ci/prek uv run --frozen --no-sync pytest scripts/tests/ci/prek/test_check_connection_doc_labels.py -quv run --no-sync scripts/ci/prek/check_connection_doc_labels.pyprek run check-connection-doc-labels --all-filesbreeze testing core-tests --backend sqlite --python 3.10 --db-reset -- airflow-core/tests/unit/api_fastapi/execution_api/versions/head/test_task_instances.py airflow-core/tests/unit/assets/test_manager.py -qbreeze testing core-tests --backend postgres --python 3.10 --db-reset -- airflow-core/tests/unit/api_fastapi/execution_api/versions/head/test_task_instances.py airflow-core/tests/unit/assets/test_manager.py -qbreeze testing core-tests --backend postgres --python 3.10 --downgrade-pendulum --db-reset -- airflow-core/tests/unit/api_fastapi/execution_api/versions/head/test_task_instances.py airflow-core/tests/unit/assets/test_manager.py -qbreeze testing core-tests --backend sqlite --python 3.10 --force-lowest-dependencies --db-reset -- airflow-core/tests/unit/api_fastapi/execution_api/versions/head/test_task_instances.py airflow-core/tests/unit/assets/test_manager.py -qgit diff --check
PR Checklist
- [x] My PR is targeted at the
mainbranch - [x] Tests added/updated
- [x] Targeted
prek, mypy, pytest, and Breeze validation passed locally
The failing CI job (provider distributions tests / Compat 3.0.6:P3.10) is pre-existing on main and unrelated to this PR. It fails with:
ImportError: cannot import name 'Options' from 'jwt.types'
This is a flask_jwt_extended/PyJWT version incompatibility in providers/fab tests running against Airflow 3.0.6. Confirmed failing on main in run https://github.com/apache/airflow/actions/runs/25789005777 before this PR was opened.
All other CI checks pass.
The CI failure in Integration and System Tests / Integration core otel (test_export_legacy_metric_names) is unrelated to this PR — it tests scheduler-side metric emission timing and has a history of flakiness (see #61070, #65867). This PR touches only task_instances.py and assets/manager.py; no OTEL or scheduler metric code is modified.
@hkc-8010 Converting to draft — this PR doesn't yet meet our Pull Request quality criteria.
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.
Drafted-by: Claude Code (Opus 4.7); reviewed by @potiuk before posting
@hkc-8010 — There are 2 unresolved review thread(s) on this PR from @Lee-W, @kaxil. Could you either push a fix or reply in each thread explaining why the feedback doesn't apply? When you believe the feedback is addressed, please mark the threads as resolved and ping the reviewer (@Lee-W, @kaxil) for a final look. Thanks!
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 thanks for the triage notes. The items called out in your comments should be addressed now:
- The unresolved review threads from @Lee-W / @kaxil have been replied to and resolved.
- The PR is no longer draft.
- The latest pushed commit is
c3e3e7cb98a, and the visible GitHub checks are green:131passing,0failing,0pending,14skipped.
Could you please take another look at the PR when you get a chance?
Is it a good idea to make the endpoint succeed when lock contention happens? I feel it’s a consistency issue. We should either do retry in the endpoint, or report back to the client there’s something wrong.
Retry/reconciliation for this path is intentionally out of scope for this PR (called out in the description) — the goal here is resolving the task_instance row lock contention causing idle-in-transaction pile-ups and apiserver OOMKills, not building a full delivery guarantee for asset events.
On why it still returns success: by the time register_asset_changes_in_db runs, the TI state is already committed and durable. Returning 500 here would make the task-sdk worker retry a state update for a task that already succeeded, which is a worse failure mode than a dropped asset event. The failure is now observable via the asset.registration_failures metric and a log line, so an operator can catch and manually reconcile if it happens.
Agreed it's not fully consistent. Happy to file a follow-up issue to track retry/reconciliation for dropped asset events as separate work if that addresses the concern for this PR.
Renamed the PR title, check_no_conventional_commit_message was failing on the Conventional-Commits-style title.
Also looked at the Integration and System Tests / Integration core otel failure (test_dag_execution_succeeds[detail_spans], span-hierarchy assertion on sub_span1/_execute_task). This is unrelated to this PR: test_otel.py isn't touched by this diff, and git blame shows the failing expected-hierarchy block was added by a separate commit (2e9cbc25ebbe, "Add configurable task span detail level for OTel tracing") that landed on main independently. The test itself notes the gap ("Additional detail spans are deferred to follow-up PRs"), so this looks like a pre-existing baseline failure rather than something introduced here.
How do you plan to do the followup? The response is indistinguishable to when the asset registration is successful. You response is too hand-wavy to the inconsistency. A concrete plan should be layed out so the behavior is not just silently broken until your next submission is merged. This PR is simply not an improvement on its own.
Since this PR and the discussion mainly revolve around the early-commit approach and the resulting consistency trade-offs, I was wondering whether there might be another approach that avoids the early commit.
To be more specific, would it be possible to keep the TI state update and asset registration in the same transaction, but defer acquiring the TI row lock until immediately before the ti.state update?
My current understanding of the original flow is:
ti_update_state()
→ SELECT the TI row FOR UPDATE (lock acquire)
→ perform asset registration (long job)
→ update ti.state
→ commit and release the lock
This seems to mean that when asset registration takes a long time, the TI row lock is held for that entire period, causing later requests for the same TI to wait on SELECT ... FOR UPDATE.
I was wondering whether the ordering could instead be:
ti_update_state()
→ perform asset registration (long job)
→ acquire the TI row lock and re-check the state
→ update ti.state
→ commit both changes together
If the state is no longer valid at that point, the transaction could be rolled back together with the asset changes.
Would this potentially shorten the TI lock window while preserving atomicity between the state update and asset events? (Since #66853 identifies the long-held TI lock and waiter pile-up as the OOM path) I have not audited the other TI writers or the lock-ordering implications, so there may be a constraint I have overlooked.
@uranusjr @Andrushika you're right, and I've stopped defending the current shape. Returning 204 while a failed register_asset_changes_in_db is only logged and counted means a dropped asset event silently never fires its downstream DAG, and "follow up later" isn't good enough. As it stands the PR isn't an improvement on its own. Before I push more code I want to agree on the shape.
Proposal: a durable transactional outbox plus a scheduler reconciliation sweep, so a dropped registration is guaranteed to be delivered eventually rather than lost.
- Durable marker committed atomically with the TI state. On the success path, alongside the existing early
session.commit(), I insert one row into a newasset_registration_outboxtable capturingti_idand the (already-validated)task_outletsandoutlet_events. Because it commits in the same transaction as the state update, the 204 is only returned once the pending-registration record is durable, so even a crash between the state commit and registration can't lose the event. That is the "not silently broken" guarantee. - Inline registration stays post-commit, as an optimization. The expensive work (scheduled-dag scan,
AssetDagRunQueueinserts, alias association) still runs after the lock is released, so the #66853 contention fix is preserved. On success it deletes the outbox row in the same transaction as the asset writes, which keeps it exactly-once against that row; on failure it rolls the asset writes back and leaves the outbox row for the scheduler. The outbox insert itself touches no hot rows and runs no queries, so it doesn't reintroduce thetask_instancelock contention. - Scheduler reconciles leftovers. A recurring sweep (claiming rows with
FOR UPDATE SKIP LOCKED, HA-safe, modeled on the existing heartbeat/zombie purge) replays any leftover outbox rows throughregister_asset_changes_in_dband deletes them, so the events land asAssetEventandAssetDagRunQueuerows and_create_dag_runs_asset_triggeredpicks them up. Astats.gaugeexposes the pending backlog so operators can see if reconciliation falls behind.
@Andrushika thanks, your reorder (register before taking the TI lock, then commit state and assets together) is a clean way to shrink the lock window and I considered it seriously. I leaned toward the outbox for two reasons. The reorder still needs a full audit of every task_instance writer for lock-ordering and deadlock risk before I'd trust it, and it still loses the event if the process dies between the asset work and the commit. The outbox gives an explicit, testable at-least-once guarantee instead. I'm happy to go the reorder route if you'd both prefer it; I don't have a strong attachment beyond wanting the guarantee to be verifiable.
Two questions before I implement:
- Does this shape address the consistency concern for you?
- Should the outbox and reconciliation land in this PR (it adds a table, a migration, and a scheduler timer), or as a stacked PR that merges together with this one? I'd rather not split it in a way that leaves a window where the drop is unhandled on
main.
@uranusjr I reworked this along the lines we discussed. The set-state endpoint no longer registers asset events under the task_instance lock and no longer drops them on failure.
On success it now commits the TI state first (releasing the row lock), then tries the asset write once under a short lock timeout. If it cannot get the locks in time, or fails for any reason, it writes the events to a new asset_event_queue table. The scheduler drains that queue and retries until the events land, parking a row only after a bounded number of failures (with a metric). So the common case still registers inline, contention sheds to the queue, and nothing is silently dropped.
I also kept the alias direct-INSERT fix, documented the enqueue-to-registration window in the asset-scheduling docs, and added a significant newsfragment. Validation: new endpoint and scheduler unit tests, plus breeze core-tests on Python 3.10 against both sqlite and postgres.
Draining the TI state update itself through the same queue is left out, as we agreed. Would appreciate another look when you get a chance.
it still loses the event if the process dies between the asset work and the commit.
No, I think this part may be a misunderstanding. The one possible solution I mentioned simply changes the lock-acquisition sequence while preserving the original pattern of a DB transaction. Asset registration and state updates are atomic here.
To make the comparison concrete, I prototyped it: https://github.com/apache/airflow/pull/70078
It registers the events before taking the task_instance row lock, still within the same transaction, then rechecks the state under the lock and rolls back if it loses the race. About 40 lines of code plus tests. Test results and Postgres numbers are in the draft PR.
I opened it as a draft for comparison. Happy to move it forward if this direction is useful, or drop it if the queue direction is preferred :)
@uranusjr following up on the queue design we landed on in Slack. After @jason810496's review I simplified this to be queue-only: the execution API commits a durable asset_event_queue marker in the same transaction as the task-success state, and the scheduler drain is now the single writer that runs register_asset_changes_in_db. That drops the inline registration fast-path I had added on the request path, so there is no asset registration inside the state-update request at all now, which is the cleanest form of the scheduler-drained queue we discussed.
The tradeoff is that a task's asset events (and the downstream asset-triggered runs) become visible after a drain interval instead of immediately, and dag.test does not register them at all since it has no scheduler. Both are documented in the newsfragment and the asset-scheduling note.
Wanted to confirm you are good dropping the inline path before I treat the direction as settled. @jason810496 thanks for pushing on this.
Hi @jason810496 @hkc-8010, thanks for the work here! After looking again, I think the OOM might be fixable with a much smaller change, and this PR may already contain it.
The bottleneck is this line in register_asset_change():
asset_alias_models: Iterable[AssetAliasModel] = session.scalars(
select(AssetAliasModel)
.where(AssetAliasModel.name.in_(source_alias_names))
.options(
joinedload(AssetAliasModel.scheduled_dags).joinedload(DagScheduleAssetAliasReference.dag)
)
).unique()
for asset_alias_model in asset_alias_models:
asset_alias_model.asset_events.append(asset_event)
session.add(asset_alias_model)
asset_events is a lazy relationship. To append one event, SQLAlchemy first loads the alias's whole existing event history into memory. We never read those rows, we only want to add one link. The direct insert already in this PR's manager.py skips that load.
I benchmarked register_asset_change with N prior events on the alias:
| N | append (lazy load) | direct insert |
|---|---|---|
| 0 | 1.6 ms | 1.2 ms |
| 1,000 | 5.2 ms | 1.2 ms |
| 10,000 | 107 ms | 1.2 ms |
| 50,000 | 470 ms | 1.4 ms |
After that, the function only takes ~1 ms, regardless of the history size. If that holds, I think we might not need the outbox pattern or queue anymore, since the lock contention time becomes really short.
Happy to share the benchmarking script.