Skip to content

feat: retry sandbox creates on mutation lock timeouts - #5745

Open
EmilienM wants to merge 5 commits into
ai-openshell:mainfrom
EmilienM:feat/5697-create-retry/EmilienM
Open

EmilienM wants to merge 5 commits into
ai-openshell:mainfrom
EmilienM:feat/5697-create-retry/EmilienM

Conversation

@EmilienM

@EmilienM EmilienM commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Summary

sandbox create and the Rust SDK's create methods now retry a create that loses the gateway mutation lock, so burst creation under contention no longer needs a retry loop in every caller. The gateway keeps the machine-readable retry signal when failed-create cleanup rewrites the error, and both lock-timeout producers carry it.

Related Issue

Closes #5697

Changes

  • Server: both SSH identity lock acquisitions map LockTimeout to UNAVAILABLE + MUTATION_LOCK_TIMEOUT + RetryInfo, and compensate_failed_create preserves ErrorInfo/RetryInfo on every rebuilt status
  • Core: the reason constant, an exact-match predicate on tonic::Status, a detail-preserving rebuild helper, and the retry policy itself (delay floor with proportional jitter, backoff, 5-attempt cap, wall-clock budget, AlreadyExists phase decisions with holder provenance), shared by the SDK and the CLI
  • SDK: opt-in create_sandbox_with_retry / create_sandbox_from_template_with_retry on both clients, CreateRetryOptions with a 60s default budget, and SdkError::mutation_lock_timeout(); retryable() keeps its auth-only contract
  • CLI: retry on by default, controlled by --create-retry-timeout, --no-create-retry, and OPENSHELL_CREATE_RETRY_TIMEOUT (60s default, 24h clamp); progress on stderr only; a named create waits out a holder that is deleting, or still provisioning when an earlier attempt of the same command may have left it
  • Docs: SDK error contract, HA page, sandbox overview, CLI skill, debug skill, SDK README

Release Notes

sandbox create now retries for up to 60 seconds when the gateway mutation lock is busy and waits out a same-name sandbox that is still being cleaned up. The Rust SDK gains opt-in retrying create methods. MUTATION_LOCK_TIMEOUT failures keep their reason and retry delay even after failed-create cleanup rewrites the message.

Retry is on by default, so a contended create can now take up to ~70 seconds where it previously failed at ~10 seconds, and callers with their own retry loop can nest up to five create attempts inside it. --no-create-retry keeps the fail-fast behavior.

Testing

  • Checks appropriate to the affected code and behavior pass
  • Unit tests added/updated (if applicable)
  • E2E tests added/updated (if applicable)

Tests cover the reason predicate, detail survival through every compensation branch, retry timing (floor, proportional jitter, backoff, attempt cap), budget exhaustion, the AlreadyExists phase matrix (deleting, own-attempt provisioning, foreign provisioning, missing, live, different-id holder, holder change across conflict episodes), and deadline-bounded holder polls. The PostgreSQL lock suite passed 48/48. The one local failure is a pre-existing z3 solver timeout in openshell-prover, reproduced on clean origin/main. No e2e lane: this is client retry policy plus server error mapping, covered by the SDK/CLI mock suites and the server compensation tests.

Checklist

  • Follows Conventional Commits
  • Commits are signed off (DCO)
  • Architecture docs updated (if applicable)

@copy-pr-bot

copy-pr-bot Bot commented Nov 19, 2026

Copy link
Copy Markdown

This pull request requires additional validation before any workflows can run on NVIDIA's runners.

Pull request vetters can view their responsibilities here.

Contributors can view more details about this message here.

@EmilienM

Copy link
Copy Markdown
Contributor Author

@FrostGod tagging you since you filed #5697. The PR takes it end to end: the server now keeps ErrorInfo/RetryInfo through failed-create cleanup (and the SSH identity step carries the reason), the SDK has opt-in retrying create methods, and the CLI retries by default within a bounded budget. The parts I'd most like your eyes on are the retry policy in openshell-core/src/create_retry.rs and the two client loops. One deliberate deviation from the issue: the budget is wall-clock with a 5-attempt cap rather than attempts-only, to bound lock-pool re-entry under saturation.

@FrostGod

Copy link
Copy Markdown
Contributor

@EmilienM can we repurpose this PR to fix for other SDKs ( not rust or CLI ) if its okay

@EmilienM

Copy link
Copy Markdown
Contributor Author

