diff --git a/baseten/sandbox/_process.py b/baseten/sandbox/_process.py index 897fa2a..fe6637d 100644 --- a/baseten/sandbox/_process.py +++ b/baseten/sandbox/_process.py @@ -16,6 +16,8 @@ from datetime import datetime, timedelta from typing import Literal, TypeAlias +import httpx + import baseten.client.sandboxapi from baseten.sandbox._common import ( AsyncSandboxContext, @@ -368,16 +370,25 @@ def wait( SandboxProcessWaitTimeoutError: The process was still running when the wait timed out. The process keeps running. """ - # A check already in flight cannot be interrupted, so the wait can - # run over by up to one check. deadline = ( None if timeout is None else time.monotonic() + timeout.total_seconds() ) last_error: Exception | None = None while True: + # Each check is bounded by the time left, so a stalled one cannot + # hold the wait past its timeout. + if deadline is None: + api_context = self._context.api() + else: + time_left = timedelta(seconds=max(deadline - time.monotonic(), 0)) + api_context = self._context.api_with_timeout(time_left) try: - with self._context.api() as api: + with api_context as api: process = api.get_process_identifier(identifier=identifier) + except httpx.TimeoutException as err: + if deadline is None: + raise + last_error = err except Exception as err: if not _is_retryable_wait_error(err): raise diff --git a/tests/sandbox/test_process.py b/tests/sandbox/test_process.py index d94b23c..4e5ccd7 100644 --- a/tests/sandbox/test_process.py +++ b/tests/sandbox/test_process.py @@ -367,6 +367,19 @@ def test_wait_times_out_with_last_error_as_cause(self) -> None: assert raised.value.identifier == "job" assert isinstance(raised.value.__cause__, SandboxGatewayError) + def test_wait_bounds_each_check_by_the_time_left(self) -> None: + api = _Api() + api.route("GET", "/process/job", httpx.ReadTimeout("stalled")) + with pytest.raises(SandboxProcessWaitTimeoutError) as raised: + api.sandbox().process.wait( + identifier="job", + timeout=timedelta(milliseconds=50), + poll_interval=timedelta(milliseconds=1), + ) + assert isinstance(raised.value.__cause__, httpx.ReadTimeout) + read_timeout = api.requests[0].extensions["timeout"]["read"] + assert read_timeout is not None and read_timeout <= 0.05 + def test_writes_stdin_as_bytes(self) -> None: api = _Api() api.route("POST", "/process/job/stdin", {"message": "ok"})