Skip to content

Add deferrable mode to SFTPOperator - #72336

Merged
potiuk merged 31 commits into
apache:mainfrom
dabla:sftp-deferrable-clean
Sep 21, 2026
Merged

potiuk merged 31 commits into
apache:mainfrom
dabla:sftp-deferrable-clean

Conversation

@dabla

@dabla dabla commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

Add deferrable mode to SFTPOperator

closes: #65475

Credits

This PR is a revival of the original work by SunilKumarReddy (@sunildataengineer) in apache/airflow#68298, which was closed without being merged. All credit for the original design and initial implementation belongs to the original author. This PR also replaces another attempt made by @tannnmayy.

Summary

SFTPOperator gains a deferrable=True parameter. The worker slot is released while the transfer runs and reclaimed when it finishes. The transfer itself is performed in the Triggerer by a new SFTPTransferTrigger driving SFTPHookAsync.

The deferrable flag is meant to be transparent: the same arguments produce the same outcome as the synchronous path, including directory transfers, deletes of missing files, confirm, prefetch and create_intermediate_dirs. The one documented difference is how concurrency is applied (see below).

As part of this, the synchronous GET / PUT / DELETE logic that lived in the operator moved into SFTPHook.transfer(), so the synchronous execute() path and the trigger share one authoritative implementation each side.

Changes

providers/sftp/hooks/sftp.py

  • SFTPOperation enum (GET, PUT, DELETE) moved here from operators/sftp.py so the hook, operator and trigger can all import it without a circular dependency. It is still importable from the operator module.
  • SFTPHook.transfer(): synchronous dispatcher for GET / PUT / DELETE handling single files and directories, including the concurrent directory variants. The operator's execute() delegates to it.
  • SFTPHookAsync gains the operations the trigger needs: transfer(), isdir(), path_exists(), create_directory(), delete_file(), delete_directory(), get_tree_map(), retrieve_directory() and store_directory(), plus confirm / prefetch support on store_file() / retrieve_file().
  • SFTPHookAsync.get_managed_conn(): a reference-counted managed connection mirroring the synchronous hook. handle_connection_management now wraps coroutine methods too, so nested hook calls share one SSH connection and a whole deferred transfer, files and directory trees alike, runs over a single connection. That is the resource that matters in the Triggerer, where many deferred tasks share one process.
  • Directory walks run in a worker thread so they never block the Triggerer event loop; relative paths are computed with pathlib, which does no I/O.
  • An existing target path in the async directory methods raises FileExistsError.
  • The unused aiofiles dependency is dropped: the async retrieve_file() now delegates to asyncssh's own get().

providers/sftp/operators/sftp.py

  • New deferrable: bool = False parameter.
  • execute() performs the same validation as before and, for the synchronous path, calls sftp_hook.transfer().
  • With deferrable=True, execute() resolves the connection id from ssh_conn_id or the supplied sftp_hook, raises ValueError if neither carries one, and defers to SFTPTransferTrigger.
  • execute_complete() resumes after the trigger fires and returns local_filepath, or raises if the trigger reported an error.

providers/sftp/triggers/sftp.py

  • BaseSFTPTrigger factors out the async hook construction shared by SFTPTrigger and the new trigger.
  • SFTPTransferTrigger calls SFTPHookAsync.transfer() and yields a TriggerEvent with {"status": "success" | "error", "message": ...}.

providers/sftp/exceptions.py

  • New SFTPOperationError, raised by the synchronous path when a transfer fails.

Tests

  • Async hook: coverage for every new SFTPHookAsync method, transfer() dispatch for all three operations, directory downloads and uploads, path-traversal rejection, missing-file delete, and tests asserting that a directory transfer opens exactly one connection and that nested calls share it.
  • Operator: deferral, execute_complete() success and error, the supplied-sftp_hook connection id being honoured, and the missing-connection-id error.
  • Trigger: run() success and error events.

Connection and concurrency semantics in deferrable mode

The whole transfer() call runs over one connection. concurrency bounds how many top-level paths are in flight on that connection at once; files inside a directory are transferred sequentially. The synchronous path differs there: it opens one connection per worker and transfers directory contents concurrently. For bulk transfers of many files where per-connection throughput matters, the synchronous concurrent path remains the better fit.

Usage

from airflow.providers.sftp.operators.sftp import SFTPOperator, SFTPOperation

