destiny

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Dec 3, 2026 License: BSD-3-Clause Imports: 10 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

destiny

Why

github.com/rm4n0s/errors lets a test check that an error happened along a specific execution path. This package does the same for things that are not errors.

A game has few errors but many outcomes: an enemy fled, a chest dropped a rare item, a quest advanced, a door opened. Each one is reached through a chain of decisions in the code. destiny records those outcomes together with the path that led to each one. One run grows many of them, and because their paths share their beginnings, together they form a tree:

World.Step
├── Orc.think
│   └── Root
│       ├── Flee
│       │   └── IsHurt
│       │       └── [Failed] x421
│       └── Chase
│           └── Approach
│               └── [Succeeded] x132
└── Player.act
    └── Player.swingSword
        └── Orc.hurt
            ├── [Damaged] x6
            └── Orc.die
                ├── [Died] x3
                └── Quest.onKill
                    ├── [Advanced] x2
                    ├── [Completed] kills=3
                    └── Door.onQuestCompleted
                        └── Door.update
                            └── [Opened]

A test then asks whether the tree grew a given path, or compares the whole shape of the tree with what it expects. That lets you design a game by writing down, for each situation, the paths it should take.

Usage

AI coding assistants: read AI_GUIDE.md before using this package.

go get github.com/rm4n0s/destiny
Grow a leaf where something happens
func (w *World) Step(in Input) {
    fate := w.fate.Here() // routes start here, whoever calls Step
    w.player.act(fate, w, in)
    for _, o := range w.orcs {
        o.think(fate, w)
    }
    w.fate.Tick() // the end of a frame
}

func (o *Orc) hurt(fate *destiny.Tree, w *World, damage int) {
    o.hp -= damage
    fate.Grow("Damaged", "orc", o.id, "hp", o.hp)
    if o.hp <= 0 {
        o.die(fate, w)
    }
}

Grow takes a tag and key-value pairs. It remembers the call stack of the line it is on. The tree is passed down as an argument, like a context.Context.

Test which paths a game took
func TestASwingThatKillsStartsAChain(t *testing.T) {
    tree := destiny.NewTree()
    w, _ := NewWorld(levelOne, tree, seed)
    w.orcs[0].hp = swordDamage
    putPlayer(w, w.orcs[0], 1.5)

    w.Step(Input{Attack: true})

    // One path:
    if !tree.HasRoute("Player.swingSword->Orc.hurt->Orc.die->Quest.onKill.Advanced") {
        t.Errorf("unexpected tree:\n%s", tree)
    }
    // Or everything the swing caused, and nothing else:
    want := []string{
        "World.Step->Player.act->Player.swingSword->Orc.hurt.Damaged",
        "World.Step->Player.act->Player.swingSword->Orc.hurt->Orc.die.Died",
        "World.Step->Player.act->Player.swingSword->Orc.hurt->Orc.die->Loot.drop.CommonDrop",
        "World.Step->Player.act->Player.swingSword->Orc.hurt->Orc.die->Quest.onKill.Advanced",
    }
    if got := tree.Only("Player.swingSword").Routes(); !slices.Equal(got, want) {
        t.Errorf("got %q", got)
    }
}

A route is the functions from the root of the tree to the leaf, joined by ->, then . and the tag. HasRoute accepts a part of a route, as long as it does not cut a name in two. Routes lists each different route once, in the order it first grew, so comparing it checks both what happened and that nothing else did. Only(route) and During(firstTick, lastTick) give a part of the tree; Find(route) gives the leaves, with their metadata and the tick they grew in.

Name the parts that the call stack cannot tell apart

A scene graph or a behaviour tree is walked by one function that calls itself, so every route would read run->run->run. Branch gives the calling function a name in the routes below it:

func run(fate *destiny.Tree, n *node, o *Orc, w *World) bool {
    fate = fate.Branch(n.name)
    // ... run the children with fate ...
    fate.Grow("Succeeded", "orc", o.id)
}
// World.Step->Orc.think->Root->Fight->Strike.Succeeded

The same works for the states of a state machine: fate.Branch(w.phase.String()).

Carry a path to a goroutine, or to a later frame

A goroutine's stack does not contain the function that started it, and an event that is handled later does not contain the function that sent it. Fork keeps the path:

go p.search(fate.Fork(), grid)                     // a goroutine: Fork runs in the parent

w.events = append(w.events, event{fate: fate.Fork()}) // an event: handled in a later step

