Documentation
¶
Overview ¶
Package dag provides a small action-oriented directed acyclic graph.
Nodes are Nexss actions. Compile validates dependencies and produces deterministic execution layers. Execute runs each layer with cancellation and merges results only at layer boundaries.
Index ¶
- Variables
- func GetNodeOutput[T any](state ReadState, nodeID string) (T, error)
- func InnerStateKey(nodeID string) string
- func OutputKey(nodeID string) string
- func Suspend(reason string, payload any) error
- func WithLayerCallback(ctx context.Context, fn LayerCallback) context.Context
- type Builder
- func (b *Builder) AddConditionalEdge(from string, router RouterFunc) *Builder
- func (b *Builder) AddEdge(from, to string) *Builder
- func (b *Builder) AddNamedConditionalEdge(from, label string, router RouterFunc) *Builder
- func (b *Builder) AddNode(id, _ string, act action.AnyAction) *Builder
- func (b *Builder) Compile() (*DAG, error)
- func (b *Builder) WithEntry(nodeID string) *Builder
- func (b *Builder) WithMaxSteps(n int) *Builder
- type DAG
- type Edge
- type EdgeMeta
- type ExecutionError
- type LayerCallback
- type Node
- type NodeContext
- type ReadState
- type RouterFunc
- type State
- type SuspendError
- type TopologyRegistry
- type Value
Constants ¶
This section is empty.
Variables ¶
var ErrSuspended = errors.New("graph: execution suspended for human intervention")
ErrSuspended signals that a node paused execution (e.g. awaiting human approval). Returning it preserves partial state for later resume.
var GlobalTopology = &TopologyRegistry{}
Functions ¶
func GetNodeOutput ¶
GetNodeOutput reads a node's typed output from a read-only state view.
Hot path: single type assertion, zero allocations. Slow path (checkpoint resume): falls back to action.Coerce for JSON-decoded map values.
func InnerStateKey ¶ added in v0.14.0
InnerStateKey returns the state key that holds a nested DAG's partially-completed inner state. On nested failure the parent DAG stashes the inner *State under this key so a resume run can continue the inner graph from where it stopped.
func Suspend ¶ added in v0.11.1
Suspend pauses DAG execution gracefully. The returned error matches ErrSuspended.
func WithLayerCallback ¶ added in v0.11.0
func WithLayerCallback(ctx context.Context, fn LayerCallback) context.Context
WithLayerCallback attaches a callback to ctx.
Use it to checkpoint each layer of a layer-mode DAG. If the graph definition is unchanged, re-executing with the last successful state skips nodes whose outputs are already present, so only unfinished nodes run again.
Types ¶
type Builder ¶
type Builder struct {
// contains filtered or unexported fields
}
Builder accumulates nodes and edges, then compiles them into an immutable DAG. The first builder error short-circuits further calls.
func (*Builder) AddConditionalEdge ¶ added in v0.27.0
func (b *Builder) AddConditionalEdge(from string, router RouterFunc) *Builder
AddConditionalEdge makes the graph dynamic: execution walks node by node from the entry point, following RouterFunc decisions instead of running topological layers.
Only one router per source node is allowed. The label defaults to the source node ID; see AddNamedConditionalEdge for a distinct one.
func (*Builder) AddEdge ¶
AddEdge declares that `to` depends on `from`. Duplicate edges are rejected at build time.
func (*Builder) AddNamedConditionalEdge ¶ added in v0.27.0
func (b *Builder) AddNamedConditionalEdge(from, label string, router RouterFunc) *Builder
AddNamedConditionalEdge is AddConditionalEdge with an explicit label that appears in diagnostics when the router points at an unknown node.
func (*Builder) AddNode ¶
AddNode registers a node. id must be unique and non-empty; act must implement action.Executable. The second argument (a display name) is accepted for API compatibility and ignored — the node's output key is always derived from id.
func (*Builder) Compile ¶
Compile validates the graph and produces the immutable DAG. Errors accumulated by AddNode / AddEdge / AddConditionalEdge surface here.
func (*Builder) WithEntry ¶ added in v0.27.0
WithEntry designates the node a dynamic DAG starts from. Only meaningful when the DAG has at least one conditional edge; ignored otherwise.
The default entry is the first node added via AddNode. Set this explicitly when the natural start is not the first AddNode call — e.g. when a common setup node is registered before the actual branch point.
func (*Builder) WithMaxSteps ¶ added in v0.27.0
WithMaxSteps bounds the number of dynamic-execution steps when the DAG contains conditional edges. Without a bound, a router that returns a cycle would loop forever. The default (32) is applied at execute time when the value is <= 0.
Ignored for DAGs without conditional edges — layer execution is always bounded by the layer count.
type DAG ¶
type DAG struct {
// contains filtered or unexported fields
}
DAG is an immutable, compiled directed acyclic graph.
A DAG is either static (only AddEdge calls, executed layer by layer) or dynamic (at least one AddConditionalEdge, executed node by node starting from entryID and following RouterFunc decisions). The two modes are mutually exclusive; see Execute.
func (*DAG) AsAction ¶
AsAction wraps the DAG as a standard Nexss action. The wrapped action accepts a ReadState and returns a freshly owned *State that the caller must Release.
func (*DAG) Execute ¶
Execute runs the DAG.
Execution mode is selected by the compiled graph's shape:
- Layer mode (default) groups nodes into topological layers. Layers run sequentially, with nodes within each layer running concurrently. On resume, nodes whose output keys are already in initialState are skipped.
- Dynamic mode is selected when the graph has conditional edges. The engine follows RouterFunc decisions from entryID until a router returns "" or "end", or maxSteps is exceeded. Layers are ignored. Outputs in initialState are skipped on first visit; revisited nodes run again and replace their output. Routers should be deterministic from persisted state and stable graph configuration when a resumed run must follow the same path.
WithLayerCallback runs after each completed layer in layer mode. A dynamic DAG consumes any attached callback without invoking it, so nested layer-mode DAGs do not fire the outermost callback. Use a Journal (see action.Durable) to checkpoint dynamic DAGs.
On any error the returned non-nil state owns outputs produced so far. The caller must Release it.
type ExecutionError ¶ added in v0.11.0
type ExecutionError struct {
Layer int
FailedNode string
Cause error
State *State
Completed []string
}
ExecutionError reports that a layer stopped before every node in it succeeded. State carries the partial result: every node whose output is present already ran, so a caller that persists State and later re-executes with it will re-run only the missing nodes.
The caller owns State and must call Release on it, exactly as with a successful return.
func (*ExecutionError) Error ¶ added in v0.11.0
func (e *ExecutionError) Error() string
func (*ExecutionError) Unwrap ¶ added in v0.11.0
func (e *ExecutionError) Unwrap() error
type LayerCallback ¶ added in v0.11.0
LayerCallback is invoked by a layer-mode DAG's Execute after each layer completes. The state includes every node output from that layer. A callback error aborts execution; the state at failure is preserved for inspection or persistence.
Nested DAGs do not invoke the callback independently. A dynamic outermost DAG consumes an attached callback without invoking it, so nested layer-mode DAGs do not fire it either.
func LayerCallbackFromCtx ¶ added in v0.11.0
func LayerCallbackFromCtx(ctx context.Context) LayerCallback
LayerCallbackFromCtx returns the callback attached by WithLayerCallback. It returns nil when no callback is set or an outer DAG has consumed it.
type Node ¶
type Node struct {
ID string
OutputKey string
Action action.Executable
}
Node is a single unit of DAG work.
type NodeContext ¶
NodeContext is the execution context handed to every node.
Input is read-only by construction: the compiler enforces that nodes cannot mutate the parent layer's state. There is no Set method on ReadState, and the engine never exposes a *State through this struct.
A node may retain Input past its own return (e.g. spawn a goroutine that reads it later) — the underlying map is guaranteed alive as long as any ReadState view of it exists.
type ReadState ¶ added in v0.14.0
type ReadState struct {
// contains filtered or unexported fields
}
ReadState is the read-only view of an immutable State snapshot. Copying it shares the root and keeps that snapshot alive.
func (ReadState) Clone ¶ added in v0.14.0
Clone returns a fresh *State sharing the immutable root of the read view.
type RouterFunc ¶ added in v0.27.0
RouterFunc decides the next node to visit after its owning edge's source node. Returning "" or "end" terminates the dynamic walk. An error aborts the walk and is returned to the caller unchanged.
type State ¶
type State struct {
// contains filtered or unexported fields
}
State is the mutable graph state. Only the DAG engine writes to it; nodes receive a read-only view via NodeContext.Input.
Ownership: whoever receives a *State from Execute owns it and calls Release when finished. Release drops this State's root; any outstanding ReadState view keeps its immutable snapshot alive. The GC reclaims tree nodes once every State and ReadState reference to them is gone.
State is deliberately NOT pooled. Nodes receive NodeContext.Input and may legally retain that reference inside their own scope; recycling States across executions would create use-after-free hazards the compiler cannot catch. Persistent roots preserve those snapshots while dynamic execution publishes later outputs.
func AcquireState ¶
func AcquireState() *State
AcquireState returns a fresh, empty State. The caller owns it and should call Release when finished.
func (*State) AsRead ¶ added in v0.14.0
AsRead returns the immutable snapshot of this state. Zero cost: it copies the root pointer. Safe on a nil receiver.
func (*State) Clone ¶
Clone returns a fresh State with the same immutable root. Values are shared, not deep-copied; nodes must not return mutable values they intend to modify after returning.
func (*State) CopyFrom ¶
CopyFrom shares src's immutable root. Later Set calls replace only the receiver's root, so source and destination diverge after either is written.
func (*State) Get ¶
Get on *State delegates to the read-only view so callers that hold the writable handle can read without an explicit AsRead hop. Nil-safe.
type SuspendError ¶ added in v0.11.1
SuspendError carries the reason and payload for a graceful pause. Reason is human-readable; Payload is what the approver needs to see.
func (*SuspendError) Error ¶ added in v0.11.1
func (e *SuspendError) Error() string
func (*SuspendError) Is ¶ added in v0.11.1
func (e *SuspendError) Is(target error) bool
type TopologyRegistry ¶
type TopologyRegistry struct {
// contains filtered or unexported fields
}
func (*TopologyRegistry) Register ¶
func (t *TopologyRegistry) Register(from, to, channel, protocol string)
func (*TopologyRegistry) Reset ¶ added in v0.14.0
func (t *TopologyRegistry) Reset()
func (*TopologyRegistry) ToMermaid ¶
func (t *TopologyRegistry) ToMermaid() string