Documentation
¶
Overview ¶
Package sqlstore is the SQL implementation of store.Store shared by every database the store runs on. It writes each statement once, with "?" placeholders, and runs it through a Dialect that rebinds the query, converts time and bool arguments, and classifies driver errors. A database package (internal/store/sqlite, internal/store/postgres) opens the connection pools, supplies its dialect, and builds the store with New.
Reads and writes run on separate pools: New takes a write pool and a read pool, and every statement goes to one or the other by its text (see poolFor). Transactions always run on the write pool.
Index ¶
- func TimeText(t time.Time) string
- type Anchor
- type Dialect
- type ErrClass
- type LockMode
- type Option
- type Store
- func (s *Store) AbortRetirement(ctx context.Context, workerID string, now time.Time, reason string) (bool, error)
- func (s *Store) AcquireLeadership(ctx context.Context, holder string, ttl time.Duration) (epoch int64, ok bool, err error)
- func (s *Store) ActiveClaimCount(ctx context.Context, poolID string) (int, error)
- func (s *Store) AppendAuditEntry(ctx context.Context, entry store.AuditEntry) error
- func (s *Store) BeginRetirement(ctx context.Context, groupID, workerID string, now time.Time) (store.Worker, bool, error)
- func (s *Store) CancelBlockedJob(ctx context.Context, id, reason string, now time.Time) (bool, []store.Task, error)
- func (s *Store) CancelJobExecution(ctx context.Context, jobID, reason string, now time.Time) ([]store.Task, error)
- func (s *Store) CancelJobStatus(ctx context.Context, id string) error
- func (s *Store) CancelPendingStep(ctx context.Context, id, reason string, now time.Time) (bool, []store.Task, error)
- func (s *Store) CancelTaskExecution(ctx context.Context, taskID, reason string, now time.Time) (store.Task, bool, error)
- func (s *Store) ClaimInvariantViolations(ctx context.Context) ([]string, error)
- func (s *Store) Close() error
- func (s *Store) CommittedCores(ctx context.Context, workerID string, fullMachineCost int) (int, error)
- func (s *Store) CompleteTaskAttempt(ctx context.Context, c store.AttemptCompletion) (store.CompletionResult, error)
- func (s *Store) CountActiveTasksInFarm(ctx context.Context, farmID string) (int, error)
- func (s *Store) CountActiveTasksInQueue(ctx context.Context, queueID string) (int, error)
- func (s *Store) CountIdleWorkers(ctx context.Context, farmID string) (int, error)
- func (s *Store) CountReadyTasksByQueue(ctx context.Context, farmID string, now time.Time) (map[string]int, error)
- func (s *Store) CountTasksByJob(ctx context.Context, jobID string) (map[store.TaskStatus]int, error)
- func (s *Store) CountUnschedulableTasksByJob(ctx context.Context, jobID string) (int, error)
- func (s *Store) CountUsers(ctx context.Context) (int, error)
- func (s *Store) CreateAPIKey(ctx context.Context, k store.APIKey) (store.APIKey, error)
- func (s *Store) CreateCapacityGroup(ctx context.Context, g store.CapacityGroup) (store.CapacityGroup, error)
- func (s *Store) CreateComputeLocation(ctx context.Context, loc store.ComputeLocation) (store.ComputeLocation, error)
- func (s *Store) CreateFarm(ctx context.Context, farm store.Farm) (store.Farm, error)
- func (s *Store) CreateJobSubmission(ctx context.Context, sub store.JobSubmission) (store.JobSubmission, error)
- func (s *Store) CreateProduct(ctx context.Context, p store.Product) (store.Product, error)
- func (s *Store) CreateQueue(ctx context.Context, queue store.Queue) (store.Queue, error)
- func (s *Store) CreateSession(ctx context.Context, sess store.Session) (store.Session, error)
- func (s *Store) CreateStorageLocation(ctx context.Context, loc store.StorageLocation) (store.StorageLocation, error)
- func (s *Store) CreateTaskLog(ctx context.Context, log store.TaskLog) (store.TaskLog, error)
- func (s *Store) CreateUsagePool(ctx context.Context, pool store.UsagePool) (store.UsagePool, error)
- func (s *Store) CreateUser(ctx context.Context, u store.User) (store.User, error)
- func (s *Store) CreateWorkerCredential(ctx context.Context, c store.WorkerCredential) (store.WorkerCredential, error)
- func (s *Store) CreateWorkerJoinToken(ctx context.Context, t store.WorkerJoinToken) (store.WorkerJoinToken, error)
- func (s *Store) DeleteCapacityGroup(ctx context.Context, id string) error
- func (s *Store) DeleteComputeLocation(ctx context.Context, id string) error
- func (s *Store) DeleteEphemeralWorker(ctx context.Context, id string, now time.Time) (store.Worker, bool, error)
- func (s *Store) DeleteExpiredSessions(ctx context.Context, now time.Time) (int, error)
- func (s *Store) DeleteFarm(ctx context.Context, id string) error
- func (s *Store) DeleteJob(ctx context.Context, id string) error
- func (s *Store) DeleteOfflineWorkersBefore(ctx context.Context, cutoff time.Time) ([]store.Worker, error)
- func (s *Store) DeleteProduct(ctx context.Context, name string) error
- func (s *Store) DeleteQueue(ctx context.Context, id string) error
- func (s *Store) DeleteServerMembersUnseenFor(ctx context.Context, d time.Duration) (int, error)
- func (s *Store) DeleteSession(ctx context.Context, id string) error
- func (s *Store) DeleteStorageLocation(ctx context.Context, id string) error
- func (s *Store) DeleteTerminalJobsBefore(ctx context.Context, cutoff time.Time, includeFailed bool) ([]store.DeletedJob, error)
- func (s *Store) DeleteUsagePool(ctx context.Context, id string) error
- func (s *Store) DeleteUser(ctx context.Context, id string) error
- func (s *Store) DeleteVanishedEphemeralWorker(ctx context.Context, id string, cutoff, now time.Time) (store.Worker, bool, error)
- func (s *Store) DeleteWorkerIfRemovable(ctx context.Context, id string) error
- func (s *Store) DemoteStalledJobs(ctx context.Context, now time.Time) ([]string, error)
- func (s *Store) ExpireRetirements(ctx context.Context, groupID string, cutoff, now time.Time, reason string) ([]string, error)
- func (s *Store) FailWakes(ctx context.Context, groupID string, cutoff, now time.Time, reason string) ([]string, error)
- func (s *Store) FailureReasonSummary(ctx context.Context, jobID string) (store.FailureSummary, error)
- func (s *Store) FinalizeJob(ctx context.Context, id string, now time.Time) (store.JobStatus, bool, error)
- func (s *Store) FinalizeStep(ctx context.Context, id string, now time.Time) (store.StepStatus, bool, error)
- func (s *Store) FinishRetirement(ctx context.Context, workerID string, now time.Time) (w store.Worker, deleted, ok bool, err error)
- func (s *Store) GetAPIKeyUserByTokenHash(ctx context.Context, tokenHash string, now time.Time) (store.APIKey, store.User, error)
- func (s *Store) GetActiveWorkerCredentialByPublicKey(ctx context.Context, publicKey string) (store.WorkerCredential, error)
- func (s *Store) GetBrokerIdentity(ctx context.Context) (string, error)
- func (s *Store) GetCapacityGroup(ctx context.Context, id string) (store.CapacityGroup, error)
- func (s *Store) GetCapacityGroupByName(ctx context.Context, name string) (store.CapacityGroup, error)
- func (s *Store) GetComputeLocation(ctx context.Context, id string) (store.ComputeLocation, error)
- func (s *Store) GetComputeLocationByName(ctx context.Context, name string) (store.ComputeLocation, error)
- func (s *Store) GetFarm(ctx context.Context, id string) (store.Farm, error)
- func (s *Store) GetJob(ctx context.Context, id string) (store.Job, error)
- func (s *Store) GetLeadership(ctx context.Context) (store.Lease, error)
- func (s *Store) GetProductByName(ctx context.Context, name string) (store.Product, error)
- func (s *Store) GetQueue(ctx context.Context, id string) (store.Queue, error)
- func (s *Store) GetSessionByTokenHash(ctx context.Context, tokenHash string, now time.Time) (store.Session, error)
- func (s *Store) GetSessionUserByTokenHash(ctx context.Context, tokenHash string, now time.Time) (store.User, error)
- func (s *Store) GetStep(ctx context.Context, id string) (store.Step, error)
- func (s *Store) GetStorageLocation(ctx context.Context, id string) (store.StorageLocation, error)
- func (s *Store) GetStorageLocationByName(ctx context.Context, name string) (store.StorageLocation, error)
- func (s *Store) GetTask(ctx context.Context, id string) (store.Task, error)
- func (s *Store) GetTaskAttempt(ctx context.Context, id string) (store.TaskAttempt, error)
- func (s *Store) GetUsagePool(ctx context.Context, id string) (store.UsagePool, error)
- func (s *Store) GetUser(ctx context.Context, id string) (store.User, error)
- func (s *Store) GetUserByExternalID(ctx context.Context, authSource, externalID string) (store.User, error)
- func (s *Store) GetUserByUsername(ctx context.Context, username string) (store.User, error)
- func (s *Store) GetWorker(ctx context.Context, id string) (store.Worker, error)
- func (s *Store) GetWorkerJoinTokenByHash(ctx context.Context, hash string) (store.WorkerJoinToken, error)
- func (s *Store) InjectClaim(ctx context.Context, claim store.UsageClaim) (store.UsageClaim, error)
- func (s *Store) InjectTaskAttempt(ctx context.Context, attempt store.TaskAttempt) (store.TaskAttempt, error)
- func (s *Store) InjectWorkerPowerState(ctx context.Context, workerID string, state store.PowerState, at time.Time, ...) error
- func (s *Store) JobTimings(ctx context.Context, jobIDs []string) (map[string]store.JobTiming, error)
- func (s *Store) LatestAttemptProgress(ctx context.Context, taskIDs []string) (map[string]store.TaskProgress, error)
- func (s *Store) LatestTaskAttempt(ctx context.Context, taskID string) (store.TaskAttempt, error)
- func (s *Store) LeaseTask(ctx context.Context, req store.LeaseRequest) (store.LeaseResult, error)
- func (s *Store) ListAPIKeysForUser(ctx context.Context, userID string) ([]store.APIKey, error)
- func (s *Store) ListActiveWorkerCredentials(ctx context.Context) ([]store.WorkerCredential, error)
- func (s *Store) ListAuditEntries(ctx context.Context, entityType, entityID string) ([]store.AuditEntry, error)
- func (s *Store) ListBlockedJobs(ctx context.Context) ([]store.Job, error)
- func (s *Store) ListCapacityGroupMembers(ctx context.Context, groupID string) ([]store.Worker, error)
- func (s *Store) ListCapacityGroupStates(ctx context.Context) (map[string]store.CapacityGroupState, error)
- func (s *Store) ListCapacityGroupTokens(ctx context.Context, groupID string) ([]store.WorkerJoinToken, error)
- func (s *Store) ListCapacityGroups(ctx context.Context) ([]store.CapacityGroup, error)
- func (s *Store) ListComputeLocations(ctx context.Context) ([]store.ComputeLocation, error)
- func (s *Store) ListDependents(ctx context.Context, upstreamJobID string) ([]string, error)
- func (s *Store) ListFarms(ctx context.Context) ([]store.Farm, error)
- func (s *Store) ListJobDependencyIDs(ctx context.Context, jobID string) ([]string, error)
- func (s *Store) ListJobIDsWithPendingSteps(ctx context.Context) ([]string, error)
- func (s *Store) ListJobs(ctx context.Context, opts store.ListJobsOptions) (store.Page[store.Job], error)
- func (s *Store) ListOpenAttempts(ctx context.Context) ([]store.OpenAttempt, error)
- func (s *Store) ListProducts(ctx context.Context) ([]store.Product, error)
- func (s *Store) ListQueues(ctx context.Context, opts store.ListQueuesOptions) (store.Page[store.Queue], error)
- func (s *Store) ListReadyStepDemand(ctx context.Context, farmID string, now time.Time) ([]store.StepDemand, error)
- func (s *Store) ListReadyTasks(ctx context.Context, farmID string, now time.Time, limit int) ([]store.Task, error)
- func (s *Store) ListServerMembers(ctx context.Context) ([]store.ServerMember, int64, error)
- func (s *Store) ListStaleWorkers(ctx context.Context, before time.Time) ([]store.Worker, error)
- func (s *Store) ListSteps(ctx context.Context, jobID string) ([]store.Step, error)
- func (s *Store) ListStorageLocations(ctx context.Context) ([]store.StorageLocation, error)
- func (s *Store) ListStuckSteps(ctx context.Context) ([]store.Step, error)
- func (s *Store) ListTaskAttempts(ctx context.Context, taskID string) ([]store.TaskAttempt, error)
- func (s *Store) ListTaskLogs(ctx context.Context, attemptID string, afterNATSSeq int64, limit int) ([]store.TaskLog, error)
- func (s *Store) ListTasks(ctx context.Context, opts store.ListTasksOptions) (store.Page[store.Task], error)
- func (s *Store) ListUsagePoolUtilization(ctx context.Context) ([]store.UsagePoolUtilization, error)
- func (s *Store) ListUsagePools(ctx context.Context) ([]store.UsagePool, error)
- func (s *Store) ListUsers(ctx context.Context) ([]store.User, error)
- func (s *Store) ListWorkerCommitments(ctx context.Context, farmID string) (map[string]store.WorkerCommitment, error)
- func (s *Store) ListWorkers(ctx context.Context, opts store.ListWorkersOptions) (store.Page[store.Worker], error)
- func (s *Store) MarkWaking(ctx context.Context, groupID string, workerIDs []string, now time.Time) ([]string, error)
- func (s *Store) MarkWorkerJoinTokenUsed(ctx context.Context, id string, at time.Time) error
- func (s *Store) OfflineStaleWorker(ctx context.Context, id string, cutoff, now time.Time) ([]store.Task, bool, error)
- func (s *Store) OfflineWorker(ctx context.Context, id, instanceID string, now time.Time) ([]store.Task, bool, error)
- func (s *Store) ParkJob(ctx context.Context, jobID, reason string, now time.Time) error
- func (s *Store) PauseJob(ctx context.Context, id string, now time.Time) error
- func (s *Store) PromoteJobRunning(ctx context.Context, id string, now time.Time) (bool, error)
- func (s *Store) PutCapacityGroupState(ctx context.Context, st store.CapacityGroupState) error
- func (s *Store) QueueJobTimings(ctx context.Context, queueIDs []string) ([]store.JobTiming, error)
- func (s *Store) ReclaimStaleAssignedTasks(ctx context.Context, cutoff time.Time, skip map[string]bool) ([]store.Task, error)
- func (s *Store) ReclaimTaskAttempt(ctx context.Context, attemptID, taskID string, now time.Time) (bool, error)
- func (s *Store) RecordAttemptProgress(ctx context.Context, p store.AttemptProgress) (store.ProgressOutcome, string, error)
- func (s *Store) RecordTaskFailure(ctx context.Context, attemptID, taskID string, exitCode *int, ...) (taskFailed, jobFailed int, firstClose bool, err error)
- func (s *Store) RedeemWorkerJoinToken(ctx context.Context, hash string, now time.Time, cred store.WorkerCredential) (store.WorkerCredential, error)
- func (s *Store) RegisterWorker(ctx context.Context, worker store.Worker) (store.Worker, store.Registration, error)
- func (s *Store) ReleaseBlockedJob(ctx context.Context, id string, now time.Time) (bool, error)
- func (s *Store) ReleaseLeadership(ctx context.Context, holder string, epoch int64) error
- func (s *Store) ReleaseStep(ctx context.Context, id string, now time.Time) (bool, []store.Task, error)
- func (s *Store) RenewLeadership(ctx context.Context, holder string, epoch int64, ttl time.Duration) (bool, error)
- func (s *Store) RequeueTaskForRetry(ctx context.Context, taskID, attemptID string, retryAfter, now time.Time) (bool, error)
- func (s *Store) ResumeJob(ctx context.Context, jobID string, now time.Time) error
- func (s *Store) RetryTasks(ctx context.Context, jobID string, taskIDs []string, now time.Time) ([]store.Task, error)
- func (s *Store) RevokeAPIKey(ctx context.Context, id, userID string, now time.Time) error
- func (s *Store) RevokeCapacityGroupToken(ctx context.Context, groupID, id string, at time.Time) error
- func (s *Store) RevokeWorkerCredential(ctx context.Context, workerID string, at time.Time) error
- func (s *Store) RunningProgressByJob(ctx context.Context, jobID string) (float64, error)
- func (s *Store) RunningProgressByJobs(ctx context.Context, jobIDs []string) (map[string]float64, error)
- func (s *Store) SetBrokerIdentity(ctx context.Context, identity string, at time.Time) error
- func (s *Store) SetTaskUnschedulableReason(ctx context.Context, id, reason string) (bool, error)
- func (s *Store) SetUserDisplayName(ctx context.Context, id, displayName string) (store.User, error)
- func (s *Store) SetUserPassword(ctx context.Context, id, passwordHash string) error
- func (s *Store) SetUserPasswordAndEvictSessions(ctx context.Context, id, passwordHash string) error
- func (s *Store) SetWorkerCapacityGroup(ctx context.Context, workerID, groupID string, ephemeral bool) (store.Worker, error)
- func (s *Store) SetWorkerDisabled(ctx context.Context, id string, disabled bool) (store.Worker, error)
- func (s *Store) StartTaskAttempt(ctx context.Context, attemptID, taskID, sessionID string, now time.Time) (bool, error)
- func (s *Store) TouchAPIKeyLastUsed(ctx context.Context, id string, now time.Time) error
- func (s *Store) TouchWorkerCredential(ctx context.Context, workerID string, at time.Time) (store.WorkerCredential, error)
- func (s *Store) TxRetries() int64
- func (s *Store) UpdateCapacityGroup(ctx context.Context, g store.CapacityGroup) (store.CapacityGroup, error)
- func (s *Store) UpdateComputeLocation(ctx context.Context, loc store.ComputeLocation) (store.ComputeLocation, error)
- func (s *Store) UpdateFarm(ctx context.Context, farm store.Farm) (store.Farm, error)
- func (s *Store) UpdateJob(ctx context.Context, job store.Job) (store.Job, error)
- func (s *Store) UpdateProduct(ctx context.Context, p store.Product) (store.Product, error)
- func (s *Store) UpdateQueue(ctx context.Context, queue store.Queue) (store.Queue, error)
- func (s *Store) UpdateStorageLocation(ctx context.Context, loc store.StorageLocation) (store.StorageLocation, error)
- func (s *Store) UpdateUsagePool(ctx context.Context, pool store.UsagePool) (store.UsagePool, error)
- func (s *Store) UpdateUser(ctx context.Context, u store.User) (store.User, error)
- func (s *Store) UpdateUserKeepingAdmin(ctx context.Context, u store.User) (store.User, error)
- func (s *Store) UpdateWorkerHeartbeat(ctx context.Context, id string, at time.Time, brokerAt, startedAt *time.Time) (store.HeartbeatOutcome, error)
- func (s *Store) UpsertServerMember(ctx context.Context, m store.ServerMember) error
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
Types ¶
type Anchor ¶
Anchor is a row a transaction locks before it writes, per the anchor-row table in docs/architecture.md.
type Dialect ¶
type Dialect interface {
// Rebind rewrites "?" placeholders into the driver's form.
Rebind(query string) string
// Classify reports what an error from the driver means.
Classify(err error) ErrClass
// LockAnchors locks each anchor row, in the order given, in tx.
LockAnchors(ctx context.Context, tx *sql.Tx, anchors ...Anchor) error
// BindTime and BindBool return the value a Go time or bool is bound as.
BindTime(t time.Time) any
BindBool(b bool) any
// CIEqual returns "<col> = ?" compared case-insensitively.
CIEqual(col string) string
// CILike returns "<col> LIKE ?" matched case-insensitively, in the dialect's
// own form (PostgreSQL: "<col> ILIKE ? ESCAPE ”"). Like CIEqual it may carry
// only the column, a "?" and literals.
CILike(col string) string
// ForUpdate returns the clause that makes a SELECT lock the rows it reads
// until the transaction ends (PostgreSQL: " FOR UPDATE"), or "" where the
// database takes no row locks (SQLite, whose single write connection
// serializes every writer). A statement that exists only to take those
// locks is not run when it is "".
ForUpdate() string
// a SELECT reads cannot change until the transaction ends, though other
// readers may share them. It is "" where the database takes no row locks.
ForShare() string
// ClockMicros returns a SQL expression for the database's wall clock now
// as integer microseconds since the Unix epoch. It reads the clock at
// each evaluation, not once per transaction.
ClockMicros() string
// EpochSeconds returns a SQL expression for the stored timestamp expr as
// float seconds since the Unix epoch.
EpochSeconds(expr string) string
}
Dialect is what differs between the SQL databases the store runs on. The store writes every statement with "?" placeholders and binds Go values; the dialect rewrites, converts and classifies at the boundary.
type LockMode ¶
type LockMode int
LockMode is how LockAnchors locks a row.
LockUpdate excludes other writers of the row; LockShare only keeps the row from changing (an upstream job a dependent waits on). LockNoKeyUpdate (PostgreSQL's FOR NO KEY UPDATE) excludes other writers too: it conflicts with itself, with LockUpdate and LockShare, and with an UPDATE or DELETE of the row. It does not conflict with the FOR KEY SHARE lock a foreign-key check takes on a referenced row, so inserting a row that references the anchor (a job referencing its queue and farm, a claim referencing its pool) does not wait for it, nor it for the insert. SQLite ignores every mode.
type Option ¶
type Option func(*Store)
Option configures New.
func WithForcedRetry ¶
func WithForcedRetry() Option
WithForcedRetry makes every transaction run its function twice, the first run rolled back, as if the database had aborted it for a concurrent writer. Tests only: it exposes a function that keeps state from a failed run.
func WithLeasePool ¶
WithLeasePool gives the leadership methods (the lease and the server membership) a pool of their own, which the store owns and Close closes. A lease renewal then waits for no other write, however many hold the write pool's connections. Without it they share the write pool.
func WithLogger ¶
WithLogger sets the logger retry diagnostics go to.
func WithTaskInsertBatch ¶
WithTaskInsertBatch makes CreateJobSubmission insert a submission's tasks rows at a time, several per statement, instead of one statement per task. Without it (or below 2) the statements are the single-row ones.
It is an option rather than a Dialect method the store looks for on its dialect, because a wrapped dialect (the tests wrap one to check lock order and to pause a transaction) embeds the Dialect interface and so does not carry a method outside it: the batched path would silently turn off under every wrapper.
type Store ¶
type Store struct {
// contains filtered or unexported fields
}
Store is the SQL implementation of store.Store. Create one with New; close it with Store.Close when done.
func New ¶
New builds a Store over open write and read pools for dialect d and prepares its statements. read may be write. Close releases the pools; on error New closes them itself.
func (*Store) AbortRetirement ¶
func (s *Store) AbortRetirement(ctx context.Context, workerID string, now time.Time, reason string) (bool, error)
AbortRetirement implements store.CapacityPowerStore.
Anchor: the worker row.
func (*Store) AcquireLeadership ¶
func (s *Store) AcquireLeadership(ctx context.Context, holder string, ttl time.Duration) (epoch int64, ok bool, err error)
AcquireLeadership implements store.LeadershipStore.
func (*Store) ActiveClaimCount ¶
ActiveClaimCount implements store.UsageClaimStore.
func (*Store) AppendAuditEntry ¶
AppendAuditEntry implements store.AuditStore.
func (*Store) BeginRetirement ¶
func (s *Store) BeginRetirement(ctx context.Context, groupID, workerID string, now time.Time) (store.Worker, bool, error)
BeginRetirement implements store.CapacityPowerStore.
Anchor: the worker row, exclusive. LeaseTask holds it shared and re-checks the power state under it, so the two serialize on it: a lease that committed first holds a task the in-flight condition sees, and one that waits sees the worker retiring and is Lost.
func (*Store) CancelBlockedJob ¶
func (s *Store) CancelBlockedJob(ctx context.Context, id, reason string, now time.Time) (bool, []store.Task, error)
CancelBlockedJob implements store.JobStore.
Anchors as for Store.ReleaseBlockedJob. The job row is written first and guards the rest: when the job is no longer blocked nothing is written at all, otherwise its open steps and pending tasks follow in the same transaction so a canceled job is never observed with live children.
func (*Store) CancelJobExecution ¶
func (s *Store) CancelJobExecution(ctx context.Context, jobID, reason string, now time.Time) ([]store.Task, error)
CancelJobExecution implements store.TaskStore.
Anchor: the job row, the parent every job-level operation locks. The anchor comes before the SELECT that reports the active tasks (I2), and the writes run in the order Postgres requires: the tasks are canceled first, and only then are their attempts closed and their claims released. The job's steps are finalized after that, and the job row itself is canceled last, under the same guard as Store.CancelJobStatus, so a job cancel is one write: no stop or failed second write can leave a job live with all of its work canceled. The task UPDATE's predicate matches a task both as ready and as assigned, and the attempts and claims are closed only after it, so whatever any writer committed to a task before the UPDATE is seen by the two statements after it. Closing attempts first would miss an attempt created in between.
The anchor also makes the reported set exact. LeaseTask holds the job row FOR SHARE, so no lease commits between the SELECT and the task UPDATE: a lease in flight is waited for and its task is reported as assigned; a later lease waits for this commit, finds the job canceled and is Lost. Every task the UPDATE takes out of flight is in the returned set, so its worker can be sent a cancel signal. On SQLite the single write connection gives the same.
func (*Store) CancelJobStatus ¶
CancelJobStatus implements store.JobStore.
It issues a conditional UPDATE that only fires when the job is not already in a terminal state. When zero rows are affected the job is either missing or already terminal; a follow-up GetJob disambiguates:
- not found → store.ErrNotFound
- already canceled → nil (idempotent)
- completed or failed → store.ErrConflict
func (*Store) CancelPendingStep ¶
func (s *Store) CancelPendingStep(ctx context.Context, id, reason string, now time.Time) (bool, []store.Task, error)
CancelPendingStep implements store.StepStore.
func (*Store) CancelTaskExecution ¶
func (s *Store) CancelTaskExecution(ctx context.Context, taskID, reason string, now time.Time) (store.Task, bool, error)
CancelTaskExecution implements store.TaskStore.
Anchor and statement order are CancelJobExecution's: the task's job row first (the task's job id never changes, so it is read before the lock), then the task as it is under that lock, then the task is canceled before its attempt is closed and its claims released. The task row is read after the lock rather than before it, so on Postgres the returned prior task is current against every job-anchored writer. The "already terminal" answer comes from the guarded UPDATE itself, so it is exact on any store. The prior task is current against LeaseTask too, which holds the job row FOR SHARE: no lease commits between the read and the UPDATE, so a task leased just before the anchor is read as assigned to its worker, and a lease that waited for this commit finds the task canceled and is Lost.
func (*Store) ClaimInvariantViolations ¶
ClaimInvariantViolations returns the IDs of active usage claims that break invariant I3. It is a diagnostic used by tests and is not part of store.Store. An empty result means the invariant holds.
func (*Store) Close ¶
Close closes all prepared statements and both connection pools. It is safe to call Close more than once.
func (*Store) CommittedCores ¶
func (s *Store) CommittedCores(ctx context.Context, workerID string, fullMachineCost int) (int, error)
CommittedCores implements store.TaskStore.
func (*Store) CompleteTaskAttempt ¶
func (s *Store) CompleteTaskAttempt(ctx context.Context, c store.AttemptCompletion) (store.CompletionResult, error)
CompleteTaskAttempt implements store.TaskStore.
Anchor: the task's job row, the parent every job-level operation (cancel, retry, finalize) locks, so this is ordered against them on Postgres. The statements run in this order: close the attempt, release its claims, then move the task. The claims are released before the task row is touched, and the release commits even when the task move is refused, so a canceled task's late report still frees its pool slots. The latest-attempt check runs after the release and before the task move. The job anchor makes the two one step: LeaseTask holds the task's job row FOR SHARE, so a lease in flight is waited for and its attempt is seen by the check, and a later lease waits for this commit. No lease can add a newer attempt between the check and the compare-and-set's read (which would make a superseded report look current), so no task-row lock is needed. On SQLite the single write connection gives the same.
func (*Store) CountActiveTasksInFarm ¶
CountActiveTasksInFarm implements store.TaskStore.
func (*Store) CountActiveTasksInQueue ¶
CountActiveTasksInQueue implements store.TaskStore.
func (*Store) CountIdleWorkers ¶
CountIdleWorkers implements store.WorkerStore. When farmID is empty all farms are counted.
func (*Store) CountReadyTasksByQueue ¶
func (s *Store) CountReadyTasksByQueue(ctx context.Context, farmID string, now time.Time) (map[string]int, error)
CountReadyTasksByQueue implements store.TaskStore. Returns a map of queue ID → leasable ready-task count for the given farm. Queues with zero leasable tasks are omitted.
func (*Store) CountTasksByJob ¶
func (s *Store) CountTasksByJob(ctx context.Context, jobID string) (map[store.TaskStatus]int, error)
CountTasksByJob implements store.TaskStore. Returns the number of tasks for the given job keyed by status. Statuses with zero tasks are omitted from the returned map.
func (*Store) CountUnschedulableTasksByJob ¶
CountUnschedulableTasksByJob implements store.TaskStore. Returns the number of ready tasks for the given job that carry a non-empty unschedulable reason.
func (*Store) CountUsers ¶
CountUsers implements store.UserStore.
func (*Store) CreateAPIKey ¶
CreateAPIKey implements store.APIKeyStore.
func (*Store) CreateCapacityGroup ¶
func (s *Store) CreateCapacityGroup(ctx context.Context, g store.CapacityGroup) (store.CapacityGroup, error)
CreateCapacityGroup implements store.CapacityGroupStore.
func (*Store) CreateComputeLocation ¶
func (s *Store) CreateComputeLocation(ctx context.Context, loc store.ComputeLocation) (store.ComputeLocation, error)
CreateComputeLocation implements store.ComputeLocationStore.
func (*Store) CreateFarm ¶
CreateFarm implements store.FarmStore.
func (*Store) CreateJobSubmission ¶
func (s *Store) CreateJobSubmission(ctx context.Context, sub store.JobSubmission) (store.JobSubmission, error)
CreateJobSubmission implements store.JobStore. Every row one submission creates — the job, its dependency edges, its steps and its tasks — is written in a single transaction, so a failure at any point leaves nothing behind.
Rows are inserted in foreign-key order (job, edges, steps, tasks) and each insert runs raw SQL in tx rather than a prepared statement bound to the transaction with tx.Stmt, as the other transactional writers here do (see casWriteTaskStatus in attemptclose.go).
Each step and task row is stamped with its own, strictly later time from one [rowClock]; see insertTasksTx for why the rows must not share one timestamp.
func (*Store) CreateProduct ¶
CreateProduct implements store.ProductStore.
func (*Store) CreateQueue ¶
CreateQueue implements store.QueueStore.
func (*Store) CreateSession ¶
CreateSession implements store.SessionStore.
Unlike CreateUser, this does not stamp CreatedAt (or ExpiresAt) server-side: both are caller-supplied by design, since ExpiresAt is derived from the issuance instant and the two timestamps must agree with each other.
func (*Store) CreateStorageLocation ¶
func (s *Store) CreateStorageLocation(ctx context.Context, loc store.StorageLocation) (store.StorageLocation, error)
CreateStorageLocation implements store.StorageLocationStore.
func (*Store) CreateTaskLog ¶
CreateTaskLog implements store.TaskLogStore.
func (*Store) CreateUsagePool ¶
CreateUsagePool implements store.UsagePoolStore.
func (*Store) CreateUser ¶
CreateUser implements store.UserStore.
func (*Store) CreateWorkerCredential ¶
func (s *Store) CreateWorkerCredential(ctx context.Context, c store.WorkerCredential) (store.WorkerCredential, error)
CreateWorkerCredential implements store.WorkerCredentialStore.
func (*Store) CreateWorkerJoinToken ¶
func (s *Store) CreateWorkerJoinToken(ctx context.Context, t store.WorkerJoinToken) (store.WorkerJoinToken, error)
CreateWorkerJoinToken implements store.WorkerCredentialStore.
func (*Store) DeleteCapacityGroup ¶
DeleteCapacityGroup implements store.CapacityGroupStore. A worker that belongs to the group makes the foreign key refuse, which is store.ErrConflict.
func (*Store) DeleteComputeLocation ¶
DeleteComputeLocation implements store.ComputeLocationStore.
func (*Store) DeleteEphemeralWorker ¶
func (s *Store) DeleteEphemeralWorker(ctx context.Context, id string, now time.Time) (store.Worker, bool, error)
DeleteEphemeralWorker implements store.WorkerStore.
Anchor: the worker row, which orders the delete against a lease (LeaseTask holds it FOR SHARE) so a task leased to the worker is seen by the in-flight condition. The credential is revoked in the same transaction, only when the worker was deleted.
func (*Store) DeleteExpiredSessions ¶
DeleteExpiredSessions implements store.SessionStore.
func (*Store) DeleteFarm ¶
DeleteFarm implements store.FarmStore.
func (*Store) DeleteJob ¶
DeleteJob implements store.JobStore. The cascade runs in a single transaction; if the jobs-row delete affects zero rows the job did not exist and the transaction is rolled back with store.ErrNotFound.
The job anchor is taken first, which serializes the cascade against the other job-anchored writers (cancel, retry, finalize, completion, retention), and against leases, which hold the job row FOR SHARE. A log append (CreateTaskLog, no transaction, no anchor) is held off by the lock on the job's logged tasks taken next ([lockJobLoggedTasksTx]): it waits for the delete instead of inserting a child row after its table was cleared. As a backstop the cascade (claims, logs, attempts, tasks, steps, dependency edges, then the job row) is retried if a DELETE in it fails on a foreign key ([cascadeErr]) or deadlocks. SQLite cannot produce either error: its single write connection serializes every writer.
func (*Store) DeleteOfflineWorkersBefore ¶
func (s *Store) DeleteOfflineWorkersBefore(ctx context.Context, cutoff time.Time) ([]store.Worker, error)
DeleteOfflineWorkersBefore implements store.WorkerStore. The deleted rows are read inside the write, before a fenced one commits.
func (*Store) DeleteProduct ¶
DeleteProduct implements store.ProductStore.
func (*Store) DeleteQueue ¶
DeleteQueue implements store.QueueStore.
func (*Store) DeleteServerMembersUnseenFor ¶
DeleteServerMembersUnseenFor implements store.LeadershipStore.
func (*Store) DeleteSession ¶
DeleteSession implements store.SessionStore.
func (*Store) DeleteStorageLocation ¶
DeleteStorageLocation implements store.StorageLocationStore.
func (*Store) DeleteTerminalJobsBefore ¶
func (s *Store) DeleteTerminalJobsBefore( ctx context.Context, cutoff time.Time, includeFailed bool, ) ([]store.DeletedJob, error)
DeleteTerminalJobsBefore implements store.JobStore. It lists the eligible jobs unlocked, in id order, then deletes each in its own transaction: the job's anchor, a re-check of the eligibility predicate under it, then the shared cascade. Each cascade is atomic, so no job is left half-deleted, and the sweep never holds more than one job's locks, or the SQLite write connection for more than one job's cascade. On error, the result lists the jobs already deleted.
The list is a snapshot, and a retry can revive one of its jobs before that job's turn comes. So each job is re-checked against the full eligibility predicate (terminal status, cutoff, no live dependent) under its anchor, immediately before its cascade starts; a job that no longer matches is skipped, neither deleted nor reported.
func (*Store) DeleteUsagePool ¶
DeleteUsagePool implements store.UsagePoolStore.
func (*Store) DeleteUser ¶
DeleteUser implements store.UserStore. The guard is in the DELETE's WHERE clause, so the refusal and the write are one statement.
func (*Store) DeleteVanishedEphemeralWorker ¶
func (s *Store) DeleteVanishedEphemeralWorker(ctx context.Context, id string, cutoff, now time.Time) (store.Worker, bool, error)
DeleteVanishedEphemeralWorker implements store.WorkerStore, as Store.DeleteEphemeralWorker does.
func (*Store) DeleteWorkerIfRemovable ¶
DeleteWorkerIfRemovable implements store.WorkerStore.
The zero-rows case is told apart by a read after the delete: a worker that exists but did not match is store.ErrConflict, one that is gone is store.ErrNotFound. A concurrent change between the two statements can only move the answer between those two errors, never delete a row the rule refused.
func (*Store) DemoteStalledJobs ¶
DemoteStalledJobs implements store.JobStore.
It lists the stalled jobs unlocked, then demotes each in its own transaction: the job row locked, the stalled predicate checked again under the lock, then the write. A lease holds the job row shared, so a lease in flight is waited for and the re-check sees the task it assigned; a job that is no longer stalled is left alone.
The returned IDs are in id order, the order the candidates are locked in. On error, the result lists the jobs already demoted.
func (*Store) ExpireRetirements ¶
func (s *Store) ExpireRetirements(ctx context.Context, groupID string, cutoff, now time.Time, reason string) ([]string, error)
ExpireRetirements implements store.CapacityPowerStore.
Anchors: each overdue member, in id order.
func (*Store) FailWakes ¶
func (s *Store) FailWakes(ctx context.Context, groupID string, cutoff, now time.Time, reason string) ([]string, error)
FailWakes implements store.CapacityPowerStore.
Anchors: each overdue member, in id order.
func (*Store) FailureReasonSummary ¶
func (s *Store) FailureReasonSummary(ctx context.Context, jobID string) (store.FailureSummary, error)
FailureReasonSummary implements store.TaskStore.
func (*Store) FinalizeJob ¶
func (s *Store) FinalizeJob(ctx context.Context, id string, now time.Time) (store.JobStatus, bool, error)
FinalizeJob implements store.JobStore.
Anchor: the job row. As in Store.FinalizeStep, the current status is read under the anchor, only when the finalize writes nothing.
func (*Store) FinalizeStep ¶
func (s *Store) FinalizeStep(ctx context.Context, id string, now time.Time) (store.StepStatus, bool, error)
FinalizeStep implements store.StepStore.
Anchor: the step's job row. When the finalize writes nothing, the current status is read under the anchor to report an already-terminal step, so it is current against every job-anchored writer.
func (*Store) FinishRetirement ¶
func (s *Store) FinishRetirement( ctx context.Context, workerID string, now time.Time, ) (w store.Worker, deleted, ok bool, err error)
FinishRetirement implements store.CapacityPowerStore.
Anchor: the worker row. An ephemeral member is first put to sleep and offline like a named one, which makes it match DeleteEphemeralWorker's rule, and is then deleted with its credential revoked by the same statement and helper DeleteEphemeralWorker uses.
func (*Store) GetAPIKeyUserByTokenHash ¶
func (s *Store) GetAPIKeyUserByTokenHash(ctx context.Context, tokenHash string, now time.Time) (store.APIKey, store.User, error)
GetAPIKeyUserByTokenHash implements store.APIKeyStore.
func (*Store) GetActiveWorkerCredentialByPublicKey ¶
func (s *Store) GetActiveWorkerCredentialByPublicKey(ctx context.Context, publicKey string) (store.WorkerCredential, error)
GetActiveWorkerCredentialByPublicKey implements store.WorkerCredentialStore.
func (*Store) GetBrokerIdentity ¶
GetBrokerIdentity implements store.BrokerStateStore.
func (*Store) GetCapacityGroup ¶
GetCapacityGroup implements store.CapacityGroupStore.
func (*Store) GetCapacityGroupByName ¶
func (s *Store) GetCapacityGroupByName(ctx context.Context, name string) (store.CapacityGroup, error)
GetCapacityGroupByName implements store.CapacityGroupStore.
func (*Store) GetComputeLocation ¶
GetComputeLocation implements store.ComputeLocationStore.
func (*Store) GetComputeLocationByName ¶
func (s *Store) GetComputeLocationByName(ctx context.Context, name string) (store.ComputeLocation, error)
GetComputeLocationByName implements store.ComputeLocationStore.
func (*Store) GetFarm ¶
GetFarm implements store.FarmStore.
func (*Store) GetJob ¶
GetJob implements store.JobStore.
func (*Store) GetLeadership ¶
GetLeadership implements store.LeadershipStore.
func (*Store) GetProductByName ¶
GetProductByName implements store.ProductStore.
func (*Store) GetQueue ¶
GetQueue implements store.QueueStore.
func (*Store) GetSessionByTokenHash ¶
func (s *Store) GetSessionByTokenHash(ctx context.Context, tokenHash string, now time.Time) (store.Session, error)
GetSessionByTokenHash implements store.SessionStore.
func (*Store) GetSessionUserByTokenHash ¶
func (s *Store) GetSessionUserByTokenHash(ctx context.Context, tokenHash string, now time.Time) (store.User, error)
GetSessionUserByTokenHash implements store.SessionStore.
func (*Store) GetStep ¶
GetStep implements store.StepStore.
func (*Store) GetStorageLocation ¶
GetStorageLocation implements store.StorageLocationStore.
func (*Store) GetStorageLocationByName ¶
func (s *Store) GetStorageLocationByName(ctx context.Context, name string) (store.StorageLocation, error)
GetStorageLocationByName implements store.StorageLocationStore.
func (*Store) GetTask ¶
GetTask implements store.TaskStore.
func (*Store) GetTaskAttempt ¶
GetTaskAttempt implements store.TaskAttemptStore.
func (*Store) GetUsagePool ¶
GetUsagePool implements store.UsagePoolStore.
func (*Store) GetUser ¶
GetUser implements store.UserStore.
func (*Store) GetUserByExternalID ¶
func (s *Store) GetUserByExternalID(ctx context.Context, authSource, externalID string) (store.User, error)
GetUserByExternalID implements store.UserStore.
func (*Store) GetUserByUsername ¶
GetUserByUsername implements store.UserStore.
func (*Store) GetWorker ¶
GetWorker implements store.WorkerStore.
func (*Store) GetWorkerJoinTokenByHash ¶
func (s *Store) GetWorkerJoinTokenByHash(ctx context.Context, hash string) (store.WorkerJoinToken, error)
GetWorkerJoinTokenByHash implements store.WorkerCredentialStore.
func (*Store) InjectClaim ¶
func (s *Store) InjectClaim(ctx context.Context, claim store.UsageClaim) (store.UsageClaim, error)
InjectClaim inserts claim active, with no capacity or state checks; a zero ClaimedAt is stamped now and ReleasedAt is ignored. Same contract as Store.InjectTaskAttempt: corruption injection only, not part of store.Store. Foreign keys still apply: the claim's pool and attempt must exist.
func (*Store) InjectTaskAttempt ¶
func (s *Store) InjectTaskAttempt(ctx context.Context, attempt store.TaskAttempt) (store.TaskAttempt, error)
InjectTaskAttempt inserts attempt as given, with no state checks; a zero CreatedAt is stamped now.
Corruption injection for invariant, recovery and repair tests: it exists to build states production cannot reach, and must never be used to seed a reachable one — seed through CreateJobSubmission and production writes instead (internal/store/storetest). It is not part of store.Store. Foreign keys still apply: the attempt's task must exist. The task's stored run time (tasks.run_ms) is recomputed after the insert, so a timing fixture built from injected attempts reads as the attempts say.
func (*Store) InjectWorkerPowerState ¶
func (s *Store) InjectWorkerPowerState( ctx context.Context, workerID string, state store.PowerState, at time.Time, reason string, ) error
InjectWorkerPowerState sets worker workerID's power state, its time and its reason as given. Same contract as Store.InjectTaskAttempt: it stands in for the power-transition writers where a test needs a state, and is not part of store.Store. It returns store.ErrNotFound for an unknown worker.
func (*Store) JobTimings ¶
func (s *Store) JobTimings(ctx context.Context, jobIDs []string) (map[string]store.JobTiming, error)
JobTimings implements store.TimingStore.
func (*Store) LatestAttemptProgress ¶
func (s *Store) LatestAttemptProgress(ctx context.Context, taskIDs []string) (map[string]store.TaskProgress, error)
LatestAttemptProgress implements store.TaskAttemptStore.
func (*Store) LatestTaskAttempt ¶
LatestTaskAttempt implements store.TaskAttemptStore.
func (*Store) LeaseTask ¶
func (s *Store) LeaseTask(ctx context.Context, req store.LeaseRequest) (store.LeaseResult, error)
LeaseTask implements store.TaskStore.
func (*Store) ListAPIKeysForUser ¶
ListAPIKeysForUser implements store.APIKeyStore.
func (*Store) ListActiveWorkerCredentials ¶
ListActiveWorkerCredentials implements store.WorkerCredentialStore.
func (*Store) ListAuditEntries ¶
func (s *Store) ListAuditEntries(ctx context.Context, entityType, entityID string) ([]store.AuditEntry, error)
ListAuditEntries returns all audit entries for the given entity, ordered by CreatedAt ascending. Passing empty strings for both entityType and entityID returns all entries. A test oracle: nothing in production reads the audit log, so it is not part of store.Store.
func (*Store) ListBlockedJobs ¶
ListBlockedJobs implements store.JobStore. It returns every job currently in store.JobStatusBlocked.
func (*Store) ListCapacityGroupMembers ¶
func (s *Store) ListCapacityGroupMembers(ctx context.Context, groupID string) ([]store.Worker, error)
ListCapacityGroupMembers implements store.WorkerStore.
func (*Store) ListCapacityGroupStates ¶
func (s *Store) ListCapacityGroupStates(ctx context.Context) (map[string]store.CapacityGroupState, error)
ListCapacityGroupStates implements store.CapacityPowerStore.
func (*Store) ListCapacityGroupTokens ¶
func (s *Store) ListCapacityGroupTokens(ctx context.Context, groupID string) ([]store.WorkerJoinToken, error)
ListCapacityGroupTokens implements store.WorkerCredentialStore.
func (*Store) ListCapacityGroups ¶
ListCapacityGroups implements store.CapacityGroupStore.
func (*Store) ListComputeLocations ¶
ListComputeLocations implements store.ComputeLocationStore.
func (*Store) ListDependents ¶
ListDependents implements store.JobStore. It returns the IDs of jobs waiting on upstreamJobID, ordered by dependent job ID.
func (*Store) ListFarms ¶
ListFarms implements store.FarmStore.
func (*Store) ListJobDependencyIDs ¶
ListJobDependencyIDs implements store.JobStore. It returns the upstream job IDs jobID waits on, ordered by upstream job ID.
func (*Store) ListJobIDsWithPendingSteps ¶
ListJobIDsWithPendingSteps implements store.StepStore.
func (*Store) ListJobs ¶
func (s *Store) ListJobs(ctx context.Context, opts store.ListJobsOptions) (store.Page[store.Job], error)
ListJobs implements store.JobStore. Dynamic filters use parameterised ad-hoc queries due to the variable WHERE clause. The sort column is looked up from a hard-coded allow-list before being interpolated into the SQL to prevent injection.
func (*Store) ListOpenAttempts ¶
ListOpenAttempts implements store.TaskAttemptStore.
func (*Store) ListProducts ¶
ListProducts implements store.ProductStore.
func (*Store) ListQueues ¶
func (s *Store) ListQueues(ctx context.Context, opts store.ListQueuesOptions) (store.Page[store.Queue], error)
ListQueues implements store.QueueStore. Dynamic filters use parameterised ad-hoc queries; the sort column is looked up from a hard-coded allow-list to prevent injection.
func (*Store) ListReadyStepDemand ¶
func (s *Store) ListReadyStepDemand(ctx context.Context, farmID string, now time.Time) ([]store.StepDemand, error)
ListReadyStepDemand implements store.TaskStore.
func (*Store) ListReadyTasks ¶
func (s *Store) ListReadyTasks(ctx context.Context, farmID string, now time.Time, limit int) ([]store.Task, error)
ListReadyTasks implements store.TaskStore.
func (*Store) ListServerMembers ¶
ListServerMembers implements store.LeadershipStore.
func (*Store) ListStaleWorkers ¶
ListStaleWorkers implements store.WorkerStore.
func (*Store) ListSteps ¶
ListSteps implements store.StepStore.
func (*Store) ListStorageLocations ¶
ListStorageLocations implements store.StorageLocationStore.
func (*Store) ListStuckSteps ¶
ListStuckSteps implements store.StepStore.
func (*Store) ListTaskAttempts ¶
ListTaskAttempts implements store.TaskAttemptStore.
func (*Store) ListTaskLogs ¶
func (s *Store) ListTaskLogs(ctx context.Context, attemptID string, afterNATSSeq int64, limit int) ([]store.TaskLog, error)
ListTaskLogs implements store.TaskLogStore.
func (*Store) ListTasks ¶
func (s *Store) ListTasks(ctx context.Context, opts store.ListTasksOptions) (store.Page[store.Task], error)
ListTasks implements store.TaskStore. Dynamic filters use parameterised ad-hoc queries due to the variable WHERE clause. The sort column is looked up from a hard-coded allow-list.
func (*Store) ListUsagePoolUtilization ¶
ListUsagePoolUtilization implements store.UsagePoolStore.
func (*Store) ListUsagePools ¶
ListUsagePools implements store.UsagePoolStore.
func (*Store) ListUsers ¶
ListUsers implements store.UserStore.
func (*Store) ListWorkerCommitments ¶
func (s *Store) ListWorkerCommitments(ctx context.Context, farmID string) (map[string]store.WorkerCommitment, error)
ListWorkerCommitments implements store.TaskStore.
func (*Store) ListWorkers ¶
func (s *Store) ListWorkers(ctx context.Context, opts store.ListWorkersOptions) (store.Page[store.Worker], error)
ListWorkers implements store.WorkerStore. Dynamic filters are applied via parameterised ad-hoc queries because the WHERE clause varies; this is safe as all values are bound via placeholders. The sort column is looked up from a hard-coded allow-list.
func (*Store) MarkWaking ¶
func (s *Store) MarkWaking(ctx context.Context, groupID string, workerIDs []string, now time.Time) ([]string, error)
MarkWaking implements store.CapacityPowerStore.
Anchors: each named worker, in id order.
func (*Store) MarkWorkerJoinTokenUsed ¶
MarkWorkerJoinTokenUsed implements store.WorkerCredentialStore.
func (*Store) OfflineStaleWorker ¶
func (s *Store) OfflineStaleWorker(ctx context.Context, id string, cutoff, now time.Time) ([]store.Task, bool, error)
OfflineStaleWorker implements store.WorkerStore.
func (*Store) OfflineWorker ¶
func (s *Store) OfflineWorker(ctx context.Context, id, instanceID string, now time.Time) ([]store.Task, bool, error)
OfflineWorker implements store.WorkerStore.
func (*Store) ParkJob ¶
ParkJob implements store.JobStore.
A zero-row UPDATE is ambiguous between "job not found" and "job already terminal"; a follow-up GetJob disambiguates the same way Store.CancelJobStatus does — terminal is a legitimate no-op (nil), missing propagates store.ErrNotFound.
func (*Store) PauseJob ¶
PauseJob implements store.JobStore. The guarded UPDATE does the work; a zero-row result is ambiguous between an unknown job and one in another status, and a follow-up read tells them apart.
func (*Store) PromoteJobRunning ¶
PromoteJobRunning implements store.JobStore. It is one guarded UPDATE, so it needs no anchor: an unknown job and a job that is not pending both write nothing and return false.
func (*Store) PutCapacityGroupState ¶
PutCapacityGroupState implements store.CapacityPowerStore. An unknown group is found by a read before the write, in the same transaction, so a leadership context's fence check still runs for it. A group deleted between the read and the write makes the foreign key refuse the write; that conflict is reported as store.ErrNotFound when a fresh read confirms the group is gone, and as store.ErrConflict otherwise.
func (*Store) QueueJobTimings ¶
QueueJobTimings implements store.TimingStore. Jobs are ordered by ID.
func (*Store) ReclaimStaleAssignedTasks ¶
func (s *Store) ReclaimStaleAssignedTasks(ctx context.Context, cutoff time.Time, skip map[string]bool) ([]store.Task, error)
ReclaimStaleAssignedTasks implements store.TaskStore.
It lists the stale assignments unlocked, then, a batch at a time, locks the batch's job rows sorted by id and resets the batch with a re-guarded UPDATE … RETURNING, then closes each reset task's running attempts and releases their claims (I3). The returned set is the RETURNING set: exactly what was reset (I2), so the scheduler never has to look an attempt up after the fact and cannot close the new attempt of a task leased again in between. Each batch commits on its own, so on error the result lists the tasks earlier batches reclaimed. Candidates named in skip are dropped before batching.
Order: no task row is locked before its job row (every job-level operation locks the job first, so the reverse would deadlock), and the job lock is what orders the reaper against CompleteTaskAttempt, which writes the attempt before the task, the reverse of the reaper. Within the transaction the tasks are reset before their attempts are closed, so a worker's report already holding a task row is waited for and the re-check then skips the task it moved; closing attempts first would let a report move the task (assigned to running, say) after its attempt was already closed as failed. A LeaseTask is not a competitor: it moves a ready row, which the re-check does not match, and the task it leaves assigned is not stale.
func (*Store) ReclaimTaskAttempt ¶
func (s *Store) ReclaimTaskAttempt(ctx context.Context, attemptID, taskID string, now time.Time) (bool, error)
ReclaimTaskAttempt implements store.TaskStore.
Anchor and statement order are offlineWorker's for one task: the job row (lockTaskJobTx), then the task, then its attempts and claims (closeTaskAttemptsTx). No worker anchor is taken, because the worker row is neither read nor written here. The task is written before its attempt is closed for offlineWorker's reason. As for StartTaskAttempt, no task-row lock is needed for the latest-attempt check: a lease holds the job row FOR SHARE, so none commits between the check and the write.
func (*Store) RecordAttemptProgress ¶
func (s *Store) RecordAttemptProgress(ctx context.Context, p store.AttemptProgress) (store.ProgressOutcome, string, error)
RecordAttemptProgress implements store.TaskStore.
No job-row anchor is taken: the liveness read and the guarded update touch only the task and attempt rows, and a snapshot that races a close is harmless because the update re-checks status = 'running'.
func (*Store) RecordTaskFailure ¶
func (s *Store) RecordTaskFailure( ctx context.Context, attemptID, taskID string, exitCode *int, sessionID, message string, now time.Time, ) (taskFailed, jobFailed int, firstClose bool, err error)
RecordTaskFailure implements store.TaskStore.
The attempt close, task increment, and job increment run inside a single transaction. The counter increments are gated on the attempt's running→failed transition: closing the attempt (which only affects a row while it is still running) authorizes the increment, so an at-least-once redelivery of the same status message, whose attempt is already terminal, counts zero rows, skips both increments, and returns the current counts instead. The failure count is therefore exactly once per attempt, and the two counters stay in lockstep: either both increment or neither does.
Invariant I3: the same transaction releases the attempt's claims, so a closed attempt never keeps a usage slot. Anchor: the task's job row, taken before the first write. The statements run attempt close, claim release, then the counters; the claim release does not depend on the counters.
func (*Store) RedeemWorkerJoinToken ¶
func (s *Store) RedeemWorkerJoinToken(ctx context.Context, hash string, now time.Time, cred store.WorkerCredential) (store.WorkerCredential, error)
RedeemWorkerJoinToken implements store.WorkerCredentialStore.
Follows the same idiom as CreateJobSubmission (job.go): the whole operation runs inside one transaction (inTx), using raw SQL via tx rather than the prepared statements the standalone per-row methods use.
The token claim reuses sqlConsumeWorkerJoinToken's text — a single UPDATE ... RETURNING that carries both the validity check and the claim in one statement, so an unknown token, an expired one, and one another request claimed a moment earlier are all the same "matched no row" outcome. If that claim fails, the transaction is rolled back and store.ErrNotFound is returned with the token untouched.
The credential insert happens inside the same transaction, so a conflict there (a worker ID already bound to an active credential, or a public key already enrolled anywhere) rolls back the token claim too: the token is not consumed, and remains redeemable by a later, non-conflicting request.
func (*Store) RegisterWorker ¶
func (s *Store) RegisterWorker(ctx context.Context, worker store.Worker) (store.Worker, store.Registration, error)
RegisterWorker implements store.WorkerStore.
Anchor: the worker row, then (on a restart) the reclaim's job rows, the same order as offlineWorker. A restart's reclaim is ordered against leases the way offlineWorker is: LeaseTask holds the worker row FOR SHARE, so a lease in flight is waited for and its task reclaimed.
func (*Store) ReleaseBlockedJob ¶
ReleaseBlockedJob implements store.JobStore.
Anchors: the job row, then each upstream job row (a PostgreSQL store locks those FOR SHARE, so a concurrent finalize of an upstream is ordered against this release). The write is one guarded UPDATE; see [sqlReleaseBlockedJob].
func (*Store) ReleaseLeadership ¶
ReleaseLeadership implements store.LeadershipStore.
func (*Store) ReleaseStep ¶
func (s *Store) ReleaseStep(ctx context.Context, id string, now time.Time) (bool, []store.Task, error)
ReleaseStep implements store.StepStore.
func (*Store) RenewLeadership ¶
func (s *Store) RenewLeadership(ctx context.Context, holder string, epoch int64, ttl time.Duration) (bool, error)
RenewLeadership implements store.LeadershipStore.
func (*Store) RequeueTaskForRetry ¶
func (s *Store) RequeueTaskForRetry(ctx context.Context, taskID, attemptID string, retryAfter, now time.Time) (bool, error)
RequeueTaskForRetry implements store.TaskStore. Zero rows (task missing, no longer assigned/running, or attemptID not the task's latest attempt) is a no-op reported as false, not an error, so a stale redelivery never naks into a redelivery loop.
Anchor: the task's job row, so the latest-attempt check in the guard cannot be overtaken by a lease committing a new attempt (a lease holds the job row shared).
func (*Store) ResumeJob ¶
ResumeJob implements store.JobStore.
A zero-row UPDATE is ambiguous between "job not found" and "job no longer paused"; a follow-up GetJob disambiguates the same way Store.ParkJob does — not-paused is a legitimate no-op (nil), missing propagates store.ErrNotFound.
func (*Store) RetryTasks ¶
func (s *Store) RetryTasks(ctx context.Context, jobID string, taskIDs []string, now time.Time) ([]store.Task, error)
RetryTasks implements store.TaskStore.
func (*Store) RevokeAPIKey ¶
RevokeAPIKey implements store.APIKeyStore.
func (*Store) RevokeCapacityGroupToken ¶
func (s *Store) RevokeCapacityGroupToken(ctx context.Context, groupID, id string, at time.Time) error
RevokeCapacityGroupToken implements store.WorkerCredentialStore.
func (*Store) RevokeWorkerCredential ¶
RevokeWorkerCredential implements store.WorkerCredentialStore.
func (*Store) RunningProgressByJob ¶
RunningProgressByJob implements store.TaskAttemptStore. The percents are summed as integers and divided once, so the result does not depend on the backend's numeric type.
func (*Store) RunningProgressByJobs ¶
func (s *Store) RunningProgressByJobs(ctx context.Context, jobIDs []string) (map[string]float64, error)
RunningProgressByJobs implements store.TaskAttemptStore. Sums stay integer per job and are divided once, as in RunningProgressByJob.
func (*Store) SetBrokerIdentity ¶
SetBrokerIdentity implements store.BrokerStateStore.
func (*Store) SetTaskUnschedulableReason ¶
SetTaskUnschedulableReason implements store.TaskStore. A task that is no longer ready is a guarded no-op returning (false, nil); only an unknown task is an error.
func (*Store) SetUserDisplayName ¶
SetUserDisplayName implements store.UserStore.
func (*Store) SetUserPassword ¶
SetUserPassword implements store.UserStore.
func (*Store) SetUserPasswordAndEvictSessions ¶
SetUserPasswordAndEvictSessions implements store.UserStore. Both writes share one transaction, so a failure means neither landed.
func (*Store) SetWorkerCapacityGroup ¶
func (s *Store) SetWorkerCapacityGroup(ctx context.Context, workerID, groupID string, ephemeral bool) (store.Worker, error)
SetWorkerCapacityGroup implements store.WorkerStore.
Anchor: the worker row. The group is read, not locked: deleting it while this transaction runs makes the foreign key refuse the write, which is store.ErrConflict.
func (*Store) SetWorkerDisabled ¶
func (s *Store) SetWorkerDisabled(ctx context.Context, id string, disabled bool) (store.Worker, error)
SetWorkerDisabled implements store.WorkerStore.
func (*Store) StartTaskAttempt ¶
func (s *Store) StartTaskAttempt(ctx context.Context, attemptID, taskID, sessionID string, now time.Time) (bool, error)
StartTaskAttempt implements store.TaskStore.
func (*Store) TouchAPIKeyLastUsed ¶
TouchAPIKeyLastUsed implements store.APIKeyStore.
func (*Store) TouchWorkerCredential ¶
func (s *Store) TouchWorkerCredential(ctx context.Context, workerID string, at time.Time) (store.WorkerCredential, error)
TouchWorkerCredential implements store.WorkerCredentialStore. The partial unique index on active credentials leaves at most one row to update, so the RETURNING row is the worker's active credential; none is store.ErrNotFound.
func (*Store) TxRetries ¶
TxRetries reports how many times a transaction was run again after the database aborted it for a concurrent writer.
func (*Store) UpdateCapacityGroup ¶
func (s *Store) UpdateCapacityGroup(ctx context.Context, g store.CapacityGroup) (store.CapacityGroup, error)
UpdateCapacityGroup implements store.CapacityGroupStore.
func (*Store) UpdateComputeLocation ¶
func (s *Store) UpdateComputeLocation(ctx context.Context, loc store.ComputeLocation) (store.ComputeLocation, error)
UpdateComputeLocation implements store.ComputeLocationStore.
func (*Store) UpdateFarm ¶
UpdateFarm implements store.FarmStore.
func (*Store) UpdateJob ¶
UpdateJob implements store.JobStore. Only mutable user-settable fields are written (farm_id, queue_id, name, owner, submitter, priority, project, raw_template, template_format, max_attempts, retry_delay_seconds, failure_limit, estimated_seconds). product_name and product_version are left as stored. status, started_at, completed_at, failed_attempts, and park_reason are never touched here; use CancelJobStatus, FinalizeJob, or the scheduler's failure-limit sweep for those.
func (*Store) UpdateProduct ¶
UpdateProduct implements store.ProductStore.
func (*Store) UpdateQueue ¶
UpdateQueue implements store.QueueStore. See the type's doc comment for PreserveRunAsUser/PreserveRunAsGroup semantics.
Wrapped in an explicit transaction (rather than the single QueryRowContext every other Update* uses) because store.ErrRunAsGroupWithoutUser must be checked against the resolved run_as_user/run_as_group, after the statement's own CASE WHEN preserve substitution, rather than the raw request fields: a PUT that omits run_as_user/run_as_group cannot tell from the request alone whether the preserved column will end up empty. RETURNING yields those resolved values from the very statement that would commit them, so the invalid-combo check and the write see identical data with no separate read and therefore no read-then-write race. An invalid combo rolls the transaction back so the update has no effect at all, rather than committing a queue update while reporting an error.
func (*Store) UpdateStorageLocation ¶
func (s *Store) UpdateStorageLocation(ctx context.Context, loc store.StorageLocation) (store.StorageLocation, error)
UpdateStorageLocation implements store.StorageLocationStore.
func (*Store) UpdateUsagePool ¶
UpdateUsagePool implements store.UsagePoolStore.
func (*Store) UpdateUser ¶
UpdateUser implements store.UserStore.
func (*Store) UpdateUserKeepingAdmin ¶
UpdateUserKeepingAdmin implements store.UserStore. The guard is in the UPDATE's WHERE clause, so the refusal and the write are one statement.
func (*Store) UpdateWorkerHeartbeat ¶
func (s *Store) UpdateWorkerHeartbeat( ctx context.Context, id string, at time.Time, brokerAt, startedAt *time.Time, ) (store.HeartbeatOutcome, error)
UpdateWorkerHeartbeat implements store.WorkerStore.
func (*Store) UpsertServerMember ¶
UpsertServerMember implements store.LeadershipStore.
Source Files
¶
- anchor.go
- apikey.go
- attemptclose.go
- attemptreport.go
- audit.go
- brokerstate.go
- capacity.go
- capacitypower.go
- compute_location.go
- dialect.go
- farm.go
- fence.go
- finalize.go
- inject.go
- invariants.go
- job.go
- leadership.go
- lease.go
- product.go
- queue.go
- runms.go
- scan.go
- search.go
- session.go
- step.go
- storage_location.go
- store.go
- task.go
- task_attempt.go
- task_log.go
- timing.go
- tx.go
- usage.go
- user.go
- worker.go
- workercredential.go