github.com/rotari-dev/rotari/internal/projectrun

Overview

package projectrun // import "github.com/rotari-dev/rotari/internal/projectrun"

Package projectrun runs one project's queue against its on-disk state.

It owns the run lifecycle that the synchronous supervisor run, the async worker,
and cancellation finalization share: Begin records the run, moves the queue
into its command snapshot, and marks the project running, Execute plans and
executes the snapshot's jobs through internal/run and writes the run summary,
and Finish records final context, finalizes metadata, and releases the run lock.

Planning, dependency, retry, and lane rules stay in internal/run, file layout
in internal/state, and job execution in internal/executor. Services that live
outside the project directory, such as the run registry, config discovery,
webhooks, and failure diagnosis, are supplied by the caller.

Constants

const LoadSampleInterval = 10 * time.Second
    LoadSampleInterval is how often a running run appends a load sample.

Variables

var ErrNoPreviousRun = run.ErrNoReferenceRun
    ErrNoPreviousRun reports that a selection needs the project's last run but
    the project has none.

var ErrPlanChanged = errors.New("this run would execute other jobs than its preview")
    ErrPlanChanged refuses a run whose plan differs from the preview whose
    revision it was given.

Functions

func CheckRunPlanRevision(ifRevision, projectRevision string, planned PlannedRun) error
    CheckRunPlanRevision refuses planned when ifRevision is a preview's revision
    with another plan. A revision without a plan, such as `check` reports,
    guards only the project's state, which project.CheckRevision checked.

func CheckRunProjectRevision(paths state.ProjectPaths, ifRevision string) (string, error)
    CheckRunProjectRevision checks the project part of a run's ifRevision
    under the state lock, before the run is planned, and returns the project's
    revision; CheckRunPlanRevision checks the plan part after planning.

func ClassifyDefinitions(paths state.ProjectPaths, queue model.Queue, filter jobfilter.Filter, referenceRunID, mode string) (jobfilter.Filter, error)
    ClassifyDefinitions sets filter's changed and new job IDs by comparing queue
    with the command snapshot of referenceRunID, matched by mode (the --match-by
    modes; empty means id-and-fingerprint). Without a reference run every job
    is new. It returns filter unchanged when neither --filter-changed nor
    --filter-new is set. Callers resolve referenceRunID before Begin makes the
    new run the project's last run.

func FingerprintReferenceRun(paths state.ProjectPaths, requested string) (string, error)
    FingerprintReferenceRun selects the latest settled run for fingerprint
    matching when the caller did not provide one. The metadata fallback matches
    the existing latest-run resolution used by run planning.

func LoadOriginAttemptResult(store state.Store, paths state.ProjectPaths, origin model.JobOrigin) (model.JobResult, bool, error)
    LoadOriginAttemptResult reads the result of the exact attempt an origin
    names. It reports false when the attempt has not finished.

func PlanRevision(projectRevision string, planned PlannedRun) string
    PlanRevision is the revision a run preview reports: the project's revision
    and, after a dot, a hash of the jobs the plan executes and carries and the
    run it builds from. A run given this revision starts only while both still
    hold, so a start whose options select other jobs than its preview fails
    instead of running them.

func ReferenceRun(paths state.ProjectPaths, selection, requested string) (string, error)
    ReferenceRun returns the run whose results a selection falls back to for
    jobs without an origin: requested when given, otherwise the project's last
    run. It is empty without a selection or a previous run. Call it before
    Begin, which makes the new run the last one.

func SourceNotice(sourceRunID string, omitted []string, location string) string
    SourceNotice tells a run or retry preview that it uses the non-empty
    queue instead of the latest run sourceRunID, naming that run's failed or
    unfinished jobs the queue leaves out and the copy command that adds them.
    location is the --basedir/--project-name part of the command, as the caller
    can render it.

Types

type Check struct {
	// State is ready, empty, running, locked (running on another host or in
	// another PID namespace), or interrupted.
	State    string
	Runnable bool
	// RunID is the active or interrupted run, if any.
	RunID string
	// Queued counts the queued jobs when QueuedKnown is set: the queue of an
	// active or interrupted project may be unreadable.
	Queued      int
	QueuedKnown bool
	Lock        string
	// Revision is the project's revision, for --if-revision.
	Revision string
}
    Check is what `rotari check` reports about a project.

