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

Overview

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

Package state owns Rotari's filesystem-backed project state.

It reads and writes model values as durable JSON files, validates path elements,
lists run and attempt directories, and manages locks and other persistence
details. It should not decide run orchestration, retry policy, dependency
scheduling, or executor behavior.

Constants

const (
	BaseDirEnv = "ROTARI_BASEDIR"
)
const (
	StdoutFileName = "stdout"
	StderrFileName = "stderr"
	// SchedulerEventsFileName is a scheduler job's log of query outcomes.
	SchedulerEventsFileName = "scheduler_events.jsonl"
)
const ArtifactsFileName = "artifacts.json"
    ArtifactsFileName holds the artifact candidates discovered for an attempt
    when it started. It is best-effort metadata: an attempt without one has no
    discovery information, not no associated files.

const CancelsFileName = "cancels.jsonl"
    CancelsFileName is the run-directory file that records each cancel request
    of the run, one JSON line each, appended only.

const CarriedResultsFileName = "carried.json"
    CarriedResultsFileName is the run file in which a run records, before it
    dispatches any job, the results it carries forward from earlier runs instead
    of executing. It holds a model.RunSummary with only RunID and Results,
    and is read through LoadRunSummary until the run writes summary.json;
    see jobstatus.RecordedResults.

const DefaultProjectName = "default"
    DefaultProjectName is the project used when none is given and the base
    directory does not have exactly one.

const FinalResultFileName = "final_result.json"
    FinalResultFileName marks an attempt whose job will not be retried.

const HeartbeatClockMargin = time.Minute
    HeartbeatClockMargin is added to HeartbeatStaleAfter by a reader that
    compares a beat's own time with its clock, which another host's clock need
    not agree with.

const HeartbeatFileName = "heartbeat.json"
    HeartbeatFileName is the run-directory file a run's coordinator rewrites
    while the run is active, so a reader on any host can tell whether it is
    still writing.

const HeartbeatInterval = 30 * time.Second
    HeartbeatInterval is how often a coordinator rewrites its heartbeat.

const HeartbeatStaleAfter = 10 * HeartbeatInterval
    HeartbeatStaleAfter is how long a heartbeat may go unchanged before its run
    is called unresponsive: ten missed beats.

const LoadSamplesFileName = "load_samples.jsonl"
    LoadSamplesFileName is the run-directory file that holds a run's load
    samples.

const NoPIDNamespaces = "none"
    NoPIDNamespaces is the PID namespace recorded on a platform that has none,
    such as macOS and the BSDs, where every process on a host shares one PID
    space. Two records naming it on the same host are in the same PID space,
    so Locate verifies them as it verifies two equal Linux namespaces.
    A record written there by an older rotari has an empty namespace and stays
    unverified.

const ProgressFileName = "progress.jsonl"
const ProjectNameEnv = "ROTARI_PROJECT_NAME"
const ReadConcurrency = 16
    ReadConcurrency bounds how many independent reads ReadEach runs at once. On
    a shared file system each open, stat, and directory listing is a round trip,
    so reading independent files concurrently overlaps their latency.

const RunClientStatusFileName = "client_status.json"
const RunNotesFileName = "notes.jsonl"
    RunNotesFileName is the run file holding a run's notes, one JSON
    model.RunNote per line, in the order they were added. It is the one run file
    that changes after a run finishes, and only by appending.

const RunSourcesFileName = "sources.json"
    RunSourcesFileName is the run file in which a run records, before it
    dispatches any job, the version-control revisions its executed jobs run
    from. A run started before rotari recorded sources has none.

const StaleLockRemovalFileName = "stale_lock_removed.json"
    StaleLockRemovalFileName is the record, in a run's directory, of the reader
    that removed the run's stale lock.

Variables

var ErrBaseDirMissing = errors.New("basedir does not exist")
    ErrBaseDirMissing matches a BaseDirMissingError.

