state

package
v0.1.28 Latest Latest
Warning

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

Go to latest
Published: Nov 9, 2026 License: MIT Imports: 15 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 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.

Index

Constants

View Source
const (
	StdoutFileName = "stdout"
	StderrFileName = "stderr"
	// SchedulerEventsFileName is a scheduler job's log of query outcomes.
	SchedulerEventsFileName = "scheduler_events.jsonl"
)
View Source
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.

View Source
const (
	BaseDirEnv = "ROTARI_BASEDIR"
)
View Source
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.

View Source
const DefaultProjectName = "default"

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

View Source
const FinalResultFileName = "final_result.json"

FinalResultFileName marks an attempt whose job will not be retried.

View Source
const LoadSamplesFileName = "load_samples.jsonl"

LoadSamplesFileName is the run-directory file that holds a run's load samples.

View Source
const ProgressFileName = "progress.jsonl"
View Source
const ProjectNameEnv = "ROTARI_PROJECT_NAME"
View Source
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.

View Source
const RunClientStatusFileName = "client_status.json"
View Source
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.

View Source
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.

View Source
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

View Source
var ErrInvalidJSON = errors.New("invalid JSON")
View Source
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

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

func AcquireStateLock(lockPath string) (func(), error)

AcquireStateLock takes the exclusive project state lock at lockPath and returns its release function.

func AcquireStateReadLock

func AcquireStateReadLock(lockPath string) (func(), error)

AcquireStateReadLock takes the shared project state lock at lockPath. A missing lock file needs no lock.

func AppendLoadSample

func AppendLoadSample(path string, sample model.LoadSample) error

func AppendRunNote

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

func AttemptJobDir(runDir string, job model.JobSpec) (string, error)

func AttemptSource

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

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

func ContextPath(runDir string) string

func DefaultMeta

func DefaultMeta() model.Meta

func DirectoryMode

func DirectoryMode() os.FileMode

func FileMode

func FileMode() os.FileMode

func FinalizeRun

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

func IsValidPathElement(value string) bool

func LatestAttempt

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

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

func LatestAttemptID(runDir, jobID string) (string, error)

func LatestAttemptJobDir

func LatestAttemptJobDir(runDir, jobID string) (string, error)

func ListAttemptIDs

func ListAttemptIDs(runDir, jobID string) []string

ListAttemptIDs lists a job's attempt IDs in the run, oldest first.

func LoadContext

func LoadContext(store Store, runDir string) (model.RunContext, error)

func LoadLocalJobResult

func LoadLocalJobResult(jobDir string, job model.JobSpec) (model.JobResult, bool)

func LoadLock

func LoadLock(path string) (model.LockInfo, error)

func LoadMeta

func LoadMeta(path string) (model.Meta, error)

func LoadQueue

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

func LoadRunClientStatus(store Store, runDir string) (model.RunClientStatus, error)

LoadRunClientStatus reads the initiating client's persisted status for a run.

func LoadRunNotes

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

func LoadRunOrigin(runDir, jobID string) *model.JobOrigin

LoadRunOrigin returns jobID's origin from the run's commands.json snapshot, or nil when the job has none or the snapshot cannot be read; see model.Queue.OriginOf.

func LoadRunSources

func LoadRunSources(runDir string) (model.RunSources, bool, error)

LoadRunSources reads a run's sources, and false when the run recorded none.

func LoadRunStartedBy

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

func LoadRunSummary(path string) (model.RunSummary, error)

func LoadRunSummaryHead

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

func MakeAttemptID(runID, jobID string, number int) string

func OtherPIDNamespace

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

func PIDNamespace() string

PIDNamespace names this process's PID namespace, within which alone a PID identifies a process. It is empty when the platform does not expose it.

func ProcessAlive

func ProcessAlive(pid int) bool

func ProcessStart

func ProcessStart(pid int) string

ProcessStart is Linux's per-process start-time identity from field 22 of /proc/PID/stat, which tells a process from a later one reusing its PID. An empty value means the platform cannot verify PID reuse.

func ProjectNameGiven

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 ReadAttemptExecutor

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

func ReadAttemptTimestamp(jobDir, name string) string

func ReadEach

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

func ReadJobName(jobDir string) string

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

func ReadJobTimestamp

func ReadJobTimestamp(runDir, jobID, name string) string

func ReadLoadSamples

func ReadLoadSamples(path string) []model.LoadSample

func ReadQueueFile

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 RequireRunStateFile

func RequireRunStateFile(runDir, name, runID string) error

func ResolveAttemptTimestamp

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.

func ResolveBaseDir

func ResolveBaseDir(cliBaseDir string) (string, bool, error)

func ResolveBaseDirDefault

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

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

func ResolveProjectName(baseDir, cliProjectName string) (string, error)

func SafeJoin

func SafeJoin(basePath, element string) (string, error)

func SaveContext

func SaveContext(store Store, runDir string, context model.RunContext) error

func SaveRunSources

func SaveRunSources(runDir string, sources model.RunSources) error

SaveRunSources writes a run's sources.

func ScriptMode

func ScriptMode() os.FileMode

func SpecificAttemptJobDir

func SpecificAttemptJobDir(runDir, jobID, attemptID string) (string, error)

func TryAcquireStateReadLock

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

func ValidateRunDirectory(runsDir, runID string, requireCommands bool) (string, error)

func ValidateStatePath

func ValidateStatePath(path string) error

func ValidatedStateFile

func ValidatedStateFile(basePath, fileName string) (string, error)

func WriteJSON

func WriteJSON(path string, value any) error

func WriteRunClientStatus

func WriteRunClientStatus(store Store, runDir string, status model.RunClientStatus) error

WriteRunClientStatus persists the initiating client's last known status.

Types

type AttemptIDPayload

type AttemptIDPayload struct {
	RunID  string
	JobID  string
	Number int
}

func DecodeAttemptID

func DecodeAttemptID(attemptID string) (AttemptIDPayload, error)

func DecodeAttemptIDForRun

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 LockState

type LockState string
const (
	LockNone   LockState = "none"
	LockActive LockState = "active"
	LockStale  LockState = "stale"
	LockRemote LockState = "remote"
)

func InspectLock

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 ProgressCursor

type ProgressCursor struct {
	// contains filtered or 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 (*ProgressCursor) Read

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 (*ProgressCursor) SkipExisting

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

type ProgressJournal struct {
	// contains filtered or 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

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

func (*ProgressJournal) Append

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

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

func ResolveProjectPaths

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

type RunSnapshot

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

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 (RunSnapshot) Queue

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 (RunSnapshot) RecordedSummary

func (snapshot RunSnapshot) RecordedSummary() *model.RunSummary

RecordedSummary is the run's summary, or nil when it has no readable one.

type Store

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

func NewStore

func NewStore(directoryMode, fileMode os.FileMode) Store

func (Store) ReadJSON

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

func (Store) WriteJSON

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

Jump to

Keyboard shortcuts

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