type Observer struct {
	// Progress is called for every job result, including retries.
	Progress func(result model.JobResult, completed, total, succeeded, failed int)
	// Started is called when a job attempt starts.
	Started func(job model.JobSpec)
	// Finished is called once when a job reaches its final result.
	Finished func(job model.JobSpec, result model.JobResult)
}
    Observer receives run progress. All fields are optional.

type Options struct {
	RunID            string
	RunName          string
	LocalConcurrency int
	BatchMaxActive   int
	Retry            int
	// Executor overrides the queue's default executor for jobs without one.
	Executor        string
	ExecutorOptions []string
	EnvMode         string
	Settings        executor.RunSettingsMap
	// Selection, JobIDs, Scope, Filter, SourceRunID, and PartialArray choose
	// which jobs execute and which carry a result forward; see run.PlanRerun.
	Selection    string
	JobIDs       []string
	Scope        model.CommandSelector
	Filter       jobfilter.Filter
	SourceRunID  string
	PartialArray bool
	MatchBy      string
}
    Options selects and configures the work of one run.

type PlanRequest struct {
	Executor        string
	ExecutorOptions []string
	Settings        executor.RunSettingsMap
	Selection       string
	JobIDs          []string
	Scope           model.CommandSelector
	Filter          jobfilter.Filter
	SourceRunID     string
	SourcePolicy    SourcePolicy
	// SourceProject, when it names another project, holds SourceRunID; see
	// sourceSnapshot.
	SourceProject string
	CopyAttempts  bool
	CopyJobIDs    []string
	PartialArray  bool
	MatchBy       string
}
    PlanRequest is what planning a run of a queue needs.

type PlannedRun struct {
	Queue               model.Queue
	Plan                run.Plan
	SourceRunID         string
	SnapshotFromSource  bool
	UsedQueueWithSource bool
	// OmittedSourceJobs are failed or unfinished jobs from SourceRunID that
	// are not represented by the non-empty queue used for this run.
	OmittedSourceJobs []string
	// Request is the request as planned, which the run executes with. A run
	// from another project's saved run has its selection applied already.
	Request PlanRequest
}
    PlannedRun is a planned run: the queue it runs, with fingerprint matches
    applied, which of its jobs execute and which carry results, and the resolved
    reference run.

type Runner struct {
	Store     state.Store
	Executors executor.Registry
	// NewJobID supplies IDs for matrix groups and jobs copied into run snapshots.
	NewJobID func() string
	// Logf receives job submission, completion, and failure lines.
	Logf func(string, ...any)
	// Errorf reports a run that failed to prepare or record its jobs; the run
	// still finishes with a failing exit code. Optional.
	Errorf func(string, ...any)

	// Environment names the variables exported to every job.
	Environment run.EnvironmentNames
	// AttemptIDName names the variable that carries a job's attempt ID.
	AttemptIDName string
	// PropagatedVariables are copied from the runner's environment into jobs.
	PropagatedVariables []string

	// ConfigPaths lists the loaded config and notification files for a run;
	// Begin snapshots them into the run directory. Optional.
	ConfigPaths func(paths state.ProjectPaths, configPath string) []string
	// RegisterRun records where runID lives so other commands can find it.
	// Optional.
	RegisterRun func(paths state.ProjectPaths, runID string) error
	// Diagnose attaches failure diagnoses to a result before the summary is
	// written. Optional.
	Diagnose func(runDir string, result model.JobResult) model.JobResult
	// JobFinished is called once for each job's diagnosis-enriched final result.
	// Optional.
	JobFinished func(paths state.ProjectPaths, runID, runName string, job model.JobSpec, result model.JobResult)
	// RunFinished is called after the project is finalized. Optional.
	RunFinished func(paths state.ProjectPaths, runID string, exitCode int)
	// ExecutionEnded is called by Run once the jobs have ended, before
	// Finish finalizes the project and removes the run lock. Optional.
	ExecutionEnded func(paths state.ProjectPaths)

	// Now returns the current time; nil means time.Now.
	Now func() time.Time
	// Binary is the rotari binary the coordinator runs, recorded in the run context so
	// that a later command can say when it is another one. Optional.
	Binary *model.RunBinary
}
    Runner runs project queues. The zero value is not usable; every field except
    the optional hooks must be set.