var ErrInvalidJSON = errors.New("invalid JSON")
var ErrNewerStateVersion = errors.New("state file is from a newer rotari")
    ErrNewerStateVersion reports a state file written by a newer rotari whose
    format this binary cannot read safely.

Functions

func AcquireRunLock(lockPath string, info model.LockInfo) error
    AcquireRunLock publishes info as the run lock at lockPath. It fails while
    another run holds an active or remote lock, and never replaces an existing
    lock file. The caller holds the state lock exclusively and has checked the
    project, so a stale lock left at lockPath is removed first.

func AcquireStateLock(lockPath string) (func(), error)
    AcquireStateLock takes the exclusive project state lock at lockPath and
    returns its release function.

func AcquireStateReadLock(lockPath string) (func(), error)
    AcquireStateReadLock takes the shared project state lock at lockPath.
    A missing lock file needs no lock.

func AppendCancelRecord(runDir string, record model.CancelRecord) error
    AppendCancelRecord appends record to runDir's cancels.jsonl.

func AppendLoadSample(path string, sample model.LoadSample) error
func AppendRunNote(runDir string, note model.RunNote) error
    AppendRunNote adds a note to the run in runDir. Each note is written with
    one append, so notes added at the same time do not interleave.

func AttemptJobDir(runDir string, job model.JobSpec) (string, error)
func AttemptSource(runDir, attemptDir string) (model.SourceRevision, bool)
    AttemptSource returns the recorded revision of the repository the attempt in
    attemptDir ran from: its working directory, from its command.json, matched
    against its run's sources. It returns false when either is not recorded.

func CheckRunVersions(runDir string) error
    CheckRunVersions returns ErrNewerStateVersion when the run's commands.json
    or summary.json was written by a newer rotari, and nil otherwise, leaving a
    missing or unreadable file to the caller. Readers that treat those files as
    optional call it first, so a newer file is refused instead of being read as
    absent.

func ContextPath(runDir string) string
func DefaultMeta() model.Meta
func DirectoryMode() os.FileMode
func Elsewhere(identity ProcessIdentity, observation ProcessObservation) error
    Elsewhere returns an *ElsewhereError when observation places the process on
    another host or in another namespace, and nil otherwise.

func FileMode() os.FileMode
func FinalizeRun(meta model.Meta, runID string, exitCode int, now time.Time) (model.Meta, error)
    FinalizeRun returns meta marked finished with runID's exit code.

func IsValidPathElement(value string) bool
func LatestAttempt(runDir, jobID string) (attemptID, jobDir string, err error)
    LatestAttempt lists jobID's attempts once and returns the latest attempt's
    ID, "" when there is none, and the directory holding the job's state:
    that attempt's directory, or the job directory without one.

func LatestAttemptDirs(runDir string) ([]string, error)
    LatestAttemptDirs returns, sorted, the latest attempt directory of each job
    of runDir that has a command snapshot: JOB/attempts/ATTEMPT, or JOB itself
    in a run written before attempts had directories of their own.

func LatestAttemptID(runDir, jobID string) (string, error)
func LatestAttemptJobDir(runDir, jobID string) (string, error)
func ListAttemptIDs(runDir, jobID string) []string
    ListAttemptIDs lists a job's attempt IDs in the run, oldest first.

func LoadAttemptTimestamp(jobDir, name string) (value, path string, err error)
    LoadAttemptTimestamp reads an attempt's submitted_at or finished_at from
    the sources ResolveAttemptTimestamp reads, and returns it with the file it
    came from. It returns "" when no source records it. A source that exists but
    cannot be read or decoded is an error naming the file.

func LoadContext(store Store, runDir string) (model.RunContext, error)
func LoadLocalJobResult(jobDir string, job model.JobSpec) (model.JobResult, bool)
func LoadLock(path string) (model.LockInfo, error)
func LoadMeta(path string) (model.Meta, error)
func LoadQueue(path string) (model.Queue, error)
    LoadQueue reads a queue.json or commands.json file, treating a missing file
    as an empty queue.

