[Bug]: Async Python watch_dir immediate stop skips on_exit
Environment
Python SDK 2.62.0, current main 8cc9ed1e30a57d89cefaec112680567d62f21112, Python 3.12.14, macOS. No cloud sandbox is needed for this minimal reproduction.
Reproduction
import asyncio
from e2b import AsyncWatchHandle
async def main():
exit_calls = []
async def events():
await asyncio.Event().wait()
yield
handle = AsyncWatchHandle(events(), lambda event: None, exit_calls.append)
await handle.stop()
print(exit_calls) # [] on current main; expected [None]
asyncio.run(main())
The same scheduling window occurs via handle = await sandbox.files.watch_dir(..., on_exit=...) followed immediately by await handle.stop(): watch_dir has received the start event, but the newly created background task has not run yet. I reproduced this public call with a local Connect/HTTP2 server as well as a mocked transport.
Expected / actual
watch_dir documents that on_exit receives None when stop() is called. Instead the callback is skipped if the background task is cancelled before its first step. Waiting for that task to start before stopping gives the expected callback.
AsyncWatchHandle.stop() relies on _handle_events() catching cancellation, but a task cancelled before its first step cannot execute that handler. This is a follow-up to #1480's Python exit-notification contract; the merged JS stop-error fix #1923 concerns a different failure.
I have a minimal fix and regression tests prepared. AI assistance was used to investigate and verify this report.
Triage
- type: bug
- priority: medium
- complexity: small
- affected_area: python-sdk/filesystem (AsyncWatchHandle / watch_dir)
- actionable: yes
- needs_clarification: false
- summary: In the async Python SDK, calling
AsyncWatchHandle.stop()immediately afterwatch_dir(before the background event task has run its first step) cancels the task before_handle_events()can catch the cancellation, so the documentedon_exit(None)callback is never invoked; includes a minimal offline repro and the reporter has a fix with tests ready.