scheduler

package
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Nov 24, 2026 License: AGPL-3.0 Imports: 32 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package scheduler implements the sqi-server assignment loop and worker registry. It decides which task runs on which worker.

The Scheduler runs three concurrent loops:

  1. Lease subscriber: a core-NATS request/reply subscriber on work.lease.> ([handleLeaseRequest]). Idle workers ask for work; the scheduler selects a priority-ordered batch of ready tasks the worker is eligible for that fits its free CPU cores ([selectLeaseBatch]), atomically leases each (store.TaskStore.LeaseTask), and replies with the assignment payloads. When no work is available the request parks in the waiter registry until new work appears or the hold elapses, then replies.

  2. Worker registry: a NATS push-consumer for worker.register.<worker> messages that persists capability data via store.WorkerStore.RegisterWorker and keeps the WorkersTotal Prometheus gauge current.

  3. Heartbeat sweep: a NATS push-consumer that updates each worker's LastHeartbeatAt on worker.heartbeat messages, paired with a periodic timer that finds workers whose heartbeat has gone stale (store.WorkerStore.ListStaleWorkers, a candidate list only) and takes each offline with store.WorkerStore.OfflineStaleWorker, which re-checks the heartbeat inside its write, closes the worker's open attempts, releases their usage claims and returns its in-flight tasks to the ready queue in one transaction. The same tick refreshes the queue-depth, idle-worker, and usage-claim Prometheus gauges.

Worker selection. A task is matched to a worker by capability tags, compute-location affinity, and queue/farm filtering (WorkerEligible), subject to per-queue and per-farm maximum-concurrent-task limits ([policyGate]). Those checks are early filters. Once a worker is chosen, store.TaskStore.LeaseTask makes the real decision in one transaction: it moves the task to assigned, re-checks the queue, farm and usage-pool caps against their current values, creates the provisional store.TaskAttempt and claims any required usage pool slots. If a cap filled in the meantime nothing is written and the task stays ready for the next lease request. Attempt numbers are computed by the same transaction — 1 for a fresh task, N+1 on retry.

Assignment payload. [buildAssignPayload] re-parses the job's raw OpenJD template to extract the matching step's OnRun action, embedded files, and ordered environments (job environments first, then step, per the OpenJD spec). It also attaches path-mapping rules built from the registered storage locations for the worker's compute location.

Status and log ingestion. A push-consumer on the SQI_TASK stream ([handleTaskStatusMessage]) decodes protocol.TaskStatusMsg from task.status.<worker>.<job>, updates the task/attempt, releases held usage pool slots, and drives step/job completion including openjd.ResolveDependencies for multi-step jobs. A push-consumer on SQI_LOGS ([handleLogChunk]) persists each task.logs.<worker>.<task> chunk as a store.TaskLog row, recording both the worker-assigned sequence number and the NATS stream sequence that serves as the log-tail pagination cursor.

Cancellation. [CancelJob] and [CancelTask] are the server-side entry points called by the REST layer: each makes one store call that transitions tasks to store.TaskStatusCanceled, closes their running attempts and releases their usage pool slots in a single transaction, then publishes a cancel signal to each worker that held one, on its task.cancel.<workerID> subject (bus.Client.PublishTaskCancel). The logic lives in cancellation.go; the SQI_CANCEL stream and publish helper live in the bus package.

Wire protocol and metrics. All worker messages use the versioned JSON types in worker/protocol (protocol.RegisterMsg, protocol.HeartbeatMsg, protocol.AssignMsg, protocol.TaskStatusMsg, protocol.LogChunkMsg). Each heartbeat-sweep tick refreshes the scheduler's Prometheus metrics (metrics.Metrics): queue depth by queue, idle workers by farm, and active usage-pool claims per pool.

Index

Constants

View Source
const LogHeartbeatSkewed = "scheduler: worker heartbeat delayed or skewed"

LogHeartbeatSkewed begins the warning the scheduler logs for a heartbeat whose worker timestamp is more than heartbeat_timeout from its receipt. The chaos checks look for it in the server's log.