func LoadRunClientStatus(store Store, runDir string) (model.RunClientStatus, error)
    LoadRunClientStatus reads the initiating client's persisted status for a
    run.

func LoadRunNotes(runDir string) ([]model.RunNote, error)
    LoadRunNotes reads a run's notes in the order they were added; a run without
    notes has none.

func LoadRunOrigin(runDir, jobID string) (*model.JobOrigin, error)
    LoadRunOrigin returns jobID's origin from the run's commands.json snapshot,
    nil when the job has none (model.Queue.OriginOf), or the error when the
    snapshot cannot be read.

func LoadRunSources(runDir string) (model.RunSources, bool, error)
    LoadRunSources reads a run's sources, and false when the run recorded none.

func LoadRunStartedBy(store Store, runDir string) (*model.StartedBy, error)
    LoadRunStartedBy reads how the run in runDir was started, nil when its
    context is missing or predates the record.

func LoadRunSummary(path string) (model.RunSummary, error)
func LoadRunSummaryHead(path string) (model.RunSummary, error)
    LoadRunSummaryHead is LoadRunSummary without the per-job results, which it
    leaves nil: a listing of many runs needs only their times, names, status,
    and exit code, and a run of many jobs has a large summary.

func MakeAttemptID(runID, jobID string, number int) string
func NewRunID(now time.Time) string
    NewRunID makes the ID of a run that starts at now.

func NewestRunID(paths ProjectPaths) (string, error)
    NewestRunID is the first run of RunsNewestFirst, empty when the project has
    none.

func OtherPIDNamespace(lock model.LockInfo) bool
    OtherPIDNamespace reports whether lock records a PID namespace other than
    this process's, where its PID names another process or none.

func PIDNamespace() string
    PIDNamespace names this process's PID namespace, within which alone a PID
    identifies a process: Linux's namespace link, NoPIDNamespaces on a platform
    without namespaces, and empty where neither can be told.

func ProcessAlive(pid int) bool
func ProcessStart(pid int) string
    ProcessStart is pid's start time, which tells a process from a later one
    reusing its PID. It is compared only with values recorded on the same host,
    so its form is the platform's own. An empty value means the platform cannot
    verify PID reuse, or that pid is not running.

func ProjectNameGiven(cliProjectName string) bool
    ProjectNameGiven reports whether a project was chosen explicitly,
    by cliProjectName or ROTARI_PROJECT_NAME, rather than inferred from the base
    directory.

func ProjectNames(baseDir string) ([]string, error)
    ProjectNames lists the projects in baseDir, sorted: the directories
    under its projects directory whose names are valid path elements.
    A basedir without a projects directory has none and gives nil; one whose
    projects directory is empty, for example after its last project was deleted,
    gives an empty list. A basedir that does not exist is a BaseDirMissingError;
    each caller decides what that means for it, which is why this is the one
    place that reads the projects directory.

func ProjectNamesOrNone(baseDir string) ([]string, error)
    ProjectNamesOrNone is ProjectNames for a basedir that may be the
    implicit default before its first run, or a basedir already checked by
    RequireBaseDir: a missing basedir has no projects.

func ReadAttemptExecutor(attemptDir string) string
    ReadAttemptExecutor returns the executor an attempt ran on, as its
    command.json records it once submitted, or "" for an attempt that has none.
    It reflects a run-level --executor and the queue's default, which the job's
    definition alone does not.

func ReadAttemptTimestamp(jobDir, name string) string
func ReadEach(count int, read func(index int))
    ReadEach calls read for every index in [0, count) from up to ReadConcurrency
    goroutines, and returns once all calls have returned. read must be safe to
    call concurrently; callers keep results in a slice indexed like their input,
    so output order does not depend on scheduling.

func ReadJobName(jobDir string) string
    ReadJobName returns the job name recorded in jobDir, or "" when there is
    none.

func ReadJobTimestamp(runDir, jobID, name string) string
func ReadLoadSamples(path string) []model.LoadSample
func ReadQueueFile(path string) (model.Queue, error)
    ReadQueueFile reads a queue.json or commands.json file and returns an
    os.ErrNotExist error when it is missing.

