Documentation
¶
Overview ¶
Package sandbox defines the Sandbox Provider contract for authorized compute. This file is the Core–Sandbox Provider protocol; docs/sandbox-provider.md describes it. Start here when adding an adapter. Value types that Core also uses beyond this boundary, such as DeploymentSpec and CallFence, live in their own files of this package. 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.
The protocol has two interfaces. SandboxProvider is the allocation-time half and ConfigurationAdapter the setup-time half. Every adapter implements every method of both and declares which operations it supports: SandboxProvider through ProviderOperations, ConfigurationAdapter through Requirements. An unsupported method returns a typed providercontract.UnsupportedError; method-set presence never means support.
Registration is explicit construction, not a global init-time registry. 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
- Variables
- func BackendFingerprint(kind, namespace string) string
- func CheckCapacity(r Resources, cpus int, memory uint64) error
- func DecodeConfigurationObject(raw json.RawMessage, target any, allowed ...string) error
- func DeploymentContract(providers map[string]ProviderProjection) (python, typescript string)
- func NodeDiagnostic(err error) string
- func NormalizeNodeDiagnostic(code string) string
- func SupportsCheckpoint(p SandboxProvider) bool
- func ValidateOperations(operations providercontract.Operations) error
- func ValidateProvider(p SandboxProvider) error
- func ValidateWorkspaceBinding(r Reference, binding *workspacefs.Binding) error
- type Bootstrap
- type Built
- type CallFence
- type CheckpointCompatibility
- type Command
- type CommandResult
- type Compute
- type ComputeState
- type Configuration
- type ConfigurationAdapter
- type ConfigurationDiscoveryInput
- type ConfigurationError
- type ConfigurationErrorClass
- type ConfigurationRecord
- type ConfigurationRequirements
- type DeploymentMode
- type DeploymentPolicy
- type DeploymentSpec
- type Description
- type DirectConfig
- type GenerationReference
- type GenerationRetention
- type GenerationStatus
- type Info
- type LocalOptions
- type NodeConfig
- type NodeDeployment
- type NodeDiagnosticCode
- type ProcessPaths
- type ProviderProjection
- type Reference
- type Requirement
- type Resources
- type ResumeRequest
- type SandboxProvider
- type Selection
- type SnapshotIdentity
- type SuspendRequest
- type ValidationError
Constants ¶
const MaxCommandInputBytes = 50*1024*1024 + 32
Variables ¶
var ( ErrProviderUnavailable = errors.New("sandbox provider unavailable") // The host lacks a capability the Provider requires. ErrHostUnsupported = errors.New("host lacks a capability the sandbox provider requires") ErrArtifactsUnavailable = errors.New("pinned provider artifacts are unavailable") ErrRuntimeImageUnavailable = errors.New("installed Runtime image is unavailable") // The host cannot hold one sandbox of the deployment specification. ErrCapacityInsufficient = errors.New("node cannot provide one sandbox of the deployment specification") )
Node readiness classes. A node probe returns or wraps the class of its first failed check and keeps the Provider's detail, such as host paths or daemon messages, in the local error text. Only the class code crosses the node transport.
var ( ErrInvalid = errors.New("invalid sandbox configuration") // ErrWorkspaceRequired reports a Provider that runs every Environment on // external storage while none is selected. ErrWorkspaceRequired = errors.New("sandbox provider requires workspace storage") 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") // ErrComputeUnconfirmed requires observation of the retained operation identity; // it does not authorize another Create, capture, restore, or cold start. ErrComputeUnconfirmed = errors.New("sandbox lifecycle outcome unconfirmed") // ErrCheckpointUnusable is a Resume outcome: the adapter durably closed this // operation before dispatching native restoration, and the snapshot cannot be // restored. It repeats for the same operation and is never returned once // native restoration was dispatched. ErrCheckpointUnusable = errors.New("sandbox checkpoint cannot be restored") )
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."} )
Functions ¶
func BackendFingerprint ¶ added in v0.0.10
func CheckCapacity ¶ added in v0.0.10
CheckCapacity reports whether a host can hold one sandbox of the given resources.
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 DeploymentContract ¶ added in v0.0.10
func DeploymentContract(providers map[string]ProviderProjection) (python, typescript string)
DeploymentContract generates the installer and TypeScript client projections of one contract. Struct order is checked first because it also defines Go's canonical JSON bytes.
func NodeDiagnostic ¶
NodeDiagnostic maps a readiness probe result to its class code: empty when ready and provider_unavailable when no class is wrapped.
func NormalizeNodeDiagnostic ¶
NormalizeNodeDiagnostic keeps an empty or known code. Any other reported value becomes provider_unavailable, so Core never stores node-supplied text.
func SupportsCheckpoint ¶
func SupportsCheckpoint(p SandboxProvider) bool
func ValidateOperations ¶
func ValidateOperations(operations providercontract.Operations) error
ValidateOperations rejects omitted, unknown and contradictory declarations. SandboxProvider's method set is the operation inventory.
func ValidateProvider ¶
func ValidateProvider(p SandboxProvider) error
ValidateProvider checks a constructed Provider's declaration.
func ValidateWorkspaceBinding ¶ added in v0.0.10
func ValidateWorkspaceBinding(r Reference, binding *workspacefs.Binding) error
ValidateWorkspaceBinding checks the shared ownership envelope before forwarding. Adapter-native receipts are validated only by the selected filesystem resolver.
Types ¶
type Bootstrap ¶
type Bootstrap struct {
Workspace *workspacefs.Binding `json:",omitempty"`
Reference
SessionID, DeviceID, CoreURL, Credential 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 Built ¶ added in v0.0.10
type Built struct {
SpecificationDigest string
Provider SandboxProvider
InstallationID, BackendFingerprint string
Probe func(context.Context) (*CheckpointCompatibility, error)
// Quiescent is nil when no helper can outlive its caller.
Quiescent func() bool
}
Built is a constructed node adapter. Construction fills InstallationID and SpecificationDigest; the adapter fills the rest.
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()
type CheckpointCompatibility ¶ added in v0.0.10
type CheckpointCompatibility struct {
ArtifactDomain string `json:"artifact_domain"`
ExecutionClass string `json:"execution_class"`
}
CheckpointCompatibility identifies an adapter-verified private checkpoint domain and execution compatibility class. Core compares these opaque tokens only.
func (CheckpointCompatibility) Validate ¶ added in v0.0.10
func (c CheckpointCompatibility) Validate() error
type CommandResult ¶
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 is the native state of Compute. "stopped" and "crashed" mean the
// adapter verified that the exact incarnation's process no longer exists;
// its record or disks can remain until KillCompute removes them.
Status string
BootstrapComplete bool
Snapshot *SnapshotIdentity
// SourceStopped proves the checkpoint is durable and all source-local compute
// and capture obligations have settled, so another node can own restoration.
SourceStopped bool
// RestoreAttemptClosed echoes the exact Resume OperationID only after a
// never-dispatched attempt is durably closed against late native execution.
RestoreAttemptClosed string
}
func (ComputeState) ClosesRestoreAttempt ¶ added in v0.0.10
func (s ComputeState) ClosesRestoreAttempt(q ResumeRequest) bool
ClosesRestoreAttempt validates a never-executed closure against the exact persisted request. Absence without this operation-bound evidence is unknown.
func (ComputeState) Terminated ¶ added in v0.0.10
func (s ComputeState) Terminated() bool
Terminated reports a verified stopped or crashed incarnation.
type Configuration ¶
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)
// DiscoverConfiguration lists the native catalog a credential can use,
// without a saved deployment.
DiscoverConfiguration(context.Context, ConfigurationDiscoveryInput, ProcessPaths) (json.RawMessage, error)
// DiscoverSelection resolves a candidate's omitted native values before
// commit. Loading retained ownership never calls it.
DiscoverSelection(context.Context, DirectConfig) (Selection, error)
// VerifyCredential verifies access to already owned resources without
// mutation. Replacing a credential requires it and a shared CallFence.
VerifyCredential(context.Context, DirectConfig, []Reference) 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.
The three setup operations are read-only native calls, separate from compute and candidate admission. Each builds its own native client from its input.
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
SelectionDiscovery providercontract.Support
CredentialVerification providercontract.Support
}
ConfigurationRequirements is the setup-time declaration. Discovery, SelectionDiscovery and CredentialVerification declare DiscoverConfiguration, DiscoverSelection and VerifyCredential; requiring a credential does not promise VerifyCredential.
type DeploymentMode ¶ added in v0.0.10
type DeploymentMode string
const ( DeploymentUnconfigured DeploymentMode = "" DeploymentNodes DeploymentMode = "nodes" DeploymentDirect DeploymentMode = "direct" )
type DeploymentPolicy ¶
type DeploymentPolicy struct {
Workspace *workspacefs.Requirements `json:"workspace,omitempty"`
Disk bool `json:"disk"`
DefaultResources *Resources `json:"default_resources"`
}
DeploymentPolicy is the deployment declaration. Workspace, when present, means the Provider runs every Environment on external storage; absent means its own disk. Disk declares independent disk limits. DefaultResources is the size setup proposes, or nil when the Provider's configuration selects it.
type DeploymentSpec ¶
type DeploymentSpec struct {
Resources Resources `json:"resources" binding:"required"`
// Workspace is a derived immutable capability receipt, never filesystem configuration.
Workspace *workspacefs.Declaration `json:"workspace,omitempty" readonly:"true"`
}
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. A Provider that declares workspace requirements runs every Environment on external storage and cannot be deployed without a selection.
type Description ¶
type Description struct {
Mode DeploymentMode
BackendFingerprint string
}
Description is what a provider registration says about a deployment of it: its mode and its backend namespace fingerprint.
type DirectConfig ¶ added in v0.0.10
type DirectConfig struct {
ProcessPaths ProcessPaths
InstallationID string
Selection Selection
Fence *CallFence
}
DirectConfig constructs a direct adapter for one selection. Fence counts the adapter's helper processes so that a credential commit waits for them.
type GenerationReference ¶
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"`
Checkpoint *CheckpointCompatibility `json:"checkpoint,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 LocalOptions ¶ added in v0.0.10
type LocalOptions struct {
Workspace workspacefs.Resolver
// Standalone selects registration or execution without a generation manager.
Standalone bool
// GenerationStateDirectory is the node state directory when constructing a
// retained generation. It must be canonical and absolute, and Standalone
// must be false.
GenerationStateDirectory string
}
LocalOptions supplies process-local context without changing persisted configuration.
type NodeConfig ¶ added in v0.0.10
type NodeConfig struct {
Specification DeploymentSpec `json:"specification"`
Generation uint64 `json:"generation"`
CoreURL string `json:"core_url"`
Provider string `json:"provider"`
InstallationID string `json:"installation_id"`
Native json.RawMessage `json:"native"`
}
NodeConfig is a node's configuration for one deployment generation. Native holds only the selected adapter's node-local settings, such as host paths; that adapter alone decodes it, strictly. Resources are read from Specification, never copied into Native.
type NodeDeployment ¶
type NodeDiagnosticCode ¶ added in v0.0.10
type NodeDiagnosticCode string
const ( NodeHostUnsupported NodeDiagnosticCode = "host_unsupported" NodeCapacityInsufficient NodeDiagnosticCode = "capacity_insufficient" )
type ProcessPaths ¶
ProcessPaths locates installed adapter helpers and their private state. The launcher supplies roots from the distribution layout; adapters own subpaths.
type ProviderProjection ¶ added in v0.0.10
type ProviderProjection struct {
Mode DeploymentMode `json:"mode"`
DeploymentPolicy
}
ProviderProjection is one registered Provider in the generated projections.
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" binding:"required"`
MemoryMiB uint32 `json:"memory_mib" binding:"required"`
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
ValidatePolicy validates the resources against a Provider's declaration. On external storage, environment_disk_mib is only the capacity quota request: zero requests none and the storage declaration decides whether a quota is possible.
type ResumeRequest ¶
type ResumeRequest struct {
Workspace *workspacefs.Binding `json:",omitempty"`
Reference Reference
OperationID string
Snapshot SnapshotIdentity
Target Compute
// Recovery observes the previous target and never starts a new restore.
ObserveOnly bool
}
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)
// The checkpoint lifecycle supplies exact-incarnation operations; Worker and
// Store remain the lifecycle owner. Its operations share one declaration.
Initial(context.Context, Reference) (Compute, error)
NewCompute(context.Context, Reference, uint64, *SnapshotIdentity) (Compute, error)
// GetCompute returns ErrNotFound only after the owning node verified that
// the exact incarnation no longer exists.
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)
// The preparation cache keeps the Environment filesystem left by one finished
// preparation. Key is opaque and the adapter owns storage and lifetime. Both
// address the allocation's initial compute and share one declaration.
// RestorePreparation returns false when it holds no valid entry.
RestorePreparation(ctx context.Context, r Reference, key string) (bool, error)
SavePreparation(ctx context.Context, r Reference, key string) error
// Observe reads one owned Runtime instance after verifying its ownership. It
// never renews, restarts or stops compute.
Observe(context.Context, runtimeobs.Target) (runtimeobs.Sample, 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 (Selection) ReplacesCredential ¶
type SnapshotIdentity ¶
type SnapshotIdentity struct {
Compatibility CheckpointCompatibility
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 ¶
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
Source Files
¶
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. |
|
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. |