Happy to take the other SDKs, but I'd rather do that as a follow-up PR than repurpose this one. This PR carries the server-side signal fixes (ErrorInfo/RetryInfo surviving compensation, the SSH identity step carrying the reason) and the core retry policy that any other SDK would build on, and it's fully reviewed. Repurposing it would throw that away.

Proposal: merge this as the Rust/CLI/server base, then I'll take the TypeScript retry as the next PR on top. Go and Python live in the ai-openshell repos now, so those need PRs there anyway (python/ is frozen in-tree, Branch Checks fails changes to it).

One thing worth deciding before the follow-up: Eric's #5725 adds a server-side SANDBOX_DELETING reason for the AlreadyExists race. We went with a client-side phase poll here to avoid a public API change in this PR; happy to switch to a server-side signal in the follow-up if you prefer that design.

@FrostGod FrostGod left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tested this locally on a 2-replica HA gateway (external Postgres, Envoy) by holding the advisory locks by hand. Retry works on both paths: 5/5 creates recovered for the creation guard and for the SSH identity step, and --no-create-retry failed fast as expected. Nice work.

A few comments inline. General ones:

  • Could we settle client-side phase polling vs. a server-side SANDBOX_DELETING reason (#5725) before merge? If we switch later, most of the AlreadyExists code gets replaced.
  • Splitting out the server fix (keeping ErrorInfo/RetryInfo, SSH step reason) would make this much easier to review and land.
  • An e2e that holds the lock and checks the retry would guard this better than mocks alone.

MAX_RETRY_DELAY,
);
let sleep = delay.saturating_add(jitter(seed, attempt, delay));
if sleep <= remaining_budget {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This checks only the sleep against the budget; the next attempt can still wait the server's full 10s. With --create-retry-timeout 15 I saw the CLI stop at 22s. Either skip an attempt when less than the lock wait remains, or document that the last attempt can overrun by up to 10s.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Went with documenting it. The client can't know the server's lock wait before sending, and cutting an in-flight create at the deadline would report failure while the gateway may still create the sandbox, which is a worse contract than the overrun. The decision-layer docs, the flag help, and api-errors.mdx now state that the attempt in flight when the budget runs out can still wait the gateway's 10s lock budget.

seed: u64,
) -> AlreadyExistsPlan {
match observed {
CleanupPhase::Deleting | CleanupPhase::Provisioning => {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Waiting on Provisioning means a duplicate create of a healthy but slow sandbox blocks for the whole budget (60s) and then conflicts. Should we only wait when the holder came from our own earlier attempt?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The loop now waits out a provisioning holder only when an earlier attempt of the same call already saw a lock timeout, so the holder is plausibly its own compensated record. A first-attempt conflict with someone else's in-flight create stops immediately, with "the holder is still being created by another caller" appended to the conflict. While testing this I also found the holder-id guard firing across conflict episodes: a stale id from an earlier NotFound-driven retry made the loop stop on its own fresh record. The recorded id now resets when the create is resent.

pub const DEFAULT_RETRY_DELAY: Duration = Duration::from_secs(1);

/// Upper bound on the jitter added to each retry delay.
pub const MAX_RETRY_JITTER: Duration = Duration::from_millis(500);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

500ms of jitter is small next to a 10s lock wait. A burst times out together at ~10s and retries within the same half second. Jitter proportional to the delay would spread it better.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Dropped the 500ms cap. Jitter is now proportional, at most half the delay, so a burst timing out at ~10s spreads across a seconds-wide window instead of the same half second.

Comment thread crates/openshell-cli/src/main.rs Outdated
timeout: Option<std::num::NonZeroU32>,

/// Seconds to keep retrying while the gateway mutation lock is busy
/// (default: 60, or `OPENSHELL_CREATE_RETRY_TIMEOUT`).

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Retry on by default changes the worst case from ~10s to ~70s, and callers that already retry now nest up to 5 attempts inside theirs. Worth calling out in the release notes.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Release notes now call out retry-on-by-default: the worst case for a contended create goes from ~10s to ~70s, callers with their own retry loop can nest up to five attempts inside it, and --no-create-retry keeps the old fail-fast behavior.

/// workspace. `rootfs_tar` is set when `--from` staged a local archive, whose
/// single-use token is refreshed only when the gateway reports it spent. Progress
/// lines go to stderr so structured output on stdout stays parseable.
async fn create_sandbox_with_retry(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This duplicates the SDK loop (client.rs create_with_retry_using), including the AlreadyExists handling. Could the CLI use the SDK path so the two can't drift?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The decision layer (plan_retry, plan_already_exists, backoff, jitter, the stopped suffix) is shared in openshell-core and unit-tested there. What's left per surface is transport and error shaping, and those don't share a shape: raw proto plus miette plus stderr progress in the CLI, SdkError plus SandboxRef in the SDK. Folding them into one driver means a hookable trait across both error surfaces, which I'd rather do as a follow-up than grow this PR further. I'll file an issue for it.

Comment thread crates/openshell-cli/src/run.rs Outdated
// guard again, so a rejection after that consuming send re-stages
// too; only two rejections with no send in between stay terminal.
// Re-staging needs the budget: the archive re-copy is not free.
Err(status) if is_rootfs_tar_staging_token_spent(&status) => {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The --from re-staging is beyond #5697. Could it move to a follow-up to keep this PR smaller?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Moved out. The retry loop now surfaces the gateway's spent-token error terminally, and guard-timeout retries keep reusing the still-valid token, so the common contention path still retries. I'll file a narrow follow-up issue for the re-stage.

// mutation lock keeps its retry contract instead, because the
// client keys on that reason, and the message reports the
// begin-delete outcome.
if is_mutation_lock_timeout(&original) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here, and at the DEADLINE_EXCEEDED arm above, a lock-timeout create now returns retryable UNAVAILABLE even though cleanup didn't proceed and the record may still exist. I think the AlreadyExists wait covers it; just confirming that's intended.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Intended. Those arms keep the original lock-timeout status because the client keys on the reason, and the appended message reports the cleanup outcome. When cleanup didn't proceed the record may still exist, and the next attempt resolves that through the AlreadyExists wait, the same shape as the SSH identity step.

// reports this reason, but only after the record was
// persisted: that failure is compensated server-side, and the
// next attempt resolves through the AlreadyExists cleanup wait
// below. `request_id` stays empty either way: a non-empty one

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Retries always clear request_id, so replay protection is off for retried creates. What should happen if a caller sets its own request_id?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The public create surfaces can't set one today: the request builders always send it empty, and the loop relies on that. The comment now states that a future caller-supplied id must not enter the loop, since replay admission would turn every retry into the recorded failure. If we ever expose request_id on the spec, the right behavior is to skip retrying when it's set; happy to add that guard then.

Comment thread docs/sdk/api-errors.mdx
most five create attempts, including the first, so it cannot keep re-entering
the gateway's 10-second mutation-lock wait on the budget alone.

One wall-clock budget covers the retry delays and the `ALREADY_EXISTS` cleanup

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same as the create_retry.rs comment: the last attempt can run past the budget by up to 10s. Worth saying here.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added: the budget bounds the waits, not the attempt in flight, and the last attempt can overrun by the gateway's 10s lock budget.

…sion layer

Add the shared primitives that let clients retry sandbox creates that
lose the gateway mutation lock budget. rpc_error gains the
MUTATION_LOCK_TIMEOUT reason constant, an exact-match predicate that
also requires UNAVAILABLE (so DATABASE_UNAVAILABLE and other transient
failures never select a mutation retry), and rebuild_with_message,
which rewrites a status message at the google.rpc.Status envelope
level so every error detail, known or unknown, survives message
appends.

The new create_retry module holds the pure retry policy shared by the
SDK and the CLI: a delay floor from the server's RetryInfo (1s when
absent), proportional jitter (at most half the delay) derived from an
injected per-client seed so a burst that times out together spreads
its retries, a wall-clock budget that stops instead of overrunning,
and the AlreadyExists disambiguation for named creates: a Deleting
holder waits, a Provisioning holder waits only when an earlier attempt
of the same call may have left it (HolderProvenance), NotFound resends
the create up to three times, and a live holder is terminal. Every
wait and retry requires room for one more create attempt, so a spent
attempt cap stops instead of polling toward a conflict already
determined.

Signed-off-by: Emilien Macchi <emacchi@redhat.com>
…s in create compensation

A create that loses the SSH identity mutation lock budget returned a
bare UNAVAILABLE with no machine-readable reason, so clients could not
tell it apart from any other transient failure. Both identity lock
acquisitions now route PersistenceError::LockTimeout through
persistence_error_to_status, reporting the shared MUTATION_LOCK_TIMEOUT
reason and a 1s RetryInfo like the creation guard does; other
persistence failures keep the previous bare status.

compensate_failed_create rebuilt every status it returns with
Status::new, dropping the ErrorInfo and RetryInfo the create failure
carried and silently disabling client retry once cleanup appended to
the message. Every rebuild branch now goes through the core
rebuild_with_message helper, which rewrites the message at the
google.rpc.Status envelope level and keeps every error detail. The
begin-delete supersession arm now reports the original create failure
with the begin-delete outcome appended instead of replacing the status
outright, so the retry contract survives that branch too.

Signed-off-by: Emilien Macchi <emacchi@redhat.com>
Add opt-in retrying entry points for all four create surfaces:
create_sandbox_with_retry and create_sandbox_from_template_with_retry
on both OpenShellClient and WorkspaceScopedClient, backed by one
shared loop over the core create-retry policy. SdkError gains
mutation_lock_timeout(), an exact-match predicate on the shared
reason; retryable() keeps its auth-only contract.

Each attempt waits at least the server's RetryInfo delay plus
per-call jitter and shares one wall-clock budget (CreateRetryOptions,
default 60s) with the AlreadyExists cleanup wait. request_id stays
empty on every attempt so mutation replay never surfaces a recorded
failure. A named create that hits AlreadyExists polls the holder's
phase in the create's workspace: a Deleting holder is waited out, a
missing record resends the create up to three times, and a live,
recovered, or different-id holder is a terminal conflict. Budget
exhaustion surfaces the last error annotated with the attempt count
and the original lock-timeout cause, keeping the raw status intact.

Signed-off-by: Emilien Macchi <emacchi@redhat.com>
sandbox create now retries while the gateway mutation lock is busy,
using the same openshell-core decision layer as the SDK: each attempt
waits at least the server's RetryInfo delay plus per-invocation
jitter inside one wall-clock budget, and only MUTATION_LOCK_TIMEOUT
retries; every other failure may have persisted the create, so it
stays terminal.

The budget defaults to 60s, follows OPENSHELL_CREATE_RETRY_TIMEOUT,
and is set with --create-retry-timeout <SECONDS>; --no-create-retry
restores the fail-fast behavior. Progress lines go to stderr only, so
structured stdout output stays parseable. A named create that hits
AlreadyExists polls the holder's phase in the create's workspace: a
Deleting holder is waited out, a missing record resends the create up
to three times, and a live or recovered holder stops with the
delete-first hint. Budget exhaustion surfaces the last error
annotated with the attempt count and the original lock-timeout cause.

Signed-off-by: Emilien Macchi <emacchi@redhat.com>
Document the create-retry contract end to end: the SDK's opt-in
retrying create methods and the mutation_lock_timeout accessor on the
api-errors page (with the retry conditions, delay floor, jitter bound,
budget, and the AlreadyExists cleanup-wait matrix), the automatic CLI
and Rust SDK retry on the high-availability page, the CLI flags and
cleanup-wait behavior in the openshell-cli skill, and the retrying
entry points in the SDK README. Correct the high-availability page
for the SSH identity step now carrying the MUTATION_LOCK_TIMEOUT
reason.

Closes ai-openshell#5697

Signed-off-by: Emilien Macchi <emacchi@redhat.com>
@EmilienM
EmilienM force-pushed the feat/5697-create-retry/EmilienM branch from c4ab3d1 to 4c8c94b Compare November 23, 2026 15:13
@EmilienM

Copy link
Copy Markdown
Contributor Author

On the three general points:

  • Phase polling vs a server-side reason: feat(sdk): retry TypeScript sandbox create on lock timeout #5725 looks like the TypeScript half of feat: retry sandbox create on MUTATION_LOCK_TIMEOUT in the SDK and CLI #5697 (closed 11-20), and I couldn't find an open issue for a server-side SANDBOX_DELETING reason, so I may be missing the number you meant. As it stands I'd keep client-side polling: it works against deployed gateways, and the observation is isolated behind CleanupPhase, so a server-side reason later replaces the poll, not the decision layer.
  • Splitting out the server fix: it's already its own commit (458232f). Happy to pull it into its own PR first if you'd rather land it separately; it would need its own narrow issue for the acceptance gate. Say the word.
  • e2e holding the lock: happy to file a follow-up issue for it. The mock suites cover the decision matrix; the e2e needs the testkit to reach the gateway's Postgres to hold the advisory lock, which is why it isn't wedged into this PR.

@EmilienM

Copy link
Copy Markdown
Contributor Author

Follow-ups filed: #5898 (re-stage a --from archive when the staging token is spent), #5899 (e2e holding the mutation lock), #5900 (shared create-retry loop driver).

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat: retry sandbox create on MUTATION_LOCK_TIMEOUT in the SDK and CLI

2 participants