Skip to content

Add a SKILL for async API endpoint migrations - #73405

Open
Dev-iL wants to merge 1 commit into
apache:mainfrom
Dev-iL:2609/endpoint-conversion
Open

Dev-iL wants to merge 1 commit into
apache:mainfrom
Dev-iL:2609/endpoint-conversion

Conversation

@Dev-iL

@Dev-iL Dev-iL commented Sep 20, 2026 •

Copy link
Copy Markdown
Collaborator

related: #67799

Add the airflow-async-endpoints SKILL to guide and standardize the incremental conversions and new async endpoints for the migrations tracked in #67799. The skill captures lessons from the heartbeat conversion in #67800, including transaction ownership, commit-before-response behavior, synchronous compatibility boundaries, and async test-engine lifetimes. It also covers secrets resolution, contract regression tests, and verification across SQLite, PostgreSQL, and MySQL, with references to the current implementation and driver guidance.

The skill is most useful for the duration of the migration, and especially if additional contributors participate in the effort. Afterwards it can either be removed or be used as a reference for adding more endpoints.


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

Generated-by: Codex and Claude Code (Opus 5.5) following the guidelines


  • 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, in airflow-core/newsfragments. You can add this file in a follow-up commit after the PR is created so you know the PR number.

@Dev-iL
Dev-iL force-pushed the 2609/endpoint-conversion branch from 26d8415 to 46f2825 Compare September 21, 2026 05:38
@Dev-iL
Dev-iL force-pushed the 2609/endpoint-conversion branch 2 times, most recently from 431ae13 to 09d7478 Compare September 30, 2026 18:00
@Dev-iL
Dev-iL force-pushed the 2609/endpoint-conversion branch 3 times, most recently from 662c299 to 61aa794 Compare October 1, 2026 15:22
@Dev-iL
Dev-iL marked this pull request as draft October 12, 2026 06:54
@Dev-iL

Dev-iL commented Oct 12, 2026

Copy link
Copy Markdown
Collaborator Author

Marked as draft to make room for other PRs

@Dev-iL
Dev-iL force-pushed the 2609/endpoint-conversion branch 2 times, most recently from 367e8cc to 7a10316 Compare October 22, 2026 07:04
@Dev-iL Dev-iL mentioned this pull request Oct 22, 2026
1 task done
@Dev-iL
Dev-iL force-pushed the 2609/endpoint-conversion branch 3 times, most recently from b1af3f9 to 678dc58 Compare November 8, 2026 07:00
@Dev-iL Dev-iL changed the title Add an agent skill for async API endpoint migrations Add a SKILL for async API endpoint migrations Nov 14, 2026
@Dev-iL
Dev-iL force-pushed the 2609/endpoint-conversion branch from 678dc58 to 6097045 Compare November 23, 2026 12:58
@Dev-iL
Dev-iL force-pushed the 2609/endpoint-conversion branch from 6097045 to 73e27e9 Compare November 23, 2026 18:04

@dabla dabla left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Addressed

Nothing since the previous round: this is the first review, and the PR has no review threads yet.

Open

  • Comment [1]: the working_set advice cannot restore session.get's visibility of archived attempts; name include_all_attempts.
  • Comments [4] and [5]: two reference files describe the open PRs #75381 and #75396 as the current state of the repository.
  • Comments [2], [3], [6]: known_sync_db_on_event_loop.txt missing from the verification steps, the cadwyn#51 citation, an unresolvable commit.
  • Not commented inline: the head commit carries [skip ci], so no static check (license headers, Markdown and spelling hooks) has run on it; it needs one CI run before leaving draft. SKILL.md has lines of up to 1,275 characters where the sibling skills wrap at about 100, which makes later one-word edits hard to review. Nothing links the skill from AGENTS.md or execution_api/AGENTS.md; three other skills on main have no link either, so this is a suggestion, not a finding.

