allocator

package
v0.5.1 Latest Latest
Warning

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

Go to latest
Published: Oct 4, 2026 License: MIT Imports: 21 Imported by: 0

Documentation

Index

Constants

View Source
const CommandHorizon = 7 * 24 * time.Hour

CommandHorizon bounds how far back an incoming command may be sent and how long a tombstone guards its resources. It matches maxLeaseTTL so a durable lease never outlives the tombstones that guard it.

View Source
const DefaultMaxRecords = 10000

DefaultMaxRecords bounds the allocator's retained terminal records.

View Source
const DefaultRetention = 24 * time.Hour

DefaultRetention is the allocator's operator-configured terminal-record retention horizon applied when no explicit --retention is set. Since the F22 cutover, retention is allocator-local policy — a workload cannot choose it — and every configured value is bounded below by CommandHorizon.

Variables

View Source
var (
	ErrOfferReleased        = errors.New("offer was released")
	ErrInvalidConfig        = errors.New("invalid allocator configuration")
	ErrUnsupportedMessage   = errors.New("unsupported allocator message")
	ErrCapacityExhausted    = errors.New("allocator capacity exhausted")
	ErrOfferNotFound        = errors.New("offer not found")
	ErrOfferExpired         = errors.New("offer expired")
	ErrOfferAlreadyAssigned = errors.New("offer already assigned")
	ErrExecutionNotFound    = errors.New("execution not found")
	ErrExecutionConflict    = errors.New("execution conflicts with existing execution")
	ErrUnauthorized         = errors.New("sender is not authorized")
	ErrInvalidTransition    = errors.New("invalid execution transition")
	ErrRuntimeStart         = errors.New("runtime start failed")
	ErrRuntimeStop          = errors.New("runtime stop failed")
	ErrIDCollision          = errors.New("generated identifier already exists")
	ErrReplayCapacity       = errors.New("replay capacity exhausted")
	ErrReplayConflict       = errors.New("message ID reused with different content")
	ErrLeaseTooLong         = errors.New("lease duration exceeds the allocator bound")
	ErrStore                = errors.New("allocator state store failed")
	ErrRecoveryUnsupported  = errors.New("runtime does not support recovery")
	ErrIncompatible         = errors.New("node does not satisfy placement constraints")
)
View Source
var (
	ErrTunnelDisabled   = errors.New("direct-access tunnels are disabled on this allocator")
	ErrTunnelNoEndpoint = errors.New("tunnel endpoint is not ready")
)

tunnel errors map to explicit CommandError codes in errorResponse.

View Source
var ErrAdmission = errors.New("client admission denied")
View Source
var ErrCommandExpired = errors.New("command outside replay horizon")
View Source
var ErrResultExpired = errors.New("retained result expired")

Functions

This section is empty.

Types

type AdmissionPolicy added in v0.1.1

type AdmissionPolicy struct {
	Profiles map[string]r1sruntime.Resources `json:"profiles"`
	// Nil means a trusted network allowing all authenticated clients. [] denies all.
	AllowedClients []string         `json:"allowed_clients"`
	DefaultQuota   Quota            `json:"default_quota"`
	ClientQuotas   map[string]Quota `json:"client_quotas"`
}

func ReadAdmission added in v0.1.1

func ReadAdmission(reader io.Reader, capacity map[string]uint32) (AdmissionPolicy, error)

type Allocator

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

Allocator coordinates command handling around local policy, durable state, capacity accounting, replay protection, and the runtime boundary.

func New

func New(config Config, runtime r1sruntime.Runtime) (*Allocator, error)

New restores or constructs an allocator.

New is the allocator's composition root: it validates Config, builds the capacity ledger, replay cache, and tunnel registry, and loads durable state for the allocator's own identity. Command routing happens in Handle (dispatch.go), state transitions in the per-command files, and durable load/persist in state.go.

func (*Allocator) Available

func (a *Allocator) Available(class string) uint32

Available reports currently unreserved slots for a resource class.

func (*Allocator) CloseTunnel added in v0.3.1

