sandbox

package
v0.0.7 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 3, 2026 License: MIT Imports: 18 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package sandbox defines the Sandbox Provider contract for authorized compute. Start at sandbox_provider.go and docs/sandbox-provider.md when adding an adapter. Core owns durable Environment/allocation state and lifecycle serialization; SandboxProvider owns compute and bootstrap, Runtime owns capability preparation, and Harness adapters own native execution. Compute running is not execution ready.

Required operations are on SandboxProvider. CheckpointProvider and runtimeobs observation remain separate small interfaces. Every registered adapter explicitly declares and implements each operation, including safe Unsupported rejections. Method-set presence never means an extension is supported. ValidateProvider and the common contract tests check declaration completeness and implementation.

Registration is explicit construction, not a global init-time registry. Node-local adapters register in sandbox/providers; Core's managed setup constructs direct adapters or node proxies. execution.RuntimeProvider binds the selected adapter to installation, backend, deployment generation and node identity. Keep vendor configuration at those construction boundaries; common lifecycle code selects behavior through these contracts, never through a vendor name.

Index

Constants

View Source
const MaxCommandInputBytes = 50*1024*1024 + 32
View Source
const NodeProviderUnavailable = "provider_unavailable"

NodeProviderUnavailable reports every readiness failure without a fixed cause.

View Source
const NodeRuntimeDownloadFailed = "runtime_download_failed"

Variables

View Source
var (
	ErrCredentialRejected       = &ConfigurationError{ConfigurationInvalid, "sandbox_credential_invalid", "credential", "The sandbox provider credential was rejected."}
	ErrCredentialOwnership      = &ConfigurationError{ConfigurationConflict, "sandbox_credential_ownership", "credential", "The credential cannot manage the retained deployment. Reset before changing accounts."}
	ErrConfigurationUnconfirmed = &ConfigurationError{ConfigurationUnconfirmed, "sandbox_verification_unconfirmed", "", "Sandbox provider verification could not be confirmed."}
	ErrConfigurationSelection   = &ConfigurationError{ConfigurationInvalid, "sandbox_configuration_invalid", "configuration", "Select a ready immutable provider configuration with matching resources."}
)
View Source
var (
	ErrRuntimeDownloadFailed            = errors.New("Runtime preparation failed")
	ErrDockerUnavailable                = errors.New("Docker daemon is unavailable")
	ErrDockerLimitsUnsupported          = errors.New("Docker host does not enforce CPU and memory limits")
	ErrRuntimeImageUnavailable          = errors.New("pinned Runtime image is unavailable")
	ErrKVMUnavailable                   = errors.New("KVM is unavailable to sandbox node")
	ErrMicrosandboxArtifactsUnavailable = errors.New("pinned microsandbox artifacts are unavailable")
	ErrCapacityInsufficient             = errors.New("node cannot provide one sandbox of the deployment specification")
)

Node readiness failures. A node probe returns or wraps the one matching its first failed check. Only the fixed code crosses the node transport; the error text and any wrapped detail, such as host paths or daemon messages, stay local.

View Source
var (
	ErrInvalid            = errors.New("invalid sandbox configuration")
	ErrOwnership          = errors.New("sandbox ownership mismatch")
	ErrExists             = errors.New("sandbox allocation already exists")
	ErrNotFound           = errors.New("sandbox allocation not found")
	ErrCommandUnconfirmed = errors.New("initialization command outcome unconfirmed; reclaim allocation before reuse")
)
View Source
var ErrComputeUnconfirmed = errors.New("sandbox lifecycle outcome unconfirmed")

ErrComputeUnconfirmed requires observation of the retained operation identity; it does not authorize another Create, capture, restore, or cold start.

Functions

func DecodeConfigurationObject

func DecodeConfigurationObject(raw json.RawMessage, target any, allowed ...string) error

DecodeConfigurationObject rejects unknown fields, null, nonobjects and trailing input without exposing submitted content in its error. Missing objects are empty.

