Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions sdk/python/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1068,6 +1068,9 @@ not apply the tunnel descriptor's creation-time value. When reconnecting with
`Sandbox.connect`, pass the original timeout to configure the new local client;
reconnecting does not change Execd's saved configuration.

When `pause()` fails and the sandbox stays running, automatic tunnel
reconnection keeps the previously effective client timeout.

For an HTTPS target, the SDK-side tunnel client performs the TLS handshake and
certificate verification. The sandbox application talks only to its loopback
HTTP listener. AKernel supports one HTTP/HTTPS reverse tunnel per sandbox and
Expand Down
41 changes: 27 additions & 14 deletions sdk/python/akernel_sdk/_backends/adx.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,24 +101,31 @@ def _directory_info(row: Mapping[str, Any]) -> SandboxInfo:
)


def _bind_tunnel(sandbox: Any, tunnel: Any, connection: Any) -> None:
def _bind_tunnel(
sandbox: Any,
tunnel: Any,
connection: Any,
*,
previous_http_timeout: httpx.Timeout | None = None,
) -> None:
if tunnel is None:
return
gateway = connection.gateway_address or connection.server_address
tls = connection.gateway_use_tls
scheme = "wss" if tls else "ws"
safe_id = sandbox._client._safe_id(sandbox.id)
timeout_options = (
{}
if tunnel.http_timeout_seconds is None
else {"http_timeout_seconds": tunnel.http_timeout_seconds}
)
client = TunnelClient(
tunnel.target,
token=connection.resolved_token() if tls else None,
environment_id=sandbox.id,
**timeout_options,
http_timeout_seconds=(
tunnel.http_timeout_seconds if previous_http_timeout is None else None
),
)
if previous_http_timeout is not None:
# The native constructor accepts integer seconds. Reuse the resolved
# HTTPX budgets so rollback also keeps fractional process defaults.
client._http_timeout = previous_http_timeout
sandbox._tunnel_client = client
sandbox._upstream = tunnel.target
sandbox._tunnel_url = f"http://127.0.0.1:{tunnel.listen_port}"
Expand All @@ -139,11 +146,13 @@ def _bind_tunnel(sandbox: Any, tunnel: Any, connection: Any) -> None:
raise


def _unbind_tunnel(sandbox: Any) -> None:
tunnel = getattr(sandbox, "_tunnel_client", None)
if tunnel is not None:
tunnel.stop()
sandbox._tunnel_client = None
def _unbind_tunnel(sandbox: Any) -> httpx.Timeout | None:
client = getattr(sandbox, "_tunnel_client", None)
if client is None:
return None
client.stop()
sandbox._tunnel_client = None
return client._http_timeout


def _log_creation_budgets(
Expand Down Expand Up @@ -743,8 +752,9 @@ def pause(self, timeout: int) -> bool:
return False
# Stop retries before pausing: a reconnecting tunnel can demand-resume
# the environment immediately after the pause commits.
previous_http_timeout = None
try:
_unbind_tunnel(self._sandbox)
previous_http_timeout = _unbind_tunnel(self._sandbox)
self._sandbox.pause(
timeout_seconds=timeout,
retention=adx_environment.RetentionPolicy.forever(),
Expand All @@ -756,7 +766,10 @@ def pause(self, timeout: int) -> bool:
and self.get_info().state == "running"
):
_bind_tunnel(
self._sandbox, self._spec.reverse_tunnel, self._connection
self._sandbox,
self._spec.reverse_tunnel,
self._connection,
previous_http_timeout=previous_http_timeout,
)
except Exception as cleanup:
retain_failure_context(error, self.id, cleanup)
Expand Down
88 changes: 69 additions & 19 deletions sdk/python/tests/unit/test_reverse_tunnel_timeout.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,14 @@
"""Per-sandbox HTTP timeout through the real ADX request encoder."""

import json
import os
import unittest
from contextlib import contextmanager
from unittest.mock import MagicMock, patch

import httpx

from akernel_sdk import HttpReverseTunnel
from akernel_sdk import BackendOperationError, HttpReverseTunnel
from akernel_sdk._addresses import Endpoint
from akernel_sdk._backends import adx
from akernel_sdk._backends.base import BackendConfig
Expand All @@ -39,7 +41,8 @@ def setUp(self):
)
)

def exercise(self, seconds, *, restore=False):
@contextmanager
def tunnel_session(self, tunnel, *, confirmed_seconds, restore=False):
calls = []
bodies = []