upload = SFTPOperator(
    task_id="upload_report",
    ssh_conn_id="sftp_default",
    local_filepath="/tmp/report.csv",
    remote_filepath="/uploads/report.csv",
    operation=SFTPOperation.PUT,
    deferrable=True,  # worker slot freed while the transfer runs
)

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

GitHub Copilot (Claude Sonnet 4.6) for the initial revival; Claude Code (Claude Fable 5.1) for the review follow-ups.

Generated-by: GitHub Copilot (Claude Sonnet 4.6) and Claude Code (Claude Fable 5.1) 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.

@dabla
dabla requested a review from potiuk August 31, 2026 15:32
@dabla
dabla force-pushed the sftp-deferrable-clean branch from 721747c to 210549e Compare August 31, 2026 15:36
@dabla dabla self-assigned this Aug 31, 2026
@dabla dabla mentioned this pull request Aug 31, 2026
1 task done
- Fix circular import: SFTPOperationTrigger now imported lazily inside
  execute() so operators -> triggers -> hooks is a clean DAG with no cycle
- Fix triggers/sftp.py to import SFTPOperation from hooks (where it lives)
  instead of operators, fully breaking the circular dependency
- Wire up self.defer() in execute() when deferrable=True — the call was
  missing so deferrable mode never actually deferred
- Apply conf.getboolean('operators', 'default_deferrable') as the default
  for the deferrable parameter, matching Airflow convention
- Remove paramiko<5.0.0 upper cap: paramiko 5.0.0 is already in uv.lock
  and the cap caused pip check failures in the CI image build
- Remove asgiref dependency: it was added by the original PR but is not
  imported anywhere in the provider source

Co-authored-by: Copilot <[email protected]>
@sunildataanalytics

Copy link
Copy Markdown

Hi @dabla, thanks so much for picking this up and pushing it forward. I originally worked on the deferrable mode for SFTPOperator, and I know firsthand how complex it was to get right.

This feature is really important to me and to the Airflow community. Here's why:

Deferrable operators free up worker slots during long I/O operations, which is huge for production Airflow instances where resources are tight
For users transferring large files over SFTP, this means they can run more tasks in parallel without spinning up more workers — better cost efficiency
The refactoring you did to share transfer logic between sync and async paths is exactly the right approach — it eliminates bugs and makes maintenance easier going forward

I faced a lot of challenges getting the original implementation right — edge cases around directory traversal, async error handling, concurrency limits. Your version looks solid and well-tested.

I'd really appreciate if this could get merged soon. I know there are a lot of PRs in the queue, but this feature unlocks better resource utilization for anyone doing file transfers in their Airflow DAGs, which is a pretty common use case.

Thanks for sticking with this and making it production-ready. The Airflow ecosystem needs more operators like this.

@dabla
dabla force-pushed the sftp-deferrable-clean branch from b5d1c49 to c5c00b3 Compare September 3, 2026 12:48
SFTPTrigger and the operator's deferred transfer trigger duplicated
connection/hook setup and, in SFTPTrigger's case, embedded file-sensing
logic directly in the trigger's run loop. Move that sensing logic into
SFTPHookAsync (sense_files_by_pattern/sense_path) so triggers stay thin
dispatchers, and introduce BaseSFTPTrigger to share sftp_conn_id storage
and hook construction between SFTPTrigger and the renamed
SFTPTransferTrigger (formerly SFTPOperationTrigger).
Providers are released from main and their changelogs are regenerated
from git log by the release manager; per-PR newsfragments are not
consumed for provider distributions.
@dabla
dabla requested a review from potiuk September 9, 2026 14:43

@potiuk potiuk left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Reviving this rather than letting it lapse was the right call, and the credit to the original author is handled well. The refactor that pulls the sync transfer logic into SFTPHook.transfer() is a genuine improvement on its own — the operator's execute() is much easier to follow now, and single-file GET finally honours prefetch.

I also want to say up front that I checked the rewritten _validate_within_directory closely, since directory traversal is the one thing you really don't want to get wrong here: the guard still runs before every mkdir and every write in both sync directory paths, and startswith(base + os.sep) is equivalent to the old commonpath check. No regression there.

My concern is the async side. SFTPOperator's promise with deferrable=True is that the flag is transparent — same arguments, same outcome, just without holding the worker slot. SFTPHookAsync.transfer() is a much thinner implementation than the sync one it stands in for, and the gaps are user-visible.

Sync and async transfer are not equivalent (hooks/sftp.py:1236)

Same operator arguments produce different behaviour depending on deferrable:

