Skip to content

Cancel the Dataflow job when a user kills the deferred task - #69586

Merged
shahar1 merged 6 commits into
apache:mainfrom
steveahnahn:dataflow-cancel-job-on-user-kill-deferred
Oct 17, 2026
Merged

shahar1 merged 6 commits into
apache:mainfrom
steveahnahn:dataflow-cancel-job-on-user-kill-deferred

Conversation

@steveahnahn

@steveahnahn steveahnahn commented Jul 8, 2026 •

Copy link
Copy Markdown
Contributor

Problem

  • Killing a deferred Dataflow task (mark failed, clear, mark success) leaves the Dataflow job running and billing in GCP.
  • Neither TemplateJobStartTrigger (templated/flex jobs) nor DataflowStartYamlJobTrigger (YAML jobs) has on_kill; the BigQuery and Dataproc triggers in this provider already cancel in the same situation.
  • The YAML operator's own on_kill even documents the gap: it "will not be called if a task instance is killed in a deferred state."
  • A streaming job runs until someone notices it in the Cloud console.

Change

  • Add on_kill to both TemplateJobStartTrigger and DataflowStartYamlJobTrigger: checks cancel_on_kill, job_id, project_id, then cancels via the sync DataflowHook. Identical cancel path in both.
  • drain_pipeline is honored, matching the non deferred kill path.
  • Hook is constructed and invoked inside a worker thread (sync_to_async): DataflowHook resolves its connection eagerly at construction, which must not run in the triggerer event loop. Construction inside the try means a connection error is logged, not raised.
  • Fires only on user kill, never on triggerer restart, redistribution, or timeout.

End to end verification

  1. Deferrable operator launched the job; task deferred, job JOB_STATE_RUNNING.
deferred task, job running
  1. Marked the task failed from the UI.
marking the deferred task failed
  1. Triggerer log, no exception escaping on_kill:
Trigger cancelled by user action, invoking on_kill
Stopping Dataflow job. Project ID: <redacted>, Location: us-central1, Job ID: 2026-07-08_21_43_34-418737444659630262, drain: False
  1. Job went JOB_STATE_RUNNING -> JOB_STATE_CANCELLING -> JOB_STATE_CANCELLED (gcloud dataflow jobs list). With cancel_on_kill=False the job keeps running.

The YAML trigger uses the identical DataflowHook.cancel_job path proven above, so the e2e run covers its cancel mechanism; it is additionally unit tested.

Tests

  • on_kill tests for both triggers: cancel, drain_pipeline honored, no ops (cancel_on_kill=False, missing job_id/project_id), hook errors swallowed, hook construction errors swallowed; plus operator threading of drain_pipeline into the trigger.
  • All new assertions fail without the change; 95 trigger tests pass with it; provider mypy clean.

Was generative AI tooling used to co-author this PR?
  • Yes, Claude Code (Opus 4.8)

Generated-by: Claude Code (Opus 4.8) following the guidelines

@boring-cyborg boring-cyborg Bot added area:providers provider:google Google (including GCP) related issues labels Jul 8, 2026
@steveahnahn
steveahnahn force-pushed the dataflow-cancel-job-on-user-kill-deferred branch 2 times, most recently from cadba9a to f4df591 Compare July 8, 2026 06:46
@steveahnahn
steveahnahn marked this pull request as ready for review July 8, 2026 21:02
@steveahnahn
steveahnahn requested a review from shahar1 as a code owner July 8, 2026 21:02
@steveahnahn
steveahnahn force-pushed the dataflow-cancel-job-on-user-kill-deferred branch from f4df591 to 6e7fa45 Compare July 10, 2026 23:05
@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 Jul 11, 2026

@aaron-y-chen aaron-y-chen 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.

Hi, thanks for the PR, very impressive :)

@steveahnahn
steveahnahn force-pushed the dataflow-cancel-job-on-user-kill-deferred branch 2 times, most recently from 54df2f5 to bd3f1bb Compare July 16, 2026 02:05

@shahar1 shahar1 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.

AI Review

Thanks for the careful end-to-end check. The approach fits how the BigQuery and Dataproc triggers already work: the trigger cancels only on user kill through BaseTrigger.on_kill, and the operators pass cancel_on_kill through. Two issues need a fix before merge:

  • on_kill does nothing when project_id comes from the connection, which is the default.
  • _stop_job can block the triggerer's shared sync_to_async thread until the Dataflow job reaches a terminal state.

on_kill silently skips the cancel when project_id comes from the connection (triggers/dataflow.py:118, :406)

All three operators default to project_id=PROVIDE_PROJECT_ID, which is None, and pass self.project_id to the trigger unchanged. run() handles None by falling back to the connection's project. The new if not self.cancel_on_kill or not self.job_id or not self.project_id: return does not. So users who rely on the connection's default project get no cancel on a deferred kill, and no log line either, because the return comes before the log. DataflowHook.cancel_job is already decorated with @GoogleBaseHook.fallback_to_default_project_id, so you can drop the project_id check. The BigQuery and Dataproc on_kill implementations check only job_id. The no-project-id case in test_on_kill_does_not_stop_the_job currently locks this behaviour in, so it should become a positive test.

_stop_job blocks the shared sync_to_async thread (triggers/dataflow.py:144, :432)

on_kill() is given a bounded time to complete. Implementations that call slow external APIs should apply their own timeouts rather than relying on the framework bound.

(from the BaseTrigger.on_kill docstring, airflow-core/src/airflow/triggers/base.py)