Expand All @@ -53,42 +56,57 @@ def send(_client, request, **_kwargs):
)
if request.url.path.endswith("/environments"):
bodies.append(json.loads(request.content))
tunnel = {}
if seconds is not None:
tunnel["httpTimeoutSeconds"] = seconds
tunnel_response = {}
if confirmed_seconds is not None:
tunnel_response["httpTimeoutSeconds"] = confirmed_seconds
payload = {
"environmentId": "default-timeout-test",
"status": "running",
"newlyCreated": True,
"tunnel": tunnel,
"tunnel": tunnel_response,
}
return httpx.Response(
200,
headers={"content-type": "text/event-stream"},
content="event: final\ndata: " + json.dumps(payload) + "\n\n",
request=request,
)
if request.url.path == "/api/instances":
return httpx.Response(
200,
json=[{"id": "default-timeout-test", "status": "running"}],
request=request,
)
if request.url.path.endswith("/pause"):
return httpx.Response(
409, json={"message": "pause rejected"}, request=request
)
return httpx.Response(200, json={"processes": []}, request=request)

tunnel = HttpReverseTunnel(
"http://127.0.0.1:9000", http_timeout_seconds=seconds
)
with (
patch.object(httpx.Client, "send", autospec=True, side_effect=send),
patch("adx_environment.tunnel_client.TunnelClient") as client,
):
client.return_value.start.return_value = True
with patch.object(httpx.Client, "send", autospec=True, side_effect=send):
if restore:
session = self.backend.from_snapshot(
restore_spec(reverse_tunnel=tunnel)
)
else:
session = self.backend.create(_spec(reverse_tunnel=tunnel))
client_options = client.call_args.kwargs
session.close()
self.assertEqual(len(bodies), 1)
self.assertNotIn("ADX_TUNNEL_HTTP_TIMEOUT", bodies[0].get("env", {}))
return calls, bodies[0], client_options
try:
self.assertEqual(len(bodies), 1)
self.assertNotIn("ADX_TUNNEL_HTTP_TIMEOUT", bodies[0].get("env", {}))
yield session, calls, bodies[0]
finally:
session.close()

def exercise(self, seconds, *, restore=False):
tunnel = HttpReverseTunnel(
"http://127.0.0.1:9000", http_timeout_seconds=seconds
)
with patch("adx_environment.tunnel_client.TunnelClient") as client:
client.return_value.start.return_value = True
with self.tunnel_session(
tunnel, confirmed_seconds=seconds, restore=restore
) as (_, calls, body):
return calls, body, client.call_args.kwargs

def test_fresh_create_confirms_timeout_and_configures_both_ends(self):
calls, body, client = self.exercise(3600)
Expand All @@ -109,6 +127,38 @@ def test_snapshot_restore_inherits_without_sending_a_timeout_override(self):
self.assertFalse(any(path.endswith("/capabilities") for _, path in calls))
self.assertEqual(client["http_timeout_seconds"], 3600)

def test_failed_pause_preserves_effective_snapshot_tunnel_timeout(self):
for requested, confirmed, effective in (
(None, 3600, 3600),
(1800, 3600, 3600),
(None, None, 37.5),
):
tunnel = HttpReverseTunnel(
"http://127.0.0.1:9000", http_timeout_seconds=requested
)
with (
self.subTest(requested=requested, confirmed=confirmed),
patch.dict(os.environ, {"ADX_TUNNEL_HTTP_TIMEOUT": "37.5"}),
patch.object(adx.TunnelClient, "start", return_value=True) as start,
self.tunnel_session(
tunnel, confirmed_seconds=confirmed, restore=True
) as (session, _, _),
):
native = session._sandbox
initial = native._tunnel_client
self.assertEqual(initial._http_timeout, httpx.Timeout(effective))
with (
patch.dict(os.environ, {"ADX_TUNNEL_HTTP_TIMEOUT": "600"}),
self.assertRaises(BackendOperationError) as raised,
):
session.pause(timeout=30)
self.assertEqual(raised.exception.status_code, 409)
self.assertIsNot(native._tunnel_client, initial)
self.assertEqual(start.call_count, 2)
self.assertEqual(
native._tunnel_client._http_timeout, httpx.Timeout(effective)
)

def test_rebinding_preserves_explicit_client_timeout(self):
sandbox = MagicMock(id="default-timeout-test")
tunnel = HttpReverseTunnel(
Expand Down
Loading