sync SFTPHook.transfer async SFTPHookAsync.transfer
GET/PUT of a directory branches on isdir → retrieve_directory / store_directory always retrieve_file / store_file — a directory fails
DELETE of a directory delete_directory(include_files=True) sftp.unlink — fails on a directory
DELETE of a missing file warns and skips raises
confirm, prefetch honoured accepted and silently ignored
create_intermediate_dirs Path("").mkdir() — works for a bare filename os.makedirs("") — raises FileNotFoundError

The DELETE-of-a-missing-file row is the one I'd single out: it silently regresses #62639 ("return a warning instead of an error when file is already absent") for anyone who sets deferrable=True.

The docstring does say deferrable mode is "best suited for single large file transfers", but concurrency and prefetch are still accepted parameters and directories are still accepted paths, so nothing stops a user from hitting these. Either close the gaps or reject the unsupported combinations explicitly at execute() time, so the failure is a clear error rather than a silent difference.

Every deferrable GET/PUT opens an SSH connection it never uses (hooks/sftp.py:1232)

See inline — the outer connection and SFTP client are only used by the DELETE branch; retrieve_file and store_file each open their own. That leaves an idle connection held for the duration of every transfer, in the process where connections are most contended.

Deferrable mode ignores a supplied sftp_hook (operators/sftp.py:177)

sftp_conn_id=self.ssh_conn_id or SFTPHookAsync.default_conn_name falls back to "sftp_default". A Dag passing sftp_hook=SFTPHook(ssh_conn_id="my_prod_sftp") with no ssh_conn_id works today; adding deferrable=True silently redirects it to a different connection.

The new async transfer has no test coverage (hooks/sftp.py:1205)

Every test mocks it out — test_run_success patches SFTPHookAsync.transfer wholesale, and the hook tests add only test_sftp_operation_values. From the testing standards: "Target exactly 100% coverage of what the PR changes… Every changed or added behaviour must have a test; every test must fail without the PR's change." Both points above would have surfaced as tests.

Smaller observations

  • operators/sftp.py:204 — the failure message lost the path. It was "…GET operation from {remote} to {local}, error: …" and is now "…GET operation, error: …"; with a list of filepaths you can no longer tell which one failed, and remote_fp / local_fp are both in scope in the loop.
  • operators/sftp.py:125 and :149 — the # ----- Input validation ----- banner blocks are decorative (and the # don't line up). AGENTS.md: "Comment sparingly — code says what, comments say why… Do not write narrating comments that restate the next line."
  • execute_complete's docstring says SFTPOperatorTrigger, the PR description says SFTPOperationTrigger, and the class is SFTPTransferTrigger. Relatedly, the success TriggerEvent carries no message key, so "Deferrable SFTP transfer completed: %s" logs None.
  • Two unrelated deletions rode along: the v4.1.0 backward-compatibility explanation in get_openlineage_facets_on_start (that one is a real why-comment worth keeping) and a # line from the licence header at the top of tests/unit/sftp/operators/test_sftp.py.
  • Newsfragment removal was right. If you want a user-visible note for the feature, providers take it in providers/sftp/docs/changelog.rst directly — though per providers/AGENTS.md the release manager regenerates most of it from git log, so this is optional.

This review was drafted by an AI-assisted tool and
confirmed by an Airflow maintainer. After you've
addressed the points above and pushed an update, an 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 Airflow handles maintainer review:
contributing-docs/05_pull_requests.rst.


Drafted-by: Claude Code (Opus 5); reviewed by @potiuk before posting

SFTPHookAsync.transfer() only handled single-file GET/PUT and a bare
unlink for DELETE, so deferrable=True silently diverged from the
synchronous SFTPHook.transfer() whenever a directory path was used —
directory GET/PUT was unsupported and DELETE on a directory would
fail. Bring the async path to parity with the sync hook: dispatch to
directory-aware transfers when the source/target is a directory,
warn instead of raising when deleting an already-missing file, honor
prefetch/confirm options, and validate that downloaded paths stay
within the destination directory.

Also drop the idle SSH connection SFTPHookAsync.transfer() kept open
for its whole duration; each helper now opens its own connection like
the rest of the class.
When only sftp_hook (not ssh_conn_id) was provided, deferring silently
fell back to SFTPHookAsync's default connection instead of the hook's
actual connection id, redirecting the deferred transfer to the wrong
server with no warning and a task that still reports success.

