Documentation
¶
Overview ¶
Package destiny records what a program did as a tree of execution paths, so that tests can check not only that something happened but along which path.
It is github.com/rm4n0s/errors for things that are not errors. A game has few errors, but it has many outcomes: an enemy fled, a chest dropped a rare item, a quest advanced. Each call to Tree.Grow adds a leaf that remembers the path that led to it. One run grows many leaves, and their paths together form a tree:
Game.Tick
├── EnemyAI.decide
│ └── EnemyAI.flee
│ └── [LowHealth] hp=12
└── Loot.roll
└── [RareDrop] item=sword
A route is one path of that tree, written from the root to the leaf:
Game.Tick->EnemyAI.decide->EnemyAI.flee.LowHealth
Tree.HasRoute reports whether the tree grew a given path.
A path is made of the functions on the call stack: every function between the root and the line that grows a leaf is in its route. Three methods change what the call stack alone would give:
- Tree.Here starts the routes at the calling function, whatever an engine or a test has on the stack above it.
- Tree.Branch gives a part of the tree a name where the call stack says nothing useful: a scene graph or a behaviour tree walked by one function that calls itself.
- Tree.Fork carries a path to another goroutine or to a later moment: an event queue, a timer.
A tree also holds a tape: what a game started from (Tree.Start) and what it was given in every tick (Tree.Input). Tree.Dump writes it with the leaves. A game with deterministic rules plays a recording again from its tape, up to any tick (Take.ReadStart, Take.ReadInput), and Take.Diverged checks that the replay took the paths of the recording.
Index ¶
- Constants
- type Divergence
- type InputJson
- type Leaf
- type LeafJson
- type PathJson
- type StackFrame
- type StartJson
- type Take
- type Tree
- func (t *Tree) Branch(name string) *Tree
- func (t *Tree) Counts() map[string]int
- func (t *Tree) Dump(w io.Writer) error
- func (t *Tree) During(first, last int) *Tree
- func (t *Tree) Find(route string) []*Leaf
- func (t *Tree) Fork() *Tree
- func (t *Tree) Grow(tag string, metadata ...any)
- func (t *Tree) HasRoute(route string) bool
- func (t *Tree) Here() *Tree
- func (t *Tree) Input(v any)
- func (t *Tree) Leaves() []*Leaf
- func (t *Tree) Len() int
- func (t *Tree) LogValue() slog.Value
- func (t *Tree) Only(route string) *Tree
- func (t *Tree) Routes() []string
- func (t *Tree) Start(v any)
- func (t *Tree) String() string
- func (t *Tree) TagCounts() map[string]int
- func (t *Tree) TakeAt(tick int) *Take
- func (t *Tree) Takes() []*Take
- func (t *Tree) Tick() int
- func (t *Tree) ToJson() *TreeJson
- type TreeJson
Constants ¶
const ( // TagDumpEncodeFailed is the tag of the error of Dump when the leaves // could not be turned into JSON. TagDumpEncodeFailed = "DumpEncodeFailed" // TagDumpWriteFailed is the tag of the error of Dump when the writer // failed. Its OriginalErr is the error of the writer. TagDumpWriteFailed = "DumpWriteFailed" // TagLoadDecodeFailed is the tag of the error of Load when the reader // failed or what it read is not a dump. Its metadata has the number of // the line under "line". TagLoadDecodeFailed = "LoadDecodeFailed" )
The tags of the errors of this package.
const ( // TagTapeEncodeFailed is the tag of the error of a start value or an input // that JSON cannot hold. Dump returns it once, and Take.ReadStart and // Take.ReadInput return it for that take or tick. Its metadata has the // tick under "tick". TagTapeEncodeFailed = "TapeEncodeFailed" // TagTapeDecodeFailed is the tag of the error of Take.ReadStart and // Take.ReadInput when the value on the tape does not fit what it is read // into. Its metadata has the tick under "tick". TagTapeDecodeFailed = "TapeDecodeFailed" )
The tags of the errors of the tape.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Divergence ¶ added in v0.3.0
type Divergence struct {
// Tick is the tick of the recording. The replay is at tick Tick-First of
// the take.
Tick int
// Missing are the routes that the recording has in that tick and the
// replay does not, and Extra those that the replay has and the recording
// does not, both sorted. A route that grew more often on one side is
// there once for every time.
Missing, Extra []string
}
Divergence is the first tick in which a replay did something else than the recording.
type InputJson ¶ added in v0.3.0
type InputJson struct {
Tick int `json:",omitempty"`
Repeat int `json:",omitempty"`
Value json.RawMessage
}
InputJson is the input of a tick (Tree.Input) in a form that can be marshaled. Repeat is how many ticks after Tick have the same input.
type Leaf ¶
type Leaf struct {
Tag string
Metadata map[string]any
// Tick is how many times Tree.Tick had been called when the leaf grew.
Tick int
// contains filtered or unexported fields
}
Leaf is one outcome grown on a Tree: a tag, optional metadata, the tick it grew in and the path that led to it.
func (*Leaf) HasRoute ¶
HasRoute reports whether the route of the leaf contains the given route. The given route may leave out the start or the end of the path, but not part of a name: "EnemyAI.flee.LowHealth", "decide->EnemyAI.flee" and "LowHealth" all match "Game.Tick->EnemyAI.decide->EnemyAI.flee.LowHealth", while "flee.Low" and "Tick->Enemy" do not. An empty route matches nothing.
func (*Leaf) Route ¶
Route returns the path of the leaf from the root of its tree, followed by its tag: "Game.Tick->EnemyAI.decide->EnemyAI.flee.LowHealth".
func (*Leaf) StackFrames ¶
func (l *Leaf) StackFrames() []StackFrame
StackFrames returns the steps on the path of the leaf, from the root of the tree to the function that grew the leaf.
type LeafJson ¶
type LeafJson struct {
Tag string
Path int // an index into TreeJson.Paths
Tick int `json:",omitempty"`
Metadata map[string]any `json:",omitempty"`
}
LeafJson is a Leaf in a form that can be marshaled.
type PathJson ¶
type PathJson struct {
// Route is the steps as text, for whoever reads the log. FromJson and
// Load ignore it and use StackFrames.
Route string `json:",omitempty"`
StackFrames []StackFrame // from the root of the tree to the leaf
}
PathJson is one path of a tree: the steps that several leaves share.
type StackFrame ¶
type StackFrame struct {
FuncName string
StructName string `json:",omitempty"`
PackageName string `json:",omitempty"`
}
StackFrame is one step of a route: a function on the call stack, or a name given by Tree.Branch, which has only a FuncName.
type StartJson ¶ added in v0.3.0
type StartJson struct {
Tick int `json:",omitempty"`
Value json.RawMessage `json:",omitempty"`
}
StartJson is the beginning of a take (Tree.Start) in a form that can be marshaled. A take without a start value has no Value.
type Take ¶ added in v0.3.0
type Take struct {
// First is the tick in which the take began. Last is the last tick of it
// that has an input: First-1 when it has none. The tree counts the ticks
// of the whole session, so a game that counts its steps from 0 in every
// take is at step tick-First.
First, Last int
// contains filtered or unexported fields
}
Take is a part of a session that started from nothing: a start value, and the inputs and the leaves of its ticks. It is a copy: what the tree records or forgets afterwards does not change it.
Every method works on a nil *Take: the reads return false and Diverged returns nil.
func (*Take) Diverged ¶ added in v0.3.0
func (k *Take) Diverged(replay *Tree) *Divergence
Diverged compares the take with the tree of a game that played it again, and returns the first tick in which they differ, or nil when they do not.
The replay is a tree that started with the take: its tick 0 is the tick First of the recording. Tick by tick, the routes of the leaves that grew in the recording are compared with those of the replay, for the ticks that the replay has ended (Tree.Tick) and the take covers. Within a tick the order of the leaves does not count; how often a route grew does. Metadata is not compared.
It is the check that a replay is the session that was recorded: a game whose rules are not deterministic, or have changed since, learns in which tick it left the recording.
func (*Take) ReadInput ¶ added in v0.3.0
ReadInput fills into with the input of a tick of the take, as json.Unmarshal does. It returns false when the tick has no input or is not a tick of the take.
Read into a new variable for every tick: json.Unmarshal leaves alone what the JSON does not mention, so a variable that is used again may keep a part of the input of the tick before.
type Tree ¶
type Tree struct {
// contains filtered or unexported fields
}
Tree collects the leaves that a program grows while it runs.
The root of the tree is the function that called NewTree: routes start with the functions that it calls. When that function is no longer running, routes start below the deepest function that is on both the stack of NewTree and the stack of Grow. With nothing in common, a route is the whole stack of the goroutine.
A nil *Tree is valid and does nothing, so a game can leave its tree nil when it does not record.
A tree keeps every leaf until Dump writes them out, so a tree that records a long session has to be dumped from time to time.
A Tree is safe for concurrent use. The handles that Here, Branch and Fork return grow leaves on the same tree, and the methods that read the tree (HasRoute, Routes, Counts, Leaves, String...) read all of it whichever handle they are called on.
func FromJson ¶
FromJson rebuilds a tree, for example one that was logged by a running game, so that a test can compare it with the tree of its own run. The root of the leaves grown on it afterwards is the function that called FromJson.
Numbers in the metadata of a tree that went through JSON are float64.
func Load ¶
Load reads what Dump wrote, any number of lines, into one tree. The root of the leaves grown on it afterwards is the function that called Load.
When the reader fails or a line is not a dump (the last line of a game that crashed while writing, for example), Load returns the tree of the lines before it together with an error with the tag TagLoadDecodeFailed.
Numbers in the metadata of a loaded tree are float64.
func NewTree ¶
func NewTree() *Tree
NewTree returns an empty tree whose root is the calling function.
func (*Tree) Branch ¶
Branch returns a handle for a named part of the tree. In the routes of what grows through the handle, the function that called Branch appears under the given name:
func (n *Node) update(t *destiny.Tree) {
t = t.Branch(n.Name)
for _, child := range n.Children {
child.update(t)
}
}
Without Branch every route of this scene graph would read Node.update->Node.update->Node.update. With it they read World->Level1->Door3.
Calling Branch again in the same function, on the handle it returned, adds a name below the first one.
A name is part of the route, so it has to come from a small, fixed set (the names of nodes, states or scripts) and must not contain "." or "->". What changes for each entity or frame belongs in the metadata of a leaf.
func (*Tree) Counts ¶ added in v0.4.0
Counts returns how often a leaf grew along each route of the tree. Its keys are the routes that Routes lists. Over one game it says what happened how often; over many games it shows what never happens and what happens far too often. Cut the tree first to count a part of it: Only(route).Counts().
func (*Tree) Dump ¶
Dump writes the leaves that the tree holds to w and then forgets them, so that a tree that records a long session does not grow without end. Call it from time to time: every tick, every few seconds, or when Len passes a limit.
Each call writes one line of JSON, a TreeJson, that can be read on its own: the output can be cut into files between two calls. A tree without leaves and without a tape writes nothing. Load reads the lines back.
The line also holds the tape since the last call (Tree.Start, Tree.Input), which the tree forgets with the leaves.
When writing fails, Dump returns an error with the tag TagDumpWriteFailed and the tree keeps its leaves and its tape. A metadata value that JSON cannot hold (a channel, a function, a NaN) is written as its text. A start value or an input that JSON could not hold is not on the tape: Dump writes the rest and then returns the error with the tag TagTapeEncodeFailed.
Dump may be called from another goroutine than the one that grows the tree. Growing does not wait for the writer.
func (*Tree) During ¶
During returns a tree with the leaves that grew in the ticks from first to last, both included. It is a copy: leaves grown later on either tree do not appear on the other.
func (*Tree) Find ¶
Find returns the leaves whose route has the given route, in the order they grew. Use it to count how often a path was taken, to read the metadata of its leaves, or to compare the ticks of two outcomes.
func (*Tree) Fork ¶
Fork returns a handle that continues the current path somewhere else: in another goroutine, or at a later moment in the same one.
A goroutine's call stack does not contain the function that started it. Call Fork in the goroutine that hands the work off and use the handle in the new one:
go ai.think(tree.Fork()) // the arguments of a go statement run in the parent
An event that is queued and handled later has the same problem: when the handler runs, the function that sent the event has returned. Store a fork in the event and grow through it in the handler:
queue.push(event{kind: doorOpened, fate: tree.Fork()})
The routes of the leaves grown through the handle start with the path of the Fork call and continue with the functions of the stack of Grow that were not already running when Fork was called.
func (*Tree) Grow ¶
Grow adds a leaf with the given tag at the end of the current path.
The metadata is a list of key-value pairs, as in log/slog: Grow("LowHealth", "hp", 12). A value without a string key before it is stored as "arg<index>". Pass values, not pointers to things that change: the leaf keeps what it is given, and what a pointer points to may be different when the leaf is read.
Whatever is different for each entity or each frame (an ID, a position) belongs in the metadata. The tag is part of the route, and the tree keeps every different path it has seen.
func (*Tree) HasRoute ¶
HasRoute reports whether the tree grew a leaf along the given route. See Leaf.HasRoute for what a route may leave out.
func (*Tree) Here ¶
Here returns a handle whose routes continue with the calling function alone, and leave out everything else that is on the call stack above it.
A game engine calls the frame function of a game through many functions of its own, and a test calls it through others. Call Here at the top of the frame function and grow through the handle: the routes then start with that function wherever it was called from.
func (w *World) Step(in Input) {
fate := w.fate.Here()
w.player.act(fate, in) // World.Step->Player.act...
}
On a handle of Fork or Branch, Here keeps the path of the handle and adds the calling function to it.
func (*Tree) Input ¶ added in v0.3.0
Input stores the input of the current tick: what the rules of the game are given in it. Call it once in every tick, before the rules run. Called again in the same tick, it replaces the first. A tick without a call has no input.
v is turned into JSON at once, so a game may pass a slice that it uses again in the next tick. Equal inputs of ticks that follow each other are stored once. Take.ReadInput reads the value back.
A value that JSON cannot hold (a function, a NaN) is not kept: Dump returns an error with the tag TagTapeEncodeFailed, and Take.ReadInput of that tick returns the same error.
func (*Tree) Leaves ¶
Leaves returns the leaves that the tree holds, in the order they grew. A path that was taken twice has two leaves.
func (*Tree) LogValue ¶
LogValue implements slog.LogValuer. The keys match the fields of TreeJson, so a logged tree can be unmarshaled into TreeJson and rebuilt with FromJson.
func (*Tree) Only ¶
Only returns a tree with the leaves whose route has the given route (see Leaf.HasRoute). Use it to look at one part of a tree: the routes below one function, or the leaves with one tag. It is a copy, as with During.
func (*Tree) Routes ¶
Routes returns the different routes of the tree, in the order they first grew. A path that was taken many times appears once, so the result describes the shape of the tree: comparing it with a list of expected routes checks both what happened and that nothing else did.
func (*Tree) Start ¶ added in v0.3.0
Start begins a take at the current tick: a part of a session that starts from nothing, such as one level or one match. v is what the game needs to begin it again: the level, the players, the seed of its random numbers.
A take covers the ticks until the next Start. Together with the inputs of its ticks (Input) it lets a deterministic game play the take again, up to any tick. Take.ReadStart reads the value back.
v is turned into JSON at once. A value that JSON cannot hold is not kept: the take then has no start value, Dump returns an error with the tag TagTapeEncodeFailed, and Take.ReadStart returns the same error.
func (*Tree) String ¶
String draws the tree, one step or leaf per line, in the order they first grew. A leaf is written as its tag in brackets followed by its metadata. Leaves with the same tag at the same place are drawn once, with how many there are instead of their metadata:
Game.Tick
├── EnemyAI.decide
│ └── EnemyAI.flee
│ └── [LowHealth] hp=12
└── Physics.step
└── [Grounded] x120
func (*Tree) TagCounts ¶ added in v0.4.0
TagCounts returns how often a leaf with each tag grew, along whatever route.
func (*Tree) TakeAt ¶ added in v0.3.0
TakeAt returns the take that a tick belongs to: the one that began last at or before it. Give it the tick of a leaf to find the take in which the leaf grew. It returns nil when no take had begun.
func (*Tree) Takes ¶ added in v0.3.0
Takes returns the takes that the tree holds, in the order they began. Inputs from before the first Start are a take without a start value.
type TreeJson ¶
type TreeJson struct {
Paths []PathJson
Leaves []LeafJson
Starts []StartJson `json:",omitempty"`
Inputs []InputJson `json:",omitempty"`
}
TreeJson is a Tree in a form that can be marshaled: the different paths, the leaves in the order they grew, and the tape when the game recorded one.
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
destiny
command
Command destiny reads a recording that Tree.Dump wrote and prints what is in it: the leaves with the ticks they grew in, or how often each route grew.
|
Command destiny reads a recording that Tree.Dump wrote and prints what is in it: the leaves with the ticks they grew in, or how often each route grew. |