Skip to content

Commit d51c243

Browse files
committed
fix(python-sdk): end watch_logs on clean stream close and isolate its executor
Signed-off-by: letv1nnn <letv1n2007@icloud.com>
1 parent 42bbc2b commit d51c243

2 files changed

Lines changed: 176 additions & 94 deletions

File tree

‎python/openshell/sandbox.py‎

Lines changed: 107 additions & 86 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55

66
import asyncio
77
import base64
8+
import concurrent.futures
89
import contextlib
910
import errno
1011
import functools
@@ -549,18 +550,21 @@ class SandboxError(RuntimeError):
549550
pass
550551

551552

552-
def _timestamp_from_proto(ts) -> datetime:
553-
"""Convert protobuf Timestamp to aware UTC datetime. Return current time if unset."""
554-
if ts is None or ts.seconds == 0:
555-
return datetime.now(UTC)
556-
return ts.ToDatetime(tzinfo=UTC)
553+
def _timestamp_from_proto(ts) -> datetime | None:
554+
"""Convert protobuf Timestamp to aware UTC datetime. Return None if unset or invalid."""
555+
if ts is None or (ts.seconds == 0 and ts.nanos == 0):
556+
return None
557+
try:
558+
return ts.ToDatetime(tzinfo=UTC)
559+
except (ValueError, OverflowError):
560+
return None
557561

558562

559563
@dataclass(frozen=True)
560564
class PlatformEvent:
561565
"""A runtime event observed for a sandbox (e.g., Kubernetes pod event)."""
562566

563-
timestamp: datetime
567+
timestamp: datetime | None
564568
source: str
565569
type: str
566570
reason: str
@@ -590,7 +594,7 @@ class LogLine:
590594
"""One log entry from a sandbox."""
591595

