Repository navigation
Add deferrable mode to SFTPOperator - #72336
Conversation
closes: apache#65475 Co-authored-by: Copilot <[email protected]>
721747c to
210549e
Compare
- 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]>
|
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 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. |
…irectory and warn on missing DELETE target
…ated SFTPOperationError
b5d1c49 to
c5c00b3
Compare
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.
potiuk
left a comment
There was a problem hiding this comment.
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, andremote_fp/local_fpare both in scope in the loop.operators/sftp.py:125and: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 saysSFTPOperatorTrigger, the PR description saysSFTPOperationTrigger, and the class isSFTPTransferTrigger. Relatedly, the successTriggerEventcarries nomessagekey, so"Deferrable SFTP transfer completed: %s"logsNone.- 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 oftests/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.rstdirectly — though perproviders/AGENTS.mdthe release manager regenerates most of it fromgit 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
left a comment
There was a problem hiding this comment.
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
isdirexactly 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. confirmandprefetchare threaded through tostore_file/retrieve_fileinstead of being accepted and dropped.create_intermediate_dirswith a bare filename works —Path(os.path.dirname(local))resolves to.rather than raising the wayos.makedirs("")did.- The idle outer connection is gone.
sftp_hook's connection is honoured viaself.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 inretrieve_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.
983d2dc to
7e76fb2
Compare
potiuk
left a comment
There was a problem hiding this comment.
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
Co-authored-by: Jarek Potiuk <[email protected]>
Add deferrable mode to
SFTPOperatorcloses: #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
SFTPOperatorgains adeferrable=Trueparameter. The worker slot is released while the transfer runs and reclaimed when it finishes. The transfer itself is performed in the Triggerer by a newSFTPTransferTriggerdrivingSFTPHookAsync.The
deferrableflag is meant to be transparent: the same arguments produce the same outcome as the synchronous path, including directory transfers, deletes of missing files,confirm,prefetchandcreate_intermediate_dirs. The one documented difference is howconcurrencyis applied (see below).As part of this, the synchronous GET / PUT / DELETE logic that lived in the operator moved into
SFTPHook.transfer(), so the synchronousexecute()path and the trigger share one authoritative implementation each side.Changes
providers/sftp/hooks/sftp.pySFTPOperationenum (GET,PUT,DELETE) moved here fromoperators/sftp.pyso 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'sexecute()delegates to it.SFTPHookAsyncgains the operations the trigger needs:transfer(),isdir(),path_exists(),create_directory(),delete_file(),delete_directory(),get_tree_map(),retrieve_directory()andstore_directory(), plusconfirm/prefetchsupport onstore_file()/retrieve_file().SFTPHookAsync.get_managed_conn(): a reference-counted managed connection mirroring the synchronous hook.handle_connection_managementnow 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.pathlib, which does no I/O.FileExistsError.aiofilesdependency is dropped: the asyncretrieve_file()now delegates to asyncssh's ownget().providers/sftp/operators/sftp.pydeferrable: bool = Falseparameter.execute()performs the same validation as before and, for the synchronous path, callssftp_hook.transfer().deferrable=True,execute()resolves the connection id fromssh_conn_idor the suppliedsftp_hook, raisesValueErrorif neither carries one, and defers toSFTPTransferTrigger.execute_complete()resumes after the trigger fires and returnslocal_filepath, or raises if the trigger reported an error.providers/sftp/triggers/sftp.pyBaseSFTPTriggerfactors out the async hook construction shared bySFTPTriggerand the new trigger.SFTPTransferTriggercallsSFTPHookAsync.transfer()and yields aTriggerEventwith{"status": "success" | "error", "message": ...}.providers/sftp/exceptions.pySFTPOperationError, raised by the synchronous path when a transfer fails.Tests
SFTPHookAsyncmethod,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.execute_complete()success and error, the supplied-sftp_hookconnection id being honoured, and the missing-connection-id error.run()success and error events.Connection and concurrency semantics in deferrable mode
The whole
transfer()call runs over one connection.concurrencybounds 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
Was generative AI tooling used to co-author this PR?
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
{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.