View Source
const StopCeiling = 30 * time.Second

StopCeiling is the longest a server waits for Scheduler.Run to return once it has stopped it, before it closes the bus and the store. It sits inside the server's 30 s shutdown budget, which the service managers' stop timeouts are sized for. Run's own drains are capped to finish inside it ([maxCapacityDrain]).

Variables

This section is empty.

Functions

func BuildAssignPayload added in v0.4.0

func BuildAssignPayload(
	ctx context.Context,
	task store.Task,
	worker store.Worker,
	job store.Job,
	step store.Step,
	queue store.Queue,
	attemptID string,
	locStore store.StorageLocationStore,
) ([]byte, error)

BuildAssignPayload is [buildAssignPayload] for callers outside this package.

It delegates verbatim and adds nothing. Keep it that way: the unexported function stays the single implementation, so a change to assignment building cannot reach production without also reaching the preset goldens.

func ReconnectGrace added in v0.4.0

func ReconnectGrace(workerTimeout time.Duration) time.Duration

ReconnectGrace is the Config.BusReconnectGrace the server sets: how long after its bus connection returns the liveness sweeps keep standing down. A live worker lost the same broker, so it redials on its own backoff, which is independent of the server's: the grace must cover the worker timeout, a worker's longest redial wait with its jitter, and one heartbeat interval for the first heartbeat after the redial. A shorter grace reclaims the running tasks of a worker that is still waiting to reconnect. A workerTimeout <= 0 means the default WorkerTimeout.

func WorkerEligible

func WorkerEligible(
	worker store.Worker,
	job store.Job,
	step store.Step,
	pools map[string]store.UsagePool,
	activeCounts map[string]int,
) bool

WorkerEligible reports whether worker w can run a task that belongs to step s and job j, given the current usage pool state.

pools maps pool name → store.UsagePool. activeCounts maps pool name → current active claim count.

Both maps may be nil or empty when no usage pools exist.

func WorkerEligibleWithReason

func WorkerEligibleWithReason(
	worker store.Worker,
	job store.Job,
	step store.Step,
	pools map[string]store.UsagePool,
	activeCounts map[string]int,
) (reason string, eligible bool)

WorkerEligibleWithReason is the same as WorkerEligible but also returns a human-readable rejection reason for diagnostic logging.

Types

type Config