func (d *Door) onQuestCompleted(e event) {
    e.fate.Here().Grow("Unlocking")
}
// World.Step->Player.act->Player.swingSword->Orc.hurt->Orc.die->Quest.onKill->Door.onQuestCompleted.Unlocking

The route of the door says what caused it, even though it opened in another frame.

Record a real game without running out of memory

A nil *destiny.Tree does nothing, so a game that does not record leaves its tree nil. A game that records writes its tree out from time to time:

if w.steps%60 == 0 {
    if err := tree.Dump(file); err != nil { // one line of JSON; the tree forgets what it wrote
        slog.Error("the tree was not written", "err", err)
    }
}

destiny.Load(file) reads the file back into a tree, which a test queries like any other: to see what happened in a session, or to play the same inputs again and compare the two trees. A tree also logs itself through log/slog, and ToJson/FromJson turn it into JSON and back.

Print the tree

fmt.Println(tree) draws the tree shown at the top. A failing test should print it: t.Errorf("unexpected tree:\n%s", tree).

Cost

Measured on an AMD Ryzen 9 6900HX with Go 1.27 (go test -bench .):

Call Time Memory
Grow without metadata, ten calls deep 1.3 µs 48 B, 1 allocation
Grow with one key-value pair 1.5 µs 392 B, 4 allocations
Branch, Fork or Here at a place the tree has seen 0.4–0.5 µs none
Grow on a nil tree a nil check none; 8 B when a number is passed as metadata

A recording of the example game crypt takes 67 bytes a leaf on disk, and gzip makes it 18 times smaller.

Examples

examples holds two small 3D games made with Glutter, in a module of their own so that this package depends on nothing but rm4n0s/errors:

  • examples/crypt: a dungeon. A behaviour tree (Branch), a chain of consequences from one sword swing, an event that opens a door a second later (Fork), three orcs through the same code, recording and replay.
  • examples/bastion: a tower defence. A state machine (Branch), path-finding on another goroutine (Fork), recording and replay.

Each has tests of its rules and tests of its real page on Glutter's test harness.

More

SPEC.md describes every rule in detail: where a route starts, how names are matched, what Branch, Fork and Here do to a path, and the format of a dump.

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

Index

Constants

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

Variables

This section is empty.

Functions

This section is empty.

Types

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

func (l *Leaf) HasRoute(route string) bool

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

func (l *Leaf) Route() string

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 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 Branch and Fork return grow leaves on the same tree, and the methods that read the tree (HasRoute, Routes, Leaves, String...) read all of it whichever handle they are called on.

func FromJson

func FromJson(tj TreeJson) *Tree

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

func Load(r io.Reader) (*Tree, error)

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

func (t *Tree) Branch(name string) *Tree

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) Dump

func (t *Tree) Dump(w io.Writer) error

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 writes nothing. Load reads the lines back.

When writing fails, Dump returns an error with the tag TagDumpWriteFailed and the tree keeps its leaves. A metadata value that JSON cannot hold (a channel, a function, a NaN) is written as its text.

Dump may be called from another goroutine than the one that grows the tree. Growing does not wait for the writer.

func (*Tree) During

func (t *Tree) During(first, last int) *Tree

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

func (t *Tree) Find(route string) []*Leaf

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

func (t *Tree) Fork() *Tree

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

func (t *Tree) Grow(tag string, metadata ...any)

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

func (t *Tree) HasRoute(route string) bool

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

func (t *Tree) Here() *Tree

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) Leaves

func (t *Tree) Leaves() []*Leaf

Leaves returns the leaves that the tree holds, in the order they grew. A path that was taken twice has two leaves.

func (*Tree) Len

func (t *Tree) Len() int

Len returns the number of leaves that the tree holds.

func (*Tree) LogValue

func (t *Tree) LogValue() slog.Value

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

func (t *Tree) Only(route string) *Tree

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

func (t *Tree) Routes() []string

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) String

func (t *Tree) String() 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) Tick

func (t *Tree) Tick() int

Tick ends the current tick and starts the next one. It returns the number of the tick that starts. Call it at the end of each frame: every leaf then knows in which frame it grew (Leaf.Tick), counted from 0.

func (*Tree) ToJson

func (t *Tree) ToJson() *TreeJson

ToJson returns the leaves that the tree holds in a form that can be marshaled. The tree keeps them.

type TreeJson

type TreeJson struct {
	Paths  []PathJson
	Leaves []LeafJson
}

TreeJson is a Tree in a form that can be marshaled: the different paths, and the leaves in the order they grew.

Jump to

Keyboard shortcuts

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