func RequireBaseDir(baseDir string) error
    RequireBaseDir returns a BaseDirMissingError if baseDir does not exist.
    A command that only reads state calls it for a basedir that was given to it,
    which is most likely mistyped if missing. The implicit default may not exist
    yet: that is a basedir in which nothing has run.

func RequireRunStateFile(runDir, name, runID string) error
func ResolveAttemptTimestamp(jobDir, name string) string
    ResolveAttemptTimestamp reads an attempt's submitted_at or finished_at,
    falling back to the times job.json and status.json record. A source that
    cannot be read is skipped; LoadAttemptTimestamp reports it instead.

func ResolveBaseDir(cliBaseDir string) (string, bool, error)
func ResolveBaseDirDefault() (string, error)
    ResolveBaseDirDefault resolves the local/XDG/home state directory without
    consulting ROTARI_BASEDIR. Aggregate views use it when only CLI scope
    selectors may narrow their target.

func ResolveMasterDir(cliMasterDir string) (string, error)
    ResolveMasterDir resolves the master directory that holds the run
    and server registries: cliMasterDir, then ROTARI_MASTERDIR, then
    $XDG_STATE_HOME/rotari/master, then ~/.local/state/rotari/master.

func ResolveProjectName(baseDir, cliProjectName string) (string, error)
func RunIDStart(runID string) (time.Time, bool)
    RunIDStart is the start second a run ID records. ok is false for an ID in
    another form.

func RunsNewestFirst(paths ProjectPaths) ([]string, error)
    RunsNewestFirst lists the runs of a project, newest first. This is the one
    run order:

      - The newest run is meta.json's last run when it names a run directory.
      - The others are ordered by the start second in the run ID. Runs that
        share a second are ordered by the coordinator's recorded_at in their
        context.json, read only for those runs; a run without it sorts by its ID
        among them, after the runs that have it.
      - Runs whose ID records no start are the oldest, ordered by ID.

    A project without a runs directory has no runs.

func SafeJoin(basePath, element string) (string, error)
func SaveContext(store Store, runDir string, context model.RunContext) error
func SaveRunSources(runDir string, sources model.RunSources) error
    SaveRunSources writes a run's sources.

func ScriptMode() os.FileMode
func SpecificAttemptJobDir(runDir, jobID, attemptID string) (string, error)
func TryAcquireStateReadLock(lockPath string) (release func(), ok bool, err error)
    TryAcquireStateReadLock takes the shared project state lock at lockPath
    without waiting, creating the lock file as AcquireStateLock does. ok is
    false while another holder, possibly in this process, has it exclusively.

func ValidateRunDirectory(runsDir, runID string, requireCommands bool) (string, error)
func ValidateStatePath(path string) error
func ValidatedStateFile(basePath, fileName string) (string, error)
func WriteJSON(path string, value any) error
func WriteRunClientStatus(store Store, runDir string, status model.RunClientStatus) error
    WriteRunClientStatus persists the initiating client's last known status.

Types

type AttemptIDPayload struct {
	RunID  string
	JobID  string
	Number int
}

func DecodeAttemptID(attemptID string) (AttemptIDPayload, error)

func DecodeAttemptIDForRun(attemptID, runID string) (AttemptIDPayload, error)
    DecodeAttemptIDForRun decodes an attempt belonging to runID, including
    imported runs whose IDs do not have the usual timestamp format.

type BaseDirMissingError struct {
	Path string
}
    BaseDirMissingError reports that a basedir's directory does not exist,
    as opposed to a basedir that exists and has no projects yet.

func (err *BaseDirMissingError) Error() string

func (err *BaseDirMissingError) Is(target error) bool

type ElsewhereError struct {
	Identity    ProcessIdentity
	Observation ProcessObservation
}
    ElsewhereError is a refusal to control a process that runs on another host
    or in another PID namespace, where its PID names another process or none
    (COORD-1).