type Config struct {
	// FarmID is the farm this scheduler instance manages. The assignment loop
	// only considers tasks that belong to this farm.
	FarmID string

	// AssignInterval is how often the assignment loop polls the store for ready
	// tasks. Lower values reduce latency; higher values reduce DB pressure.
	// Default: 1 s.
	AssignInterval time.Duration

	// AssignBatchSize is the maximum number of ready tasks fetched per
	// assignment loop tick. Limits burst DB load without capping throughput
	// over time. Default: 50.
	AssignBatchSize int

	// AssignWorkers is the size of the goroutine pool that processes assignment
	// decisions concurrently. Default: 4.
	AssignWorkers int

	// WorkerTimeout is the maximum time since a worker's last heartbeat before
	// the heartbeat sweep considers it offline. Default: 30 s.
	WorkerTimeout time.Duration

	// BusUpSince reports when the message bus connection was last established
	// or re-established, and the zero time while it is down. Worker heartbeats
	// and running-reports travel over that bus, so while it is down (or has
	// just come back) their absence says nothing about the workers: the
	// liveness sweeps decide nothing until the bus has been up for
	// BusReconnectGrace. Nil means no grace: every sweep acts on what the
	// store holds. Not a tuning knob; the server wires it from its bus client.
	BusUpSince func() time.Time

	// BusInterruptedAt reports the latest moment the bus connection or one of
	// the scheduler's consumers was interrupted, and the zero time if none has
	// been. Messages the broker sent during an interruption are redelivered
	// only after the consumer's AckWait, so the ingest trackers are held for
	// that long after it. Nil means no interruption is ever seen. Not a tuning
	// knob; the server wires it from its bus client.
	BusInterruptedAt func() time.Time

	// BusReconnectGrace is how long the bus must have been up before the
	// liveness sweeps act on heartbeats again. It must cover the time a live
	// worker needs to notice the outage ended, redial and heartbeat, which is
	// longer than WorkerTimeout when workers back off between redials. A value
	// <= 0 is coerced to WorkerTimeout in [New]; the server sets a larger
	// value derived from the workers' reconnect behavior. Unused when
	// BusUpSince is nil.
	BusReconnectGrace time.Duration

	// HeartbeatSweepInterval is how often the heartbeat sweep runs. Should be
	// well below WorkerTimeout so stale workers are caught promptly. Default: 15 s.
	HeartbeatSweepInterval time.Duration

	// AssignedTaskTimeout is the maximum time a task may sit in 'assigned'
	// without transitioning to 'running' before the reaper returns it to the
	// ready queue. It guards the brief leased→running window: a task a worker
	// leased but never reported running (e.g. the worker crashed between lease
	// and process start). The heartbeat sweep cannot recover such tasks while the
	// worker is still heartbeating, so this reaper runs independently on the
	// heartbeat sweep tick. Default: 30 s.
	AssignedTaskTimeout time.Duration

	// OfflineWorkerRetention is how long a worker may remain in
	// [store.WorkerStatusOffline] before the retention sweep hard-deletes it,
	// bounding the growth of the worker table on farms with ephemeral nodes.
	// Disabled and online workers are never auto-removed. A value <= 0 disables
	// the sweep entirely. Default: 24 h.
	OfflineWorkerRetention time.Duration

	// JobRetention is how long a terminal job is kept before the retention
	// sweep hard-deletes it and all of its data (steps, tasks, attempts, logs).
	// completed and canceled jobs are always eligible; failed jobs only when
	// JobRetentionIncludeFailed is set. A value <= 0 disables the sweep.
	// Default: 168 h (7 days).
	JobRetention time.Duration

	// JobRetentionIncludeFailed extends the retention sweep to failed jobs.
	// Default: false (failed jobs are kept for debugging).
	JobRetentionIncludeFailed bool

	// UnschedulableGrace is how long a ready task may wait with no eligible
	// online worker before it is flagged unschedulable (surfaced in the
	// API/UI). A value <= 0 disables the sweep entirely. Unlike the other
	// duration knobs above, it is not coerced up to the default in [New], since
	// 0 is a legitimate "off" setting. Default: 30 s.
	UnschedulableGrace time.Duration

	// ReconcileGrace is how long a live worker may go without reporting an
	// attempt it holds before the sweep reclaims that attempt (see
	// attemptreconcile.go). 0 disables reconciliation; like
	// UnschedulableGrace, [New] does not coerce it up to the default, but it
	// raises a positive value below WorkerTimeout to WorkerTimeout. Reports
	// are trusted only when the worker's timestamp is within WorkerTimeout of
	// their receipt. Default: 2 m.
	ReconcileGrace time.Duration

	// DefaultMaxAttempts is the server-level fallback tier of the layered
	// retry policy (Server -> Farm -> Queue -> Job): the farm-wide default
	// number of attempts a task may make before going terminal-failed. A
	// value <= 0 is coerced up to the [DefaultConfig] value in [New], since
	// unlike UnschedulableGrace this knob has no meaningful "off" state (the
	// minimum valid value is 1, which disables auto-retry outright).
	// Default: 3.
	DefaultMaxAttempts int

	// RetryDelay is the server-level fallback default backoff before a
	// failed task re-enters the ready queue. 0 is a legitimate "immediate"
	// setting; only a negative value is coerced up to the [DefaultConfig]
	// value in [New]. Default: 30 s.
	RetryDelay time.Duration

	// DefaultFailureLimit is the server-level fallback default job-level
	// failure ceiling. 0 = off (no auto-park) and is a legitimate setting —
	// like UnschedulableGrace, it is not coerced up in [New]. Default: 0.
	DefaultFailureLimit int

	// ExprLimits are the OpenJD EXPR limits this server enforces when it
	// accepts a template (internal/config's openjd.expr_* keys). The scheduler
	// does not evaluate expressions; it uses them to compare against each
	// worker's advertised caps before dispatching an EXPR job (see
	// exprcaps.go). It must be the same value the submitter is built with, so
	// internal/server sets both from one field.
	//
	// Zero fields normalize to the defaults in [New].
	ExprLimits openjd.ExprLimits

	// NATSAuthEnabled mirrors config.NATSAuthConfig.Enabled (server.Config's
	// NATSAuthEnabled). It gates two things here: whether worker registration
	// touches the worker's broker-credential LastSeenAt, and where a worker's
	// capacity-group membership comes from (its credential when on, its
	// worker.capacity_group setting when off; see capacitymembership.go).
	// With broker authentication off there are no credential rows, and
	// registration does no extra store work (see handleWorkerRegister).
	NATSAuthEnabled bool

	// RevokeWorker drops a removed ephemeral capacity-group member's broker
	// connection. The scheduler calls it after the store has deleted the
	// worker, which revoked its credential in the same transaction, so an
	// implementation must not revoke again by worker ID: that could revoke a
	// credential enrolled under the same ID since. It runs on a goroutine of
	// its own, because dropping a broker connection takes seconds. Nil means
	// the store's revocation alone applies. Not a tuning knob; the server
	// wires it.
	RevokeWorker func(ctx context.Context, workerID string) error

	// ScriptProviders are the capacity provider programs from the server's
	// configuration file, by name without the "script:" prefix. A group
	// naming one that is not here does not act. Not a tuning knob; the
	// server wires it.
	ScriptProviders map[string]script.Provider

	// WakeOnLANPort is the UDP port magic packets go to. A value <= 0 is
	// coerced to [wol.DefaultPort] in [New].
	WakeOnLANPort int

	// WakeOnLANSendTo are extra "ip:port" endpoints the server sends magic
	// packets to when it sends them itself.
	WakeOnLANSendTo []string

	// SendWakePackets sends magic packets for macs to each of targets
	// ("ip:port") and reports how many targets it reached, with an error
	// joining every failure. Nil means [wol.Send] with its default burst and
	// gap.
	SendWakePackets func(ctx context.Context, macs []net.HardwareAddr, targets []string) (int, error)

	// OnFenced is called once, with the error, the first time a store write
	// made under the context [Scheduler.Run] was given fails with
	// [store.ErrFenced]: another server has taken the leadership, so this one
	// must stop. It runs on a goroutine of its own and may call
	// [Scheduler.Stop] and wait for Run to return. By then the scheduler has
	// already stopped acknowledging messages and leasing tasks (see
	// fence.go). Nil means the loss is only logged. Not a tuning knob; the
	// server wires it when scheduler high availability is on.
	OnFenced func(error)
}