The pass: head 73e27e9152, diff-based, against main at 08dd8a208d. The change is documentation only, so the code audits (thread affinity, lifecycle, benchmarks) do not apply; the docs-claims audit ran over all four files. Every file path, symbol, fixture, config value, commit and PR the skill names was looked up on main. Confirmed as written: AsyncSessionDep with scope="function", create_session_async, settings.dispose_async_engine() in the API server lifespan and the in-process Execution API, _configure_async_session, SerializedDagModel.get executing only latest_item_select_object, the session-free DBDagBag._read_dag, the joined TaskInstance.dag_run, ExecutionAPISecretsBackend.aget_variable/aget_connection, the get_variable(key, team_name) signature, asyncio_default_fixture_loop_scope = "function", the async_db_engine and client fixtures (added by #73554) and client.portal disposal, the with TestClient core fixtures, test_session.py's dispose call, event_loop_queries, the strict-xfail handling of the known-offload file, InProcessExecutionAPI(triggerer_id=…), breeze verify and its untracked-file check, the AGENTS.md#coding-standards anchor, both in-file anchors of the references, the full-entity select in MetastoreBackend._aget_asset_state_store, and the titles and states of all twelve linked PRs and the four linked review comments. No tests ran: the PR adds none and changes no code.


Inspect mapper loading too: `select(TaskInstance)` also loads its joined `dag_run`. Column projections avoid both unused database fields and entity hydration; they also prevent response access from triggering lazy SQL. `load_only` still constructs entities and is useful only when consumers actually need them.

Replacing `session.get(TaskInstance, id)` with a column select changes which attempts are visible: primary-key lookups bypass the session hook that hides archived attempts, and a select filtered on `TaskInstance.id` does not (see the `TaskInstance` docstring). Write the intended `working_set` predicate into the query rather than relying on either behavior.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[warning] A working_set predicate cannot bring archived attempts back; only include_all_attempts can.

The paragraph is right that session.get(TaskInstance, id) sees archived attempts and a select on TaskInstance.id does not. The remedy it gives ("write the intended working_set predicate into the query") only works in one direction. The session hook adds working_set IS TRUE to every ORM select unless the statement carries the include_all_attempts execution option (_restrict_to_current_attempts), so a query that adds .where(TaskInstance.working_set.is_(None)), or no predicate at all, still returns no archived row.

For a pure migration that replaces session.get and has to keep its visibility (the 410-versus-404 branch in the heartbeat route depends on it), the statement needs .execution_options(include_all_attempts=True), as the converted heartbeat already does (task_instances.py#L1323). Suggested wording: "To keep session.get's visibility, add .execution_options(include_all_attempts=True); to restrict to live attempts, rely on the hook or filter working_set explicitly."


Run existing HTTP contract tests before and after the change, including supported Execution API versions. Preserve assertions; adapt async session mocks and fixtures where needed instead of requiring test source to remain byte-identical. Use spec/autospec and awaited mocks for coroutine methods, normal mocks for buffered result accessors. Add regressions only for behavior introduced or endangered by this conversion, including failure paths; reuse existing coverage for old behavior. An awaited-call assertion (`mock.patch.object(AsyncSession, "scalar", autospec=True)` plus `assert_awaited_once()`) adds signal only for a route whose handler calls the session directly; a route already exercised by DB-backed contract tests gains coupling, not coverage, from it.

Run [`test_event_loop_blocking.py`](https://github.com/apache/airflow/blob/main/airflow-core/tests/unit/api_fastapi/test_event_loop_blocking.py) in Breeze. Its static check covers explicit offloads throughout `api_fastapi`. Its runtime sweep sends generic requests to core API and UI routes in both team modes. For a changed path the sweep misses, including Execution API routes, reuse the `event_loop_queries` fixture with a valid route-specific request. Assert the HTTP result and that the fixture recorded no synchronous SQL on the event loop.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[nit] The runtime sweep has its own known-offender list, and a conversion has to edit it.

The offload section explains ALLOWED_OFFLOADS and known_api_server_threadpool_offloads.txt, but this paragraph does not mention known_sync_db_on_event_loop.txt, which lists 21 core API routes as strict xfails today. Converting one of them makes test_known_route_no_longer_blocks fail until its line is deleted, and the file is the nearest thing to a to-do list for this migration. One sentence would do: "delete the route's line from known_sync_db_on_event_loop.txt in the same PR, and pick the next route from it".

1. Select only the columns the response uses.
2. Unpack rows as tuples (`.tuples()`), or use `scalars()` for a single column, and build the response directly; per-row `Row` attribute access and temporary containers add up across thousands of rows.
3. For results that grow with data, stream them and process each partition as it arrives, so the loop regains control between partitions: `result = await session.stream(statement.execution_options(yield_per=500))`, then `async for partition in result.tuples().partitions()`. This uses a server-side cursor, so consume it fully before the next statement on the session, run the contract tests on PostgreSQL and MySQL, and repeat the stall measurement on PostgreSQL, since each partition adds a database round trip.
4. Use the profile to isolate the remaining CPU work. For large JSON reads, measure decoding, model construction, and rendering together because recursive `JsonValue` validation can dominate. If the data already satisfies the response contract, consider returning a `JSONResponse` and retaining `response_model=` in the route decorator. Compare `/openapi.json?version=<v>` for every API version, and confirm no `convert_response_to_previous_version_for` targets the model. Cadwyn decodes and re-encodes a returned `JSONResponse` body on the loop (cadwyn#51) and double-encodes a plain `Response` with an `application/json` content type. If the remaining cost warrants a worker fallback, compare event-loop delay and request latency under concurrent load with and without it. Pass detached data to the worker when it only needs to render the response. See [the XCom example](references/xcom-conversion.md).

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[nit] cadwyn#51 does not look like the reference for the JSONResponse re-encode.

zmievsa/cadwyn#51 is "Optimize request migration for migration-less cases" (closed): it is about request migration, not about decoding and re-encoding a returned JSONResponse body. Either point to the issue or source lines that describe the response path, or drop the number and keep the measured statement from the XCom reference.


## GET worker boundaries

The default `BaseStoreBackend.aget_value` awaits `aget`, then runs `json.loads` in a worker with `asyncio.to_thread`. Backends that return native values can override `aget_value` and skip that decode. The GET route separately constructs and validates `TaskStateStoreResponse` with `run_in_threadpool`. FastAPI still serializes the response on the event loop.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[warning] "GET worker boundaries" describes #75381 in the present tense, and that PR is still open.

SKILL.md opens with "Use the current checkout as the source of truth" and, at line 54, sends the reader here for the model ALLOWED_OFFLOADS entry. On main none of what this section states exists yet:

An agent that follows the skill before #75381 merges looks for an example that is not in its checkout, and if review changes the shape of #75381 this text goes stale without anyone touching it. Either merge this after #75381, or word the section as "as proposed in #75381" and keep the present tense for what is on main. (Same point in comment [5] for the XCom reference.)


# XCom conversion evidence

See [the reviewed XCom conversion](https://github.com/apache/airflow/pull/75396) for the split after the offload check landed. Ordinary lookups use the async driver. The Dag-aware fallback and three JSON renderers have documented offload entries. The conversion returns its read-only connection before waiting for either kind of worker call. The PR compares the alternatives under concurrency and reports the cost for requests that need Dag-aware resolution.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[warning] Same as comment [4]: the opening paragraph and "the kept form" below describe #75396, which is open.

On main every XCom route is still synchronous (xcoms.py#L568), so "Ordinary lookups use the async driver", "three JSON renderers have documented offload entries" and "Each now queries in a short create_session_async() session of its own" describe a branch, not the repository the skill ships in. "The reviewed XCom conversion" also reads as settled while its review is ongoing. The measurements are useful as they are; the framing needs either the merge order (after #75396) or "proposed in" wording.


## Historical benchmark

These measurements cover the earlier conversion in commit `b265496e2c`, measured as patches on base `8cc830d4ef`. The GET offload variant combined decoding and model construction in one worker call.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[nit] The measured revision cannot be looked up from this repository.

Commit b265496e2c does not resolve in apache/airflow (the commits API answers "No commit found for SHA"), and 2610/async-xcoms in the XCom reference is a fork branch name. The bases (8cc830d4ef, fe589528ee) are on main and fine. Since the numbers are presented as evidence, link the PR commit they were taken at (a full SHA under /pull/75381/commits/… stays reachable) or say plainly that the revision is no longer available.

@Dev-iL
Dev-iL force-pushed the 2609/endpoint-conversion branch from 73e27e9 to 5dc1051 Compare November 24, 2026 09:22
@Dev-iL
Dev-iL marked this pull request as ready for review November 24, 2026 09:32
@github-actions github-actions Bot added fork ci required Gated by AIP-120: CI must pass in the contributor's fork. Managed by the fork CI reconciler. ready for maintainer review Set by triage when all criteria pass, or by the fork CI reconciler when fork CI is green. labels Nov 24, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Fork CI: green. CI for the latest commit passed in your fork. The pull request is ready for maintainer review.

Pull requests from contributors run their CI in the contributor's own fork. GitHub Actions is free and has no minute limit on public forks, while the CI capacity of the Apache Software Foundation is shared by every ASF project and is finite.

Fork CI tested this branch merged with main at 8c6adb23be, as project CI would, 0 commits behind main when the run turned green.

Latest run: https://github.com/Dev-iL/airflow/actions/runs/45364599020

How this works: CI in your fork.


This comment was posted automatically by the fork CI monitor from templates drafted with an AI-assisted tool, so it may contain mistakes. An Apache Airflow maintainer, a real person, will review the pull request once its fork CI is green. Why the first pass is automated.

@mergeable

mergeable Bot commented Nov 24, 2026

Copy link
Copy Markdown

❌ Error Occurred while executing an Action

If you believe this is an unexpected error, please report it on our issue tracker: https://github.com/mergeability/mergeable/issues/new

Error Details

HttpError: Not Found

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

fork ci required Gated by AIP-120: CI must pass in the contributor's fork. Managed by the fork CI reconciler. 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.

2 participants