Skip to content

Commit e56054a

Browse files
committed
fix(python): close owned async client when context entry fails
1 parent 6f4b5f9 commit e56054a

2 files changed

Lines changed: 87 additions & 21 deletions

File tree

‎python/openshell/sandbox.py‎

Lines changed: 30 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -2344,6 +2344,7 @@ class AsyncSandbox:
23442344
Async twin of `Sandbox`: use it with `async with`. Constructor
23452345
arguments and OIDC kwargs mirror `Sandbox` exactly and forward to
23462346
`AsyncSandboxClient.from_active_cluster`.
2347+
The wrapper owns its client and closes it if entry fails or is cancelled.
23472348
"""
23482349

23492350
def __init__(
@@ -2415,30 +2416,38 @@ async def __aenter__(self) -> AsyncSandbox:
24152416
)
24162417
self._client = client
24172418

2418-
if self._sandbox_input is None:
2419-
self._session = await client.create_session(
2420-
workspace=self._workspace,
2421-
spec=self._spec,
2422-
name=self._name,
2423-
labels=self._labels,
2424-
)
2425-
elif isinstance(self._sandbox_input, SandboxRef):
2426-
self._session = AsyncSandboxSession(client, self._sandbox_input)
2427-
else:
2428-
self._session = await client.get_session(
2429-
self._sandbox_input, workspace=self._workspace
2430-
)
2419+
try:
2420+
if self._sandbox_input is None:
2421+
self._session = await client.create_session(
2422+
workspace=self._workspace,
2423+
spec=self._spec,
2424+
name=self._name,
2425+
labels=self._labels,
2426+
)
2427+
elif isinstance(self._sandbox_input, SandboxRef):
2428+
self._session = AsyncSandboxSession(client, self._sandbox_input)
2429+
else:
2430+
self._session = await client.get_session(
2431+
self._sandbox_input, workspace=self._workspace
2432+
)
24312433

2432-
self._workspace = getattr(self._session, "_workspace", self._workspace)
2434+
self._workspace = getattr(self._session, "_workspace", self._workspace)
24332435

2434-
ready = await client.wait_ready(
2435-
self._session.sandbox.name,
2436-
workspace=self._workspace,
2437-
timeout_seconds=self._ready_timeout_seconds,
2438-
)
2439-
self._session = AsyncSandboxSession(client, ready)
2436+
ready = await client.wait_ready(
2437+
self._session.sandbox.name,
2438+
workspace=self._workspace,
2439+
timeout_seconds=self._ready_timeout_seconds,
2440+
)
2441+
self._session = AsyncSandboxSession(client, ready)
24402442

2441-
return self
2443+
return self
2444+
except BaseException:
2445+
try:
2446+
await client.close()
2447+
finally:
2448+
self._session = None
2449+
self._client = None
2450+
raise
24422451

24432452
async def __aexit__(self, *args: object) -> None:
24442453
try:
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
Fresh native AsyncSandbox failed-entry proposed repair, 2026-10-16
2+
3+
Owner Dhiraj Bokde PR2645:
4+
https://github.com/NVIDIA/OpenShell/pull/2645
5+
Owner source42f2ab96891c0ac848b9d8aad55f27ec147b1e90 remains untouched upstream.
6+
Untouched-source RED packet is parent commit6f4b5f9 on this same evidence carrier.
7+
Original dot packet remains unavailable; this is fresh, independently readable proof.
8+
9+
Requirement/ownership: AsyncSandbox creates AsyncSandboxClient.from_active_cluster
10+
inside __aenter__; the client constructor creates its own grpc.aio channel. No
11+
caller-owned channel is supplied here. Existing normal __aexit__ closes this client
12+
and resets wrapper state. Failed/cancelled __aenter__ bypasses Python's __aexit__, so
13+
it must release what it acquired. This is deterministic owned-resource cleanup, not
14+
a permanent GC leak claim or a request to close caller-owned shared channels.
15+
16+
Only production change: AsyncSandbox.__aenter__ protects post-construction entry
17+
with except BaseException, awaits client.close(), clears _session/_client in finally,
18+
then re-raises. Catch includes task cancellation; successful entry/body and normal
19+
__aexit__ are unchanged. Class docstring records ownership/failure cleanup contract.
20+
No OIDC redesign, remote sandbox deletion/adoption, async client API change, original
21+
owner branch rewrite or competing upstream PR.
22+
23+
Same exact combined command before/after:
24+
<venv>/bin/python -m pytest -q python/openshell/async_sandbox_test.py python/openshell/sandbox_test.py review-evidence/2645-native-entry_test.py
25+
Corrected-fixture RED:114PASS/6FAIL in14.76s,exit1.
26+
Proposed repair GREEN:120PASS in6.78s,exit0; no warnings/skips/xfails reported.
27+
Includes37 existing async owner tests,75 existing sync owner tests,8 native cases.
28+
Six failed-entry cases: native PERMISSION_DENIED or task cancellation at create,
29+
attach/get, readiness; original actual channel stays READY after failed async-with
30+
entry. Repair produces SHUTDOWN and clears wrapper state. Original RPC code/details
31+
and CancelledError remain observable. Two success controls confirm channel READY
32+
inside context body, SHUTDOWN/reset after ordinary exit. Test finally closes any
33+
failed-head retained channels, avoiding environmental leak and overstated persistence.
34+
35+
Complete production AsyncSandbox -> actual gateway metadata -> AsyncSandboxClient
36+
-> grpc.aio channel -> generated CreateSandbox/GetSandbox RPC -> real aio loopback
37+
service. No SDK method/client/stub/channel replacement or extracted helper.
38+
Ephemeral metadata only. Test observes actual channel via wrapper state in server
39+
handler, never substitutes source objects. delete_on_exit=False intentionally isolates
40+
channel lifecycle from remote sandbox deletion semantics.
41+
42+
Environment: native Linux ARM64 Python3.14.8;grpcio/grpcio-tools1.84.0;
43+
protobuf7.36.2;httpx0.28.1;cloudpickle3.1.2;pytest9.1.1;pytest-asyncio1.4.0.
44+
Bindings generated with owner tasks/python.toml python:proto task; only uv Python
45+
invocation substituted for isolated venv Python. No generated bindings committed.
46+
Initial fixture used nonexistent response type names and produced112PASS/8FAIL;
47+
corrected to actual SandboxResponse before accepted RED, source unchanged then.
48+
49+
LIMITED: loopback service is not a production gateway deployment, real provisioning,
50+
OIDC HTTP cleanup instrumentation, repeated cancellation during cleanup, close()
51+
exceptions, dependency-minimum matrix, full SDK suite, hosted CI, Rust, Docker,
52+
macOS/VM/GPU or performance acceptance. No current-main async implementation claim.
53+
Parent independent machine source review requested separately, not personal human
54+
review, DCO signoff, maintainer approval or permission to create upstream PRs.
55+
Dhiraj owns original SDK implementation; dot historical evidence credit preserved;
56+
ChatGPT fresh native tests and narrow proposed repair under scoped user direction.
57+
Canonical queue67 bounded manual lease6219784722. Original admission gates retained.

0 commit comments

Comments
 (0)