Skip to content

fix(python-sdk): fire on_exit when stop() precedes the watch task start - #2073

Open
TINGyu123644 wants to merge 3 commits into
e2b-dev:mainfrom
TINGyu123644:fix/issue-2071
Open

TINGyu123644 wants to merge 3 commits into
e2b-dev:mainfrom
TINGyu123644:fix/issue-2071

Conversation

@TINGyu123644

@TINGyu123644 TINGyu123644 commented Oct 31, 2026 •

Copy link
Copy Markdown

Summary

Fixes #2071: in the async Python SDK, AsyncWatchHandle.stop() skipped the on_exit callback when it was called before the watch's background task had started.

Root cause

AsyncWatchHandle.__init__ spawns self._wait = asyncio.create_task(self._handle_events()), and stop() ends the watch by cancelling that task, relying on the except asyncio.CancelledError handler inside _handle_events() to fire on_exit(None). A task that is cancelled before its first step never runs its coroutine body at all, so the handler never executes and on_exit is skipped.

That window is reachable through the public API: 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 been scheduled yet.

This contradicts the documented contract of watch_dir:

on_exit: Callback to call when the watching ends. It receives the error that ended the watch, or None on a clean end or when stop() is called

Fix

stop() now fires on_exit(None) itself when the background task was cancelled before running, guarded by a one-shot _on_exit_called flag that _call_on_exit() sets, so every path still fires the callback exactly once:

  • clean stream end → fired by _handle_events (unchanged)
  • stream error → fired by _handle_events (unchanged)
  • stop() after the task started → fired by the CancelledError handler (unchanged)
  • stop() before the task started → fired by stop() (new)

The sync WatchHandle is polling-based (get_new_events/remove_watcher) and has no on_exit callback, 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, proving stop() drives it to completion

Verification (Python 3.13, uv-managed env, deps from pyproject.toml):

  • New tests fail on unpatched main (8cc9ed1e) and pass with the fix — RED/GREEN confirmed
  • All 11 tests in tests/test_watch_handle.py pass (9 pre-existing + 2 new); the pre-existing on_exit tests prove no double-firing on the normal paths
  • The issue's minimal repro now prints [None]
  • Full suite before/after: only the 2 new tests change status (178→176 failures; the remaining failures/errors are the pre-existing live-sandbox tests that require E2B_API_KEY, identical with and without the patch)
  • ruff check + ruff format --check clean; ty check clean on the changed files

AI 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_exit contract rather than changing user-facing behavior.


Devin Review

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-bot

changeset-bot Bot commented Oct 31, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: f70e112

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 2 packages
Name Type
@e2b/python-sdk Patch
@e2b/code-interpreter-python Patch

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

@cla-bot cla-bot Bot added the cla-signed label Oct 31, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 31, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-01T02:30:31.287050Z c62fbba Manual request
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@devin-ai-integration devin-ai-integration Bot 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.

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.

devin-ai-integration[bot]

This comment was marked as resolved.

@TINGyu123644

Copy link
Copy Markdown
Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Something went wrong. Try again later by commenting “@codex review”.

An unknown error occurred
ℹ️ 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".

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

Copy link
Copy Markdown
Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Something went wrong. Try again later by commenting “@codex review”.

An unknown error occurred
ℹ️ 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".

@TINGyu123644

Copy link
Copy Markdown
Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 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".

Comment on lines +49 to +50
if not self._on_exit_called:
await self._call_on_exit(None)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

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:
        pass

On 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.
@TINGyu123644

Copy link
Copy Markdown
Author

Replying to @codex's P2 finding ("Close the stream even if the fallback callback is cancelled"): this is fixed in the current head f70e1128 ("fix(python-sdk): close watch stream even if fallback on_exit").

The await self._events.aclose() call moved into a finally: block in stop(), so a cancelled (or raising) fallback on_exit callback can no longer bypass stream cleanup - the same guarantee the existing background-task path already had. A regression test covers the cancelled-callback case (stop() before the watch task starts, with an on_exit awaiting a cancelled future: the stream previously stayed open, now it is closed).

@TINGyu123644

Copy link
Copy Markdown
Author

CI note for triage on the current head f70e1128: the five GitHub Actions workflows (Lint, Typecheck, SDK Tests, Generated files, Package Artifacts) are in action_required state - as a fork PR they need a maintainer to click "Approve and run workflows" before they can execute (the earlier Cursor Security Agent review on the initial commit passed, and Devin's review found no blocking issues). Could a maintainer approve the runs for this head? Happy to provide anything else needed.

This branch has not been deployed

No deployments
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.

[Bug]: Async Python watch_dir immediate stop skips on_exit

1 participant