Documentation
¶
Index ¶
- Constants
- Variables
- func ChildRunID(parentRunID, nodePath string) string
- type AbortAskedEvent
- type AbortSettledEvent
- type AggregateInputsEvent
- type Attempt
- type AttemptCompletedEvent
- type BranchRoutedEvent
- type BudgetExceededEvent
- type CallRequest
- type CallResult
- type Candidate
- type Checkpoint
- type Completion
- func Failure(stopReason, cause string, d time.Duration) Completion
- func Proposal(proposalID string, d time.Duration) Completion
- func ProposalWithDiff(proposalID string, changedLines int, d time.Duration) Completion
- func Report(text string, d time.Duration) Completion
- func TerminalFailure(stopReason, cause string, d time.Duration) Completion
- type Config
- type Contract
- type Dispatch
- type DispatchStartedEvent
- type Event
- type EventKind
- type FakeRuntime
- func (f *FakeRuntime) Advance(d time.Duration)
- func (f *FakeRuntime) Backoff(_ context.Context, d time.Duration) error
- func (f *FakeRuntime) Backoffs() []time.Duration
- func (f *FakeRuntime) Block(_ context.Context) error
- func (f *FakeRuntime) Blocks() int
- func (f *FakeRuntime) Call(_ context.Context, req CallRequest) (CallResult, error)
- func (f *FakeRuntime) Calls() []CallRequest
- func (f *FakeRuntime) Cancel(h Handle) error
- func (f *FakeRuntime) Cancels() []string
- func (f *FakeRuntime) Completed(h Handle) (Completion, bool)
- func (f *FakeRuntime) InFlight() int
- func (f *FakeRuntime) Now() time.Time
- func (f *FakeRuntime) Peak() int
- func (f *FakeRuntime) SetNow(t time.Time)
- func (f *FakeRuntime) Settle(_ context.Context, req SettleRequest) (Settled, error)
- func (f *FakeRuntime) Settles() []SettleRequest
- func (f *FakeRuntime) Start(_ context.Context, d Dispatch) (Handle, error)
- func (f *FakeRuntime) Started() []Dispatch
- type FanoutExpandedEvent
- type FanoutItem
- type GateEvaluatedEvent
- type GuardFunc
- type Handle
- type InstanceState
- type Ledger
- type Limits
- type LoopCompletedEvent
- type LoopIteration
- type LoopIterationStartedEvent
- type NodeCancelledEvent
- type NodeFailedEvent
- type NodeOutput
- type NodeReadyEvent
- type NodeSkippedEvent
- type NodeState
- type NodeSucceededEvent
- type ProposalHandle
- type ProposalRef
- type ProposalSettledEvent
- type Recovery
- type Result
- type RetryScheduledEvent
- type Run
- func (r *Run) Advance(ctx context.Context) (bool, error)
- func (r *Run) Apply(ev Event) error
- func (r *Run) Cancel(reason string) error
- func (r *Run) Checkpoint() Checkpoint
- func (r *Run) Events() []string
- func (r *Run) Execute(ctx context.Context) (Result, error)
- func (r *Run) Node(path string) (NodeState, bool)
- func (r *Run) Result() Result
- func (r *Run) Status() RunStatus
- type RunFinishedEvent
- type RunResumedEvent
- type RunStartedEvent
- type RunStatus
- type Runtime
- type ScopeSnapshot
- type SelectChosenEvent
- type SelectResolvedEvent
- type SettlePlan
- type SettleRequest
- type Settled
- type SettlementAskedEvent
- type SettlementPlannedEvent
- type State
- type Store
Constants ¶
const ( // ReasonAggregateInputsEmpty prefixes an aggregate that declares no inputs: // there is nothing to combine, and an empty combined value would look like a // successful combine of nothing. ReasonAggregateInputsEmpty = "aggregate_inputs_empty" // source, a producer that did not succeed, or a field the value does not // carry. ReasonAggregateInputUnavailable = "aggregate_input_unavailable" // ReasonAggregateStrategyUnsupported names a strategy outside the three the // vocabulary declares. ReasonAggregateStrategyUnsupported = "aggregate_strategy_unsupported" // ReasonAggregateBodyMissing prefixes a summarize with no body to dispatch. ReasonAggregateBodyMissing = "aggregate_body_missing" // ReasonAggregateBodyUnresolved prefixes a body node whose need names nothing // in the aggregate's scope. ReasonAggregateBodyUnresolved = "aggregate_body_unresolved" // ReasonAggregateBodyFailed names a summarize whose body failed. ReasonAggregateBodyFailed = "aggregate_body_failed" // ReasonAggregateCombineFailed prefixes a combine that could not be performed: // an input of the wrong shape for the strategy, or a value that would not // encode as the node's recorded text. ReasonAggregateCombineFailed = "aggregate_combine_failed" )
Reasons the aggregate family states.
const ( // `on` source, a producer that did not succeed, an `on` carrying a predicate, // or a case naming a step that is not in the graph. ReasonBranchSourceUnavailable = "branch_source_unavailable" // ReasonBranchArmNotSelected names an arm the branch did not choose. It is the // reason a skip is declared, not a failure: the author declared the routing. ReasonBranchArmNotSelected = "branch_arm_not_selected" )
Reasons the branch family states.
const ( AxisMaxDispatches = "max_dispatches" AxisMaxWallClock = "max_wall_clock" AxisMaxConcurrentDispatches = "max_concurrent_dispatches" )
Budget axes named in BudgetExceededEvent and Result.Reason. They are strings rather than an enum so the event log states which ceiling ran out in the same words Limits documents.
const ( StatusProposal = "proposal" StatusReport = "report" StatusCompleted = "completed" StatusError = "error" )
Envelope status values, verbatim from the dispatch vocabulary.
const ( // run cannot resolve: no source, an out-of-scope step, a producer that did // not succeed, or a field the value does not carry. Fanning out to zero // items would make an unreadable source look like "no work to do", which is // the quiet outcome this reason exists to prevent. ReasonFanoutOverUnavailable = "fanout_over_unavailable" // ReasonFanoutBodyMissing prefixes a fan-out with no body to run per item. ReasonFanoutBodyMissing = "fanout_body_missing" // ReasonFanoutBodyUnresolved prefixes a body node whose need names nothing // in its item scope. Such an instance could never become ready, so the // fan-out would stay open forever; the expansion refuses instead. ReasonFanoutBodyUnresolved = "fanout_body_unresolved" // ReasonFanoutItemFailed names the item behind a failed fan-out: under // on_item_failure: abort the container fails with this reason and the run // stops scheduling. ReasonFanoutItemFailed = "fanout_item_failed" // ReasonFanoutCollectFailed prefixes a collected value that could not be // encoded as the node's recorded text. ReasonFanoutCollectFailed = "fanout_collect_failed" )
Reasons the fan-out family states.
const ( // ReasonGateDeclarationInvalid prefixes a gate that names no condition, or // two of them: a gate has exactly one question, and a second would leave // the run choosing which answer wins. ReasonGateDeclarationInvalid = "gate_declaration_invalid" // ReasonGateAssertUnknown names an assert outside the registry allowlist. ReasonGateAssertUnknown = "gate_assert_unknown" // ReasonGateAssertArgs names arguments the named check does not read, or // reads in another shape. ReasonGateAssertArgs = "gate_assert_args_invalid" // ReasonGateJudgeMissing names a judge with no role (or no prompt): nobody // is named to decide. ReasonGateJudgeMissing = "gate_judge_missing" // read from this run: a `from` naming no step, or one that is not in reach. ReasonGateSubjectUnavailable = "gate_subject_unavailable" // ReasonGateVerdictInvalid prefixes a judge result that is not a structured // verdict at all, or one that contradicts itself. ReasonGateVerdictInvalid = "gate_verdict_invalid" // ReasonGateFailed prefixes a failing assert with no on_fail to route to. // The author's on_failure disposition raises it from here. ReasonGateFailed = "gate_assertion_failed" // ReasonGateEscalated prefixes a judge verdict that asks for a human // decision. It is terminal whatever on_fail says: an escalation is the // judge's own refusal to decide, so routing past it would answer the // question the judge declined to. ReasonGateEscalated = "gate_escalated" // ReasonGateArmUnknown names an on_pass/on_fail that resolves to no step in // this graph. ir.resolveGate refuses it in an authored document, so only a // hand-built graph reaches this. ReasonGateArmUnknown = "gate_arm_unknown" // ReasonGateArmNotTaken names a gate arm the gate did not route to. It is // the reason a skip is declared, not a failure: the author declared the // routing. ReasonGateArmNotTaken = "gate_arm_not_taken" )
Reasons the gate family states.
const ( // DispositionPass is an assert that held, or a judge that said pass. DispositionPass = "pass" // DispositionFail is an assert that did not hold, or a judge that said fail. DispositionFail = "fail" // DispositionEscalate is a judge that declined to decide. DispositionEscalate = "escalate" )
Gate disposition vocabulary. These strings are the value a gate reports, so they are the words a selector matches on and a report quotes.
const ( // ReasonFanoutJoinUnmet prefixes a container whose join can no longer be // satisfied: enough items have terminated without succeeding that the // remaining ones cannot make up the count. Waiting for them would be waiting // for an answer the run can already prove it will never get. ReasonFanoutJoinUnmet = "fanout_join_unmet" // ReasonFanoutQuorumInvalid names a join: quorum declaration that is not a // usable count — no quorum at all, one below 1, or one above the number of // items the `over` source resolved to. It is a declaration refusal, so it is // stated before a single item dispatches. ReasonFanoutQuorumInvalid = "fanout_quorum_invalid" // ReasonFanoutJoinAbandoned is the reason an item the join did not wait for // carries: the container is already terminal, so this item's work is recorded // and never folded into the container's value. ReasonFanoutJoinAbandoned = "fanout_join_abandoned_item" )
Reasons the join family states.
const ( // ReasonNotImplemented prefixes a node whose kind the core does not // execute yet. The suffix names the bead that owns the kind. ReasonNotImplemented = "not_implemented" // ReasonUpstreamSkipped prefixes a node skipped because a need of it was // skipped: its input was never produced. ReasonUpstreamSkipped = "upstream_skipped" // ReasonUpstreamCancelled prefixes a node cancelled because a need of it // was cancelled. ReasonUpstreamCancelled = "upstream_cancelled" // ReasonGuardFalse is a node its own `when` guard refused. ReasonGuardFalse = "when guard is false" // ReasonGuardError prefixes a guard that failed to evaluate. ReasonGuardError = "guard_error" // ReasonRuntimeError prefixes a door malfunction: no envelope exists, so // nothing is asserted about retryability and the node is terminal. ReasonRuntimeError = "runtime_error" // ReasonDispatchFailed prefixes a node whose attempts are done and whose // last envelope reported status=error. ReasonDispatchFailed = "dispatch_failed" // ReasonRunStopped prefixes a node the run stopped before it could start. ReasonRunStopped = "run_stopped" // ReasonCancelledByRun prefixes a running attempt the run cancelled. ReasonCancelledByRun = "cancelled_by_run" // ReasonUnknownKind prefixes a node whose kind is not in the resolved // vocabulary at all: a hand-built graph, not an authored document. ReasonUnknownKind = "unknown_kind" // ReasonCallWorkflowMissing prefixes a call node that names no workflow: // a declaration fact, so the node may not run at all. ReasonCallWorkflowMissing = "call_workflow_missing" // ReasonCallFailed prefixes a call whose nested workflow did not succeed // — the child run failed, aborted, or exhausted a budget, or the door // refused the request itself. ReasonCallFailed = "call_failed" )
Terminal reasons. The scheduler states a cause for every node it ends in a non-success state; an unexplained terminal node is a bug in this package.
const ( // ReasonLoopBodyMissing prefixes a loop with no body to iterate. ReasonLoopBodyMissing = "loop_body_missing" // ReasonLoopUnbounded prefixes a loop that declares no max_iterations. A // deterministic core that invented a bound would be inventing a host policy // nobody authored, and one that iterated without a ceiling would not // terminate; WF034 reports the declaration and the run refuses instead. ReasonLoopUnbounded = "loop_unbounded" // no source, a producer that did not succeed, a field the collected value // does not carry, or a read of the loop's own output. Fanning out to "the // condition never matched" on any of those would run the loop to its bound // and call the ceiling an answer. ReasonLoopUntilUnavailable = "loop_until_unavailable" // ReasonLoopBodyUnresolved prefixes a body node whose need names nothing in // its own iteration scope. Such an instance could never become ready, so the // loop would stay open forever; the iteration refuses instead. ReasonLoopBodyUnresolved = "loop_body_unresolved" // ReasonLoopIterationFailed names the iteration behind a failed loop. ReasonLoopIterationFailed = "loop_iteration_failed" // ReasonLoopIterationsExhausted names a loop whose declared terminator never // matched within its declared bound. ReasonLoopIterationsExhausted = "loop_iterations_exhausted" // ReasonLoopCollectFailed prefixes an accumulation that could not be encoded // as the node's recorded text. ReasonLoopCollectFailed = "loop_collect_failed" )
Reasons the loop family states.
const ( // LoopTerminatedUntil: the declared terminator matched. LoopTerminatedUntil = "until" // LoopTerminatedBound: the declared max_iterations was reached. LoopTerminatedBound = "bound" )
Loop terminator words, carried on LoopCompletedEvent so the event log says which declaration ended the loop.
const ( // cannot resolve: no selector at all, an unreadable source, or a predicate // no element satisfies. An unresolvable set is not an empty one, and both // are refused rather than reported as a selection over nothing. ReasonSelectCandidatesUnavailable = "select_candidates_unavailable" // ReasonSelectCandidatesEmpty prefixes a set that resolved to zero // candidates: no policy can choose among nothing. WF028 reports the half a // document can prove; this is the run-time half. ReasonSelectCandidatesEmpty = "select_candidates_empty" // ReasonSelectJudgeMissing names `policy: judge` with no judge payload: // nobody is named to decide, so the selection has no rule. ReasonSelectJudgeMissing = "select_judge_missing" // ReasonSelectPolicyUnsupported names a policy outside the three the // vocabulary declares. Only a hand-built graph reaches it — ir.Resolve // refuses an unknown policy with a resolve error — so it is stated as a // refusal rather than left to crash. ReasonSelectPolicyUnsupported = "select_policy_unsupported" // ReasonSelectNoCandidate prefixes a set in which no candidate qualifies: // none succeeded, or none carried the fact the policy reads. ReasonSelectNoCandidate = "select_no_candidate" // ReasonSelectNoDiffMetadata names smallest_diff over a set where no // eligible candidate records a changed-line count. ReasonSelectNoDiffMetadata = "select_no_diff_metadata" // ReasonSelectVerdictInvalid prefixes a judge result that is not a // structured verdict at all: no JSON object, or no winner field. ReasonSelectVerdictInvalid = "select_verdict_invalid" // ReasonSelectVerdictUnmatched names a verdict that picked nobody in the // candidate set — an index out of range, or a ref no candidate carries. ReasonSelectVerdictUnmatched = "select_verdict_unmatched" )
Reasons the selection family states.
const ( // ReasonProposalAlreadySettled is the runtime linearity guard: a proposal // has exactly one disposition, so a settle naming an id this run already // disposed of is refused before any settlement is asked for. ReasonProposalAlreadySettled = "proposal_already_settled" // ReasonProposalSettleInFlight is the same guard seen from the other side: // another settle node holds the proposal right now. ReasonProposalSettleInFlight = "proposal_settle_in_flight" // ReasonOpenProposalsAtExit is the run-level half of the guard: a run must // not report success while a proposal it sealed has no disposition. The // v1 vocabulary declares no on_abort field for that residue (WF025 says so // at its own rule), so the escape is the caller's Config.OpenProposals. ReasonOpenProposalsAtExit = "open_proposals_at_run_end" // ReasonSettlementFailed prefixes a door malfunction or a settlement whose // status came back neither settled nor conflict. ReasonSettlementFailed = "settlement_failed" // ReasonSettleActionUnsupported names a settle action outside the four // settlement verbs. continue and fork are NOT settlement verbs — they are // re-run bindings on a delegate (continue_from / fork_from) — so they are // refused here rather than mapped. ReasonSettleActionUnsupported = "unsupported_settle_action" // scheduler cannot resolve from recorded run state: an output carrying no // proposal handle, an item binding inside a container body, or a filter // field no handle has. ReasonSettleSourceUnavailable = "settle_source_unavailable" // ReasonNoProposalsMatched is on_empty: fail — matching nothing was an // outcome the author declared unacceptable. ReasonNoProposalsMatched = "no_proposals_matched" )
Reasons and statuses the settlement family states.
const ( SettlementStatusSettled = "settled" SettlementStatusConflict = "conflict" SettlementStatusError = "error" )
Settlement statuses, verbatim from the proposal runtime's one settlement envelope. The scheduler never synthesizes one.
const AttemptStatusInterrupted = "interrupted"
AttemptStatusInterrupted marks an attempt the run was killed during. It is not an envelope status — no lane reports it — which is exactly why it is worth recording: the attempt history shows work that was started and whose outcome the world never told us.
const ReasonEmitValueFailed = "emit_value_failed"
ReasonEmitValueFailed prefixes an emit node whose declared value could not be rendered against the run's scope. The scope's own error names the cause — an unbound param, a step that never produced an output, or a `collect` reference this bead does not resolve — so the reason stays a quotation of the fence rather than a second opinion about it.
const ReasonSettlementInterrupted = "settlement_outcome_unknown"
ReasonSettlementInterrupted is the refusal a reset settle node states when a disposition was asked for and the run stopped before the door answered. The proposal is left open, and the run cannot report success while it is, so the gap is visible instead of being papered over with a second ask.
Variables ¶
var ( // ErrRunNotFound is reported by a Store that holds no checkpoint for the // requested run id. ErrRunNotFound = errors.New("workflow/exec: no persisted run") // ErrSpecHashMismatch refuses a resume against a document other than the one // the run was started from. ErrSpecHashMismatch = errors.New("workflow/exec: spec hash mismatch") // ErrRunAlreadyFinished refuses a resume of a run whose disposition is // already final. ErrRunAlreadyFinished = errors.New("workflow/exec: run already finished") )
Errors a resume reports. They are distinct because the caller's response differs: a missing run is "wrong run id", a finished run is "nothing to do", and a hash mismatch is "the document changed".
Functions ¶
func ChildRunID ¶ added in v0.191.0
ChildRunID derives the durable identity of a call's child run from the parent's run id and the call node's path. The derivation is total and holds no state, which is the whole idempotency story: any process that resumes the same parent run and reaches the same call node computes the same id, finds the child's record, and continues the child where it stopped instead of running it again.
Types ¶
type AbortAskedEvent ¶ added in v0.192.0
AbortAskedEvent records the abort-time disposition the run is about to ask the door for, in settlement_asked's write-ahead shape (yaah-0u0v.24): the reducer commits it — and the store persists it — BEFORE the door is called. Action carries the door's verb for the log line. The ask it records is permanent for the proposal it names: the door's one-disposition invariant is what a resumed run leans on refusing to ask a second time.
func (AbortAskedEvent) Kind ¶ added in v0.192.0
func (AbortAskedEvent) Kind() EventKind
type AbortSettledEvent ¶ added in v0.192.0
AbortSettledEvent carries one abort-time disposition's outcome back from the door. DoorError reports that the door itself malfunctioned: there is no settlement envelope behind it, the proposal keeps whatever state it had, and the run's close is the report of what that left open.
func (AbortSettledEvent) Kind ¶ added in v0.192.0
func (AbortSettledEvent) Kind() EventKind
type AggregateInputsEvent ¶ added in v0.185.0
AggregateInputsEvent carries the values one aggregate's inputs resolved to, in declaration order. Refusal carries an input the run could not read, which the reducer turns into the aggregate's terminal state rather than combining a shorter list than the author declared.
func (AggregateInputsEvent) Kind ¶ added in v0.185.0
func (AggregateInputsEvent) Kind() EventKind
type Attempt ¶
type Attempt struct {
// Number is the 1-based per-node attempt ordinal.
Number int
// NodePath and DispatchID identify the attempt absolutely; DispatchID is
// "<node path>#<number>", which is the shape the dispatch envelope's
// dispatch_id already uses.
NodePath string
DispatchID string
// Role and Lane echo the node's declared dispatch identity for the trace
// surface; they are facts of the graph, not of the envelope.
Role string
Lane string
// Backoff is the virtual or real delay the run waited before starting
// this attempt, honored through Runtime.Backoff.
Backoff time.Duration
// Handle is the door's reference to the started attempt.
Handle Handle
StartedAt time.Time
FinishedAt time.Time
// Status is the envelope's status: proposal, report, shared, completed,
// or error.
Status string
// StopReason is the envelope's typed stop reason. It is recorded verbatim;
// the scheduler never invents one and never infers one from error text.
StopReason string
// DurationMs is the envelope's wall-clock span of the dispatch.
DurationMs int64
Model string
World string
ProposalID string
Result string
Error string
// Partial mirrors the envelope's flag that Result is what the run produced
// before it stopped.
Partial bool
// Retryable is the envelope's recovery.retryable, verbatim.
Retryable bool
// RecoveryAsserted records whether the envelope carried a recovery block
// at all. Absent is a third value distinct from "retryable: false", and
// the scheduler treats it as no licence to retry.
RecoveryAsserted bool
// Contract is the envelope's `contract.status` verdict, verbatim
// (yaah-was9.2). Empty means the lane asserted nothing about the result
// contract — which is what every envelope does today, since the field is
// reserved. The scheduler never derives a verdict of its own.
Contract string
// Cancelled marks an attempt the run stopped through the door. Its
// envelope, if it ever arrives, is dropped: the reducer's state is
// authoritative.
Cancelled bool
}
Attempt is one dispatched try of one node. Every envelope fact the completion carried is recorded here as it arrived, because trace records (yaah-0u0v.17) read attempt history and must not have to re-derive a duration, a model, or a world from per-lane plumbing.
type AttemptCompletedEvent ¶
type AttemptCompletedEvent struct {
NodePath string
DispatchID string
Attempt int
Completion Completion
// RuntimeError reports that the door itself malfunctioned — Start failed,
// or a completion arrived that the reducer cannot act on. There is no
// envelope behind it, so it asserts nothing about retryability and is
// terminal.
RuntimeError string
}
AttemptCompletedEvent carries one completion envelope back from the door. It is the only way a run learns that an attempt's work ended, and the only place failure semantics are decided.
func (AttemptCompletedEvent) Kind ¶
func (AttemptCompletedEvent) Kind() EventKind
type BranchRoutedEvent ¶ added in v0.185.0
BranchRoutedEvent reports a branch's decision: the step id of the arm the resolved value selected, empty when no case matched and no default was declared, and Refusal for a value the run could not route on. Value is the resolved value rendered as one log field, so the log line says what was matched as well as what was chosen.
func (BranchRoutedEvent) Kind ¶ added in v0.185.0
func (BranchRoutedEvent) Kind() EventKind
type BudgetExceededEvent ¶
BudgetExceededEvent records that a declared ceiling was reached. Axis and Limit are the same strings Limits documents, so a reader never has to map an enum to find out what ran out.
func (BudgetExceededEvent) Kind ¶
func (BudgetExceededEvent) Kind() EventKind
type CallRequest ¶ added in v0.191.0
type CallRequest struct {
// Node is the call node, immutable IR: the same single source of truth
// the dispatch and settle requests carry.
Node *ir.Node
// Workflow is the registry name the node declares.
Workflow string
// MaxDepth is the node's declared max_depth, zero when undeclared. The
// door reads it as this edge's bound: the number of copies of the named
// workflow that may be in effect along one call path.
MaxDepth int
// Params are the node's call parameters rendered against the run's
// snapshot: templates resolved to text, constants passed through.
Params map[string]any
// ParentRunID and NodePath derive the child run's durable identity, so
// a resume finds the child's record without any parent-side fact
// beyond the id derivation itself.
ParentRunID string
NodePath string
}
CallRequest is one nested workflow the run is asking the door to execute.
type CallResult ¶ added in v0.191.0
type CallResult struct {
Succeeded bool
// ChildRunID names the run record the child's state lives under.
ChildRunID string
// Status and Reason carry the child run's disposition for the report.
Status RunStatus
Reason string
// Outputs is the child's recorded output bindings by name — what
// `steps.<id>.output.<name>` reads in the parent.
Outputs map[string]string
// Warnings are door-side facts from the child (a declined artifact
// write, a binding the lane could not honor).
Warnings []string
}
CallResult is the child run's outcome as the reducer reads it: whether it succeeded, the identity its record lives under, the status and reason for the report, and the child's output bindings by name — what `steps.<id>.output.<name>` reads in the parent.
func CallOK ¶ added in v0.191.0
func CallOK(req CallRequest) CallResult
CallOK is the result a fake reports for a call nobody scripted: the child succeeded, under the run id the request derives.
type Candidate ¶ added in v0.187.0
type Candidate struct {
// Index is the candidate's position in the resolved list — declared order,
// and the tie-break every policy falls back to.
Index int `json:"index"`
// Ref is the candidate's identity as a verdict names it: the proposal id of
// a sealed handle, else the id/node/step the element carries.
Ref string `json:"ref,omitempty"`
// Node is the node path this candidate was correlated with, when the element
// named one in this run.
Node string `json:"node,omitempty"`
// State is the candidate's status. It is the correlated node's state when one
// was found, and otherwise StateSucceeded for a plain value and StateFailed
// for a failure record.
State State `json:"state,omitempty"`
// DiffLines is the changed-line count the candidate carries, or -1 when it
// carries none.
DiffLines int `json:"diff_lines"`
// Value is the candidate itself: what the node reports if this one wins.
Value any `json:"value,omitempty"`
// Reason is the candidate's own stated cause, when it has one.
Reason string `json:"reason,omitempty"`
}
Candidate is one element of a select node's resolved candidate set, as the reducer read it. It is the ledger a policy decides over and a trace quotes, so it records the facts the decision used rather than the decision itself.
type Checkpoint ¶ added in v0.186.0
type Checkpoint struct {
RunID string `json:"run_id"`
// SpecHash and SpecPath identify the document the run was started from.
SpecHash string `json:"spec_hash,omitempty"`
SpecPath string `json:"spec_path,omitempty"`
// GraphName is the document's metadata.name, kept so a listing can say which
// workflow a run id belongs to without resolving the document.
GraphName string `json:"graph_name,omitempty"`
Status RunStatus `json:"status"`
Reason string `json:"reason,omitempty"`
// Dispatches and PeakInFlight are the run's tallies so far: a resumed run
// keeps spending the same budget, and the concurrency ceiling is measured
// against the same dispatches.
Dispatches int `json:"dispatches"`
PeakInFlight int `json:"peak_in_flight,omitempty"`
StartedAt time.Time `json:"started_at,omitempty"`
FinishedAt time.Time `json:"finished_at,omitempty"`
// Params are the parameters the run bound at New. A resume restores them
// rather than re-binding from the caller: templates already rendered against
// these values, and a run resumed under different params would be a
// different run with the same id.
Params map[string]any `json:"params,omitempty"`
Ledger Ledger `json:"ledger"`
// Seq is the last event sequence number the run wrote.
Seq int `json:"seq"`
// Nodes is every node's state in canonical result order — a top-level node
// followed by the instances its containers minted. Instances describes those
// instance paths, in the same order.
Nodes []*NodeState `json:"nodes"`
Instances []InstanceState `json:"instances,omitempty"`
Warnings []string `json:"warnings,omitempty"`
// EventBase is the number of log lines the store has already recorded, so a
// save writes only what is new. Events are those new lines, oldest first.
EventBase int `json:"event_base,omitempty"`
Events []string `json:"events,omitempty"`
// TraceBase and Trace are the same pair for the run's trace records
// (yaah-0u0v.17): the count the store already holds, and the new records in
// sequence order. A record is a typed projection of one event line, so the
// two append in lockstep and a resumed run's trace continues the sequence
// instead of restarting it.
TraceBase int `json:"trace_base,omitempty"`
Trace []trace.Record `json:"trace,omitempty"`
}
Checkpoint is the durable projection of one run at one instant: everything the reducer had committed when Apply last returned.
type Completion ¶
type Completion struct {
// Status is the envelope status: proposal, report, shared, completed, or
// error.
Status string `json:"status"`
// DispatchID names the dispatch that produced this completion.
DispatchID string `json:"dispatch_id,omitempty"`
Role string `json:"role,omitempty"`
Lane string `json:"lane,omitempty"`
World string `json:"world,omitempty"`
Model string `json:"model,omitempty"`
// DurationMs is the wall-clock span the lane reported for the dispatch.
DurationMs int64 `json:"duration_ms,omitempty"`
// StopReason is the envelope's typed reason: completed, turn_budget,
// iteration_budget, max_tokens, timeout, stuck, halted, canceled, or
// provider_error.
StopReason string `json:"stop_reason,omitempty"`
// ProposalID is set when the attempt sealed a proposal. The scheduler
// records it and does nothing else with it: settlement verbs are
// yaah-0u0v.13's, and a node's lifecycle deliberately leaves the
// proposal it produced open rather than disposing of it here.
ProposalID string `json:"proposal_id,omitempty"`
// Result is the delivered text or the sealed envelope's result body.
Result string `json:"result,omitempty"`
// Error is the untruncated cause of a status=error completion.
Error string `json:"error,omitempty"`
Partial bool `json:"partial,omitempty"`
// Recovery is the envelope's recovery block. A nil Recovery means the
// producer asserted nothing about re-dispatch, which is not an assertion
// that a retry is allowed.
Recovery *Recovery `json:"recovery,omitempty"`
// Contract is the envelope's `contract` block (yaah-was9.2): the per-role
// response contract the delivered result was checked against. It is
// mirrored verbatim and never synthesized — a nil Contract means the lane
// asserted nothing, which is what every dispatch lane does today while the
// field is reserved. Absent is not "checked and passed", and a typed
// workflow output that needs a verdict reads this field instead of
// running its own validator.
Contract *Contract `json:"contract,omitempty"`
}
Completion is the scheduler's view of the ONE dispatch completion envelope (yaah-was9.1). It is the same JSON contract the model-facing surface reads — every field name below is the envelope's own tag — but it is a separate type, because the scheduler core may not import internal/dispatch: that package links internal/tools/substrate, and this package must have no internal/tools dependency at all. The producer that bridges the two is the dispatch adapter (wired outside this package), and envelope_parity_test.go pins the mirror by decoding an envelope rendered by dispatch.Run's own result type into Completion and checking the scheduler-visible facts survive.
The scheduler reads exactly three things from a completion: whether the status says the attempt completed, whether the envelope's recovery block asserts the work is worth re-dispatching, and the facts to record. It never inspects error prose to decide either of the first two.
func Failure ¶
func Failure(stopReason, cause string, d time.Duration) Completion
Failure is a status=error completion whose envelope asserts retryability — the shape dispatch.RecoveryFor produces for a provider error or a timeout.
func Proposal ¶
func Proposal(proposalID string, d time.Duration) Completion
Proposal is the completion a successful proposal-lane dispatch returns: the lane sealed a proposal and left it open, which is what the settlement verbs (yaah-0u0v.13) will act on.
func ProposalWithDiff ¶ added in v0.187.0
func ProposalWithDiff(proposalID string, changedLines int, d time.Duration) Completion
ProposalWithDiff is the completion a successful proposal-lane dispatch returns when the lane also reports how big the change is: the sealed proposal id, and a result body carrying the changed-line count the selection policies read (yaah-0u0v.20). The count is delivered as the payload's own field, which is where a real lane puts it.
func Report ¶
func Report(text string, d time.Duration) Completion
Report is the completion a successful report-lane dispatch returns, with the result text the node would deliver.
func TerminalFailure ¶
func TerminalFailure(stopReason, cause string, d time.Duration) Completion
TerminalFailure is a status=error completion whose envelope asserts that re-dispatching is worthless: the retry rule must not fire on it.
func (Completion) Completed ¶
func (c Completion) Completed() bool
Completed reports whether the envelope says the attempt finished its work. An empty or unknown status is not a completion: the scheduler refuses to credit success to a lane that could not name its outcome, because a succeeded node with no result is exactly the silent divergence from the envelope this package exists to avoid.
func (Completion) ContractStatus ¶ added in v0.183.0
func (c Completion) ContractStatus() string
ContractStatus is the envelope's contract verdict, verbatim, or empty when the envelope carried no contract block.
func (Completion) Duration ¶
func (c Completion) Duration() time.Duration
Duration is the reported wall-clock span.
func (Completion) Retryable ¶
func (c Completion) Retryable() bool
Retryable is the envelope's assertion, never a derivation. A missing recovery block reads as false.
type Config ¶
type Config struct {
// RunID labels the run. Empty asks the scheduler to mint one from the
// graph name; the value always lands in run_started.
RunID string
// SpecHash is the digest of the document this graph resolved from
// (spec.SpecHash). It is persisted with the run so a resume can refuse to
// continue a run against a document that has changed underneath it
// (yaah-0u0v.16). Empty declines the refusal, and is only appropriate for a
// caller that keeps no state.
SpecHash string
// SpecPath is the document path the run was started from, recorded as the
// caller named it. It is what `yaah workflow resume <run_id>` re-reads when
// no path is given. Informational: the scheduler never opens it.
SpecPath string
// Store is the durable projection of this run (yaah-0u0v.16). Nil means the
// run keeps no state, which is what a one-shot run and every deterministic
// test do.
//
// The store is written from inside the reducer, after every applied event
// and before Apply returns, so a run that stops at any point leaves a
// checkpoint that is exactly the state the reducer had committed — never a
// half-applied step. A save that fails is reported to the driver and NO
// further event is applied: a run whose state cannot be recorded must not
// advance, or a resume would re-do work the log never recorded.
Store Store
// Limits are the ceilings the caller declares. The scheduler adds none.
Limits Limits
// Params binds the workflow parameters the graph declares. A declared
// default fills an unbound name; a required param with neither is an
// error at New rather than a template that fails later.
Params map[string]any
// Guard evaluates node `when` selectors. Optional; see GuardFunc.
Guard GuardFunc
// OpenProposals is the caller's declaration that a run may finish
// succeeded while proposals it sealed are still undisposed.
//
// The default is the refusal: a run that ends with a worktree standing has
// left the author's work neither landed nor thrown away, and reporting
// that as success is the outcome WF021 and WF025 exist to prevent. The
// v1 vocabulary declares no per-node `on_abort` field to discharge it
// (validate/linearity.go says so at WF025's own rule), so the escape is
// stated by the host that owns the residue — an interactive caller that
// will settle from its own surface afterwards — rather than invented as a
// graph key the strict decoder would refuse. When that field lands, this
// flag becomes its folded default and the guard keeps the same reason.
OpenProposals bool
}
Config is a run's input, fixed at New.
type Contract ¶ added in v0.183.0
type Contract struct {
Name string `json:"name,omitempty"`
Status string `json:"status,omitempty"`
}
Contract mirrors dispatch.ResultContract: the name of the contract a result was checked against and the verdict, with the same JSON field names so the envelope parity test can decode one into the other.
type Dispatch ¶
type Dispatch struct {
Node *ir.Node
Attempt int
// DispatchID is "<node path>#<attempt>", the same identity the envelope
// reports back, so a trace can join the request and the completion.
DispatchID string
// Scope is the immutable snapshot of run state at start time. The
// adapter renders the node's templates against it. It is a snapshot and
// not the live run because a Runtime is allowed to read it after other
// nodes have terminated; reading live scheduler state from an adapter
// would be a data race against the event loop.
Scope ir.Scope
// Timeout is the node's declared timeout_seconds, converted. Zero means
// the node declared none. The scheduler does not implement timeouts — it
// has no timers — so this is plumbing for the lane that does.
Timeout time.Duration
// Deadline is the run's wall-clock budget expiry, when one is declared.
// Zero means undeclared.
Deadline time.Time
}
Dispatch is one attempt the run is asking the door to start. It carries the immutable IR node rather than a flattened argument struct: the node already holds the complete authored payload (role, prompt template, lane, provider, model, max_turns, grants, network, world, seed/continue/fork bindings), and a second shape would be a second source of truth that could drift from the graph the validator checked.
type DispatchStartedEvent ¶
type DispatchStartedEvent struct{ Attempt *Attempt }
DispatchStartedEvent records that the run handed one attempt to the Runtime door and the door accepted it. The driver mints the attempt before calling Start, because the attempt's dispatch id is part of the request; the state transition still happens here.
func (DispatchStartedEvent) Kind ¶
func (DispatchStartedEvent) Kind() EventKind
type Event ¶
type Event interface {
Kind() EventKind
// contains filtered or unexported methods
}
Event is one fact about a run. The marker method seals the interface: a caller outside this package cannot invent an event kind the reducer has never heard of, which is what makes the exhaustive switch in Apply total.
type EventKind ¶
type EventKind string
EventKind names one lifecycle fact. The vocabulary is fixed: a scheduler that needs a new word has found a new state, and states are the contract the trace surface, the persistence bead, and the CLI read.
const ( EventRunStarted EventKind = "run_started" // EventRunResumed records that a process picked a run up from its durable // checkpoint (yaah-0u0v.16). It is an ordinary input event — folded by the // reducer and persisted like every other fact — because the run id, the // status, and the log are all the run's own, and a resume that wrote them // out of band would be a second state owner. EventRunResumed EventKind = "run_resumed" EventNodeReady EventKind = "node_ready" EventDispatchStarted EventKind = "dispatch_started" EventAttemptCompleted EventKind = "attempt_completed" EventRetryScheduled EventKind = "retry_scheduled" EventNodeSucceeded EventKind = "node_succeeded" EventNodeFailed EventKind = "node_failed" EventNodeSkipped EventKind = "node_skipped" EventNodeCancelled EventKind = "node_cancelled" EventBudgetExceeded EventKind = "budget_exceeded" EventRunFinished EventKind = "run_finished" // EventSettlementPlanned reports the handle set one settle node resolved // from recorded run state; EventProposalSettled reports one disposition the // door's settlement path returned. Both are inputs: the driver reads the // graph's own facts and the world's own answers, and the reducer decides // what either means for the node and the run. EventSettlementPlanned EventKind = "settlement_planned" // EventSettlementAsked records that the run is about to ask the door for one // disposition (yaah-0u0v.16). It is the settlement write-ahead record: the // reducer commits it — and the store persists it — BEFORE the door is // called, so a run resumed after a crash can tell "asked, outcome unknown" // from "never asked". It carries no outcome and changes no disposition. EventSettlementAsked EventKind = "settlement_asked" EventProposalSettled EventKind = "proposal_settled" // EventAbortAsked and EventAbortSettled are the abort-time disposition // pass's half of the settlement discipline (yaah-0u0v.24). The run asks // through the SAME door — Runtime.Settle with release or discard — for // every proposal it has not disposed of when it ends without succeeding, // and the two events mirror settlement_asked / proposal_settled without // owning a node: the pass's subject is the run as a whole. The asked // record is permanent in one respect a settle node's is not: a proposal // the run asked for once is never asked for again, whatever became of // the first answer. EventAbortAsked EventKind = "abort_asked" EventAbortSettled EventKind = "abort_settled" // EventFanoutExpanded reports the item list one fan-out node resolved from // its declared `over` source (yaah-0u0v.14). It is the fan-out's answer to // the same question a settlement plan answers — what work does this node own // — and like the plan it is an input: the reducer instantiates the item // instances, and owns everything that follows. EventFanoutExpanded EventKind = "fanout_expanded" // EventLoopIterationStarted asks the reducer to instantiate one loop // iteration's body (yaah-0u0v.15); EventLoopCompleted reports what ended the // loop — its declared terminator, its declared bound, or a terminator the run // could not evaluate. Both are inputs: the driver decides WHEN, the reducer // decides what it means, and the instances a loop creates are ordinary nodes // from there on. EventLoopIterationStarted EventKind = "loop_iteration_started" EventLoopCompleted EventKind = "loop_completed" // EventBranchRouted reports the arm a branch's selector resolved to // (yaah-0u0v.15). It is the branch's whole decision as an input, so the // reducer applies it — record the arm, skip the rest — inside Apply. EventBranchRouted EventKind = "branch_routed" // EventAggregateInputs reports the values an aggregate's inputs resolved to // (yaah-0u0v.15). A deterministic strategy combines them in the reducer; a // summarize instantiates its body. EventAggregateInputs EventKind = "aggregate_inputs" // EventSelectResolved reports the candidate set one select node resolved from // its `candidates` selector (yaah-0u0v.20). It is the selection's answer to the // same question a fan-out expansion answers — what work does this node choose // among — and like the expansion it is an input: the reducer reads every // candidate into its ledger and decides what that means for the node. EventSelectResolved EventKind = "select_resolved" // EventSelectChosen reports the decision itself: which candidate won, by which // policy (yaah-0u0v.20). Only the reducer emits it — a deterministic policy // derives it from the candidate ledger, and a judge policy derives it from the // verdict its attempt delivered — so the decision lands in the log once, in the // one place a selection becomes a node's outcome. EventSelectChosen EventKind = "select_chosen" // EventGateEvaluated reports one gate's decision (yaah-0u0v.21): the // disposition a registry assert reached, or the verdict a judge delegate // delivered. It is the gate's whole condition as an input — the driver reports // what the check said, or the reducer reports what the judge's attempt said — // so the reducer applies it: record the value, route to the arm the gate // selected, skip the other, or end the node failed so the author's on_failure // disposition raises the failure. One event, both halves: a gate has one // decision and one place it becomes state. EventGateEvaluated EventKind = "gate_evaluated" )
Event kinds.
type FakeRuntime ¶
type FakeRuntime struct {
// Script maps a node path to the completions its attempts return, in
// attempt order. A path with no entry answers with Default.
Script map[string][]Completion
// Default answers attempts whose path has no scripted entries left. When
// a plain report is wanted, leave it zero — a zero Completion is not a
// completion, so use NewReport for the convenience.
Default Completion
// HasDefault marks Default as meaningful. Without it an exhausted script
// returns a completed report with the attempt's duration.
HasDefault bool
// StartErr scripts a door malfunction: a node path listed here fails to
// start, and the run records it as a runtime error with no envelope.
StartErr map[string]error
// CancelErr scripts a Runtime.Cancel error per dispatch id, so the
// cancel-error path on NodeState is reachable in a test.
CancelErr map[string]error
// SettleScript maps a proposal id to the settlement the door reports for
// it, so a settle node's dispositions are scripted as exactly as its
// completions are. A path with no entry answers with SettledOK.
SettleScript map[string]Settled
// SettleErr scripts a door malfunction on one settlement: the proposal is
// reported as untouched, the node ends with a runtime failure, and the
// path is reachable in a test.
SettleErr map[string]error
// CallScript maps a call node's workflow name to the results its calls
// return, in call order. A workflow with no entry answers CallOK: the
// child succeeded with no bindings.
CallScript map[string][]CallResult
// CallErr scripts a call door malfunction by workflow name: the request
// never produced an answer, and the node ends with a runtime error.
CallErr map[string]error
// Hold names the node paths whose attempts stay IN FLIGHT: Completed reports
// nothing for them until the attempt is cancelled (Cancel clears the hold).
// It is the one hook a cancellation test needs, because an ordinary scripted
// attempt completes the instant it starts — there would be nothing left to
// cancel (yaah-0u0v.19).
Hold map[string]bool
// contains filtered or unexported fields
}
FakeRuntime is the deterministic Runtime the scheduler is tested on, and the reference for what a real adapter must provide. Outcomes are scripted per node path, the clock is virtual, and nothing sleeps: no method blocks, so a test that drives a Run through Advance sees exactly the sequence the script describes.
The virtual clock is the part that makes wall-clock budgets testable. It advances by a scripted attempt's duration_ms at the moment that attempt's completion is *read back* — which the scheduler does from its own single-threaded commit loop — and by the delay of a retry backoff when Backoff is called. Neither depends on goroutine timing, so elapsed time is a deterministic function of the script.
A FakeRuntime is not safe for concurrent use, and does not need to be: the scheduler is the only caller, and it calls from one goroutine.
func NewFakeRuntime ¶
func NewFakeRuntime(t time.Time) *FakeRuntime
NewFakeRuntime returns a fake whose virtual clock starts at t.
func (*FakeRuntime) Advance ¶
func (f *FakeRuntime) Advance(d time.Duration)
Advance moves the virtual clock, which is how a test makes a wall-clock budget expire between two scheduler cycles.
func (*FakeRuntime) Backoff ¶
Backoff advances the virtual clock by d and returns immediately. Tests see the delay in the clock and in Backoffs; they never sleep.
func (*FakeRuntime) Backoffs ¶
func (f *FakeRuntime) Backoffs() []time.Duration
Backoffs returns the retry delays the run honored, in order.
func (*FakeRuntime) Blocks ¶
func (f *FakeRuntime) Blocks() int
Blocks counts the idle requests the scheduler made. A run that finished without ever calling Block did all its work in dispatch order.
func (*FakeRuntime) Call ¶ added in v0.191.0
func (f *FakeRuntime) Call(_ context.Context, req CallRequest) (CallResult, error)
Call answers one nested workflow call from the script, recording the request so a test can assert the params the reducer rendered. A workflow nobody scripted succeeds with no bindings: the plainest call is a plain success.
func (*FakeRuntime) Calls ¶ added in v0.191.0
func (f *FakeRuntime) Calls() []CallRequest
Calls returns the call requests the fake answered, in call order.
func (*FakeRuntime) Cancel ¶
func (f *FakeRuntime) Cancel(h Handle) error
func (*FakeRuntime) Cancels ¶
func (f *FakeRuntime) Cancels() []string
Cancels returns the dispatch ids the run asked to cancel, in request order.
func (*FakeRuntime) Completed ¶
func (f *FakeRuntime) Completed(h Handle) (Completion, bool)
Completed reports the scripted outcome once it has been read. The answer is stable: a re-poll returns the same completion and charges the clock only the first time, which is what lets the scheduler poll the head of its dispatch order until that attempt's turn to commit arrives.
func (*FakeRuntime) InFlight ¶
func (f *FakeRuntime) InFlight() int
InFlight reports the attempts started and not yet read back or cancelled.
func (*FakeRuntime) Now ¶
func (f *FakeRuntime) Now() time.Time
func (*FakeRuntime) Peak ¶
func (f *FakeRuntime) Peak() int
Peak reports the highest number of attempts the fake held in flight at once, which is the door-side view of the concurrency cap.
func (*FakeRuntime) SetNow ¶
func (f *FakeRuntime) SetNow(t time.Time)
SetNow places the virtual clock absolutely.
func (*FakeRuntime) Settle ¶ added in v0.184.0
func (f *FakeRuntime) Settle(_ context.Context, req SettleRequest) (Settled, error)
Settle reports the scripted settlement for one proposal id. A fake answers synchronously: a settlement is a world effect with one result, and the scheduler asks for one per cycle, so there is nothing to poll and no clock to advance. An id with no scripted entry is disposed of successfully, which is what lets a happy-path test script only the interesting outcomes.
func (*FakeRuntime) Settles ¶ added in v0.184.0
func (f *FakeRuntime) Settles() []SettleRequest
Settles returns the settlement requests the run made, in request order.
func (*FakeRuntime) Started ¶
func (f *FakeRuntime) Started() []Dispatch
Started returns the dispatch requests in start order.
type FanoutExpandedEvent ¶ added in v0.185.0
type FanoutExpandedEvent struct {
NodePath string
// Items are the resolved `over` elements in input order. The reducer mints
// one item per element, in this order, and the collected value is assembled
// in the same order however the dispatches interleave.
Items []any
Refusal string
}
FanoutExpandedEvent reports the items a fan-out node resolved from its declared `over` source. The reducer instantiates one body instance per item and owns what follows: which instance may start, the fan-out's nested max_parallel, the join, and the collected value. Refusal carries a reason the reducer turns into the node's terminal state — an `over` source this run cannot read, or a body with nothing to run — so even a refusal changes state only inside Apply.
func (FanoutExpandedEvent) Kind ¶ added in v0.185.0
func (FanoutExpandedEvent) Kind() EventKind
type FanoutItem ¶ added in v0.185.0
type FanoutItem struct {
// Index is the item's position in the resolved `over` list. The collected
// value is assembled in this order.
Index int `json:"index"`
// Bound is the value the fan-out's `as` name resolved to for this item.
Bound any `json:"bound,omitempty"`
// Paths are the item's body instances in body order. The last one is the
// item's PRODUCT: its recorded value is what the item contributes to the
// collect, because the body is ordered as a sequence (§5.3) and its earlier
// nodes are inputs to the last.
Paths []string `json:"paths,omitempty"`
// State is the item's outcome, folded from its instances once they all
// terminated: failed outranks cancelled outranks skipped, and success means
// the body ran to its product.
State State `json:"state,omitempty"`
// Reason names the instance that decided the outcome, with its own reason.
Reason string `json:"reason,omitempty"`
// Value is the item's collected value: its product instance's recorded
// value, and nil for an item that did not succeed.
Value any `json:"value,omitempty"`
}
FanoutItem is one expanded item of a fan-out node: the element of `over` it bound, the body instances it became, and its own outcome. It is the item ledger a trace reads and the source the collected value is assembled from, so it is written only inside Apply, like every other piece of lifecycle state.
type GateEvaluatedEvent ¶ added in v0.188.0
type GateEvaluatedEvent struct {
NodePath string
// Assert is the registry check that decided, empty under a judge.
Assert string
// Value is the subject the check read, rendered as one log field.
Value string
// Verdict is the judge's delivered verdict body, empty under an assert.
Verdict string
// Pass is the check's or the verdict's answer; Escalate marks a judge that
// declined to decide, which is terminal whatever on_fail says.
Pass bool
Escalate bool
Reason string
Refusal string
}
GateEvaluatedEvent carries one gate's decision. Pass, Escalate, and Reason are what the check or the judge said; Assert and Verdict record WHICH half decided and what it delivered, so a trace can quote the decision and not only its outcome. Refusal carries a subject this run could not read, which the reducer turns into the node's terminal state instead of evaluating a check against a value that does not exist.
func (GateEvaluatedEvent) Kind ¶ added in v0.188.0
func (GateEvaluatedEvent) Kind() EventKind
type GuardFunc ¶
GuardFunc answers whether a node's `when` guard admits it. Selector evaluation is value plumbing owned by the bead that extracts values (yaah-0u0v.13), so the scheduler asks instead of implementing it. A nil Guard means no evaluator is wired, and then every guard is treated as satisfied — a choice recorded in Result.Warnings so a caller can see that guarded nodes ran.
A Guard must not call back into the Run that is asking: it is invoked from inside the reducer, and the reducer is the only place state changes.
type Handle ¶
type Handle struct {
DispatchID string
// Ref is the adapter's own reference — a background job id, a scope id.
Ref string
}
Handle names one started attempt at the door. The scheduler mints the DispatchID and the Runtime hands back whatever it needs to find the attempt again; a Runtime that keys on the id alone ignores the field.
type InstanceState ¶ added in v0.186.0
type InstanceState struct {
Path string `json:"path"`
Owner string `json:"owner"`
BodyPath string `json:"body_path"`
Item int `json:"item,omitempty"`
Name string `json:"name,omitempty"`
Bound any `json:"bound,omitempty"`
Locals map[string]string `json:"locals,omitempty"`
}
InstanceState is one body instance's identity, recorded so a resume can rebuild the instance without re-running the expansion that minted it. The body TEMPLATE is not persisted: BodyPath names the container's body node the instance was copied from, and the resume copies it again from the same immutable graph.
type Ledger ¶ added in v0.186.0
type Ledger struct {
Open map[string]string `json:"open,omitempty"`
Claims map[string]string `json:"claims,omitempty"`
Settled map[string]string `json:"settled,omitempty"`
AbortAsked map[string]string `json:"abort_asked,omitempty"`
}
Ledger is the run's proposal bookkeeping: the proposals it sealed and has not disposed of, the ones a settle node is working through, and the ones that reached a disposition. It is the reducer's own state, carried in the checkpoint so a resumed run's linearity guards read the same ledger the original run had (yaah-0u0v.13's guards, extended by .16). AbortAsked adds the abort pass's permanent ask record (yaah-0u0v.24): every proposal the run asked an abort-time disposition for, so a resume disposes of the rest without ever asking one twice.
type Limits ¶
Limits are the ceilings a run enforces. Zero means undeclared, and an undeclared axis is declined rather than guessed: this package invents no host defaults, because a default cap inside a deterministic core is a host policy nobody authored. The caller passes what the graph declares and what the host configures — LimitsFromBudgets maps the graph's half.
MaxConcurrentDispatches is a scheduling constraint, not a stop condition: the run never exceeds it, and reaching it parks ready nodes until a slot frees instead of ending anything. MaxDispatches and MaxWallClock are ceilings on the run: exhausting either ends it with RunBudgetExceeded.
func LimitsFromBudgets ¶
LimitsFromBudgets maps a resolved graph's declared budgets onto Limits. A nil field is undeclared and maps to zero. A negative declared value is treated as undeclared rather than as an impossible ceiling: the document is the author's, and refusing to schedule anything because a field was mistyped is the validator's business, not the scheduler's.
MaxTokens is not mapped. Token usage does not arrive on the completion envelope, so the scheduler cannot meter the axis it would be enforcing, and silently accepting a ceiling it cannot honor is worse than declining it and saying so; accounting for tokens belongs to the trace bead (yaah-0u0v.17).
type LoopCompletedEvent ¶ added in v0.185.0
type LoopCompletedEvent struct {
NodePath string
// Iterations is how many iterations ran, for the log line: the reducer's own
// ledger is the authority, and the driver states what it read.
Iterations int
Terminated string
Exhausted bool
Refusal string
}
LoopCompletedEvent reports what ended a loop. Terminated names the declaration that fired — until, or the bound — and Exhausted marks the one case that is not a success when a terminator WAS declared: the bound reached without the condition ever matching. Refusal carries a terminator the run could not evaluate, which the reducer turns into the node's terminal state.
func (LoopCompletedEvent) Kind ¶ added in v0.185.0
func (LoopCompletedEvent) Kind() EventKind
type LoopIteration ¶ added in v0.185.0
type LoopIteration struct {
// Index is the iteration's position in the loop, 0-based.
Index int `json:"index"`
// Paths are the iteration's body instances in body order. The last one is
// the iteration's PRODUCT: its recorded value is what the iteration
// contributes to the collect.
Paths []string `json:"paths,omitempty"`
// State is the iteration's outcome, folded from its instances once they all
// terminated: failed outranks cancelled outranks skipped, and success means
// the body ran to its product.
State State `json:"state,omitempty"`
// Reason names the instance that decided the outcome, with its own reason.
Reason string `json:"reason,omitempty"`
// Value is the iteration's product value, nil for an iteration that did not
// succeed.
Value any `json:"value,omitempty"`
}
LoopIteration is one iteration of a loop node: the body instances it became and its own outcome. It is the ledger a trace reads and the record the accumulated collect is assembled from, so it is written only inside Apply, like every other piece of lifecycle state.
type LoopIterationStartedEvent ¶ added in v0.185.0
LoopIterationStartedEvent asks the reducer to instantiate one loop iteration. Iteration is the 0-based index the reducer must find next in its own ledger: a driver asking for any other index is a bug in this package, not a declaration an author can fix.
func (LoopIterationStartedEvent) Kind ¶ added in v0.185.0
func (LoopIterationStartedEvent) Kind() EventKind
type NodeCancelledEvent ¶
NodeCancelledEvent closes a running, ready, or pending node because the run stopped. CancelErr carries a Runtime.Cancel door error when the attempt may still be running in the world; the state transition is the run's own decision either way.
func (NodeCancelledEvent) Kind ¶
func (NodeCancelledEvent) Kind() EventKind
type NodeFailedEvent ¶
NodeFailedEvent closes a node whose failure is final for this run: retries were exhausted, the envelope asserted no retry, or the kind or the door refused the work. Reason always names the cause.
func (NodeFailedEvent) Kind ¶
func (NodeFailedEvent) Kind() EventKind
type NodeOutput ¶ added in v0.183.0
type NodeOutput struct {
// NodePath and Kind name the producing node, so a flattened run output
// needs no second lookup.
NodePath string `json:"node_path"`
Kind ir.Kind `json:"kind"`
Name string `json:"name,omitempty"`
Value string `json:"value,omitempty"`
Artifact string `json:"artifact_path,omitempty"`
Contract string `json:"contract,omitempty"`
}
NodeOutput is one declared output binding the reducer recorded for a node. It is the value a later step reads, and the record a run prints: the name is the node's `output:` name (for an emit that declares none, the step id, which is the name `steps.<id>.output` already reads), the value is the delivered report text or the rendered emit value, and Artifact is the artifact path the node declared for it — recorded, not written, because writing is the host's door and not the scheduler's.
Per-binding extraction of a structured result (reading one field out of a declared Report or Verdict) is value plumbing, and it landed with yaah-0u0v.13: references read through Run.stepValue, which resolves a delegate's recorded value as the envelope facts plus any JSON object body, and a settle node's as its settled record. The binding stored here is what the node itself produced — a report's delivered text, an emit's rendered value, a settle's settled record.
type NodeReadyEvent ¶
type NodeReadyEvent struct{ NodePath string }
NodeReadyEvent records that a node passed its join-all test and is in the ready queue. It is derived: readiness is a consequence of a need terminating, never an assertion from outside.
func (NodeReadyEvent) Kind ¶
func (NodeReadyEvent) Kind() EventKind
type NodeSkippedEvent ¶
NodeSkippedEvent closes a node that was not run: its own on_failure: skip absorbed a failure, a need of it was skipped, or its guard did not pass.
func (NodeSkippedEvent) Kind ¶
func (NodeSkippedEvent) Kind() EventKind
type NodeState ¶
type NodeState struct {
Path string
ID string
Kind ir.Kind
// State is the lifecycle position.
State State
// Needs is the node's declared needs, in author order.
Needs []string
// Policy is the effective failure disposition, with the folded default
// applied: an undeclared on_failure is abort.
Policy ir.FailurePolicy
// MaxAttempts is the attempt ceiling from the node's retry block, at
// least 1.
MaxAttempts int
// Attempts is the attempt history in start order.
Attempts []*Attempt
// Failures counts attempts that came back not-completed.
Failures int
// Reason is the terminal reason for a failed, skipped, or cancelled node.
Reason string
// Exposed names the need paths that ended failed under on_failure:
// continue and were therefore handed to this node as an input fact.
Exposed []string
// CancelErr records a Runtime.Cancel door error for this node's attempt.
// A cancel that failed is a fact about the world, not a state change, so
// it is kept next to the state the run already committed.
CancelErr string
// The fields below carry the last completion's envelope facts for
// consumers that only want the node's outcome. Attempt history holds the
// full sequence.
Status string
StopReason string
DurationMs int64
Model string
World string
ProposalID string
Result string
Error string
Retryable bool
RecoverySet bool
// Contract is the last completion's contract verdict, verbatim; empty
// means the envelope carried no contract block.
Contract string
// Outputs are the output bindings this node produced, in declaration
// order. A re-run of the node replaces the binding of the same name
// rather than appending, so the list is the node's current outputs, not
// its history (the history is Attempt.Result).
Outputs []NodeOutput
// Proposal is the typed handle this node sealed, when a proposal-lane
// attempt sealed one. It is what a settle node reads as its input, and it
// stays set after settlement: the disposition is recorded on the settle
// node and in the run's ledger, not by erasing the producer's fact.
Proposal *ProposalHandle
// SettlePlan, Settling, Settled, and Asked are a settle node's own ledger:
// the handle set it resolved, how far through it the run is, every
// disposition the door reported, and the one disposition the run has asked
// for and not yet had answered. They are lifecycle state, so they are
// written only inside Apply — the driver reads them to decide which
// settlement to ask the door for next.
SettlePlan *SettlePlan
Settling int
Settled []Settled
// Asked names the proposal the run has asked the door to dispose of with no
// recorded disposition yet (yaah-0u0v.16). It is the settlement write-ahead
// record: it is persisted BEFORE the door is called, so a run resumed from a
// checkpoint can tell "asked, outcome unknown" from "never asked" and refuse
// to ask twice. Empty means no disposition is in flight.
Asked string
// Expanded, Items, and Collect are a fan-out node's own ledger
// (yaah-0u0v.14). Expanded records that the items were instantiated, so a
// second expansion of the same node is a refused event rather than a second
// set of instances; Items is the per-item record in `over` order, and
// Collect is the joined value the node reports — the item values in that
// same input order, never completion order.
Expanded bool
Items []FanoutItem
Collect []any
// Winners is the item set a join:any|quorum container closed on
// (yaah-0u0v.19): the first success under any, the first N under quorum, in
// item order. It is the fixed answer to "which items the run collected", so
// Collect holds exactly these items' values and a result that arrives after
// the close is recorded on its own item without widening either. Empty for
// join: all, which never decides on a tally.
Winners []int
// Discards is the dispositions the run obtained for proposals a NON-WINNING
// item of this container sealed (yaah-0u0v.19). Each one went through the
// door's settlement path with the discard verb — the same path a settle node
// uses — because work the join cancelled must not leave a proposal (or its
// worktree) standing. A record whose settlement did not land keeps the
// proposal in the run's open ledger, so the close states the residue instead
// of asking a second time.
Discards []Settled
// Iterations is a loop node's own ledger (yaah-0u0v.15): one record per
// iteration, in iteration order, folded from the iteration's instance states
// as they all terminate. Collect accumulates each SUCCEEDED iteration's
// product value in that same order, so it is the value a terminator reads
// while the loop is still running and the value the loop reports when it
// closes.
Iterations []LoopIteration
// Selected is a branch node's routing decision (yaah-0u0v.15): the node path
// of the arm it chose, or empty for "no case matched and no default was
// declared". The arms a branch did not select read it — through the routing
// relation the reducer keeps — to decide whether they may run at all.
Selected string
// Combined is an aggregate node's value (yaah-0u0v.15): the concatenated
// list, the merged mapping, or a summarize body's product. It is kept
// structured so `steps.<id>.output` and a selector read the value rather than
// a re-parse of its text, while Result carries the text.
Combined any
// CallRunID (yaah-0u0v.23) is the child run's identity when a call node's
// nested workflow succeeded — the run record its state lives under, so a
// report or an audit can follow a call into the workflow it ran. Empty
// before the first call and on a node that did not succeed.
CallRunID string
// Candidates, Chosen, Selection, SelectPolicy, and Verdict are a select
// node's own ledger (yaah-0u0v.20): what it chose among, which one won, the
// winning value, the effective policy with the folded default applied, and
// the judge's delivered verdict body under `policy: judge`. They are kept
// structured for the same reason Combined is — `steps.<id>.output.winner` is
// what a downstream settle reads — while Result carries the winner's text.
//
// Chosen is the winner's index in Candidates and is meaningful only together
// with a non-nil Selection: a node that has not decided yet records neither.
Candidates []Candidate
Chosen int
Selection any
SelectPolicy ir.SelectPolicy
Verdict string
// Disposition, GateAssert, GateReason, and GateVerdict are a gate node's own
// ledger (yaah-0u0v.21): the answer it reached (pass, fail, or escalate), the
// registry assert that reached it (empty under a judge), the one sentence the
// check or the judge stated, and the judge's delivered verdict body (empty
// under an assert). They are the node's VALUE — gateValue reads them into the
// mapping `steps.<id>.output` resolves — which is what makes a gate's result a
// value rather than control flow hidden in a prompt.
Disposition string
GateAssert string
GateReason string
GateVerdict string
}
NodeState is one node's lifecycle state, owned by the reducer.
func (*NodeState) LastAttempt ¶
LastAttempt returns the node's most recent attempt, or nil.
type NodeSucceededEvent ¶
NodeSucceededEvent closes a node that completed its work. Outputs names the output bindings the reducer recorded for it — the delegate report or the emitted value — so the event log says which node produced what without quoting any of the values themselves.
func (NodeSucceededEvent) Kind ¶
func (NodeSucceededEvent) Kind() EventKind
type ProposalHandle ¶ added in v0.184.0
type ProposalHandle struct {
ProposalID string `json:"proposal_id"`
// Producer is the node path that sealed it.
Producer string `json:"producer,omitempty"`
Role string `json:"role,omitempty"`
Lane string `json:"lane,omitempty"`
DispatchID string `json:"dispatch_id,omitempty"`
}
ProposalHandle is the typed record of a proposal an attempt sealed. The envelope's proposal_id is the whole fact; the rest is what a settle node and a later trace need in order to name where it came from without re-deriving it from per-lane plumbing.
type ProposalRef ¶ added in v0.184.0
type ProposalRef struct {
ProposalID string `json:"proposal_id"`
Producer string `json:"producer,omitempty"`
}
ProposalRef is one element of a settle node's resolved handle set.
type ProposalSettledEvent ¶ added in v0.184.0
type ProposalSettledEvent struct {
NodePath string
Settled Settled
DoorError string
// Refused marks a settlement the scheduler declined to ask for at all —
// an action outside the four settlement verbs — as distinct from one the
// door attempted and could not complete.
Refused string
}
ProposalSettledEvent carries one settlement's outcome back from the door. DoorError reports that the door itself malfunctioned: there is no settlement envelope behind it, the proposal keeps whatever state it had, and the node ends failed rather than retrying a world effect that may already have landed.
func (ProposalSettledEvent) Kind ¶ added in v0.184.0
func (ProposalSettledEvent) Kind() EventKind
type Recovery ¶
type Recovery struct {
Retryable bool `json:"retryable"`
Recommended string `json:"recommended,omitempty"`
}
Recovery mirrors the envelope's recovery block: the one place the runtime says whether running the work again can make progress.
type Result ¶
type Result struct {
RunID string
Status RunStatus
// Reason names the stopping cause: the aborting node, the exhausted
// budget axis, or the first node that ended failed and was exposed.
Reason string
Dispatches int
// PeakInFlight is the highest number of attempts the reducer had open at
// once — the scheduler's own witness that MaxConcurrentDispatches held.
PeakInFlight int
Elapsed time.Duration
Events []string
// Records is the run's trace projection: one typed record per lifecycle
// fact, in the order the events were folded. It is a rendering of the same
// sequence as Events, not a second account of the run, and it is what
// `yaah workflow explain --from-trace` reads back from the store.
Records []trace.Record
Warnings []string
Nodes []*NodeState
// Outputs flattens every node's recorded output bindings in canonical
// node-path order: the delegate reports and emit values a run produced.
Outputs []NodeOutput
}
Result is what a finished run says about itself.
type RetryScheduledEvent ¶
RetryScheduledEvent records that a retryable failure will be retried, and how long the run must wait first. The delay is honored through the door (Runtime.Backoff), so a test's virtual clock moves without any goroutine sleeping.
func (RetryScheduledEvent) Kind ¶
func (RetryScheduledEvent) Kind() EventKind
type Run ¶
type Run struct {
// contains filtered or unexported fields
}
Run is one workflow run: the graph, the ceilings, the door, and all of the lifecycle state. A Run is driven by exactly one goroutine; the reducer needs no lock because there is nothing to lock against, and that is also what makes the event sequence reproducible.
func New ¶
New prepares a run over a resolved graph. Only the graph's top-level steps are scheduled here: a body node is entered through its container, so it becomes lifecycle state only when a fan-out expands into items (yaah-0u0v.14), and until then it is not silently skipped either — the container that owns it answers for it.
func Resume ¶ added in v0.186.0
Resume rebuilds a run from a checkpoint and returns it ready to drive: the nodes that had terminated stay terminated, the ones that were waiting stay waiting, and the next Advance continues from there.
The graph must be the one the checkpoint's SpecHash names; cfg.SpecHash is compared against the record and a mismatch is refused with ErrSpecHashMismatch. cfg.Store is used for the resume's own writes, and cfg.RunID is ignored in favour of the checkpoint's: a run id is the identity of a run, not an argument to it.
func (*Run) Advance ¶
Advance performs one scheduler cycle: sample the budgets, start what the ready queue and the concurrency cap allow, then commit the oldest outstanding attempt's completion. It reports whether the cycle did anything; a cycle that does nothing means the run is finished.
The driver never mutates lifecycle state. It reads the reducer, calls the door, and submits the resulting event — which is why the same sequence comes out of a real adapter and a scripted fake.
func (*Run) Apply ¶
Apply folds one event into the run's state. It is the only exported mutator: lifecycle transitions, the ready queue, the dispatch tally, and the event log change nowhere else, so the reducer is the single answer to "what state is this run in". Events that are consequences rather than reports — node_ready, node_succeeded, node_failed, node_skipped, retry_scheduled — are rejected here, because submitting a conclusion is how a parallel state view gets built.
When a Store is configured, the checkpoint is written HERE, after the event is folded and before Apply returns (yaah-0u0v.16). That ordering is the whole idempotency argument: no attempt, proposal handle, or disposition can become visible to a resume without being durable first, so a run that stops at any boundary resumes from exactly the state it had committed. A store write fails the event: a run whose state cannot be recorded must not advance, because the next step would then re-do work the record does not know about.
func (*Run) Cancel ¶
Cancel stops the run from the outside: every running attempt is cancelled through the door, every node that never ran is cancelled by the close, and the run finishes with RunCancelled. Cancel takes no context — teardown is unconditional, for the reason stop documents. Call Cancel from the same goroutine that drives Advance; it is not a signal to a concurrent loop.
func (*Run) Checkpoint ¶ added in v0.186.0
func (r *Run) Checkpoint() Checkpoint
Checkpoint returns the run's current projection. It is a snapshot: node states are copied, and attempt records are shared because a committed attempt is immutable.
func (*Run) Execute ¶
Execute drives the run to a terminal state and returns its result. It is the ordinary entry point: New, Execute, read the Result. Each cycle is one Advance, so a caller that needs to interleave with the door — a test moving a virtual clock, a host observing progress between dispatches — can drive Advance itself and read State at any point.
type RunFinishedEvent ¶
RunFinishedEvent closes the run. The reducer derives the cancellation of every node that never terminated before recording the line, so run_finished is always the last event and the log never claims a finished run with live nodes in it.
func (RunFinishedEvent) Kind ¶
func (RunFinishedEvent) Kind() EventKind
type RunResumedEvent ¶ added in v0.186.0
type RunResumedEvent struct {
RunID string
// Nodes and Instances are the counts the checkpoint restored; they let a
// reader tell a resume of a large run from one that restored nothing.
Nodes int
Instances int
}
RunResumedEvent records that a process picked a run up from its checkpoint. It is an ordinary input event so the resume is folded — and persisted — like every other fact, and so the log says where one process ended and the next began.
func (RunResumedEvent) Kind ¶ added in v0.186.0
func (RunResumedEvent) Kind() EventKind
type RunStartedEvent ¶
type RunStartedEvent struct{ RunID string }
RunStartedEvent opens a run. The reducer takes the run clock here, so elapsed time and the event log start from the same instant.
func (RunStartedEvent) Kind ¶
func (RunStartedEvent) Kind() EventKind
type RunStatus ¶
type RunStatus string
RunStatus is the disposition of a finished run.
const ( // RunSucceeded: every node terminated succeeded or skipped. A skip is a // completed disposition, not a failure — the author declared it. RunSucceeded RunStatus = "succeeded" // RunFailed: the run drained to completion but a node ended failed under // on_failure: continue, so the failure was exposed downstream instead of // stopping the run. RunFailed RunStatus = "failed" // RunAborted: a node ended failed under on_failure: abort (the default), // and the run stopped scheduling. RunAborted RunStatus = "aborted" // RunCancelled: the run was cancelled from outside, or its context ended. RunCancelled RunStatus = "cancelled" // RunBudgetExceeded: a declared budget was exhausted. The run stops with a // status rather than hanging or spinning. RunBudgetExceeded RunStatus = "budget_exceeded" // RunRunning is the pre-terminal status. RunRunning RunStatus = "running" )
Run dispositions.
type Runtime ¶
type Runtime interface {
// Start launches one attempt and returns as soon as it is running. It
// must not block on the attempt's completion. A Start that fails has
// dispatched nothing, and the run records the failure through the door
// malfunction path rather than inventing an envelope.
Start(ctx context.Context, d Dispatch) (Handle, error)
// Settle disposes of one proposal through the lane's existing settlement
// path and reports what the world did. It is the one door method the
// scheduler calls synchronously, and it is deliberately not a start/poll
// pair: a settlement is a world effect with one answer, the run asks for
// one per cycle in the plan's fixed order, and two settles may never work
// the same proposal at once (validate's WF023 orders any two settlement
// steps that could). A door that cannot settle reports an error and states
// nothing about the proposal; a conflict is an outcome, not an error.
Settle(ctx context.Context, req SettleRequest) (Settled, error)
// Completed reports the envelope for a started attempt when the attempt
// has finished. It must not block, and its answer must be stable: an
// attempt once reported complete stays complete, because the scheduler
// polls the oldest outstanding attempt until its turn to commit comes
// and must not lose a completion it looked at early.
Completed(h Handle) (Completion, bool)
// Block waits until at least one started attempt has become completable,
// or ctx is done. It exists so a real adapter can idle without polling,
// and a synchronous fake returns immediately. Returning nil when nothing
// became completable is a door malfunction, not a spurious wake: the
// scheduler treats it as an error rather than spinning or hanging on it.
Block(ctx context.Context) error
// Cancel asks a running attempt to stop. The run's state does not wait
// for the world to agree: the node is cancelled the moment the request is
// made, and a late envelope is dropped. An error here is recorded on the
// node so an adapter that could not stop real work is visible.
Cancel(h Handle) error
// Backoff waits out a node's declared retry backoff. A test fake advances
// its virtual clock and returns immediately: tests never sleep.
Backoff(ctx context.Context, d time.Duration) error
// Now reads the run clock. The scheduler only ever samples it at event
// boundaries — it arms no timers — so a virtual clock in a fake makes
// wall-clock budget behavior deterministic.
Now() time.Time
// Call executes one nested workflow (yaah-0u0v.23). Like Settle it is
// deliberately synchronous with one answer, and it stays on the door's
// side of the world for the same reasons: resolving a subworkflow name
// reads a registry the reducer cannot see, and running the child composes
// a runner, a retained runtime, and a store the graph holds no mention
// of. A Call that fails has run something whose side effects stand —
// the child run's own state is its record — so the error names the door,
// never the child's outcome; the outcome travels on CallResult and the
// reducer folds it like any other envelope.
Call(ctx context.Context, req CallRequest) (CallResult, error)
}
Runtime is the only door through which a workflow run touches the world. Everything here is a side effect or a clock: no method returns scheduler state, and no method may call Run.Apply.
The shape is deliberately start/poll rather than a blocking call, so the scheduler stays single-threaded: one goroutine owns the Run, asks the door for starts, and commits completions in canonical order. A blocking Dispatch would either serialize the whole graph or move state mutation into the callbacks of whatever goroutine finished first, and the second option is precisely the parallel state this package refuses to have. A real adapter therefore runs its dispatch in its own goroutine (typically internal/dispatch.Run) and reports it through Completed.
type ScopeSnapshot ¶
type ScopeSnapshot struct {
// contains filtered or unexported fields
}
ScopeSnapshot is the immutable view of run state one attempt is dispatched against. ir.Template documents that "the scheduler implements [Scope] over run state; the graph never holds run state", and this is that implementation: the reducer builds it from its own state at the moment the attempt starts, and a Runtime that reads it later cannot observe a value that changed underneath it.
What it resolves, and what it refuses:
- params.* — bound at New, defaults folded in;
- run.id and run.attempt — the run's label and this attempt's ordinal;
- steps.<id>.output — the recorded value of a node that succeeded. A proposal-lane delegate's value is its typed handle, a structured Report's is decoded by field name, a settle's is its settled record, an emit's is the rendered text, and a fan-out's is its collected items. One place decides those readings (Run.stepValue), so a template and a selector can never disagree about what a step produced;
- steps.<id>.collect — a fan-out's joined value: its item values in INPUT order (yaah-0u0v.14). It is present once the fan-out has closed, and absent — an honest error, not an empty list — before that: an empty list would let a template render "no workstreams" and a selector filter to nothing, and both look like a successful run to the log;
- item.<as> and index — the item scope of the fan-out body this attempt belongs to. A top-level node has none, and asking for one is an error rather than a zero value.
The bindings are looked up by node PATH, not by step id, because a fan-out instance's id is body-local: two items' bodies may both declare `review`, and only the item's own scope may resolve it. A body-local id shadows a top-level one of the same name, which is the shadowing rule ir.resolveBody's child scope applies at compile time.
func (*ScopeSnapshot) Index ¶
func (s *ScopeSnapshot) Index() int
Index is the innermost item's index in its fan-out's `over` list. A node outside a container body reports 0, which is what it always reported.
type SelectChosenEvent ¶ added in v0.187.0
type SelectChosenEvent struct {
NodePath string
Policy ir.SelectPolicy
Chosen int
Ref string
Reason string
}
SelectChosenEvent carries one selection's decision: the winning candidate's index in the node's resolved candidate ledger, its ref, and the policy that decided. Reason quotes what the judge said, when a judge decided.
func (SelectChosenEvent) Kind ¶ added in v0.187.0
func (SelectChosenEvent) Kind() EventKind
type SelectResolvedEvent ¶ added in v0.187.0
SelectResolvedEvent carries the candidate values one select node's `candidates` selector resolved, in resolved order. Refusal carries a set this run could not read or that resolved to nothing, which the reducer turns into the node's terminal state rather than deciding over a shorter list than the author declared.
func (SelectResolvedEvent) Kind ¶ added in v0.187.0
func (SelectResolvedEvent) Kind() EventKind
type SettlePlan ¶ added in v0.184.0
type SettlePlan struct {
Refs []ProposalRef `json:"refs"`
Action ir.SettleAction `json:"action"`
Policy ir.SettlePolicy `json:"policy,omitempty"`
Order ir.SettleOrder `json:"order,omitempty"`
OnConflict ir.ConflictPolicy `json:"on_conflict,omitempty"`
Empty ir.EmptyPolicy `json:"on_empty,omitempty"`
}
SettlePlan is one settle node's resolved work: the handles to dispose of, in the order the door is asked to take them, plus the dispositions the author declared for what the door reports back.
type SettleRequest ¶ added in v0.184.0
type SettleRequest struct {
// NodePath is the settle node asking for the disposition.
NodePath string
// ProposalID is the sealed proposal to dispose of.
ProposalID string
// Producer is the node path that sealed it, when a handle records one.
Producer string
// Verb is one of select, apply, release, discard. The scheduler maps its
// resolved action onto these four and refuses anything else: continue and
// fork are delegate re-run bindings, not settlement verbs.
Verb string
// Policy is the declared settle policy, or empty when undeclared.
Policy ir.SettlePolicy
}
SettleRequest is one settlement the run is asking the door to perform. It names a proposal by the id the sealing envelope reported and the verb the author declared; everything else a settlement needs — the registry, the world, the merge strategy — belongs to the lane, and the door is the only place that reaches it.
Policy may be empty. An empty policy means the author declared none, and the runtime default (path_disjoint) is the door's interpretation, not validate's: the validator deliberately does not materialize it, so the resolved graph keeps saying "undeclared" and the adapter says what it did.
type Settled ¶ added in v0.184.0
type Settled struct {
ProposalID string `json:"proposal_id"`
Producer string `json:"producer,omitempty"`
// Action is the verb the door was asked to apply.
Action string `json:"action,omitempty"`
// Status is settled, conflict, or error — verbatim.
Status string `json:"status,omitempty"`
// Outcome is the runtime's typed work/scope/record/notes block. It is
// multi-line prose and therefore never reaches an event log line.
Outcome string `json:"outcome,omitempty"`
Error string `json:"error,omitempty"`
// Conflicts are the overlap paths a refused apply named.
Conflicts []string `json:"conflicts,omitempty"`
// Files are the paths the settlement touched, when the envelope reported.
Files []string `json:"files,omitempty"`
// LeftOpen reports that the proposal has no disposition now: a conflict
// leaves the worktree standing, and an error leaves everything standing.
LeftOpen bool `json:"left_open,omitempty"`
}
Settled is the scheduler's view of one settlement. It mirrors the proposal runtime's settlement envelope the way Completion mirrors the dispatch envelope — same facts, separate type, because this package may not import internal/dispatch. internal/workflow/host is the producer that bridges them.
func SettleConflicted ¶ added in v0.184.0
SettleConflicted scripts a refused apply: the overlap paths are named and the proposal stays open, which is the shape internal/dispatch returns for a path_disjoint collision.
func SettledOK ¶ added in v0.184.0
func SettledOK(req SettleRequest) Settled
SettledOK is the settlement a fake reports for a proposal nobody scripted: the verb the scheduler asked for, applied, and nothing left open.
type SettlementAskedEvent ¶ added in v0.186.0
SettlementAskedEvent records the disposition the run is about to ask the door for. The driver emits it immediately before Runtime.Settle, and the reducer commits it so the checkpoint states the intent durably before the world effect can happen (yaah-0u0v.16). Action is the door's verb, carried for the log line and for the reason a resumed run states when it refuses to ask twice.
func (SettlementAskedEvent) Kind ¶ added in v0.186.0
func (SettlementAskedEvent) Kind() EventKind
type SettlementPlannedEvent ¶ added in v0.184.0
type SettlementPlannedEvent struct {
NodePath string
Refs []ProposalRef
Action ir.SettleAction
Policy ir.SettlePolicy
Order ir.SettleOrder
// OnConflict and Empty are the node's declared dispositions, carried so
// the reducer's decisions read one event and not the graph behind it.
OnConflict ir.ConflictPolicy
Empty ir.EmptyPolicy
Refusal string
}
SettlementPlannedEvent reports the proposal handles a settle node resolved from recorded run state, before any settlement is asked for. Refusal carries a reason the reducer turns into the node's terminal state — a handle set this bead cannot resolve, or a proposal another node already disposed of — so even a refusal changes state only inside Apply.
func (SettlementPlannedEvent) Kind ¶ added in v0.184.0
func (SettlementPlannedEvent) Kind() EventKind
type State ¶
type State string
State is one node's position in the lifecycle. The vocabulary is exactly the bead's: pending, ready, running, then one of four terminal states.
const ( StatePending State = "pending" StateReady State = "ready" StateRunning State = "running" StateSucceeded State = "succeeded" StateFailed State = "failed" StateSkipped State = "skipped" StateCancelled State = "cancelled" )
Lifecycle states.
func (State) Terminal ¶
Terminal reports whether a state can change again. Terminal is precisely the set that satisfies a join-all need: a node in one of these states has terminated, which is what releases its dependents. Ready, running, and pending are not, and a readiness rule that counted them would either hang or run a node against an input that does not exist yet.
type Store ¶ added in v0.186.0
type Store interface {
// SaveCheckpoint records the run's projection. A save that fails stops the
// run: state that cannot be recorded must not advance.
SaveCheckpoint(ctx context.Context, cp Checkpoint) error
// LoadCheckpoint returns the last recorded projection for a run id, or an
// error wrapping ErrRunNotFound.
LoadCheckpoint(ctx context.Context, runID string) (Checkpoint, error)
// Close releases the store. A caller that opened the store is responsible
// for closing it; on Windows an open SQLite file cannot be removed.
Close() error
}
Store is the durable projection of a run: the one place its state is kept between processes. A store must be idempotent — the reducer re-writes the whole projection on every event — and it must be atomic per call, because a half-written checkpoint is a run state that never existed.
The port lives here rather than in the store's own package so this package depends on nothing: internal/workflow/store is the SQLite adapter over the session store family, and a test supplies an in-memory one.