Documentation
¶
Overview ¶
Package store defines the storage interface for sqi-server and the domain model types shared across all components.
Design ¶
Store is a composite interface that embeds one sub-interface per aggregate (Farm, Queue, Worker, Job, Step, Task, etc.). Callers declare the narrowest interface they need rather than depending on the full Store:
// Scheduler only needs tasks and workers. func NewScheduler(tasks store.TaskStore, workers store.WorkerStore) *Scheduler // REST handler only needs jobs and queues. func NewJobHandler(jobs store.JobStore, queues store.QueueStore) *JobHandler
The SQLite and PostgreSQL implementations implement Store in full. The in-memory fake also implements Store in full, for unit tests that must not touch the filesystem.
JSON columns ¶
Fields that are stored as JSON text (e.g. Worker.Tags, Task.Parameters) are typed as Go maps or slices. The shared SQL implementation (internal/store/sqlstore) marshals and unmarshals them; callers work with native Go types throughout.
Errors ¶
Methods return ErrNotFound when the requested row does not exist, and ErrConflict when a uniqueness constraint would be violated. All other errors are driver-level and should be treated as opaque.
Index ¶
- Constants
- Variables
- func LeaderEpoch(ctx context.Context) (epoch int64, ok bool)
- func LeaseTTLMicros(ttl time.Duration) (int64, error)
- func MatchesSearch(query string, fields ...string) bool
- func RunAsComboValid(user, group *string) bool
- func RunMs(start, end time.Time) int64
- func SearchTerms(query string) []string
- func StaleRegistration(stored, incoming Worker) bool
- func ValidateTaskTransition(from, to TaskStatus) error
- func WithLeaderEpoch(ctx context.Context, epoch int64) context.Context
- type APIKey
- type APIKeyStore
- type AttemptCompletion
- type AttemptProgress
- type AttemptStatus
- type AuditEntry
- type AuditStore
- type BrokerStateStore
- type CapacityGroup
- type CapacityGroupKind
- type CapacityGroupState
- type CapacityGroupStore
- type CapacityPowerStore
- type CapacityProvider
- type CompletionResult
- type ComputeLocation
- type ComputeLocationStore
- type DeletedJob
- type DependencyUnsatisfiableError
- type FailureSummary
- type Farm
- type FarmStore
- type GPUInfo
- type HeartbeatOutcome
- type Job
- type JobSortField
- type JobStatus
- type JobStore
- type JobSubmission
- type JobTiming
- type LeadershipStore
- type Lease
- type LeaseOutcome
- type LeaseRequest
- type LeaseResult
- type ListJobsOptions
- type ListQueuesOptions
- type ListTasksOptions
- type ListWorkersOptions
- type LogStream
- type MachineProfile
- type NetInterface
- type OpenAttempt
- type Page
- type Pagination
- type PowerState
- type Product
- type ProductStore
- type ProgressOutcome
- type Queue
- type QueueSortField
- type QueueStore
- type Registration
- type RunningTiming
- type ServerMember
- type Session
- type SessionStore
- type SortDir
- type Source
- type Step
- type StepAmountRequirement
- type StepAttributeRequirement
- type StepDemand
- type StepHostRequirements
- type StepStatus
- type StepStore
- type StepTiming
- type StorageLocation
- type StorageLocationStore
- type StorageLocationType
- type Store
- type Task
- type TaskAttempt
- type TaskAttemptStore
- type TaskLog
- type TaskLogStore
- type TaskProgress
- type TaskSortField
- type TaskStatus
- type TaskStore
- type TemplateFormat
- type TimingStore
- type UsageClaim
- type UsageClaimStore
- type UsagePool
- type UsagePoolClaim
- type UsagePoolStore
- type UsagePoolUtilization
- type User
- type UserStore
- type Worker
- type WorkerCommitment
- type WorkerCredential
- type WorkerCredentialStore
- type WorkerExprLimits
- type WorkerJoinToken
- type WorkerSortField
- type WorkerStatus
- type WorkerStore
Constants ¶
const ( CapacityRetireSleep = "sleep" CapacityRetireShutdown = "shutdown" )
Capacity group retire actions.
const ( // MaxCapacityGroupMachines is the largest MaxMachines a group may declare. MaxCapacityGroupMachines = 10000 // MinCapacityGroupTimeout is the shortest IdleTimeout and BootTimeout. MinCapacityGroupTimeout = time.Minute )
Capacity group limits.
const ( // DefaultLimit is the page size used when the caller does not specify one. DefaultLimit = 50 // MaxLimit is the maximum page size accepted from callers. Requests above // it are clamped rather than rejected. MaxLimit = 1000 )
const ( // FailureReasonCanceledByUser annotates tasks canceled by an explicit // user/API cancel of the task or its job. FailureReasonCanceledByUser = "canceled by user" // FailureReasonUpstreamFailed annotates tasks cascade-canceled because an // upstream step dependency failed or was canceled. FailureReasonUpstreamFailed = "canceled: upstream step failed" // FailureReasonWorkerOffline is the attempt message recorded when the // heartbeat sweep terminates attempts of a worker that went offline. FailureReasonWorkerOffline = "worker went offline" // FailureReasonWorkerShutdown is the attempt message recorded when a // worker's forced shutdown abandons a task and it is reclaimed. FailureReasonWorkerShutdown = "worker shut down" // FailureReasonWorkerRestarted is the attempt message recorded when a // worker re-registers from a new process and its previous process's tasks // are reclaimed. FailureReasonWorkerRestarted = "worker restarted" )
Server-originated failure/termination reasons. TaskStore.FailureReasonSummary groups by exact string, so every producer of these annotations (scheduler, SQL stores, fake store) must share these values; differing wording would split the per-job dominant-reason counts.
const ( // AuthSourceLocal verifies against the stored password hash. AuthSourceLocal = "local" // AuthSourceLDAP verifies against the configured directory. AuthSourceLDAP = "ldap" // AuthSourceOIDC verifies against the configured OIDC provider. AuthSourceOIDC = "oidc" )
Credential backends for User.AuthSource.
const CapacityProviderScriptPrefix = "script:"
CapacityProviderScriptPrefix starts the name of a script provider: "script:<name>".
Variables ¶
var ErrConflict = errors.New("store: conflict")
ErrConflict is returned when an insert or update would violate a uniqueness constraint (e.g. creating a farm with a name that already exists).
var ErrDependencyUnsatisfiable = errors.New("store: job dependency can never be satisfied")
ErrDependencyUnsatisfiable is returned by JobStore.CreateJobSubmission when, inside its own transaction, a depends-on upstream job is missing or has already failed or been canceled.
var ErrFenced = errors.New("store: this server is no longer the leader")
ErrFenced is returned by a write made under a leadership context (WithLeaderEpoch) whose epoch is no longer the database's: another server has taken over since, and the write was rolled back. The server that gets it has lost its authority.
var ErrInvalidPagination = errors.New("store: invalid pagination parameters")
ErrInvalidPagination is reserved for Pagination values that cannot be corrected by clamping. No store method returns it.
var ErrInvalidTransition = errors.New("store: invalid state transition")
ErrInvalidTransition is returned when a requested status transition is not permitted by the task state machine.
Use errors.Is to test:
err := ValidateTaskTransition(from, to)
if errors.Is(err, ErrInvalidTransition) { ... }
var ErrLastAdmin = errors.New("store: would remove the last admin")
ErrLastAdmin is returned when a write would leave the farm with no enabled admin account. The guard is evaluated inside the write itself (invariant I4), so two concurrent demotions cannot both pass it.
var ErrNotFound = errors.New("store: not found")
ErrNotFound is returned by Get* methods when the requested row does not exist. Use errors.Is to check:
job, err := store.GetJob(ctx, id)
if errors.Is(err, store.ErrNotFound) { ... }
var ErrRunAsGroupWithoutUser = errors.New("store: run_as_group requires run_as_user")
ErrRunAsGroupWithoutUser is returned by QueueStore.CreateQueue and QueueStore.UpdateQueue when the resolved run_as_group (after any PreserveRunAsGroup substitution) would be non-empty while the resolved run_as_user (after any PreserveRunAsUser substitution) is nil or empty. The scheduler builds an isolation spec only when RunAsUser is set, adding RunAsGroup to it, so a group with no user would be ignored without a warning. The check uses the resolved values, not the raw request, so an UpdateQueue that clears run_as_user while an existing run_as_group is preserved, or sets run_as_group while run_as_user is preserved at nil, is rejected like a request setting both.
var ErrStaleRegistration = errors.New("store: registration is older than the one recorded")
ErrStaleRegistration is returned by WorkerStore.RegisterWorker when the registration was stamped by the broker earlier than the one already recorded: a late redelivery. Nothing is written; the returned worker is the stored row. Redelivery cannot make it current, so a caller acknowledges it rather than retrying.
var JobTransitions = map[JobStatus][]JobStatus{ JobStatusPending: {JobStatusRunning, JobStatusPaused, JobStatusCompleted, JobStatusFailed, JobStatusCanceled}, JobStatusRunning: {JobStatusPending, JobStatusPaused, JobStatusCompleted, JobStatusFailed, JobStatusCanceled}, JobStatusPaused: {JobStatusPending, JobStatusBlocked, JobStatusCompleted, JobStatusFailed, JobStatusCanceled}, JobStatusBlocked: {JobStatusPending, JobStatusPaused, JobStatusCanceled}, JobStatusCompleted: {}, JobStatusFailed: {JobStatusPending}, JobStatusCanceled: {JobStatusPending}, }
JobTransitions is the job lifecycle as sqi implements it. It is a test-time specification, not consulted at run time: every job write is a named store operation guarded in its own SQL (invariant I1), and the transition-table test asserts each operation's from-states are legal here.
The arrows come from the operations themselves:
pending → running PromoteJobRunning, on the first running report
pending/running/paused → terminal FinalizeJob, derived from the steps
running → pending DemoteStalledJobs
paused → pending ResumeJob, and RetryTasks on an auto-parked job
paused → blocked ResumeJob, for a job still holding its dependencies
blocked → pending ReleaseBlockedJob
failed/canceled → pending RetryTasks
any non-terminal → paused ParkJob (PauseJob for pending, running and blocked)
any non-terminal → canceled CancelJobExecution and CancelJobStatus
(CancelBlockedJob for blocked)
FinalizeJob's pending → completed is real: a task can reach assigned → succeeded with its running report dropped, so the job is never promoted. Its SQL guard also admits blocked, and a blocked job can be finalized: canceling the only task of its only step (CancelTask) finalizes that step pending → canceled, and FinalizeJob then moves the job blocked → canceled, an arrow the table already lists. blocked → completed and blocked → failed cannot happen, because a blocked job's tasks are never leased, so none of them succeeds or fails.
A write to a job's current status is a no-op, not a transition, so no status lists itself.
Functions ¶
func LeaderEpoch ¶ added in v0.4.0
LeaderEpoch returns the epoch ctx carries, and whether it carries one.
func LeaseTTLMicros ¶ added in v0.4.0
LeaseTTLMicros converts ttl to the integer microseconds a lease is held for, refusing one that rounds to nothing: a lease that expires as it is granted could never be told from a lost one.
func MatchesSearch ¶ added in v0.2.0
MatchesSearch reports whether every term in query (per SearchTerms) appears as a case-insensitive substring in at least one of fields. An empty query matches. It is the in-memory fake store's equivalent of the SQL stores' case-insensitive LIKE search, kept in this package so the two agree.
func RunAsComboValid ¶ added in v0.3.0
RunAsComboValid reports whether a resolved run_as_user/run_as_group pair is a valid queue isolation identity: nil/empty is always valid (no isolation configured); a non-empty group additionally requires a non-empty user.
func RunMs ¶ added in v0.4.0
RunMs is a succeeded attempt's measured run time from start to end, in whole milliseconds, rounded. Both stores measure with it, the SQL stores when they store tasks.run_ms and the fake on each read, so they agree to the millisecond.
func SearchTerms ¶ added in v0.2.0
SearchTerms splits a free-text search query into whitespace-separated, lower-cased terms. An empty or whitespace-only query yields no terms.
Terms are ANDed by callers and matched as case-insensitive substrings, so a multi-word query narrows results and is order-independent: "foo bar" keeps "fool-grabbing-rebar" and "barfoo". This matches the web UI's client-side filter (web/src/utils/filterBySearch.ts).
func StaleRegistration ¶ added in v0.4.0
StaleRegistration reports whether incoming, a registration for the worker stored describes, is a late redelivery of one the broker delivered before: both carry a broker timestamp and incoming's is strictly the earlier. It is the one statement of the rule WorkerStore.RegisterWorker applies, shared by the SQL stores and the fake.
func ValidateTaskTransition ¶ added in v0.3.0
func ValidateTaskTransition(from, to TaskStatus) error
ValidateTaskTransition returns nil if transitioning a task from one status to another is permitted by the state machine, or a descriptive error wrapping ErrInvalidTransition otherwise.
It lives in package store because TaskStore.CompleteTaskAttempt enforces it, and openjd imports store, so store cannot import openjd. Package openjd owns only the step machine (github.com/uberware/sqi/internal/openjd.ValidateStepTransition), with its own ErrInvalidTransition sentinel: match an error against the sentinel of the package whose machine returned it, or errors.Is does not match.
func WithLeaderEpoch ¶ added in v0.4.0
WithLeaderEpoch returns ctx carrying the epoch its server leads at. A store write made under it commits only while epoch is still the database's fencing epoch, checked as the last statement before the commit, and otherwise fails with ErrFenced. Reads, and the LeadershipStore methods, ignore it.
Types ¶
type APIKey ¶ added in v0.3.0
type APIKey struct {
ID string
UserID string
Name string
Prefix string // leading chars of the raw key, for list identification
TokenHash string // SHA-256 of the raw key; Go-side only
ExpiresAt *time.Time // nil = never expires
LastUsedAt *time.Time // nil = never used
RevokedAt *time.Time // nil = active
CreatedAt time.Time
}
APIKey is a long-lived machine credential owned by a user. TokenHash is a Go-side field only; it is never marshaled into a REST response, and the raw key it hashes is shown to the client exactly once, at creation.
type APIKeyStore ¶ added in v0.3.0
type APIKeyStore interface {
// CreateAPIKey inserts a new key. Returns [ErrConflict] on a token-hash or
// id collision.
CreateAPIKey(ctx context.Context, k APIKey) (APIKey, error)
// GetAPIKeyUserByTokenHash returns the active key for tokenHash together
// with its owning user, or [ErrNotFound] if the key is missing, revoked,
// or expired at now.
//
// It exists so authenticating a Bearer request costs one query rather than
// a key lookup followed by a user lookup. The key is returned alongside
// the user because the caller needs its id and last_used_at to decide
// whether to record a touch.
GetAPIKeyUserByTokenHash(ctx context.Context, tokenHash string, now time.Time) (APIKey, User, error)
// ListAPIKeysForUser returns the user's non-revoked keys, newest first.
ListAPIKeysForUser(ctx context.Context, userID string) ([]APIKey, error)
// RevokeAPIKey soft-revokes the key, scoped to its owner. Returns
// [ErrNotFound] if id is not one of userID's keys.
RevokeAPIKey(ctx context.Context, id, userID string, now time.Time) error
// TouchAPIKeyLastUsed sets last_used_at. Returns [ErrNotFound].
TouchAPIKeyLastUsed(ctx context.Context, id string, now time.Time) error
}
APIKeyStore is the persistence interface for APIKey records.
type AttemptCompletion ¶ added in v0.4.0
type AttemptCompletion struct {
// AttemptID is the attempt the worker is reporting on.
AttemptID string
// TaskID is the task the attempt belongs to.
TaskID string
// TaskStatus is the status the task should end up in: succeeded, failed or
// canceled.
TaskStatus TaskStatus
// AttemptStatus is the attempt's terminal status.
AttemptStatus AttemptStatus
// ExitCode is the process exit code, or nil when there is none.
ExitCode *int
// SessionID is the OpenJD session ID; "" leaves the stored value unchanged.
SessionID string
// Message is the attempt's human-readable outcome; "" leaves the stored
// value unchanged.
Message string
// FailureReason, when non-empty, is stamped on the task if the task ends up
// holding TaskStatus. It is never stamped by a Rejected report, including
// one from a superseded attempt. Callers pass "" for a success.
FailureReason string
// EndedAt is when the attempt ended, as the worker reports it. It feeds only
// the attempt's ended_at: the task row's updated_at and the released claims'
// released_at are stamped with server time.
EndedAt time.Time
}
AttemptCompletion is a worker's terminal report for one attempt.
type AttemptProgress ¶ added in v0.4.0
type AttemptProgress struct {
AttemptID, TaskID string
Progress *int
StatusText string
At time.Time
}
AttemptProgress is one progress snapshot a worker reports for an attempt. At is the worker's stamp and orders snapshots of the same attempt.
type AttemptStatus ¶
type AttemptStatus string
AttemptStatus is the terminal-or-active state of a single task execution.
const ( // AttemptStatusRunning means the worker is actively executing the task. AttemptStatusRunning AttemptStatus = "running" // AttemptStatusSucceeded means the task exited cleanly. AttemptStatusSucceeded AttemptStatus = "succeeded" // AttemptStatusFailed means the task exited with a non-zero code or the // worker reported a fatal error. AttemptStatusFailed AttemptStatus = "failed" // AttemptStatusCanceled means the attempt was interrupted before completion. AttemptStatusCanceled AttemptStatus = "canceled" )
func (AttemptStatus) IsTerminal ¶ added in v0.4.0
func (s AttemptStatus) IsTerminal() bool
IsTerminal reports whether s is a closed attempt state (succeeded, failed, canceled).
type AuditEntry ¶
type AuditEntry struct {
ID string
EntityType string // e.g. "job", "worker", "queue", "farm"
EntityID string // ID of the affected entity
Action string // e.g. "submitted", "canceled", "priority_changed"
Actor string // authenticated identity; empty in no-auth deployments
Details map[string]any // action-specific context
CreatedAt time.Time
}
AuditEntry is a single append-only record in the audit log. The log captures state-changing actions performed by users or internal components so that operators can reconstruct what happened and who did it.
Details is a free-form map for action-specific context — before/after values, failure reasons, parameter diffs, etc. The interpretation of Details is defined by the code that writes the entry.
type AuditStore ¶
type AuditStore interface {
// AppendAuditEntry inserts a new audit log entry. The caller must populate
// all fields including a unique ID and CreatedAt.
AppendAuditEntry(ctx context.Context, entry AuditEntry) error
}
AuditStore is the persistence interface for AuditEntry records. The audit log is append-only; there are no update or delete methods.
type BrokerStateStore ¶ added in v0.4.0
type BrokerStateStore interface {
// GetBrokerIdentity returns the recorded identity, or "" and a nil error
// when none has ever been recorded.
GetBrokerIdentity(ctx context.Context) (string, error)
// SetBrokerIdentity records identity as of at, replacing any earlier one.
// The database holds at most one identity.
SetBrokerIdentity(ctx context.Context, identity string, at time.Time) error
}
BrokerStateStore records which broker a database last ran against, so the server can notice at boot that the database has moved to a different one.
type CapacityGroup ¶ added in v0.4.0
type CapacityGroup struct {
ID string
FarmID string
Name string
Kind CapacityGroupKind
// Provider starts and stops the group's machines.
Provider CapacityProvider
Enabled bool
// QueueIDs are the queues whose demand the group serves.
QueueIDs []string
// MinMachines is the number of machines kept up regardless of demand;
// MaxMachines is the most the group may have up.
MinMachines int
MaxMachines int
// Priority orders groups competing for the same demand; higher first.
Priority int
// MaxStepUp is the most machines one scale-up decision may add.
MaxStepUp int
// ScaleUpCooldown is the shortest time between scale-ups.
ScaleUpCooldown time.Duration
// IdleTimeout is how long a machine sits idle before it is retired;
// BootTimeout is how long a started machine has to register.
IdleTimeout time.Duration
BootTimeout time.Duration
// RetireAction is what an idle machine is told to do: "sleep" or
// "shutdown".
RetireAction string
Profile MachineProfile
CreatedAt time.Time
UpdatedAt time.Time
}
CapacityGroup is a set of machines the server may grow and shrink to follow demand, and the policy for doing so.
func (CapacityGroup) ProfileWorker ¶ added in v0.4.0
func (g CapacityGroup) ProfileWorker() Worker
ProfileWorker returns a synthetic worker standing for one machine of g: the group's farm and the hardware, platform, tags, extensions and EXPR limits its profile declares. The worker owns copies of the profile's tags and extensions.
QueueID is the group's sole queue when it serves exactly one, and empty otherwise, which is what a real worker registered against several queues carries (no single queue affinity).
func (CapacityGroup) Validate ¶ added in v0.4.0
func (g CapacityGroup) Validate() error
Validate reports every rule the group breaks, joined, or nil. The API calls it before writing a group; the stores do not.
type CapacityGroupKind ¶ added in v0.4.0
type CapacityGroupKind string
CapacityGroupKind says how a capacity group's machines are known.
const ( // CapacityGroupNamed is a group of specific, already-provisioned machines. CapacityGroupNamed CapacityGroupKind = "named" // CapacityGroupSized is a group of interchangeable machines, all matching // the group's [MachineProfile]. CapacityGroupSized CapacityGroupKind = "sized" )
type CapacityGroupState ¶ added in v0.4.0
type CapacityGroupState struct {
GroupID string
// Requested is how many machines the server last asked the group's
// provider for, and RequestedAt when.
Requested int
RequestedAt *time.Time
// DegradedReason says why the group is degraded, empty when it is not;
// DegradedAt is when it became so.
DegradedReason string
DegradedAt *time.Time
// BackoffUntil is the earliest time the server asks for more machines
// again, or nil.
BackoffUntil *time.Time
UpdatedAt time.Time
}
CapacityGroupState is what the server has decided about a group at run time, kept apart from the operator's CapacityGroup fields so that replacing those can never overwrite it.
type CapacityGroupStore ¶ added in v0.4.0
type CapacityGroupStore interface {
// CreateCapacityGroup inserts a new group. Returns [ErrConflict] if the
// name is taken or the farm does not exist.
CreateCapacityGroup(ctx context.Context, g CapacityGroup) (CapacityGroup, error)
// GetCapacityGroup returns the group with the given ID, or [ErrNotFound].
GetCapacityGroup(ctx context.Context, id string) (CapacityGroup, error)
// GetCapacityGroupByName returns the group with the given name, or
// [ErrNotFound].
GetCapacityGroupByName(ctx context.Context, name string) (CapacityGroup, error)
// ListCapacityGroups returns all groups ordered by priority descending,
// then name.
ListCapacityGroups(ctx context.Context) ([]CapacityGroup, error)
// UpdateCapacityGroup replaces the mutable fields of an existing group and
// updates UpdatedAt. The ID and farm do not change. Returns [ErrNotFound]
// or [ErrConflict].
UpdateCapacityGroup(ctx context.Context, g CapacityGroup) (CapacityGroup, error)
// DeleteCapacityGroup removes a group by ID. Returns [ErrNotFound] if it
// does not exist, or [ErrConflict] while any worker belongs to it.
DeleteCapacityGroup(ctx context.Context, id string) error
}
CapacityGroupStore is the persistence interface for CapacityGroup records.
type CapacityPowerStore ¶ added in v0.4.0
type CapacityPowerStore interface {
// MarkWaking moves each of workerIDs that is a member of groupID, offline,
// not disabled and in [PowerAwake], [PowerAsleep] or [PowerWakeFailed] to
// [PowerWaking] at now, with no reason, and returns the IDs it moved in
// ascending order.
MarkWaking(ctx context.Context, groupID string, workerIDs []string, now time.Time) ([]string, error)
// FailWakes moves every member of groupID in [PowerWaking] whose
// PowerStateAt is before cutoff to [PowerWakeFailed] at now with reason,
// and returns the IDs it moved in ascending order.
FailWakes(ctx context.Context, groupID string, cutoff, now time.Time, reason string) ([]string, error)
// BeginRetirement moves workerID from [PowerAwake] to [PowerRetiring] at
// now, with no reason, only while it is a member of groupID, online, not
// disabled and holds no assigned or running task (the predicate
// [WorkerStore.DeleteEphemeralWorker] uses). ok is false, with no error,
// when any condition fails. It is decided under the worker's row lock, so
// a lease to the worker either committed first and is seen, or waits and
// is refused ([TaskStore.LeaseTask] refuses a retiring worker).
BeginRetirement(ctx context.Context, groupID, workerID string, now time.Time) (w Worker, ok bool, err error)
// FinishRetirement completes the retirement of workerID, which must be in
// [PowerRetiring]. A named member becomes [PowerAsleep] and offline at now,
// with no reason, and is returned. An ephemeral member is deleted and its
// active credential revoked at now, as [WorkerStore.DeleteEphemeralWorker]
// does, and returned as it was last stored (deleted = true). ok is false,
// with no error, when the worker is unknown or not retiring. A retiring
// member holding an assigned or running task, which BeginRetirement and
// the lease guard leave no way to reach, is refused with [ErrConflict] and
// left retiring, rather than put to sleep or deleted under its task.
FinishRetirement(ctx context.Context, workerID string, now time.Time) (w Worker, deleted, ok bool, err error)
// AbortRetirement moves workerID from [PowerRetiring] back to [PowerAwake]
// at now with reason; ok is false, with no error, when it is not retiring.
AbortRetirement(ctx context.Context, workerID string, now time.Time, reason string) (bool, error)
// ExpireRetirements aborts, as AbortRetirement does, every member of
// groupID in [PowerRetiring] whose PowerStateAt is before cutoff, and
// returns their IDs in ascending order.
ExpireRetirements(ctx context.Context, groupID string, cutoff, now time.Time, reason string) ([]string, error)
// ListCapacityGroupStates returns every recorded state by group ID; a
// group with none is absent.
ListCapacityGroupStates(ctx context.Context) (map[string]CapacityGroupState, error)
// PutCapacityGroupState stores s as its group's state, replacing any
// earlier one whole. A zero UpdatedAt is stamped with the current time.
// It returns [ErrNotFound] when the group does not exist. A group's state
// is deleted with the group.
PutCapacityGroupState(ctx context.Context, s CapacityGroupState) error
}
CapacityPowerStore holds the capacity machinery's power transitions of group members and each group's CapacityGroupState. Every write is made by the leader and fenced, and each one that touches a worker locks that worker's row first, so a transition and a lease to the same worker are ordered.
A transition that does not apply (the worker is unknown, or not in the state or condition it requires) is not an error: the methods report what moved.
type CapacityProvider ¶ added in v0.4.0
type CapacityProvider string
CapacityProvider names the mechanism that starts and stops a group's machines.
const ( // CapacityProviderExternal leaves starting and stopping to something // outside sqi. CapacityProviderExternal CapacityProvider = "external" // CapacityProviderWakeOnLAN ("wake_on_lan") wakes a named group's known // machines, so [CapacityGroup.Validate] refuses it on a sized group. // "script:<name>" names a provider program from the server's // configuration; Validate admits one on either kind, and the API refuses // one that is not configured. CapacityProviderWakeOnLAN CapacityProvider = "wake_on_lan" )
func (CapacityProvider) ScriptName ¶ added in v0.4.0
func (p CapacityProvider) ScriptName() (string, bool)
ScriptName returns the configured script p names and true, or "" and false when p is not a script provider.
type CompletionResult ¶ added in v0.4.0
type CompletionResult struct {
// Applied is true when the task now holds the requested status (it moved
// there, or was already there on a redelivery).
Applied bool
// Rejected is true when the task was not moved, for one of two reasons.
// Either the report's attempt is not the task's latest (the highest
// attempt_number): the reaper or an offline sweep closed it and a new lease
// replaced it, so the old worker's late report must not end the new lease.
// Or the state machine refused the transition: the task no longer holds a
// status the report can move it from, because it reached a different
// terminal status (a cancel, say) or went back to ready or pending (a reap,
// an offline reclaim, an auto-retry requeue or a manual retry). Either way
// the failure reason is not stamped, and the caller acks the report.
Rejected bool
}
CompletionResult reports what TaskStore.CompleteTaskAttempt did to the task. The attempt is closed and its claims released in every non-error case.
type ComputeLocation ¶ added in v0.2.0
type ComputeLocation struct {
ID string
Name string
Description string
CreatedAt time.Time
UpdatedAt time.Time
}
ComputeLocation is a named, globally-registered compute location. Workers declare their location at registration; jobs/steps target a location via the native OpenJD attr.worker.computelocation host requirement. The registry is a curated catalog used for surfacing and management; it does not gate scheduling (the matcher keys on the raw string).
Names are unique and matched by the scheduler exactly (case-sensitive). A worker's reported compute_location must match a step's declared location string exactly; use consistent casing when naming locations.
type ComputeLocationStore ¶ added in v0.2.0
type ComputeLocationStore interface {
// CreateComputeLocation inserts a new location. Returns [ErrConflict] if a
// location with the same name already exists.
CreateComputeLocation(ctx context.Context, loc ComputeLocation) (ComputeLocation, error)
// GetComputeLocation returns the location with the given ID, or [ErrNotFound].
GetComputeLocation(ctx context.Context, id string) (ComputeLocation, error)
// GetComputeLocationByName returns the location with the given name, or
// [ErrNotFound]. The match is exact (case-sensitive).
GetComputeLocationByName(ctx context.Context, name string) (ComputeLocation, error)
// ListComputeLocations returns all locations ordered by name.
ListComputeLocations(ctx context.Context) ([]ComputeLocation, error)
// UpdateComputeLocation replaces the mutable fields of an existing location
// and updates UpdatedAt. Returns [ErrNotFound] or [ErrConflict].
UpdateComputeLocation(ctx context.Context, loc ComputeLocation) (ComputeLocation, error)
// DeleteComputeLocation removes a location by ID. Returns [ErrNotFound] if
// it does not exist.
DeleteComputeLocation(ctx context.Context, id string) error
}
ComputeLocationStore is the persistence interface for ComputeLocation records.
type DeletedJob ¶
DeletedJob is the summary of a job removed by JobStore.DeleteTerminalJobsBefore, carrying the fields a WebSocket "removed" event needs.
type DependencyUnsatisfiableError ¶ added in v0.4.0
DependencyUnsatisfiableError names the upstream that made a submission's dependency unsatisfiable inside JobStore.CreateJobSubmission. Status is the upstream's status (failed or canceled), or empty when it was deleted. It matches ErrDependencyUnsatisfiable under errors.Is.
func (*DependencyUnsatisfiableError) Error ¶ added in v0.4.0
func (e *DependencyUnsatisfiableError) Error() string
func (*DependencyUnsatisfiableError) Unwrap ¶ added in v0.4.0
func (*DependencyUnsatisfiableError) Unwrap() error
Unwrap makes errors.Is(err, ErrDependencyUnsatisfiable) hold.
type FailureSummary ¶ added in v0.2.0
type FailureSummary struct {
// FailedCount is the total number of failed tasks with a non-empty
// FailureReason.
FailedCount int
// DominantReason is the most frequent FailureReason among failed tasks;
// ties are broken by reason string ascending for determinism.
DominantReason string
// DistinctReasons is the number of distinct FailureReason values.
DistinctReasons int
}
FailureSummary aggregates a job's failed tasks by Task.FailureReason, for the job-detail failure banner. The zero value ({0 "" 0}) means the job has no failed tasks with a recorded reason.
type Farm ¶
type Farm struct {
ID string
Name string
Description string
MaxConcurrentTasks int // 0 = unlimited; farm-level policy
// MaxAttempts, RetryDelaySeconds, and FailureLimit are farm-level retry
// policy overrides. Nil means "inherit" (server default).
MaxAttempts *int
RetryDelaySeconds *int
FailureLimit *int
CreatedAt time.Time
UpdatedAt time.Time
}
Farm is the top-level organizational grouping in sqi. A deployment typically has one farm, but large facilities may define multiple to represent distinct infrastructure pools, studios, or departments.
type FarmStore ¶
type FarmStore interface {
// CreateFarm inserts a new farm. The caller must populate all fields;
// the implementation persists them as-is. Returns [ErrConflict] if a
// farm with the same name already exists.
CreateFarm(ctx context.Context, farm Farm) (Farm, error)
// GetFarm returns the farm with the given ID, or [ErrNotFound].
GetFarm(ctx context.Context, id string) (Farm, error)
// ListFarms returns all farms ordered by name.
ListFarms(ctx context.Context) ([]Farm, error)
// UpdateFarm replaces the mutable fields (Name, Description,
// MaxConcurrentTasks) of an existing farm and updates UpdatedAt.
// Returns [ErrNotFound] if the farm does not exist, or [ErrConflict]
// if the new name is already taken.
UpdateFarm(ctx context.Context, farm Farm) (Farm, error)
// DeleteFarm removes a farm by ID. Returns [ErrNotFound] if it does not
// exist, or [ErrConflict] while a queue, job or worker still references
// the farm.
DeleteFarm(ctx context.Context, id string) error
}
FarmStore is the persistence interface for Farm records.
type GPUInfo ¶
type GPUInfo struct {
Vendor string `json:"vendor,omitempty"`
Model string `json:"model,omitempty"`
// VRAMMb is the VRAM capacity of each GPU device in mebibytes.
// All devices are assumed to be identical (see type-level note above).
VRAMMb int `json:"vram_mb,omitempty"`
Count int `json:"count,omitempty"`
}
GPUInfo describes the GPU(s) available on a worker host.
sqi assumes a homogeneous GPU configuration: all GPUs on the host are the same model with the same VRAM. VRAMMb is the per-device VRAM capacity; Count is the number of identical devices. Mixed-GPU workers (e.g. a render card alongside a display adapter) are not modeled; a worker with heterogeneous GPUs should report the lowest common VRAM to avoid over-scheduling.
type HeartbeatOutcome ¶ added in v0.4.0
type HeartbeatOutcome struct {
// Recorded is false when the heartbeat was a late one the store ignored.
Recorded bool
// Status is the worker's liveness after the write.
Status WorkerStatus
// PowerState is the worker's power state after the write.
PowerState PowerState
}
HeartbeatOutcome is what WorkerStore.UpdateWorkerHeartbeat did. Status and PowerState are set only when Recorded is true.
type Job ¶
type Job struct {
ID string
FarmID string
QueueID string
Name string
Owner string // human responsible for the job
Submitter string // authenticated identity that placed the job
Priority int // higher = more urgent; default 50
Status JobStatus
Project string
RawTemplate string // verbatim OpenJD YAML or JSON as submitted
TemplateFormat TemplateFormat
// Parameters holds the fully-bound job-parameter values produced by
// BindJobParameters at submission time, including applied defaults.
// Nil or empty for a job with no declared parameters, or one written
// before migration 00009 added the column; the scheduler then falls back
// to the template defaults.
Parameters map[string]string
// DeclaredExtensions holds the OpenJD extension names the template declared
// (its top-level `extensions:` list), as internal/openjd decoded and
// validated them at submission. Meaningless unless ExtensionsRecorded is
// true; a nil slice with the flag false says nothing about the template.
DeclaredExtensions []string
// ExtensionsRecorded reports whether DeclaredExtensions is an answer at
// all. It is false for every job row written before migration 00027 added
// the column, and true for everything submission writes since.
//
// The flag is separate from the slice because the scheduler must tell
// three states apart: not recorded, recorded-empty and recorded-non-empty.
// "Not recorded" does not mean "declares nothing": for the first the
// scheduler falls back to scanning the raw template, and for the second it
// does not. Nil-versus-empty cannot carry that difference, since Go
// erases it at every len() check, append and clone, and a *[]string makes
// every read site dereference.
ExtensionsRecorded bool
// DependsOn holds the IDs of the upstream jobs this job waits on (whole-job
// cross-job dependencies). Populated by GetJob; ListJobs leaves it nil to
// avoid N+1 queries. Empty for jobs with no cross-job dependencies.
DependsOn []string
// FailedAttempts is the job's cumulative count of genuine task failures.
FailedAttempts int
// MaxAttempts, RetryDelaySeconds, and FailureLimit are per-job retry policy
// overrides. Nil means "inherit" (Queue -> Farm -> server default).
MaxAttempts *int
RetryDelaySeconds *int
FailureLimit *int
// ParkReason is empty for a manual pause; set when the failure-limit sweep
// auto-parks the job (e.g. "failure limit reached (25)").
ParkReason string
// DependencyHold is true while the job's cross-job dependency hold is in
// place: it is set when the job is submitted with an upstream that has not
// completed, and cleared when [JobStore.ReleaseBlockedJob] releases it. A
// held job that is paused resumes to [JobStatusBlocked] rather than
// [JobStatusPending], so its held steps are released by the dependency
// sweep and never left pending forever.
DependencyHold bool
// EstimatedSeconds is the submitter's estimate of the job's total task run
// time, nil when none was given. UpdateJob writes it.
EstimatedSeconds *int
// ProductName and ProductVersion name the product the job was submitted
// from, empty for a raw-template job. Submission writes them; UpdateJob
// leaves them as stored.
ProductName string
ProductVersion string
CreatedAt time.Time
UpdatedAt time.Time
StartedAt *time.Time
CompletedAt *time.Time
}
Job is the top-level unit of work submitted to sqi-server. It holds the verbatim OpenJD template alongside derived metadata used by the scheduler.
func (Job) DeclaresExtension ¶ added in v0.3.0
DeclaresExtension reports whether the job's template declares the OpenJD extension name, and, in recorded, whether that answer is known at all.
A caller must branch on recorded before believing declared: recorded == false means the row predates migration 00027 and carries no extension list, and declared is then always false and means nothing, not "declares nothing".
The comparison is exact, not case-folded: extension names are validated against internal/openjd's registry at submission, so a stored name is one of the spellings that registry accepts.
type JobSortField ¶
type JobSortField string
JobSortField is a column by which JobStore.ListJobs results can be ordered.
const ( // JobSortByCreatedAt orders jobs by submission time (default). JobSortByCreatedAt JobSortField = "created_at" // JobSortByPriority orders jobs by priority (higher values first when SortDesc). JobSortByPriority JobSortField = "priority" // JobSortByStatus orders jobs alphabetically by status string. JobSortByStatus JobSortField = "status" // JobSortByUpdatedAt orders jobs by the time of the most recent change. JobSortByUpdatedAt JobSortField = "updated_at" // JobSortByName orders jobs alphabetically by name. JobSortByName JobSortField = "name" )
type JobStatus ¶
type JobStatus string
JobStatus is the lifecycle state of a job as a whole.
const ( // JobStatusPending means the job has been submitted but no tasks are // running yet (e.g. waiting on step dependency resolution or queue capacity). JobStatusPending JobStatus = "pending" // JobStatusRunning means at least one task is currently assigned or running. JobStatusRunning JobStatus = "running" // JobStatusPaused means the job has been administratively paused; no new // task assignments will be made until it is resumed. JobStatusPaused JobStatus = "paused" // JobStatusBlocked means the job is waiting on one or more cross-job // dependencies (other whole jobs) to complete. Its tasks are held pending // and never leased until every upstream job reaches JobStatusCompleted, at // which point it is released to JobStatusPending. If any upstream fails, is // canceled, or is deleted, the blocked job is canceled (upstream-failed). JobStatusBlocked JobStatus = "blocked" // JobStatusCompleted means all tasks across all steps succeeded. JobStatusCompleted JobStatus = "completed" // JobStatusFailed means one or more tasks failed and the job cannot proceed. JobStatusFailed JobStatus = "failed" // JobStatusCanceled means the job was explicitly canceled by a user or API // call before it could complete. JobStatusCanceled JobStatus = "canceled" )
func (JobStatus) IsTerminal ¶ added in v0.2.0
IsTerminal reports whether s is a terminal job state (completed, failed, canceled). A terminal job cannot be modified and its tasks are never eligible for assignment.
type JobStore ¶
type JobStore interface {
// CreateJobSubmission atomically creates a job, its dependency edges, its
// steps and its tasks. On any error nothing is written.
//
// The rows must not be written by separate calls: a failure partway would
// strand a pending job that no sweep reaps, or leave a job whose missing
// steps make the scheduler's checkJobCompletion, which derives job status
// from the steps that exist, report it completed.
//
// The returned JobSubmission carries the rows as stored. Read the edges
// back from its DependsOn field, not from its Job.DependsOn: the returned
// [Job] is scanned straight from the insert, which does not join the edge
// table, so Job.DependsOn is backend-dependent and must not be relied on.
// Only [JobStore.GetJob] populates it.
//
// Before it commits, it re-checks inside its own transaction that every
// DependsOn upstream still exists and has not failed or been canceled, and
// returns a [*DependencyUnsatisfiableError] (which matches
// [ErrDependencyUnsatisfiable] under errors.Is) naming the first such
// upstream, in ID order, if one has: UpstreamID is its ID and Status its
// status (failed or canceled), empty when it was deleted. A backend must
// fill both, because the submitter words its 422 from them. The
// submitter's own pre-read runs before the transaction, so an upstream can
// change in between. An upstream completing in that window is not
// refused: the job is created blocked and sweepBlockedJobs releases it on
// its next tick.
CreateJobSubmission(ctx context.Context, sub JobSubmission) (JobSubmission, error)
// GetJob returns the job with the given ID, or [ErrNotFound].
GetJob(ctx context.Context, id string) (Job, error)
// ListJobDependencyIDs returns the IDs of the upstream jobs jobID waits on,
// ordered by upstream job ID. Some IDs may reference jobs that have since
// been deleted — the caller (the reconciler) treats a missing upstream as
// unsatisfiable. Returns an empty slice when there are no dependencies.
ListJobDependencyIDs(ctx context.Context, jobID string) ([]string, error)
// ListDependents returns the IDs of jobs that declared a dependency on
// upstreamJobID (i.e. jobs waiting for it), ordered by dependent job ID.
// Returns an empty slice when none.
ListDependents(ctx context.Context, upstreamJobID string) ([]string, error)
// ListBlockedJobs returns every job currently in JobStatusBlocked, for the
// scheduler's periodic reconciliation sweep.
ListBlockedJobs(ctx context.Context) ([]Job, error)
// ListJobs returns a paginated, filtered, and sorted page of jobs matching
// opts. Call [Pagination.Validate] on opts.Pagination before passing it to
// ensure sensible defaults are applied.
ListJobs(ctx context.Context, opts ListJobsOptions) (Page[Job], error)
// UpdateJob replaces the mutable user-settable fields of an existing job
// (farm_id, queue_id, name, owner, submitter, priority, project,
// raw_template, template_format, max_attempts, retry_delay_seconds,
// failure_limit, estimated_seconds) and updates UpdatedAt. product_name and
// product_version are fixed at submission and left as stored.
//
// status, started_at, completed_at, failed_attempts, and park_reason are
// lifecycle columns and are excluded; use [CancelJobStatus],
// [FinalizeJob], or the scheduler's failure-limit sweep for those. The
// returned Job reflects the current DB state of all columns.
//
// Returns [ErrNotFound] if the job does not exist.
UpdateJob(ctx context.Context, job Job) (Job, error)
// CancelJobStatus transitions a job to [JobStatusCanceled] only when the
// job is not already in a terminal state, preventing a race where a
// concurrent scheduler transition to completed/failed would be overwritten.
//
// - Non-terminal job → canceled, returns nil.
// - Already canceled → no-op, returns nil (idempotent).
// - Already completed or failed → returns [ErrConflict].
// - Job not found → returns [ErrNotFound].
CancelJobStatus(ctx context.Context, id string) error
// PromoteJobRunning moves a pending job to running, stamping StartedAt on
// first start. Guarded on pending (invariant I1), so a late running report
// can never un-pause, un-cancel or revive a job. Returns false, writing
// nothing, for any other status (an unknown job included).
PromoteJobRunning(ctx context.Context, id string, now time.Time) (bool, error)
// PauseJob administratively pauses a pending, running or blocked job. A
// blocked job keeps its [Job.DependencyHold], so it resumes to blocked.
// Guarded in the write (invariant I1): a job in any other status is left
// untouched and [ErrConflict] is returned. [ErrNotFound] for an unknown job.
PauseJob(ctx context.Context, id string, now time.Time) error
// FinalizeJob derives the job's terminal status from its steps and writes
// it in one statement (invariant I4): failed if any step failed, else
// canceled if any was canceled, else completed, stamping CompletedAt. The
// return contract matches [StepStore.FinalizeStep]. Returns ErrNotFound for
// an unknown job.
FinalizeJob(ctx context.Context, id string, now time.Time) (JobStatus, bool, error)
// ReleaseBlockedJob moves a blocked job to pending, but only while every
// one of its upstream edges points at an existing completed job. The check
// is evaluated inside the write (invariant I4). Returns false, writing
// nothing, when the job is not blocked or an upstream is not completed, so
// a job another writer already canceled is never revived (invariant I1).
// Returns ErrNotFound for an unknown job.
ReleaseBlockedJob(ctx context.Context, id string, now time.Time) (bool, error)
// CancelBlockedJob cancels a blocked job together with every non-terminal
// step and every pending task it owns, stamping reason on tasks that carry
// none, in one transaction. Guarded on the job being blocked; otherwise it
// returns (false, nil, nil) and writes nothing. Returns the canceled tasks,
// and ErrNotFound for an unknown job.
CancelBlockedJob(ctx context.Context, id, reason string, now time.Time) (bool, []Task, error)
// DemoteStalledJobs returns any job in [JobStatusRunning] that currently has
// no task in [TaskStatusAssigned] or [TaskStatusRunning] — yet still has at
// least one schedulable (ready or pending) task — back to [JobStatusPending],
// stamping updated_at = now. It reconciles the [JobStatusRunning] invariant
// ("at least one task is currently assigned or running") after the heartbeat
// sweep or stale-assigned reaper returns a job's last in-flight task to the
// ready queue with no worker to pick it up, leaving the job spuriously marked
// running. Jobs whose tasks are all terminal are left untouched so the
// completion logic can finalize them to completed/failed. StartedAt is
// preserved (the job did start). Returns the IDs of the demoted jobs; on
// error, the result lists the jobs already demoted.
DemoteStalledJobs(ctx context.Context, now time.Time) ([]string, error)
// DeleteJob hard-deletes a job and every row that belongs to it, in one
// transaction and FK-safe order: usage_claims (for the job's task attempts),
// task_logs, task_attempts, tasks, steps, the job's own job_dependencies
// rows (its outgoing edges), then the jobs row. Incoming edges — rows where
// the deleted job is the depends_on_job_id of some other job — are
// left intact for the reconciler to observe as "upstream
// deleted". Returns [ErrNotFound] when the job does not exist. The
// audit_log is left intact (it references entities by id, not by foreign
// key).
//
// The job's anchor row is locked first, which serializes the cascade
// against the other job-anchored writers (cancel, retry, finalize,
// completion, retention) and against leases, which hold it FOR SHARE. A
// concurrent log append ([TaskLogStore.CreateTaskLog]) takes no anchor;
// on a store without a single writer the SQL store also locks the job's
// tasks that have attempts, so such an append waits for the delete and
// then fails on its foreign key instead of inserting a child row
// mid-cascade. As a backstop the store retries the cascade itself, inside
// DeleteJob, on a foreign-key or deadlock error; the REST handler that
// calls it does not retry. SQLite cannot produce either error, because
// its single write connection serializes every writer.
DeleteJob(ctx context.Context, id string) error
// DeleteTerminalJobsBefore hard-deletes terminal jobs whose completion time
// (completed_at, falling back to updated_at when NULL) is before cutoff, and
// returns a summary of each removed job. completed and canceled jobs are
// always eligible; failed jobs are included only when includeFailed is true.
// Active jobs are never removed. Each removed job's children are deleted via
// the same cascade as [DeleteJob].
//
// Each job is re-checked against that eligibility rule, under its anchor
// lock, immediately before its cascade starts. A job that a concurrent
// retry has made live since the eligibility read is skipped: it is neither
// deleted nor included in the returned summary. Each job is deleted in its
// own transaction, so on error the result lists the jobs already deleted.
DeleteTerminalJobsBefore(ctx context.Context, cutoff time.Time, includeFailed bool) ([]DeletedJob, error)
// ParkJob transitions a job to [JobStatusPaused] and records reason in
// ParkReason, but only while the job is non-terminal (not completed,
// failed, or canceled). A terminal job is a legitimate no-op: ParkJob
// returns nil without modifying it. Returns [ErrNotFound] if the job does
// not exist.
ParkJob(ctx context.Context, jobID, reason string, now time.Time) error
// ResumeJob is the inverse of [ParkJob] and of a manual pause. It moves a
// paused job to [JobStatusPending], or to [JobStatusBlocked] when the job
// still has its [Job.DependencyHold], so the dependency sweep releases or
// cancels it as it would any blocked job. An auto-parked job
// (non-empty ParkReason) additionally has its ParkReason cleared and its
// FailedAttempts reset to zero, re-arming the failure limit; without the
// reset the next genuine failure would re-park the job immediately.
// A manually paused job (empty ParkReason) keeps its FailedAttempts.
// A job that is no longer paused is a legitimate no-op: ResumeJob returns
// nil without modifying it. Returns [ErrNotFound] if the job does not
// exist.
ResumeJob(ctx context.Context, jobID string, now time.Time) error
}
JobStore is the persistence interface for Job records.
type JobSubmission ¶ added in v0.3.0
JobSubmission is everything one job submission creates.
It exists so a job, its dependency edges, its steps and its tasks are created together or not at all — see JobStore.CreateJobSubmission.
type JobTiming ¶ added in v0.4.0
type JobTiming struct {
JobID, QueueID string
Status JobStatus
EstimatedSeconds *int
Steps []StepTiming // ordered by step_id; steps with no tasks omitted
Running []RunningTiming // ordered by StartedAt
}
JobTiming is the inputs a remaining-time estimate reads for one job.
type LeadershipStore ¶ added in v0.4.0
type LeadershipStore interface {
// AcquireLeadership takes the lease for holder for ttl and returns the
// new epoch, when it is unheld or has lapsed. A lease still held and
// unexpired returns ok false and no error. Every takeover, of a lapsed
// lease or a released one, raises the epoch by one.
AcquireLeadership(ctx context.Context, holder string, ttl time.Duration) (epoch int64, ok bool, err error)
// RenewLeadership extends holder's lease at epoch to ttl from now. ok is
// false when holder no longer holds the lease at epoch, which is a loss of
// authority rather than an error.
RenewLeadership(ctx context.Context, holder string, epoch int64, ttl time.Duration) (ok bool, err error)
// ReleaseLeadership gives the lease up when holder holds it at epoch. It
// does nothing, and returns nil, for anyone else. The epoch is unchanged:
// the next acquire raises it.
ReleaseLeadership(ctx context.Context, holder string, epoch int64) error
// GetLeadership returns the lease and the database clock.
GetLeadership(ctx context.Context) (Lease, error)
// UpsertServerMember records m as seen now, inserting the member or
// refreshing its row. LastSeenUS is stamped from the database clock; the
// broker stamp is refreshed only when m.BrokerOK is set, so a member that
// has lost its broker keeps the time it last saw it.
UpsertServerMember(ctx context.Context, m ServerMember) error
// ListServerMembers returns every member, ordered by name then instance
// id, and the database clock the members' stamps are compared against.
ListServerMembers(ctx context.Context) (members []ServerMember, nowUS int64, err error)
// DeleteServerMembersUnseenFor removes members not seen for d and returns
// how many it removed.
DeleteServerMembersUnseenFor(ctx context.Context, d time.Duration) (int, error)
}
LeadershipStore is the leader lease and the membership of the servers sharing one database.
Its methods are never fenced (WithLeaderEpoch), even when called with a leadership context, stale or current: they are how a server comes to hold an epoch and keeps it, so they must work whatever epoch it holds. Where the store has a connection of its own for them they use it, so a renewal is never queued behind other writes.
type Lease ¶ added in v0.4.0
type Lease struct {
// Holder is the instance id leading, or "" when the lease is released.
Holder string
// Epoch is the epoch Holder leads at. It rises on every takeover, so a
// write stamped with an older epoch is known to come from a deposed leader.
Epoch int64
// ExpiresUS is when the lease lapses, in microseconds since the Unix epoch.
ExpiresUS int64
// NowUS is the database clock when the lease was read, on the same scale,
// so a reader can tell whether ExpiresUS has passed without its own clock.
NowUS int64
}
Lease is the leadership lease as the database holds it. Every instant is on the database's clock, never a server's.
type LeaseOutcome ¶ added in v0.4.0
type LeaseOutcome string
LeaseOutcome says what TaskStore.LeaseTask did. Every outcome other than LeaseLeased wrote nothing.
const ( // LeaseLeased means the task is now assigned to the worker, with a running // attempt and every requested usage claim. LeaseLeased LeaseOutcome = "leased" // LeaseLost means the task is no longer leasable: it is unknown, another // lease took it, it is still backing off, or its job or queue is paused or // its job is terminal. LeaseLost LeaseOutcome = "lost" // LeaseQueueFull means the task's queue is at its MaxConcurrentTasks. LeaseQueueFull LeaseOutcome = "queue_full" // LeaseFarmFull means the task's farm is at its MaxConcurrentTasks. LeaseFarmFull LeaseOutcome = "farm_full" // LeasePoolFull means a requested usage pool is at its max_concurrent, or // no longer exists. [LeaseResult.FullPool] names it. LeasePoolFull LeaseOutcome = "pool_full" )
type LeaseRequest ¶ added in v0.4.0
type LeaseRequest struct {
// TaskID is the task to lease.
TaskID string
// WorkerID is the worker the task is assigned to and the attempt runs on.
WorkerID string
// AttemptID is the caller-generated ID of the attempt the lease creates.
AttemptID string
// Now stamps the assignment, the attempt's start and the claims, and is
// the instant a retry backoff is compared against.
Now time.Time
// Claims are the usage-pool slots the attempt must hold. ClaimID, PoolID
// and PoolName are used; MaxConcurrent is ignored, because the pool's cap
// is read in the lease's own transaction.
Claims []UsagePoolClaim
// RequireOnline refuses the lease, as [LeaseLost], unless the worker's row
// exists and is online when the lease commits. A caller sets it when it
// chose to lease because it read the worker online, so a worker taken
// offline (a deregister, the heartbeat sweep) or deleted between that read
// and this write is not handed a task it will never receive. Left false,
// an offline worker and one with no row are not refused.
RequireOnline bool
}
LeaseRequest asks TaskStore.LeaseTask to lease one task to one worker.
type LeaseResult ¶ added in v0.4.0
type LeaseResult struct {
// Outcome is the lease's outcome.
Outcome LeaseOutcome
// Attempt is the attempt the lease created. It is set only when Outcome is
// [LeaseLeased].
Attempt TaskAttempt
// FullPool is the name of the full or missing pool when Outcome is
// [LeasePoolFull].
FullPool string
}
LeaseResult is what TaskStore.LeaseTask did.
type ListJobsOptions ¶
type ListJobsOptions struct {
// Filters
FarmID string
QueueID string
Status JobStatus // empty = all statuses
// Owner filters by job owner, compared case-insensitively. Empty = no
// filter.
Owner string
Project string
// Search is a case-insensitive substring matched against name, id, owner,
// and project. Empty = no search filter.
Search string
// Ordering — zero values use JobSortByCreatedAt / SortAsc.
SortBy JobSortField
SortDir SortDir
// Pagination — call Pagination.Validate() before use.
Pagination Pagination
}
ListJobsOptions filters and orders JobStore.ListJobs results. Zero values mean "no filter / use defaults".
type ListQueuesOptions ¶
type ListQueuesOptions struct {
// Filters
FarmID string
Paused *bool // nil = all, true = paused only, false = active only
// Ordering — zero values use QueueSortByName / SortAsc.
SortBy QueueSortField
SortDir SortDir
// Pagination — call Pagination.Validate() before use.
Pagination Pagination
}
ListQueuesOptions filters and orders QueueStore.ListQueues results. Zero values mean "no filter / use defaults".
type ListTasksOptions ¶
type ListTasksOptions struct {
// Filters
JobID string
StepID string
Status TaskStatus // empty = all statuses (mutually exclusive with Statuses)
Statuses []TaskStatus // IN-filter; takes precedence over Status when non-empty
WorkerID string // filter by assigned worker
// Ordering — zero values use TaskSortByCreatedAt / SortAsc.
SortBy TaskSortField
SortDir SortDir
// Pagination — call Pagination.Validate() before use.
Pagination Pagination
}
ListTasksOptions filters and orders TaskStore.ListTasks results. Zero values mean "no filter / use defaults".
type ListWorkersOptions ¶
type ListWorkersOptions struct {
// Filters
FarmID string
QueueID string
ComputeLocation string
// CapacityGroupID keeps only the members of that capacity group.
CapacityGroupID string
// Status filters by [Worker.EffectiveStatus]: disabled matches every
// disabled worker, online and offline match only enabled ones. Empty = all.
Status WorkerStatus
// Search is a case-insensitive substring matched against name, hostname,
// id, and compute_location. Empty = no search filter.
Search string
// IncludeUnaffiliated, when true and FarmID is non-empty, also returns
// workers whose FarmID is empty (unaffiliated workers that accept tasks
// from any farm). The scheduler's onlineWorkers sets it, so workers started
// without an explicit farm configuration are still dispatched to.
IncludeUnaffiliated bool
// Ordering — zero values use WorkerSortByHostname / SortAsc.
SortBy WorkerSortField
SortDir SortDir
// Pagination — call Pagination.Validate() before use.
Pagination Pagination
}
ListWorkersOptions filters and orders WorkerStore.ListWorkers results. Zero values mean "no filter / use defaults".
type LogStream ¶
type LogStream string
LogStream identifies the output stream a log chunk was captured from.
type MachineProfile ¶ added in v0.4.0
type MachineProfile struct {
CPUCount int `json:"cpu_count,omitempty"`
RAMMb int `json:"ram_mb,omitempty"`
GPUCount int `json:"gpu_count,omitempty"`
GPUMemoryMb int `json:"gpu_memory_mb,omitempty"`
OS string `json:"os,omitempty"`
Arch string `json:"arch,omitempty"`
ComputeLocation string `json:"compute_location,omitempty"`
Tags map[string]string `json:"tags,omitempty"`
Extensions []string `json:"extensions,omitempty"`
ExprLimits WorkerExprLimits `json:"expr_limits,omitzero"`
}
MachineProfile describes the machine a group's machines are expected to be. It is stored as JSON; a zero value means the field is not declared.
type NetInterface ¶ added in v0.4.0
type NetInterface struct {
Name string `json:"name"`
MAC string `json:"mac"`
Addrs []string `json:"addrs,omitempty"`
}
NetInterface is one network interface of a worker's machine: what a wake-on-LAN packet is addressed with. The JSON tags are the wire form, and the form the interfaces column stores.
func (NetInterface) WakeAddressable ¶ added in v0.4.0
func (i NetInterface) WakeAddressable() bool
WakeAddressable reports whether a wake-on-LAN packet can be addressed with i: it has a 6-byte MAC and an IPv4 address in CIDR form, whose network the packet is broadcast on. It is the one statement of that rule, which the wake_on_lan provider and the API's has_wake_address both apply.
type OpenAttempt ¶ added in v0.4.0
OpenAttempt is an attempt a worker may still be executing: running, its task's latest, while the task is assigned or running.
type Page ¶
type Page[T any] struct { // Items holds the current page of results. It is never nil; an empty // page is represented as an empty slice. Items []T // Total is the total number of items matching the filter, regardless of // the current page window. Used by clients to compute page counts. Total int // Limit mirrors the effective limit used to produce this page. Limit int // Offset mirrors the effective offset used to produce this page. Offset int }
Page is the generic result type returned by paginated list queries. T is the item type (e.g. Job, Task, Worker).
type Pagination ¶
type Pagination struct {
// Limit is the maximum number of items to return. 0 or less means use
// [DefaultLimit]. Values above [MaxLimit] are clamped to [MaxLimit].
Limit int
// Offset is the zero-based index of the first item to return.
Offset int
}
Pagination carries cursor-free (limit/offset) pagination parameters. Zero values are treated as "use defaults"; call Pagination.Validate before passing to a store method to ensure limits are applied.
func (*Pagination) Validate ¶
func (p *Pagination) Validate() error
Validate clamps Limit into the range [1, MaxLimit], applying DefaultLimit when Limit is zero or negative. Negative Offset is reset to zero. It always returns nil: every out-of-range value is clamped.
type PowerState ¶ added in v0.4.0
type PowerState string
PowerState is where a worker is in the capacity machinery's power cycle. It is separate from the worker's liveness (WorkerStatus) and from an operator's disabled flag.
const ( // PowerAwake is a running worker, and the state of every worker that is // not managed by a capacity group. PowerAwake PowerState = "awake" // PowerWaking is a machine the server has asked to start and that has not // registered yet. PowerWaking PowerState = "waking" // PowerRetiring is a worker told to sleep or shut down; it takes no new // work while it finishes what it holds. PowerRetiring PowerState = "retiring" // PowerAsleep is a machine that has deregistered and is suspended or off. PowerAsleep PowerState = "asleep" // PowerWakeFailed is a machine that did not register within its group's // boot timeout. PowerWakeFailed PowerState = "wake_failed" )
func RegistrationWake ¶ added in v0.4.0
func RegistrationWake(state PowerState, at *time.Time) (PowerState, *time.Time)
RegistrationWake is the wake part of the Registration for a worker whose stored power state, before the registration, was state since at.
type Product ¶ added in v0.2.0
type Product struct {
ID string
Name string // stable identity, e.g. "script", "studio/maya-render"
Title string
Description string
// Readme is long-form markdown documentation, rendered on detail pages
// only. Unlike Description it is never searched and never reaches a
// plain-text consumer; see the field table in docs/products.md.
Readme string
Category string
Version string
Source Source
Template string // verbatim OpenJD template
Format TemplateFormat
// OriginRef is the preset-library index entry name this product was
// installed from; empty for builtin/custom products.
OriginRef string
// OriginFingerprint is the definition's sha256 at install time; empty for
// builtin/custom products. Compared against the index to detect updates.
OriginFingerprint string
CreatedAt time.Time
UpdatedAt time.Time
}
Product is a named, versioned wrapper around a verbatim OpenJD template. Built-ins (SourceBuiltin) are served from the binary and never stored here; the products table holds only SourceCustom and SourceInstalled rows.
type ProductStore ¶ added in v0.2.0
type ProductStore interface {
// CreateProduct inserts a product. Returns [ErrConflict] on duplicate name.
CreateProduct(ctx context.Context, p Product) (Product, error)
// GetProductByName returns the product with the given name, or [ErrNotFound].
GetProductByName(ctx context.Context, name string) (Product, error)
// ListProducts returns all stored products ordered by name.
ListProducts(ctx context.Context) ([]Product, error)
// UpdateProduct replaces mutable fields of the product with p.Name.
// Returns [ErrNotFound] if no such product exists.
UpdateProduct(ctx context.Context, p Product) (Product, error)
// DeleteProduct removes the product with the given name. Returns
// [ErrNotFound] if it does not exist.
DeleteProduct(ctx context.Context, name string) error
}
ProductStore persists custom/installed Product rows. Built-in overlay and read-only enforcement live in internal/product.Catalog, not here.
type ProgressOutcome ¶ added in v0.4.0
type ProgressOutcome int
ProgressOutcome is what TaskStore.RecordAttemptProgress did with a snapshot.
const ( // ProgressRecorded means the snapshot replaced the attempt's previous one. ProgressRecorded ProgressOutcome = iota // ProgressOutOfOrder means a snapshot at or after At is already stored. ProgressOutOfOrder // ProgressNotLive means the attempt is closed or superseded, or the task is // not in flight. ProgressNotLive // ProgressTaskAssigned means the attempt is live but the task has not yet // been reported running. ProgressTaskAssigned )
type Queue ¶
type Queue struct {
ID string
FarmID string
Name string
Description string
Priority int
MaxConcurrentTasks int // 0 = unlimited
Paused bool
// MaxAttempts, RetryDelaySeconds, and FailureLimit are queue-level retry
// policy overrides. Nil means "inherit" (Farm -> server default).
MaxAttempts *int
RetryDelaySeconds *int
FailureLimit *int
// RunAsUser and RunAsGroup are the OS identity that tasks in this queue
// execute as. Nil RunAsUser means no isolation: tasks run as the worker's
// own user. Nil RunAsGroup means the target user's primary group.
//
// They are not part of the Queue -> Farm -> server-default cascade used by
// the retry-policy fields above: a farm-wide default would apply an OS
// identity to queues whose owner never asked for one.
RunAsUser *string
RunAsGroup *string
CreatedAt time.Time
UpdatedAt time.Time
// PreserveRunAsUser and PreserveRunAsGroup are read only by
// [QueueStore.UpdateQueue] (ignored by CreateQueue and never populated by a
// read). When true, the update leaves the corresponding column untouched,
// ignoring RunAsUser/RunAsGroup on this struct for that column, instead
// of overwriting it with the given (possibly zero) value.
//
// They let the API's "key omitted from the PUT body preserves the stored
// identity" rule run as one UPDATE statement. A GetQueue followed by a
// separate UpdateQueue would let an unrelated write that started first
// undo a concurrent admin write setting the identity (a lost update).
PreserveRunAsUser bool
PreserveRunAsGroup bool
}
Queue belongs to a Farm and is the container into which jobs are submitted. Scheduling policy (priority, concurrency limits, paused state) is configured at the queue level and may be overridden per job.
type QueueSortField ¶
type QueueSortField string
QueueSortField is a column by which QueueStore.ListQueues results can be ordered.
const ( // QueueSortByName orders queues alphabetically by name (default). QueueSortByName QueueSortField = "name" // QueueSortByPriority orders queues by priority (higher values first when // SortDesc). QueueSortByPriority QueueSortField = "priority" // QueueSortByCreatedAt orders queues by creation time. QueueSortByCreatedAt QueueSortField = "created_at" )
type QueueStore ¶
type QueueStore interface {
// CreateQueue inserts a new queue. Returns [ErrConflict] if a queue with
// the same name already exists within the same farm.
CreateQueue(ctx context.Context, queue Queue) (Queue, error)
// GetQueue returns the queue with the given ID, or [ErrNotFound].
GetQueue(ctx context.Context, id string) (Queue, error)
// ListQueues returns a paginated, filtered, and sorted page of queues
// matching opts. Call [Pagination.Validate] on opts.Pagination before
// passing it to ensure sensible defaults are applied.
ListQueues(ctx context.Context, opts ListQueuesOptions) (Page[Queue], error)
// UpdateQueue replaces the mutable fields of an existing queue and updates
// UpdatedAt, in a single atomic write. RunAsUser/RunAsGroup are the
// exception: when queue.PreserveRunAsUser (resp. PreserveRunAsGroup) is
// true, that column is left at its stored value instead of being
// overwritten by queue.RunAsUser (resp. queue.RunAsGroup) — see the
// [Queue.PreserveRunAsUser] doc for why this exists. Returns [ErrNotFound]
// or [ErrConflict] as appropriate.
UpdateQueue(ctx context.Context, queue Queue) (Queue, error)
// DeleteQueue removes a queue by ID. Returns [ErrNotFound] if it does not
// exist. The caller is responsible for ensuring no jobs reference the
// queue before deleting it.
DeleteQueue(ctx context.Context, id string) error
}
QueueStore is the persistence interface for Queue records.
type Registration ¶ added in v0.4.0
type Registration struct {
// Reclaimed are the previous process's assigned and running tasks it
// reclaimed, as they are after the reset.
Reclaimed []Task
// WokeFrom is the power state it moved the worker out of, to
// [PowerAwake]: [PowerWaking], [PowerAsleep] or [PowerWakeFailed]. Empty
// when it left the power state as it was. It is read under the lock the
// write takes.
WokeFrom PowerState
// WokeFromAt is when the worker entered WokeFrom, or nil when WokeFrom is
// empty or that time was not recorded.
WokeFromAt *time.Time
}
Registration is what WorkerStore.RegisterWorker did besides writing the worker row.
type RunningTiming ¶ added in v0.4.0
type RunningTiming struct {
StepID string
StartedAt time.Time // the task's latest attempt
Progress *int // that attempt's progress, nil when none reported
}
RunningTiming is one running task: its step, when its latest attempt started, and that attempt's progress.
type ServerMember ¶ added in v0.4.0
type ServerMember struct {
InstanceID string
Name string
Host string
PID int
Version string
GrantsFingerprint string
StartedAt time.Time
LastSeenUS int64 // set by the store from the database clock
BrokerOK bool // input to Upsert: stamp BrokerOKUS now
BrokerOKUS *int64 // output of List: the last stamp, nil if never
}
ServerMember is one server instance that has run against this database.
func (ServerMember) BrokerSeenWithin ¶ added in v0.4.0
func (m ServerMember) BrokerSeenWithin(nowUS int64, ttl time.Duration) bool
BrokerSeenWithin reports whether the member reached its broker within ttl of nowUS, the database clock its stamps were read against.
type Session ¶ added in v0.3.0
type Session struct {
ID string
TokenHash string
UserID string
ExpiresAt time.Time
CreatedAt time.Time
}
Session is a server-side login session. Token is never stored; only its hash.
type SessionStore ¶ added in v0.3.0
type SessionStore interface {
// CreateSession inserts a new session.
CreateSession(ctx context.Context, s Session) (Session, error)
// GetSessionByTokenHash returns the session with the given token hash, or
// [ErrNotFound] if missing or expired.
GetSessionByTokenHash(ctx context.Context, tokenHash string, now time.Time) (Session, error)
// GetSessionUserByTokenHash returns the user owning the unexpired session
// with the given token hash, or [ErrNotFound] if no such session exists.
//
// It exists so authenticating a request costs one query rather than a
// session lookup followed by a user lookup: it runs on every
// cookie-authenticated request.
GetSessionUserByTokenHash(ctx context.Context, tokenHash string, now time.Time) (User, error)
// DeleteSession removes a session by ID. Returns [ErrNotFound].
DeleteSession(ctx context.Context, id string) error
// DeleteExpiredSessions removes sessions whose expiry is at or before now,
// returning the count removed.
DeleteExpiredSessions(ctx context.Context, now time.Time) (int, error)
}
SessionStore is the persistence interface for Session records.
type Source ¶ added in v0.2.0
type Source string
Source identifies where a product definition came from.
const ( // SourceBuiltin is a product shipped embedded in the binary (read-only). SourceBuiltin Source = "builtin" // SourceCustom is a product authored on this server. SourceCustom Source = "custom" // SourceInstalled is a product installed from the community preset repo. SourceInstalled Source = "installed" )
type Step ¶
type Step struct {
ID string
JobID string
Name string
DependsOn []string // names of steps that must complete before this one
StepOrder int // position within the job for deterministic ordering
Status StepStatus
// HostRequirements declares the worker capabilities required by this step.
// Nil means any capable worker is eligible.
// Populated from the OpenJD hostRequirements block at submission time.
HostRequirements *StepHostRequirements
// ComputeLocation constrains tasks to workers in the named compute location
// (e.g. "onprem_linux", "cloud_aws_us_east"). Empty means any location is
// eligible. Mirrors the "attr.worker.computelocation" attribute in
// HostRequirements and is stored separately for fast SQL-level pre-filtering.
ComputeLocation string
CreatedAt time.Time
UpdatedAt time.Time
}
Step is one stage within a Job. Steps may depend on other steps; a step's tasks are not scheduled until all its dependencies have reached StepStatusCompleted.
type StepAmountRequirement ¶
type StepAmountRequirement struct {
// Name is the capability name, e.g. "amount.worker.vcpu".
Name string `json:"name"`
// Min, if non-nil, is the minimum acceptable value as a decimal string.
// The scheduler parses it with strconv.ParseFloat for comparison.
Min *string `json:"min,omitempty"`
// Max, if non-nil, is the maximum acceptable value as a decimal string.
Max *string `json:"max,omitempty"`
}
StepAmountRequirement is a single quantifiable host capability requirement.
type StepAttributeRequirement ¶
type StepAttributeRequirement struct {
// Name is the capability name, e.g. "attr.worker.os.family".
Name string `json:"name"`
// AnyOf, if non-empty, requires the host attribute to equal at least one
// of the listed values. String comparison is case-insensitive for
// well-known attributes (os.family, computelocation); exact for custom tags.
AnyOf []string `json:"any_of,omitempty"`
// AllOf, if non-empty, requires the host attribute to equal every listed
// value, for multi-valued tags (e.g. requiring two software packages to
// both be installed).
AllOf []string `json:"all_of,omitempty"`
}
StepAttributeRequirement is a single categorical host capability requirement.
type StepDemand ¶ added in v0.4.0
type StepDemand struct {
JobID, StepID, QueueID string
// RequiredCores is the tasks' declared reservation; 0 means undeclared,
// which costs a whole machine (as the scheduler's fullMachineCost).
RequiredCores int
// Ready is the number of leasable ready tasks with this RequiredCores.
Ready int
}
StepDemand is the leasable ready work of one step at one core reservation, as TaskStore.ListReadyStepDemand reports it.
type StepHostRequirements ¶
type StepHostRequirements struct {
// Amounts are quantifiable requirements such as CPUs, RAM, or GPU VRAM.
// Usage pool requirements use the "amount.worker.usagepool." prefix and
// are also listed in UsagePools for quick iteration.
Amounts []StepAmountRequirement `json:"amounts,omitempty"`
// Attributes are categorical requirements such as OS family or custom tags.
// The "attr.worker.computelocation" entry, if present, is mirrored as the
// enclosing [Step.ComputeLocation] field for SQL-level pre-filtering.
Attributes []StepAttributeRequirement `json:"attributes,omitempty"`
// UsagePools lists the names of [UsagePool] records that must have
// remaining capacity before a task from this step can be assigned.
// Derived from amounts named "amount.worker.usagepool.<name>" at
// submission time.
UsagePools []string `json:"usage_pools,omitempty"`
}
StepHostRequirements is the scheduler-facing representation of a step's hostRequirements block, normalised from the raw OpenJD model at submission time. The scheduler's matching logic reads these fields to determine whether a given worker can run a task.
Capability names follow the OpenJD specification and are matched in internal/scheduler/matcher.go:
- "attr.worker.os.family" → worker OS family ("linux", "windows", "macos"; a worker reporting GOOS "darwin" matches "macos" — see scheduler.osFamily)
- "attr.worker.os.version" → worker OS version string
- "attr.worker.computelocation" → worker compute location name
- "attr.worker.tag.<key>" → arbitrary worker tag value
- "amount.worker.vcpu" → worker CPU count
- "amount.worker.memory.mb" → worker RAM in MiB
- "amount.worker.gpu.count" → worker GPU count
- "amount.worker.gpu.memory.mb" → worker GPU VRAM in MiB
- "amount.worker.usagepool.<name>" → named usage pool (capacity check)
type StepStatus ¶
type StepStatus string
StepStatus is the lifecycle state of a step within a job.
const ( // StepStatusPending means the step is waiting for its dependencies to complete. StepStatusPending StepStatus = "pending" // StepStatusReady means all dependencies have succeeded; tasks can be scheduled. StepStatusReady StepStatus = "ready" // StepStatusRunning is reserved and never written: no store operation moves // a step to running, so a step with running tasks stays ready. It exists // for the wire types and for a submission written at that status (test // fixtures, through CreateJobSubmission), which FinalizeStep can still // finish. StepStatusRunning StepStatus = "running" // StepStatusCompleted means all tasks in this step succeeded. StepStatusCompleted StepStatus = "completed" // StepStatusFailed means one or more tasks failed. StepStatusFailed StepStatus = "failed" // StepStatusCanceled means the step was canceled. A step reaches it through // CancelPendingStep (the cascade from a failed or canceled upstream step), // CancelBlockedJob (a blocked job canceled before it ran), or FinalizeStep // once all its tasks are terminal and a canceled one is among them with no // failed one. A job cancel (CancelJobExecution) also finalizes every open // step of the job. StepStatusCanceled StepStatus = "canceled" )
func (StepStatus) IsTerminal ¶ added in v0.4.0
func (s StepStatus) IsTerminal() bool
IsTerminal reports whether s is a terminal step state (completed, failed, canceled).
type StepStore ¶
type StepStore interface {
// GetStep returns the step with the given ID, or [ErrNotFound].
GetStep(ctx context.Context, id string) (Step, error)
// ListSteps returns all steps for the given job, ordered by StepOrder
// ascending.
ListSteps(ctx context.Context, jobID string) ([]Step, error)
// FinalizeStep derives the step's terminal status from its tasks and writes
// it in one statement (invariant I4): failed if any task failed, else
// canceled if any was canceled, else completed. It returns the step's
// terminal status and whether this call wrote it. While any task is
// non-terminal it returns ("", false, nil) and writes nothing. A step that
// is already terminal returns its status with false, so a redelivered
// completion still drives the caller's idempotent propagation. A step with
// no tasks completes. Not bounded by MaxLimit. Returns ErrNotFound for an
// unknown step.
FinalizeStep(ctx context.Context, id string, now time.Time) (StepStatus, bool, error)
// ReleaseStep moves a pending step to ready and every one of its pending
// tasks to ready, in one transaction. Guarded on the step being pending
// (invariant I1): if it is not, nothing is written and it returns
// (false, nil, nil). It likewise writes nothing while the step's job still
// holds its cross-job dependencies ([Job.DependencyHold]): only
// [JobStore.ReleaseBlockedJob] lifts that hold, so no step-level release
// can run a waiting job's work early. Returns the promoted tasks.
// ErrNotFound for an unknown step.
ReleaseStep(ctx context.Context, id string, now time.Time) (bool, []Task, error)
// CancelPendingStep moves a pending step to canceled and every one of its
// pending tasks to canceled, stamping reason on tasks that carry none, in
// one transaction. Guarded on the step being pending and, decided inside
// the same transaction (invariant I4), on at least one of its upstream
// steps being failed or canceled; otherwise nothing is written and it
// returns (false, nil, nil). The second guard is what makes the failure
// cascade safe against a retry that revives the upstream after the caller
// read the step list. Returns the canceled tasks. ErrNotFound for an
// unknown step.
CancelPendingStep(ctx context.Context, id, reason string, now time.Time) (bool, []Task, error)
// ListStuckSteps returns every non-terminal step that has at least one task
// and no non-terminal task, and whose job is not terminal: steps
// FinalizeStep would finalize but that no future task report will ever
// trigger. Used once at scheduler start. Ordered by job ID, then step order.
//
// A job cancel finalizes the job's steps in its own transaction
// (CancelJobExecution), and migration 00033 finalizes the open steps of
// terminal jobs, so a terminal job carries open steps only in a database
// that has not been through that repair; those are the migration's to
// finalize, not this start-up pass's, which on a healthy farm must stay
// one query and no writes. The repair target is a live job
// whose step never finalized (so the job never completed); a terminal job
// has no downstream that needs its steps finalized, and jobs blocked on it
// follow its job status. A paused job is live and is listed. A step whose
// job row is missing is not listed.
ListStuckSteps(ctx context.Context) ([]Step, error)
// ListJobIDsWithPendingSteps returns, ascending, the IDs of jobs that are
// not terminal and not blocked and that have at least one pending step.
// Used once at scheduler start to re-run dependency resolution, so a step a
// retry reset to pending but never released (the server stopped between
// RetryTasks and ResolveDependencies) is released or cascade-canceled. A
// blocked job is excluded: its steps wait on another job.
ListJobIDsWithPendingSteps(ctx context.Context) ([]string, error)
}
StepStore is the persistence interface for Step records.
type StepTiming ¶ added in v0.4.0
type StepTiming struct {
StepID string
NotStarted int // pending + ready + assigned
Running int
Succeeded int
Failed int
Canceled int
// Measured is how many succeeded tasks have a succeeded attempt with an
// ended_at no earlier than its started_at; MeasuredSeconds sums those
// attempts' ended_at − started_at, so it is never negative.
// Only a task's latest attempt (highest attempt number, then greatest ID)
// is measured, so a task counts at most once. A task left succeeded by an
// attempt that a later one superseded counts in Succeeded but not in
// Measured: it under-measures, which only leaves the rate to the tasks
// that were measured.
Measured int
MeasuredSeconds float64
}
StepTiming is one step's task counts and measured run time, the inputs a remaining-time estimate reads for that step.
type StorageLocation ¶
type StorageLocation struct {
ID string
Name string
Type StorageLocationType
Description string
Roots map[string]string // compute_location_name -> root path
CreatedAt time.Time
UpdatedAt time.Time
}
StorageLocation is a named, globally-registered storage root. Jobs reference locations by name with a relative path; workers resolve the name to a concrete path for their compute location at execution time.
Roots maps a compute location name (or "default") to the root path for that location. Example:
Roots = map[string]string{
"default": "/mnt/nas/shows",
"windows_workers": `Z:\shows`,
"cloud_aws": "s3://studio-bucket/shows",
}
type StorageLocationStore ¶
type StorageLocationStore interface {
// CreateStorageLocation inserts a new location. Returns [ErrConflict] if
// a location with the same name already exists.
CreateStorageLocation(ctx context.Context, loc StorageLocation) (StorageLocation, error)
// GetStorageLocation returns the location with the given ID, or [ErrNotFound].
GetStorageLocation(ctx context.Context, id string) (StorageLocation, error)
// GetStorageLocationByName returns the location with the given name, or
// [ErrNotFound]. Used by the path resolver to look up locations by their
// symbolic name at task dispatch time.
GetStorageLocationByName(ctx context.Context, name string) (StorageLocation, error)
// ListStorageLocations returns all locations ordered by name.
ListStorageLocations(ctx context.Context) ([]StorageLocation, error)
// UpdateStorageLocation replaces the mutable fields of an existing
// location and updates UpdatedAt. Returns [ErrNotFound] or [ErrConflict].
UpdateStorageLocation(ctx context.Context, loc StorageLocation) (StorageLocation, error)
// DeleteStorageLocation removes a location by ID. Returns [ErrNotFound]
// if it does not exist.
DeleteStorageLocation(ctx context.Context, id string) error
}
StorageLocationStore is the persistence interface for StorageLocation records.
type StorageLocationType ¶
type StorageLocationType string
StorageLocationType identifies the backing storage technology.
const ( // StorageLocationTypeFilesystem is a POSIX or Windows filesystem path. StorageLocationTypeFilesystem StorageLocationType = "filesystem" // StorageLocationTypeS3 is an S3-compatible object store (AWS S3, // Backblaze B2, Cloudflare R2, MinIO, etc.). StorageLocationTypeS3 StorageLocationType = "s3" )
type Store ¶
type Store interface {
FarmStore
QueueStore
StorageLocationStore
ComputeLocationStore
ProductStore
UsagePoolStore
CapacityGroupStore
CapacityPowerStore
UsageClaimStore
WorkerStore
JobStore
StepStore
TaskStore
TaskAttemptStore
TaskLogStore
AuditStore
UserStore
SessionStore
APIKeyStore
WorkerCredentialStore
BrokerStateStore
LeadershipStore
TimingStore
io.Closer
}
Store is the top-level storage interface for sqi-server. It is composed of one sub-interface per aggregate so callers can depend on the narrowest slice they need.
Store embeds io.Closer; implementations must release any open database connections or file handles when Close is called.
type Task ¶
type Task struct {
ID string
JobID string // denormalized from Step for query efficiency
StepID string
Name string
Parameters map[string]string // resolved parameter values for this task
Status TaskStatus
AssignedWorkerID string // empty when unassigned
AssignedAt *time.Time // nil when unassigned
CreatedAt time.Time
UpdatedAt time.Time
// RequiredCores is the task's declared CPU reservation (OpenJD
// amount.worker.vcpu min). Nil means undeclared — the scheduler treats the
// cost as the running worker's full CPUCount (one such task per worker).
RequiredCores *int
// UnschedulableReason is set when a ready task cannot be satisfied by any
// online worker (empty = schedulable). An annotation on the task, not a
// status.
UnschedulableReason string
// FailureReason is the human-readable reason the task reached a terminal
// non-success (failed or canceled). Empty for non-terminal tasks; cleared
// on retry. A denormalized copy of the latest terminal attempt's reason.
FailureReason string
// FailedAttempts counts attempts that ran and failed (worker-reported
// "failed"). Lost or reclaimed attempts do not increment it.
FailedAttempts int
// RetryAfter, when non-nil and in the future, holds the task in the ready
// queue until the backoff delay elapses. Nil means immediately eligible.
RetryAfter *time.Time
}
Task is the atomic unit of work — one process on one worker. Tasks are derived from an OpenJD step's parameter space expansion.
type TaskAttempt ¶
type TaskAttempt struct {
ID string
TaskID string
WorkerID string
SessionID string // OpenJD session ID; empty until the worker reports one
AttemptNumber int // 1-based; incremented on each retry
Status AttemptStatus
ExitCode *int // nil while running or if the process was signaled
// Message is the human-readable reason for a terminal attempt (worker- or
// server-supplied); empty while running or on success.
Message string
StartedAt time.Time
EndedAt *time.Time // nil while running
CreatedAt time.Time
// Progress, StatusText and ProgressAt are the latest progress snapshot the
// worker reported for this attempt. Progress is a percent, nil when the
// task reports none; ProgressAt is nil until a snapshot is recorded.
Progress *int
StatusText string
ProgressAt *time.Time
}
TaskAttempt records a single execution of a Task on a specific worker. A task may have multiple attempts if it is retried after failure.
SessionID is the OpenJD session identifier reported by the worker. Multiple task attempts that share the same session ID ran within the same OpenJD Session on the same worker — they shared a working directory and environment setup. See docs/architecture.md ("SQLite schema overview") for why sessions are not a first-class table.
type TaskAttemptStore ¶
type TaskAttemptStore interface {
// GetTaskAttempt returns the attempt with the given ID, or [ErrNotFound].
GetTaskAttempt(ctx context.Context, id string) (TaskAttempt, error)
// LatestTaskAttempt returns the attempt with the highest AttemptNumber for
// the given task, or [ErrNotFound] if no attempts exist yet. The REST layer
// reads it, and the scheduler uses it to tell whether a failure report's
// attempt is still the task's latest. Attempt numbers are assigned inside
// [TaskStore.LeaseTask], not from this read.
LatestTaskAttempt(ctx context.Context, taskID string) (TaskAttempt, error)
// ListTaskAttempts returns all attempts for the given task, ordered by
// AttemptNumber ascending.
ListTaskAttempts(ctx context.Context, taskID string) ([]TaskAttempt, error)
// ListOpenAttempts returns every open attempt (see [OpenAttempt]), ordered
// by CreatedAt then AttemptID. It only reads; callers that close an attempt
// (the restore fence, reconciliation) go through ReclaimTaskAttempt, which
// re-checks openness under the job's anchor.
ListOpenAttempts(ctx context.Context) ([]OpenAttempt, error)
// LatestAttemptProgress returns, for each given task, the progress snapshot
// of its latest attempt, for a task that is in flight or finished (not
// pending or ready: a requeued task's earlier attempt is closed and its
// snapshot stale). A task with no attempt, or whose latest attempt has no
// snapshot (no ProgressAt and no status text), is absent from the map. No
// tasks returns an empty map without querying.
LatestAttemptProgress(ctx context.Context, taskIDs []string) (map[string]TaskProgress, error)
// RunningProgressByJob returns the sum, over the job's running tasks, of
// their latest attempt's progress as a fraction of one (a task with no
// reported progress counts as zero). An unknown job returns 0.
RunningProgressByJob(ctx context.Context, jobID string) (float64, error)
// RunningProgressByJobs is RunningProgressByJob for many jobs in one
// statement. A job with no running tasks, or an unknown one, is absent from
// the map (read it as zero). No jobs returns an empty map without querying.
RunningProgressByJobs(ctx context.Context, jobIDs []string) (map[string]float64, error)
}
TaskAttemptStore is the persistence interface for TaskAttempt records.
type TaskLog ¶
type TaskLog struct {
ID string
TaskID string
AttemptID string
// SeqNum is the worker-assigned monotonic sequence number for this chunk
// within the attempt. Starts at 1; callers must not assume it is
// contiguous: gaps can appear if chunks are dropped or reordered.
SeqNum int64
// NATSSeq is the JetStream message sequence number from the SQI_LOGS
// stream, used as a stable, dense offset cursor for the log-tail REST
// endpoint. Stored as int64 to match SQLite's INTEGER affinity; NATS
// stream sequences are uint64 but do not approach the int64 maximum.
NATSSeq int64
// At is the worker's local timestamp when the chunk was captured.
At time.Time
// ReceivedAt is the server's clock time when the chunk was persisted.
// Monotonically increasing within a server instance; useful for
// detecting clock skew between worker and server.
ReceivedAt time.Time
// Stream is "stdout" or "stderr".
Stream LogStream
// Data is the raw log text.
Data string
}
TaskLog is one chunk of output produced by a running task.
Workers publish log chunks to task.logs.<workerID>.<taskID> as output is produced. The server persists each chunk here with:
- A monotonic worker-side sequence number (SeqNum) per attempt, starting at 1 and incrementing by 1. This allows the REST log-tail endpoint to return chunks in the order the worker produced them regardless of NATS delivery order.
- A NATS stream sequence number (NATSSeq) used as the primary DB insertion order and for efficient cursor-based pagination.
- A server-side receipt timestamp (ReceivedAt) for audit purposes.
type TaskLogStore ¶
type TaskLogStore interface {
// CreateTaskLog inserts a new log chunk. The caller must populate all
// fields including a unique ID. A chunk whose AttemptID and SeqNum are
// already stored is not written again; CreateTaskLog returns [ErrConflict].
CreateTaskLog(ctx context.Context, log TaskLog) (TaskLog, error)
// ListTaskLogs returns log chunks for a task attempt in NATSSeq ascending
// order. Pass afterNATSSeq = 0 to start from the beginning; pass the
// NATSSeq of the last received chunk to page forward. Limit controls the
// maximum number of chunks returned.
//
// The REST log-tail endpoint uses it.
ListTaskLogs(ctx context.Context, attemptID string, afterNATSSeq int64, limit int) ([]TaskLog, error)
}
TaskLogStore is the persistence interface for TaskLog records.
type TaskProgress ¶ added in v0.4.0
TaskProgress is the latest progress snapshot of a task's latest attempt.
type TaskSortField ¶
type TaskSortField string
TaskSortField is a column by which TaskStore.ListTasks results can be ordered.
const ( // TaskSortByCreatedAt orders tasks by creation time (default). TaskSortByCreatedAt TaskSortField = "created_at" // TaskSortByStatus orders tasks alphabetically by status string. TaskSortByStatus TaskSortField = "status" // TaskSortByUpdatedAt orders tasks by the time of the most recent change. TaskSortByUpdatedAt TaskSortField = "updated_at" // TaskSortByName orders tasks alphabetically by name. TaskSortByName TaskSortField = "name" )
type TaskStatus ¶
type TaskStatus string
TaskStatus is the lifecycle state of an individual task.
const ( // TaskStatusPending means the task exists but its step's dependencies have // not yet been satisfied. TaskStatusPending TaskStatus = "pending" // TaskStatusReady means the task is eligible for assignment; its step's // dependencies have completed. TaskStatusReady TaskStatus = "ready" // TaskStatusAssigned means the task has been assigned to a worker but the // worker has not yet confirmed it is running. TaskStatusAssigned TaskStatus = "assigned" // TaskStatusRunning means the worker has confirmed the task is executing. TaskStatusRunning TaskStatus = "running" // TaskStatusSucceeded means the task completed successfully. TaskStatusSucceeded TaskStatus = "succeeded" // TaskStatusFailed means the task exited with a non-zero code or the // worker reported a fatal error. TaskStatusFailed TaskStatus = "failed" // TaskStatusCanceled means the task was explicitly canceled before it could // complete. TaskStatusCanceled TaskStatus = "canceled" )
func (TaskStatus) IsTerminal ¶ added in v0.4.0
func (s TaskStatus) IsTerminal() bool
IsTerminal reports whether s is a terminal task state (succeeded, failed, canceled).
type TaskStore ¶
type TaskStore interface {
// GetTask returns the task with the given ID, or [ErrNotFound].
GetTask(ctx context.Context, id string) (Task, error)
// ListTasks returns a paginated, filtered, and sorted page of tasks
// matching opts. Call [Pagination.Validate] on opts.Pagination before
// passing it to ensure sensible defaults are applied.
ListTasks(ctx context.Context, opts ListTasksOptions) (Page[Task], error)
// CompleteTaskAttempt applies a worker's terminal report in one
// transaction (invariant I3):
// 1. close the attempt if it is still running;
// 2. release every active claim the attempt holds;
// 3. if c.AttemptID is not the task's latest attempt (the highest
// attempt_number; an unknown attempt or another task's is not), stop:
// the result is Rejected and the task is not touched;
// 4. move the task to c.TaskStatus by compare-and-set, and only while it is
// assigned or running: a task already holding the status is a no-op
// (Applied), anything else (ready, pending, or another terminal status)
// is Rejected;
// 5. stamp c.FailureReason when the task ends up holding c.TaskStatus.
// Steps 1 and 2 commit even when step 3 or 4 rejects the report, so a
// canceled task's late report never leaks a usage slot. Step 3 is what
// stops a superseded attempt's late report (its attempt reaped or its
// worker taken offline, the task leased again) from ending the task by a
// legal arrow while the new attempt is open and holds its claims. Returns
// ErrNotFound for an unknown task. A redelivery is safe: the attempt is
// already closed, so it is not rewritten, and a task already holding
// c.TaskStatus is a no-op, provided the attempt is still the latest.
CompleteTaskAttempt(ctx context.Context, c AttemptCompletion) (CompletionResult, error)
// StartTaskAttempt applies a worker's "running" report in one transaction,
// behind the task's job-row anchor: it acts only while attemptID is still
// running (not closed) and is the task's latest attempt and the task is
// assigned or running. It then moves the task assigned -> running (a
// running task is left as is, so a redelivery is harmless) and records
// sessionID on the attempt when non-empty. started is false, with a nil
// error, when the report is stale: the attempt was closed by a reap, an
// offline reclaim or a cancel, or a newer lease superseded it. An unknown
// task is [ErrNotFound]. No task-row lock is needed for the latest-attempt
// check: a lease holds the job row FOR SHARE, so none commits between the
// check and the write.
StartTaskAttempt(ctx context.Context, attemptID, taskID, sessionID string, now time.Time) (started bool, err error)
// RecordAttemptProgress overwrites the progress snapshot of a live attempt
// (a nil Progress stores NULL). An attempt that is not live (see
// StartTaskAttempt) is [ProgressNotLive]; a live attempt whose task is still
// assigned is [ProgressTaskAssigned]; a snapshot not strictly newer than the
// stored one is [ProgressOutOfOrder]. None of those write. An unknown task
// is [ErrNotFound]. No job-row anchor is taken: the write is one guarded
// statement on the attempt row. jobID is the job that owns the task, read
// from the task row, so a caller routes by it rather than by anything the
// reporting worker asserted; it is empty only with an error.
RecordAttemptProgress(ctx context.Context, p AttemptProgress) (outcome ProgressOutcome, jobID string, err error)
// ReclaimTaskAttempt hands one task back as the offline reclaim does: it
// returns the task to ready with no worker, closes attemptID as failed with
// [FailureReasonWorkerShutdown] and releases its claims, without touching
// failed_attempts or the job's failure count. It acts only while attemptID
// is running and is the task's latest and the task is assigned or running;
// otherwise reclaimed is false and nothing changes. Anchor and statement
// order are the offline reclaim's: the job row, then the task, then the
// attempt and claims. Unknown task: [ErrNotFound].
ReclaimTaskAttempt(ctx context.Context, attemptID, taskID string, now time.Time) (reclaimed bool, err error)
// ListReadyTasks returns up to limit tasks in [TaskStatusReady] that
// belong to non-paused queues within the given farm, excluding:
// - tasks whose RetryAfter is set and after now (still backing off), and
// - tasks whose job is paused or in a terminal status (completed,
// failed, canceled),
// ordered by:
// 1. job priority descending (higher values first),
// 2. job submission time ascending (earlier jobs win ties),
// 3. step order ascending (earlier steps in a job run before later ones),
// 4. task creation time ascending (stable tiebreaker within a step).
//
// Used by the scheduler's assignment loop.
ListReadyTasks(ctx context.Context, farmID string, now time.Time, limit int) ([]Task, error)
// ReclaimStaleAssignedTasks returns tasks stuck in [TaskStatusAssigned] whose
// assigned_at is older than cutoff to [TaskStatusReady], clearing
// assigned_worker_id and assigned_at so the scheduler can reassign them.
// Tasks in [TaskStatusRunning] are left untouched: only assignments the
// worker never reported running are reclaimed.
//
// Inside the same transaction it closes each reclaimed task's running
// attempts as [AttemptStatusFailed] and releases the claims of the task's
// closed attempts (invariant I3), so the caller never looks an attempt up
// afterwards: a task leased again after this call keeps its new attempt and
// claims. Returns exactly the tasks this call reclaimed (invariant I2), as
// they are after the reset: [TaskStatusReady] with an empty
// assigned_worker_id. An implementation may commit in batches; on error,
// the result lists the tasks already reclaimed.
//
// Statement order: the tasks are reset first, then their attempts are
// closed, then their claims released. The anchors (each candidate task's
// job row, sorted by id) are taken before the UPDATE and without locking a
// task row first: the candidates are read unlocked, their job rows locked,
// then the UPDATE runs re-guarded on the candidate IDs, status assigned and
// the cutoff. Locking the task rows first, or anchoring after the UPDATE
// ... RETURNING, would take a task row before its job row, the reverse of
// every job-level operation's order.
//
// skip holds task IDs that are left as they are even when stale; nil skips
// nothing. The scheduler passes the tasks a queued status report may still
// move.
ReclaimStaleAssignedTasks(ctx context.Context, cutoff time.Time, skip map[string]bool) ([]Task, error)
// CountActiveTasksInQueue returns the number of tasks for the given queue
// that are currently in [TaskStatusAssigned] or [TaskStatusRunning] state.
// Used by the scheduler's per-queue policy gate.
CountActiveTasksInQueue(ctx context.Context, queueID string) (int, error)
// CountActiveTasksInFarm returns the number of tasks across all queues in
// the given farm that are currently in [TaskStatusAssigned] or
// [TaskStatusRunning] state. Used by the scheduler's per-farm policy gate.
CountActiveTasksInFarm(ctx context.Context, farmID string) (int, error)
// CountReadyTasksByQueue returns the number of leasable ready tasks for
// each queue within the given farm, keyed by queue ID: tasks in
// [TaskStatusReady] whose backoff has elapsed (RetryAfter unset or <= now)
// on an unpaused queue under a schedulable (not paused/terminal) job —
// the same eligibility predicate as [ListReadyTasks]. Queues with no such
// tasks are omitted from the map. Used by the scheduler to update the
// [SchedulerQueueDepth] Prometheus gauge and to wake lease waiters; the
// filters keep it from waking workers for work nothing can lease (tasks
// still backing off, or under an auto-parked job).
CountReadyTasksByQueue(ctx context.Context, farmID string, now time.Time) (map[string]int, error)
// ListReadyStepDemand groups the farm's leasable ready tasks by step and
// declared core reservation, under exactly [CountReadyTasksByQueue]'s
// eligibility (backoff elapsed, queue unpaused, job neither paused nor
// terminal), so summing Ready per QueueID reproduces that count. An empty
// farmID matches every farm. The rows are in no particular order. The
// grouping runs in the database; no task row is loaded.
ListReadyStepDemand(ctx context.Context, farmID string, now time.Time) ([]StepDemand, error)
// CancelJobExecution cancels a job's work in one transaction (invariant I3),
// in this statement order:
// 1. move every non-terminal task of the job (pending, ready, assigned or
// running) to [TaskStatusCanceled], clearing AssignedWorkerID and
// AssignedAt, and stamp reason as FailureReason on each task that has
// none yet, so a more specific cause recorded earlier (e.g. a
// cascade-cancel) is never clobbered;
// 2. close every running attempt of the job's tasks as
// [AttemptStatusCanceled], ended at now;
// 3. release every active claim held by an attempt of the job's tasks that
// is no longer running;
// 4. finalize every open step of the job (a pending step, or one with no
// tasks, becomes canceled; any other gets FinalizeStep's outcome), so
// after a job cancel every step is terminal;
// 5. move the job itself to [JobStatusCanceled], writing its CompletedAt
// and UpdatedAt as now, under the same guard as
// [JobStore.CancelJobStatus]: a completed, failed or already canceled
// job is left exactly as it is. A job cancel is therefore one write, and
// no second write can fail and leave the job live with all of its work
// canceled.
// It returns the tasks that were in [TaskStatusAssigned] or
// [TaskStatusRunning] when step 1 ran, each as it was before the cancel (its
// AssignedWorkerID intact), so the caller can signal the workers. Tasks
// already terminal are not modified, and a job with nothing left to cancel
// returns no tasks and no error. now stamps the tasks, the attempts, the
// claims, the steps and the job. A later [JobStore.CancelJobStatus] is an
// idempotent confirmation: nil for the job this call canceled, [ErrConflict]
// for a job that was already completed or failed.
//
// Statement order is part of the contract on Postgres: tasks are canceled
// first, then attempts closed and claims released, so a concurrent LeaseTask
// holding a task row is waited for and its attempt and claims are seen. The
// returned set is read before step 1 under the job-row anchor, which
// LeaseTask also takes (shared), so no lease commits between that read and
// step 1: a lease in flight is waited for and its task is returned as
// assigned, and a later lease waits for the cancel and finds the job
// canceled. Every task step 1 takes out of flight is therefore returned,
// and its worker can be signaled.
CancelJobExecution(ctx context.Context, jobID, reason string, now time.Time) ([]Task, error)
// CancelTaskExecution cancels one task in one transaction (invariant I3),
// in the same statement order as [TaskStore.CancelJobExecution]: move the
// task to [TaskStatusCanceled] (stamping reason only if it has none), close
// its running attempt as [AttemptStatusCanceled], then release the claims
// of its closed attempts. Unlike the job-wide cancel it leaves
// AssignedWorkerID and AssignedAt in place, so a canceled task still shows
// the worker that held it.
//
// It returns the task as it was before the cancel, and whether it was
// canceled. A task that is already terminal, whether it was when the call
// started or it completed first, is returned unchanged with false and a
// nil error: that is the "lost the race to completion" outcome, not a
// failure. An unknown task is [ErrNotFound]. The same statement-order
// contract applies on Postgres, and the returned prior task is exact for
// the same reason: it is read under the job-row anchor, which LeaseTask
// also takes (shared), so no lease commits between that read and the
// cancel's write.
CancelTaskExecution(ctx context.Context, taskID, reason string, now time.Time) (Task, bool, error)
// RetryTasks revives failed/canceled tasks so they can run again. It
// revives every task of jobID in [TaskStatusFailed] or
// [TaskStatusCanceled] — or, when taskIDs is non-nil, only those of the
// given IDs that are failed/canceled — clearing each revived task's
// genuine-failure state (FailedAttempts reset to zero, RetryAfter
// cleared). Each revived task becomes [TaskStatusReady] when its step is
// ready (a sibling still in flight; a step holding the reserved running
// status counts as ready too) and [TaskStatusPending] otherwise; the
// returned tasks carry that status. Any of their enclosing steps that are
// currently in a terminal status are reset to [StepStatusPending], and the
// job itself is reset to [JobStatusPending] when it is currently terminal
// (failed/canceled) — likewise clearing the job's FailedAttempts and
// ParkReason; a non-terminal job is left unchanged. All updates run in a
// single transaction.
//
// A task revived pending lets the caller re-run
// [openjd.ResolveDependencies] to re-gate it in dependency order; a task
// in a ready step is revived ready because nothing would release it from
// pending there. Tasks not in a terminal-retryable state are not modified.
// Returns the revived task rows, or an empty slice when nothing matched.
// The returned set is exactly the set of rows the call changed: it takes
// the job's anchor lock first, so a concurrent cancel cannot add a
// failed/canceled task between the read and the write.
RetryTasks(ctx context.Context, jobID string, taskIDs []string, now time.Time) ([]Task, error)
// CountTasksByJob returns the number of tasks for the given job keyed by
// status. Statuses with zero tasks are omitted from the returned map.
// Used by the REST layer to include aggregate task counts in job responses.
CountTasksByJob(ctx context.Context, jobID string) (map[TaskStatus]int, error)
// CommittedCores returns the sum of CPU-core reservations held by the worker
// across its assigned and running tasks: Σ COALESCE(required_cores,
// fullMachineCost). Callers pass the worker's CPUCount as fullMachineCost so
// an undeclared task (required_cores NULL) counts as the whole machine.
CommittedCores(ctx context.Context, workerID string, fullMachineCost int) (int, error)
// ListWorkerCommitments is [CommittedCores] for every worker at once: per
// worker holding any assigned or running task of the farm ("" = every
// farm), the sum of those tasks' RequiredCores and the count of tasks with
// none. For each worker, DeclaredCores + UndeclaredTasks*fullMachineCost
// equals CommittedCores(ctx, id, fullMachineCost). A worker holding
// nothing has no entry.
ListWorkerCommitments(ctx context.Context, farmID string) (map[string]WorkerCommitment, error)
// LeaseTask leases one ready task to a worker in a single transaction
// (invariants I3 and I5):
// 1. move the task ready → assigned, guarded on the same eligibility
// predicate as ListReadyTasks (queue not paused, job not paused or
// terminal, backoff elapsed);
// 2. re-check the queue's and farm's MaxConcurrentTasks against values read
// in the transaction;
// 3. insert the attempt, numbered MAX(attempt_number)+1;
// 4. for each claim, in pool-ID order, re-check the pool's max_concurrent
// as read in the transaction (a deleted pool counts as full) and insert
// the claim.
// Any outcome other than LeaseLeased writes nothing at all, so there is no
// rollback path for the caller. An unknown task is LeaseLost, not an error.
LeaseTask(ctx context.Context, req LeaseRequest) (LeaseResult, error)
// SetTaskUnschedulableReason sets (or, with an empty string, clears) the
// reason a ready task cannot be scheduled. It writes only while the task is
// [TaskStatusReady], evaluated inside the write: the scheduler's sweep reads
// its candidates before it writes, and a task a lease took in between is left
// alone rather than stamped with a reason that no longer applies. A task that
// is not ready is therefore a no-op, not an error: written reports whether
// the reason was stored, and is false (with a nil error) when the task is no
// longer ready, so a caller can skip any follow-up (an event) for a write
// that did not land. Returns ErrNotFound if id is unknown.
SetTaskUnschedulableReason(ctx context.Context, id, reason string) (written bool, err error)
// CountUnschedulableTasksByJob returns the number of tasks for the given
// job that are currently in [TaskStatusReady] with a non-empty
// UnschedulableReason. Used by the REST layer to surface an
// "unschedulable" count alongside the per-status task counts in job
// responses.
CountUnschedulableTasksByJob(ctx context.Context, jobID string) (int, error)
// FailureReasonSummary counts the job's [TaskStatusFailed] tasks that
// carry a non-empty FailureReason, grouped by reason. DominantReason is
// the most frequent reason; ties are broken by reason string ascending
// for determinism. A job with no such tasks returns the zero value and a
// nil error. Used by the REST layer to power the job-detail failure
// banner.
FailureReasonSummary(ctx context.Context, jobID string) (FailureSummary, error)
// RecordTaskFailure records a worker-reported failure of a single task
// attempt exactly once, tying the counter increment to the attempt's
// running→failed transition so an at-least-once redelivery of the same
// status message cannot double-count.
//
// In one transaction it closes the attempt as failed (setting ended_at,
// exit_code, session_id, and message) only when the attempt is still
// running; on that first close it increments both the task's and its
// enclosing job's FailedAttempts counters. When the attempt is already
// terminal (a redelivery), it does not increment and returns the
// current counters so the caller's retry/park decision is stable across
// redeliveries. exitCode nil leaves the attempt's exit_code unchanged;
// sessionID "" leaves the session_id unchanged; message "" leaves the
// attempt's message unchanged. Returns the authoritative post-call task and
// job FailedAttempts values, plus firstClose, true iff this call performed
// the running→failed close (the first delivery, so retry/park
// actions are authorized; a redelivery must first check that the attempt is
// still relevant before re-driving them). The same transaction releases
// every active usage claim the attempt holds (invariant I3), on a
// redelivery too. now stamps only the attempt's ended_at. The task's and
// job's updated_at and the released claims' released_at are server time,
// never now, because now is the worker's reported time: a skewed worker
// clock could otherwise put a release before its claim, or date the rows
// after the server-stamped writes and WebSocket events that follow them.
// Returns [ErrNotFound] if the task does not exist.
RecordTaskFailure(ctx context.Context, attemptID, taskID string, exitCode *int, sessionID, message string, now time.Time) (taskFailed, jobFailed int, firstClose bool, err error)
// RequeueTaskForRetry transitions a task back to [TaskStatusReady],
// clearing AssignedWorkerID and AssignedAt, and stamps RetryAfter so the
// task is excluded from [ListReadyTasks] until the backoff elapses.
//
// The transition is guarded: only a task currently in [TaskStatusAssigned]
// or [TaskStatusRunning] is requeued, so a stale or redelivered failure
// report can never resurrect a task that has since been canceled,
// succeeded, or already returned to ready. It reports whether the task was
// actually requeued; false (task missing, not assigned/running, or
// attemptID not the task's latest) is a legitimate no-op, not an error.
//
// It acts only while attemptID is the task's latest attempt, so a reclaim
// and a new lease landing between RecordTaskFailure and this call leave the
// new lease alone. The task's job-row anchor is taken first.
RequeueTaskForRetry(ctx context.Context, taskID, attemptID string, retryAfter, now time.Time) (bool, error)
}
TaskStore is the persistence interface for Task records.
type TemplateFormat ¶
type TemplateFormat string
TemplateFormat identifies the serialization format of Job.RawTemplate.
const ( // TemplateFormatYAML means the raw template was submitted as YAML. TemplateFormatYAML TemplateFormat = "yaml" // TemplateFormatJSON means the raw template was submitted as JSON. TemplateFormatJSON TemplateFormat = "json" )
type TimingStore ¶ added in v0.4.0
type TimingStore interface {
// JobTimings returns the inputs for each given job that exists; unknown
// IDs are absent. Empty input returns an empty map without querying.
JobTimings(ctx context.Context, jobIDs []string) (map[string]JobTiming, error)
// QueueJobTimings returns the inputs for every non-terminal job in the
// given queues. Empty input returns nil without querying.
QueueJobTimings(ctx context.Context, queueIDs []string) ([]JobTiming, error)
}
TimingStore reads the inputs of remaining-time estimates. Each call costs a fixed number of queries whatever the number of jobs.
type UsageClaim ¶
type UsageClaim struct {
ID string
PoolID string
TaskAttemptID string
// ClaimedAt is stored in the checked_out_at column.
ClaimedAt time.Time
ReleasedAt *time.Time // nil = currently active
}
UsageClaim records one active or completed claim of a UsagePool slot by a specific TaskAttempt. ReleasedAt is nil while the claim is active; it is set when the task attempt reaches a terminal state.
type UsageClaimStore ¶
type UsageClaimStore interface {
// ActiveClaimCount returns the number of claims for the given pool
// where ReleasedAt IS NULL. Used by the scheduler's admission check before
// assigning a task that requires the pool.
ActiveClaimCount(ctx context.Context, poolID string) (int, error)
}
UsageClaimStore is the persistence interface for UsageClaim records. It is separated from UsagePoolStore because the scheduler is the primary caller and only needs claim operations, not pool CRUD.
type UsagePool ¶
type UsagePool struct {
ID string
Name string
ServerHint string // e.g. "10.0.0.50:5053"; empty = not configured
MaxConcurrent int
CreatedAt time.Time
UpdatedAt time.Time
}
UsagePool represents a tracked named concurrency limit. sqi enforces concurrency limits itself by counting active UsageClaim records; it does not query any upstream server directly.
ServerHint is informational only — the address of a vendor's software server (FLEXlm/RLM), useful for diagnostics when the pool represents software slots. Leave empty for non-vendor dimensions.
type UsagePoolClaim ¶
type UsagePoolClaim struct {
// ClaimID is a caller-supplied UUID for the claim row to be created.
ClaimID string
// PoolID is the [UsagePool] to claim from.
PoolID string
// PoolName is used in error messages and debug logging only.
PoolName string
}
UsagePoolClaim describes a single usage pool slot to be claimed atomically by TaskStore.LeaseTask (see LeaseRequest.Claims).
type UsagePoolStore ¶
type UsagePoolStore interface {
// CreateUsagePool inserts a new pool. Returns [ErrConflict] if a pool
// with the same name already exists.
CreateUsagePool(ctx context.Context, pool UsagePool) (UsagePool, error)
// GetUsagePool returns the pool with the given ID, or [ErrNotFound].
GetUsagePool(ctx context.Context, id string) (UsagePool, error)
// ListUsagePools returns all pools ordered by name.
ListUsagePools(ctx context.Context) ([]UsagePool, error)
// ListUsagePoolUtilization returns all pools ordered by name, each paired with
// its current number of active claims. It computes utilization in a
// single query rather than one count per pool.
ListUsagePoolUtilization(ctx context.Context) ([]UsagePoolUtilization, error)
// UpdateUsagePool replaces the mutable fields of an existing pool and
// updates UpdatedAt. Returns [ErrNotFound] or [ErrConflict].
UpdateUsagePool(ctx context.Context, pool UsagePool) (UsagePool, error)
// DeleteUsagePool removes a pool by ID. Returns [ErrNotFound] if it
// does not exist, or [ErrConflict] while any claim, released or not,
// references the pool.
DeleteUsagePool(ctx context.Context, id string) error
}
UsagePoolStore is the persistence interface for UsagePool records.
type UsagePoolUtilization ¶
type UsagePoolUtilization struct {
UsagePool
// InUse is the number of active claims (released_at IS NULL) for the pool.
InUse int
}
UsagePoolUtilization pairs a UsagePool with its current live utilization — the number of active (unreleased) claims against it. It is returned by UsagePoolStore.ListUsagePoolUtilization so callers can render "in use vs capacity" without an N+1 fan-out of per-pool count queries.
type User ¶ added in v0.3.0
type User struct {
ID string
Username string
DisplayName string
PasswordHash string
Role string
// AuthSource names the credential backend that verifies this account:
// [AuthSourceLocal] (the stored password hash), [AuthSourceLDAP] (the
// directory), or [AuthSourceOIDC] (the OIDC provider). It is set at
// creation and never changes — UpdateUser does not write it, so an account
// cannot drift between backends.
AuthSource string
// ExternalID is the identity-provider-assigned identifier that is stable
// across renames and is never reused: the OIDC "sub" claim, or the
// directory attribute named by auth.ldap.unique_id_attr. Empty for local
// accounts.
//
// This, not Username, is what an external login matches on. Matching on a
// name lets a recycled address inherit a departed user's account and lets
// a provider-side rename orphan one, both without notice. Set at creation and
// never changed: UpdateUser does not write it.
ExternalID string
Disabled bool
CreatedAt time.Time
UpdatedAt time.Time
}
User is a local account. PasswordHash is a Go-side field only; it is never marshaled into a REST response.
type UserStore ¶ added in v0.3.0
type UserStore interface {
// CreateUser inserts a new user. Returns [ErrConflict] if the username
// (case-insensitive) already exists.
CreateUser(ctx context.Context, u User) (User, error)
// GetUser returns the user with the given ID, or [ErrNotFound].
GetUser(ctx context.Context, id string) (User, error)
// GetUserByUsername returns the user with the given username
// (case-insensitive), or [ErrNotFound].
GetUserByUsername(ctx context.Context, username string) (User, error)
// GetUserByExternalID returns the account an external identity provider
// owns, or [ErrNotFound]. authSource scopes the lookup so an OIDC "sub"
// can never collide with an LDAP objectGUID.
GetUserByExternalID(ctx context.Context, authSource, externalID string) (User, error)
// ListUsers returns all users ordered by username.
ListUsers(ctx context.Context) ([]User, error)
// UpdateUser replaces display_name, role and disabled, and bumps
// UpdatedAt. Returns [ErrNotFound]. It has no last-admin guard: it may
// demote or disable the last admin, which directory sync relies on. Use
// [UserStore.UpdateUserKeepingAdmin] where the last admin must survive.
UpdateUser(ctx context.Context, u User) (User, error)
// UpdateUserKeepingAdmin is UpdateUser with the last-admin guard applied
// inside the write (invariant I4): it returns [ErrLastAdmin], writing
// nothing, when the update would leave no enabled admin. The REST API uses
// it; directory sync uses plain UpdateUser, because the directory is
// authoritative there. Returns [ErrNotFound] for an unknown id.
UpdateUserKeepingAdmin(ctx context.Context, u User) (User, error)
// SetUserPassword replaces the stored password hash. Returns [ErrNotFound].
SetUserPassword(ctx context.Context, id, passwordHash string) error
// SetUserPasswordAndEvictSessions sets the password and deletes every
// session for the user atomically. Returns [ErrNotFound] if id is unknown.
//
// The two must not be separate calls: a self-service password change tells
// the user their other devices have been signed out, so a failure after
// the password landed would make that claim false with no way to detect
// it. Because the call is atomic, a failure means nothing changed and the
// caller can say so and retry.
SetUserPasswordAndEvictSessions(ctx context.Context, id, passwordHash string) error
// SetUserDisplayName updates only the display name, returning the updated
// record. Returns [ErrNotFound] if id is unknown.
//
// Distinct from UpdateUser, which writes display_name, role, and disabled
// together: a self-service caller may only touch the display name, and a
// read-modify-write through UpdateUser would race with a concurrent admin
// role or disabled change and silently revert it.
SetUserDisplayName(ctx context.Context, id, displayName string) (User, error)
// DeleteUser removes a user by ID (cascading their sessions). Returns
// [ErrNotFound]. Refused with [ErrLastAdmin], deleting nothing, when the
// user is the last enabled admin; the guard is evaluated inside the DELETE
// (invariant I4).
DeleteUser(ctx context.Context, id string) error
// CountUsers returns the number of users (for the bootstrap gate).
CountUsers(ctx context.Context) (int, error)
}
UserStore is the persistence interface for User records.
type Worker ¶
type Worker struct {
ID string
FarmID string
QueueID string // empty = no queue affinity
// Name is the worker's human-readable display label (the worker.name
// config field, default the hostname). Distinguishes multiple workers
// running on one host in the UI; may be empty, in which case callers fall
// back to Hostname.
Name string
Hostname string
IPAddress string
ComputeLocation string
OS string
OSVersion string
// Arch is the worker's CPU architecture as the worker reports it, which is
// runtime.GOARCH ("amd64", "arm64", ...). It backs the reserved OpenJD
// attr.worker.cpu.arch host requirement, whose accepted values are the
// specification's tokens ("x86_64", "arm64") rather than Go's; see
// scheduler.cpuArch for the translation, which has the same shape as the
// os.family darwin/macos one.
//
// Empty when the worker did not send it. An empty value never satisfies an
// attr.worker.cpu.arch requirement.
Arch string
// Version is the sqi-worker build version the worker self-reports at
// registration (the worker binary's internal/version.Version). May be
// empty.
Version string
// InstanceID identifies the worker process that last registered. It
// changes when the worker restarts and is empty for a worker that does not
// send one.
InstanceID string
// RegistrationBrokerAt is the message broker's stream timestamp of the
// registration that wrote this row. Nil when the registration carried none.
// It orders registrations without reference to any worker's clock:
// [WorkerStore.RegisterWorker] ignores one the broker stamped earlier than
// the stored one.
RegistrationBrokerAt *time.Time
// HeartbeatBrokerAt is the message broker's stream timestamp of the
// heartbeat [WorkerStore.UpdateWorkerHeartbeat] last recorded. Nil until a
// heartbeat carrying one is recorded. It orders heartbeats as
// RegistrationBrokerAt orders registrations; RegisterWorker never writes
// it.
HeartbeatBrokerAt *time.Time
CPUCount int
RAMMb int
GPUInfo GPUInfo
Tags map[string]string // arbitrary capability tags
// ExprLimits holds the worker's self-reported OpenJD EXPR evaluation caps.
// Zero-valued when the worker advertised none; see [WorkerExprLimits] for
// what the server does with them.
ExprLimits WorkerExprLimits
// Extensions lists the worker-enforced OpenJD extensions (see
// openjd.WorkerEnforcedExtensions) the worker advertised at registration.
// Empty for a worker that enforces none; the scheduler withholds a job
// declaring one from such a worker (internal/scheduler's workerExtensionBlock).
Extensions []string
// Status is the worker's liveness: [WorkerStatusOnline] or
// [WorkerStatusOffline]. See [WorkerStatus].
Status WorkerStatus
// Disabled is true while an operator has the worker disabled. It is
// independent of Status: a disabled worker still goes online and offline,
// and stays disabled through both.
Disabled bool
// CapacityGroupID is the capacity group the worker belongs to, or empty
// for none. Only [WorkerStore.SetWorkerCapacityGroup] and
// [WorkerStore.DeleteEphemeralWorker] write it; a registration never does.
CapacityGroupID string
// Ephemeral marks a member the server created for a group and removes
// when it retires; it is meaningful only with a CapacityGroupID. A member
// that is not ephemeral is a named machine and outlives its time offline.
Ephemeral bool
// PowerState is where the worker is in the capacity group power cycle; it
// is never empty on a stored row. A registration moves a waking, asleep or
// wake-failed worker to [PowerAwake] and leaves a retiring one retiring;
// [WorkerStore.SetWorkerCapacityGroup] with an empty group resets it.
// [PowerRetiring] and [PowerAsleep] refuse new leases ([TaskStore.LeaseTask]).
PowerState PowerState
// PowerStateAt is when PowerState last changed, or nil if it has not
// changed since the row was created.
PowerStateAt *time.Time
// PowerReason says why the state is what it is, when that is worth
// saying: why a wake failed, or what idle period retired the worker.
PowerReason string
// Interfaces are the network interfaces the worker reported at
// registration, which a wake-on-LAN packet is addressed with.
Interfaces []NetInterface
// CloudInstanceID is the cloud provider's identifier for the machine the
// worker reported at registration, or empty.
CloudInstanceID string
LastHeartbeatAt *time.Time
// RegisteredAt is when the worker first registered. A re-registration
// keeps it, so it says nothing about the process running now.
RegisteredAt time.Time
// StartedAt is when the worker's current process started. A first
// registration and one with a new instance ID set it to the time of the
// write; a reconnect of the same process and a registration that sends no
// instance ID keep it. Heartbeats then refine it from the uptime the
// worker reports, moving it only earlier
// ([WorkerStore.UpdateWorkerHeartbeat]). Nil until either has recorded
// one. The value passed to RegisterWorker is ignored.
StartedAt *time.Time
UpdatedAt time.Time
}
Worker represents a registered sqi-worker agent. Workers self-report their capabilities at registration; the server persists the reported values and uses them for task matching.
func (Worker) EffectivePowerState ¶ added in v0.4.0
func (w Worker) EffectivePowerState() PowerState
EffectivePowerState is the worker's power state. An empty one, which no stored row holds, reads as PowerAwake, the state of every worker no capacity group manages.
func (Worker) EffectiveStatus ¶ added in v0.4.0
func (w Worker) EffectiveStatus() WorkerStatus
EffectiveStatus is the status the API and the worker gauge report: WorkerStatusDisabled while the worker is disabled, otherwise its liveness.
func (Worker) HasWakeAddress ¶ added in v0.4.0
HasWakeAddress reports whether a wake-on-LAN packet can reach the worker: one of its interfaces is NetInterface.WakeAddressable.
func (Worker) MayTakeNewWork ¶ added in v0.4.0
MayTakeNewWork reports whether the worker may be leased new work: it is not disabled, and not a capacity-group member that is retiring or asleep. The SQL stores' lease guard restates this rule, since SQL cannot call Go.
func (Worker) Removable ¶ added in v0.4.0
Removable reports whether the worker may be hard-deleted. This is the one statement of the removability rule: a worker is removable when it is offline, disabled or not. A disabled worker that is still online is a paused machine and is not removable.
WorkerStore.DeleteWorkerIfRemovable applies this rule inside its write; the SQL statement restates it, since SQL cannot call Go, so a change here must be made there too. The API's pre-check and the fake call this method. The store adds one condition a Worker value alone cannot see: no task may be assigned to or running on the worker, so a true here does not guarantee the delete succeeds.
type WorkerCommitment ¶ added in v0.4.0
WorkerCommitment is the CPU a worker holds across its assigned and running tasks, as TaskStore.ListWorkerCommitments reports it: the declared reservations summed, and the tasks that declared none, each of which costs the whole machine.
type WorkerCredential ¶ added in v0.4.0
type WorkerCredential struct {
ID string
WorkerID string
PublicKey string
Name string
EnrolledAt time.Time
LastSeenAt *time.Time // nil = never seen since enrollment
RevokedAt *time.Time // nil = active
// CapacityGroupID is the capacity group the credential enrolled into with a
// group join token, or "" for an ordinary credential. Like WorkerID it is
// not a foreign key, so the credential outlives a deleted group.
CapacityGroupID string
}
WorkerCredential binds a worker's self-chosen ID to an Ed25519 nkey public key, issued during enrollment and presented on every broker connection thereafter. WorkerID is not a foreign key to a worker row: a credential is issued before the worker has registered, and on auth-off farms worker rows exist with no credential at all.
type WorkerCredentialStore ¶ added in v0.4.0
type WorkerCredentialStore interface {
// CreateWorkerCredential inserts a new credential. Returns [ErrConflict]
// on a worker-id, public-key, or id collision.
CreateWorkerCredential(ctx context.Context, c WorkerCredential) (WorkerCredential, error)
// ListActiveWorkerCredentials returns every credential with a nil
// RevokedAt, the set "sqi-server worker list" shows. A revoked credential
// never appears in the result.
ListActiveWorkerCredentials(ctx context.Context) ([]WorkerCredential, error)
// GetActiveWorkerCredentialByPublicKey returns the credential whose
// PublicKey is publicKey and whose RevokedAt is nil, or [ErrNotFound] if
// no active credential has that key. A revoked key and an unknown key
// both return [ErrNotFound]: either means "do not authenticate".
GetActiveWorkerCredentialByPublicKey(ctx context.Context, publicKey string) (WorkerCredential, error)
// RevokeWorkerCredential soft-revokes the credential for workerID.
// Returns [ErrNotFound] if no such worker has a credential.
RevokeWorkerCredential(ctx context.Context, workerID string, at time.Time) error
// TouchWorkerCredential sets LastSeenAt on workerID's active credential and
// returns that credential as stored after the write. Returns [ErrNotFound]
// if the worker has no active credential. Callers that treat "seen" as
// best-effort bookkeeping should not fail on that error. Registration also
// reads the returned credential's CapacityGroupID, so it learns a worker's
// enrolled group without a second query.
TouchWorkerCredential(ctx context.Context, workerID string, at time.Time) (WorkerCredential, error)
// CreateWorkerJoinToken inserts a new join token. Returns [ErrConflict]
// on a token-hash or id collision.
CreateWorkerJoinToken(ctx context.Context, t WorkerJoinToken) (WorkerJoinToken, error)
// GetWorkerJoinTokenByHash returns the token for hash, or [ErrNotFound] if
// no such token exists.
GetWorkerJoinTokenByHash(ctx context.Context, hash string) (WorkerJoinToken, error)
// MarkWorkerJoinTokenUsed sets UsedAt. Returns [ErrNotFound] if id is
// unknown.
MarkWorkerJoinTokenUsed(ctx context.Context, id string, at time.Time) error
// ListCapacityGroupTokens returns every join token bound to the group,
// revoked and expired ones included, newest first. An unknown group has
// none.
ListCapacityGroupTokens(ctx context.Context, groupID string) ([]WorkerJoinToken, error)
// RevokeCapacityGroupToken marks the join token id, bound to the capacity
// group groupID, revoked at the given time. Returns [ErrNotFound] if id is
// unknown or not that group's; revoking a revoked token is not an error
// and keeps the first revocation time.
RevokeCapacityGroupToken(ctx context.Context, groupID, id string, at time.Time) error
// RedeemWorkerJoinToken atomically claims the single-use join token
// identified by hash and creates cred, in one transaction. It succeeds
// only for a token that exists, has not been redeemed or revoked, and has
// not expired at now; every other case, including a token another request
// claimed a moment earlier, returns [ErrNotFound], and cred is not
// created. Returns [ErrConflict] if cred cannot be created (a worker ID
// already bound to an active credential, or a public key already
// enrolled to any worker); the whole transaction then rolls back, so the
// token is not consumed and remains redeemable.
//
// The token claim and the credential creation must be one transaction.
// Committing the claim before the credential is known to be creatable
// would consume a single-use token on a request that is then rejected as
// a conflict, and the operator would have to issue a new one. Within the
// claim itself, check and set must be a single statement: reading the
// token, inspecting UsedAt and marking it used separately is a
// check-then-act race, where two concurrent enrollments presenting the
// same single-use token both observe UsedAt as nil and both succeed.
RedeemWorkerJoinToken(ctx context.Context, hash string, now time.Time, cred WorkerCredential) (WorkerCredential, error)
}
WorkerCredentialStore is the persistence interface for WorkerCredential and WorkerJoinToken records.
type WorkerExprLimits ¶ added in v0.3.0
type WorkerExprLimits struct {
// OperationLimit is the worker's §1.3.10 operation budget for one
// expression evaluation (expr.operation_limit).
OperationLimit int64 `json:"operation_limit,omitempty"`
// MemoryLimit is the worker's §1.3.9 live-byte budget for one expression
// evaluation (expr.memory_limit).
MemoryLimit int64 `json:"memory_limit,omitempty"`
// AssignmentPositions is how many expression positions the worker will
// resolve for one assignment (expr.assignment_positions).
AssignmentPositions int64 `json:"assignment_positions,omitempty"`
// AssignmentRetainedBytes is how many bytes let: bindings may retain
// across one assignment (expr.assignment_retained_bytes).
AssignmentRetainedBytes int64 `json:"assignment_retained_bytes,omitempty"`
// LetRetainedBytes is how many bytes one task-time symbol table may hold
// live (expr.let_retained_bytes), measured across the whole table rather
// than only its let-bound names.
LetRetainedBytes int64 `json:"let_retained_bytes,omitempty"`
}
WorkerExprLimits holds the OpenJD EXPR evaluation caps a worker self-reports at registration: its expr.* worker-configuration section. The server persists them so the scheduler can refuse to dispatch an EXPR job to a worker that cannot run what the server accepted.
Expressions in an EXPR template are metered twice: against the server's openjd.expr_* limits when the template is submitted, and again against the worker's expr.* limits when a task runs. If a worker's cap is tighter than the server's, the job is accepted and persisted and then every task of it fails on that host, naming a budget the submitter never saw. Both sides are operator configuration, so "worker cap >= server cap" can be broken by a YAML file; these fields let the server see it.
Every value is self-reported, like CPUCount, RAMMb and Tags. It states what that worker will enforce, not a promise the server can verify.
A zero field means "not advertised". A worker that reports limits always reports a real value (its config layer rejects 0), so a zero comes from a worker binary that does not advertise them. The scheduler reads it as the compiled-in defaults; see internal/scheduler's legacyWorkerExprCaps.
All five of the worker's expr.* keys are carried. The server has no per-table counterpart to LetRetainedBytes, yet a worker at that key's floor rejects, on every task, a let: block the server accepted under a raised openjd.expr_template_retained_bytes. The server's limit bounds the same values at a wider scope, so it serves as the comparison; see internal/scheduler's exprCapShortfall for the comparison and for what it cannot promise.
type WorkerJoinToken ¶ added in v0.4.0
type WorkerJoinToken struct {
ID string
TokenHash string // SHA-256 of the raw token; Go-side only
Prefix string // leading chars of the raw token, for list identification
Name string
ExpiresAt time.Time
UsedAt *time.Time // nil = not yet redeemed
CreatedBy string
CreatedAt time.Time
// CapacityGroupID binds the token to a capacity group: every worker that
// enrolls with it joins that group, and the enrollment handler lets it be
// redeemed any number of times. "" is an ordinary token. A token is
// deleted with its group.
CapacityGroupID string
// RevokedAt is when an operator revoked the token; nil = not revoked. A
// revoked token enrolls nobody.
RevokedAt *time.Time
}
WorkerJoinToken is a time-limited token an operator issues so a worker can enroll and receive a WorkerCredential. Only TokenHash is stored; the raw token is shown to the operator once, at creation.
type WorkerSortField ¶
type WorkerSortField string
WorkerSortField is a column by which WorkerStore.ListWorkers results can be ordered.
const ( // WorkerSortByHostname orders workers alphabetically by hostname (default). WorkerSortByHostname WorkerSortField = "hostname" // WorkerSortByStatus orders workers alphabetically by status string. WorkerSortByStatus WorkerSortField = "status" // WorkerSortByRegisteredAt orders workers by registration time. WorkerSortByRegisteredAt WorkerSortField = "registered_at" // WorkerSortByLastHeartbeatAt orders workers by most recent heartbeat time. WorkerSortByLastHeartbeatAt WorkerSortField = "last_heartbeat_at" )
type WorkerStatus ¶
type WorkerStatus string
WorkerStatus is the operational state of a worker as known to the server.
A stored worker's Worker.Status is its liveness, online or offline, and is written by registration, deregistration and the heartbeat sweep. Whether an operator has disabled it is the separate Worker.Disabled flag, written only by WorkerStore.SetWorkerDisabled. WorkerStatusDisabled is the status the API, the status filter and the worker gauge report for a disabled worker (Worker.EffectiveStatus); it is never stored as liveness.
const ( // WorkerStatusOnline means the worker is connected and accepting tasks. WorkerStatusOnline WorkerStatus = "online" // WorkerStatusOffline means the worker has not sent a heartbeat within the // configured timeout and is presumed unreachable. WorkerStatusOffline WorkerStatus = "offline" // WorkerStatusDisabled is the effective status of a worker an operator has // administratively paused; it will not receive new task assignments until // re-enabled. WorkerStatusDisabled WorkerStatus = "disabled" )
type WorkerStore ¶
type WorkerStore interface {
// RegisterWorker inserts or replaces the worker record for the given ID.
// Called by the server when a worker sends its registration message. If the
// worker ID already exists its record is updated in full, except that an
// empty InstanceID keeps the stored one and Disabled, CapacityGroupID,
// Ephemeral, PowerReason and PowerStateAt are never written from the
// worker: a disabled worker stays disabled, a new one is enabled, and a
// worker keeps its group membership. Interfaces and CloudInstanceID are
// written from the registration, except that an empty one keeps the stored
// value, so a failed read on the worker never erases them. PowerState is
// decided by the store in the same statement: a waking, asleep or
// wake-failed worker becomes awake (PowerStateAt is now and PowerReason is
// cleared), a retiring worker stays retiring, and a new worker is awake.
// When the stored InstanceID is non-empty and differs from a non-empty
// incoming one, the previous worker process is gone: in the same
// transaction its assigned and running tasks are reclaimed as
// [WorkerStore.OfflineWorker] reclaims them (attempts closed as failed with
// [FailureReasonWorkerRestarted], claims released, tasks ready) and
// returned as they are after the reset.
//
// A registration whose RegistrationBrokerAt is earlier than the stored one
// is a late redelivery of a message the broker stamped before the one that
// wrote the row, typically from a process since replaced. It writes nothing
// and reclaims nothing: it returns the stored worker with
// [ErrStaleRegistration]. Equal timestamps are not stale, and a missing
// timestamp on either side is never stale. An incoming nil
// RegistrationBrokerAt keeps the stored one.
//
// The [Registration] says what else the write did: the tasks it
// reclaimed, and the power state it woke the worker from.
RegisterWorker(ctx context.Context, worker Worker) (Worker, Registration, error)
// GetWorker returns the worker with the given ID, or [ErrNotFound].
GetWorker(ctx context.Context, id string) (Worker, error)
// ListWorkers returns a paginated, filtered, and sorted page of workers
// matching opts. Call [Pagination.Validate] on opts.Pagination before
// passing it to ensure sensible defaults are applied.
ListWorkers(ctx context.Context, opts ListWorkersOptions) (Page[Worker], error)
// SetWorkerDisabled sets or clears the worker's [Worker.Disabled] flag,
// updates UpdatedAt and returns the stored worker. It is the admin
// enable/disable path and the only writer of the flag; it never changes
// the worker's liveness. Setting the value the flag already holds is not an
// error. Returns [ErrNotFound] if the worker does not exist.
SetWorkerDisabled(ctx context.Context, id string, disabled bool) (Worker, error)
// SetWorkerCapacityGroup makes the worker a member of the capacity group
// groupID, marked ephemeral or not, updates UpdatedAt and returns the
// stored worker. An empty groupID clears the membership and Ephemeral
// (ephemeral is then ignored). Setting the group the worker is already in
// is not an error and rewrites Ephemeral. Returns [ErrNotFound] for an
// unknown worker or group, and [ErrConflict] when the worker is already in
// a different group (the caller clears the old membership first) or when
// the group was deleted while the write ran: the group is not locked, so a
// concurrent delete surfaces as the membership's reference failing rather
// than as ErrNotFound.
SetWorkerCapacityGroup(ctx context.Context, workerID, groupID string, ephemeral bool) (Worker, error)
// ListCapacityGroupMembers returns the workers that belong to the group,
// ordered by hostname then ID. An unknown group has no members.
ListCapacityGroupMembers(ctx context.Context, groupID string) ([]Worker, error)
// DeleteEphemeralWorker deletes the worker only while it is ephemeral,
// offline and holds no assigned or running task, and revokes its active
// credential at now in the same transaction. It returns the deleted row and
// true. Otherwise (including an unknown worker) it writes nothing and
// returns (Worker{}, false, nil).
DeleteEphemeralWorker(ctx context.Context, id string, now time.Time) (Worker, bool, error)
// DeleteVanishedEphemeralWorker is [WorkerStore.DeleteEphemeralWorker] for
// a member that went away without saying so: it also requires the worker
// not disabled and its LastHeartbeatAt recorded and before cutoff, all
// judged in the delete itself, so a member that heartbeated, came back or
// was put on hold since the caller read it is kept. A worker with no
// recorded heartbeat is never deleted.
DeleteVanishedEphemeralWorker(ctx context.Context, id string, cutoff, now time.Time) (Worker, bool, error)
// UpdateWorkerHeartbeat records at as the given worker's LastHeartbeatAt,
// the time the liveness sweep judges against the server's clock. The
// scheduler passes the broker's stream timestamp of the heartbeat, or its
// own receipt time when there is none, never the worker's clock. brokerAt
// is that stream timestamp, and it alone orders heartbeats: one the broker
// stamped earlier than the recorded HeartbeatBrokerAt (a late redelivery)
// is accepted and ignored, not an error, while one stamped no earlier is
// recorded whatever at says. A nil brokerAt is recorded unconditionally
// and keeps the stored HeartbeatBrokerAt.
// The outcome reports whether the heartbeat was recorded and, when it was,
// the worker's status and power state as the write left them, so the
// caller can tell a live worker the sweep marked offline without a second
// read. An ignored heartbeat returns Recorded false and no error.
// This is a hot path; implementations should use a single UPDATE
// statement, reading only to tell an unknown worker from an ignored
// heartbeat. Returns [ErrNotFound] if the worker does not exist.
//
// startedAt, when not nil, is the caller's estimate of when the worker's
// process started (the broker stamp less the uptime the worker reports).
// A recorded heartbeat lowers StartedAt to it when it is earlier, or sets
// it when StartedAt is nil, so the earliest estimate wins: a heartbeat
// that waited in a buffer before it was sent estimates late and changes
// nothing. It is ignored when brokerAt is nil, and when brokerAt is
// earlier than the worker's RegistrationBrokerAt: such a heartbeat may
// come from the process a restart replaced, whose estimate would undo the
// restart's StartedAt.
UpdateWorkerHeartbeat(ctx context.Context, id string, at time.Time, brokerAt, startedAt *time.Time) (HeartbeatOutcome, error)
// ListStaleWorkers returns workers whose last heartbeat is older than
// before and whose status is [WorkerStatusOnline], disabled or not (a dead
// disabled worker is swept like any other). Used by the
// heartbeat timeout sweep to find workers to mark offline. The result is a
// candidate list only; [WorkerStore.OfflineStaleWorker] re-checks the guard
// inside its own write.
ListStaleWorkers(ctx context.Context, before time.Time) ([]Worker, error)
// OfflineStaleWorker takes a worker offline if, and only if, it is still
// stale: the write is guarded by status = [WorkerStatusOnline] AND a
// last_heartbeat_at strictly older than cutoff, so a heartbeat or a
// re-registration that landed after the caller listed its candidates keeps
// the worker online and its tasks running (invariant I1). Disabled does not
// enter the guard and is not written: a disabled worker goes offline like
// any other and stays disabled.
//
// When the guard matches, the same transaction closes the running attempts
// of the worker's [TaskStatusAssigned] and [TaskStatusRunning] tasks as
// [AttemptStatusFailed] with the message [FailureReasonWorkerOffline],
// releases the claims of those attempts (invariant I3), and returns the
// tasks to [TaskStatusReady] with their worker cleared. It returns exactly
// the tasks it reclaimed (invariant I2), as they are after the reset, and
// true. When the guard does not match (the worker is unknown, is not
// online, or has a heartbeat at or after cutoff) nothing is written and it
// returns (nil, false, nil). A worker with no recorded heartbeat is never stale.
//
// now stamps the worker's and the reclaimed tasks' updated_at, the closed
// attempts' ended_at and the released claims' released_at.
//
// Anchor rows and statement order: the worker row first, then each affected
// job row sorted by id; within the transaction the worker is marked
// offline, the tasks are reclaimed, and only then are their attempts closed
// and their claims released. See the shared SQL implementation
// (internal/store/sqlstore) for the exact order.
OfflineStaleWorker(ctx context.Context, id string, cutoff, now time.Time) ([]Task, bool, error)
// OfflineWorker is the sibling of [WorkerStore.OfflineStaleWorker] for a
// graceful deregister: the worker is taken offline whatever its heartbeat
// (a disabled worker stays disabled), and its in-flight tasks are reclaimed
// exactly as OfflineStaleWorker reclaims them (attempts closed, claims
// released, tasks back to ready). It returns the reclaimed tasks as they
// are after the reset and true, or [ErrNotFound] for an unknown worker. A
// worker that is already offline is not an error: it has nothing left to
// reclaim and the call returns no tasks.
//
// instanceID is the deregistering process's instance ID. When it and the
// stored [Worker.InstanceID] are both non-empty and differ, the row belongs
// to a newer process of the same worker, whose registration has already
// landed: the deregister is from a superseded process (a late or redelivered
// message), and nothing is written; the call returns (nil, false, nil). The
// check is part of the guarded write (invariant I1). An empty ID on either
// side proves nothing, and the worker is taken offline.
OfflineWorker(ctx context.Context, id, instanceID string, now time.Time) ([]Task, bool, error)
// CountIdleWorkers returns the number of online, enabled workers in the
// given farm that have no task currently in [TaskStatusAssigned] or
// [TaskStatusRunning] state. An empty farmID matches all farms.
// Used by the scheduler to update the [SchedulerIdleWorkers] Prometheus
// gauge.
CountIdleWorkers(ctx context.Context, farmID string) (int, error)
// DeleteWorkerIfRemovable deletes the worker only while it is removable
// ([Worker.Removable]: offline, disabled or not), and only while no task is
// assigned to or running on it. The rule is evaluated inside the DELETE
// (invariant I1), so a worker that came back between the caller's read and
// this write keeps its row. Returns [ErrConflict] when the worker exists
// but is not removable and [ErrNotFound] when it does not exist. Task and
// task-attempt rows that reference the worker by ID are left intact (the ID
// lives on as a snapshot).
DeleteWorkerIfRemovable(ctx context.Context, id string) error
// DeleteOfflineWorkersBefore hard-deletes every enabled worker in
// [WorkerStatusOffline] whose LastHeartbeatAt is strictly before cutoff,
// and returns the deleted records. Online workers and disabled ones are
// never touched: a disabled worker stays until an operator removes it.
// Members of a capacity group are kept too: a named machine stays until
// an operator removes it, and an ephemeral member is the capacity sweep's
// to delete, since that deletion also revokes its credential and this one
// does not. Used by the scheduler's offline-retention sweep to bound the
// growth of the worker table.
DeleteOfflineWorkersBefore(ctx context.Context, cutoff time.Time) ([]Worker, error)
}
WorkerStore is the persistence interface for Worker records.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package backend opens the state store the configuration names, so the server and the CLIs do not each switch on the driver.
|
Package backend opens the state store the configuration names, so the server and the CLIs do not each switch on the driver. |
|
Package fake provides an in-memory implementation of store.Store for unit tests that must avoid touching the filesystem.
|
Package fake provides an in-memory implementation of store.Store for unit tests that must avoid touching the filesystem. |
|
Package migrations embeds the SQL migration files goose uses to manage the sqi-server state store schema, one set per driver: FS for SQLite (this directory, from 00001) and PostgresFS for PostgreSQL (the postgres subdirectory, from 00037_baseline.sql).
|
Package migrations embeds the SQL migration files goose uses to manage the sqi-server state store schema, one set per driver: FS for SQLite (this directory, from 00001) and PostgresFS for PostgreSQL (the postgres subdirectory, from 00037_baseline.sql). |
|
Package postgres is the PostgreSQL state store: the shared SQL store in internal/store/sqlstore over pgx, with the locking and retry a database with concurrent writers needs.
|
Package postgres is the PostgreSQL state store: the shared SQL store in internal/store/sqlstore over pgx, with the locking and retry a database with concurrent writers needs. |
|
Package schemainfo reads the shape of a migrated sqi database — tables, columns, primary keys, foreign-key targets — from either backend's catalog, for tools that must follow the live schema rather than a hard-coded list (storecopy).
|
Package schemainfo reads the shape of a migrated sqi database — tables, columns, primary keys, foreign-key targets — from either backend's catalog, for tools that must follow the live schema rather than a hard-coded list (storecopy). |
|
Package sqlite provides the SQLite store.Store: it opens the database, applies its PRAGMAs, runs migrations, and builds the shared SQL store (internal/store/sqlstore) over its pools with the SQLite dialect.
|
Package sqlite provides the SQLite store.Store: it opens the database, applies its PRAGMAs, runs migrations, and builds the shared SQL store (internal/store/sqlstore) over its pools with the SQLite dialect. |
|
Package sqlstore is the SQL implementation of store.Store shared by every database the store runs on.
|
Package sqlstore is the SQL implementation of store.Store shared by every database the store runs on. |
|
Package storecopy copies a stopped farm's SQLite database into an empty PostgreSQL database, verbatim, in one PostgreSQL transaction, and verifies every table by row count and digest before committing.
|
Package storecopy copies a stopped farm's SQLite database into an empty PostgreSQL database, verbatim, in one PostgreSQL transaction, and verifies every table by row count and digest before committing. |
|
Package storetest builds store state for tests through the production write path: CreateJobSubmission for rows, LeaseTask and StartTaskAttempt for work in flight, CompleteTaskAttempt and RecordTaskFailure for work that ended.
|
Package storetest builds store state for tests through the production write path: CreateJobSubmission for rows, LeaseTask and StartTaskAttempt for work in flight, CompleteTaskAttempt and RecordTaskFailure for work that ended. |