@potiuk potiuk left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This is a big step forward. The async transfer() now reads almost line-for-line like the synchronous one, and I checked the specific gaps I raised last time rather than assuming:

  • Directory GET/PUT and directory DELETE now branch on isdir exactly as the sync path does.
  • DELETE of a missing file warns and skips again, so the #62639 behaviour is no longer lost under deferrable=True.
  • confirm and prefetch are threaded through to store_file / retrieve_file instead of being accepted and dropped.
  • create_intermediate_dirs with a bare filename works — Path(os.path.dirname(local)) resolves to . rather than raising the way os.makedirs("") did.
  • The idle outer connection is gone.
  • sftp_hook's connection is honoured via self.ssh_conn_id or self.sftp_hook.ssh_conn_id.
  • Coverage went from nothing to roughly twenty async tests, including seven that drive transfer() itself and one for path traversal in retrieve_directory. That was the point I cared about most, and it is properly addressed.

Two things remain: CI is red, and the directory support introduced a couple of issues of its own.

CI — nine red jobs, four causes

All four are in the two commits that landed after my review, and none look ambient.

Cause Where Jobs
New raise AirflowException hooks/sftp.py:1337, :1363 Static checks
Four mypy errors hooks/sftp.py:961, :1221, :1235; operators/sftp.py:177 MyPy providers checks
pipelined not in the wordlist new retrieve_file docstring Build documentation (spellcheck)
One test cannot construct its hook tests/.../operators/test_sftp.py:725 LowestDeps + all 5 Compat jobs

The AirflowException one is the hard blocker. check-no-new-airflow-exceptions gates this repo-wide, and AGENTS.md is explicit that new direct raise AirflowException(...) usages are not accepted in providers/. The sync methods you mirrored raise it, but those are pre-existing; copying them forward counts as new. This PR already ships SFTPOperationError in providers/sftp/.../exceptions.py, so that or a plain FileExistsError fits both spots.

The mypy Missing return pair (isdir, path_exists) is not a false positive worth silencing: because __aexit__ is typed as possibly suppressing the exception, mypy is right that control can reach the end of the function. A return False after the async with, or restructuring so the result is assigned and returned once, resolves it honestly.

The failing test is the regression test for the sftp_hook fix — which is a shame, because the fix itself is correct. It fails at construction, not in execute(): SSHHook.__init__ resolves the connection eagerly, so SFTPHook(ssh_conn_id="my_prod_sftp") raises AirflowNotFoundException before the operator is even built. It needs the connection to exist — a create_connection_without_db fixture, or monkeypatch.setenv("AIRFLOW_CONN_MY_PROD_SFTP", ...).

store_directory blocks the Triggerer event loop

os.walk() is called directly in an async def. Everything around it is careful — os.path.relpath and Path.mkdir are both pushed through asyncio.to_thread — but os.walk is the one doing real filesystem I/O, and it is the one running inline. In the Triggerer that stalls every other deferred task in the process for the duration of the walk, which is exactly the cost deferrable=True is supposed to avoid.

Worth noting the wrapping is inverted on both sides of this: os.path.relpath is pure string manipulation and gains nothing from a thread, while os.walk genuinely needs one. Moving the walk into asyncio.to_thread (collecting the entries first, then iterating) fixes the real problem.

Directory transfers open one connection per file

retrieve_directory calls get_tree_map (one connection) and then retrieve_file per file, each of which opens its own connection and SFTP client. A thousand-file directory becomes a thousand SSH handshakes, where the sync path does the whole tree over one connection. transfer() adds one more on top, since isdir(remote) is its own connection before the transfer starts.

I want to be fair about how this came about: I asked for the unused outer connection to go, and it did — but the underlying issue is that nothing is shared at all now, and directory support is what makes it bite. A private helper that opens one connection and passes the sftp client down to the per-file work would address both my original point and this one. Not a blocker, but I would rather flag it now than after someone hits it.

concurrency is still ignored in async directory transfers

The sync path dispatches to retrieve_directory_concurrently / store_directory_concurrently with workers=concurrency; the async path has no equivalent, so a Dag passing concurrency=8 gets eight-way parallelism without deferrable and serial transfers with it. The semaphore only bounds the outer per-filepath tasks.

That is a smaller gap than the ones you have closed, but the new docstring now says this method mirrors the sync one "so deferrable=True behaves the same as the synchronous path" — so either the gap closes or the sentence needs to name the exception.

One observation that is not yours to fix

While comparing the two paths: the sync transfer() drops prefetch for directory GETs — self.retrieve_directory(remote, local) with no prefetch=prefetch, while your async version passes it through. That is a pre-existing bug in the sync path that this parity work happens to expose. Please leave it out of this PR; it is worth its own one-liner afterwards.