func NodeDiagnostic

func NodeDiagnostic(err error) string

NodeDiagnostic maps a readiness probe result to its fixed code: empty when ready and provider_unavailable when no classified cause is wrapped.

func NormalizeNodeDiagnostic

func NormalizeNodeDiagnostic(code string) string

NormalizeNodeDiagnostic keeps an empty or known code. Any other reported value becomes provider_unavailable, so Core never stores node-supplied text.

func PythonDeploymentContract

func PythonDeploymentContract(policies map[string]DeploymentPolicy) string

PythonDeploymentContract generates the installer projection. Struct order is checked before generation because it also defines Go's canonical JSON bytes.

func SupportsCheckpoint

func SupportsCheckpoint(p SandboxProvider) bool

func ValidateOperations

func ValidateOperations(operations providercontract.Operations) error

ValidateOperations rejects omitted, unknown and contradictory declarations.

func ValidateProvider

func ValidateProvider(p SandboxProvider) error

Types

type Bootstrap

type Bootstrap struct {
	Reference
	SessionID, DeviceID, CoreURL, Credential string
	NetworkAccess                            string
	AllowedDomains                           []string
}

func (Bootstrap) RuntimeConnection

func (b Bootstrap) RuntimeConnection() runtimebootstrap.Connection

RuntimeConnection projects provider allocation input into Runtime's public startup contract. Providers must never construct a private auth profile.

type CallFence

type CallFence struct {
	// contains filtered or unexported fields
}

CallFence excludes credential commits from provider calls, including helpers still completing after their HTTP caller's deadline. It never kills a helper or treats an unknown Create as absent. A timed-out fence leaves the key intact.

func (*CallFence) ChildStarted

func (f *CallFence) ChildStarted() func()

func (*CallFence) Enter

func (f *CallFence) Enter(ctx context.Context) (func(), error)

func (*CallFence) Fence

func (f *CallFence) Fence(ctx context.Context) (func(), error)

type CheckpointProvider

type CheckpointProvider interface {
	SandboxProvider
	Initial(context.Context, Reference) (Compute, error)
	NewCompute(context.Context, Reference, uint64, *SnapshotIdentity) (Compute, error)
	GetCompute(context.Context, Reference, Compute) (ComputeState, error)
	Suspend(context.Context, SuspendRequest) (ComputeState, error)
	Resume(context.Context, ResumeRequest) (ComputeState, error)
	KillCompute(context.Context, Reference, Compute) error
	DeleteSnapshot(context.Context, Reference, SnapshotIdentity) error
	RunCommandCompute(context.Context, Reference, Compute, Command) (CommandResult, error)
	// ResumeCompute thaws only the same resident instance after an aborted pause.
	ResumeCompute(context.Context, Reference, Compute) (ComputeState, error)
}

CheckpointProvider is an explicitly declared extension. It supplies exact-incarnation operations; Worker and Store remain the lifecycle owner.

type Command

type Command struct {
	Args      []string
	Directory string
	// Stdin carries confidential initialization bytes without exposing them in argv.
	Stdin []byte
}

type CommandResult

type CommandResult struct {
	Stdout, Stderr string
	ExitCode       int
}

type Compute

type Compute struct {
	Generation   uint64
	Name         string
	ID           string
	RestoredFrom *SnapshotIdentity
}

Compute identifies one incarnation of an allocation. Name is provider-derived. ID is empty only until the original create or restore result is observed.

type ComputeState

type ComputeState struct {
	Compute           Compute
	Status            string
	BootstrapComplete bool
	Snapshot          *SnapshotIdentity
	SourceStopped     bool
}

type Configuration

type Configuration interface {
	HasCredential() bool
	ReplacesCredential() bool
}

Configuration is an adapter-owned typed value, never a request or response DTO. Implementations must exclude secrets from JSON and safe diagnostic output.