592596
sandbox_id: str
593-
timestamp: datetime
597+
timestamp: datetime | None
594598
level: str
595599
target: str
596600
message: str
@@ -1465,93 +1469,110 @@ async def watch_logs(
14651469
if not follow_logs and not follow_events:
14661470
follow_logs = True
14671471

1468-
# Resolve sandbox name first (fail fast if not found) — blocking call in executor
1472+
# Every blocking gRPC call for this watch runs on a dedicated thread so a
1473+
# long-lived stream never holds a slot in the loop's shared default
1474+
# executor, which would starve unrelated run_in_executor work.
14691475
loop = asyncio.get_running_loop()
1470-
sandbox = await loop.run_in_executor(
1471-
None, functools.partial(self.get, workspace=workspace, name=name)
1476+
executor = concurrent.futures.ThreadPoolExecutor(
1477+
max_workers=1, thread_name_prefix="openshell-watch-logs"
14721478
)
1473-
resolved_name = sandbox.name
1474-
1475-
# Initialize reconnect state
1476-
cursor = opts.resume_after_cursor
1477-
backoff = 0.1 # 100ms initial
1478-
max_backoff = 2.0 # 2s cap
1479-
consecutive_failures = 0
1480-
max_retries = 15 # Give up after 15 consecutive UNAVAILABLE
1481-
stream = None
1482-
1483-
# Reconnect loop
1484-
while True:
1485-
try:
1486-
# Build watch request
1487-
request = openshell_pb2.WatchSandboxRequest(
1488-
sandbox=resolved_name,
1489-
workspace_scope=_workspace_scope(workspace),
1490-
follow_status=False, # Don't want status snapshots
1491-
follow_logs=follow_logs,
1492-
follow_events=follow_events,
1493-
log_tail_lines=opts.log_tail_lines,
1494-
event_tail=opts.event_tail,
1495-
log_sources=list(opts.log_sources),
1496-
log_min_level=opts.log_min_level,
1497-
resume_after_cursor=cursor, # Resume from this cursor
1498-
)
1479+
try:
1480+
# Resolve sandbox name first (fail fast if not found)
1481+
sandbox = await loop.run_in_executor(
1482+
executor, functools.partial(self.get, workspace=workspace, name=name)
1483+
)
1484+
resolved_name = sandbox.name
1485+
1486+
# Initialize reconnect state
1487+
cursor = opts.resume_after_cursor
1488+
backoff = 0.1 # 100ms initial
1489+
max_backoff = 2.0 # 2s cap
1490+
consecutive_failures = 0
1491+
max_retries = 15 # Give up after 15 consecutive UNAVAILABLE
1492+
stream = None
1493+
1494+
# Reconnect loop
1495+
while True:
1496+
try:
1497+
# Build watch request
1498+
request = openshell_pb2.WatchSandboxRequest(
1499+
sandbox=resolved_name,
1500+
workspace_scope=_workspace_scope(workspace),
1501+
follow_status=False, # Don't want status snapshots
1502+
follow_logs=follow_logs,
1503+
follow_events=follow_events,
1504+
log_tail_lines=opts.log_tail_lines,
1505+
event_tail=opts.event_tail,
1506+
log_sources=list(opts.log_sources),
1507+
log_min_level=opts.log_min_level,
1508+
resume_after_cursor=cursor, # Resume from this cursor
1509+
)
14991510

1500-
# Call gRPC stream (blocking, run in executor)
1501-
stream = await loop.run_in_executor(
1502-
None, self._stub.WatchSandbox, request
1503-
)
1511+
# Call gRPC stream (blocking, run in executor)
1512+
stream = await loop.run_in_executor(
1513+
executor, self._stub.WatchSandbox, request
1514+
)
15041515

1505-
# Receive events from stream (blocking iteration, run in executor)
1506-
while True:
1507-
pb_event = await loop.run_in_executor(None, next, stream)
1516+
# Receive events from stream (blocking iteration, run in executor).
1517+
# Use a None sentinel: a StopIteration raised inside the executor
1518+
# cannot be set on an asyncio Future and would hang the await.
1519+
while True:
1520+
pb_event = await loop.run_in_executor(
1521+
executor, next, stream, None
1522+
)
1523+
if pb_event is None:
1524+
# Server closed the stream cleanly; nothing left to resume.
1525+
return
1526+
1527+
# Convert proto → domain (skip non-resumable)
1528+
item = _watch_log_event_from_proto(pb_event)
1529+
if item is None:
1530+
continue
1531+
1532+
# Reset backoff and failure count only after yielding resumable item
1533+
backoff = 0.1
1534+
consecutive_failures = 0
1535+
1536+
# Update cursor: high-water mark (max, not last)
1537+
# Live delivery reads log and event sources independently,
1538+
# so arrival order ≠ cursor order. Keep max to avoid rewinding.
1539+
if item.cursor > cursor:
1540+
cursor = item.cursor
1541+
1542+
# Yield to caller
1543+
yield item
1544+
1545+
except OutOfRangeError:
1546+
# Terminal: resume cursor is gone, never retry
1547+
# Caller gets this exception, knows to start fresh with empty cursor
1548+
raise
15081549

1509-
# Convert proto → domain (skip non-resumable)
1510-
item = _watch_log_event_from_proto(pb_event)
1511-
if item is None:
1550+
except grpc.RpcError as e:
1551+
# Check if retryable (Unavailable = connection drop, gateway restart)
1552+
if e.code() == grpc.StatusCode.UNAVAILABLE:
1553+
consecutive_failures += 1
1554+
if consecutive_failures > max_retries:
1555+
# Gave up after max retries, raise as GatewayError
1556+
raise from_grpc_error(e) from e
1557+
# Sleep with backoff, then reconnect from cursor
1558+
await asyncio.sleep(backoff)
1559+
backoff = min(backoff * 2, max_backoff)
15121560
continue
1513-
1514-
# Reset backoff and failure count only after yielding resumable item
1515-
backoff = 0.1
1516-
consecutive_failures = 0
1517-
1518-
# Update cursor: high-water mark (max, not last)
1519-
# Live delivery reads log and event sources independently,
1520-
# so arrival order ≠ cursor order. Keep max to avoid rewinding.
1521-
if item.cursor > cursor:
1522-
cursor = item.cursor
1523-
1524-
# Yield to caller
1525-
yield item
1526-
1527-
except OutOfRangeError:
1528-
# Terminal: resume cursor is gone, never retry
1529-
# Caller gets this exception, knows to start fresh with empty cursor
1530-
raise
1531-
1532-
except grpc.RpcError as e:
1533-
# Check if retryable (Unavailable = connection drop, gateway restart)
1534-
if e.code() == grpc.StatusCode.UNAVAILABLE:
1535-
consecutive_failures += 1
1536-
if consecutive_failures > max_retries:
1537-
# Gave up after max retries, raise as GatewayError
1561+
else:
1562+
# Other gRPC error (PermissionDenied, NotFound, Internal, etc)
1563+
# Terminal — raise as GatewayError
15381564
raise from_grpc_error(e) from e
1539-
# Sleep with backoff, then reconnect from cursor
1540-
await asyncio.sleep(backoff)
1541-
backoff = min(backoff * 2, max_backoff)
1542-
continue
1543-
else:
1544-
# Other gRPC error (PermissionDenied, NotFound, Internal, etc)
1545-
# Terminal — raise as GatewayError
1546-
raise from_grpc_error(e) from e
1547-
1548-
finally:
1549-
if stream is not None:
1550-
await loop.run_in_executor(None, stream.cancel)
1551-
stream = None
15521565

1553-
# If we reach here without exception, stream ended cleanly (shouldn't happen)
1554-
break
1566+
finally:
1567+
if stream is not None:
1568+
# cancel() is non-blocking and thread-safe. Call it directly:
1569+
# the executor's only thread may still be blocked in next()
1570+
# (e.g. the consumer task was cancelled), and cancelling is
1571+
# what unblocks it.
1572+
stream.cancel()
1573+
stream = None
1574+
finally:
1575+
executor.shutdown(wait=False)
15551576

15561577

15571578
class SandboxTemplateClient:

‎python/openshell/sandbox_test.py‎

Lines changed: 69 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33

44
from __future__ import annotations
55

6+
import asyncio
67
import json
78
import os
89
import pickle
@@ -35,6 +36,7 @@
3536
SandboxTemplateClient,
3637
ServiceExposure,
3738
TlsConfig,
39+
WatchLogEvent,
3840
WatchLogKind,
3941
_atomic_replace,
4042
_BearerAuthInterceptor,
@@ -3144,13 +3146,72 @@ def test_timestamp_from_proto():
31443146
assert dt.timestamp() == 1700000000.0
31453147

31463148

3147-
def test_timestamp_from_proto_none():
3148-
"""Verify None timestamp returns current time in UTC."""
3149-
from datetime import datetime
3149+
def test_timestamp_from_proto_unset_returns_none():
3150+
"""Verify an unset timestamp maps to None instead of a fabricated time."""
3151+
unset = openshell_pb2.SandboxLogLine().event_time
31503152

3151-
before = datetime.now(UTC)
3152-
dt = sandbox_module._timestamp_from_proto(None)
3153-
after = datetime.now(UTC)
3153+
assert sandbox_module._timestamp_from_proto(None) is None
3154+
assert sandbox_module._timestamp_from_proto(unset) is None
31543155

3155-
assert dt.tzinfo == UTC
3156-
assert before <= dt <= after
3156+
3157+
def test_watch_logs_log_line_without_event_time_has_no_timestamp():
3158+
"""Verify a log line with no event_time is not stamped with the current time."""
3159+
pb_event = openshell_pb2.SandboxStreamEvent(
3160+
cursor="0000000001",
3161+
log=openshell_pb2.SandboxLogLine(sandbox_id="sb-1", message="replayed"),
3162+
)
3163+
3164+
item = sandbox_module._watch_log_event_from_proto(pb_event)
3165+
3166+
assert item is not None
3167+
assert item.log is not None
3168+
assert item.log.timestamp is None
3169+
3170+
3171+
class _FakeWatchStream:
3172+
def __init__(self, events: list[openshell_pb2.SandboxStreamEvent]) -> None:
3173+
self._events = iter(events)
3174+
self.cancelled = False
3175+
3176+
def __iter__(self) -> _FakeWatchStream:
3177+
return self
3178+
3179+
def __next__(self) -> openshell_pb2.SandboxStreamEvent:
3180+
return next(self._events)
3181+
3182+
def cancel(self) -> None:
3183+
self.cancelled = True
3184+
3185+
3186+
class _FakeWatchStub:
3187+
def __init__(self, events: list[openshell_pb2.SandboxStreamEvent]) -> None:
3188+
self.stream = _FakeWatchStream(events)
3189+
3190+
def WatchSandbox(self, request: openshell_pb2.WatchSandboxRequest):
3191+
_ = request
3192+
return self.stream
3193+
3194+
3195+
@pytest.mark.asyncio
3196+
async def test_watch_logs_ends_when_stream_closes_cleanly():
3197+
"""Verify a cleanly closed stream ends iteration instead of hanging."""
3198+
stub = _FakeWatchStub(
3199+
[
3200+
openshell_pb2.SandboxStreamEvent(
3201+
cursor="0000000001",
3202+
log=openshell_pb2.SandboxLogLine(sandbox_id="sb-1", message="only"),
3203+
)
3204+
]
3205+
)
3206+
client = _client_with_fake_stub(stub)
3207+
client.get = lambda name, **_: SimpleNamespace(name=name) # type: ignore[method-assign]
3208+
3209+
async def collect() -> list[WatchLogEvent]:
3210+
return [
3211+
item async for item in client.watch_logs(workspace="default", name="sb-1")
3212+
]
3213+
3214+
items = await asyncio.wait_for(collect(), timeout=5)
3215+
3216+
assert [item.cursor for item in items] == ["0000000001"]
3217+
assert stub.stream.cancelled

0 commit comments

Comments
 (0)