Config holds tuning parameters for the Scheduler.

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns a Config with the default values.

type RetryPolicy added in v0.2.0

type RetryPolicy struct {
	MaxAttempts  int           // total genuine tries before terminal-fail (>= 1)
	RetryDelay   time.Duration // backoff before re-queue (>= 0)
	FailureLimit int           // job-level ceiling; 0 = off
}

RetryPolicy is the resolved, effective retry configuration for a task.

func ResolveRetryPolicy added in v0.2.0

func ResolveRetryPolicy(job store.Job, queue store.Queue, farm store.Farm, def RetryPolicy) RetryPolicy

ResolveRetryPolicy computes the effective policy as the first non-nil of Job -> Queue -> Farm for each knob, falling back to the server default def. Out-of-range values are clamped to sane bounds as a last-line defense (the API layer rejects them at write time). Exported so the REST layer can report the resolved policy (effective_retry) a job runs under.

type Scheduler

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

Scheduler owns the assignment loop, worker registry, and heartbeat sweep. Create it with New and drive it with [Run].

func New

func New(cfg Config, st store.Store, busClient busClient, m *metrics.Metrics, logger *slog.Logger, notifier ws.Notifier, diagBuf *diag.Buffer) *Scheduler

New creates a Scheduler. Call [Run] to start its goroutines.