This review was drafted by an AI-assisted tool and
confirmed by an Airflow maintainer. After you've
addressed the points above and pushed an update, an 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 Airflow handles maintainer review:
contributing-docs/05_pull_requests.rst.


Drafted-by: Claude Code (Opus 5); reviewed by @potiuk before posting

The word "pipelined" is not in the docs spelling wordlist and broke the
documentation build for the SFTP provider. Rewording the prefetch
descriptions is preferable to whitelisting a non-dictionary word.
The async retrieve_directory and store_directory methods copied the
synchronous methods' AirflowException for an existing target path. The
project no longer accepts new direct AirflowException usages, and
FileExistsError names the actual condition.
mypy is right that control can fall out of the async with blocks when a
context manager suppresses an exception, which would return None from a
method typed as returning bool. Assigning the result inside the block and
returning it once after the connection closes makes the return path
explicit instead of silencing the check.
SSHHook resolves its connection eagerly, so the test raised
AirflowNotFoundException before the operator under test was even built.
Defining the connection through the environment keeps the test db-free
and lets it exercise the deferred path it was written for.
…ectory uploads

store_directory walked the local tree inline in a coroutine, stalling every
other deferred task in the Triggerer for the duration of the walk, while the
pure string work around it was needlessly pushed to threads. Collect the walk
in one thread hop and compute relative paths with pathlib, which does no I/O
and keeps the async lint rule satisfied honestly.
The async hook's retrieve_file used aiofiles to stream a remote file into a
local path. It now delegates to asyncssh's own get, and nothing else in the
provider imports aiofiles, so the dependency only added install weight.
A deferred directory transfer opened a fresh SSH connection for the isdir
check, another to walk the tree, and one more per file, so a large directory
cost thousands of handshakes where the synchronous path needs one. Every
operation now has a private helper that works on an already-open SFTP client,
and transfer() opens a single connection per top-level path and passes that
client down, matching the synchronous hook's connection cost.
asyncssh types the destination of get() as PurePath rather than the wider
os.PathLike, so the narrowed str | PathLike value did not type-check.
os.fspath is the exact PathLike contract and leaves strings untouched.
When neither ssh_conn_id nor the supplied sftp_hook carries a connection
id, the deferred path cannot recover: the trigger would silently receive
None. Raising in execute() surfaces the misconfiguration where it can be
fixed, and gives mypy the narrowing it needs without casting.
…s hook

The async hook threaded an open SFTP client through private helpers to avoid
a connection per operation, duplicating every method. The synchronous hook
already solves this with a reference-counted managed connection and a
decorator, so the same decorator now wraps coroutine methods too. Nested
calls reuse the open connection and a whole deferred transfer runs over a
single one, which is the resource that matters in the Triggerer.
The operator used to recognise a missing path through a helper that also
matched an OSError carrying ENOENT. paramiko raises IOError(errno.ENOENT,
text), which Python turns into FileNotFoundError, so catching that class is
sufficient. Covering that exact shape in the test locks the decision in.
@dabla
dabla force-pushed the sftp-deferrable-clean branch from 983d2dc to 7e76fb2 Compare September 17, 2026 12:28
@dabla
dabla requested a review from potiuk September 17, 2026 18:20

@potiuk potiuk left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Third round, and everything from the last one is closed. I verified rather than assumed on the two that matter: the AirflowException count is unchanged in all three files (6/6, 2/2, 0/0), so what remains are permitted verbatim relocations rather than new usages; and the single-connection claim holds up — get_managed_conn is refcounted on both hooks, so the nested decorated calls really do share one connection instead of just saying so in a docstring. The concurrency divergence taking the "document the exception" route is the right call for a first deferrable implementation.

One thing left, and it's my mistake rather than yours. Last round I said the sync transfer() dropping prefetch for directory GETs was pre-existing and asked you to leave it alone. It isn't — SFTPHook.transfer() is new in this PR, so it's in scope after all. Suggestion inline; apologies for the detour.

Approving — the fixup is a one-word change and shouldn't hold this up.


This review was drafted by an AI-assisted tool and
confirmed by an Apache Airflow maintainer. The maintainer
approving this PR has read the findings and signed off. If
something feels off, please reply on the PR and a maintainer
will follow up.

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


Drafted-by: Claude Code (Opus 5); reviewed by @potiuk before posting

@potiuk
potiuk merged commit 2f5d44a into apache:main Sep 21, 2026
90 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add deferrable mode to SFTPOperator

3 participants