func (err *ElsewhereError) Error() string

type Heartbeat struct {
	Seq          uint64 `json:"seq"`
	At           string `json:"at"`
	Host         string `json:"host,omitempty"`
	PID          int    `json:"pid,omitempty"`
	PIDNamespace string `json:"pid_namespace,omitempty"`
}
    Heartbeat is one beat of a run's coordinator. Seq changes with every beat
    a coordinator writes; it starts again at 1 when another coordinator takes
    the run over, so a reader compares it for change, not order. At is the
    coordinator's own clock, which another host's clock need not agree with.

type LockState string

const (
	LockNone   LockState = "none"
	LockActive LockState = "active"
	LockStale  LockState = "stale"
	LockRemote LockState = "remote"
)
func InspectLock(path string) (LockState, model.LockInfo, error)
    InspectLock classifies the run lock at path without changing it. A lock
    whose coordinator PID cannot be checked here, because it was written on
    another host or in another PID namespace such as a sandbox or container,
    is remote. A stale lock is removed by internal/project, which checks the
    project first.

type ProcessIdentity struct {
	Host         string
	PIDNamespace string
	PID          int
	ProcessStart string
}
    ProcessIdentity is a recorded process: the host and PID namespace it ran in,
    its PID there, and its start time (ProcessStart). A PID names a process
    only within its host and namespace, and the start time tells it from a later
    process that reuses the PID. Records from an earlier rotari may lack the
    namespace, the start, or even the host.

func (identity ProcessIdentity) Locate(host, namespace string) (ProcessVerdict, bool)
    Locate places identity relative to host and namespace without probing:
    ProcessOtherHost, ProcessOtherNamespace, or ProcessHere, and whether the
    record names both so that ProcessHere is verified.

type ProcessObservation struct {
	Verdict ProcessVerdict
	// LocationVerified is true when the record names this host and PID
	// namespace and this platform exposes its own namespace. A record without
	// them, from an earlier rotari, is probed as if it were here, as before;
	// callers that require a verified location check this.
	LocationVerified bool
	// ProbeErr is the signal-zero probe's error when it was neither nil nor
	// ESRCH, such as EPERM, for a process that exists but is not ours.
	ProbeErr error
	// Host and PIDNamespace are this process's, for messages.
	Host         string
	PIDNamespace string
}
    ProcessObservation is the one answer to whether a recorded process can
    be observed from here, used by local job control and liveness, client
    attachments, the coordinator check, and the execution probe.

func LocateProcess(identity ProcessIdentity) ProcessObservation
    LocateProcess is Locate from this process's host and PID namespace.

func ObserveProcess(identity ProcessIdentity) ProcessObservation
    ObserveProcess says whether the recorded process is the one running here
    under its PID.

func ObserveProcessGroup(identity ProcessIdentity) ProcessObservation
    ObserveProcessGroup says the same of the process group the recorded process
    leads, which outlives its leader while its other members run.

func ProbeOutcome(recordedStart, currentStart string, probeErr error) ProcessObservation
    ProbeOutcome is the verdict and probe error of a process probed here;
    see ClassifyProcess.

type ProcessVerdict string
    ProcessVerdict is what can be said, from here, about a recorded process.

const (
	// ProcessHere is a location verdict: the record does not place the
	// process on another host or in another namespace.
	ProcessHere ProcessVerdict = "here"
	// ProcessSame is the recorded process, still running.
	ProcessSame ProcessVerdict = "same"
	// ProcessGone is no process with the PID.
	ProcessGone ProcessVerdict = "gone"
	// ProcessReused is another process that now has the PID.
	ProcessReused ProcessVerdict = "reused"
	// ProcessOtherHost and ProcessOtherNamespace are processes whose PID
	// means nothing here; they must not be probed or signalled.
	ProcessOtherHost      ProcessVerdict = "other host"
	ProcessOtherNamespace ProcessVerdict = "other namespace"
	// ProcessUnverifiable is a process with the PID whose identity cannot be
	// checked, or a PID that cannot be probed.
	ProcessUnverifiable ProcessVerdict = "unverifiable"
)
func ClassifyProcess(recordedStart, currentStart string, probeErr error) ProcessVerdict
    ClassifyProcess decides a probed process from the signal-zero probe's error
    and the recorded and current start times of its PID. EPERM means the process
    exists; a start time unknown on either side cannot be checked.