type ConfigurationAdapter

type ConfigurationAdapter interface {
	Requirements() ConfigurationRequirements
	DecodeInput(public, credential json.RawMessage) (Configuration, error)
	Encode(Configuration) (ConfigurationRecord, error)
	Decode(ConfigurationRecord) (Configuration, error)
	Normalize(Selection) (Selection, error)
	ResolveChange(next, previous Selection) (Selection, error)
	WithCredential(owner, candidate Configuration) (Configuration, error)
	Equal(a, b Configuration) (bool, error)
}

ConfigurationAdapter owns all interpretation of provider configuration. Decode loads retained ownership without remote discovery or new-build admission. Normalize validates a candidate; ResolveChange first applies omitted-field inheritance, then normalizes. Equal compares normalized identity, excluding discovery metadata and explicit credential-submission intent.

type ConfigurationDiscoverer

type ConfigurationDiscoverer interface {
	DiscoverConfiguration(context.Context, ConfigurationDiscoveryInput, ProcessPaths) (json.RawMessage, error)
}

ConfigurationDiscoverer is separate from compute and candidate admission. Support must also be explicitly declared in ConfigurationRequirements.

type ConfigurationDiscoveryInput

type ConfigurationDiscoveryInput struct {
	Configuration json.RawMessage `json:"configuration" swaggertype:"object"`
	Credential    json.RawMessage `json:"credential" swaggertype:"object"`
	Query         json.RawMessage `json:"query" swaggertype:"object"`
}

ConfigurationDiscoveryInput is a transient read-only request. Query is typed and validated by the adapter; it cannot select a compute mutation.

type ConfigurationError

type ConfigurationError struct {
	Class                ConfigurationErrorClass
	Code, Param, Message string
}

ConfigurationError is a fixed safe diagnostic, never SDK text or submitted data. Class describes the request outcome; it does not authorize replay.

func (*ConfigurationError) Error

func (e *ConfigurationError) Error() string

type ConfigurationErrorClass

type ConfigurationErrorClass string
const (
	ConfigurationInvalid     ConfigurationErrorClass = "invalid"
	ConfigurationConflict    ConfigurationErrorClass = "conflict"
	ConfigurationUnconfirmed ConfigurationErrorClass = "unconfirmed"
)

type ConfigurationRecord

type ConfigurationRecord struct {
	Public   json.RawMessage
	Metadata json.RawMessage
	Secret   []byte `json:"-"`
}

ConfigurationRecord separates public selectors, read-only observations and secret bytes. Store encrypts Secret with the installation and generation. Only adapter codecs may produce Public and Metadata; neither is input passthrough.

type ConfigurationRequirements

type ConfigurationRequirements struct {
	Credential   Requirement
	PublicOrigin Requirement
	Discovery    providercontract.Support
}

type CredentialVerifier

type CredentialVerifier interface {
	VerifyCredential(context.Context, []Reference) error
}

CredentialVerifier verifies access to already owned resources without mutation. Replacing credentials requires this capability and a shared CallFence.

type DeploymentPolicy

type DeploymentPolicy struct {
	RuntimeError string `json:"-"`
	Disk         bool   `json:"disk"`
	Runtime      bool   `json:"runtime"`
}

DeploymentPolicy is declared by an adapter and projected to the installer.

type DeploymentSpec

type DeploymentSpec struct {
	Resources Resources       `json:"resources"`
	Runtime   *RuntimeRelease `json:"runtime,omitempty"`
}

func (DeploymentSpec) Digest

func (s DeploymentSpec) Digest(provider string) string

func (DeploymentSpec) ValidatePolicy

func (s DeploymentSpec) ValidatePolicy(provider string, policy DeploymentPolicy) error

ValidatePolicy applies a registered adapter's rules without knowing its kind.

type Description

type Description struct {
	Mode, BackendFingerprint      string
	IdleSeconds, RetentionSeconds int64
}

