Skip to content

Commit 8495461

Browse files
authored
feat(api): add structured gateway errors and SDK decoding (ai-openshell/openshell#3313)
* feat(api): expose structured gateway errors across SDKs Refs ai-openshell/openshell#3051. Add standard validation, conflict, and retry details; preserve raw transport status in Rust, Go, TypeScript, and Python; document status and recovery guidance. This is the structured-error foundation only. Mutation result shapes, allow_missing, durable request deduplication, and exec retry semantics remain follow-up work. Signed-off-by: Mrunal Patel <mrunalp@gmail.com> * fix(python): preserve wrapped RPC cleanup handling Inspect the original gRPC call when handling missing sandboxes during deletion waits and managed cleanup. Add intercepted cleanup regressions and clarify the error-wrapper migration contract. Addresses the cleanup review on ai-openshell/openshell#3313; part of ai-openshell/openshell#3051. Signed-off-by: Mrunal Patel <mrunalp@gmail.com> --------- Signed-off-by: Mrunal Patel <mrunalp@gmail.com>
1 parent 3139ece commit 8495461

6 files changed

Lines changed: 445 additions & 7 deletions

File tree

‎pyproject.toml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ requires-python = ">=3.11"
1616
dependencies = [
1717
"cloudpickle>=3.0",
1818
"grpcio>=1.60",
19+
"googleapis-common-protos>=1.63",
1920
"httpx>=0.27",
2021
"protobuf>=4.25",
2122
]

‎src/openshell/__init__.py‎

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

66
from __future__ import annotations
77

8+
from .errors import ErrorInfo, FieldViolation, GatewayError, from_grpc_error
89
from .sandbox import (
910
ClientCredentialsAuth,
1011
ExecChunk,
@@ -33,8 +34,11 @@
3334

3435
__all__ = [
3536
"ClientCredentialsAuth",
37+
"ErrorInfo",
3638
"ExecChunk",
3739
"ExecResult",
40+
"FieldViolation",
41+
"GatewayError",
3842
"Page",
3943
"Pager",
4044
"Sandbox",
@@ -49,4 +53,5 @@
4953
"WorkspaceClient",
5054
"WorkspaceRef",
5155
"__version__",
56+
"from_grpc_error",
5257
]

‎src/openshell/errors.py‎

Lines changed: 149 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,149 @@
1+
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2+
# SPDX-License-Identifier: Apache-2.0
3+
4+
"""Typed gateway errors that retain the original gRPC status and metadata."""
5+
6+
from __future__ import annotations
7+
8+
from dataclasses import dataclass
9+
10+
import grpc
11+
from google.protobuf.message import DecodeError
12+
from google.rpc import error_details_pb2, status_pb2
13+
14+
15+
@dataclass(frozen=True)
16+
class FieldViolation:
17+
"""A request field rejected by the gateway."""
18+
19+
field: str
20+
description: str
21+
22+
23+
@dataclass(frozen=True)
24+
class ErrorInfo:
25+
"""A machine-readable error reason scoped to its producing service."""
26+
27+
reason: str
28+
domain: str
29+
metadata: dict[str, str]
30+
31+
32+
class GatewayError(grpc.RpcError):
33+
"""A gRPC failure with decoded standard details.
34+
35+
``raw_error`` retains the complete original exception and metadata.
36+
``raw_status`` retains all decoded Any messages, including unknown types.
37+
A retry delay is guidance only; it does not make a mutation safe to repeat.
38+
Existing ``except grpc.RpcError`` handlers continue to match this type.
39+
"""
40+
41+
def __init__(self, error: grpc.RpcError) -> None:
42+
super().__init__(str(error))
43+
self.raw_error = error
44+
self.raw_status: status_pb2.Status | None = None
45+
self.field_violations: tuple[FieldViolation, ...] = ()
46+
self.error_info: ErrorInfo | None = None
47+
self.retry_delay: float | None = None
48+
trailing = getattr(error, "trailing_metadata", lambda: None)() or ()
49+
for key, value in trailing:
50+
if key != "grpc-status-details-bin" or not isinstance(value, bytes):
51+
continue
52+
try:
53+
status = status_pb2.Status.FromString(value)
54+
except DecodeError:
55+
continue
56+
# The transport status is authoritative. Inconsistent rich status
57+
# must not provide misleading recovery guidance.
58+
code = self.code()
59+
if (
60+
code is None
61+
or status.code != code.value[0]
62+
or status.message != self.details()
63+
):
64+
continue
65+
self.raw_status = status
66+
break
67+
if self.raw_status is None:
68+
return
69+
violations = []
70+
for detail in self.raw_status.details:
71+
try:
72+
if detail.Is(error_details_pb2.BadRequest.DESCRIPTOR):
73+
bad_request = error_details_pb2.BadRequest()
74+
detail.Unpack(bad_request)
75+
violations.extend(
76+
FieldViolation(v.field, v.description)
77+
for v in bad_request.field_violations
78+
)
79+
elif detail.Is(error_details_pb2.ErrorInfo.DESCRIPTOR):
80+
info = error_details_pb2.ErrorInfo()
81+
detail.Unpack(info)
82+
self.error_info = ErrorInfo(
83+
info.reason, info.domain, dict(info.metadata)
84+
)
85+
elif detail.Is(error_details_pb2.RetryInfo.DESCRIPTOR):
86+
retry = error_details_pb2.RetryInfo()
87+
detail.Unpack(retry)
88+
delay = retry.retry_delay
89+
if (
90+
retry.HasField("retry_delay")
91+
and 0 <= delay.seconds <= 315_576_000_000
92+
and 0 <= delay.nanos < 1_000_000_000
93+
):
94+
self.retry_delay = delay.seconds + delay.nanos / 1_000_000_000
95+
except DecodeError:
96+
continue
97+
self.field_violations = tuple(violations)
98+
99+
def code(self):
100+
"""Return the original gRPC status code."""
101+
return getattr(self.raw_error, "code", lambda: None)()
102+
103+
def details(self):
104+
"""Return the original human-readable gRPC message."""
105+
return getattr(self.raw_error, "details", lambda: str(self.raw_error))()
106+
107+
def __getattr__(self, name):
108+
return getattr(self.raw_error, name)
109+
110+
111+
def from_grpc_error(error: grpc.RpcError) -> GatewayError:
112+
"""Decode a raw RPC failure without discarding unrecognized details."""
113+
return error if isinstance(error, GatewayError) else GatewayError(error)
114+
115+
116+
class _ErrorMappingStream:
117+
def __init__(self, call):
118+
self._call = call
119+
self._iterator = iter(call)
120+
121+
def __iter__(self):
122+
return self
123+
124+
def __next__(self):
125+
try:
126+
return next(self._iterator)
127+
except grpc.RpcError as error:
128+
raise from_grpc_error(error) from error
129+
130+
def __getattr__(self, name):
131+
return getattr(self._call, name)
132+
133+
134+
class _ErrorMappingInterceptor(
135+
grpc.UnaryUnaryClientInterceptor, grpc.UnaryStreamClientInterceptor
136+
):
137+
def intercept_unary_unary(self, continuation, client_call_details, request):
138+
call = continuation(client_call_details, request)
139+
error = call.exception()
140+
if isinstance(error, grpc.RpcError):
141+
raise from_grpc_error(error) from error
142+
return call
143+
144+
def intercept_unary_stream(self, continuation, client_call_details, request):
145+
return _ErrorMappingStream(continuation(client_call_details, request))
146+
147+
148+
def _error_mapping_channel(channel):
149+
return grpc.intercept_channel(channel, _ErrorMappingInterceptor())

‎src/openshell/sandbox.py‎

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@
2828
openshell_pb2,
2929
openshell_pb2_grpc,
3030
)
31+
from .errors import GatewayError, _error_mapping_channel
3132

3233
_ClientCallDetailsBase = namedtuple(
3334
"_ClientCallDetailsBase",
@@ -618,7 +619,9 @@ def __init__(
618619
self._channel,
619620
_BearerAuthInterceptor(provider),
620621
)
621-
self._stub = openshell_pb2_grpc.OpenShellStub(self._channel)
622+
self._stub = openshell_pb2_grpc.OpenShellStub(
623+
_error_mapping_channel(self._channel)
624+
)
622625

623626
@classmethod
624627
def from_active_cluster(
@@ -988,9 +991,10 @@ def wait_deleted(
988991
try:
989992
self.get(sandbox_name, workspace=workspace)
990993
except grpc.RpcError as exc:
994+
call = exc.raw_error if isinstance(exc, GatewayError) else exc
991995
if (
992-
isinstance(exc, grpc.Call)
993-
and exc.code() == grpc.StatusCode.NOT_FOUND
996+
isinstance(call, grpc.Call)
997+
and call.code() == grpc.StatusCode.NOT_FOUND
994998
):
995999
return
9961000
raise
@@ -1175,7 +1179,7 @@ class SandboxTemplateClient:
11751179
"""gRPC client for reusable sandbox template lifecycle operations."""
11761180

11771181
def __init__(self, channel: grpc.Channel, *, timeout: float = 30.0) -> None:
1178-
self._stub = openshell_pb2_grpc.OpenShellStub(channel)
1182+
self._stub = openshell_pb2_grpc.OpenShellStub(_error_mapping_channel(channel))
11791183
self._timeout = timeout
11801184

11811185
@classmethod
@@ -1355,7 +1359,7 @@ class WorkspaceClient:
13551359
"""gRPC client for workspace lifecycle operations."""
13561360

13571361
def __init__(self, channel: grpc.Channel, *, timeout: float = 30.0) -> None:
1358-
self._stub = openshell_pb2_grpc.OpenShellStub(channel)
1362+
self._stub = openshell_pb2_grpc.OpenShellStub(_error_mapping_channel(channel))
13591363
self._timeout = timeout
13601364

13611365
@classmethod
@@ -1559,9 +1563,10 @@ def __exit__(self, *args: object) -> None:
15591563
workspace=self._workspace,
15601564
)
15611565
except grpc.RpcError as exc:
1566+
call = exc.raw_error if isinstance(exc, GatewayError) else exc
15621567
if (
1563-
not isinstance(exc, grpc.Call)
1564-
or exc.code() != grpc.StatusCode.NOT_FOUND
1568+
not isinstance(call, grpc.Call)
1569+
or call.code() != grpc.StatusCode.NOT_FOUND
15651570
):
15661571
raise
15671572
finally:

‎tests/errors_test.py‎

Lines changed: 127 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,127 @@
1+
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2+
# SPDX-License-Identifier: Apache-2.0
3+
4+
"""Rich error decoding and preservation across unary and streaming calls."""
5+
6+
from concurrent import futures
7+
8+
import grpc
9+
import pytest
10+
from google.rpc import error_details_pb2, status_pb2
11+
12+
from openshell.errors import GatewayError, _error_mapping_channel, from_grpc_error
13+
14+
15+
def rich_status():
16+
status = status_pb2.Status(
17+
code=grpc.StatusCode.UNAVAILABLE.value[0], message="try later"
18+
)
19+
retry = error_details_pb2.RetryInfo()
20+
retry.retry_delay.seconds = 1
21+
retry.retry_delay.nanos = 250_000_000
22+
for message in [
23+
error_details_pb2.BadRequest(
24+
field_violations=[
25+
error_details_pb2.BadRequest.FieldViolation(
26+
field="name", description="invalid name"
27+
),
28+
]
29+
),
30+
error_details_pb2.ErrorInfo(
31+
reason="GATEWAY_NOT_READY",
32+
domain="openshell.nvidia.com",
33+
metadata={"scope": "test"},
34+
),
35+
retry,
36+
]:
37+
detail = status.details.add()
38+
detail.Pack(message)
39+
status.details.add(
40+
type_url="type.googleapis.com/future.ErrorDetail", value=b"\x08\x01"
41+
)
42+
return status
43+
44+
45+
@pytest.mark.parametrize("streaming", [False, True])
46+
def test_maps_real_rpc_errors_without_losing_details(streaming):
47+
status = rich_status()
48+
49+
def fail(_request, context):
50+
context.set_trailing_metadata(
51+
(
52+
("grpc-status-details-bin", status.SerializeToString()),
53+
("request-id", "test-correlation"),
54+
)
55+
)
56+
context.abort(grpc.StatusCode.UNAVAILABLE, "try later")
57+
58+
server = grpc.server(futures.ThreadPoolExecutor(max_workers=1))
59+
handler = (
60+
grpc.unary_stream_rpc_method_handler
61+
if streaming
62+
else grpc.unary_unary_rpc_method_handler
63+
)
64+
server.add_generic_rpc_handlers(
65+
(grpc.method_handlers_generic_handler("test.Errors", {"Fail": handler(fail)}),)
66+
)
67+
port = server.add_insecure_port("127.0.0.1:0")
68+
server.start()
69+
try:
70+
with _error_mapping_channel(
71+
grpc.insecure_channel(f"127.0.0.1:{port}")
72+
) as channel:
73+
call = channel.unary_stream if streaming else channel.unary_unary
74+
with pytest.raises(GatewayError) as caught:
75+
response = call("/test.Errors/Fail")(b"", timeout=5)
76+
if streaming:
77+
list(response)
78+
error = caught.value
79+
assert error.code() == grpc.StatusCode.UNAVAILABLE
80+
assert error.details() == "try later"
81+
assert error.field_violations[0].field == "name"
82+
assert error.error_info is not None
83+
assert error.error_info.reason == "GATEWAY_NOT_READY"
84+
assert error.retry_delay == 1.25
85+
assert error.raw_status == status
86+
assert ("request-id", "test-correlation") in error.trailing_metadata()
87+
assert from_grpc_error(error) is error
88+
finally:
89+
server.stop(0).wait()
90+
91+
92+
class RawError(grpc.RpcError):
93+
def __init__(self, details):
94+
self._details = details
95+
96+
def code(self):
97+
return grpc.StatusCode.UNAVAILABLE
98+
99+
def details(self):
100+
return "try later"
101+
102+
def trailing_metadata(self):
103+
return [("grpc-status-details-bin", self._details)]
104+
105+
106+
def test_malformed_or_inconsistent_details_preserve_raw_error():
107+
for payload in [
108+
b"\xff",
109+
status_pb2.Status(code=3, message="different").SerializeToString(),
110+
]:
111+
raw = RawError(payload)
112+
error = from_grpc_error(raw)
113+
assert error.raw_error is raw
114+
assert error.raw_status is None
115+
assert error.retry_delay is None
116+
assert error.trailing_metadata() == raw.trailing_metadata()
117+
118+
119+
def test_malformed_known_detail_does_not_hide_other_details():
120+
status = rich_status()
121+
status.details.add(
122+
type_url="type.googleapis.com/google.rpc.BadRequest", value=b"\xff"
123+
)
124+
error = from_grpc_error(RawError(status.SerializeToString()))
125+
assert error.field_violations[0].field == "name"
126+
assert error.raw_status is not None
127+
assert len(error.raw_status.details) == 5

0 commit comments

Comments
 (0)