func (a *Allocator) CloseTunnel(session *tunnel.Session)

CloseTunnel releases an edge's session without changing execution lifetime.

func (*Allocator) DialTunnelTarget added in v0.3.1

func (a *Allocator) DialTunnelTarget(ctx context.Context, session *tunnel.Session, port uint16) (net.Conn, error)

DialTunnelTarget revalidates execution authority at each splice, then delegates network namespace resolution to the runtime. The edge cancels ctx on session close and owns closing the returned connection on revocation.

func (*Allocator) EvictExpiredLeases added in v0.2.1

func (a *Allocator) EvictExpiredLeases(ctx context.Context) error

EvictExpiredLeases stops and terminally fails every non-terminal execution whose lease expired without renewal. Eviction follows the existing runtime Stop boundary exactly like cancellation: the CANCELLING transition commits first, the runtime stop is idempotent, and the terminal state commits with a lease-expiry reason that is distinguishable from client cancellation. A failed eviction restores the pre-eviction state and returns; the next sweep retries it instead of this call tight-looping over the same record. Terminal metadata stays retrievable for the result_retention horizon, and capacity returns on eviction.

func (*Allocator) Execution

func (a *Allocator) Execution(id string) (ExecutionSnapshot, bool)

Execution returns a cloned execution snapshot.

func (*Allocator) Handle

func (a *Allocator) Handle(ctx context.Context, envelope *r1sv1.Envelope) (responses []*r1sv1.Envelope, err error)

Handle validates an authenticated envelope and applies one allocator command. Duplicate message IDs from the same sender are acknowledged without mutation.

This is the protocol dispatch surface of the allocator: it checks freshness and envelope shape, keys every command into the replay cache so a redelivered message is answered from durable state instead of being re-applied, and routes to the per-command handlers in this package (offers.go, executions.go, lease.go, release.go, logs.go, tunnel.go). State transitions themselves live in those handler files; dispatch.go owns only the routing.

func (*Allocator) Node added in v0.3.1

func (a *Allocator) Node() *r1sv1.NodeCapabilities

Node returns a clone of the allocator's local capability advertisement.

func (*Allocator) Offer

func (a *Allocator) Offer(id string) (OfferSnapshot, bool)

Offer returns a cloned offer snapshot.

func (*Allocator) OpenTunnelSession added in v0.4.0

func (a *Allocator) OpenTunnelSession(executionID string, peerKey []byte) (*tunnel.Session, error)

OpenTunnelSession is the allocator-side accept-time authorization the edge (F14-02) calls before splicing a tunnel stream: it re-validates that the execution is still live and that the authenticated mesh peer key matches the execution's owner-bound key, then opens the execution's single session (F22-06). There is no grant token to consume and no TTL: the binding lives for the execution's lifetime. A failed validation leaves the binding intact and reusable, so a transient rejection (for example from a peer reconnecting) never burns the binding the way a consumed grant could.

func (*Allocator) Recover

func (a *Allocator) Recover(ctx context.Context) error

Recover reconciles durable non-terminal executions with the runtime. It never creates a missing workload: missing or conflicting runtime metadata is recorded as a terminal failure, while running tasks regain completion monitoring. An execution whose client-held lease already expired is evicted instead of being revived; one with a valid lease keeps running.

func (*Allocator) RuntimeCompleted

func (a *Allocator) RuntimeCompleted(completion r1sruntime.Completion) error

RuntimeCompleted applies an asynchronous completion or failure callback.

func (*Allocator) Sweep added in v0.1.1

func (a *Allocator) Sweep(ctx context.Context) error

Sweep evicts executions whose client-held lease expired without renewal, then commits metadata collection before deleting local log files. Pending cleanup survives failures and restart. In-flight transitions are never collected.

The retention policy this collector applies — CommandHorizon, DefaultRetention, tombstones, and candidate selection — lives in retention_policy.go.

func (*Allocator) SweepExpired

func (a *Allocator) SweepExpired() int

SweepExpired releases capacity held by offers whose TTL elapsed.

func (*Allocator) TunnelSession added in v0.3.0

