Skip to content

Commit 79d81b9

Browse files
fix(sandbox): acknowledge initial policy revision; expose SDK labels/selectors (ai-openshell/openshell#2170)
* fix(sandbox): acknowledge initial policy revision The supervisor loaded and enforced a sandbox-scoped policy but never told the gateway which revision it loaded. The policy poll loop seeded itself with the initial revision's hash on its first poll, so `policy_changed` was never true for that revision and `ReportPolicyStatus(LOADED)` — which only ran in the hot-reload branch — was never called. The revision stayed `Pending` and `current_policy_version` stayed 0 even though the sandbox was `Ready` and the policy was effective. This was most visible with sparse policies that get baseline-enriched into a new revision during startup. After the OPA engine is constructed, report the exact sandbox revision the supervisor loaded as LOADED, and seed the poll loop from that revision so it is not re-reported. Report FAILED with the original construction error if engine construction or conversion fails. Only sandbox-sourced revisions (version > 0) whose canonical content matches the loaded policy are acknowledged; global and local-file policies are untouched. Delivery uses the shared bounded retry, is non-fatal on transient failure, and a pending initial acknowledgement is delivered before any newer revision so policy history is never reordered. Signed-off-by: Kyle Zheng <kyzheng@nvidia.com> * feat(python): expose sandbox labels and selectors The gateway protobuf and CLI already support request-level sandbox labels (`CreateSandboxRequest.name`/`labels`) and selector-based listing (`ListSandboxesRequest.label_selector`), but the public Python SDK dropped them, so Python-created sandboxes could not be found via `openshell sandbox list --selector ...`. Add optional, source-compatible `name`/`labels` to `SandboxClient.create`, `create_session`, and the high-level `Sandbox`, and `label_selector` to `list`/`list_ids`. `SandboxRef` now carries the gateway labels as an immutable mapping (default empty, so `SandboxRef(id, name, status)` still works). Caller-provided label mappings are copied. Attaching the high-level `Sandbox` to an existing sandbox rejects `name`/`labels` since creation metadata cannot change on attach. Template labels remain a separate concept. No protobuf changes are required. Signed-off-by: Kyle Zheng <kyzheng@nvidia.com> * fix(python): keep SandboxRef hashable and copy high-level labels Excluding the new immutable `labels` field from SandboxRef equality/hash (`compare=False`) preserves the original (id, name, status) identity and keeps the frozen dataclass hashable — a MappingProxyType field would otherwise make `hash(SandboxRef(...))` raise. Also defensively copy caller-provided labels in the high-level `Sandbox` so later caller mutation cannot change what is sent. Signed-off-by: Kyle Zheng <kyzheng@nvidia.com> * fix(sandbox): bound initial-policy-ack retries The poll loop retried a pending initial acknowledgement before processing any newer revision, but retried unconditionally forever. A permanently undeliverable ack (e.g. the revision was superseded before it could be reported) would then stall all later policy hot-reloads and provider-env refreshes. Cap the retries; after the bound, give up and resume normal polling so the loop cannot livelock on a stuck acknowledgement. Signed-off-by: Kyle Zheng <kyzheng@nvidia.com> * test(sandbox): add sparse-policy revision-2 acknowledgement e2e Regression for ai-openshell/openshell#2159: create a sandbox with the network-only policy-advisor fixture, which the supervisor enriches with baseline filesystem paths during startup (creating revision 2, superseding revision 1). Assert the effective policy reaches revision 2 and no revision remains Pending once the supervisor acknowledges the load. Adds SandboxGuard::create_keep_with_args to create a kept sandbox with an initial --policy. Signed-off-by: Kyle Zheng <kyzheng@nvidia.com> * fix(ci): correct sandbox checks Signed-off-by: Kyle Zheng <kyzheng@nvidia.com> * test(cli): serialize mTLS environment access Signed-off-by: Kyle Zheng <kyzheng@nvidia.com> * fix(sandbox): address policy review feedback Signed-off-by: Kyle Zheng <kyzheng@nvidia.com> * fix(sandbox): preserve exact policy acknowledgements Signed-off-by: Kyle Zheng <kyzheng@nvidia.com> * fix(sandbox): preserve local policy overrides Signed-off-by: John Myers <9696606+johntmyers@users.noreply.github.com> --------- Signed-off-by: Kyle Zheng <kyzheng@nvidia.com> Signed-off-by: John Myers <9696606+johntmyers@users.noreply.github.com> Co-authored-by: John Myers <9696606+johntmyers@users.noreply.github.com>
1 parent 9b6aebc commit 79d81b9

2 files changed

Lines changed: 365 additions & 10 deletions

File tree

‎src/openshell/sandbox.py‎

Lines changed: 86 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,8 @@
1313
import threading
1414
import time
1515
from collections import namedtuple
16-
from dataclasses import dataclass
17-
from typing import TYPE_CHECKING, cast
16+
from dataclasses import dataclass, field
17+
from typing import TYPE_CHECKING, Any, Never, SupportsIndex, cast
1818
from urllib.parse import urlparse
1919

2020
import grpc
@@ -130,11 +130,42 @@ class SandboxStatusRef:
130130
current_policy_version: int
131131

132132

133+
class _ImmutableLabels(dict[str, str]):
134+
"""A read-only, copy- and pickle-safe label mapping."""
135+
136+
def _deny_mutation(self, *args: object, **kwargs: object) -> Never:
137+
del args, kwargs
138+
raise TypeError("sandbox labels are immutable")
139+
140+
__setitem__ = _deny_mutation
141+
__delitem__ = _deny_mutation
142+
clear = _deny_mutation
143+
pop = _deny_mutation
144+
popitem = _deny_mutation
145+
setdefault = _deny_mutation
146+
update = _deny_mutation
147+
__ior__ = _deny_mutation
148+
149+
def __deepcopy__(self, memo: dict[int, object]) -> _ImmutableLabels:
150+
del memo
151+
return type(self)(self)
152+
153+
def __reduce_ex__(self, protocol: SupportsIndex, /) -> str | tuple[Any, ...]:
154+
del protocol
155+
return type(self), (dict(self),)
156+
157+
133158
@dataclass(frozen=True)
134159
class SandboxRef:
135160
id: str
136161
name: str
137162
status: SandboxStatusRef
163+
# Excluded from equality/hash to preserve the original identity while the
164+
# immutable mapping remains safe for deepcopy, pickle, and asdict.
165+
labels: Mapping[str, str] = field(default_factory=_ImmutableLabels, compare=False)
166+
167+
def __post_init__(self) -> None:
168+
object.__setattr__(self, "labels", _ImmutableLabels(self.labels))
138169

139170
@property
140171
def phase(self) -> int:
@@ -397,10 +428,16 @@ def create(
397428
self,
398429
*,
399430
spec: openshell_pb2.SandboxSpec | None = None,
431+
name: str | None = None,
432+
labels: Mapping[str, str] | None = None,
400433
) -> SandboxRef:
401434
request_spec = spec if spec is not None else _default_spec()
402435
response = self._stub.CreateSandbox(
403-
openshell_pb2.CreateSandboxRequest(spec=request_spec),
436+
openshell_pb2.CreateSandboxRequest(
437+
spec=request_spec,
438+
name=name or "",
439+
labels=dict(labels) if labels else {},
440+
),
404441
timeout=self._timeout,
405442
)
406443
sandbox_ref = _sandbox_ref(response.sandbox)
@@ -412,8 +449,10 @@ def create_session(
412449
self,
413450
*,
414451
spec: openshell_pb2.SandboxSpec | None = None,
452+
name: str | None = None,
453+
labels: Mapping[str, str] | None = None,
415454
) -> SandboxSession:
416-
return SandboxSession(self, self.create(spec=spec))
455+
return SandboxSession(self, self.create(spec=spec, name=name, labels=labels))
417456

418457
def get(self, sandbox_name: str) -> SandboxRef:
419458
response = self._stub.GetSandbox(
@@ -425,15 +464,36 @@ def get(self, sandbox_name: str) -> SandboxRef:
425464
def get_session(self, sandbox_name: str) -> SandboxSession:
426465
return SandboxSession(self, self.get(sandbox_name))
427466

428-
def list(self, *, limit: int = 100, offset: int = 0) -> builtins.list[SandboxRef]:
467+
def list(
468+
self,
469+
*,
470+
limit: int = 100,
471+
offset: int = 0,
472+
label_selector: str | None = None,
473+
) -> builtins.list[SandboxRef]:
429474
response = self._stub.ListSandboxes(
430-
openshell_pb2.ListSandboxesRequest(limit=limit, offset=offset),
475+
openshell_pb2.ListSandboxesRequest(
476+
limit=limit,
477+
offset=offset,
478+
label_selector=label_selector or "",
479+
),
431480
timeout=self._timeout,
432481
)
433482
return [_sandbox_ref(item) for item in response.sandboxes]
434483

435-
def list_ids(self, *, limit: int = 100, offset: int = 0) -> builtins.list[str]:
436-
return [item.id for item in self.list(limit=limit, offset=offset)]
484+
def list_ids(
485+
self,
486+
*,
487+
limit: int = 100,
488+
offset: int = 0,
489+
label_selector: str | None = None,
490+
) -> builtins.list[str]:
491+
return [
492+
item.id
493+
for item in self.list(
494+
limit=limit, offset=offset, label_selector=label_selector
495+
)
496+
]
437497

438498
def delete(self, sandbox_name: str) -> bool:
439499
response = self._stub.DeleteSandbox(
@@ -646,6 +706,8 @@ def __init__(
646706
sandbox: str | SandboxRef | None = None,
647707
delete_on_exit: bool = True,
648708
spec: openshell_pb2.SandboxSpec | None = None,
709+
name: str | None = None,
710+
labels: Mapping[str, str] | None = None,
649711
timeout: float = 30.0,
650712
ready_timeout_seconds: float = 120.0,
651713
auto_refresh: bool = True,
@@ -665,6 +727,9 @@ def __init__(
665727
self._sandbox_input = sandbox
666728
self._delete_on_exit = delete_on_exit
667729
self._spec = spec
730+
self._name = name
731+
# Copy so later caller mutation cannot change what gets sent on enter.
732+
self._labels = dict(labels) if labels is not None else None
668733
self._timeout = timeout
669734
self._ready_timeout_seconds = ready_timeout_seconds
670735
self._auto_refresh = auto_refresh
@@ -686,6 +751,15 @@ def sandbox(self) -> SandboxRef:
686751
return self._session.sandbox
687752

688753
def __enter__(self) -> Sandbox:
754+
# Creation metadata cannot be applied when attaching to an existing
755+
# sandbox; reject it before opening a connection.
756+
if self._sandbox_input is not None and (
757+
self._name is not None or self._labels is not None
758+
):
759+
raise SandboxError(
760+
"name and labels cannot be set when attaching to an existing sandbox"
761+
)
762+
689763
client = SandboxClient.from_active_cluster(
690764
cluster=self._cluster,
691765
timeout=self._timeout,
@@ -696,7 +770,9 @@ def __enter__(self) -> Sandbox:
696770
self._client = client
697771

698772
if self._sandbox_input is None:
699-
self._session = client.create_session(spec=self._spec)
773+
self._session = client.create_session(
774+
spec=self._spec, name=self._name, labels=self._labels
775+
)
700776
elif isinstance(self._sandbox_input, SandboxRef):
701777
self._session = SandboxSession(client, self._sandbox_input)
702778
else:
@@ -813,6 +889,7 @@ def _sandbox_ref(sandbox: openshell_pb2.Sandbox) -> SandboxRef:
813889
phase=status.phase if status else 0,
814890
current_policy_version=status.current_policy_version if status else 0,
815891
),
892+
labels=sandbox.metadata.labels if sandbox.metadata else {},
816893
)
817894

818895

0 commit comments

Comments
 (0)