func (runner Runner) AssignAttemptIDs(jobs []model.JobSpec, runID string, attempt int)
    AssignAttemptIDs gives each job a new attempt ID for the given attempt
    number and points its environment at the attempt directory.

func (runner Runner) Begin(paths state.ProjectPaths, start Start) error
    Begin records a new run, moves the queue into it, and marks the project
    running. The caller must hold the project's state lock and have checked that
    the project is idle.

    The run context and the queue's command snapshot are written before the
    run lock and metadata, so a project that looks running always has its
    context.json and commands.json. The queue is emptied last, keeping its
    defaults: a crash before that leaves the jobs queued beside an interrupted
    run instead of losing them. Begin takes the run lock for the current
    process; a caller that hands the run to another process rewrites the lock
    with that process's PID.

func (runner Runner) Check(paths state.ProjectPaths, deep func(model.Queue) error) (Check, error)
    Check reports whether the project's queued run can start, without changing
    state. A ready queue must pass ValidateQueue; deep, when set, adds checks
    that need the current host, such as finding the jobs' executables.

func (runner Runner) Execute(paths state.ProjectPaths, options Options, observer Observer) (int, error)
    Execute reads the command snapshot Begin took from the queue, plans the
    selected work, runs local and batch jobs through the shared run engine,
    and writes the run summary. It returns the run's exit code. An error means
    the run could not be prepared or recorded; its exit code is then 1.

func (runner Runner) Finalize(paths state.ProjectPaths, runID string, exitCode int) error
    Finalize marks the project finished with the run's exit code. It verifies,
    under the state lock, that the run lock still belongs to runID. It leaves
    the queue alone, since Begin already took the run's jobs from it and later
    edits belong to the next run, and it does not remove the run lock.

func (runner Runner) Finish(paths state.ProjectPaths, runID string, exitCode int) error
    Finish records the run's final context, finalizes the project, and removes
    the run lock. When the project cannot be finalized, the lock is still
    removed so the project reads as interrupted rather than running.

func (runner Runner) FinishContext(paths state.ProjectPaths, runID string) error
    FinishContext adds the load at the end of a run to its context.

func (runner Runner) LoadQueue(paths state.ProjectPaths, requestedExecutor string, executorOptions []string, settings executor.RunSettingsMap) (model.Queue, error)
    LoadQueue loads the project's queue and checks that it can run; see
    ValidateQueue.

func (runner Runner) MatchFingerprintQueue(paths state.ProjectPaths, queue model.Queue, mode, sourceRunID string) (model.Queue, error)
    MatchFingerprintQueue enriches queue commands with origins found in a
    historical queue. Fingerprints are calculated from both queues each time;
    no fingerprint is persisted.

func (runner Runner) OmittedFailedOrUnfinished(paths state.ProjectPaths, queue model.Queue, sourceRunID string) ([]string, error)
    OmittedFailedOrUnfinished reports source-run jobs selected by the shared
    failed/unfinished selection rule that are not represented in queue by ID
    or provenance. It selects recorded results, not an expanded execution plan:
    successful dependents must not be counted as failed or unfinished work.

func (runner Runner) PlanRun(paths state.ProjectPaths, queue model.Queue, request PlanRequest) (PlannedRun, error)
    PlanRun plans a run of queue as the run itself will: it validates the queue,
    resolves the reference run, applies fingerprint matching, and plans the
    selection. A run request and a preview of it both use it, so the preview
    shows what the run would do. The caller holds the project's state lock and
    has checked that the project is idle.

func (runner Runner) PlanSelection(paths state.ProjectPaths, queue model.Queue, selection string, jobIDs []string, scope model.CommandSelector, filter jobfilter.Filter, referenceRunID string, partialArray bool) (run.Plan, error)
    PlanSelection decides which of the queue's jobs a run executes, reading
    earlier results from the project's runs; see run.PlanRerun. referenceRunID
    comes from ReferenceRun.

