ephraimbuddy commented on code in PR #76303:
URL: https://github.com/apache/airflow/pull/76303#discussion_r4709783890
##########
airflow-core/src/airflow/jobs/scheduler_job_runner.py:
##########
@@ -2181,6 +2734,11 @@ def _run_scheduler_loop(self) -> None:
# are picked up each iteration without requiring a scheduler
restart.
self._dag_id_to_team_name = {}
with stats.timer("scheduler.scheduler_loop_duration") as timer:
+ if self._route_dag_processor_callbacks_enabled:
+ with create_session() as session:
+ # Ahead of the tasks that would take the free executor
slots.
+ self._route_dag_processor_callbacks(session=session)
Review Comment:
I measured 50 transactions per case after one warm-up, using one scheduler
and a mock executor. The timings include commit.
| Scenario | SQL statements | Median | p95 |
| --- | ---: | ---: | ---: |
| Routing off, idle maintenance | 1 | 0.71 ms | 1.09 ms |
| Routing on, empty queue | 1 | 0.61 ms | 0.75 ms |
| Routing on, eight waiting callbacks | 41 | 19.96 ms | 36.00 ms |
With routing off, there’s also one query at scheduler startup to hand back
waiting callbacks. That accounts for the difference in the isolated startup
test (38 queries here, 37 on upstream).
##########
airflow-core/src/airflow/api_fastapi/execution_api/routes/callbacks.py:
##########
@@ -58,39 +110,207 @@ def run_callback(
response: Response,
session: SessionDep,
services=DepContainer,
+ body: CallbackRunPayload | None = None,
+ prefer: Annotated[str | None, Header()] = None,
) -> None:
- """Exchange a single-use callback token for a short-lived execution
token."""
- callback = session.get(Callback, callback_id, with_for_update=True)
- if callback is None:
+ """
+ Exchange a single-use callback token for a short-lived execution token.
+
+ An attempt that identifies itself can repeat its own exchange, as when it
never got the response,
+ and gets a new execution token. Any other exchange of a callback that
already started is refused,
+ including a second delivery of its workload.
+
+ A deadline worker can request heartbeats with ``Prefer:
callback-heartbeat``. When enabled,
+ the response returns its worker timeout in seconds in
``Airflow-Callback-Heartbeat-Timeout``.
+ """
+ callback = _get_callback(callback_id, session=session, for_update=True)
+ started_by = body.model_dump(mode="json") if body is not None else None
+ heartbeat_timeout = (
+ _get_callback_heartbeat_timeout()
+ if (
+ started_by is not None
+ and prefer == "callback-heartbeat"
+ and callback.fetch_method == CallbackFetchMethod.IMPORT_PATH
+ and callback.data.get(HEARTBEAT_SUPPORTED_KEY)
+ )
+ else None
+ )
+ if not callback.try_start(
+ timezone.utcnow(), started_by=started_by,
heartbeat_timeout=heartbeat_timeout, session=session
+ ):
+ callback = _get_callback(callback_id, session=session, for_update=True)
+ if callback.state == CallbackState.QUEUED and callback.state_deadline
is not None:
+ raise HTTPException(
+ status_code=status.HTTP_409_CONFLICT,
+ detail={
+ "reason": "start_deadline_passed",
+ "message": f"Callback {callback_id} had to start by
{callback.state_deadline.isoformat()}",
+ },
+ )
+ if callback.state != CallbackState.RUNNING or started_by is None or
callback.started_by != started_by:
+ raise HTTPException(
+ status_code=status.HTTP_409_CONFLICT,
+ detail={
+ "reason": "invalid_state",
+ "message": (
+ f"Callback {callback_id} is in state {callback.state};
its token can only be "
+ "exchanged once while QUEUED."
+ ),
+ "previous_state": callback.state,
+ "worker_is_monitored": callback.state_deadline is not None,
+ },
+ )
+ # A retry whose first response was lost repeats the original
negotiation.
+ if callback.fetch_method == CallbackFetchMethod.IMPORT_PATH and
callback.state_deadline is not None:
+ heartbeat_timeout = _get_callback_heartbeat_timeout()
+ _renew_callback_heartbeat(callback_id, heartbeat_timeout,
session=session)
+ else:
+ heartbeat_timeout = None
+
+ if heartbeat_timeout is not None:
+ response.headers["Airflow-Callback-Heartbeat-Timeout"] =
str(int(heartbeat_timeout.total_seconds()))
+ # A routed callback doesn't heartbeat, so its token must last until it
reports its outcome.
+ timeout = callback.data.get(EXECUTION_TIMEOUT_KEY)
+ issue_execution_token(
+ services,
+ response,
+ sub=str(callback.id),
+ claims=_get_identity_claims(callback, session=session),
+ min_valid_for=get_callback_report_window(timeout) if timeout else None,
+ )
Review Comment:
I’d keep routed heartbeats for a follow-up. Today the worker enforces the
execution timeout, and its token stays valid long enough to report the outcome.
The tradeoff is that a lost worker can occupy its slot until the reporting
window expires. I’d change worker renewal and token lifetime together.
##########
task-sdk/src/airflow/sdk/execution_time/execute_workload.py:
##########
@@ -99,7 +102,11 @@ def main():
log.error("Failed to parse input JSON string", error=str(e))
sys.exit(1)
- execute_workload(workload)
+ try:
+ execute_workload(workload)
+ except CallbackAlreadyStartedError:
+ # A container executor must distinguish a duplicate delivery from the
admitted worker's failure.
+ sys.exit(os.EX_TEMPFAIL)
Review Comment:
I kept the routed opt-in because older ECS executors can run deadline alerts
but drop the original task’s IAM and network overrides on a routed callback.
Workload-type support alone would admit those versions.
The docs now explain exit code 75. It means the API declined this delivery
because the callback had already started or its start deadline had passed. The
executor drops the delivery and leaves the callback’s outcome alone. I’ve
deferred the shared `BaseExecutor` result hook, so the providers still handle
that exit code locally.
--
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]