Description is what a provider registration says about a deployment of it: its mode, its backend namespace fingerprint and its checkpoint timing.

type GenerationReference

type GenerationReference struct {
	Generation          uint64 `json:"generation"`
	SpecificationDigest string `json:"specification_digest"`
}

type GenerationRetention

type GenerationRetention struct {
	GenerationReference
	Keep bool `json:"keep"`
}

func (*GenerationRetention) UnmarshalJSON

func (g *GenerationRetention) UnmarshalJSON(raw []byte) error

Omission or null cannot become an implicit destructive false grant.

type GenerationStatus

type GenerationStatus struct {
	Generation          uint64 `json:"generation"`
	SpecificationDigest string `json:"specification_digest"`
	State               string `json:"state"`
	Diagnostic          string `json:"diagnostic,omitempty"`
}

GenerationStatus is one sparse observation, not a complete provider inventory. A serving pin is owned by Core and is independent of target preparation.

type Info

type Info struct {
	Reference
	ProviderID, State string
	// BootstrapComplete is provider evidence that initialization has reached its
	// last mutating step. It does not establish daemon or native readiness.
	BootstrapComplete bool
	// CreateSettled proves that the original create and initialization attempt can
	// no longer mutate resources. An absent observation needs this explicit proof;
	// an ordinary missing resource or empty provider listing is not sufficient.
	CreateSettled bool
}

Info describes compute only. Running does not establish daemon authentication, native preparation, Environment readiness or a renewable provider lease.

type NodeDeployment

type NodeDeployment struct {
	SpecificationDigest string  `json:"specification_digest"`
	Generation          uint64  `json:"generation"`
	ServingGeneration   *uint64 `json:"serving_generation"`
}

type ProcessPaths

type ProcessPaths struct {
	ArtifactRoot string
	StateRoot    string
}

ProcessPaths locates installed adapter helpers and their private state. The launcher supplies roots from the distribution layout; adapters own subpaths.

type Reference

type Reference struct{ TenantID, EnvironmentID, AllocationID string }

Reference must be persisted by the caller before Create. AllocationID is a fresh UUID for one attempt, not the Environment ID. Serialize lifecycle operations for an allocation; a lost Create response is resolved with GetInfo, never by replay.

type Requirement

type Requirement string

Requirement has no implicit default: registration must choose either value.

const (
	Required    Requirement = "required"
	NotRequired Requirement = "not_required"
)

type Resources

type Resources struct {
	CPUs               uint32 `json:"cpus"`
	MemoryMiB          uint32 `json:"memory_mib"`
	RootDiskMiB        uint32 `json:"root_disk_mib,omitempty"`
	EnvironmentDiskMiB uint32 `json:"environment_disk_mib,omitempty"`
}

Resources describes one managed sandbox, independently of node concurrency. Disk bounds are available only where the native provider enforces them.

func (Resources) ValidatePolicy

func (r Resources) ValidatePolicy(provider string, rules DeploymentPolicy) error

type ResumeRequest

type ResumeRequest struct {
	Reference   Reference
	OperationID string
	Snapshot    SnapshotIdentity
	Target      Compute
	// Recovery observes the previous target and never starts a new restore.
	ObserveOnly bool
}

type RuntimeRelease

type RuntimeRelease struct {
	SourceCommit        string `json:"source_commit"`
	ImageID             string `json:"image_id"`
	ImageManifestDigest string `json:"image_manifest_digest"`
	MicrosandboxRef     string `json:"microsandbox_ref"`
	RuntimeSHA256       string `json:"runtime_sha256"`
	FirmwareSHA256      string `json:"firmware_sha256"`
}

RuntimeRelease preserves the identities of one verified distribution. Docker may address the same archive by config ID or OCI manifest digest; microsandbox has its own imported OCI identity. These are not interchangeable hashes.

func (RuntimeRelease) Validate