func (a *Allocator) TunnelSession(executionID string) (*tunnel.Session, bool)

TunnelSession returns the active session for an execution, if any. Used by lifecycle tests and the edge plumbing.

type Config

type Config struct {
	// MaxRecords bounds the durable offer/execution/tombstone budget.
	MaxRecords int
	// Retention is the terminal-record retention the allocator applies to
	// every completed execution. It is operator configuration, never workload
	// input (F22-07): after the policy's result_retention was retired, a
	// workload cannot choose bookkeeping retention. Zero means
	// DefaultRetention; any value is bounded by CommandHorizon, which also
	// bounds replay-safe tombstones.
	Retention      time.Duration
	Identity       []byte
	Capacity       map[string]uint32
	OfferTTL       time.Duration
	LeaseTTL       time.Duration
	ReplayTTL      time.Duration
	ReplayCapacity int
	Now            func() time.Time
	NewID          func() string
	Store          StateStore
	Admission      AdmissionPolicy
	Logs           r1sruntime.LogStore
	// Tunnel is the allocator-local F14 direct-access tunnel authorization
	// surface. It is transport-neutral (opaque endpoint bytes, no network
	// library) and in-memory: grants are never persisted and a restart
	// invalidates them by construction.
	Tunnel TunnelConfig
	// Node is the allocator's bounded local capability metadata. When nil, the
	// allocator advertises no placement details and only matches empty
	// constraints (every node accepts every request); an explicit placement
	// constraint is then rejected so the client is never told a node matches
	// without evidence.
	Node *r1sv1.NodeCapabilities

	// Metrics optionally receives bounded allocator lifecycle and telemetry events.
	Metrics MetricsCollector
}

Config defines local allocator authority and fixed class capacities.

type ExecutionSnapshot

type ExecutionSnapshot struct {
	ExecutionID   string
	OfferID       string
	Client        []byte
	ResourceClass string
	Request       *r1sv1.ExecutionRequest
	State         *r1sv1.ExecutionState
}

ExecutionSnapshot is a read-only view of allocator execution state.

type MetricsCollector added in v0.5.0

type MetricsCollector interface {
	ObserveRequest(resourceClass string)
	ObserveOffer(resourceClass string)
	ObserveRejection(reason string)
	ObserveLeaseEviction()
	ObserveExecutionTerminal(resourceClass, phase string, duration time.Duration)
	ObserveDispatchLatency(command string, duration time.Duration)
	UpdateCapacity(class string, total, available uint32)
	SetActiveExecutions(class string, count int)
}

MetricsCollector is the interface Allocator uses to record operator-facing telemetry.

type OfferSnapshot

type OfferSnapshot struct {
	Offer       *r1sv1.ExecutionOffer
	Client      []byte
	Outstanding bool
	Assigned    bool
	Expired     bool
	Released    bool
	ExecutionID string
}

OfferSnapshot is a read-only view of allocator offer state.

type Quota added in v0.1.1

type Quota struct {
	Offers     uint32 `json:"offers"`
	Executions uint32 `json:"executions"`
}

type StateStore

type StateStore interface {
	Load(context.Context) ([]byte, error)
	Save(context.Context, []byte) error
}

StateStore atomically loads and saves one opaque allocator snapshot. Implementations must not retain or mutate the supplied byte slices. The durable schema itself lives in state_schema.go.

type TunnelConfig added in v0.3.0

type TunnelConfig struct {
	// Enabled turns on direct-access tunneling. When disabled, any open
	// request fails with a clear CommandError.
	Enabled bool
	// Endpoint is the allocator's transport-neutral overlay advertisement
	// returned in every open ack. The allocator edge (F14-02) supplies it when
	// it starts; without it an open fails as "endpoint not ready".
	Endpoint tunnel.Endpoint
}

TunnelConfig is the allocator-local authorization surface for direct-access tunnels. It carries no Yggdrasil-specific type: the endpoint advertisement is opaque bytes supplied by whatever edge is running inside r1sd, so the allocator core and the control protocol stay transport-neutral.

Jump to

Keyboard shortcuts

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