DataflowHook.cancel_job calls _DataflowJobsController.cancel(). That method sends the cancel/drain request first. Then, because cancel_timeout is set (default 300), it waits in with timeout(...) for _wait_for_states({CANCELLED, DRAINED}). That loop runs _refresh_jobs() and time.sleep(poll_sleep) and has no bound of its own. The timeout does nothing off the main thread: TimeoutPosix.__enter__ catches the ValueError from signal.signal, logs "TimeoutPosix requires signal.SIGALRM and the main thread. Proceeding without a timeout." and continues. So the poll runs until the job is CANCELLED or DRAINED. A cancel usually takes a minute or more. A streaming drain can take much longer. If the job never reaches either state, the poll never ends.

This has two effects:

  • sync_to_async uses thread_sensitive=True by default, and the triggerer sets up no ThreadSensitiveContext. So every such call in the triggerer process runs on asgiref's one shared SyncToAsync.single_thread_executor. While the poll runs, every sync_to_async call from other triggers in that triggerer waits behind it (for example the Dataproc, BigQuery and Cloud SQL triggers in this provider). I checked this in isolation with asgiref 3.12.1. A blocking call on that executor delayed an unrelated sync_to_async call until the blocking call finished, even after the awaiting coroutine had timed out.
  • The triggerer runs on_kill() inside asyncio.wait_for(..., timeout=[triggerer] on_kill_timeout), which is 30s by default. A cancel usually takes longer than that. The triggerer then logs on_kill() timed out, and Dataflow job %s stopped. is never logged, but the thread keeps polling.
  • Cancels can be lost. Take a user who marks failed a run with several deferred Dataflow tasks. The first on_kill occupies the shared thread, and the other on_kill calls wait in the queue behind it. When their 30s wait_for expires, asgiref cancels the queued work items before they start. Those cancel requests are never sent. The only trace is an on_kill() timed out warning, and those jobs keep running.

The first cancel/drain request goes out before the wait, so the wait adds nothing inside on_kill. If you build the hook with cancel_timeout=None, cancel() skips _wait_for_states completely (if self._cancel_timeout and isinstance(self._cancel_timeout, int)). on_kill then sends the request and returns, like the BigQuery and Dataproc triggers. See the inline suggestions. Two related changes:

  • Dataflow job %s stopped. should then say that a cancel was requested.
  • test_on_kill_stops_the_job in both test classes should assert cancel_timeout=None.

Smaller observations

  • operators/dataflow.py:301, :537, :715: the new cancel_on_kill docstrings say the job is cancelled "for a deferred task, while it waits in the triggerer". BaseTrigger.on_kill exists only in Airflow 3.3+, and this provider supports apache-airflow>=2.11.0. On older versions, killing a deferred task still leaves the job running. This PR also removes the "does not work … in the deferrable mode" caveat from the YAML drain_pipeline doc. You could add "(Airflow 3.3+)" to these docstrings and to the YAML operator's on_kill docstring. Alternatively, add the legacy path the BigQuery and Dataproc triggers use for older versions: cancel in run()'s except asyncio.CancelledError, gated by AIRFLOW_V_3_3_PLUS and safe_to_cancel().
  • The Flex operator now passes drain_pipeline into TemplateJobStartTrigger, but only the YAML operator has a test for this (test_deferrable_threads_drain_pipeline_into_trigger). AGENTS.md: "Every changed or added behaviour must have a test".
  • Nits in the new trigger tests: they call asyncio.run(trigger.on_kill()), while the rest of the file uses @pytest.mark.asyncio with await. They also patch DataflowHook without autospec=True (AGENTS.md: "Use spec/autospec when mocking.").
  • Optional: on_kill and _stop_job are the same in both triggers. A shared helper would keep the two copies from drifting apart.

This review was drafted by an AI-assisted tool and
confirmed by an Apache Airflow maintainer. After you've
addressed the points above and pushed an update, an Apache Airflow
maintainer — a real person — will take the next look
at the PR. The findings cite the project's review criteria;
if you think one of them is mis-applied, please reply on the
PR and a maintainer will weigh in.

More on how Apache Airflow handles maintainer review:
contributing-docs/05_pull_requests.rst.

Killing a deferred Dataflow task (mark-failed, clear or mark-succeeded)
leaves the Dataflow job running: the trigger has no on_kill, so the
user-kill cancellation the sibling BigQuery and Dataproc triggers
already perform never happens, and a streaming pipeline keeps running
and billing until someone notices in the Cloud console. Before the
Airflow 3.3 trigger cancellation redesign the legacy path cancelled the
job from inside the trigger, so this is also a behavior regression for
deferrable users.

Implement on_kill on TemplateJobStartTrigger following the merged
BigQuery/Dataproc/EMR pattern, honoring the operator's drain_pipeline
setting so streaming jobs are drained rather than cancelled when
configured, exactly as the non-deferred kill path does. The hook is
built and invoked inside a worker thread because the synchronous
DataflowHook resolves its connection during construction, which must
not run in the triggerer's event loop.
@steveahnahn
steveahnahn force-pushed the dataflow-cancel-job-on-user-kill-deferred branch from 56c4223 to 426400a Compare October 2, 2026 17:11
@shahar1
shahar1 dismissed their stale review October 17, 2026 18:53

Concerns addressed

@shahar1

shahar1 commented Oct 17, 2026

Copy link
Copy Markdown
Contributor

@steveahnahn Sorry that it took a while to approve, great work!

@shahar1
shahar1 merged commit a5c2806 into apache:main Oct 17, 2026
87 checks passed
@shahar1 shahar1 mentioned this pull request Oct 20, 2026
6 of 7 tasks
SameerMesiah97 pushed a commit to SameerMesiah97/airflow-oss-sm97 that referenced this pull request Oct 27, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:providers provider:google Google (including GCP) related issues 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.

4 participants