Documentation
¶
Overview ¶
Package jobs is the machine job API's record (migration 0037): one-shot jobs an external orchestrator submits — "run this prompt on this agent, optionally at this commit, and give me the result" — and reads back by id.
The package holds the row, its store and the one rule every caller must agree on: how the outcome of a turn becomes a job's terminal status (Classify). Running the turn is internal/api's (jobs.go there), because a turn needs the agent gateway and the chat store, which this package deliberately does not import.
🔴 EVERY METHOD EXCEPT ReapOverdue RUNS UNDER THE CALLER'S PRINCIPAL. jobs is under FORCE row-level security, so a caller reads and writes only its own user's rows; the owner of a row is the principal's user (owner_id's default), never a parameter. ReapOverdue is the reaper across every owner and runs under the system principal itself (sys).
🔴 A JOB IS FAILED BY THE REAPER ONLY WHEN IT IS PAST ITS OWN DEADLINE, NEVER BECAUSE A PROCESS STARTED. During a rolling update the new process boots while the old one is still running jobs, so "fail whatever is unfinished at boot" would fail a live job and drop its real result. The reaper instead fails a running job only once started_at + timeout_s + ReapSlack has passed, and a queued one only once created_at + MaxQueueWait has — points no live runner can still be before (see each constant). The same pass covers every other way a job can be left unfinished: a process that exited mid-job, a recovered panic, an outcome write that kept failing.
Index ¶
- Constants
- Variables
- func ValidRepo(s string) bool
- func ValidResultPath(p string) bool
- func ValidSHA(s string) bool
- type ActiveCount
- type ChooseFunc
- type Failover
- type Job
- type NewJob
- type Outcome
- type PGStore
- func (s *PGStore) ByIdempotencyKey(ctx context.Context, key string) (Job, error)
- func (s *PGStore) Create(ctx context.Context, n NewJob) (Job, bool, error)
- func (s *PGStore) CreateChosen(ctx context.Context, n NewJob, candidates []int64, choose ChooseFunc) (Job, bool, error)
- func (s *PGStore) Finish(ctx context.Context, id int64, o Outcome) (bool, error)
- func (s *PGStore) Get(ctx context.Context, id int64) (Job, error)
- func (s *PGStore) ReapOverdue(ctx context.Context, now time.Time) (int64, error)
- func (s *PGStore) Requeue(ctx context.Context, id int64, f Failover) (bool, error)
- func (s *PGStore) Start(ctx context.Context, id int64, ccAccount string, sessionID int64) (bool, error)
- type Requeuer
- type Store
Constants ¶
const ( StatusQueued = "queued" StatusRunning = "running" StatusSucceeded = "succeeded" StatusFailed = "failed" StatusTimedOut = "timed_out" )
Statuses. A job moves queued → running → one of the three terminal ones, or queued → failed when it never started.
const ( // ReasonTimeout: the job's own timeout_s elapsed. ReasonTimeout = "timeout" // ReasonInterrupted: nothing finished the job by its deadline, so the reaper // (ReapOverdue) failed it — the process running it stopped, panicked or could // not record the outcome. The token predates the reaper and is kept so a // caller branching on it sees no change. ReasonInterrupted = "interrupted" // was due to start (deleted since, or the store failed). ReasonAgentUnavailable = "agent_unavailable" // ReasonCheckoutFailed: the job's worktree at its sha could not be made (the // commit could not be fetched, the default branch could not be resolved or // carries a symlink among the overlaid paths, or git failed). The token // predates worktrees, when a sha job moved the agent's own checkout, and is // kept so a caller branching on it sees no change. ReasonCheckoutFailed = "checkout_failed" // ReasonWorkdirUnconfirmed: a sha job's turn succeeded but the agent's // runtime did not confirm it ran in the job's worktree — an agent image too // old for sha jobs — so its output was discarded. ReasonWorkdirUnconfirmed = "workdir_unconfirmed" // ReasonModelUnconfirmed: a model job's turn succeeded but the agent's // runtime did not confirm it ran the turn in a session CLI of the job's own // (no agents.HeaderCCWorkdirUsed, which ccd sends only from such a CLI) — an // agent image that ignores the session and model headers would have run it // in the agent's primary CLI on that CLI's model — so its output was // discarded. ReasonModelUnconfirmed = "model_unconfirmed" // ReasonResultReadFailed: the turn succeeded but result_path could not be read. ReasonResultReadFailed = "result_read_failed" // ReasonEmptyReply: the turn succeeded with no reply text and no result_path // was asked for, so there is no result to return. ReasonEmptyReply = "empty_reply" // ReasonTurnFailed: the turn failed with an error the runtime did not type. ReasonTurnFailed = "turn_failed" // ReasonInternal: muster itself failed around the turn (a store write). ReasonInternal = "internal" )
Reasons a job did not succeed that this package and its runner produce themselves. A failure the agent runtime reported carries the runtime's own typed failure instead (cmd/ccd's failure.go vocabulary: rate_limited, auth_failed, busy, capacity, …), so a caller can branch on exactly the token ccd wrote — above all on rate_limited and auth_failed, which mean "re-queue on another account".
const ( // MaxPromptBytes bounds a job's prompt. MaxPromptBytes = 64 << 10 // MaxResultBytes bounds a stored result: the reply, or the file read back. MaxResultBytes = 1 << 20 // MaxErrorBytes bounds a stored error message. MaxErrorBytes = 4096 // DefaultTimeoutSeconds is a job's timeout when the request names none. DefaultTimeoutSeconds = 30 * 60 // MaxTimeoutSeconds is the longest timeout a job may ask for: the claude-code // kind's per-request budget (agents.ClaudeCodeTurnTimeout), so the job's own // deadline, not the HTTP client's, is always what ends an overlong turn. MaxTimeoutSeconds = int(agents.ClaudeCodeTurnTimeout / time.Second) // MaxIdempotencyKeyBytes bounds an idempotency key. MaxIdempotencyKeyBytes = 128 // MaxActivePerAgent is how many of one agent's jobs may be queued or running // at once; a submission past it is refused (ErrAgentAtCapacity). Jobs on one // agent run one at a time, so this is also what bounds a queued job's wait // (MaxQueueWait). MaxActivePerAgent = 4 )
Bounds. Each is also a CHECK in migration 0037.
const ( // ReapSlack is how long past a running job's own deadline (started_at + // timeout_s) the reaper waits before failing it. A live runner is done by // then: the job's context ends the checkout, the turn and the read at the // deadline, and recording the outcome is a few bounded write attempts // (internal/api's jobFinishAttempts × jobFinishTimeout, well under a minute). // The rest is margin for clock skew between the processes and the database. ReapSlack = 5 * time.Minute // MaxQueueWait is how long a job may stay queued (from created_at) before the // reaper fails it. A queued job waits for the jobs ahead of it on the same // agent, at most MaxActivePerAgent−1 of them, each running for at most // MaxTimeoutSeconds + ReapSlack; one job's worth more is margin. With the // values above it is 2h40m. MaxQueueWait = MaxActivePerAgent * (time.Duration(MaxTimeoutSeconds)*time.Second + ReapSlack) )
The reaper's deadlines (ReapOverdue).
const ( // AbandonedRunningError is a running job's. AbandonedRunningError = "nothing recorded this job's outcome by its deadline (timeout_s plus a grace period): " + "the server running it stopped, crashed or could not record the outcome. The agent may have done some " + "or all of the work, so re-submit it only if repeating that is safe" // AbandonedQueuedError is a queued job's. AbandonedQueuedError = "this job never started within the longest a queued job can wait: the server holding " + "it stopped or crashed before running it. Nothing was sent to the agent for it" )
The errors ReapOverdue records.
const ( // ShutdownQueuedError is a queued job's. ShutdownQueuedError = "the server holding this job shut down before starting it. Nothing was sent to the agent for it, so it is safe to re-submit" // ShutdownRunningError is a running job's. ShutdownRunningError = "the server running this job shut down before the agent's turn finished. The agent may have done some " + "or all of the work, so re-submit it only if repeating that is safe" )
The errors a graceful shutdown records on the jobs the stopping process held (internal/api FailOwnJobs).
const MaxFailovers = 16
MaxFailovers bounds a job's re-queues (migration 0066's jobs_failovers_check); with at most once per FROM account a job reaches it only with that many accounts.
const MaxPR = 1<<31 - 1
MaxPR bounds a pull request number.
Variables ¶
var ErrAgentAtCapacity = errors.New("jobs: the agent has too many jobs queued or running")
ErrAgentAtCapacity is Create's answer when the agent already has MaxActivePerAgent jobs queued or running.
var ErrNotFound = errors.New("jobs: no such job")
ErrNotFound is Get's answer for an id the caller cannot see.
Functions ¶
func ValidResultPath ¶
ValidResultPath reports whether p may be a job's result_path: a non-empty, relative, already-clean path with no ".", ".." or ".git" element, at most 512 bytes, and no NUL. It is resolved against the agent's working directory.
⚠ IT CHECKS THE PATH STRING ONLY. It keeps the lexical path inside the working directory; it does not stop a symlink at or under that path from pointing outside it, and the read follows symlinks.
Types ¶
type ActiveCount ¶
type ActiveCount struct {
Queued, Running int
}
ActiveCount is how many of one agent's jobs are queued and running.
func (ActiveCount) Active ¶
func (c ActiveCount) Active() int
Active is Queued + Running: what MaxActivePerAgent bounds.
type ChooseFunc ¶
type ChooseFunc func(active map[int64]ActiveCount) (NewJob, error)
ChooseFunc is CreateChosen's choice: given each candidate's queued and running jobs, the job to record, or an error that refuses the submission.
type Failover ¶ added in v0.114.0
type Failover struct {
From string `json:"from"`
To string `json:"to"`
Reason string `json:"reason"`
At time.Time `json:"at"`
}
Failover is one re-queue of a job after its agent was moved off the Claude account its turn hit a limit on (internal/ccfailover).
type Job ¶
type Job struct {
ID int64
AgentID int64 // 0 once the agent is deleted
Agent string
// WorkerPool is the pool the job was submitted to ("" when it named its
// agent); Agent is the member the pool chose.
WorkerPool string
Prompt string
Repo string
SHA string
// PR is the pull request a sha job's commit is on (0 without a sha).
PR int
ResultPath string
TimeoutSeconds int
IdempotencyKey string
// Model is the Claude model the job's turn runs on ("" = the CLI's default).
Model string
// ConfigRef is the commit a sha job's worktree takes its agent
// configuration from ("" = the default branch).
ConfigRef string
// BaseSHA is a commit a sha job's turn may diff against ("" = none): it is
// fetched with the head's credential path into refs/muster-jobs/<id>-base.
BaseSHA string
RequestedBy string
Status string
// Result is set only on a succeeded job (HasResult), verbatim.
Result string
HasResult bool
Reason string
Error string
CCAccount string
SessionID int64
CreatedAt time.Time
// StartedAt and FinishedAt are zero until set.
StartedAt time.Time
FinishedAt time.Time
// Failovers are the account failovers the job was re-queued for, oldest
// first (jobs.failovers, migration 0066).
Failovers []Failover
}
Job is one row.
type NewJob ¶
type NewJob struct {
AgentID int64
Agent string
WorkerPool string
Prompt string
Repo string
SHA string
PR int
ResultPath string
TimeoutSeconds int
IdempotencyKey string
Model string
ConfigRef string
BaseSHA string
RequestedBy string
}
NewJob is what a submission records.
type Outcome ¶
Outcome is how a job ended: a terminal status, and either a result (succeeded) or a reason and an error message (failed, timed_out). A succeeded outcome may also carry an error: a note that does not change the status (its result file could not be deleted).
func Classify ¶
Classify turns a finished turn into a job outcome. reply and err are the turn's; deadline reports whether the job's own deadline had passed when the turn returned (ctx.Err() == context.DeadlineExceeded). On success the reply is the result; a caller that returns a file instead replaces it afterwards.
🔴 THE ORDER IS THE CONTRACT. A deadline wins over the error it caused (an aborted request surfaces as some transport error, and "timed_out" is the fact a caller can act on). A runtime's TYPED failure is reported by its own token, unchanged — rate_limited and auth_failed are what a caller re-queues on, so they must never be folded into a generic failure.
type PGStore ¶
type PGStore struct {
// contains filtered or unexported fields
}
PGStore is Store on Postgres.
func (*PGStore) ByIdempotencyKey ¶
ByIdempotencyKey is the caller's job recorded with key.
func (*PGStore) Create ¶
Create records a queued job, or answers the caller's existing job for the same idempotency key.
🔴 THE CAPACITY COUNT AND THE INSERT ARE ONE TRANSACTION UNDER A PER-AGENT ADVISORY LOCK, so two concurrent submissions cannot both see room for one. MaxQueueWait is derived from the cap, so a cap that could be overshot would let the reaper fail a job that was legitimately still waiting.
func (*PGStore) CreateChosen ¶
func (s *PGStore) CreateChosen(ctx context.Context, n NewJob, candidates []int64, choose ChooseFunc) (Job, bool, error)
CreateChosen records a job on the agent choose picks from candidates.
🔴 THE READ CHOOSE DECIDES ON AND THE INSERT ARE ONE TRANSACTION UNDER EVERY CANDIDATE'S PER-AGENT LOCK — the same lock Create takes for one agent. A pool choice read outside it let concurrent submissions all read the same queues and all pick the same worker: six submitted at once to two idle workers with four places each sent four to one, whose cap refused the other two with a 429 while the second worker sat idle. Under the locks each submission reads the queues the ones before it left, so choose sees every job it competes with, a named submission to a candidate included. The locks are taken in one global order (ascending key), so two choices over overlapping candidates cannot deadlock, and a named submission takes only one.
func (*PGStore) ReapOverdue ¶
ReapOverdue fails every job past its own deadline at now, across every owner, under the system principal (sys) whatever ctx carries.
type Requeuer ¶ added in v0.114.0
type Requeuer interface {
// Requeue moves running job id back to queued, appending f to its
// failovers, and reports whether it did: false when the job is not running
// any more, already holds a failover FROM f.From (at most once per account
// per job), or holds MaxFailovers.
Requeue(ctx context.Context, id int64, f Failover) (bool, error)
}
Requeuer is the store's conditional re-queue, asserted by the job runner rather than added to Store: a store without it re-queues nothing, and a job whose account failed is failed as before.
type Store ¶
type Store interface {
// Create records a queued job. With an idempotency key the caller already
// used, it records nothing and returns that job with created == false. It
// refuses with ErrAgentAtCapacity when the agent already has
// MaxActivePerAgent jobs queued or running (a repeated key is answered
// first, so a retry of an accepted job is never refused).
Create(ctx context.Context, n NewJob) (j Job, created bool, err error)
// CreateChosen is Create for a job whose agent is chosen from candidates by
// what they hold: it reads each candidate's queued and running jobs and
// calls choose with them (an agent with none is absent), and records the
// job choose returns, whose AgentID must be one of candidates and whose
// IdempotencyKey must be n's. Nothing else can record a job on any of
// candidates between the read and the insert, so concurrent submissions
// each see the ones before them. With n's idempotency key already used it
// answers that job (created == false) without calling choose. An error from
// choose is returned unwrapped, and nothing is recorded.
CreateChosen(ctx context.Context, n NewJob, candidates []int64, choose ChooseFunc) (j Job, created bool, err error)
// Get is one of the caller's jobs, or ErrNotFound.
Get(ctx context.Context, id int64) (Job, error)
// ByIdempotencyKey is the caller's job recorded with key, or ErrNotFound.
ByIdempotencyKey(ctx context.Context, key string) (Job, error)
// Start moves a queued job to running, recording the Claude account and the
// chat session the turn runs on. It reports false when the job was not
// queued any more (the reaper failed it), and then the caller must not run
// it.
Start(ctx context.Context, id int64, ccAccount string, sessionID int64) (bool, error)
// Finish moves a queued or running job to o's terminal status. It reports
// false when the job had already finished, and changes nothing then.
Finish(ctx context.Context, id int64, o Outcome) (bool, error)
// ReapOverdue fails, with ReasonInterrupted and across every owner, each
// job that is past its own deadline at now: running with started_at +
// timeout_s + ReapSlack before now, or queued with created_at +
// MaxQueueWait before now. It returns how many. A job inside its deadline
// is never touched, so it is safe while another process is still running
// jobs (a rolling update). It runs under the system principal whatever ctx
// carries.
ReapOverdue(ctx context.Context, now time.Time) (int64, error)
}
Store is the jobs persistence.