type ProgressCursor struct {
	// Has unexported fields.
}
    ProgressCursor is an incremental reader for one run's append-only journal.
    Its zero value starts at the beginning. Use a separate cursor per run and
    consumer; it is not safe for concurrent reads.

func (cursor *ProgressCursor) Read(runDir string) ([]model.ProgressEvent, error)
    Read returns newly completed lines. An absent journal (including old runs)
    is an empty successful read. A trailing line without a newline is left
    at the cursor for the next read, even if it already contains valid JSON.
    A malformed complete line is consumed and returns ErrInvalidJSON along with
    any preceding events; a later Read can continue after it.

func (cursor *ProgressCursor) SkipExisting(runDir string) (model.ProgressEvent, bool, error)
    SkipExisting advances the cursor past complete events already in the
    journal and returns their latest progress-count snapshot, if one exists.
    If the final line is still being appended, the cursor stays at its start so
    Read can consume it once the line is complete.

type ProgressJournal struct {
	// Has unexported fields.
}
    ProgressJournal appends progress events to one existing run directory.
    Share one instance between the run's writers; Append serializes whole lines.
    It holds no open file and does not create directories or rewrite history.

func NewProgressJournal(runDir string) (*ProgressJournal, error)

func (journal *ProgressJournal) Append(event model.ProgressEvent) error
    Append writes one newline-terminated JSON event using the state file mode.
    Non-progress events are rejected. Errors are returned to the caller, which
    decides whether journaling is best-effort; Append does not fsync each event.

type ProjectPaths struct {
	BaseDir         string
	BaseDirExplicit bool
	ProjectName     string
	ProjectDir      string
	QueueFile       string
	MetaFile        string
	StateLockFile   string
	LockFile        string
	RunsDir         string
}

func ResolveProjectPaths(cliBaseDir, projectName string) (ProjectPaths, error)

type RunSnapshot struct {
	Commands    model.Queue
	CommandsErr error
	Summary     model.RunSummary
	SummaryErr  error
	Carried     model.RunSummary
	CarriedErr  error
}
    RunSnapshot is what a run directory records about the whole run:
    commands.json, summary.json, and carried.json, each read once. An error
    field is os.ErrNotExist for a missing file.

func LoadRunSnapshot(runDir string) (RunSnapshot, error)
    LoadRunSnapshot reads runDir's run files. It fails, with
    ErrNewerStateVersion, only when one was written by a newer rotari; any other
    error is kept in the snapshot for the caller.

func (snapshot RunSnapshot) Queue() (model.Queue, error)
    Queue is the run's command snapshot as LoadQueue reads it: empty when the
    file is missing.

func (snapshot RunSnapshot) RecordedSummary() *model.RunSummary
    RecordedSummary is the run's summary, or nil when it has no readable one.

type Store struct {
	DirectoryMode os.FileMode
	FileMode      os.FileMode
	ScriptMode    os.FileMode
}

func NewStore(directoryMode, fileMode os.FileMode) Store

func (s Store) LoadHeartbeat(runDir string) (beat Heartbeat, found bool, err error)
    LoadHeartbeat reads runDir's heartbeat. found is false when the run has
    none, such as a run started by a rotari that wrote no heartbeat; a heartbeat
    that cannot be read or decoded is an error naming the file.

func (s Store) ReadJSON(path string, value any) error

func (s Store) WriteHeartbeat(runDir string, beat Heartbeat) error
    WriteHeartbeat replaces runDir's heartbeat. The write goes through a
    temporary file and a rename, so a reader sees one whole beat or another.

func (s Store) WriteJSON(path string, value any) error