mirror of
https://github.com/NVIDIA/OpenShell.git
synced 2026-10-18 05:39:50 +08:00
* test(server): add a local PostgreSQL test runner
The openshell-server tests that need a real PostgreSQL server are
ignored by default and had no shared way to run. The mutation-replay
test reads its own OPENSHELL_REPLAY_TEST_DATABASE_URL, so every
contributor had to provision a database by hand, and the advisory-lock
tests that follow in this series need the same setup.
Add mise run test:rust:postgres. It runs every ignored postgres_* test
in openshell-server against OPENSHELL_TEST_POSTGRES_URL, or starts a
disposable PostgreSQL container with Docker or Podman (CONTAINER_ENGINE
selects one) on the image pinned by the Kubernetes e2e fixture and
removes it on exit. Tests run one at a time because advisory locks are
database-wide. The runner always points the legacy replay variable at
the selected database, so an inherited URL cannot send that test to a
different server. test:postgres-runner checks that selection with a fake
cargo and needs no database or container engine. CI does not run the
PostgreSQL tests; TESTING.md documents the task.
Part of #3528
Signed-off-by: Emilien Macchi <emacchi@redhat.com>
* fix(server): hold the mutation guard while deleting a provider
DeleteProvider checked that no sandbox referenced the provider and then
deleted the record without holding the sandbox mutation guard. Sandbox
create and provider attach take that guard while they write provider
references, so one of them could add a reference after the attached
sandbox check passed, and the delete then removed a provider that a
sandbox spec still named.
Take the guard before the attached sandbox check, as provider create and
update already do, so the check and the delete run against a stable
set of sandbox references, and reject an empty name after authorization
but before the guard. A new test holds the guard, attaches the provider
while the delete waits, and asserts that the delete fails with
FailedPrecondition and leaves the provider in place.
Part of #3528
Signed-off-by: Emilien Macchi <emacchi@redhat.com>
* fix(server): release staged credentials when a refresh fails early
A provider credential refresh stages the minted values under new
credential handles before it commits the provider update, and deletes
those handles when validation or persistence fails. Two earlier returns
skipped that cleanup. The minted expiry was converted to a protobuf
timestamp only after staging, so an expiry outside the timestamp range
failed the refresh and left the staged values in the credential driver.
A failure to acquire the sandbox mutation guard returned the same way.
Convert the expiry before staging anything, so a bad value fails before
any handle exists, and delete the staged handles when the guard cannot
be acquired. A new test refreshes a stored credential with an expiry of
i64::MAX and asserts that the call fails, the provider keeps its
original handles, and the credential driver holds the same number of
values as before. The guard failure path has no test here, because the
SQLite guard used by unit tests cannot fail.
Part of #3528
Signed-off-by: Emilien Macchi <emacchi@redhat.com>
* feat(server): acquire mutation locks on a dedicated PostgreSQL lock pool
The cross-object mutation guard took its advisory-lock session from the
10-connection data pool and closed it on every release, so each guarded
mutation opened a new database connection, and lock holders competed
with their own critical sections for data connections. A lock wait that
hit the 10 second lock_timeout surfaced as INTERNAL.
Add a lazy, dedicated 4-connection lock pool and a new
persistence::mutation_lock module for the lock key, mode and set types.
Store::acquire_distributed_mutation_guard now takes a lock set and a
deadline, and each lock statement sets lock_timeout to the time left
before that deadline, so a cancelled acquisition never waits past it on
the server. Returned connections are scrubbed with
pg_advisory_unlock_all() and reused, and each return is bounded by 5
seconds so a stalled session cannot keep a pool permit.
A lock statement that PostgreSQL ends with SQLSTATE 55P03 fails with a
new LockTimeout error, and so does a wait for a lock connection during
which every one was checked out at some point, or that started with less
than a second left, too little to open one. The API returns it as
UNAVAILABLE with reason MUTATION_LOCK_TIMEOUT and a 1 second retry
delay, because the mutation lock was not acquired, so the request's
guarded writes did not run. Only the guard acquisition classifies 55P03;
any other 55P03 stays a database error. A lock connection that
PostgreSQL does not open by the deadline despite at least a second to do
so (refused, out of connection slots, starting up, or not answering, all
of which SQLx retries silently) is a database error, not a lock timeout.
Mutations still take the legacy global key exclusively, so old and new
replicas keep excluding each other during a rolling upgrade. Each
PostgreSQL-backed gateway pod can now open up to 14 database
connections (10 data plus 4 lock) instead of 10, and the chart's
autoscaling.maxReplicas comment says what its default of 4 needs. The
SSH host identity lock stays on a data connection, because sandbox
creation takes it while holding its mutation guard and a second
lock-pool connection there could exhaust the pool. The provider
credential refresh lock stays there too, so a refresh still progresses
while every lock connection is in use.
Part of #3528
Co-authored-by: divesh <dgude@nvidia.com>
Signed-off-by: Emilien Macchi <emacchi@redhat.com>
* perf(server): partition mutation locks by workspace and sandbox
Every cross-object mutation, and every lifecycle and supervisor update,
took one process-wide mutex and, on PostgreSQL, one fleet-wide advisory
lock. Unrelated sandboxes and providers therefore serialized across all
replicas, and one slow critical section delayed every other mutation in
the fleet.
Replace that lock with hierarchical intention locks on a global key, one
key per workspace and one key per sandbox, each held shared or
exclusive. Global settings and policy writers and platform-scope profile
writers hold the global key exclusively. Provider and workspace-scoped
profile writers, including DeleteProvider and credential refresh, hold
their workspace key exclusively. Sandbox writers and supervisor reports
hold their sandbox key exclusively under shared global and workspace
keys. Lifecycle, driver-watch and reconcile paths take only
process-local keys and keep relying on compare-and-swap across replicas.
Workspace and sandbox keys are domain-separated SHA-256 prefixes. Each
guard takes its local keys and then its advisory locks in ascending
order under one 10 second deadline, and no path nests guards. The
settings mutex is removed, since the global and sandbox keys cover it.
Sandbox settings are keyed by sandbox name, which a sandbox key no
longer covers once another sandbox reuses the name, so a settings
update returns NOT_FOUND unless its sandbox still holds the name after
the read, and ABORTED if the settings row was recreated before the
write.
The global key keeps its legacy value, so older replicas, which hold it
exclusively for every mutation, still exclude new ones during a rolling
upgrade. Guards now also give up after 10 seconds on SQLite, and
provider refresh reports a guard timeout as UNAVAILABLE instead of
INTERNAL. A supervisor report for a missing sandbox returns NOT_FOUND.
Startup endpoint-status reconciliation still holds the global key for
its whole scan.
Part of #3528
Signed-off-by: Emilien Macchi <emacchi@redhat.com>
* fix(server): reconcile endpoint status on startup one sandbox at a time
Startup endpoint-status reconciliation held the global mutation key
exclusively for its whole scan. On PostgreSQL that blocked every guarded
mutation on every replica until the starting gateway had walked all
sandboxes, and the scan first waited behind every in-flight sandbox
mutation. It also paged with an offset, so sandboxes deleted mid-scan
shifted rows between pages, and a write that raced the scan (a Conflict
from a lifecycle update on another replica, or a sandbox deleted after
it was listed) failed gateway startup.
Walk the sandboxes with keyset paging instead, and reset each candidate
under its own sandbox-scoped guard, up to four at a time to match the
lock pool. A candidate with a fresh shared owner is skipped before any
guard is taken. Under the guard the reconciliation re-checks the owner,
re-reads the sandbox, skips it when it is gone or no longer carries
endpoint status, and writes against the version it just read. A Conflict
or a database error at write time, which is how a row deleted after the
re-read surfaces, is retried with a fresh read, at most five attempts
per sandbox. A lock timeout on the guard is retried the same way, so a
holder of the sandbox, its workspace or the global key that releases
within the retry window cannot stop a replica from starting. No
lock-timeout retry starts once the scan has run for three lock timeouts,
so a scan stuck behind a long holder fails within about 40 seconds,
inside the chart's 60-second startup probe, and logs the sandbox it gave
up on. Store::list_all_messages loses its only caller and is removed.
Reconciliation stays fail-closed: a holder that outlasts the retry
window, an owner lookup failure, or a sandbox that keeps changing still
fails startup, so stale endpoint success is never served. User-visible
change: a restarting gateway no longer stalls mutations of unrelated
sandboxes and providers on its peers while it reconciles.
Part of #3528
Signed-off-by: Emilien Macchi <emacchi@redhat.com>
* perf(server): skip the endpoint-status lock when a session was replaced
When a supervisor session ends, the gateway resets that sandbox's tool
server endpoint evidence unless a replacement session already owns
endpoint observation. The replacement check ran only after the reset
had read the sandbox and taken its sandbox mutation guard, so a reset
whose supervisor had already reconnected still queued behind other
mutations of that sandbox, and on PostgreSQL it used a lock-pool
connection, only to find it had nothing to do.
Check for a replacement first: a live local session, or a fresh owner
record on a peer. When one exists, return without reading the sandbox
or taking the guard. Otherwise take the guard and repeat the same check
under it, because a replacement's pre-acknowledgement reset runs under
the same sandbox key and resetting after it would wipe the
replacement's fresh evidence. Both checks share one helper, so they
cannot drift apart. When no replacement exists, the reset costs one
extra owner-row read.
This helps most when a replica notices a dead stream late, after the
supervisor has already reconnected elsewhere (a network partition or a
keepalive expiry).
Deferring to a replacement leaves the old session's evidence to the
replacement's pre-acknowledgement reset, which can time out on its
bounded mutation lock wait. That reset's failure path removed the
replacement and released its owner record but scheduled no
invalidation, so the old session's success evidence could outlive both
sessions. An old session that ended after its replacement registered
already deferred this way, and the unguarded check now makes every
disconnect that finds the replacement defer too. When the reset fails
while the replacement is still current, also schedule the retried
invalidation that follows a session end. That failure path keeps the
lifecycle demotion from abandon_session_setup, but runs it in the
spawned task before the retry and only while this session is still
current, so a timed-out reset returns promptly.
Part of #3528
Co-authored-by: divesh <dgude@nvidia.com>
Signed-off-by: Emilien Macchi <emacchi@redhat.com>
* test(server): cover staged credential cleanup on a lock timeout
A provider credential refresh deletes its staged handles when it cannot
acquire the provider mutation guard, but that path had no test: the
SQLite guard used by unit tests could not fail. Mutation locks now
acquire under a deadline that tests can shorten, so the timeout path
can be exercised directly.
The new test shortens the lock deadline to 50 ms, holds the workspace
mutation guard, and refreshes a provider that already stores an AWS
access key. The refresh returns UNAVAILABLE with the
MUTATION_LOCK_TIMEOUT reason, the provider keeps its original handle,
which still resolves to the old key, and the credential driver holds
the same number of values as before the refresh.
Part of #3528
Signed-off-by: Emilien Macchi <emacchi@redhat.com>
* feat(server): export mutation lock wait and timeout metrics
A handler mutation guard can now wait up to 10 seconds for its keys and
then fail with UNAVAILABLE, but nothing showed operators how long guards
waited or how often they gave up, short of reading warning logs on each
replica.
Export openshell_server_mutation_lock_wait_seconds, a histogram of the
time one guard took to acquire all of its keys (local registry plus
PostgreSQL advisory locks), recorded on success, and
openshell_server_mutation_lock_timeouts_total, a counter of guard
acquisitions that timed out. Both carry a bounded scope label: global,
workspace or sandbox. The platform scope, whose workspace is empty,
counts as global. The histogram uses the same 1 ms to 15 s buckets as
the relay and peer histograms, and the timeout counter starts at 0 for
every scope, so rate() works on an idle replica. The timeout warning
now also logs the scope. A guard that fails for another reason, such as
a lock connection PostgreSQL did not open, is not counted as a timeout
and logs a "mutation lock acquisition failed" warning instead.
Lifecycle, driver-watch and reconcile paths take only process-local
locks and never time out, so they are not recorded.
Part of #3528
Signed-off-by: Emilien Macchi <emacchi@redhat.com>
* test(server): add PostgreSQL mutation lock integration tests
The scoped mutation locks were only unit-tested on SQLite, where the
database layer is a no-op. Add ignored postgres_* tests that run the
advisory-lock layer against a real PostgreSQL through mise run
test:rust:postgres, each in its own disposable schema (TestSchema).
persistence/mutation_lock_pg_tests.rs uses two stores on one database
as two replicas. It covers disjoint sandbox scopes holding at once, a
workspace key blocking only sandboxes in that workspace, the global key
blocking every scope, and exclusion in both directions against a raw
holder of the legacy global key, whose 55P03 stays a database error
outside a guard acquisition. It checks that timed-out and cancelled
acquisitions release the keys they already took, that a released lock
connection returns to the pool without residual locks, that a release
stalled on the network closes its session and the pool recovers, and
that the lock pool never grows past its size. It also checks that a
full lock pool times out as lock contention, while a lock connection
that PostgreSQL never answers fails as a database error.
compute/mutation_guard.rs runs the random scope mix across two
PostgreSQL runtimes and checks that a by-id guard waits for a workspace
writer on the other replica. The provider refresh lock test moves onto
the runner too, and checks that a refresh proceeds while every lock
connection is held.
A bench_postgres_* capacity check measures a paced burst of 500
reconnects 12 ms apart into one replica and fails when the p99 lock
wait reaches a fifth of the lock timeout. Machine load moves those
waits, so mise run test:rust:postgres skips it and mise run
test:rust:postgres:bench runs it alone, through a new
OPENSHELL_TEST_POSTGRES_PREFIX setting in the runner.
The tests add test-only helpers: the lock pool's size and idle count
and the backend pid of a held lock session. Nothing changes outside
tests and the test runner.
Part of #3528
Co-authored-by: divesh <dgude@nvidia.com>
Signed-off-by: Emilien Macchi <emacchi@redhat.com>
* ci: run the PostgreSQL-backed server tests
Branch Checks now runs the postgres_* tests through the same runner
developers use, on an x86_64 Linux runner with Docker. They cover lock
scope exclusion, interop with replicas still on the old global key,
cancellation, lock-pool bounds and connection failures, which no other
CI lane checks directly. The load-sensitive bench_postgres_* capacity
checks stay local.
Part of #3528
Signed-off-by: Emilien Macchi <emacchi@redhat.com>
* docs: document scoped mutation locks and lock-pool sizing
In the High Availability guide, size PostgreSQL for 14 connections per
gateway pod, 10 for data and 4 for the new lock pool, so three or more
replicas now exceed what the PostgreSQL default leaves, and keep
headroom for lock sessions that cancelled requests leave behind.
Explain which changes lock a sandbox, a workspace, or the whole fleet,
and that a lock wait over 10 seconds returns a retryable UNAVAILABLE
with reason MUTATION_LOCK_TIMEOUT. A new upgrade subsection says to
raise max_connections to the 14-per-pod size before upgrading, because
the rollout already runs new pods at that count, and warns that older
replicas keep serializing every mutation until the rollout finishes.
Monitor Capacity gains the lock metrics and their queries, and names
slow driver, credential, middleware, or profile source calls as another
cause of lock waits.
List the lock wait histogram and timeout counter, with their scope
label, on the Gateway Metrics page. The counter also counts background
work and leaves out lock connections that PostgreSQL does not open
although at least a second of the wait remained.
In the cluster debugging skill, replace the single advisory-lock
paragraph with the lock levels and pool, what each timeout detail
means, how a lock connection that PostgreSQL does not open shows up,
when terminating a lock backend is safe, a pg_locks query that shows
holders and waiters, and how to spot the global key. The per-pod greps
also read the timeout counter, and new rows cover lock timeouts and
lock connections that PostgreSQL does not open.
Part of #3528
Signed-off-by: Emilien Macchi <emacchi@redhat.com>
* feat(server): check mutation lock ordering in debug builds
The mutation lock ordering rules were prose only, so a nested guard on
a different key passed every test and could only deadlock under
contention. Debug builds now register each held guard with the Tokio
task (or the thread, outside a task) that acquired it, and panic before
waiting when a local key, a blocking lifecycle gate or the SSH identity
lock would break rules 1, 4 or 5. Startup endpoint-status
reconciliation and the tests that hold a guard while driving guarded
code run under lock_order::branch(), which marks deliberate concurrency
within one task. Release builds compile the check out.
Part of #3528
Signed-off-by: Emilien Macchi <emacchi@redhat.com>
* fix(server): do not hold gateway shutdown for the endpoint-status retry
When a replacement supervisor session failed its endpoint-status reset,
the spawned cleanup task kept the session lifetime guard through
retry_endpoint_status_after_supervisor_disconnect. That retry only ends
once the reset is durable, so a gateway shutdown during a database or
lock outage waited the full 10 s and reported ownership cleanup as
incomplete. The guard now covers only the lifecycle demotion, as in
finish_supervisor_session, and a SQLite test checks that shutdown
completes while the retry is still blocked.
Part of #3528
Signed-off-by: Emilien Macchi <emacchi@redhat.com>
* refactor(server): make the platform profile lock scope explicit
Platform-scope provider profile writers (import, update, delete) pass an
empty workspace on purpose and need X(global), because they validate
sandboxes in every workspace. MutationScope::profiles() now names that
escalation and picks Global for the platform scope, instead of relying
on MutationScope::Workspace("") to mean it. An empty workspace name now
trips a debug assertion, and release builds keep X(global) as a
fail-safe that over-locks rather than under-locks.
Part of #3528
Signed-off-by: Emilien Macchi <emacchi@redhat.com>
* perf(server): amortize local mutation lock table sweeps
LocalMutationLocks swept its whole table on every key lookup, so a
burst of N concurrent acquisitions on one replica cost O(N^2) under a
blocking mutex. The table is now swept only when a new key grows it
past the larger of 64 and twice the live entries left by the last
sweep, which makes acquisition amortized O(1). Released entries,
including those of cancelled waiters, stay bounded at about twice the
peak live set. The lifecycle gate registry keeps its per-call sweep.
Part of #3528
Signed-off-by: Emilien Macchi <emacchi@redhat.com>
* feat(server): make the database pool ceiling configurable
Both stores hardcoded their pool ceiling: 10 connections for Postgres, 5
for on-disk SQLite. One pool is shared by every database-backed RPC, so
that number is also the gateway's ceiling on concurrent database work.
Once every connection is checked out, callers queue on acquire and sqlx
logs "time to acquire exceeded slow threshold"; sandbox creates then time
out and are retried, which adds load rather than shedding it.
The right ceiling is deployment-specific — it depends on how many gateway
replicas share the database and what max_connections the server itself
allows — so it cannot be a single number baked into the binary.
Expose it on the same config surface as the rest of the gateway's
settings: --db-max-connections, OPENSHELL_DB_MAX_CONNECTIONS, and the
TOML key database_max_connections, resolved in that precedence order.
Helm deployments set the key through gatewayConfig. Omitting it keeps
each backend's previous value, so existing deployments do not move.
Values below 1 are rejected rather than silently replaced by the default:
a zero pool would block every acquire, and quietly ignoring a typo would
reproduce the ceiling the operator is trying to lift. An in-memory SQLite
database stays pinned to one connection, since the database lives inside
that connection.
Refs: #2561
Signed-off-by: Bryce Wilkinson <22760097+bjw123@users.noreply.github.com>
(cherry picked from commit 33517b32bd)
[emacchi: dropped the server.dbMaxConnections Helm value; operators set
the key through gatewayConfig]
Signed-off-by: Emilien Macchi <emacchi@redhat.com>
* feat(server): make the mutation lock pool size configurable
The mutation lock pool was fixed at 4 connections per replica. That
number rests on one reconnect-burst bench rather than scale testing, so
a gateway that serves many more sandboxes needs a way to raise it
without a rebuild. Add --db-lock-max-connections,
OPENSHELL_DB_LOCK_MAX_CONNECTIONS and the database_lock_max_connections
gateway.toml key next to the data pool knob, resolved in the same order;
Helm deployments set it through gatewayConfig. The default stays 4,
zero is rejected, SQLite ignores it with a warning, and the gateway logs
both pool sizes at startup. PostgreSQL now needs at least 2 data
connections, because the SSH identity lock keeps one while it queries
the pool. The connection sizing docs, the HA guide formula and the
debug skill now count data plus lock connections.
Part of #3528
Signed-off-by: Emilien Macchi <emacchi@redhat.com>
* feat(server): export mutation lock errors and lock connections in use
A mutation lock acquisition that failed without timing out, such as a
lock connection PostgreSQL never opened or a failed lock statement,
only logged a warning, and readiness stays healthy because it pings the
data pool. Count those failures in
openshell_server_mutation_lock_errors_total{scope}, kept apart from
timeouts because they point at PostgreSQL capacity or connectivity
rather than contention. Export
openshell_server_mutation_lock_connections_in_use as a gauge slot held
by each checked-out lock connection, next to
openshell_server_mutation_lock_connections_capacity, which reads the
configured lock pool size; both exist only with PostgreSQL. The metrics
catalog, the HA guide's signals and PromQL examples, and the debug
skill cover the new series.
Part of #3528
Signed-off-by: Emilien Macchi <emacchi@redhat.com>
* feat(server): time mutation lock holds and test a stalled holder
Nothing bounds how long a mutation guard is held, so a holder stuck in
a compute driver, credential backend or middleware call keeps its scope
locked while waiters time out. Each guard now records its hold in
openshell_server_mutation_lock_hold_seconds{scope} when it is released,
and logs a warning when the hold outlasted the lock wait timeout, so
operators can find the replica and scope behind those timeouts. A
PostgreSQL test with a stalled holder pins the current contract:
waiters on its sandbox, workspace and global scopes fail by their
deadline, other scopes proceed, the holder keeps its key, and a full
lock pool on one replica leaves the other working. The metrics catalog,
the HA guide and the debug skill describe the new signals, which
observe holds without bounding them.
Part of #3528
Signed-off-by: Emilien Macchi <emacchi@redhat.com>
---------
Signed-off-by: Emilien Macchi <emacchi@redhat.com>
Co-authored-by: divesh <dgude@nvidia.com>
Co-authored-by: Bryce Wilkinson <22760097+bjw123@users.noreply.github.com>
311 lines
20 KiB
Plaintext
311 lines
20 KiB
Plaintext
---
|
|
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
|
# SPDX-License-Identifier: Apache-2.0
|
|
title: "API Errors"
|
|
sidebar-title: "API Errors"
|
|
description: "Inspect structured gateway failures and choose an appropriate recovery action."
|
|
keywords: "OpenShell, SDK, gRPC, API errors, retries"
|
|
---
|
|
|
|
Gateway errors include a gRPC status code and a message. Shared request validation
|
|
and concurrency checks also return standard protobuf details in
|
|
`grpc-status-details-bin`. Use the status code and structured fields for decisions.
|
|
Treat messages as explanations whose text can change.
|
|
|
|
## Structured details
|
|
|
|
The SDKs decode these standard detail types while retaining the original failure.
|
|
Older gateways and checks that have not adopted structured details can return only
|
|
a code and message. Missing details do not change the meaning of the status code.
|
|
|
|
| Detail | Meaning |
|
|
|---|---|
|
|
| `google.rpc.BadRequest` | `field_violations` identifies rejected fields and explains each violation. Shared sandbox, exec, provider size, and workspace selector checks supply these details. |
|
|
| `google.rpc.ErrorInfo` | `reason`, `domain`, and `metadata` identify a failure without parsing its message. Gateway reasons use the `openshell.nvidia.com` domain. |
|
|
| `google.rpc.RetryInfo` | `retry_delay` gives a minimum delay before an otherwise safe retry. Its presence does not guarantee that a mutation has not already committed. |
|
|
|
|
Recognized gateway reasons include the following.
|
|
|
|
| Reason | Code | Recovery |
|
|
|---|---|---|
|
|
| `INVALID_ARGUMENT` | `INVALID_ARGUMENT` | Correct the fields listed in `BadRequest`. |
|
|
| `RESOURCE_VERSION_CONFLICT` | `ABORTED` | Read the resource again and construct a new conditional write. `metadata.recovery` is `REFRESH_STATE`; `current_resource_version` is included when known. |
|
|
| `PROFILE_SOURCE_UNAVAILABLE` | `UNAVAILABLE` | Retry a profile snapshot read after at least the supplied delay. |
|
|
| `MUTATION_LOCK_TIMEOUT` | `UNAVAILABLE` | The request waited more than 10 seconds for a concurrent mutation to release a sandbox, workspace, or gateway-wide lock. Retry after at least the supplied delay. A request that carried a `request_id` leaves its admission unresolved, like any other error, so a retry with that ID returns `REQUEST_OUTCOME_UNCERTAIN`. Observe resource state and reconcile effects before you start a new request with a new ID. |
|
|
| `REQUEST_ID_PAYLOAD_MISMATCH` | `FAILED_PRECONDITION` | Keep the original payload for that request ID. Inspect the original operation before submitting a different one. |
|
|
| `REQUEST_OUTCOME_UNCERTAIN` | `FAILED_PRECONDITION` | An attempt is admitted but has no confirmed replayable success. Observe resource state and reconcile effects. Do not switch to a new ID to bypass the admission. |
|
|
| `REQUEST_REPLAY_UNAVAILABLE` | `FAILED_PRECONDITION` | The original scope, resource, interceptor transformation, or fingerprint key is no longer replayable. Reconcile effects; the gateway does not execute the request again. Missing private-key material can also reject admission before work starts. |
|
|
| `REQUEST_STREAM_UNAVAILABLE` | `FAILED_PRECONDITION` | The exec attempt terminated, but its output was not stored. Reconcile command effects; the gateway does not launch it again or recreate its stream. |
|
|
|
|
## Status and retry guidance
|
|
|
|
A timeout or disconnected transport can occur after a mutation commits. Do not
|
|
automatically repeat creates, credential rotation, or command execution based
|
|
only on a transient status. Retry a mutation only when its documented operation
|
|
contract makes the repeated request safe. A correlation ID does not provide that
|
|
guarantee.
|
|
|
|
| Status | Recovery |
|
|
|---|---|
|
|
| `INVALID_ARGUMENT`, `OUT_OF_RANGE` | Correct the request. |
|
|
| `UNAUTHENTICATED` | Refresh or replace credentials before a new attempt. |
|
|
| `PERMISSION_DENIED` | Obtain the required authorization. |
|
|
| `NOT_FOUND` | Check the resource and workspace. Follow the operation's missing-resource contract. |
|
|
| `ALREADY_EXISTS` | Inspect the existing resource before deciding whether it satisfies the request. |
|
|
| `FAILED_PRECONDITION` | Resolve the reported state or configuration requirement. |
|
|
| `ABORTED` | Read fresh state before retrying a conditional operation. |
|
|
| `UNAVAILABLE`, `RESOURCE_EXHAUSTED` | A transient condition may recover. Apply backoff and any minimum retry delay only to a retry-safe operation. |
|
|
| `DEADLINE_EXCEEDED`, `CANCELLED` | A mutation's outcome can be unknown. Cancellation does not imply rollback. |
|
|
| `UNIMPLEMENTED` | Check gateway and SDK version compatibility. |
|
|
| `INTERNAL`, `UNKNOWN`, `DATA_LOSS` | Preserve the status and correlation metadata for diagnosis. Do not blindly retry mutations. |
|
|
|
|
## SDK access
|
|
|
|
Each SDK exposes decoded fields and an escape hatch for complete transport data.
|
|
Unknown details remain available through the original error even when the SDK
|
|
does not recognize their message type.
|
|
|
|
| SDK | Decoded details | Original failure |
|
|
|---|---|---|
|
|
| Rust | `SdkError::error_details()`, `retry_delay()` | `SdkError::grpc_status()` returns the original `tonic::Status`, including details bytes and metadata. |
|
|
| Go | `StatusError.FieldViolations`, `ErrorInfo`, `RetryDelay`, `GRPCCode` | `StatusError.Cause` retains the gRPC error. `status.FromError` can recover its details through error wrapping. |
|
|
| TypeScript | `SdkError.fieldViolations`, `errorInfo`, `retryDelayMs`, `connectCode` | `SdkError.cause` retains the `ConnectError`, including all details and metadata. Use `fromConnect` for raw calls. |
|
|
| Python | `GatewayError.field_violations`, `error_info`, `retry_delay` | `raw_error` retains the gRPC exception and metadata; `raw_status` retains the parsed envelope. Use `from_grpc_error` for raw calls. |
|
|
|
|
Retry delays are Rust and Go durations, TypeScript milliseconds, and Python
|
|
seconds. Absent or invalid delay details do not produce a suggested delay.
|
|
|
|
## Migration
|
|
|
|
Existing error codes and human-readable messages remain available. Python curated
|
|
clients now raise `GatewayError`, which remains a `grpc.RpcError`; existing
|
|
`except grpc.RpcError` handlers continue to work. `GatewayError` is not a
|
|
`grpc.Call`. If your handler checks that interface, inspect `raw_error` before
|
|
checking the status, or call `GatewayError.code()` directly. Python deletion waits
|
|
recognize `NOT_FOUND` through the wrapper; managed-sandbox cleanup requests
|
|
`allow_missing=True` and handles the typed deletion outcome. Other failures still
|
|
propagate. Rust error variants now retain
|
|
status fields; use `..` when destructuring variants that do not need those fields.
|
|
Go and TypeScript add typed detail fields to their existing error types.
|
|
|
|
No SDK automatically retries a mutation as a result of decoding these details.
|
|
|
|
## Durable request admission
|
|
|
|
Thirty user-callable unary RPCs accept an optional `request_id` in their protobuf requests.
|
|
|
|
| Resource | RPCs |
|
|
|---|---|
|
|
| Workspace | `CreateWorkspace`, `DeleteWorkspace` |
|
|
| Workspace member | `AddWorkspaceMember`, `RemoveWorkspaceMember` |
|
|
| Sandbox template | `CreateSandboxTemplate`, `DeleteSandboxTemplate` |
|
|
| Sandbox | `CreateSandbox`, `DeleteSandbox`, `StartSandbox`, `StopSandbox`, `AttachSandboxProvider`, `DetachSandboxProvider` |
|
|
| Service | `ExposeService`, `DeleteService` |
|
|
| Provider | `CreateProvider`, `UpdateProvider`, `DeleteProvider`, `ConfigureProviderRefresh`, `DeleteProviderRefresh`, `RotateProviderCredential` |
|
|
| Provider profile | `ImportProviderProfiles`, `UpdateProviderProfiles`, `DeleteProviderProfile` |
|
|
| Policy and config | `UpdateConfig`, `ApproveDraftChunk`, `RejectDraftChunk`, `EditDraftChunk`, `UndoDraftChunk`, `ApproveAllDraftChunks`, `ClearDraftChunks` |
|
|
|
|
Use a nonzero, hyphenated UUID of exactly 36 characters. Uppercase and lowercase
|
|
forms identify the same request. An empty ID preserves the existing behavior
|
|
without deduplication. This ID is separate from transport correlation metadata.
|
|
The gateway scopes it to the authenticated identity provider, OIDC issuer,
|
|
subject, RPC method, and requested workspace. Use the same identity, scope, ID,
|
|
and payload when checking an admitted attempt. Map ordering does not affect the
|
|
payload fingerprint; changed values or protobuf message presence do.
|
|
|
|
For `CreateWorkspace` and `DeleteWorkspace`, the requested workspace is the
|
|
request's `name`. The same caller can reuse an ID for the same method on different
|
|
workspace names. Within one workspace name, a changed payload still returns
|
|
`REQUEST_ID_PAYLOAD_MISMATCH`. Workspace deletion replay does not require the
|
|
deleted workspace to exist and does not delete a same-name replacement.
|
|
|
|
Pre-release gateways that used unscoped workspace admission require reconciliation
|
|
before upgrading. Their workspace create/delete receipts do not replay under the
|
|
corrected name-scoped namespace. Do not retry those IDs after upgrading without
|
|
reconciling the original operations' effects.
|
|
|
|
The gateway durably admits one owner before executing the mutation. Concurrent
|
|
duplicates either replay its confirmed success or return
|
|
`REQUEST_OUTCOME_UNCERTAIN`. Disconnecting or cancelling the client does not stop
|
|
admitted work. An error, interrupted process, or failed success-record write
|
|
leaves the admission unresolved. No gateway replica takes over that admission,
|
|
even after restart or after 24 hours. Status codes alone do not prove that the
|
|
attempt had no effects.
|
|
|
|
Successful results have a 24-hour replay window, measured from durable completion.
|
|
A successful replay includes `openshell-replayed: true` response metadata and
|
|
does not extend the window. After it expires, the same ID can admit a new
|
|
execution. Do not retry an old operation after that window without reconciling
|
|
its effects. Unresolved admissions never expire.
|
|
|
|
Every replay checks current authorization, including membership and permission
|
|
to assign workspace administrators. A replacement workspace makes workspace-scoped
|
|
replay unavailable. Target readiness, conditional-write versions, and draft review
|
|
tokens are first-execution preconditions, not conditions to execute again.
|
|
|
|
| Result family | Replay behavior |
|
|
|---|---|
|
|
| Workspace, membership, template, provider, and profile resources | Load the original UUID at its recorded version. Missing or changed resources make replay unavailable. Provider credentials remain redacted. |
|
|
| Sandbox resources | Load the original UUID with its current state, including newer status or configuration. Attach/detach flags describe the original operation. A missing original sandbox makes replay unavailable. |
|
|
| Provider readiness receipts | Return the original attach, detach, or update receipts and mutation ID, including the original update target set. Later attachment changes do not replace these receipts. Missing operation evidence makes replay unavailable without executing the mutation again. |
|
|
| Service endpoint | Require the original endpoint version and sandbox identity. Return the recorded URL. |
|
|
| Refresh status | Return current status for the original provider, refresh record, and authorization epoch. Reconfiguration or removal makes replay unavailable. Rotation is not repeated. |
|
|
| Policy and config | Return the original versions, counts, and nonsecret annotations while the original sandbox exists. Global config has no sandbox guard. |
|
|
| Deletion | Return the original outcome without requiring the deleted target or parent to exist and without deleting a replacement. `ACCEPTED` remains an acknowledgment of the original cleanup, not proof of completion. |
|
|
|
|
Profile imports and updates also preserve their original public diagnostics and
|
|
success flags. Profile declarations, diagnostic source labels, and annotations
|
|
must not contain secrets.
|
|
|
|
For sandbox, service, provider, profile, and policy/config methods, fingerprints
|
|
use HMAC with domain-separated material derived from the configured gateway JWT
|
|
private key, or the primary TLS private key when JWT signing is not configured.
|
|
These methods require readable, stable private-key material when you supply an
|
|
ID. Replicas sharing a database must share that material. Changing it makes
|
|
existing protected receipts unavailable until their successful replay window
|
|
expires; unresolved admissions remain protected indefinitely. Workspace,
|
|
membership, and template methods retain their original fingerprint format.
|
|
|
|
Gateway interceptors run their current modification and validation phases on
|
|
every attempt, including replay. They cannot add, remove, or change `request_id`.
|
|
The gateway fingerprints the original client payload and separately guards the
|
|
effective transformed payload and workspace. A changed transformation makes
|
|
replay unavailable. A current denial remains authoritative. Successful replay
|
|
does not invoke post-commit observers again. Post-commit observation remains
|
|
best-effort; this is not a durable delivery queue.
|
|
|
|
Replay rows contain fingerprints, resource references, and explicitly selected
|
|
public diagnostic or scalar outcomes, not credential-bearing response snapshots.
|
|
Completed receipts are limited to 64 KiB. A failure to capture a bounded receipt
|
|
after execution leaves the admission unresolved. Each caller can
|
|
hold at most 1,000 durable admissions. At capacity, the gateway removes expired
|
|
successes; if no space remains, it rejects new admissions with
|
|
`RESOURCE_EXHAUSTED`. Existing records remain protected. Unresolved records
|
|
require operator investigation; there is no automatic reset or takeover API.
|
|
The gateway also limits detached admission workers to 64 per process and these
|
|
request messages to 4 MiB.
|
|
|
|
Supply IDs through generated/raw RPC clients. Curated SDK request-ID helpers and
|
|
automatic retry policies are not part of this contract yet. SSH sessions,
|
|
rootfs staging, and supervisor-authenticated mutations do not gain deduplication
|
|
from this feature. Sandbox principals cannot opt into `UpdateConfig` admission.
|
|
Check gateway compatibility
|
|
before relying on IDs; older protobuf servers can silently ignore unknown fields.
|
|
|
|
## Exec launch admission
|
|
|
|
`ExecSandbox` and `ExecSandboxInteractive` accept an optional `request_id` in
|
|
`ExecSandboxRequest`. For interactive exec, supply it in the initial `start`
|
|
message. The UUID rules, keyed fingerprints, current authorization checks,
|
|
per-caller quota, and request-size limit above also apply to exec.
|
|
|
|
The gateway admits one owner before opening the supervisor relay. Both RPCs
|
|
fingerprint the command, sandbox name, workspace selector, environment, initial
|
|
stdin, and other start fields, excluding the request ID. Admission also binds the
|
|
resolved sandbox UUID, so a replacement with the same name cannot receive the
|
|
original launch. If the sandbox is replaced between authorization lookups for an
|
|
unchanged name and workspace selector, the gateway returns
|
|
`REQUEST_REPLAY_UNAVAILABLE` before admitting or launching the command.
|
|
The RPCs use separate method namespaces.
|
|
Later interactive stdin and resize messages are not part of the fingerprint and
|
|
cannot be submitted through a duplicate stream.
|
|
|
|
| Admitted attempt | Duplicate response |
|
|
|---|---|
|
|
| Still running, interrupted, timed out, or missing confirmed exit status | `REQUEST_OUTCOME_UNCERTAIN`. The record does not expire or permit another launch. |
|
|
| Confirmed remote exit, including a nonzero exit code | `REQUEST_STREAM_UNAVAILABLE` for 24 hours after durable completion. No output, exit code, stream attachment, or stdin is replayed. |
|
|
| Changed start payload | `REQUEST_ID_PAYLOAD_MISMATCH`. The changed command does not run. |
|
|
| Sandbox replaced under the same name | `REQUEST_REPLAY_UNAVAILABLE`. The replacement does not receive the command. |
|
|
|
|
The terminal receipt contains only a marker and completion time, not commands,
|
|
environment values, stdin, stdout, or stderr. Receiving a stream handle is not
|
|
completion. A gateway-generated timeout exit code of `124` does not prove the
|
|
remote process stopped, so it leaves the admission unresolved. A confirmed remote
|
|
exit code of `124` is a terminal result.
|
|
|
|
Cancellation does not undo admission. Existing transport behavior still applies
|
|
to the original execution, including interactive SSH closure on disconnect; the
|
|
gateway does not promise that a disconnected command continues. When it loses
|
|
exit confirmation, the record remains unresolved even after restart. Current
|
|
authorization is checked before duplicate lookup, and the resolved sandbox UUID
|
|
must match the original admission before the gateway returns its recorded outcome.
|
|
|
|
After confirmed terminal retention expires, the same ID can start a new command.
|
|
Do not reuse an old ID without reconciling its effects. Empty IDs keep the existing
|
|
streaming behavior without launch deduplication. Use generated/raw RPC clients
|
|
for this opt-in contract; curated SDK helpers and automatic retries are separate.
|
|
|
|
## Deletion outcomes
|
|
|
|
Delete, membership-removal, and SSH-revocation RPCs return a typed outcome.
|
|
Transport success alone does not establish completion.
|
|
|
|
| Outcome | Meaning |
|
|
|---|---|
|
|
| `COMPLETED` | The gateway resource was removed, or the existing SSH session is revoked. Downstream platform garbage collection may still be finishing. |
|
|
| `ACCEPTED` | Sandbox deletion started, but the gateway sandbox record still exists. Observe its removal before assuming completion. |
|
|
| `ALREADY_ABSENT` | The target was missing when resolved, and the request set `allow_missing=true`. |
|
|
| `UNSPECIFIED` or an unknown value | Completion is not established. Check gateway and SDK compatibility. |
|
|
|
|
Requests default to `allow_missing=false`: an initially missing target returns
|
|
`NOT_FOUND`. Set it to `true` for cleanup that allows an absent target. This flag
|
|
does not suppress missing parents, authorization failures, invalid requests,
|
|
failed preconditions, or backend errors. Re-revoking an existing revoked session
|
|
returns `COMPLETED` after authorization without changing its resource version.
|
|
|
|
`DeleteSandbox` also returns the original `sandbox_id` when it found a target.
|
|
For an accepted deletion, poll or watch that identity. A same-name sandbox with a
|
|
different ID is not the sandbox being deleted. Cancellation or a disconnected
|
|
client does not stop the gateway's already-started deletion worker.
|
|
|
|
Pass the deletion result's ID to the SDK wait helper to avoid following a
|
|
same-name replacement.
|
|
|
|
| SDK | Identity-aware deletion wait |
|
|
|---|---|
|
|
| Rust | `client.wait_deleted(name, timeout, result.sandbox_id.as_deref()).await?` on either the default or workspace-scoped client. |
|
|
| Python | `client.wait_deleted(name, workspace=workspace, expected_sandbox_id=result.sandbox_id)`. Managed-sandbox cleanup supplies this automatically. |
|
|
| TypeScript | `client.sandbox.waitDeleted(name, timeoutSecs, { workspace, expectedSandboxId: result.sandboxId })`. |
|
|
|
|
These waits complete on `NOT_FOUND` or a different observed ID. Without an
|
|
expected ID, they wait for the name to be absent. Existing Rust callers must add
|
|
the third argument; use `None` to retain name-only behavior.
|
|
|
|
`allow_missing` is not request deduplication. A later request by name can delete
|
|
a newly created resource with that name. Do not blindly repeat a timed-out
|
|
deletion when names might be reused.
|
|
|
|
### SDK migration for deletion
|
|
|
|
Upgrade gateways and clients together. This pre-1.0 change removes the boolean
|
|
response fields, reserving their names and wire numbers. New clients reading an
|
|
old response see `UNSPECIFIED`; they must not interpret it as completion.
|
|
|
|
| RPC | Removed field | Replacement |
|
|
|---|---|---|
|
|
| `DeleteSandboxTemplate` | `deleted` | `outcome` |
|
|
| `DeleteSandbox` | `deleted` | `outcome`, `sandbox_id` |
|
|
| `DeleteService` | `deleted` | `outcome` |
|
|
| `DeleteProvider` | `deleted` | `outcome` |
|
|
| `DeleteProviderRefresh` | `deleted` | `outcome` |
|
|
| `DeleteProviderProfile` | `deleted` | `outcome` |
|
|
| `DeleteWorkspace` | `deleted` | `outcome` |
|
|
| `RemoveWorkspaceMember` | `removed` | `outcome` |
|
|
| `RevokeSshSession` | `revoked` | `outcome` |
|
|
|
|
These RPCs use a typed result rather than `Empty` because callers must
|
|
distinguish absence, asynchronous acceptance, and completion.
|
|
|
|
Curated SDK methods return `DeletionResult` instead of a boolean or no result.
|
|
Rust accepts `DeleteOptions { allow_missing: true }`; Python accepts the keyword
|
|
`allow_missing=True`; TypeScript accepts `{ allowMissing: true }`; Go accepts an
|
|
optional `DeleteOptions{AllowMissing: true}` and returns `(result, error)`.
|
|
Go and Python preserve unknown numeric outcomes, Rust uses `Unknown(i32)`, and
|
|
TypeScript returns `outcome: 'unknown'` with `rawOutcome`.
|
|
|
|
Other mutation responses remain unchanged: provider attach/detach also return
|
|
the resulting sandbox, profile import/update return resources and diagnostics,
|
|
and config updates return version/application information. Their supplementary
|
|
booleans are not the sole result. Internal compute-driver and supervisor
|
|
contracts are separate from this public API migration.
|