func (r RuntimeRelease) Validate() error

type SandboxProvider

type SandboxProvider interface {
	providercontract.Declared
	// Create performs the original attempt once; no credential overwrite on conflict.
	Create(context.Context, Bootstrap) (Info, error)
	// GetInfo observes compute without creating, starting, renewing or preparing it.
	GetInfo(context.Context, Reference) (Info, error)
	// Renew extends an existing native lease where supported; otherwise it observes.
	// It never revives stopped compute or establishes execution readiness.
	Renew(context.Context, Reference) (Info, error)
	// Kill confirms removal of owned compute and retained resources. Absence is
	// idempotent, but nil alone cannot settle an outstanding Create.
	Kill(context.Context, Reference) error
	RunCommand(context.Context, Reference, Command) (CommandResult, error)
}

SandboxProvider manages one persisted Reference at a time. Every call has a bounded context; cancellation ends the caller's wait, not proof of native stop. Non-nil errors retain ownership, including partial results. Do not retry Create or RunCommand after unknown delivery; observe/reclaim the original Reference. Implementations verify installation plus Reference ownership before mutation. See docs/sandbox-provider.md for settlement, cleanup and retry requirements.

type Selection

type Selection struct {
	DeploymentSpec
	ExpectedGeneration uint64        `json:"expected_generation"`
	Provider           string        `json:"provider"`
	Configuration      Configuration `json:"-"`
}

Selection is the typed deployment configuration shared by preview and commit.

func (Selection) HasCredential

func (s Selection) HasCredential() bool

func (Selection) ReplacesCredential

func (s Selection) ReplacesCredential() bool

type SelectionDiscoverer

type SelectionDiscoverer interface {
	DiscoverSelection(context.Context, Selection) (Selection, error)
}

SelectionDiscoverer is an optional read-only native configuration capability. It resolves candidate configuration; loading retained ownership never calls it.

type SnapshotIdentity

type SnapshotIdentity struct {
	Reference        string
	ID               string
	Digest           string
	CheckpointID     string
	CheckpointRoot   string
	OperationID      string
	SourceGeneration uint64
	SourceName       string
	SourceID         string
}

SnapshotIdentity is provider evidence from a verified full snapshot. Core persists it unchanged and records consumption separately; it never invents paths, checksums, native checkpoint fields, or source identity.

type SuspendRequest

type SuspendRequest struct {
	Reference   Reference
	OperationID string
	Source      Compute
	Snapshot    *SnapshotIdentity
	// Recovery observes the previous attempt and never starts a new capture.
	ObserveOnly bool
}

type ValidationError

type ValidationError struct {
	Param    string
	Min, Max *uint32
	Message  string
}

ValidationError preserves the sandbox error text and identity while identifying a fixed configuration field and, for numeric limits, fixed inclusive bounds.

func (*ValidationError) Error

func (e *ValidationError) Error() string

func (*ValidationError) Unwrap

func (e *ValidationError) Unwrap() error

Directories

Path Synopsis
Package contracttest runs shared lifecycle assertions against real adapters backed by controlled native transports.
Package contracttest runs shared lifecycle assertions against real adapters backed by controlled native transports.
Package docker is a thin SDK adapter for the dedicated, colocated Runtime.
Package docker is a thin SDK adapter for the dedicated, colocated Runtime.
e2b
Code generated by contractgen; DO NOT EDIT.
Code generated by contractgen; DO NOT EDIT.
internal/contractgen command
Command contractgen projects the adapter's Go declarations into its Python artifacts.
Command contractgen projects the adapter's Go declarations into its Python artifacts.
Package microsandbox is the pure-Go client for the colocated SDK helper.
Package microsandbox is the pure-Go client for the colocated SDK helper.
Package node transports the finite sandbox Provider contract.
Package node transports the finite sandbox Provider contract.
Node-local adapter configuration and construction.
Node-local adapter configuration and construction.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL