mirror of
https://github.com/NVIDIA/OpenShell.git
synced 2026-10-02 07:34:45 +08:00
feat(workspace): add workspace resource model with scoping, membershi… (#2243)
* feat(workspace): implement workspace model (Phase 1 of RFC 0011) Implements workspace and membership model providing hard isolation boundaries for multi-player OpenShell deployments. Workspace CRUD with Kubernetes-style Terminating phase for graceful deletion. All resources scoped by workspace via ObjectMeta. Membership RPCs for workspace access control. Persistence migration shifts name uniqueness to (object_type, workspace, name). Provider profiles support platform and workspace scoping. Service routing uses workspace-prefixed DNS labels. Inference routes renamed and workspace-scoped with DeleteInferenceRoute RPC. Python SDK with WorkspaceClient, two-method list pattern (workspace-scoped and for_all_workspaces), and workspace parameter on all methods. CLI workspace flags, TUI workspace cycling. K8s driver filters unmanaged CRs and uses delete preconditions. Podman driver uses immutable container IDs. Label serialization fixed across all put_if call sites. Signed-off-by: Derek Carr <decarr@redhat.com> * fix(cli): delegate sandbox upload command to existing upload function The standalone `sandbox upload` command reimplemented upload logic inline with two bugs: it used `Path::exists()` which follows symlinks (rejecting dangling symlinks), and it ran git-aware filtering on symlink sources. The `run::sandbox_upload()` function already handles both cases correctly via `sandbox_upload_plan()`. Replace the inline logic with a call to the existing function. Signed-off-by: Derek Carr <decarr@redhat.com> * fix(e2e): shorten sandbox names and fix test compatibility Shorten the sandbox name in initial_sparse_policy_is_acknowledged_as_loaded from 'e2e-2159-sparse-enrich' (22 chars) to 'e2e-sparse-enrich' (17 chars) to comply with MAX_ROUTABLE_NAME_LEN (19 chars). Also capture stderr in create_keep_with_args so future sandbox creation failures include the actual CLI error instead of reporting empty output. Signed-off-by: Derek Carr <decarr@redhat.com> * test(workspace): add test coverage for workspace CRUD and persistence isolation Add unit tests for workspace create happy path, get round-trip, get not-found, get empty-name rejection, already-exists error, and resolve_workspace not-found. Add persistence test proving cross-workspace name uniqueness (same name in different workspaces produces separate records). Add workspace name max-length boundary tests. Fix e2e harness to include stderr in name-parse-failure error path. Align Python e2e test_workspace_crud with try/finally pattern. Document provider profile catalog workspace scoping gap in RFC 0011. Signed-off-by: Derek Carr <decarr@redhat.com> * fix(examples): update examples for workspace model compatibility Shorten sandbox names in demo scripts to fit the 19-character MAX_ROUTABLE_NAME_LEN limit: policy-demo prefix to pd-, multi-agent notepad derives a short SANDBOX_TAG from the run ID, governance interceptor uses gs-PID-RANDOM. Update vscode-remote-sandbox.md SSH host aliases from openshell-{name} to openshell-{name}.{workspace} format. Signed-off-by: Derek Carr <decarr@redhat.com> * feat(sdk): add workspace-scoped client and workspace CRUD Add WorkspaceScopedClient modeled after kube::Api::namespaced — captures workspace once and injects it into every sandbox request. Add workspace CRUD methods (create, get, list, delete) and list_sandboxes_all_workspaces on OpenShellClient. Extend SandboxRef with workspace field and add WorkspaceRef type. Include mock tests for all new operations. Signed-off-by: Derek Carr <decarr@redhat.com> * fix(lint): resolve clippy warnings in workspace test assertions Signed-off-by: Derek Carr <decarr@redhat.com> * fix(docs): convert indented code blocks to fenced in RFC 0011 Signed-off-by: Derek Carr <decarr@redhat.com> * fix(lint): resolve clippy warnings and apply cargo fmt across workspace Auto-format with cargo fmt and fix clippy warnings exposed by the reformat: unnecessary qualifications, map_unwrap_or, identical match arms, unused variable prefix, dead code annotations, and let-unit-value in e2e harness. Signed-off-by: Derek Carr <decarr@redhat.com> * fix(workspace): address workspace scoping issues from review - Add workspace field to settings JSON output (CLI) - Skip Podman containers missing workspace label instead of defaulting to empty string, matching K8s driver behavior - Add resource_version to list_by_scope SELECT in both SQLite and Postgres backends, with regression test - Gate PolicyLocalContext proposal/lookup routes on workspace readiness, returning 503 when workspace is not yet discovered - Block sandbox and provider creation in TUI all-workspaces mode - Clear workspace vectors in TUI reset_sandbox_state Signed-off-by: Derek Carr <decarr@redhat.com> * fix(workspace): make provider profile catalog workspace-aware Thread workspace through snapshot_catalog so the EffectiveProviderProfileCatalog enforces workspace boundaries on both read and write paths. UserProviderProfileSource now loads platform-scoped profiles (workspace "") plus the target workspace's profiles, preventing cross-workspace duplicate profile ID collisions that previously caused global catalog failures. Update RFC 0011 to reflect catalog scoping is implemented in Phase 1 rather than deferred to future work. Signed-off-by: Derek Carr <decarr@redhat.com> * fix(persistence): include workspace column in atomic policy revision INSERT put_policy_revision_atomic omitted the workspace column from the INSERT into the objects table in both SQLite and Postgres backends, causing atomically-written policy revisions to lose their workspace association. Add workspace field to AtomicPolicyRevisionWrite and thread it through both backend INSERT statements, matching the non-atomic put_policy_revision path which already included it. Signed-off-by: Derek Carr <decarr@redhat.com> * fix(proxy): skip ancestor walk when socket owner is the entrypoint collect_ancestor_identities walked the entire process tree above the entrypoint when the connecting process was the entrypoint itself, SHA256-hashing every ancestor binary (IDE, shell, container runtime). On dev machines with large binaries in the ancestor chain this exceeded the 30-second test timeout. When start_pid == stop_pid there are no intermediate ancestors to verify, so return an empty list immediately. Signed-off-by: Derek Carr <decarr@redhat.com> * fix(workspace): make provider profile catalog scope-aware Allow the same profile ID at platform and workspace scopes by introducing layered catalog entries where workspace profiles shadow platform profiles. Add source and scope fields to the ProviderProfile proto and CLI output. Migrate List/Get handlers to the catalog, fixing divergence with runtime profile resolution. Signed-off-by: Derek Carr <decarr@redhat.com> * fix(e2e): align podman e2e labels with centralized driver constants The podman driver moved its container labels to the centralized openshell.ai/ prefix, but the e2e test harness and cleanup script still referenced the old openshell.sandbox-* keys, causing the local_driver_token_restart test to fail on container lookup. Signed-off-by: Derek Carr <decarr@redhat.com> * fix(e2e): align python profile isolation test with scope-aware catalog Platform profiles are now visible in workspace listings as fallbacks per the layered catalog design. Update the assertion to match. Signed-off-by: Derek Carr <decarr@redhat.com> * fix(workspace): honor profile_workspace in runtime profile resolution Runtime profile lookups now consult provider.profile_workspace via get_type_profile_for_scope. Providers created with --global-profile (profile_workspace="") resolve to the platform profile even when a workspace profile shadows the same ID. All 6 runtime call sites updated; type-only call sites remain scope-agnostic. Signed-off-by: Derek Carr <decarr@redhat.com> --------- Signed-off-by: Derek Carr <decarr@redhat.com>
This commit is contained in:
@@ -6,10 +6,10 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from .sandbox import (
|
||||
ClusterInferenceConfig,
|
||||
ExecChunk,
|
||||
ExecResult,
|
||||
InferenceRouteClient,
|
||||
InferenceRouteConfig,
|
||||
Sandbox,
|
||||
SandboxClient,
|
||||
SandboxError,
|
||||
@@ -17,6 +17,8 @@ from .sandbox import (
|
||||
SandboxSession,
|
||||
SandboxStatusRef,
|
||||
TlsConfig,
|
||||
WorkspaceClient,
|
||||
WorkspaceRef,
|
||||
)
|
||||
|
||||
try:
|
||||
@@ -27,10 +29,10 @@ except Exception:
|
||||
__version__ = "0.0.0"
|
||||
|
||||
__all__ = [
|
||||
"ClusterInferenceConfig",
|
||||
"ExecChunk",
|
||||
"ExecResult",
|
||||
"InferenceRouteClient",
|
||||
"InferenceRouteConfig",
|
||||
"Sandbox",
|
||||
"SandboxClient",
|
||||
"SandboxError",
|
||||
@@ -38,5 +40,7 @@ __all__ = [
|
||||
"SandboxSession",
|
||||
"SandboxStatusRef",
|
||||
"TlsConfig",
|
||||
"WorkspaceClient",
|
||||
"WorkspaceRef",
|
||||
"__version__",
|
||||
]
|
||||
|
||||
+186
-35
@@ -21,6 +21,7 @@ import grpc
|
||||
import httpx
|
||||
|
||||
from ._proto import (
|
||||
datamodel_pb2,
|
||||
inference_pb2,
|
||||
inference_pb2_grpc,
|
||||
openshell_pb2,
|
||||
@@ -159,6 +160,7 @@ class _ImmutableLabels(dict[str, str]):
|
||||
class SandboxRef:
|
||||
id: str
|
||||
name: str
|
||||
workspace: str
|
||||
status: SandboxStatusRef
|
||||
# Excluded from equality/hash to preserve the original identity while the
|
||||
# immutable mapping remains safe for deepcopy, pickle, and asdict.
|
||||
@@ -197,6 +199,7 @@ class SandboxSession:
|
||||
def __init__(self, client: SandboxClient, sandbox: SandboxRef) -> None:
|
||||
self._client = client
|
||||
self.sandbox = sandbox
|
||||
self._workspace = sandbox.workspace
|
||||
|
||||
@property
|
||||
def id(self) -> str:
|
||||
@@ -245,7 +248,7 @@ class SandboxSession:
|
||||
)
|
||||
|
||||
def delete(self) -> bool:
|
||||
return self._client.delete(self.sandbox.name)
|
||||
return self._client.delete(self.sandbox.name, workspace=self._workspace)
|
||||
|
||||
|
||||
class SandboxClient:
|
||||
@@ -427,6 +430,7 @@ class SandboxClient:
|
||||
def create(
|
||||
self,
|
||||
*,
|
||||
workspace: str,
|
||||
spec: openshell_pb2.SandboxSpec | None = None,
|
||||
name: str | None = None,
|
||||
labels: Mapping[str, str] | None = None,
|
||||
@@ -437,6 +441,7 @@ class SandboxClient:
|
||||
spec=request_spec,
|
||||
name=name or "",
|
||||
labels=dict(labels) if labels else {},
|
||||
workspace=workspace,
|
||||
),
|
||||
timeout=self._timeout,
|
||||
)
|
||||
@@ -448,40 +453,77 @@ class SandboxClient:
|
||||
def create_session(
|
||||
self,
|
||||
*,
|
||||
workspace: str,
|
||||
spec: openshell_pb2.SandboxSpec | None = None,
|
||||
name: str | None = None,
|
||||
labels: Mapping[str, str] | None = None,
|
||||
) -> SandboxSession:
|
||||
return SandboxSession(self, self.create(spec=spec, name=name, labels=labels))
|
||||
return SandboxSession(
|
||||
self, self.create(workspace=workspace, spec=spec, name=name, labels=labels)
|
||||
)
|
||||
|
||||
def get(self, sandbox_name: str) -> SandboxRef:
|
||||
def get(self, sandbox_name: str, *, workspace: str) -> SandboxRef:
|
||||
response = self._stub.GetSandbox(
|
||||
openshell_pb2.GetSandboxRequest(name=sandbox_name),
|
||||
openshell_pb2.GetSandboxRequest(name=sandbox_name, workspace=workspace),
|
||||
timeout=self._timeout,
|
||||
)
|
||||
return _sandbox_ref(response.sandbox)
|
||||
|
||||
def get_session(self, sandbox_name: str) -> SandboxSession:
|
||||
return SandboxSession(self, self.get(sandbox_name))
|
||||
def get_session(self, sandbox_name: str, *, workspace: str) -> SandboxSession:
|
||||
return SandboxSession(self, self.get(sandbox_name, workspace=workspace))
|
||||
|
||||
def list(
|
||||
self,
|
||||
*,
|
||||
workspace: str,
|
||||
limit: int = 100,
|
||||
offset: int = 0,
|
||||
label_selector: str | None = None,
|
||||
) -> builtins.list[SandboxRef]:
|
||||
request = openshell_pb2.ListSandboxesRequest(
|
||||
workspace=workspace,
|
||||
limit=limit,
|
||||
offset=offset,
|
||||
label_selector=label_selector or "",
|
||||
)
|
||||
response = self._stub.ListSandboxes(request, timeout=self._timeout)
|
||||
return [_sandbox_ref(item) for item in response.sandboxes]
|
||||
|
||||
def list_for_all_workspaces(
|
||||
self,
|
||||
*,
|
||||
limit: int = 100,
|
||||
offset: int = 0,
|
||||
label_selector: str | None = None,
|
||||
) -> builtins.list[SandboxRef]:
|
||||
response = self._stub.ListSandboxes(
|
||||
openshell_pb2.ListSandboxesRequest(
|
||||
limit=limit,
|
||||
offset=offset,
|
||||
label_selector=label_selector or "",
|
||||
),
|
||||
timeout=self._timeout,
|
||||
request = openshell_pb2.ListSandboxesRequest(
|
||||
all_workspaces=True,
|
||||
limit=limit,
|
||||
offset=offset,
|
||||
label_selector=label_selector or "",
|
||||
)
|
||||
response = self._stub.ListSandboxes(request, timeout=self._timeout)
|
||||
return [_sandbox_ref(item) for item in response.sandboxes]
|
||||
|
||||
def list_ids(
|
||||
self,
|
||||
*,
|
||||
workspace: str,
|
||||
limit: int = 100,
|
||||
offset: int = 0,
|
||||
label_selector: str | None = None,
|
||||
) -> builtins.list[str]:
|
||||
return [
|
||||
item.id
|
||||
for item in self.list(
|
||||
workspace=workspace,
|
||||
limit=limit,
|
||||
offset=offset,
|
||||
label_selector=label_selector,
|
||||
)
|
||||
]
|
||||
|
||||
def list_ids_for_all_workspaces(
|
||||
self,
|
||||
*,
|
||||
limit: int = 100,
|
||||
@@ -490,23 +532,27 @@ class SandboxClient:
|
||||
) -> builtins.list[str]:
|
||||
return [
|
||||
item.id
|
||||
for item in self.list(
|
||||
limit=limit, offset=offset, label_selector=label_selector
|
||||
for item in self.list_for_all_workspaces(
|
||||
limit=limit,
|
||||
offset=offset,
|
||||
label_selector=label_selector,
|
||||
)
|
||||
]
|
||||
|
||||
def delete(self, sandbox_name: str) -> bool:
|
||||
def delete(self, sandbox_name: str, *, workspace: str) -> bool:
|
||||
response = self._stub.DeleteSandbox(
|
||||
openshell_pb2.DeleteSandboxRequest(name=sandbox_name),
|
||||
openshell_pb2.DeleteSandboxRequest(name=sandbox_name, workspace=workspace),
|
||||
timeout=self._timeout,
|
||||
)
|
||||
return bool(response.deleted)
|
||||
|
||||
def wait_deleted(self, sandbox_name: str, *, timeout_seconds: float = 60.0) -> None:
|
||||
def wait_deleted(
|
||||
self, sandbox_name: str, *, workspace: str, timeout_seconds: float = 60.0
|
||||
) -> None:
|
||||
deadline = time.time() + timeout_seconds
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
self.get(sandbox_name)
|
||||
self.get(sandbox_name, workspace=workspace)
|
||||
except grpc.RpcError as exc:
|
||||
if (
|
||||
isinstance(exc, grpc.Call)
|
||||
@@ -518,11 +564,11 @@ class SandboxClient:
|
||||
raise SandboxError(f"sandbox {sandbox_name} was not deleted within timeout")
|
||||
|
||||
def wait_ready(
|
||||
self, sandbox_name: str, *, timeout_seconds: float = 300.0
|
||||
self, sandbox_name: str, *, workspace: str, timeout_seconds: float = 300.0
|
||||
) -> SandboxRef:
|
||||
deadline = time.time() + timeout_seconds
|
||||
while time.time() < deadline:
|
||||
sandbox = self.get(sandbox_name)
|
||||
sandbox = self.get(sandbox_name, workspace=workspace)
|
||||
if sandbox.status.phase == openshell_pb2.SANDBOX_PHASE_READY:
|
||||
return sandbox
|
||||
if sandbox.status.phase == openshell_pb2.SANDBOX_PHASE_ERROR:
|
||||
@@ -646,14 +692,14 @@ class SandboxClient:
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ClusterInferenceConfig:
|
||||
class InferenceRouteConfig:
|
||||
provider_name: str
|
||||
model_id: str
|
||||
version: int
|
||||
|
||||
|
||||
class InferenceRouteClient:
|
||||
"""gRPC client for cluster-level inference configuration."""
|
||||
"""gRPC client for workspace-scoped inference route configuration."""
|
||||
|
||||
def __init__(self, channel: grpc.Channel, *, timeout: float = 30.0) -> None:
|
||||
self._stub = inference_pb2_grpc.InferenceStub(channel)
|
||||
@@ -663,38 +709,129 @@ class InferenceRouteClient:
|
||||
def from_sandbox_client(cls, client: SandboxClient) -> InferenceRouteClient:
|
||||
return cls(client._channel, timeout=client._timeout)
|
||||
|
||||
def set_cluster(
|
||||
def set_route(
|
||||
self,
|
||||
*,
|
||||
workspace: str,
|
||||
provider_name: str,
|
||||
model_id: str,
|
||||
no_verify: bool = False,
|
||||
) -> ClusterInferenceConfig:
|
||||
response = self._stub.SetClusterInference(
|
||||
inference_pb2.SetClusterInferenceRequest(
|
||||
) -> InferenceRouteConfig:
|
||||
response = self._stub.SetInferenceRoute(
|
||||
inference_pb2.SetInferenceRouteRequest(
|
||||
workspace=workspace,
|
||||
provider_name=provider_name,
|
||||
model_id=model_id,
|
||||
no_verify=no_verify,
|
||||
),
|
||||
timeout=self._timeout,
|
||||
)
|
||||
return ClusterInferenceConfig(
|
||||
return InferenceRouteConfig(
|
||||
provider_name=response.provider_name,
|
||||
model_id=response.model_id,
|
||||
version=response.version,
|
||||
)
|
||||
|
||||
def get_cluster(self) -> ClusterInferenceConfig:
|
||||
response = self._stub.GetClusterInference(
|
||||
inference_pb2.GetClusterInferenceRequest(),
|
||||
def get_route(self, *, workspace: str) -> InferenceRouteConfig:
|
||||
response = self._stub.GetInferenceRoute(
|
||||
inference_pb2.GetInferenceRouteRequest(workspace=workspace),
|
||||
timeout=self._timeout,
|
||||
)
|
||||
return ClusterInferenceConfig(
|
||||
return InferenceRouteConfig(
|
||||
provider_name=response.provider_name,
|
||||
model_id=response.model_id,
|
||||
version=response.version,
|
||||
)
|
||||
|
||||
def delete_route(
|
||||
self,
|
||||
*,
|
||||
workspace: str,
|
||||
route_name: str = "",
|
||||
) -> bool:
|
||||
response = self._stub.DeleteInferenceRoute(
|
||||
inference_pb2.DeleteInferenceRouteRequest(
|
||||
workspace=workspace,
|
||||
route_name=route_name,
|
||||
),
|
||||
timeout=self._timeout,
|
||||
)
|
||||
return response.deleted
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class WorkspaceRef:
|
||||
name: str
|
||||
phase: str
|
||||
labels: dict[str, str]
|
||||
|
||||
|
||||
def _workspace_ref(ws: datamodel_pb2.Workspace) -> WorkspaceRef:
|
||||
meta = ws.metadata
|
||||
return WorkspaceRef(
|
||||
name=meta.name,
|
||||
phase=datamodel_pb2.WorkspacePhase.Name(ws.status.phase),
|
||||
labels=dict(meta.labels),
|
||||
)
|
||||
|
||||
|
||||
class WorkspaceClient:
|
||||
"""gRPC client for workspace lifecycle operations."""
|
||||
|
||||
def __init__(self, channel: grpc.Channel, *, timeout: float = 30.0) -> None:
|
||||
self._stub = openshell_pb2_grpc.OpenShellStub(channel)
|
||||
self._timeout = timeout
|
||||
|
||||
@classmethod
|
||||
def from_sandbox_client(cls, client: SandboxClient) -> WorkspaceClient:
|
||||
return cls(client._channel, timeout=client._timeout)
|
||||
|
||||
def create(
|
||||
self,
|
||||
name: str,
|
||||
*,
|
||||
labels: Mapping[str, str] | None = None,
|
||||
) -> WorkspaceRef:
|
||||
response = self._stub.CreateWorkspace(
|
||||
openshell_pb2.CreateWorkspaceRequest(
|
||||
name=name,
|
||||
labels=dict(labels) if labels else {},
|
||||
),
|
||||
timeout=self._timeout,
|
||||
)
|
||||
return _workspace_ref(response.workspace)
|
||||
|
||||
def get(self, name: str) -> WorkspaceRef:
|
||||
response = self._stub.GetWorkspace(
|
||||
openshell_pb2.GetWorkspaceRequest(name=name),
|
||||
timeout=self._timeout,
|
||||
)
|
||||
return _workspace_ref(response.workspace)
|
||||
|
||||
def list(
|
||||
self,
|
||||
*,
|
||||
limit: int = 100,
|
||||
offset: int = 0,
|
||||
label_selector: str | None = None,
|
||||
) -> builtins.list[WorkspaceRef]:
|
||||
response = self._stub.ListWorkspaces(
|
||||
openshell_pb2.ListWorkspacesRequest(
|
||||
limit=limit,
|
||||
offset=offset,
|
||||
label_selector=label_selector or "",
|
||||
),
|
||||
timeout=self._timeout,
|
||||
)
|
||||
return [_workspace_ref(ws) for ws in response.workspaces]
|
||||
|
||||
def delete(self, name: str) -> bool:
|
||||
response = self._stub.DeleteWorkspace(
|
||||
openshell_pb2.DeleteWorkspaceRequest(name=name),
|
||||
timeout=self._timeout,
|
||||
)
|
||||
return response.deleted
|
||||
|
||||
|
||||
class Sandbox:
|
||||
"""Context-managed sandbox session bound to one sandbox id."""
|
||||
@@ -702,6 +839,7 @@ class Sandbox:
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
workspace: str,
|
||||
cluster: str | None = None,
|
||||
sandbox: str | SandboxRef | None = None,
|
||||
delete_on_exit: bool = True,
|
||||
@@ -723,6 +861,7 @@ class Sandbox:
|
||||
OIDC-protected gateways (e.g. passing `insecure=True` for a
|
||||
self-signed dev IdP). Non-OIDC gateways ignore them.
|
||||
"""
|
||||
self._workspace = workspace
|
||||
self._cluster = cluster
|
||||
self._sandbox_input = sandbox
|
||||
self._delete_on_exit = delete_on_exit
|
||||
@@ -771,15 +910,23 @@ class Sandbox:
|
||||
|
||||
if self._sandbox_input is None:
|
||||
self._session = client.create_session(
|
||||
spec=self._spec, name=self._name, labels=self._labels
|
||||
workspace=self._workspace,
|
||||
spec=self._spec,
|
||||
name=self._name,
|
||||
labels=self._labels,
|
||||
)
|
||||
elif isinstance(self._sandbox_input, SandboxRef):
|
||||
self._session = SandboxSession(client, self._sandbox_input)
|
||||
else:
|
||||
self._session = client.get_session(self._sandbox_input)
|
||||
self._session = client.get_session(
|
||||
self._sandbox_input, workspace=self._workspace
|
||||
)
|
||||
|
||||
self._workspace = getattr(self._session, "_workspace", self._workspace)
|
||||
|
||||
ready = client.wait_ready(
|
||||
self._session.sandbox.name,
|
||||
workspace=self._workspace,
|
||||
timeout_seconds=self._ready_timeout_seconds,
|
||||
)
|
||||
self._session = SandboxSession(client, ready)
|
||||
@@ -796,7 +943,10 @@ class Sandbox:
|
||||
try:
|
||||
deleted = self._session.delete()
|
||||
if deleted:
|
||||
self._client.wait_deleted(self._session.sandbox.name)
|
||||
self._client.wait_deleted(
|
||||
self._session.sandbox.name,
|
||||
workspace=self._workspace,
|
||||
)
|
||||
except grpc.RpcError as exc:
|
||||
if (
|
||||
not isinstance(exc, grpc.Call)
|
||||
@@ -885,6 +1035,7 @@ def _sandbox_ref(sandbox: openshell_pb2.Sandbox) -> SandboxRef:
|
||||
return SandboxRef(
|
||||
id=sandbox.metadata.id if sandbox.metadata else "",
|
||||
name=sandbox.metadata.name if sandbox.metadata else "",
|
||||
workspace=sandbox.metadata.workspace if sandbox.metadata else "",
|
||||
status=SandboxStatusRef(
|
||||
phase=status.phase if status else 0,
|
||||
current_policy_version=status.current_policy_version if status else 0,
|
||||
|
||||
@@ -55,10 +55,11 @@ class _FakeStub:
|
||||
|
||||
class _FakeInferenceStub:
|
||||
def __init__(self) -> None:
|
||||
self.request = None
|
||||
self.set_request = None
|
||||
self.get_request = None
|
||||
|
||||
def SetClusterInference(self, request: Any, timeout: float | None = None) -> Any:
|
||||
self.request = request
|
||||
def SetInferenceRoute(self, request: Any, timeout: float | None = None) -> Any:
|
||||
self.set_request = request
|
||||
_ = timeout
|
||||
|
||||
class _Response:
|
||||
@@ -68,6 +69,17 @@ class _FakeInferenceStub:
|
||||
|
||||
return _Response()
|
||||
|
||||
def GetInferenceRoute(self, request: Any, timeout: float | None = None) -> Any:
|
||||
self.get_request = request
|
||||
_ = timeout
|
||||
|
||||
class _Response:
|
||||
provider_name = "openai-dev"
|
||||
model_id = "gpt-4.1"
|
||||
version = 2
|
||||
|
||||
return _Response()
|
||||
|
||||
|
||||
def _client_with_fake_stub(stub: object) -> SandboxClient:
|
||||
client = cast("SandboxClient", object.__new__(SandboxClient))
|
||||
@@ -1293,6 +1305,7 @@ def test_sandbox_wrapper_forwards_auth_kwargs_to_from_active_cluster(
|
||||
)
|
||||
|
||||
sandbox = Sandbox(
|
||||
workspace="default",
|
||||
cluster="my-gw",
|
||||
timeout=42.0,
|
||||
auto_refresh=False,
|
||||
@@ -1334,27 +1347,44 @@ def test_sandbox_wrapper_defaults_match_from_active_cluster(
|
||||
import pytest as _pytest
|
||||
|
||||
with _pytest.raises(_Sentinel):
|
||||
Sandbox().__enter__()
|
||||
Sandbox(workspace="default").__enter__()
|
||||
|
||||
assert captured["auto_refresh"] is True
|
||||
assert captured["write_back"] is True
|
||||
assert captured["insecure"] is False
|
||||
|
||||
|
||||
def test_inference_set_cluster_forwards_no_verify_flag() -> None:
|
||||
def test_inference_set_route_forwards_workspace_and_no_verify() -> None:
|
||||
stub = _FakeInferenceStub()
|
||||
client = cast("InferenceRouteClient", object.__new__(InferenceRouteClient))
|
||||
client._timeout = 30.0
|
||||
client._stub = cast("Any", stub)
|
||||
|
||||
client.set_cluster(
|
||||
client.set_route(
|
||||
workspace="production",
|
||||
provider_name="openai-dev",
|
||||
model_id="gpt-4.1",
|
||||
no_verify=True,
|
||||
)
|
||||
|
||||
assert stub.request is not None
|
||||
assert stub.request.no_verify is True
|
||||
assert stub.set_request is not None
|
||||
assert stub.set_request.no_verify is True
|
||||
assert stub.set_request.workspace == "production"
|
||||
|
||||
|
||||
def test_inference_get_route_forwards_workspace() -> None:
|
||||
stub = _FakeInferenceStub()
|
||||
client = cast("InferenceRouteClient", object.__new__(InferenceRouteClient))
|
||||
client._timeout = 30.0
|
||||
client._stub = cast("Any", stub)
|
||||
|
||||
config = client.get_route(workspace="staging")
|
||||
|
||||
assert stub.get_request is not None
|
||||
assert stub.get_request.workspace == "staging"
|
||||
assert config.provider_name == "openai-dev"
|
||||
assert config.model_id == "gpt-4.1"
|
||||
assert config.version == 2
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -1433,10 +1463,12 @@ def _make_sandbox_proto(
|
||||
labels: dict[str, str] | None = None,
|
||||
phase: openshell_pb2.SandboxPhase = openshell_pb2.SANDBOX_PHASE_READY,
|
||||
version: int = 0,
|
||||
workspace: str = "default",
|
||||
) -> openshell_pb2.Sandbox:
|
||||
sandbox = openshell_pb2.Sandbox()
|
||||
sandbox.metadata.id = id_
|
||||
sandbox.metadata.name = name
|
||||
sandbox.metadata.workspace = workspace
|
||||
for key, value in (labels or {}).items():
|
||||
sandbox.metadata.labels[key] = value
|
||||
sandbox.status.phase = phase
|
||||
@@ -1448,8 +1480,32 @@ class _FakeSandboxStub:
|
||||
def __init__(self, listed: list[openshell_pb2.Sandbox] | None = None) -> None:
|
||||
self.create_request: openshell_pb2.CreateSandboxRequest | None = None
|
||||
self.list_request: openshell_pb2.ListSandboxesRequest | None = None
|
||||
self.get_request: openshell_pb2.GetSandboxRequest | None = None
|
||||
self.delete_request: openshell_pb2.DeleteSandboxRequest | None = None
|
||||
self._listed = listed or []
|
||||
|
||||
def GetSandbox(
|
||||
self,
|
||||
request: openshell_pb2.GetSandboxRequest,
|
||||
timeout: float | None = None,
|
||||
) -> Any:
|
||||
self.get_request = request
|
||||
_ = timeout
|
||||
return SimpleNamespace(
|
||||
sandbox=_make_sandbox_proto(
|
||||
"sandbox-1", request.name, workspace=request.workspace or "default"
|
||||
)
|
||||
)
|
||||
|
||||
def DeleteSandbox(
|
||||
self,
|
||||
request: openshell_pb2.DeleteSandboxRequest,
|
||||
timeout: float | None = None,
|
||||
) -> Any:
|
||||
self.delete_request = request
|
||||
_ = timeout
|
||||
return SimpleNamespace(deleted=True)
|
||||
|
||||
def CreateSandbox(
|
||||
self,
|
||||
request: openshell_pb2.CreateSandboxRequest,
|
||||
@@ -1459,7 +1515,10 @@ class _FakeSandboxStub:
|
||||
_ = timeout
|
||||
return SimpleNamespace(
|
||||
sandbox=_make_sandbox_proto(
|
||||
"sandbox-1", request.name or "generated", dict(request.labels)
|
||||
"sandbox-1",
|
||||
request.name or "generated",
|
||||
dict(request.labels),
|
||||
workspace=request.workspace or "default",
|
||||
)
|
||||
)
|
||||
|
||||
@@ -1482,18 +1541,27 @@ class _RecordingHighLevelClient:
|
||||
def create_session(
|
||||
self,
|
||||
*,
|
||||
workspace: str,
|
||||
spec: Any = None,
|
||||
name: str | None = None,
|
||||
labels: Any = None,
|
||||
) -> Any:
|
||||
self.create_kwargs = {"spec": spec, "name": name, "labels": labels}
|
||||
self.create_kwargs = {
|
||||
"workspace": workspace,
|
||||
"spec": spec,
|
||||
"name": name,
|
||||
"labels": labels,
|
||||
}
|
||||
return SimpleNamespace(sandbox=SimpleNamespace(name=name or "generated"))
|
||||
|
||||
def wait_ready(self, name: str, *, timeout_seconds: float = 300.0) -> SandboxRef:
|
||||
def wait_ready(
|
||||
self, name: str, *, workspace: str, timeout_seconds: float = 300.0
|
||||
) -> SandboxRef:
|
||||
_ = timeout_seconds
|
||||
return SandboxRef(
|
||||
id="sandbox-1",
|
||||
name=name,
|
||||
workspace=workspace,
|
||||
status=SandboxStatusRef(phase=2, current_policy_version=0),
|
||||
)
|
||||
|
||||
@@ -1502,7 +1570,9 @@ def test_create_forwards_name_and_labels() -> None:
|
||||
stub = _FakeSandboxStub()
|
||||
client = _client_with_fake_stub(stub)
|
||||
|
||||
ref = client.create(name="job-1", labels={"aiq": "deep-research"})
|
||||
ref = client.create(
|
||||
workspace="default", name="job-1", labels={"aiq": "deep-research"}
|
||||
)
|
||||
|
||||
assert stub.create_request is not None
|
||||
assert stub.create_request.name == "job-1"
|
||||
@@ -1514,11 +1584,12 @@ def test_create_without_args_sends_empty_metadata() -> None:
|
||||
stub = _FakeSandboxStub()
|
||||
client = _client_with_fake_stub(stub)
|
||||
|
||||
client.create()
|
||||
client.create(workspace="default")
|
||||
|
||||
assert stub.create_request is not None
|
||||
assert stub.create_request.name == ""
|
||||
assert dict(stub.create_request.labels) == {}
|
||||
assert stub.create_request.workspace == "default"
|
||||
|
||||
|
||||
def test_create_copies_caller_labels() -> None:
|
||||
@@ -1526,7 +1597,7 @@ def test_create_copies_caller_labels() -> None:
|
||||
client = _client_with_fake_stub(stub)
|
||||
|
||||
caller_labels = {"aiq": "deep-research"}
|
||||
client.create(labels=caller_labels)
|
||||
client.create(workspace="default", labels=caller_labels)
|
||||
caller_labels["aiq"] = "mutated"
|
||||
|
||||
assert stub.create_request is not None
|
||||
@@ -1537,7 +1608,9 @@ def test_create_session_forwards_name_and_labels() -> None:
|
||||
stub = _FakeSandboxStub()
|
||||
client = _client_with_fake_stub(stub)
|
||||
|
||||
session = client.create_session(name="job-2", labels={"team": "aiq"})
|
||||
session = client.create_session(
|
||||
workspace="default", name="job-2", labels={"team": "aiq"}
|
||||
)
|
||||
|
||||
assert stub.create_request is not None
|
||||
assert stub.create_request.name == "job-2"
|
||||
@@ -1549,17 +1622,18 @@ def test_list_forwards_label_selector() -> None:
|
||||
stub = _FakeSandboxStub()
|
||||
client = _client_with_fake_stub(stub)
|
||||
|
||||
client.list(label_selector="aiq=deep-research")
|
||||
client.list(workspace="default", label_selector="aiq=deep-research")
|
||||
|
||||
assert stub.list_request is not None
|
||||
assert stub.list_request.label_selector == "aiq=deep-research"
|
||||
assert stub.list_request.workspace == "default"
|
||||
|
||||
|
||||
def test_list_without_selector_sends_empty_string() -> None:
|
||||
stub = _FakeSandboxStub()
|
||||
client = _client_with_fake_stub(stub)
|
||||
|
||||
client.list()
|
||||
client.list(workspace="default")
|
||||
|
||||
assert stub.list_request is not None
|
||||
assert stub.list_request.label_selector == ""
|
||||
@@ -1569,7 +1643,7 @@ def test_list_ids_forwards_label_selector() -> None:
|
||||
stub = _FakeSandboxStub(listed=[_make_sandbox_proto("sandbox-1", "job-1")])
|
||||
client = _client_with_fake_stub(stub)
|
||||
|
||||
ids = client.list_ids(label_selector="aiq=deep-research")
|
||||
ids = client.list_ids(workspace="default", label_selector="aiq=deep-research")
|
||||
|
||||
assert stub.list_request is not None
|
||||
assert stub.list_request.label_selector == "aiq=deep-research"
|
||||
@@ -1598,6 +1672,7 @@ def test_direct_sandbox_ref_construction_defaults_labels() -> None:
|
||||
ref = SandboxRef(
|
||||
id="sandbox-1",
|
||||
name="job-1",
|
||||
workspace="default",
|
||||
status=SandboxStatusRef(phase=2, current_policy_version=0),
|
||||
)
|
||||
|
||||
@@ -1629,6 +1704,7 @@ def test_default_sandbox_ref_labels_support_standard_serialization() -> None:
|
||||
ref = SandboxRef(
|
||||
id="sandbox-1",
|
||||
name="job-1",
|
||||
workspace="default",
|
||||
status=SandboxStatusRef(phase=2, current_policy_version=0),
|
||||
)
|
||||
|
||||
@@ -1642,6 +1718,7 @@ def test_direct_sandbox_ref_copies_and_freezes_labels() -> None:
|
||||
ref = SandboxRef(
|
||||
id="sandbox-1",
|
||||
name="job-1",
|
||||
workspace="default",
|
||||
status=SandboxStatusRef(phase=2, current_policy_version=0),
|
||||
labels=labels,
|
||||
)
|
||||
@@ -1663,11 +1740,15 @@ def test_high_level_creation_forwards_name_and_labels(
|
||||
)
|
||||
|
||||
sandbox = Sandbox(
|
||||
name="job-1", labels={"aiq": "deep-research"}, delete_on_exit=False
|
||||
workspace="staging",
|
||||
name="job-1",
|
||||
labels={"aiq": "deep-research"},
|
||||
delete_on_exit=False,
|
||||
)
|
||||
sandbox.__enter__()
|
||||
|
||||
assert recording.create_kwargs == {
|
||||
"workspace": "staging",
|
||||
"spec": None,
|
||||
"name": "job-1",
|
||||
"labels": {"aiq": "deep-research"},
|
||||
@@ -1675,7 +1756,7 @@ def test_high_level_creation_forwards_name_and_labels(
|
||||
|
||||
|
||||
def test_high_level_attach_rejects_name() -> None:
|
||||
sandbox = Sandbox(sandbox="existing-sandbox", name="job-1")
|
||||
sandbox = Sandbox(workspace="default", sandbox="existing-sandbox", name="job-1")
|
||||
|
||||
with pytest.raises(SandboxError):
|
||||
sandbox.__enter__()
|
||||
@@ -1685,9 +1766,97 @@ def test_high_level_attach_rejects_labels() -> None:
|
||||
ref = SandboxRef(
|
||||
id="sandbox-1",
|
||||
name="existing",
|
||||
workspace="default",
|
||||
status=SandboxStatusRef(phase=2, current_policy_version=0),
|
||||
)
|
||||
sandbox = Sandbox(sandbox=ref, labels={"aiq": "deep-research"})
|
||||
sandbox = Sandbox(workspace="default", sandbox=ref, labels={"aiq": "deep-research"})
|
||||
|
||||
with pytest.raises(SandboxError):
|
||||
sandbox.__enter__()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Workspace support
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_create_passes_workspace_to_proto() -> None:
|
||||
stub = _FakeSandboxStub()
|
||||
client = _client_with_fake_stub(stub)
|
||||
|
||||
ref = client.create(workspace="staging", name="job-1")
|
||||
|
||||
assert stub.create_request is not None
|
||||
assert stub.create_request.workspace == "staging"
|
||||
assert ref.workspace == "staging"
|
||||
|
||||
|
||||
def test_get_passes_workspace_to_proto() -> None:
|
||||
stub = _FakeSandboxStub()
|
||||
client = _client_with_fake_stub(stub)
|
||||
|
||||
ref = client.get("job-1", workspace="production")
|
||||
|
||||
assert stub.get_request is not None
|
||||
assert stub.get_request.workspace == "production"
|
||||
assert ref.workspace == "production"
|
||||
|
||||
|
||||
def test_delete_passes_workspace_to_proto() -> None:
|
||||
stub = _FakeSandboxStub()
|
||||
client = _client_with_fake_stub(stub)
|
||||
|
||||
result = client.delete("job-1", workspace="staging")
|
||||
|
||||
assert result is True
|
||||
assert stub.delete_request is not None
|
||||
assert stub.delete_request.workspace == "staging"
|
||||
|
||||
|
||||
def test_list_for_all_workspaces_sets_flag() -> None:
|
||||
stub = _FakeSandboxStub()
|
||||
client = _client_with_fake_stub(stub)
|
||||
|
||||
client.list_for_all_workspaces()
|
||||
|
||||
assert stub.list_request is not None
|
||||
assert stub.list_request.all_workspaces is True
|
||||
assert stub.list_request.workspace == ""
|
||||
|
||||
|
||||
def test_list_with_workspace_passes_workspace() -> None:
|
||||
stub = _FakeSandboxStub()
|
||||
client = _client_with_fake_stub(stub)
|
||||
|
||||
client.list(workspace="staging")
|
||||
|
||||
assert stub.list_request is not None
|
||||
assert stub.list_request.workspace == "staging"
|
||||
assert stub.list_request.all_workspaces is False
|
||||
|
||||
|
||||
def test_sandbox_ref_includes_workspace_from_proto() -> None:
|
||||
proto = _make_sandbox_proto("sandbox-1", "job-1", workspace="production")
|
||||
|
||||
ref = _sandbox_ref(proto)
|
||||
|
||||
assert ref.workspace == "production"
|
||||
|
||||
|
||||
def test_sandbox_session_delete_passes_workspace() -> None:
|
||||
from openshell.sandbox import SandboxSession
|
||||
|
||||
stub = _FakeSandboxStub()
|
||||
client = _client_with_fake_stub(stub)
|
||||
ref = SandboxRef(
|
||||
id="sandbox-1",
|
||||
name="job-1",
|
||||
workspace="staging",
|
||||
status=SandboxStatusRef(phase=2, current_policy_version=0),
|
||||
)
|
||||
session = SandboxSession(client, ref)
|
||||
|
||||
session.delete()
|
||||
|
||||
assert stub.delete_request is not None
|
||||
assert stub.delete_request.workspace == "staging"
|
||||
|
||||
Reference in New Issue
Block a user