func (runner Runner) PrepareJobEnvironments(paths state.ProjectPaths, options Options, jobs []model.JobSpec)
    PrepareJobEnvironments sets the rotari variables every job of the run sees.

func (runner Runner) PreviewRun(paths state.ProjectPaths, queue *model.Queue, request PlanRequest, ifRevision string) (PlannedRun, string, error)
    PreviewRun plans a run of the project without starting it, as a run would
    plan it under the state lock: the project must be idle and, when ifRevision
    is set, still at that revision, with the same plan when the revision is a
    preview's. queue, when set, replaces the project's queue, such as the queue
    a copy from the reference run would leave. It returns the plan and its
    revision, PlanRevision.

func (runner Runner) ResolveJobWorkingDirectories(paths state.ProjectPaths, options Options, jobs []model.JobSpec)

func (runner Runner) Run(paths state.ProjectPaths, options Options, observer Observer) (int, error)
    Run executes a run that Begin recorded and then finishes it. It samples
    load while the jobs run, and writes the run's heartbeat until the run is
    finished.

func (runner Runner) SetRunClientStatus(paths state.ProjectPaths, runID string, status model.RunClientStatus) error
    SetRunClientStatus records a connection transition for the active run.
    A summary or replacement lock means the run has already moved on.

func (runner Runner) ValidateQueue(queue model.Queue, requestedExecutor string, executorOptions []string, settings executor.RunSettingsMap) error
    ValidateQueue checks that queue can run: its jobs and dependencies are
    valid, every job's executor is known, and each job's executor options,
    after run-level defaults are applied, suit its executor.

func (runner Runner) WasExplicitlyCancelled(runDir, jobID string, result model.JobResult) bool
    WasExplicitlyCancelled reports whether a job's latest attempt was cancelled
    on purpose, which ends its retries for this run.

func (runner Runner) WriteContext(paths state.ProjectPaths, runID, cwd, configPath string, origin *model.LaunchOrigin, startedBy *model.StartedBy, snapshots ...*model.FileConfigSnapshot) error
    WriteContext records where and how a run starts: working directory, host,
    the launching process, load, and snapshots of the loaded command and
    notification configs.

type SourcePolicy string
    SourcePolicy says whether a run uses the current queue or constructs its
    snapshot from a saved run. CopyIfEmpty is resolved against the queue under
    the state lock, so a concurrent queue edit cannot change the decision.

const (
	SourceKeepQueue   SourcePolicy = "queue"
	SourceCopyIfEmpty SourcePolicy = "copy-if-empty"
	SourceCopyRun     SourcePolicy = "copy-run"
)
func RunSource(paths state.ProjectPaths, selection, requestedRunID string) (sourceRunID string, policy SourcePolicy, err error)
    RunSource describes the input requested by `rotari run` or `retry` without
    deciding from a potentially stale queue read. An explicit run is copied;
    a selection copies the latest run only if the queue is empty when the
    supervisor takes its state lock; a plain run, or a selection in a project
    without a previous run, keeps the queue. Planning then rejects a queued job
    whose result the selection needs and no run records.

type Start struct {
	RunID   string
	RunName string
	// Note, when not empty, is why the run is made; Begin records it as the
	// run's first note.
	Note string
	// ClientStatus records the initiating client's mode and initial state.
	ClientStatus model.RunClientStatus
	// Snapshot, when non-nil, is already built from a saved run. Begin writes
	// it to the new run and leaves queue.json untouched.
	Snapshot *model.Queue
	// CWD is the working directory the run was requested from.
	CWD string
	// ConfigPath is the command config file that the client loaded.
	ConfigPath string
	FileConfig *model.FileConfigSnapshot
	// LaunchOrigin is the process that ran the rotari command starting the
	// run, when a CLI client started it.
	LaunchOrigin *model.LaunchOrigin
	// StartedBy is how the run was started, recorded in its context.
	StartedBy *model.StartedBy
}
    Start identifies a run that Begin records.