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-backed implementation implements Store in full. The in-memory fake also implements Store in full, used by unit tests that must not touch the filesystem.
JSON columns ¶
Fields that are stored as JSON in SQLite (e.g. Worker.Tags, Task.Parameters) are typed as Go maps or slices. The SQLite implementation is responsible for marshaling and unmarshaling; 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 MatchesSearch(query string, fields ...string) bool
- func RunAsComboValid(user, group *string) bool
- func SearchTerms(query string) []string
- func ValidateTaskTransition(from, to TaskStatus) error
- type APIKey
- type APIKeyStore
- type AttemptStatus
- type AuditEntry
- type AuditStore
- type ComputeLocation
- type ComputeLocationStore
- type DeletedJob
- type FailureSummary
- type Farm
- type FarmStore
- type GPUInfo
- type Job
- type JobSortField
- type JobStatus
- type JobStore
- type JobSubmission
- type ListJobsOptions
- type ListQueuesOptions
- type ListTasksOptions
- type ListWorkersOptions
- type LogStream
- type Page
- type Pagination
- type Product
- type ProductStore
- type Queue
- type QueueSortField
- type QueueStore
- type Session
- type SessionStore
- type SortDir
- type Source
- type Step
- type StepAmountRequirement
- type StepAttributeRequirement
- type StepHostRequirements
- type StepStatus
- type StepStore
- type StorageLocation
- type StorageLocationStore
- type StorageLocationType
- type Store
- type Task
- type TaskAttempt
- type TaskAttemptStore
- type TaskLog
- type TaskLogStore
- type TaskSortField
- type TaskStatus
- type TaskStore
- type TemplateFormat
- type UsageClaim
- type UsageClaimStore
- type UsagePool
- type UsagePoolClaim
- type UsagePoolStore
- type UsagePoolUtilization
- type User
- type UserStore
- type Worker
- type WorkerExprLimits
- type WorkerSortField
- type WorkerStatus
- type WorkerStore
Constants ¶
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 // this are clamped rather than rejected, matching the behavior of most // REST pagination conventions. 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" )
Server-originated failure/termination reasons. TaskStore.FailureReasonSummary groups by exact string, so every producer of these annotations (scheduler, SQLite store, fake store) must share these values — a wording tweak in one producer would otherwise 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.
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 ErrInvalidPagination = errors.New("store: invalid pagination parameters")
ErrInvalidPagination is returned when Pagination contains values that cannot be corrected by clamping (reserved for future use).
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 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 only gates isolation on RunAsUser (internal/scheduler/ assign.go builds protocol.IsolationSpec only when queue.RunAsUser is set, folding RunAsGroup in only as a supplement) — so a group with no user selects no OS identity at all and is silently ignored, giving an operator no isolation and no warning that their configuration did nothing. Checking the resolved values (not the raw request) matters for UpdateQueue: a PUT that clears run_as_user while an existing run_as_group is preserved, or that sets run_as_group while run_as_user is preserved at nil, must be rejected exactly like setting both in the same request.
var ErrUsageAtCapacity = errors.New("store: usage pool at capacity")
ErrUsageAtCapacity is returned by UsageClaimStore.TryClaimSlots when one or more required usage pools are saturated (active claims have reached MaxConcurrent). The task should remain ready for reassignment on the next scheduler tick.
Functions ¶
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 SQLite LIKE search, kept in the shared package so both stay in lockstep.
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 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 mirrors the web UI's client-side filter (utils/filterBySearch.ts) so search behaves identically everywhere.
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.
This lives in package store rather than package openjd because the store is what enforces it on every write; openjd imports store, so the store cannot import openjd. There is no openjd counterpart to call instead: package openjd owns only the STEP machine (github.com/uberware/sqi/internal/openjd.ValidateStepTransition), with its own separate ErrInvalidTransition sentinel — match errors against the sentinel from the same package as the machine you called, or errors.Is silently stops matching.
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)
// GetAPIKeyByTokenHash returns the active key for tokenHash, or
// [ErrNotFound] if it is missing, revoked, or expired at now.
GetAPIKeyByTokenHash(ctx context.Context, tokenHash string, now time.Time) (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 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" )
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
// ListAuditEntries returns all audit entries for the given entity,
// ordered by CreatedAt ascending. Pass empty strings to list all entries
// (for administrative views).
ListAuditEntries(ctx context.Context, entityType, entityID string) ([]AuditEntry, error)
}
AuditStore is the persistence interface for AuditEntry records. The audit log is append-only; there are no update or delete methods.
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 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. The caller is responsible for ensuring no queues or workers
// reference the farm before deleting it.
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.
Phase 1 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 — workers with heterogeneous GPUs should report the lowest common VRAM to avoid over-scheduling. A []GPUDevice slice should replace this struct when heterogeneous per-device tracking is required.
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 jobs with no declared parameters or submitted before
// the parameters-persistence migration (back-compat: scheduler falls back
// to 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 ON PURPOSE. Three states have to be
// distinguishable by the scheduler — not recorded, recorded-empty,
// recorded-non-empty — and "not recorded" is NOT "declares nothing": for
// the first it must fall back to scanning the raw template, and for the
// second it must not. Leaning on nil-versus-empty to carry that difference
// puts the whole distinction on a property Go erases at every len() check,
// every append and every clone; a *[]string carries it but makes every read
// site dereference. A bool is checked explicitly or the compiler does not
// care, which is the property wanted here.
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
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, for which declared is always false and means nothing. Reading it as "declares nothing" is the mistake the two-value return exists to make hard.
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 {
// CreateJob inserts a new job with all fields populated by the caller.
//
// It has NO production callers. Submission was its only one and now goes
// through [JobStore.CreateJobSubmission]; the same is true of
// [JobStore.CreateJobDependencies], [StepStore.CreateStep] and
// [TaskStore.CreateTask]. All four are test-only API surface kept for
// fixture construction, with two consequences worth knowing:
//
// - No production test exercises them, so they can drift from the path
// production actually takes without anything going red. The fake's
// CreateStep and CreateTask already differ: they do not stamp
// CreatedAt/UpdatedAt, while its CreateJobSubmission does (per row, so
// tasks within a step get distinct created_at values — SQLite relies on
// that for the ready-task ordering tiebreaker and ListTasks paging).
// A fixture built from these creators therefore has zero timestamps
// where a real submission has meaningful ones.
// - A behavior change made here does not reach production. Change
// CreateJobSubmission too, or the change is cosmetic.
CreateJob(ctx context.Context, job Job) (Job, error)
// CreateJobSubmission atomically creates a job, its dependency edges, its
// steps and its tasks. On ANY error nothing is written.
//
// It exists because creating those rows through separate calls left two
// defects with no cure at the call site: a failed submission stranded a
// pending job that no sweep reaps, and a submission whose write failed
// after some steps were persisted produced a job whose missing steps made
// checkJobCompletion — which derives job status from the steps that exist —
// report it completed. The second needs a STORE failure specifically: an
// expansion failure left the step row too, because the old code wrote it
// before expanding its tasks, so that case hung pending rather than
// completing. Both are properties of partial creation, so both end here.
//
// The returned JobSubmission carries the rows as stored, the way
// [JobStore.CreateJob], [StepStore.CreateStep] and [TaskStore.CreateTask]
// each return theirs. 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.
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)
// CreateJobDependencies records that jobID waits on each ID in upstreamIDs
// (whole-job cross-job dependencies). Duplicate edges are ignored.
//
// Submission no longer calls this: the edges are written by
// [JobStore.CreateJobSubmission], in the same transaction as the job row
// whose blocked status they justify. See [JobStore.CreateJob] on what that
// leaves this method.
CreateJobDependencies(ctx context.Context, jobID string, upstreamIDs []string) 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) and updates UpdatedAt.
//
// status, started_at, completed_at, failed_attempts, and park_reason are
// lifecycle columns and are intentionally excluded — use [UpdateJobStatus],
// [CancelJobStatus], 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)
// UpdateJobStatus transitions a job to a new status and updates UpdatedAt.
// If the new status is [JobStatusRunning] and StartedAt is nil, StartedAt
// is set to the current time. Terminal statuses set CompletedAt.
// Returns [ErrNotFound] if the job does not exist.
UpdateJobStatus(ctx context.Context, id string, status JobStatus) 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
// 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.
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
// deliberately 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).
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].
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 transitions a paused job back to [JobStatusPending] — the
// inverse of [ParkJob] and of a manual pause. 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 very next genuine failure would immediately re-park the job.
// 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 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
Status WorkerStatus // empty = all statuses
// 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). Used by the scheduler's pickWorker so that 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 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 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. Negative Offset is reset to zero. It returns an error only for values that cannot be silently corrected (currently none — all out-of-range values are clamped).
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 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, which is the pre-isolation behavior. Nil RunAsGroup means the
// target user's primary group.
//
// Deliberately NOT part of the Queue -> Farm -> server-default cascade used
// by the retry-policy fields above: a farm-wide default would silently
// 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 —
// RunAsUser/RunAsGroup on this struct is ignored for that column — instead
// of overwriting it with the given (possibly zero) value.
//
// This exists so the API layer's "key omitted from the PUT body means
// preserve the stored identity" rule can be expressed as a single atomic
// UPDATE statement instead of a read-then-write: a prior GetQueue to fetch
// the existing value followed by a separate UpdateQueue left a window in
// which a concurrent admin write setting the identity could be silently
// undone by an unrelated operator write that started before it (lost
// update). Preferring "leave this column alone" inside the same statement
// closes that race outright rather than narrowing it.
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 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 — this runs on every
// cookie-authenticated request, so the second round trip is pure overhead
// on the hottest path in the server.
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
// DeleteSessionsForUser removes all sessions for a user.
DeleteSessionsForUser(ctx context.Context, userID 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. Useful for multi-valued tag semantics (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 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 conventions established in the OpenJD spec and documented in [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 means at least one task in this step is running. 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, typically because the // parent job was canceled. StepStatusCanceled StepStatus = "canceled" )
type StepStore ¶
type StepStore interface {
// CreateStep inserts a new step. The (JobID, Name) pair must be unique
// within the job; returns [ErrConflict] if violated.
//
// It has no production callers — submission writes steps through
// [JobStore.CreateJobSubmission]. See [JobStore.CreateJob] for what that
// means for anyone changing this method or building fixtures with it.
CreateStep(ctx context.Context, step Step) (Step, error)
// 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)
// UpdateStepStatus transitions a step to a new status and updates
// UpdatedAt. Returns [ErrNotFound] if the step does not exist.
UpdateStepStatus(ctx context.Context, id string, status StepStatus) error
}
StepStore is the persistence interface for Step records.
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
UsageClaimStore
WorkerStore
JobStore
StepStore
TaskStore
TaskAttemptStore
TaskLogStore
AuditStore
UserStore
SessionStore
APIKeyStore
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 GENUINELY ran and failed
// (worker-reported "failed"). Lost/reclaimed attempts never 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; may be empty for legacy workers
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
}
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 {
// CreateTaskAttempt inserts a new attempt record. Called when the server
// assigns a task to a worker and the worker acknowledges it.
CreateTaskAttempt(ctx context.Context, attempt TaskAttempt) (TaskAttempt, error)
// 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. Used by the
// scheduler to determine the correct AttemptNumber when creating a retry.
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)
// UpdateTaskAttempt replaces the mutable fields of an existing attempt
// (Status, ExitCode, EndedAt). Returns [ErrNotFound] if it does not exist.
UpdateTaskAttempt(ctx context.Context, attempt TaskAttempt) (TaskAttempt, error)
// TerminateWorkerAttempts marks all running [TaskAttempt] records for tasks
// currently assigned to workerID as the given terminal status with the
// supplied end time. Called by the heartbeat sweep before reclaiming tasks
// from an offline worker so that each attempt has a closed EndedAt.
// Returns the number of attempts updated.
TerminateWorkerAttempts(ctx context.Context, workerID string, status AttemptStatus, endedAt time.Time) (int, error)
// CancelJobAttempts marks all running [TaskAttempt] records for tasks
// belonging to the given job as [AttemptStatusCanceled] with the supplied
// end time. Should be called before [TaskStore.CancelJobTasks] so
// that attempts are closed while the tasks still carry their assigned worker.
// Returns the number of attempts updated.
CancelJobAttempts(ctx context.Context, jobID string, endedAt time.Time) (int, 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 will never approach int64 max in practice.
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.<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.
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.
//
// This method is used by the REST log-tail endpoint and by the WebSocket
// log-streaming handler.
ListTaskLogs(ctx context.Context, attemptID string, afterNATSSeq int64, limit int) ([]TaskLog, error)
}
TaskLogStore is the persistence interface for TaskLog records.
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" )
type TaskStore ¶
type TaskStore interface {
// CreateTask inserts a new task. The caller must populate all fields
// including a unique ID.
//
// It has no production callers — submission writes tasks through
// [JobStore.CreateJobSubmission]. See [JobStore.CreateJob] for what that
// means for anyone changing this method or building fixtures with it.
CreateTask(ctx context.Context, task Task) (Task, error)
// 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)
// UpdateTaskStatus transitions a task to a new status and updates
// UpdatedAt. Returns [ErrNotFound] if the task does not exist.
UpdateTaskStatus(ctx context.Context, id string, status TaskStatus) error
// AssignTask atomically sets AssignedWorkerID, AssignedAt, and Status to
// [TaskStatusAssigned] for the given task. Returns [ErrNotFound] if the
// task does not exist.
AssignTask(ctx context.Context, id, workerID string, assignedAt time.Time) 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)
// ReclaimWorkerTasks resets all tasks assigned to workerID that are still
// in [TaskStatusAssigned] or [TaskStatusRunning] back to [TaskStatusReady]
// so they can be reassigned by the scheduler. Called by the heartbeat
// timeout sweep after a worker is marked offline.
// Returns the number of tasks reclaimed.
ReclaimWorkerTasks(ctx context.Context, workerID string) (int, 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 that
// never started are reclaimed (e.g. the assignment message expired from the
// work stream before the worker pulled it). Returns the reclaimed tasks,
// each still carrying its pre-reset assigned_worker_id, so the caller can
// close their attempts and release usage-pool claims.
ReclaimStaleAssignedTasks(ctx context.Context, cutoff time.Time) ([]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)
// CancelJobTasks transitions all non-terminal tasks for the given job to
// [TaskStatusCanceled], clearing AssignedWorkerID and AssignedAt on each,
// and returns the subset that were in [TaskStatusAssigned] or
// [TaskStatusRunning] at the time of the call (with their AssignedWorkerID
// intact) so the caller can publish NATS cancel signals to the appropriate
// workers.
//
// A non-empty reason is stamped as FailureReason on each canceled task
// unless the task already carries one, so a more specific cause recorded
// earlier (e.g. a cascade-cancel) is never clobbered.
//
// The SELECT and UPDATE run inside a single database transaction so no
// concurrent assignment can race between observation and cancellation.
// Tasks already in a terminal state (succeeded, failed, canceled) are not
// modified.
CancelJobTasks(ctx context.Context, jobID string, now time.Time, reason string) ([]Task, error)
// RetryTasks revives failed/canceled tasks so they can run again. It
// transitions every task of jobID in [TaskStatusFailed] or
// [TaskStatusCanceled] — or, when taskIDs is non-nil, only those of the
// given IDs that are failed/canceled — back to [TaskStatusPending],
// clearing each revived task's genuine-failure state (FailedAttempts reset
// to zero, RetryAfter cleared). 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.
//
// Resetting to pending (rather than ready) lets the caller re-run
// [openjd.ResolveDependencies] to re-gate the revived tasks in dependency
// order. Tasks not in a terminal-retryable state are not modified. Returns
// the revived task rows (each with Status == pending), or an empty slice
// when nothing matched.
RetryTasks(ctx context.Context, jobID string, taskIDs []string, now time.Time) ([]Task, error)
// TransitionStepPendingTasks transitions every task of the given step that is
// currently in [TaskStatusPending] to status `to`, updates UpdatedAt, and
// returns the affected task rows. It is used to promote a step's tasks to
// [TaskStatusReady] once its dependencies resolve, and to cancel them when an
// upstream dependency fails.
//
// A non-empty failureReason is stamped on each transitioned task unless it
// already carries one (used by cascade-cancel; pass "" when promoting).
//
// The transition is applied as a single statement covering all matching rows
// regardless of count, so it is not subject to the [MaxLimit] pagination
// ceiling. Tasks not in pending state are not modified.
TransitionStepPendingTasks(ctx context.Context, stepID string, to TaskStatus, failureReason string) ([]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)
// LeaseReadyTask atomically transitions a task from [TaskStatusReady] to
// [TaskStatusAssigned], setting assigned_worker_id and assigned_at. It
// returns true iff the task was still ready (exactly one row changed); a
// false return means another worker leased it first. This is the race guard
// for concurrent lease requests.
LeaseReadyTask(ctx context.Context, taskID, workerID string, now time.Time) (bool, error)
// SetTaskUnschedulableReason sets (or, with an empty string, clears) the
// reason a ready task cannot be scheduled. Returns ErrNotFound if id is unknown.
SetTaskUnschedulableReason(ctx context.Context, id, reason string) error
// SetTaskFailureReason sets (or, with an empty string, clears) the
// human-readable reason the task reached a terminal non-success. Returns
// ErrNotFound if id is unknown.
SetTaskFailureReason(ctx context.Context, id, reason string) error
// SetTaskFailureReasonIfEmpty sets the failure reason only when the task
// currently has no reason recorded (an empty failure_reason). It is a
// legitimate no-op — not an error — when the task already carries a reason,
// so a more specific cause (e.g. a cascade-cancel) is never clobbered by a
// later, less specific one (e.g. a user cancel). A zero-row update (task
// unknown or already annotated) is NOT reported as ErrNotFound.
SetTaskFailureReasonIfEmpty(ctx context.Context, id, reason string) 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 genuine (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 — it simply 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 (i.e. this is the first delivery, so retry/park
// ACTIONS are authorized; a redelivery must first check that the attempt is
// still relevant before re-driving 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 or not assigned/running) is a
// legitimate no-op, not an error.
RequeueTaskForRetry(ctx context.Context, taskID 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 UsageClaim ¶
type UsageClaim struct {
ID string
PoolID string
TaskAttemptID string
// DB column: checked_out_at (historic name; kept to avoid a column-rename migration).
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 {
// CreateClaim inserts a new active claim for the given pool and task
// attempt. The (TaskAttemptID, PoolID) pair must be unique; returns
// [ErrConflict] if violated.
CreateClaim(ctx context.Context, claim UsageClaim) (UsageClaim, error)
// ReleaseClaim sets ReleasedAt on the claim with the given ID,
// marking it as no longer active. Returns [ErrNotFound] if it does not
// exist.
ReleaseClaim(ctx context.Context, id string, releasedAt time.Time) error
// 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)
// TryClaimSlots atomically verifies that every pool in claims has
// remaining capacity and, if so, inserts a [UsageClaim] row for each.
// The operation runs inside a single database transaction so the
// count-check and insert are indivisible.
//
// Returns [ErrUsageAtCapacity] if any pool is saturated; no rows are
// inserted in that case. Returns [ErrConflict] if any claim ID or
// (task_attempt_id, pool_id) pair already exists.
//
// taskAttemptID must reference an existing [TaskAttempt] row. claimedAt
// is the timestamp recorded on each new claim.
TryClaimSlots(ctx context.Context, taskAttemptID string, claims []UsagePoolClaim, claimedAt time.Time) error
// ReleaseAttemptClaims sets ReleasedAt on every active claim
// (released_at IS NULL) for the given taskAttemptID. Called when a task
// attempt reaches a terminal state so the usage pool slots are freed for
// reassignment.
//
// Returns the number of claims released (0 is not an error when the
// attempt held no claims).
ReleaseAttemptClaims(ctx context.Context, taskAttemptID string, releasedAt time.Time) (int, error)
// ReleaseJobClaims sets ReleasedAt on every active claim for any task
// attempt belonging to a task in the given job. Called during job
// cancellation to free all usage pool slots held by that job in a single
// operation, rather than iterating through individual attempts.
//
// Returns the number of claims released (0 is not an error when the job
// held no claims).
ReleaseJobClaims(ctx context.Context, jobID string, releasedAt time.Time) (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
// MaxConcurrent is the pool's current limit. The implementation uses this
// value inside the transaction to avoid a second pool lookup.
MaxConcurrent int
}
UsagePoolClaim describes a single usage pool slot to be claimed atomically by UsageClaimStore.TryClaimSlots.
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.
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 silently. 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. Role is stored but not enforced until B1.
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].
UpdateUser(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 a lie with no way to detect
// it. Atomicity means the caller can report failure honestly — nothing
// changed, 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].
DeleteUser(ctx context.Context, id string) error
// CountUsers returns the number of users (for the bootstrap gate).
CountUsers(ctx context.Context) (int, error)
// CountAdmins returns the number of enabled accounts with role "admin"
// (used by the last-admin lockout guard).
CountAdmins(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 for workers registered
// before this field existed, 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 is the same shape as the
// os.family darwin/macos one.
//
// Empty for workers registered before this field existed, and for any
// worker running an older binary that does not send it. An empty value can
// never satisfy an attr.worker.cpu.arch requirement; such a worker starts
// reporting its architecture as soon as it restarts and re-registers.
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
// for workers registered before this field existed.
Version string
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 for workers registered before this field existed; see
// [WorkerExprLimits] for what the server does with them.
ExprLimits WorkerExprLimits
Status WorkerStatus
LastHeartbeatAt *time.Time
RegisteredAt 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.
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 phase-3 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, which EXPR sub-project E4d Task 2 added and Task 3 (this type) taught it to advertise. The server persists them so the scheduler can refuse to dispatch an EXPR job to a worker that cannot run what the server accepted.
WHY THE SERVER NEEDS THEM. 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, a job is accepted, created and persisted and then every task of it fails on that host, after submission, naming a budget the submitter never saw. That failure was measured (EXPR design spec §2: server 10,000 positions, worker 5,000). Both sides became operator configuration in E4d, so the relation "worker cap >= server cap" can now be broken by a YAML file; these fields are what let the server see it.
Every value is SELF-REPORTED, exactly like CPUCount, RAMMb and Tags. It is a statement of what that worker will enforce, not a promise the server can verify.
A zero field means "not advertised": a worker built from E4d Task 3 onward always reports a real value (its config layer rejects 0), so silence means an older binary. The scheduler reads that as the compiled-in defaults, which is exact for a pre-Task-2 binary and a documented guess for one built between Tasks 2 and 3 — see internal/scheduler's legacyWorkerExprCaps.
All FIVE of the worker's expr.* keys are carried. The fifth, LetRetainedBytes, was excluded when this type was written -- on the grounds that the server has no PER-TABLE counterpart to compare it against, which is true -- and the wave's final review showed the exclusion was reachable through legal configuration: a worker at that key's floor rejects, once per task, a let: block the server accepted under a raised openjd.expr_template_retained_bytes. What the server does have is a bound on the same VALUES at a wider scope, and a wider scope is a valid upper bound; see internal/scheduler's exprCapShortfall for the comparison and for what it still cannot promise.
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.
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 means an operator has administratively paused the // worker; 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.
RegisterWorker(ctx context.Context, worker Worker) (Worker, 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)
// UpdateWorker replaces the mutable capability fields of an existing
// worker (everything except ID and RegisteredAt) and updates UpdatedAt.
// Returns [ErrNotFound] if the worker does not exist.
UpdateWorker(ctx context.Context, worker Worker) (Worker, error)
// UpdateWorkerStatus sets the status of the worker and updates UpdatedAt.
// Returns [ErrNotFound] if the worker does not exist.
UpdateWorkerStatus(ctx context.Context, id string, status WorkerStatus) error
// UpdateWorkerHeartbeat records the most recent heartbeat time for the
// given worker. This is a hot path; implementations should use a single
// UPDATE statement with no unnecessary reads.
UpdateWorkerHeartbeat(ctx context.Context, id string, at time.Time) error
// ListStaleWorkers returns workers whose last heartbeat is older than
// before and whose status is [WorkerStatusOnline]. Used by the heartbeat
// timeout sweep to find workers to mark offline.
ListStaleWorkers(ctx context.Context, before time.Time) ([]Worker, error)
// CountIdleWorkers returns the number of online 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)
// DeleteWorker hard-deletes the worker record with the given ID. Returns
// [ErrNotFound] if no such worker exists. Task and task-attempt rows that
// reference the worker by ID are left intact (the ID lives on as a
// snapshot); callers are responsible for ensuring the worker has no
// in-flight work before removing it.
DeleteWorker(ctx context.Context, id string) error
// DeleteOfflineWorkersBefore hard-deletes every worker in
// [WorkerStatusOffline] whose LastHeartbeatAt is strictly before cutoff,
// and returns the deleted records. Workers in any other status (including
// administratively disabled) are never touched. 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 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 used by goose to manage the sqi-server SQLite schema.
|
Package migrations embeds the SQL migration files used by goose to manage the sqi-server SQLite schema. |
|
Package sqlite provides a SQLite-backed implementation of store.Store.
|
Package sqlite provides a SQLite-backed implementation of store.Store. |