Documentation
¶
Overview ¶
Package fuzztape adapts go test -fuzz for typed and stateful testing.
The fuzzing engine built into go test mutates and minimizes flat byte slices. Fuzztape layers structure on top of those bytes without hiding them from the engine, so coverage guidance, corpus files, and input minimization keep working while tests operate on typed values and operation sequences.
Tapes ¶
A Tape reads a fuzz input as a sequence of typed decisions: bytes, booleans, integers, and choices. Reads past the end of the input return zero values, so every input decodes to a valid value and shorter inputs decode to simpler ones. Consumption is strictly front-to-back, which lets the engine's byte-level minimizer shrink decoded values and operation sequences without knowing they exist: truncating an input truncates the decoded behavior.
Tape.IntN deliberately skews toward boundary values — 0, 1, n-1, and powers of two — because most bugs live at boundaries and uniform random bytes rarely land there. Float64 and StringUTF8 skew the same way, toward NaN and the infinities, toward the UTF-8 encoding boundaries.
Generators ¶
A Gen composes typed generators over a Tape. Generators are plain functions, combined with Const, IntRange, OneOf, Map, Weighted, and SliceOf; every generator bottoms out in Tape reads, so the tape's decoding and shrinking properties hold for generated values automatically.
Machines ¶
A Machine runs a stateful property test: each fuzz input decodes to a bounded sequence of operations applied to a fresh system under test, with an invariant checked after every step. A machine runs either under go test -fuzz (Machine.Fuzz) or as a bounded number of pseudo-random cases inside an ordinary test (Machine.Run), sharing one corpus: a failure found by either is shrunk, saved as a seed input, and replayed by both. A panic out of an op counts as a failure and takes that same path, so the crash a fuzz target most often finds arrives as a minimal op sequence rather than as a raw traceback.
A typical machine and its two entry points:
var m = fuzztape.Machine[*Stack]{
Init: func(t *fuzztape.T) *Stack { return new(Stack) },
Ops: []fuzztape.Op[*Stack]{
{Name: "push", Apply: func(t *fuzztape.T, s *Stack) {
s.Push(t.Byte())
}},
{Name: "pop", When: func(s *Stack) bool { return s.Len() > 0 },
Apply: func(t *fuzztape.T, s *Stack) {
s.Pop()
}},
},
Check: func(t *fuzztape.T, s *Stack) {
if s.Len() < 0 {
t.Fatalf("negative length %d", s.Len())
}
},
Name: "FuzzStack",
}
func FuzzStack(f *testing.F) { m.Fuzz(f) }
func TestStack(t *testing.T) { m.Run(t, 500) }
Setting Machine.Bubble runs each case inside a testing/synctest bubble: time is virtual, and the bubble's exit check turns every case into a goroutine-leak check.
The T ¶
Ops, Init, and Check receive a T: the tape they draw from and the failure reporting of the test running them, in one value. Report a violation with T.Fatalf, abandon an op that turns out not to apply with T.Reject, and assert what should hold once the sequence has settled from T.Cleanup.
T embeds *Tape but not *testing.T, which is deliberate. Embedding the test would hand every op Run, Parallel, and Skip, each of which either panics inside a synctest bubble or abandons a sequence mid-flight.
Subpackages ¶
Each subpackage addresses one way a stateful test can pass while testing nothing.
- budget bounds work and resources: an allocation ceiling tied to input size, and a ledger that requires every acquire to be matched by a release before the sequence ends.
- corpus loads seed inputs from a directory and reports the ones that no longer decode to a distinct op sequence.
- faults injects tape-driven I/O faults, so a shrunk input names the single fault that breaks an invariant.
- linear checks that a concurrent history is linearizable, for the overlapping operations a per-op comparison cannot judge.
- model checks a system under test against a reference implementation or a second real one, comparing results and not only state.
- sched makes goroutine interleaving a tape decision, so a race reproduces from its corpus file and shrinks.
- splice builds seeds by crossing corpus inputs at the operation boundaries Machine.Splits recovers.
- stats counts how often each op actually runs, turning a machine that has silently stopped exercising an operation into a visible gap.
- trace turns a failing input into a test you can paste.
Command fuzztape runs every fuzz target in a module, which go test cannot: -fuzz takes one target in one package per invocation.
Go version ¶
The module builds with Go 1.26 and later. Under Go 1.27 and later it additionally provides method spellings of four of its functions — [Tape.Draw], [Tape.Pick], [Tape.OneOf], and [Gen.Map] — for left-to-right composition. Those methods are compiled only by a 1.27 or later toolchain, and this documentation is built by one, so it lists them unconditionally: code that must build under 1.26 has to use the free functions Pick, OneOf, and Map instead.
API stability ¶
This package is pre-v1 and its API is not yet stable. It may change without notice.
Example ¶
A Tape decodes a fuzz input front to back; reads past the end return zero values, so any prefix of an input is itself a valid input.
package main
import (
"fmt"
"github.com/tmc/go-iroh/internal/fuzztape"
)
func main() {
tape := fuzztape.New([]byte{0x2a, 0x03})
fmt.Println(tape.Byte())
fmt.Println(tape.Bool())
fmt.Println(tape.Byte()) // exhausted: zero value
}
Output: 42 true 0
Index ¶
- func Pick[V any](t *Tape, opts []V) V
- type Gen
- func Const[V any](v V) Gen[V]
- func Duration(lo, hi time.Duration) Gen[time.Duration]
- func Float32() Gen[float32]
- func Float64() Gen[float64]
- func IntRange(lo, hi int) Gen[int]
- func Map[A, B any](g Gen[A], f func(A) B) Gen[B]
- func OneOf[V any](gens ...Gen[V]) Gen[V]
- func SliceOf[V any](g Gen[V], max int) Gen[[]V]
- func StringASCII(max int) Gen[string]
- func StringUTF8(max int) Gen[string]
- func Weighted[V any](opts []V, weights []int) Gen[V]
- type Machine
- type Op
- type T
- type Tape
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Pick ¶
Pick returns one of opts, chosen by the tape. It panics if opts is empty. A zero tape picks opts[0].
The type parameter is named V rather than the conventional T because this package has a type named T.
Example ¶
package main
import (
"fmt"
"github.com/tmc/go-iroh/internal/fuzztape"
)
func main() {
tape := fuzztape.New(nil)
fmt.Println(fuzztape.Pick(tape, []string{"open", "close", "reset"}))
}
Output: open
Types ¶
type Gen ¶
A Gen decodes a value of type V from a tape. A generator is a plain function: composite generators are written as func literals calling other generators, and every Gen bottoms out in Tape reads, so the tape's decoding and shrinking properties hold for generated values automatically.
The type parameter is named V rather than the conventional T because this package has a type named T.
Example ¶
Generators compose over a tape; a zero (or exhausted) tape decodes to the simplest value each generator offers.
package main
import (
"fmt"
"github.com/tmc/go-iroh/internal/fuzztape"
)
func main() {
size := fuzztape.IntRange(1, 8)
sizes := fuzztape.SliceOf(size, 4)
fmt.Println(sizes(fuzztape.New(nil)))
fmt.Println(size(fuzztape.New([]byte{2}))) // selector 2 forces the upper boundary
}
Output: [] 8
func Duration ¶ added in v0.1.1
Duration returns a generator of durations in [lo, hi]. It panics if hi < lo or if the span exceeds the range of int. A zero tape yields lo.
Under Machine.Bubble a drawn duration costs no real time, which is what makes timeout and retry paths cheap to explore.
func Float32 ¶ added in v0.1.1
Float32 returns a generator of float32 values, skewed as Float64 is. A zero tape yields 0.
func Float64 ¶ added in v0.1.1
Float64 returns a generator of float64 values, skewed like Tape.IntN toward the values that break arithmetic: zero, negative zero, both infinities, NaN, the subnormal boundary, and the largest magnitudes. A zero tape yields 0.
The unskewed case draws a uniform bit pattern, so NaN payloads and subnormals occur naturally as well.
Example ¶
Float64 skews toward the values that break arithmetic. Selector 6 draws NaN, which a uniform bit pattern reaches vanishingly rarely.
package main
import (
"fmt"
"github.com/tmc/go-iroh/internal/fuzztape"
)
func main() {
g := fuzztape.Float64()
fmt.Println(g(fuzztape.New(nil)))
fmt.Println(g(fuzztape.New([]byte{6})))
}
Output: 0 NaN
func SliceOf ¶
SliceOf returns a generator of slices of up to max values of g. It panics if max is negative or math.MaxInt.
func StringASCII ¶ added in v0.1.1
StringASCII returns a generator of printable-ASCII strings of length in [0, max]. A zero tape yields "". It panics if max is negative or math.MaxInt.
func StringUTF8 ¶ added in v0.1.1
StringUTF8 returns a generator of valid UTF-8 strings of up to max runes, skewed toward the runes that break text handling: NUL, the ASCII and multi-byte boundaries, a combining mark, the replacement character, and the largest legal rune. A zero tape yields "".
Every string it produces is valid UTF-8 by construction. To generate invalid encodings — a lone surrogate, a truncated sequence, an overlong form — draw raw bytes with Tape.Bytes instead; a generator that returns a string cannot represent them.
It panics if max is negative or math.MaxInt.
func Weighted ¶ added in v0.1.1
Weighted returns a generator of opts, selecting opts[i] with frequency proportional to weights[i]. It panics unless opts and weights have the same non-zero length, every weight is non-negative, at least one is positive, and they sum within int. A zero tape yields the first option with a positive weight.
Example ¶
Weighted selects proportionally; a zero tape takes the first option with a positive weight.
package main
import (
"fmt"
"github.com/tmc/go-iroh/internal/fuzztape"
)
func main() {
g := fuzztape.Weighted([]string{"read", "write"}, []int{1, 9})
fmt.Println(g(fuzztape.New(nil)))
}
Output: read
type Machine ¶
type Machine[S any] struct { // Init returns a fresh system under test. It may draw from the // tape to vary the starting state; those draws precede the first // op's, and [Machine.Splits] accounts for them. Init func(t *T) S // Ops is the operation set. It must be non-empty, and its order // is part of the corpus encoding: reordering ops changes how // previously saved inputs decode. Ops []Op[S] // Check asserts the invariant, failing with t.Fatalf. It must not // draw from the tape: its draws would be indistinguishable from an // op's and would shift how the rest of the input decodes. Check func(t *T, s S) // MaxOps bounds the ops decoded per input; 0 means 64. It is only an // upper bound: a sequence also ends when the input runs out, which // for short inputs happens well before MaxOps. MaxOps int // Name, if set, is the fuzz target name (e.g. "FuzzStreamMachine") // whose seed corpus under testdata/fuzz/ [Machine.Run] replays // before its random cases and saves shrunk failing inputs to, so a // failure found by either mode becomes a seed input replayed by // both. Name string // Bubble runs each input's op sequence inside a testing/synctest // bubble: time is virtual, and the bubble's exit check reports any // goroutine the sequence left durably blocked, making every case a // goroutine-leak check. Ops must not depend on real time or on // goroutines started outside the bubble. // // Init runs inside the bubble, so a goroutine it starts must be // stopped inside the bubble too — by an op, or by a cleanup Init // registers with [T.Cleanup], which the bubble runs before its exit // check. A goroutine stopped on the outer test's cleanup is still // blocked at exit and fails every case. // // A leak is reported with the stacks of the goroutines left blocked, // and shrinks like any other failure. The goroutines themselves stay // blocked for the rest of the run, in a bubble nothing else can // reach. Bubble bool // Stall bounds how long a run may complete no input before it is // reported as wedged and the process aborted. Zero means 30 // seconds; a negative value disables the check. // // It applies only under Bubble and only to [Machine.Run], and // covers the one stall a bubble cannot report itself: a goroutine // blocked on something outside the bubble is not durably blocked, // so the bubble neither quiesces nor trips the runtime's deadlock // check, and the run hangs until go test times out. A goroutine // blocked inside the bubble never reaches this, being caught the // moment it happens. [Machine.Fuzz] is supervised by the fuzzing // engine instead. Stall time.Duration }
A Machine describes a stateful property test: a system under test, a set of operations, and an invariant. Each input decodes to a bounded operation sequence; the invariant is checked after every applied op.
func (Machine[S]) Fuzz ¶
Fuzz registers the machine as the fuzz function of f. Corpus files, -fuzztime budgets, minimization, and seeds via f.Add behave as for any other fuzz target.
Stall does not apply here. The fuzzing engine runs inputs in worker processes and already supervises them: a worker that stops responding is killed and its input recorded as a crasher. A watchdog in this process would be watching the coordinator, which runs no inputs of its own and would look stalled the moment it started orchestrating.
func (Machine[S]) Replay ¶ added in v0.1.1
Replay runs one input against a fresh system, as a subtest of t, and reports whether it passed. It is what a saved corpus file needs to be re-run by hand, and what a generated reproduction case calls.
func (Machine[S]) Run ¶
Run checks the machine inside an ordinary test: first every seed input saved under testdata/fuzz for Name, then iters pseudo-random inputs; iters <= 0 means 100. The seed is printed and can be pinned with -fuzztape.seed. On failure Run shrinks the failing input, logs the minimal op sequence, and (if Name is set) saves the input to testdata/fuzz/ for permanent replay.
Replaying the corpus here is what keeps the two modes symmetric: a failure found by Run is saved as a seed, and that seed is then checked by go test with no -fuzz flag, not only by the fuzz target.
func (Machine[S]) Splits ¶ added in v0.0.2
Splits reports the tape offsets at which the ops decoded from data begin, by replaying data against a fresh system in a subtest of t. The final element is the offset just past the last byte the sequence consumed, so data[splits[i]:splits[i+1]] holds the bytes of op i. Cutting or splicing inputs at these offsets edits whole operations.
The replay applies the sequence for real: Init runs, ops run, and if the input fails the machine the failure is reported on the subtest. Under Bubble each replay that fails its exit check leaves another set of blocked goroutines behind in an abandoned bubble — bounded and harmless, as for shrink attempts, but visible in goroutine dumps.
func (Machine[S]) Trace ¶ added in v0.1.1
Trace replays data against a fresh system and returns the names of the ops it applied, in order, with rejected ops marked. It is the decoded meaning of an input: the same thing a failing case logs, available without failing.
The replay applies the sequence for real, as Machine.Splits does, and reports on a subtest of t if the input fails the machine. An op that panics is reported and marked in the trace, not swallowed: an input that crashes the machine is the most broken thing a corpus can hold, and a trace that hid it would report it as decoding to nothing.
type Op ¶
type Op[S any] struct { // Name labels the op in failure logs. Name string // Weight is the op's relative selection frequency; 0 means 1. Weight int // When reports whether the op is currently applicable; // nil means always. Ops with a false When are not selected. When func(s S) bool // Apply performs the op, drawing parameters from t. An op that // turns out not to apply once it has drawn calls [T.Reject]; an op // that finds a violation calls [T.Fatalf] or [T.Errorf]. // // A panic out of Apply — from the system under test, most often — // is caught and reported as a failure with its stack, so it is // logged, shrunk, and saved like any other. That holds only for the // goroutine Apply runs on: a panic on a goroutine the op started // still kills the test binary, as it does anywhere in Go. Apply func(t *T, s S) }
An Op is one operation of a stateful property test.
func NewOp ¶ added in v0.1.1
NewOp returns an op that draws one parameter with g and passes it to apply. The parameter is drawn once, before apply runs, which is what lets two implementations of the same operation — a system under test and a reference model — be driven with identical input.
Example ¶
An op can draw its parameter through a generator, which keeps the value typed and lets the same draw drive a reference implementation.
package main
import (
"fmt"
"github.com/tmc/go-iroh/internal/fuzztape"
)
func main() {
type queue struct{ xs []int }
op := fuzztape.NewOp("push", fuzztape.IntRange(1, 100),
func(t *fuzztape.T, q *queue, v int) { q.xs = append(q.xs, v) })
fmt.Println(op.Name)
}
Output: push
func OpOver ¶ added in v0.1.1
OpOver returns an op that applies to one element of candidates, chosen by the tape, and is enabled only while that set is non-empty.
It replaces the pairing of a When that tests a filtered set against a Apply that rebuilds it, which is otherwise written out at every op that acts on "one of the currently eligible" things.
type T ¶ added in v0.1.1
type T struct {
*Tape
// contains filtered or unexported fields
}
A T carries the tape an op draws from and the failure reporting of the test running it. It is the fuzztape analog of testing.T: ops, Machine.Init, and Machine.Check receive one, draw parameters through the embedded Tape, and report failures through its own forwarding methods.
T embeds *Tape but not *testing.T. Embedding the test would hand every op Run, Parallel, and Skip, each of which either panics inside a synctest bubble or abandons a sequence mid-flight; testing.TB is sealed, so a narrow struct with explicit forwarders is the only way to expose reporting without them. Everything T does forward reports the caller's line, not fuzztape's.
A T is valid only for the duration of the input it was created for. Retaining one past the op sequence that received it, or using one from another goroutine after that sequence ends, is a bug.
func NewT ¶ added in v0.1.1
NewT returns a T reading data and reporting to tb.
A Machine builds its own T for every input, so this is for exercising an op directly in an ordinary test, without a machine around it. A T.Reject on a T built here panics out to the caller, because there is no op loop to unwind into, and its T.Cleanup functions run when tb finishes rather than at the end of a sequence, because there is no sequence.
func (*T) Cleanup ¶ added in v0.1.1
func (t *T) Cleanup(f func())
Cleanup registers f to run when this input's op sequence ends, after the last op and in last-registered-first order. It is where a sequence asserts what should be true once the system has settled: that every resource it took was returned, that it allocated no more than its input justified.
The scope is the input, not the test. That matters twice over. A failure reported from a cleanup is still attributed to the op sequence that caused it, so the sequence is logged and shrunk like any other failure — a cleanup deferred to the end of the test would report after the machine had stopped listening. And under Machine.Bubble the cleanup runs inside the bubble, before its exit check, which is where a goroutine started by Machine.Init must be stopped: one stopped on the outer test's cleanup is still blocked at exit and fails every case.
func (*T) Fatalf ¶ added in v0.1.1
Fatalf reports a failure and ends the sequence. It does not return.
Call it only from the goroutine running the op sequence. It ends the sequence with a runtime.Goexit, which unwinds the calling goroutine and nothing else, so from a goroutine the system under test started — one scheduled by the sched subpackage, say — it kills that goroutine and lets the sequence carry on around the hole. Report from there with T.Errorf instead, which returns.
func (*T) Helper ¶ added in v0.1.1
func (t *T) Helper()
Helper marks the calling function as a test helper.
func (*T) Logf ¶ added in v0.1.1
Logf writes to the test log, which go test prints only for a failing input.
func (*T) Reject ¶ added in v0.1.1
Reject abandons the current op: the op did not apply, the sequence continues with the next one, and the reason appears in the op log of a failing input. It does not return.
Reject is for an op that turns out not to be applicable once it has drawn its parameters — a queue that is full, an ID that is already taken. It is not a failure report: use T.Fatalf or T.Errorf for that. Prefer Op.When where applicability can be decided before drawing anything, because an op rejected after drawing has still consumed tape.
type Tape ¶
type Tape struct {
// contains filtered or unexported fields
}
A Tape consumes a fuzz input as a sequence of typed decisions. The zero Tape is empty and yields zero values forever.
func (*Tape) Bytes ¶
Bytes returns a slice of length in [0, max], drawn from the tape and zero-filled past the end of the input. It panics if max is negative or math.MaxInt.
func (*Tape) Done ¶
Done reports whether the input is exhausted. Further reads succeed and return zero values.
func (*Tape) IntN ¶
IntN returns an integer in [0, n). It panics if n <= 0.
The distribution is deliberately not uniform: one leading selector byte occasionally forces a boundary value — 0, 1, n-1, or a power of two — because most bugs live at boundaries and uniform bytes rarely land there. A zero tape decodes to 0.
The unskewed case reduces eight bytes modulo n, which for an n that is not a power of two favors the low end by a factor of at most 2⁻⁶⁴ per value. That bias is beneath notice next to the deliberate one above it, and removing it would cost a variable number of tape bytes per draw, which would break the fixed decoding that shrinking depends on.
func (*Tape) Len ¶ added in v0.1.1
Len returns the length of the input, which bounds the work a correctly behaved system under test should do for it.
Directories
¶
| Path | Synopsis |
|---|---|
|
Package faults provides tape-driven fault injection for fuzztape machines.
|
Package faults provides tape-driven fault injection for fuzztape machines. |
|
Package model checks a system under test against a reference model.
|
Package model checks a system under test against a reference model. |
|
Package splice builds new fuzz seeds by cutting corpus inputs at operation boundaries.
|
Package splice builds new fuzz seeds by cutting corpus inputs at operation boundaries. |
|
Package stats counts how often a fuzztape machine's ops actually run.
|
Package stats counts how often a fuzztape machine's ops actually run. |
|
Package trace turns a failing input into a test you can paste.
|
Package trace turns a failing input into a test you can paste. |