Repository navigation
fix(python-sdk): fire on_exit when stop() precedes the watch task start - #2073
TINGyu123644 wants to merge 3 commits into
Conversation
AsyncWatchHandle.stop() cancels the background _handle_events task and
relies on its CancelledError handler to fire on_exit. A task cancelled
before its first step never runs that handler, so calling stop() before
the background task starts - e.g. immediately after watch_dir returns,
before the task is first scheduled - skipped on_exit entirely, contrary
to the documented contract ("None ... when stop() is called").
Fire on_exit from stop() for that window, guarded by a one-shot flag so
the normal paths (clean end, stream error, post-start cancellation) keep
firing it exactly once. The sync WatchHandle is polling-based and has no
on_exit callback, so it is unaffected.
Fixes e2b-dev#2071
AI assistance: the regression tests and the root-cause analysis were
developed with AI assistance and verified locally (RED before the fix,
GREEN after; ruff check/format and ty clean; existing on_exit lifecycle
tests still pass).
🦋 Changeset detectedLatest commit: f70e112 The changes in this PR will be included in the next version bump. This PR includes changesets to release 2 packages
Not sure what this means? Click here to learn what changesets are. Click here if you're a maintainer who wants to add another changeset to this PR |
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
TASTE.md review: complies — checked T-1/T-2 parity (JS WatchHandle already fires onExit on every stop path; sync Python is a polling handle per T-28, so no mirror needed), T-26/T-27 handle and on_exit callback semantics (sync or async, awaited, fires exactly once), and T-30 stop() naming; 0 violations.
|
@codex review |
|
Codex Review: Something went wrong. Try again later by commenting “@codex review”. ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
AGENTS.md requires a changeset when changing the public surface of packages/python-sdk; the watch_dir/watch on_exit fix (e2b-dev#2071) now has a patch changeset for @e2b/python-sdk.
|
@codex review |
|
Codex Review: Something went wrong. Try again later by commenting “@codex review”. ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: c62fbba490
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| if not self._on_exit_called: | ||
| await self._call_on_exit(None) |
There was a problem hiding this comment.
Close the stream even if the fallback callback is cancelled
When stop() runs before the watch task starts and an async on_exit awaits a cancelled task or future, this new await propagates CancelledError because _call_on_exit() deliberately does not catch it. That exits stop() before _events.aclose() runs, leaving the watch RPC stream unclosed even though watch_dir() has already opened it and consumed its start event. Cancellation of the same callback on the existing background-task path does not prevent stream closure. Close the stream before invoking the fallback, or protect closure with finally, so callback cancellation cannot bypass cleanup.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Good catch - agreed. stop() now closes the stream in a finally around the fallback _call_on_exit(None) call, so a CancelledError raised by the callback (a BaseException, deliberately not caught by _call_on_exit) can no longer bypass _events.aclose().
try:
if not self._on_exit_called:
await self._call_on_exit(None)
finally:
try:
await self._events.aclose()
except Exception:
passOn the normal path (the background task did run) the callback has already fired and _call_on_exit is idempotent, so this is just the close - unchanged behavior there.
Added a regression test (test_async_stop_closes_stream_when_fallback_on_exit_is_cancelled): it builds an on_exit that awaits an already-cancelled task and asserts the stream's aclose() still runs while the CancelledError propagates. Verified RED without the fix, GREEN with it (12 passed in tests/test_watch_handle.py); full python-sdk suite unchanged vs. baseline (pre-existing live-sandbox failures only); ruff check/format clean. Pushed as f70e112.
…lled Codex review (P2) on e2b-dev#2073: when stop() runs before the watch task starts and the fallback on_exit callback awaits an already-cancelled task, the CancelledError propagates out of _call_on_exit (a BaseException, not caught there). The old ordering let that skip _events.aclose(), leaking the RPC stream that watch_dir already opened and whose start event it consumed. Close the stream in a finally so callback cancellation cannot bypass cleanup; the normal path (task did run) is unchanged because _call_on_exit is idempotent. Adds a regression test that fails without the fix. Part of e2b-dev#2073.
|
Replying to @codex's P2 finding ("Close the stream even if the fallback callback is cancelled"): this is fixed in the current head The |
|
CI note for triage on the current head |
Summary
Fixes #2071: in the async Python SDK,
AsyncWatchHandle.stop()skipped theon_exitcallback when it was called before the watch's background task had started.Root cause
AsyncWatchHandle.__init__spawnsself._wait = asyncio.create_task(self._handle_events()), andstop()ends the watch by cancelling that task, relying on theexcept asyncio.CancelledErrorhandler inside_handle_events()to fireon_exit(None). A task that is cancelled before its first step never runs its coroutine body at all, so the handler never executes andon_exitis skipped.That window is reachable through the public API:
handle = await sandbox.files.watch_dir(..., on_exit=...)followed immediately byawait handle.stop()—watch_dirhas received the start event, but the newly created background task has not been scheduled yet.This contradicts the documented contract of
watch_dir:Fix
stop()now fireson_exit(None)itself when the background task was cancelled before running, guarded by a one-shot_on_exit_calledflag that_call_on_exit()sets, so every path still fires the callback exactly once:_handle_events(unchanged)_handle_events(unchanged)stop()after the task started → fired by theCancelledErrorhandler (unchanged)stop()before the task started → fired bystop()(new)The sync
WatchHandleis polling-based (get_new_events/remove_watcher) and has noon_exitcallback, so it is unaffected. The JS SDK is likewise unaffected (its stop-error fix #1923 covered a different failure).Tests
Two regression tests in
packages/python-sdk/tests/test_watch_handle.py, following the existing on_exit-lifecycle test style (no sandbox/API key needed):test_async_on_exit_fires_on_stop_before_task_starts— the exact scenario from the issue (sync callback)test_async_on_exit_fires_once_on_stop_before_task_starts_with_async_callback— same window with an async callback that suspends, provingstop()drives it to completionVerification (Python 3.13,
uv-managed env, deps frompyproject.toml):main(8cc9ed1e) and pass with the fix — RED/GREEN confirmedtests/test_watch_handle.pypass (9 pre-existing + 2 new); the pre-existing on_exit tests prove no double-firing on the normal paths[None]E2B_API_KEY, identical with and without the patch)ruff check+ruff format --checkclean;ty checkclean on the changed filesAI assistance
Root-cause analysis, the fix, and the regression tests were developed with AI assistance; everything was reviewed and verified locally as described above (RED/GREEN, lint, typecheck, full-suite baseline comparison).
No docs PR is linked: this change makes the code match the already-documented
on_exitcontract rather than changing user-facing behavior.