notifier receives live-event notifications after each state change so the WebSocket hub can fan them out to subscribed clients. Pass ws.NoopNotifier (or nil, which is treated as NoopNotifier) when no WebSocket hub is wired.

m receives the scheduler's metrics. Nil is treated as a fresh metrics.New, so the scheduler never checks for it.

diagBuf, when non-nil, enables worker diagnostic-log ingestion: the scheduler subscribes to worker.diag.> and appends records under "worker:<id>". Pass nil to disable diagnostics.

func (*Scheduler) AbandonCapacityCalls added in v0.4.0

func (s *Scheduler) AbandonCapacityCalls()

AbandonCapacityCalls cancels the provider calls still running and closes their write gate. A server that stops waiting for Scheduler.Run calls it before it closes the store, so no provider call still running writes to a closed store. The cancel comes first: a write already under way, which the close waits for, may be on a connection to a database that will never answer, and only its context ends it. Calling it again, or after Run has returned, does nothing more.

func (*Scheduler) CancelJob

func (s *Scheduler) CancelJob(ctx context.Context, jobID string) error

CancelJob cancels every non-terminal task of the given job, closes their running attempts and releases their usage claims in one store transaction (invariant I3), then publishes a cancel signal to each worker that was actively executing one of the tasks.

The durable "canceled by user" reason is stamped in the same transaction, only on tasks with no reason yet, so a more specific cause already recorded (e.g. a cascade-cancel's "canceled: upstream step failed") is never clobbered.

The same transaction also finalizes the job's steps and moves the job itself to canceled, unless it is already completed, failed or canceled, so a job cancel is one write. A caller's later store.JobStore.CancelJobStatus (the REST handler makes one) is an idempotent confirmation that reports a job that had already completed or failed.

The method is idempotent: if all tasks are already in terminal states the store operation changes nothing and no NATS messages are published.

func (*Scheduler) CancelTask

func (s *Scheduler) CancelTask(ctx context.Context, taskID string) error

CancelTask cancels a single task, closes its running attempt and releases its usage claims in one store transaction (invariant I3), then publishes a cancel signal to the worker that held the task at that moment.

If the task is already in a terminal state (succeeded, failed, canceled), CancelTask returns nil without modifying any state. That holds whether the terminal state was visible up front or the task reached it mid-cancel: the store decides inside its transaction and reports a terminal task as "not canceled", so losing that race is reported the same way as never having had it. Any other store failure propagates. It then drives step and job completion, as a terminal report does.

func (*Scheduler) CapacityStatus added in v0.4.0

func (s *Scheduler) CapacityStatus(groupID string) (capacity.Status, bool)

CapacityStatus returns the last evaluation of the enabled group groupID, and false when there is none: before the first sweep, or when the group is disabled, deleted or in another farm. Safe for concurrent use.

func (*Scheduler) NoteWorkerRevoked added in v0.4.0

func (s *Scheduler) NoteWorkerRevoked(workerID string)

NoteWorkerRevoked records that workerID's broker credential was revoked, so the worker is leased nothing from now on: neither a request it parked before the revoke, which would otherwise be served once work arrived although the revoke disconnected the worker, nor a new one from a connection the broker cannot close (an external broker with no system credential keeps it until its user JWT expires). The record lives in this process; it ends when the worker registers with an active credential, which only a worker enrolled again can do. With broker authentication off it records nothing: there is no connection to revoke and no credential a registration could confirm.

func (*Scheduler) ReconcileBlockedJob added in v0.4.0

func (s *Scheduler) ReconcileBlockedJob(ctx context.Context, jobID string) error

ReconcileBlockedJob evaluates one job's cross-job dependencies and either releases it (all upstreams completed), cancels it (any upstream failed, canceled, or deleted), or leaves it blocked (some upstream still running). A job that is not blocked is left alone. Besides the sweep and ReconcileDependents, the job PATCH handler calls it after a resume, so a job that resumed to blocked is decided at once rather than at the next sweep.

func (*Scheduler) ReconcileDependents added in v0.2.0

func (s *Scheduler) ReconcileDependents(ctx context.Context, upstreamJobID string) error

ReconcileDependents re-evaluates every job blocked on upstreamJobID after that upstream changed state (completed, failed, canceled, or deleted). Each still- blocked dependent is released or canceled by ReconcileBlockedJob.

func (*Scheduler) RetryDefaults added in v0.2.0

func (s *Scheduler) RetryDefaults() RetryPolicy

RetryDefaults returns the server-level fallback retry policy from config. Exported so the server can hand the same defaults to the REST layer for effective-policy reporting.

func (*Scheduler) RetryJob

func (s *Scheduler) RetryJob(ctx context.Context, jobID string) (int, error)

RetryJob revives every failed/canceled task in the job. It returns the number of tasks revived (0 when none were eligible — an idempotent no-op).

func (*Scheduler) RetryTask

func (s *Scheduler) RetryTask(ctx context.Context, taskID string) error

RetryTask revives a single failed/canceled task, looking up its job to drive dependency re-resolution.

func (*Scheduler) Run

func (s *Scheduler) Run(ctx context.Context) error

Run starts all scheduler goroutines and blocks until ctx is canceled. It returns after all goroutines have exited cleanly.

ctx is the context every handler, sweep and lease writes under. Under scheduler high availability it carries the leader's epoch (store.WithLeaderEpoch), so a write made after another server took over fails with store.ErrFenced (see fence.go).

A Run that starts after [Stop] returns nil at once, starting nothing.

func (*Scheduler) StartDiag added in v0.4.0

func (s *Scheduler) StartDiag() error

StartDiag starts the worker.diag.> subscription that feeds the diagnostic buffer, ahead of Scheduler.Run. A standby server calls it so that it collects worker diagnostics while it waits, and has their recent history already when it becomes the leader. Run starts the subscription itself when StartDiag has not, so a server without HA need not call it. It is a no-op when diagnostics are disabled (diagBuf nil) or the subscription is already running; after an error, the next StartDiag or Run tries again.

func (*Scheduler) Stop

func (s *Scheduler) Stop()

Stop cancels the scheduler's internal context, triggering a clean shutdown. It does not wait for goroutines to finish — that happens inside [Run]. It may be called before Run, from any goroutine; that Run then returns at once.

func (*Scheduler) StopTimeout added in v0.4.0

func (s *Scheduler) StopTimeout() time.Duration

StopTimeout bounds how long Scheduler.Run waits, once its context ends, for the calls it drains before returning: capacity provider calls (see [Scheduler.capacityDrainTimeout]) and then broker revocations of removed workers. It stays below StopCeiling whatever the providers' timeouts.

func (*Scheduler) WakeQueue

func (s *Scheduler) WakeQueue(queueID string)

WakeQueue wakes any parked lease waiters on queueID. Called by the API job handler after a successful submission so newly-ready tasks are leased without waiting out the long-poll hold. It also wakes queue-unaffiliated workers parked under bus.WildcardQueueToken, since they are eligible for any queue's work.

func (*Scheduler) WakeWorker added in v0.4.0

func (s *Scheduler) WakeWorker(workerID string)

WakeWorker wakes the lease requests a worker that may not take new work (disabled, retiring or asleep) has parked, so a worker that has just become able to is leased work at once rather than after the rest of its leaseHoldTimeout. Called by the API's enable handler after the write, and when a woken capacity-group member registers ([Scheduler.noteMemberWoke]). A woken request re-reads the worker, so a wake for a worker that still may not take work leases nothing.

Jump to

Keyboard shortcuts

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