Documentation
¶
Overview ¶
Package shigoto is the Go representation of pleme-io's typed job-system primitive (仕事, "work/job"). It mirrors the Rust `shigoto` family of crates (shigoto-types / shigoto-dag / shigoto-scheduler / shigoto-budget / shigoto-retry / shigoto-gate / shigoto-emit) so Go services and tools model dependency-ordered, fallible, retryable, parallelism-bounded work the same way everywhere.
The algebra, condensed:
- Job[I, O] — a unit of work: typed input/output + an idempotent Execute, plus a stable Id().
- JobId — (Scope, Kind, Subject) identity, stable across cycles and scheduler restarts.
- JobPhase — a 10-state FSM (Pending, Gated, Ready, Running, Succeeded, Failed, Retrying, Deadlettered, Skipped, WaitingForOperator) driven by the pure, table-driven Advance(phase, signal).
- Dag — a typed dependency graph; Validate rejects cycles, TopoOrder yields a parent-before-child ordering.
- Scheduler — a single-step engine: one Tick per call. The loop is the caller's responsibility (a daemon loops; a K8s reconciler maps each CR event to one Tick).
- BudgetTree — a three-dimension parallelism envelope (global × by-kind × by-scope) with min-intersection admission via Allow.
- RetryPolicy — NoRetry / Fixed / Exponential / Custom, exposing NextDelay(attempt).
- Gate — a pure precondition: Check(ctx) (bool, error), no IO.
- TransitionEmitter — an append-only audit sink; every FSM transition emits one Transition. A JSONL emitter over any io.Writer is provided.
Pure stdlib: no external dependencies. Everything here is offline-testable.
job := shigoto.JobFunc[string, int]{
Identity: shigoto.JobID{Scope: "global", Kind: "len", Subject: "greeting"},
Run: func(ctx context.Context, s string) (int, error) { return len(s), nil },
}
out, err := job.Execute(ctx, "hello") // 5, nil
Index ¶
- Variables
- func CheckAll(ctx context.Context, gates []Gate) (GateAggregate, SkipReason)
- func Reduce(pass []bool, errs []error) (GateAggregate, SkipReason)
- func RegisterJob[I, O any](s *InProcessScheduler, job Job[I, O], in I)
- type BudgetConfig
- type BudgetSpec
- type BudgetTree
- func (b *BudgetTree) Acquire(kind, scope string) bool
- func (b *BudgetTree) Allow(kind, scope string) bool
- func (b *BudgetTree) Release(kind, scope string)
- func (b *BudgetTree) RunningGlobal() uint32
- func (b *BudgetTree) RunningKind(kind string) uint32
- func (b *BudgetTree) RunningScope(scope string) uint32
- func (b *BudgetTree) SetGlobal(spec BudgetSpec)
- func (b *BudgetTree) SetKind(kind string, spec BudgetSpec)
- func (b *BudgetTree) SetScope(scope string, spec BudgetSpec)
- type Config
- type CycleError
- type Dag
- func (d *Dag) AddEdge(from, to JobID)
- func (d *Dag) AddNode(id JobID)
- func (d *Dag) EdgeCount() int
- func (d *Dag) NodeCount() int
- func (d *Dag) Predecessors(id JobID) []JobID
- func (d *Dag) Successors(id JobID) []JobID
- func (d *Dag) TopoOrder() ([]JobID, error)
- func (d *Dag) Validate() error
- func (d *Dag) Waves() ([][]JobID, error)
- type Decider
- type Gate
- type GateAggregate
- type GateFunc
- type InProcessScheduler
- func (s *InProcessScheduler) Concurrency() int
- func (s *InProcessScheduler) InstallBudget(b *BudgetTree)
- func (s *InProcessScheduler) OperatorTransition(id JobID, target JobPhase, reason TransitionReason) error
- func (s *InProcessScheduler) PhaseOf(id JobID) JobPhase
- func (s *InProcessScheduler) RegisterGate(kind string, gate Gate)
- func (s *InProcessScheduler) RegisterRetryPolicy(kind string, p RetryPolicy)
- func (s *InProcessScheduler) SetConcurrency(n int)
- func (s *InProcessScheduler) SetPhase(id JobID, p JobPhase)
- func (s *InProcessScheduler) SetTimeout(id JobID, d time.Duration)
- func (s *InProcessScheduler) Snapshot() map[JobID]JobPhase
- func (s *InProcessScheduler) Tick(ctx context.Context, dag *Dag) (TickReceipt, error)
- func (s *InProcessScheduler) WaveTick(ctx context.Context, dag *Dag) (TickReceipt, error)
- func (s *InProcessScheduler) WithEmitter(e TransitionEmitter) *InProcessScheduler
- type JSONLEmitter
- type Job
- type JobFunc
- type JobID
- type JobPhase
- type MultiEmitter
- type NullEmitter
- type Option
- type RetryConfig
- type RetryKind
- type RetryOutcomeKind
- type RetryPolicy
- type Scheduler
- type Signal
- func AllocateBudget() Signal
- func BackoffElapsed() Signal
- func Cancel() Signal
- func EvaluateGates(agg GateAggregate, reason SkipReason) Signal
- func ExecutionFailed() Signal
- func ExecutionSucceeded() Signal
- func OperatorTransition(target JobPhase, reason SkipReason) Signal
- func RetryDecide(outcome RetryOutcomeKind) Signal
- func Timeout() Signal
- type SignalKind
- type SkipReason
- type TickReceipt
- type Transition
- type TransitionEmitter
- type TransitionReason
- type UnhealedDrift
Constants ¶
This section is empty.
Variables ¶
var ( // ReasonGateEvaluation — phase changed because gates were evaluated. ReasonGateEvaluation = TransitionReason{Kind: "gate-evaluation"} // ReasonBudgetAllocated — a budget slot was reserved (Ready → Running). ReasonBudgetAllocated = TransitionReason{Kind: "budget-allocated"} // ReasonExecutionSucceeded — Execute returned ok. ReasonExecutionSucceeded = TransitionReason{Kind: "execution-succeeded"} // ReasonRetryScheduled — a retry was scheduled (Failed → Retrying). ReasonRetryScheduled = TransitionReason{Kind: "retry-scheduled"} // ReasonBackoffElapsed — the retry backoff window elapsed. ReasonBackoffElapsed = TransitionReason{Kind: "backoff-elapsed"} // ReasonTimedOut — a Running job timed out. ReasonTimedOut = TransitionReason{Kind: "timed-out"} // ReasonCancelled — a Running job was cancelled. ReasonCancelled = TransitionReason{Kind: "cancelled"} )
Stable reason constructors mirroring the Rust `reason_from` mapping.
var ErrCycle = errors.New("shigoto: cycle in DAG")
ErrCycle is returned by Validate / TopoOrder / Waves when the graph contains a cycle. Use errors.As against a *CycleError to recover the offending JobID.
var ErrIllegalTransition = errors.New("shigoto: illegal FSM transition")
ErrIllegalTransition is returned by Advance when a (JobPhase, Signal) pair is not a legal cell of the FSM transition table. Returning an error rather than panicking lets consumers report drift (e.g. an operator action attempting an illegal transition) without crashing the scheduler.
var ErrSkipRetry = errors.New("shigoto: skip retry (non-retryable failure)")
ErrSkipRetry is the typed non-retryable signal: a Job whose Execute returns an error wrapping ErrSkipRetry (errors.Is(err, ErrSkipRetry)) deadletters immediately, bypassing the registered RetryPolicy. It is the one retry feature every surveyed leader shares (hibiken/asynq's SkipRetry sentinel, Temporal's NonRetryableErrorTypes, river's permanent failure) — a fatal classification co-located with the error value, not the policy.
Wrap it like any sentinel:
return fmt.Errorf("bad input %q: %w", arg, shigoto.ErrSkipRetry)
The complementary policy-level predicate is RetryPolicy.NonRetryable, which lets a kind declare fatal classification by error inspection rather than by the callee wrapping a sentinel.
Functions ¶
func CheckAll ¶
func CheckAll(ctx context.Context, gates []Gate) (GateAggregate, SkipReason)
CheckAll evaluates a cohort of gates in order and reduces the results to a GateAggregate. It short-circuits on the first refusing (error-returning) gate. A ctx cancellation surfaces as a refusal-shaped error via the gate itself. Convenience wrapper around Reduce for the common "evaluate this slice of gates" path.
func Reduce ¶
func Reduce(pass []bool, errs []error) (GateAggregate, SkipReason)
Reduce rolls a cohort of gate outcomes up to a single GateAggregate that the FSM Advance consumes. Worst-outcome wins: any error → AggSkipped; otherwise any unsatisfied (pass == false) → SomeWaiting; otherwise → AllPassed. A reason for the first error is returned alongside (always SkipGateRejected here, since the bool/error Gate surface carries no finer reason). An empty cohort trivially passes (a Job with no gates may run immediately). Mirrors the Rust `shigoto-gate::reduce`.
Each element of pass corresponds to a Gate's bool result; each element of errs is that Gate's error (nil when none). The two slices must be the same length.
func RegisterJob ¶
func RegisterJob[I, O any](s *InProcessScheduler, job Job[I, O], in I)
RegisterJob adapts a typed Job[I, O] (with its fixed input) into the scheduler's erased registry. The input is captured at registration; Execute is invoked with it on the Ready → Running transition. The typed output is discarded by the scheduler (consumers capture it via their own sink inside the job, mirroring the Rust OutputSink design).
Types ¶
type BudgetConfig ¶
type BudgetConfig struct {
// Global caps whole-tree concurrency (0 = unbounded).
Global uint32 `yaml:"global"`
// ByKind caps concurrency per JobID.Kind.
ByKind map[string]uint32 `yaml:"by_kind"`
// ByScope caps concurrency per JobID.Scope.
ByScope map[string]uint32 `yaml:"by_scope"`
}
BudgetConfig is the yaml-tagged view of a BudgetTree's limits. Each map is keyed by kind / scope; a value caps MaxConcurrent for that dimension.
func (BudgetConfig) Build ¶
func (b BudgetConfig) Build() *BudgetTree
Build materialises a *BudgetTree from the config. An unset Global / empty maps yield an unbounded tree (the NewBudgetTree default).
type BudgetSpec ¶
type BudgetSpec struct {
// MaxConcurrent is the maximum number of jobs that may run concurrently
// in this dimension. Zero means "admit nothing"; use a high value (or no
// spec at all) for "unbounded".
MaxConcurrent uint32
}
BudgetSpec is the per-dimension limit. Mirrors the Rust `BudgetSpec`; only MaxConcurrent is load-bearing for admission in v0.1 (the other Rust fields — max_failures_per_minute, queue_depth — are reserved and omitted here until a consumer needs them).
func MaxConcurrent ¶
func MaxConcurrent(n uint32) BudgetSpec
MaxConcurrent is a convenience constructor for a spec capping concurrency.
type BudgetTree ¶
type BudgetTree struct {
// contains filtered or unexported fields
}
BudgetTree is a three-dimension parallelism envelope: global × by-kind × by-scope. Admission is min-intersection — a job is admitted iff every applicable dimension (global, its kind, its scope) has slack. Absent specs are unbounded. It mirrors the Rust `shigoto-budget::BudgetTree`.
BudgetTree is safe for concurrent use: Allow / Acquire / Release take an internal mutex.
The zero value is not ready for use; construct with NewBudgetTree.
func NewBudgetTree ¶
func NewBudgetTree() *BudgetTree
NewBudgetTree returns an unbounded budget tree. Configure limits with SetGlobal / SetKind / SetScope.
func (*BudgetTree) Acquire ¶
func (b *BudgetTree) Acquire(kind, scope string) bool
Acquire atomically reserves a slot for a job of (kind, scope) across all three dimensions, returning true on success. On failure no counter is modified — the call is atomic. Mirrors the Rust `try_allocate`.
func (*BudgetTree) Allow ¶
func (b *BudgetTree) Allow(kind, scope string) bool
Allow reports whether a job of (kind, scope) could be admitted right now — i.e. every applicable dimension currently has slack (min-intersection). It does NOT reserve a slot; use Acquire for the reserving check. Allow is the pure admission predicate the spec calls for.
func (*BudgetTree) Release ¶
func (b *BudgetTree) Release(kind, scope string)
Release frees a slot held by a job of (kind, scope). Symmetric to Acquire, and saturating: a double-release never underflows. Mirrors the Rust `release`.
func (*BudgetTree) RunningGlobal ¶
func (b *BudgetTree) RunningGlobal() uint32
RunningGlobal returns the current global running count.
func (*BudgetTree) RunningKind ¶
func (b *BudgetTree) RunningKind(kind string) uint32
RunningKind returns the current running count for a kind.
func (*BudgetTree) RunningScope ¶
func (b *BudgetTree) RunningScope(scope string) uint32
RunningScope returns the current running count for a scope.
func (*BudgetTree) SetGlobal ¶
func (b *BudgetTree) SetGlobal(spec BudgetSpec)
SetGlobal installs (or replaces) the whole-tree concurrency cap.
func (*BudgetTree) SetKind ¶
func (b *BudgetTree) SetKind(kind string, spec BudgetSpec)
SetKind installs (or replaces) the cap for a JobID.Kind.
func (*BudgetTree) SetScope ¶
func (b *BudgetTree) SetScope(scope string, spec BudgetSpec)
SetScope installs (or replaces) the cap for a JobID.Scope.
type Config ¶
type Config struct {
// Tool is the consumer-name tag stamped on every emitted Transition
// (e.g. "tend", "forge-gen"). Required: FromConfig errors when empty.
Tool string `yaml:"tool"`
// Concurrency is the intra-wave worker ceiling consulted by WaveTick.
// <= 0 means unbounded fan-out within a wave; 1 is equivalent to the
// sequential Tick. The BudgetTree remains the admission authority; this
// only bounds the simultaneous Execute call count.
Concurrency int `yaml:"concurrency"`
// Budget declares the three-dimension parallelism envelope. Absent
// dimensions are unbounded.
Budget BudgetConfig `yaml:"budget"`
// Retry maps a JobID.Kind to its RetryConfig. A kind with no entry uses
// NoRetry (deadletter on first failure).
Retry map[string]RetryConfig `yaml:"retry"`
// Timeouts maps a JobID.Kind to a per-job execution timeout. Zero (absent)
// means run to completion (or ctx cancellation).
Timeouts map[string]time.Duration `yaml:"timeouts"`
}
Config is the typed, yaml-tagged runtime knob surface for a scheduler (Borealis Law 3 — config via shikumi). It is a plain struct: the yaml tags are inert without a YAML library, so the CORE package stays zero-dependency (Law 6 / Law 8 — the shikumi loader lives once, at main, in the consumer; the borealis render leaf lives in a separate sub-package). A consumer loads it the canonical way and hands the sub-struct to FromConfig:
cfg, _ := shikumi.For[App]("tend").EnvPrefix("TEND_").Load(ctx)
sched, _ := shigoto.FromConfig(cfg.Shigoto) // App.Shigoto is a shigoto.Config
FromConfig MUST NOT itself call shikumi.Load (§3.5) — precedence (args > env > file) is the loader's job, applied once at main.
type CycleError ¶
type CycleError struct {
// At is one node on the detected cycle.
At JobID
}
CycleError reports a cycle, naming one JobID that participates in it.
func (*CycleError) Unwrap ¶
func (e *CycleError) Unwrap() error
Unwrap lets errors.Is(err, ErrCycle) match a *CycleError.
type Dag ¶
type Dag struct {
// contains filtered or unexported fields
}
Dag is a typed dependency graph over JobIDs. An edge from → to declares "to may not start until from reaches a terminal phase". It mirrors the Rust `shigoto-dag::Dag`.
Cycles are NOT rejected at AddEdge (that would cost an O(V+E) check on every insert); they surface at Validate / TopoOrder / Waves, which a consumer runs before scheduling anyway. AddNode/AddEdge are idempotent.
The zero value is not ready for use; construct with NewDag.
func (*Dag) AddEdge ¶
AddEdge adds a directed edge from → to, creating either endpoint node if absent. Idempotent: re-adding an existing edge is a no-op (no parallel edges). A self-edge (from == to) is permitted at insert time and surfaces as a cycle at Validate.
func (*Dag) AddNode ¶
AddNode adds an isolated node if absent. Idempotent: re-adding an existing node is a no-op.
func (*Dag) Predecessors ¶
Predecessors returns the direct predecessors of id — every node with an edge pointing into id — in deterministic (insertion) order. Returns nil when id is unknown or a root. Used by gates such as AllUpstreamsTerminal.
func (*Dag) Successors ¶
Successors returns the direct successors of id in deterministic order.
func (*Dag) TopoOrder ¶
TopoOrder returns the nodes in a topological order (every parent before its children). Ties are broken by insertion order for determinism. It returns a *CycleError (matching ErrCycle) when the graph contains a cycle.
Uses Kahn's algorithm.
func (*Dag) Validate ¶
Validate reports whether the graph is acyclic. It returns a *CycleError (matching ErrCycle) naming one node on a detected cycle, or nil when the graph is a valid DAG. It is the public name for the cycle check; TopoOrder performs the same check and additionally returns the ordering.
func (*Dag) Waves ¶
Waves partitions the DAG into topological waves: wave 0 holds every node with no dependencies, and wave N holds nodes whose dependencies all live in earlier waves. Within a wave, nodes execute concurrently; waves run in order. Nodes inside a wave are sorted by their string key for determinism.
It returns a *CycleError (matching ErrCycle) when the graph contains a cycle. Mirrors the Rust `Dag::waves(None)`.
type Decider ¶
Decider is a user-supplied retry decision function for KindCustom. attempt is the 1-based number of the attempt that just failed. It returns the delay before the next attempt and whether to retry at all.
type Gate ¶
type Gate interface {
// Check reports whether the precondition is satisfied. It honours ctx
// cancellation even though concrete gates are expected to be pure and
// fast.
Check(ctx context.Context) (bool, error)
}
Gate is one typed precondition for a Job. Gates are PURE — they evaluate against in-memory state without IO. (A gate that "needs" IO is an antipattern: model it as a Job that emits a typed fact and a downstream gate that checks the fact.) It mirrors the Rust `shigoto-gate::Gate` trait, projected to the (bool, error) shape the spec asks for: true == the gate is satisfied (Pass); false == not yet (Wait); a non-nil error == the gate refuses permanently (the Job is Skipped).
func AllUpstreamsTerminal ¶
AllUpstreamsTerminal builds a Gate that passes iff every direct DAG predecessor of id has reached a terminal phase ({Succeeded, Skipped, Deadlettered}) per the supplied phase lookup. It enforces DAG edge semantics. Mirrors the Rust `AllUpstreamsTerminal` standard gate.
phaseOf returns the current phase of a JobID and whether it is known; unknown predecessors are treated as Pending (non-terminal → Wait).
type GateAggregate ¶
type GateAggregate int
GateAggregate is the rolled-up outcome of a Job's gate cohort: the worst outcome wins (Skipped > SomeWaiting > AllPassed). It mirrors the Rust `GateAggregate` enum and is carried by a SigEvaluateGates signal so the FSM stays agnostic about how the rollup was computed.
const ( // AllPassed — every gate returned Pass; the Job advances to Ready. AllPassed GateAggregate = iota // SomeWaiting — at least one gate returned Wait; the Job stays Gated. SomeWaiting // AggSkipped — at least one gate returned Skip; the Job advances to // Skipped with the carried SkipReason. AggSkipped )
type GateFunc ¶
GateFunc adapts a plain function into a Gate — the common authoring shape.
gate := shigoto.GateFunc(func(ctx context.Context) (bool, error) {
return approved.Load(), nil
})
type InProcessScheduler ¶
type InProcessScheduler struct {
// contains filtered or unexported fields
}
InProcessScheduler is the default single-process, in-memory Scheduler. It drives the FSM via Advance, enforcing DAG edges through an implicit AllUpstreamsTerminal gate plus per-kind consumer gates, per-kind retry policies, a three-dimension budget, optional per-job timeouts, and a transition emitter. It mirrors the Rust `InProcessScheduler`.
The load-bearing invariant: every phase change goes through Advance. The scheduler never invents transitions.
Construct with NewScheduler.
func FromConfig ¶
func FromConfig(cfg Config) (*InProcessScheduler, error)
FromConfig is the canonical config-consuming constructor (§3.5 Consume-config shape: pkg.FromConfig(cfg pkg.Config) (*T, error)). It takes the already- loaded sub-struct and MUST NOT itself call shikumi.Load — the loader lives once, at main. It materialises the BudgetTree, per-kind retry policies, and per-kind timeouts from the typed config, then returns a ready scheduler.
cfg, _ := shikumi.For[App]("tend").Load(ctx) // ← at main, once
sched, _ := shigoto.FromConfig(cfg.Shigoto) // ← FromConfig consumes
func New ¶
func New(tool string, opts ...Option) (*InProcessScheduler, error)
New is the canonical functional-options constructor (§3.5 Construct shape: pkg.New(required…, opts ...Option) (*T, error)). tool is the required consumer-name tag stamped on every Transition. It supersedes the chained- setter NewScheduler as the public construction surface; NewScheduler remains for back-compat (additive elevation — deprecate, don't delete).
sched, err := shigoto.New("tend",
shigoto.WithConcurrency(8),
shigoto.WithBudget(shigoto.NewBudgetTree()),
shigoto.WithEmitter(shigoto.NewJSONLEmitter(os.Stderr)),
)
func NewScheduler ¶
func NewScheduler(tool string) *InProcessScheduler
NewScheduler builds a scheduler tagged with tool (the consumer-name emitted on every Transition, e.g. "tend"). It starts with a NullEmitter and an unbounded budget; attach a real emitter with WithEmitter and a budget with InstallBudget.
func (*InProcessScheduler) Concurrency ¶
func (s *InProcessScheduler) Concurrency() int
Concurrency reports the configured intra-wave worker ceiling (<= 0 means unbounded).
func (*InProcessScheduler) InstallBudget ¶
func (s *InProcessScheduler) InstallBudget(b *BudgetTree)
InstallBudget replaces the unbounded budget with a configured one. After installation the Ready → Running transition becomes a real admission check.
func (*InProcessScheduler) OperatorTransition ¶
func (s *InProcessScheduler) OperatorTransition(id JobID, target JobPhase, reason TransitionReason) error
OperatorTransition applies an externally-driven transition, constrained to the legal targets by Advance. The transition emits immediately (operator actions are auditable in real time, not deferred to the next tick). It returns ErrIllegalTransition when the move violates the FSM.
func (*InProcessScheduler) PhaseOf ¶
func (s *InProcessScheduler) PhaseOf(id JobID) JobPhase
PhaseOf returns the current phase of id (Pending if unknown).
func (*InProcessScheduler) RegisterGate ¶
func (s *InProcessScheduler) RegisterGate(kind string, gate Gate)
RegisterGate registers a Gate against a JobID.Kind. Every job of that kind consults this gate (plus the implicit AllUpstreamsTerminal) during gate evaluation; multiple gates per kind reduce via Reduce (worst-outcome wins).
func (*InProcessScheduler) RegisterRetryPolicy ¶
func (s *InProcessScheduler) RegisterRetryPolicy(kind string, p RetryPolicy)
RegisterRetryPolicy registers a RetryPolicy against a JobID.Kind. The default (no registration) is NoRetry — deadletter on first failure.
func (*InProcessScheduler) SetConcurrency ¶
func (s *InProcessScheduler) SetConcurrency(n int)
SetConcurrency sets the intra-wave worker ceiling consulted by WaveTick. A value <= 0 means unbounded fan-out; n == 1 is equivalent to sequential Tick. It is the internal setter the functional-option WithConcurrency and the shikumi Config wire through (Law 1: one constructor style — chained setters are internals, not a second public constructor).
func (*InProcessScheduler) SetPhase ¶
func (s *InProcessScheduler) SetPhase(id JobID, p JobPhase)
SetPhase forces a job's phase directly. Intended for tests and for seeding a WaitingForOperator phase before an OperatorTransition; it bypasses Advance, so use it only for setup, not normal progression.
func (*InProcessScheduler) SetTimeout ¶
func (s *InProcessScheduler) SetTimeout(id JobID, d time.Duration)
SetTimeout installs an optional per-job execution timeout. Without one, Execute runs to completion (or until ctx cancellation).
func (*InProcessScheduler) Snapshot ¶
func (s *InProcessScheduler) Snapshot() map[JobID]JobPhase
Snapshot returns a copy of the current phase map.
func (*InProcessScheduler) Tick ¶
func (s *InProcessScheduler) Tick(ctx context.Context, dag *Dag) (TickReceipt, error)
Tick drives every job in the DAG one round forward. Each wave is processed in three passes: (1) fast FSM transitions up to Running (gate eval, budget allocation); (2) execute every job that reached Running; (3) post-execute terminal cleanup (Failed → retry decision). Inter-wave dependencies serialise; the loop across ticks is the caller's job. Mirrors the Rust `InProcessScheduler::tick` (sequential within a wave — this Go v0.1 does not fan out execution concurrently).
func (*InProcessScheduler) WaveTick ¶
func (s *InProcessScheduler) WaveTick(ctx context.Context, dag *Dag) (TickReceipt, error)
WaveTick is the concurrent sibling of Tick: it advances the DAG one round forward, executing each wave's admitted jobs CONCURRENTLY rather than in insertion order. It composes the package's two strongest primitives — Dag.Waves (the topological partition where every job in a wave is mutually independent and therefore safe to run in parallel) and BudgetTree (the min-intersection admission gate) — with errgroup's bounded fan-out:
- Dag.Waves guarantees intra-wave independence (no edge connects two jobs in the same wave), so parallel execution within a wave is correct by construction.
- BudgetTree.Acquire (run in pass 1, the Ready → Running admission) remains the authority on HOW MANY jobs may run across the global × kind × scope dimensions: only jobs that already acquired a slot reach pass 2, so the budget is honoured whether execution is sequential or concurrent.
- errgroup.WithContext + g.SetLimit(concurrency) bounds the worker pool: at most `concurrency` Execute calls run simultaneously, and the first error propagates the group context's cancellation to the siblings (the structured-concurrency property a bare WaitGroup cannot provide). Job execution errors are NOT surfaced as the group error (they drive the FSM to Failed and are reported via TickReceipt, matching Tick's contract); only a malformed-DAG error from Waves aborts the tick.
concurrency is read from the scheduler (WithConcurrency / SetConcurrency). A value <= 0 means unbounded fan-out within a wave (errgroup with no limit); n == 1 is exactly Tick's sequential behaviour. Inter-wave dependencies still serialise — wave N+1 starts only after wave N fully drains — so DAG ordering is preserved. Like Tick, the loop across ticks is the CALLER's job.
func (*InProcessScheduler) WithEmitter ¶
func (s *InProcessScheduler) WithEmitter(e TransitionEmitter) *InProcessScheduler
WithEmitter replaces the default NullEmitter and returns the scheduler for chaining.
type JSONLEmitter ¶
type JSONLEmitter struct {
// contains filtered or unexported fields
}
JSONLEmitter is an append-only JSON-lines emitter: one transition per line, written to an io.Writer. The same shape an operator can grep, tail, or pipe into a log pipeline. Mirrors the Rust `AuditFileEmitter` over an arbitrary writer rather than a file path.
Writes are serialised by an internal mutex so concurrent Emit calls produce whole, interleave-free lines. A marshalling or write error is dropped (the emitter is append-only and best-effort — it must never fail the scheduler); inspect LastErr if you need to observe failures.
func NewJSONLEmitter ¶
func NewJSONLEmitter(w io.Writer) *JSONLEmitter
NewJSONLEmitter returns an emitter that appends one JSON line per transition to w.
func (*JSONLEmitter) Emit ¶
func (e *JSONLEmitter) Emit(t Transition)
Emit marshals t to a single JSON line (terminated by '\n') and appends it to the writer. Errors are retained in LastErr rather than propagated.
func (*JSONLEmitter) LastErr ¶
func (e *JSONLEmitter) LastErr() error
LastErr returns the most recent marshal/write error, or nil.
type Job ¶
type Job[I, O any] interface { // Id returns the stable identity of this job. Id() JobID // Execute performs the (idempotent) work, returning a typed output or an // error. It must respect ctx cancellation. Execute(ctx context.Context, in I) (O, error) }
Job is the typed unit of work every consumer implements. It is generic over its input I and output O.
Contract (mirroring the Rust `Job` trait):
- Id is pure: the scheduler reads it many times per cycle; no IO.
- Execute is the side-effecting work and MUST be idempotent. A scheduler that crashes between completing a side effect and recording Succeeded will re-invoke Execute on the next cycle, so re-running must be safe.
- Execute honours ctx cancellation (timeout / operator cancel map to a failing return).
type JobFunc ¶
type JobFunc[I, O any] struct { // Identity is returned verbatim by Id. Identity JobID // Run is invoked by Execute. Run func(ctx context.Context, in I) (O, error) }
JobFunc adapts a plain function into a Job[I, O] — the common authoring shape, so callers rarely declare a bespoke struct. Identity supplies Id and Run supplies Execute.
job := shigoto.JobFunc[Req, Resp]{
Identity: shigoto.JobID{Scope: "global", Kind: "fetch", Subject: "url"},
Run: func(ctx context.Context, r Req) (Resp, error) { ... },
}
type JobID ¶
JobID is the typed, stable identity of a Job. The triple (Scope, Kind, Subject) is stable across scheduler cycles and restarts so the same logical work is recognised as the same Job every tick.
It mirrors the Rust `JobId { scope, kind, subject }` but flattens the nested scope/subject enums to strings: the Rust variants (Global / Workspace / Repo and None / Repo / Org / Path / Pinned) all project to a stable string key in the Rust code's `stable_job_key`, so a string triple is the natural Go shape and keeps JobID directly usable as a map key.
- Scope — the breadth of the work, e.g. "global", "workspace:pleme-io", "repo:pleme-io/tend".
- Kind — the work class, e.g. "flake-update", "publish". Budgets and gates and retry policies are registered per-kind.
- Subject — the concrete thing operated on, e.g. "nixpkgs", an org name, a path. Empty when the kind has no finer subject.
type JobPhase ¶
type JobPhase int
JobPhase is the FSM phase a Job inhabits. The ten phases and their legal transitions mirror the Rust `JobPhase` enum + its `advance` table (theory/SHIGOTO.md §III.3 / §IV.1).
Unlike the Rust enum, the Go phase carries no per-variant payload (the Rust Failed{attempts}, Retrying{until_ms} and Skipped(reason) data live in the scheduler's side state and in TickReceipt here, keeping JobPhase a plain comparable value usable as a map key and trivially serialisable).
const ( // Pending is the entry phase — a freshly registered Job awaiting gate // evaluation. Pending JobPhase = iota // Gated means at least one precondition gate returned Wait; the // scheduler re-evaluates each tick. Gated // Ready means every gate passed; the Job awaits a budget slot. Ready // Running means a budget slot was allocated and Execute is in flight. Running // Succeeded is a terminal-for-cycle phase: Execute returned ok. Succeeded // Failed means Execute returned an error (or was cancelled / timed out); // awaiting a retry decision. Failed // Retrying means a retry was scheduled and the Job is in its backoff // window before re-entering Pending. Retrying // Deadlettered is the terminal failure phase — retries are exhausted (or // the policy declined). Only an operator can revive it (→ Pending). Deadlettered // Skipped is a terminal phase — a gate refused the Job permanently. Skipped // WaitingForOperator means the Job is paused pending an explicit operator // decision (→ Ready or → Skipped). WaitingForOperator )
func Advance ¶
Advance is the canonical FSM driver. It is pure: the same (from, signal) always produces the same result. Every legal cell of the JobPhase × Signal cross-product is enumerated below, matching the Rust `advance` table (theory/SHIGOTO.md §IV.1); every other pair returns ErrIllegalTransition.
On an illegal transition the returned phase is the input phase unchanged, so a caller that ignores the error still sees a sane (no-op) value.
func (JobPhase) IsTerminal ¶
IsTerminal reports whether the phase is terminal — no automatic transition leaves it. {Succeeded, Skipped, Deadlettered} are terminal. (Deadlettered is terminal for the automatic FSM; only an operator transition revives it.) Mirrors shigoto-gate's `is_terminal`.
func (JobPhase) MarshalJSON ¶
MarshalJSON renders a JobPhase as its stable string name in JSON, so the audit log is human-readable.
func (JobPhase) String ¶
String returns the stable kebab-case name of the phase, matching the Rust `JobPhase::kind()` strings used in TickReceipt phase counts.
func (*JobPhase) UnmarshalJSON ¶
UnmarshalJSON parses a JobPhase from its stable string name (the form MarshalJSON produces), so a Transition round-trips through JSONL cleanly.
type MultiEmitter ¶
type MultiEmitter struct {
// contains filtered or unexported fields
}
MultiEmitter fans out every transition to a set of inner emitters. Mirrors the Rust `MultiEmitter`.
func NewMultiEmitter ¶
func NewMultiEmitter(sinks ...TransitionEmitter) *MultiEmitter
NewMultiEmitter returns a fan-out emitter over the given sinks.
func (*MultiEmitter) Emit ¶
func (m *MultiEmitter) Emit(t Transition)
Emit forwards t to every inner sink in order.
func (*MultiEmitter) With ¶
func (m *MultiEmitter) With(sink TransitionEmitter) *MultiEmitter
With appends a sink and returns the emitter for chaining.
type NullEmitter ¶
type NullEmitter struct{}
NullEmitter discards every transition. It is the default for tests and for consumers without observability wired up. Mirrors the Rust `NullEmitter`.
type Option ¶
type Option func(*InProcessScheduler)
Option is a functional option for New (§3.5 Construct shape: pkg.New(required…, opts ...Option) (*T, error)). The chained setters (WithEmitter / InstallBudget / SetConcurrency / RegisterRetryPolicy / …) remain as internals the options wire through, NOT a second public constructor (Law 1 forbids two construction styles for one type).
func WithBudget ¶
func WithBudget(b *BudgetTree) Option
WithBudget installs a pre-built BudgetTree (default unbounded).
func WithConcurrency ¶
WithConcurrency sets the intra-wave worker ceiling consulted by WaveTick (<= 0 means unbounded; 1 is sequential).
func WithEmitter ¶
func WithEmitter(e TransitionEmitter) Option
WithEmitter sets the audit/observability sink (default NullEmitter).
func WithRetryPolicy ¶
func WithRetryPolicy(kind string, p RetryPolicy) Option
WithRetryPolicy registers a RetryPolicy against a JobID.Kind at construction — the code-only path for the NonRetryable predicate / KindCustom Decider a yaml RetryConfig cannot express.
type RetryConfig ¶
type RetryConfig struct {
// Kind is "none" (default), "fixed", or "exponential".
Kind string `yaml:"kind"`
// Attempts is the total attempts allowed (fixed / exponential).
Attempts uint32 `yaml:"attempts"`
// Delay is the constant delay for "fixed".
Delay time.Duration `yaml:"delay"`
// Base is the first backoff for "exponential".
Base time.Duration `yaml:"base"`
// Max caps the exponential backoff.
Max time.Duration `yaml:"max"`
// Jitter is the ±fraction applied to the exponential backoff.
Jitter float64 `yaml:"jitter"`
}
RetryConfig is the yaml-tagged view of a RetryPolicy. Kind selects the strategy by stable string name ("none", "fixed", "exponential"); the per-strategy fields supply the remaining parameters. The error-classifying NonRetryable predicate and a KindCustom Decider are code-only (a yaml config cannot express a function), so they are wired via WithRetryPolicy, not here.
func (RetryConfig) Policy ¶
func (r RetryConfig) Policy() RetryPolicy
Policy materialises a RetryPolicy from the config. An unknown / empty Kind maps to NoRetry.
type RetryKind ¶
type RetryKind int
RetryKind is the discriminant of a RetryPolicy, mirroring the variants of the Rust `RetryPolicy` enum.
const ( // KindNoRetry deadletters on the first failure. KindNoRetry RetryKind = iota // KindFixed retries up to Attempts times with a constant delay. KindFixed // KindExponential retries up to Attempts times with exponential backoff // (Base × 2^(attempt-1), capped at Max), optionally jittered. KindExponential // KindCustom delegates the decision to a user-supplied Decider. KindCustom )
type RetryOutcomeKind ¶
type RetryOutcomeKind int
RetryOutcomeKind is the retry decision after a Failed Job, mirroring the Rust `RetryOutcome` enum.
const ( // RetryAgain schedules a retry (→ Retrying). RetryAgain RetryOutcomeKind = iota // RetryDeadletter exhausts retries (→ Deadlettered). RetryDeadletter )
type RetryPolicy ¶
type RetryPolicy struct {
// Kind selects the strategy.
Kind RetryKind
// Attempts is the total number of attempts allowed (Fixed / Exponential).
// Attempt N is the last; attempt >= Attempts deadletters.
Attempts uint32
// Delay is the constant delay for Fixed.
Delay time.Duration
// Base is the first backoff for Exponential.
Base time.Duration
// Max caps the Exponential backoff.
Max time.Duration
// Jitter is the +/- fraction applied to the Exponential backoff (0 = no
// jitter). Jitter is deterministic per attempt so delays are reproducible
// in tests.
Jitter float64
// Decider is the decision function for KindCustom.
Decider Decider
// NonRetryable, when set, classifies an execution error as fatal: if it
// returns true the Job deadletters immediately regardless of Kind/Attempts.
// It is the policy-level twin of the ErrSkipRetry sentinel — a kind can
// declare its own fatal classification (e.g. errors.Is(err, io.EOF), HTTP
// 4xx) without the callee having to wrap a sentinel. ErrSkipRetry is always
// honoured even when NonRetryable is nil (see ShouldRetry). It composes with
// any Kind, including KindNoRetry and KindCustom.
NonRetryable func(err error) bool
}
RetryPolicy is a typed failure-recovery strategy. Construct one with the helper constructors (NoRetry, Fixed, Exponential, Custom) rather than building the struct by hand. It mirrors the Rust `shigoto-retry::RetryPolicy` enum.
The zero value is a valid NoRetry policy.
func Custom ¶
func Custom(d Decider) RetryPolicy
Custom returns a policy that delegates every decision to d.
func Exponential ¶
func Exponential(attempts uint32, base, max time.Duration, jitter float64) RetryPolicy
Exponential returns a policy with exponential backoff: the delay after attempt N is min(base × 2^(N-1), max), optionally scaled by ±jitter.
func Fixed ¶
func Fixed(attempts uint32, delay time.Duration) RetryPolicy
Fixed returns a policy that retries up to attempts times with a constant delay between attempts.
func NoRetry ¶
func NoRetry() RetryPolicy
NoRetry returns a policy that deadletters on the first failure.
func (RetryPolicy) NextDelay ¶
func (p RetryPolicy) NextDelay(attempt uint32) (time.Duration, bool)
NextDelay decides whether to retry after the given (1-based) failed attempt, and if so, how long to wait. It returns (delay, retry). When retry is false the job should deadletter and delay is zero. Mirrors the Rust `RetryPolicy::decide`, projected to the (Duration, bool) shape the spec asks for.
func (RetryPolicy) ShouldRetry ¶
ShouldRetry is the error-aware retry decision: it layers the typed fatal classification over NextDelay. Resolution order, worst-outcome-first:
- errors.Is(execErr, ErrSkipRetry) → (0, false) — sentinel veto.
- p.NonRetryable != nil && p.NonRetryable(execErr) → (0, false) — policy veto.
- otherwise → p.NextDelay(attempt).
A nil execErr is treated as "no fatal classification" so ShouldRetry composes safely with callers that pass the last execution error. attempt is the 1-based number of the attempt that just failed. This is the method the scheduler consults (decideRetry); NextDelay remains the pure attempt-only decision for callers that have no error in hand.
type Scheduler ¶
type Scheduler interface {
// Tick drives the DAG one round forward and returns the rollup. A
// non-nil error means the DAG itself was malformed (e.g. a cycle);
// per-job failures are reported via phases/transitions, not the error.
Tick(ctx context.Context, dag *Dag) (TickReceipt, error)
// Snapshot returns the current phase of every known job.
Snapshot() map[JobID]JobPhase
}
Scheduler is the single-step runtime. One Tick advances the registered jobs over the supplied DAG by one round; the LOOP is the CALLER's responsibility (a daemon loops Tick → wait-for-change → Tick; a K8s reconciler maps each CR event to one Tick). It mirrors the Rust `Scheduler` trait. Tick never loops internally.
type Signal ¶
type Signal struct {
// Kind is the discriminant.
Kind SignalKind
// Gate is the gate aggregate, valid when Kind == SigEvaluateGates.
Gate GateAggregate
// SkipReason is the carried reason when Gate == AggSkipped (or for an
// operator skip transition).
SkipReason SkipReason
// Retry is the retry outcome, valid when Kind == SigRetryDecide.
Retry RetryOutcomeKind
// OperatorTarget is the target phase, valid when
// Kind == SigOperatorTransition.
OperatorTarget JobPhase
}
Signal drives the FSM. Construct one via the helper constructors (EvaluateGates, AllocateBudget, …) rather than building the struct by hand, so the right payload field is always populated for the kind.
func AllocateBudget ¶
func AllocateBudget() Signal
AllocateBudget builds the SigAllocateBudget signal.
func BackoffElapsed ¶
func BackoffElapsed() Signal
BackoffElapsed builds the SigBackoffElapsed signal.
func EvaluateGates ¶
func EvaluateGates(agg GateAggregate, reason SkipReason) Signal
EvaluateGates builds a SigEvaluateGates signal carrying the gate aggregate. When agg == AggSkipped, pass the reason; otherwise reason is ignored.
func ExecutionFailed ¶
func ExecutionFailed() Signal
ExecutionFailed builds the SigExecutionFailed signal.
func ExecutionSucceeded ¶
func ExecutionSucceeded() Signal
ExecutionSucceeded builds the SigExecutionSucceeded signal.
func OperatorTransition ¶
func OperatorTransition(target JobPhase, reason SkipReason) Signal
OperatorTransition builds the SigOperatorTransition signal targeting the given phase. For a target of Skipped, set reason; otherwise reason is ignored.
func RetryDecide ¶
func RetryDecide(outcome RetryOutcomeKind) Signal
RetryDecide builds the SigRetryDecide signal carrying the retry outcome.
func (Signal) IsOperatorDriven ¶
IsOperatorDriven reports whether the signal came from an operator command. Operator-driven transitions get logged with extra metadata. Mirrors the Rust `Signal::is_operator_driven`.
type SignalKind ¶
type SignalKind int
SignalKind is the discriminant of a Signal — every legal way a Job's phase can change. It mirrors the variants of the Rust `Signal` enum (theory/SHIGOTO.md §IV.1).
const ( // SigEvaluateGates re-evaluates the gate cohort for a Pending, Gated, // Ready or Retrying Job. The rolled-up outcome rides in Signal.Gate so // the FSM stays pure (gate evaluation itself lives in the Gate cohort). SigEvaluateGates SignalKind = iota // SigAllocateBudget means the scheduler reserved a slot for a Ready Job. SigAllocateBudget // SigExecutionSucceeded means Execute returned ok. SigExecutionSucceeded // SigExecutionFailed means Execute returned an error. SigExecutionFailed // SigRetryDecide carries the retry decision after Failed. The outcome // rides in Signal.Retry. SigRetryDecide // SigCancel is cooperative cancellation of a Running Job (→ Failed). SigCancel // SigTimeout means a Running Job's per-job timeout elapsed (→ Failed). SigTimeout // SigBackoffElapsed means a Retrying Job's backoff window elapsed // (→ Pending). SigBackoffElapsed // SigOperatorTransition is an operator-driven transition. The target // phase rides in Signal.OperatorTarget; legal only for // (WaitingForOperator → Ready|Skipped) and (Deadlettered → Pending). SigOperatorTransition )
func (SignalKind) String ¶
func (k SignalKind) String() string
String returns the stable kebab-case name of the signal kind.
type SkipReason ¶
type SkipReason int
SkipReason explains why a Job advanced to Skipped. Mirrors the Rust `SkipReason` enum; the free-form Other case carries an arbitrary string.
const ( // SkipGateRejected — a gate returned Skip. SkipGateRejected SkipReason = iota // SkipBlockedByDeadletteredAncestor — an upstream deadlettered and the // cascade rule skips this descendant. SkipBlockedByDeadletteredAncestor // SkipOperatorDecision — an operator chose to skip. SkipOperatorDecision // SkipOther — any other reason (free-form, see TransitionReason for the // human string). SkipOther )
func (SkipReason) String ¶
func (r SkipReason) String() string
String returns the stable kebab-case name of the skip reason.
type TickReceipt ¶
type TickReceipt struct {
// TickAt is when the tick began.
TickAt time.Time
// PhaseCounts is the count of jobs in each named phase (stable kebab-case
// keys), in sorted-key order.
PhaseCounts map[string]uint32
// Transitions are the phase changes that fired during this tick, in the
// order they occurred.
Transitions []Transition
// Unhealed are the jobs requiring operator attention — Deadlettered or
// WaitingForOperator — in a deterministic order.
Unhealed []UnhealedDrift
}
TickReceipt is the derived per-tick rollup the scheduler emits from Tick. It mirrors the Rust `TickReceipt`.
type Transition ¶
type Transition struct {
// At is when the transition occurred.
At time.Time `json:"at"`
// JobID identifies the job that transitioned.
JobID JobID `json:"job_id"`
// From is the prior phase. Marshalled as its stable string name.
From JobPhase `json:"from"`
// To is the new phase. Marshalled as its stable string name.
To JobPhase `json:"to"`
// Reason is why the transition fired.
Reason TransitionReason `json:"reason"`
// Tool is the consumer-name tag (e.g. "tend", "forge-gen").
Tool string `json:"tool"`
}
Transition is one recorded FSM phase change — the unit the audit log is made of. It mirrors the Rust `TransitionEvent`.
type TransitionEmitter ¶
type TransitionEmitter interface {
// Emit records one transition. It must not block the caller for long and
// must never panic.
Emit(t Transition)
}
TransitionEmitter receives every FSM transition. Implementations are the audit/observability sinks; the scheduler calls Emit on each phase change. Mirrors the Rust `shigoto-emit::TransitionEmitter` trait.
Emit must be non-blocking and append-only: it appends the event to a log and returns promptly, never blocking the scheduler on slow IO.
type TransitionReason ¶
type TransitionReason struct {
// Kind is the stable cause label (e.g. "gate-evaluation",
// "execution-failed", "operator-action").
Kind string `json:"kind"`
// Detail is an optional human string (error message, operator note).
Detail string `json:"detail,omitempty"`
}
TransitionReason is the cause of an FSM transition, mirroring the Rust `TransitionReason` enum. The free-form Detail carries an operator note or an error string where applicable.
func ReasonExecutionFailed ¶
func ReasonExecutionFailed(detail string) TransitionReason
ReasonExecutionFailed builds an execution-failed reason carrying the error detail.
func ReasonFromSignal ¶
func ReasonFromSignal(sig Signal) TransitionReason
ReasonFromSignal derives the canonical TransitionReason from the signal that drove a transition, mirroring the Rust scheduler's `reason_from`.
func ReasonOperatorAction ¶
func ReasonOperatorAction(note string) TransitionReason
ReasonOperatorAction builds an operator-action reason carrying the note.
type UnhealedDrift ¶
type UnhealedDrift struct {
// JobID is the stuck job.
JobID JobID
// Phase is its current (stuck) phase.
Phase JobPhase
// AgeSeconds is how long it has been stuck. Reserved; currently 0.
AgeSeconds uint64
}
UnhealedDrift names a job stuck in a phase that needs operator attention. Mirrors the Rust `UnhealedDrift`. AgeSeconds is reserved (0) until per-job last-advanced timestamps are tracked.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package delivery is the Go mirror of the GSDS Delivery FSM Type System — the four typed, pure, table-driven finite state machines (one per Go artifact class) that govern every case of software delivery.
|
Package delivery is the Go mirror of the GSDS Delivery FSM Type System — the four typed, pure, table-driven finite state machines (one per Go artifact class) that govern every case of software delivery. |
|
Package render is the borealis-rendered presentation leaf for shigoto's user-facing values (TickReceipt, the Unhealed drift table, per-phase reports).
|
Package render is the borealis-rendered presentation leaf for shigoto's user-facing values (TickReceipt, the Unhealed drift table, per-phase reports). |