roc-fuzz is a Roc platform for testing pure Roc code past the examples you
write. Fuzz targets check properties over typed inputs with coverage-guided
search; goals, trace rules and allocation measurements check what a passing
campaign exercised; Model searches and fuzzes a stateful component described
as a state machine; and Solve proves or refutes claims about fixed-width
integer arithmetic. Each target builds into one self-contained executable that
checks declared examples, explores, and keeps findings for inspection, replay,
retention and minimization.
Browse the generated API reference · Download the standalone PDF manual · View roc-fuzz on GitHub.
1. Test a Roc application with roc-fuzz§
Suppose a decoder passes every example you wrote, but one unusual combination
of lengths and Unicode text still makes it fail. An expect checks the cases
you thought of; adding more of them helps only when you can imagine the
troublesome input in advance.
roc-fuzz adds techniques for the cases you did not think of. Each answers a different question about the same code, and their results feed one another:
A fuzz target states a property over typed, generated inputs. Coverage guidance searches for inputs that break it, and any failure is saved so you can show, replay, minimize and keep it as a regression.
Passing is not the same as having exercised anything. Goals say what a campaign must have reached, and trace rules and allocation measurements check behavior that the returned value does not show.
A stateful component breaks in sequences of calls. A model describes it as a state machine with rules, searches a small world exhaustively under
roc test, and fuzzes the same machine over a large one.Some properties of fixed-width integer arithmetic can be proved for every value, or refuted with the values that break them.
Campaigns run these targets for longer, keep a corpus of useful inputs, and leave a report that CI can keep as evidence.
This chapter explains what each technique is for and where it stops, then what a fuzz target is. Fuzz your first function is the hands-on start.
1.1. Choose a technique§
| Question | Technique | You supply | You get back |
|---|---|---|---|
| Does this case give the right answer? | An expect under roc test | A case and its expected result | Pass or fail for that one case |
| Does a rule hold for inputs I did not think of? | A fuzz target | A generator, an operation and a property | Saved failures to show, replay and minimize; a corpus of useful inputs |
| Did a passing campaign reach the cases that matter, and behave as it should on the way? | Goals, trace rules and allocation measurements | Named events, rules about them, and measured regions | The goals reached, each with its first witness; trace and allocation failures; an exact per-example allocation baseline |
| Does a stateful component survive every sequence of calls? | A Model | A state machine with rules and goals | From a search, a verdict and a shortest breaking trace; from a fuzz target, findings over a large world |
| Does this arithmetic hold for every value? | A Solve claim | Unknown fixed-width integers and a claim about them | Proved, or values that refute the claim or make it crash |
| Does it keep holding as the code changes? | Campaigns and CI | Bounds, a corpus directory and a CI job | A report with the outcome, goals and findings, kept as evidence |
Each technique stops somewhere, and the chapters state where:
A campaign that finds no failure shows only that the inputs it explored passed. It never proves the absence of bugs, and a weak property misses wrong answers.
Goals grade a campaign; they do not steer it. A campaign with poor inputs can pass every rule while reaching few goals, so a campaign that leaves a declared goal unreached is reported as
inconclusive, not passed.A model search covers only the small world you list. A fuzz target over the same machine reaches further, with no guarantee of completeness.
Solveworks on integers of 1 to 64 bits. A claim that multiplies unknowns gets several times harder with each bit, aProvedanswer rests on the solver, and as an input generator it is orders of magnitude slower than a hand-written one.
1.1.1. How results become examples§
Every technique ends in something you can keep. A fuzz finding, and the first
input to reach each goal, are bytes that TARGET retain turns into a
Fuzz.saved declaration in the target’s examples, so every later check runs
them. A model search’s breaking trace replays with Model.replay, and its
witness for a goal becomes an example of the model’s fuzz target. A Solve
answer is an ordinary Roc record, so an expect can pin it, and a fuzz target
can check the claim’s term against the compiled code.
1.2. What a fuzz target is§
A fuzz target is a small Roc application that connects roc-fuzz to one behavior in your code. It contains three essential ideas:
a generator that creates the Roc values to try;
an operation that calls the application code you want to exercise; and
a property that decides whether the result is acceptable.
The target is necessary because roc-fuzz cannot infer what correctness means for your application. It can explore inputs and notice crashes, hangs, leaks, and new behavior in the compiled program, but only you can state application rules such as:
encoding and then decoding returns the original value;
pushing an item and then popping returns that item and the original stack;
normalizing an already normalized value changes nothing;
two independent implementations produce the same result; or
arbitrary input may return an ordinary error but must never crash.
A target is development and test code. It is separate from the application you
ship, and it normally imports the module it exercises. Start with one operation
and one property per target so failures remain easy to understand. A Model
builds a fuzz target from a state machine, and the same runner commands apply
to it.
1.3. How fuzzing complements tests§
Unit tests and fuzzing answer different questions and work best together.
| Approach | What it does well | What it leaves to you |
|---|---|---|
| Unit tests | Check named examples and preserve known regressions quickly and deterministically. | You must choose every example. |
| A hand-written random loop | Tries more values than a short example list. | You must build generation, search strategy, repeatability, failure storage, and diagnostic tools. |
| roc-fuzz | Uses execution feedback to explore, retains useful inputs, and saves failures that can be shown, replayed, and minimized. | You must define meaningful generators and properties; a weak property can miss real bugs. |
Declared examples, including retained failures, run on every check independently of the corpus, while exploration continues searching for new cases. Unit tests can share the same application invariants.
1.4. What “typed” and “coverage-guided” mean§
Typed means the test receives ordinary Roc values rather than making every
target decode an arbitrary byte array itself. A generator can produce a U64,
a Str, or a record such as
{ delimiter : Str, value : Str }. You choose the useful ranges and shapes.
roc-fuzz does not automatically know your application’s domain rules.
Coverage-guided describes how the search chooses where to spend effort. roc-fuzz observes which parts of the compiled program each input reaches. When an input reaches behavior not seen before, it retains that input and creates further variations from it. This feedback makes the search more purposeful than independent random samples.
The retained useful inputs form a corpus. A later run can reuse that corpus to resume from behavior already discovered. Coverage here is search feedback, not a percentage and not proof that the program is correct.
roc-fuzz embeds a mature native fuzzing engine in the executable built by Roc. Normal users interact with roc-fuzz commands and Roc values; knowledge of that engine is needed only for the expert escape hatch.
1.5. What roc-fuzz provides§
Applications use three of the platform’s modules. Fuzz builds targets from
typed generators for common Roc values and tools for combining them, declared
examples, marks, trace rules and allocation measurements. Model describes and
checks state machines. Solve states and answers claims about fixed-width
integers.
A target builds into one self-contained executable:
roc build --fuzz fuzz/stack/main.roc --output=stack-fuzz
./stack-fuzz run
That executable supplies:
coverage feedback that directs the search toward new behavior;
a bounded local runner with sensible defaults;
saved inputs for crashes, failed properties, hangs, memory limits, and leaks;
commands to render a saved input as a Roc value, reproduce it, and minimize it;
a persistent corpus that makes later runs build on earlier discoveries; and
a supervised CI mode that records configuration, logs, hashes, goals and failures.
The normal workflow needs no separate native project or fuzzing tool
installation. A Model search and a Solve claim are pure functions, so they
also run in an ordinary expect under roc test.
1.6. Choose a good first target§
Good first targets are fast, deterministic operations over in-memory values with a rule that is easy to state.
| Application behavior | Possible property | Why it fits |
|---|---|---|
| Parser or decoder | Every input returns a value or an ordinary error without crashing or hanging. | Large input space and clear acceptable outcomes. |
| Encoder and decoder | Decoding an encoded value returns the original value. | Strong round-trip property. |
| Collection or state transition | An operation preserves membership, length, ordering, or an independent model. | Many combinations can exercise edge cases. |
| Canonicalization or normalization | Applying the operation twice gives the same result as once. | Simple idempotence property. |
| Two implementations of one rule | Both produce the same result. | Each implementation acts as an oracle for the other. |
A target is a poor fit when one input performs slow network, filesystem, UI, or database work; depends on nondeterministic external state; can legitimately run without a practical time or memory bound; or deliberately terminates the process for ordinary invalid input. Prefer unit, integration, end-to-end, or benchmark tests for those jobs.
Fuzzing consumes CPU time and stores a corpus and failure artifacts. More time can explore more behavior, but a clean run means only that no failure was found during that search.
roc-fuzz currently supports Linux x86-64 with musl and Apple Silicon macOS 11 or newer. Continue with Fuzz your first function to build a target against a small application module and work through a failure.
2. Fuzz your first function§
This tutorial adds a fuzz target beside a small Roc module, runs it, inspects a failure, fixes the bug, and preserves the lesson as a regression test. You do not need prior fuzzing experience or knowledge of the embedded engine.
The example uses a stack because its rule is easy to state: after pushing an item, popping must return that item and the original stack. The demo keeps the application module beside its target only to make the tutorial self-contained; a real target normally imports an existing module from the application.
2.1. Create the application module§
Create fuzz/stack/Stack.roc:
Stack := [].{
push : List(a), a -> List(a)
push = |items, item| List.append(items, item)
pop : List(a) -> Try({ value : a, rest : List(a) }, [Empty])
pop = |items|
match items {
[first, .. as rest] => Ok({ value: first, rest })
[] => Err(Empty)
}
}
This version contains a plausible implementation mistake: push appends the
new item to the end, while pop removes an item from the front. A test using
only an empty stack would pass, so the defect is easy to overlook.
The fuzz target is a separate development application that imports this module; the shipped application does not need to depend on roc-fuzz.
2.2. Write the target§
Create fuzz/stack/main.roc:
app [target] { fuzz: platform "PLATFORM_URL" }
import fuzz.Fuzz
import Stack
test : List(U8) -> Fuzz.Outcome
test = |initial| {
item = 0
pushed = Stack.push(initial, item)
match Stack.pop(pushed) {
Ok({ value, rest }) if value == item and rest == initial => Fuzz.keep
Ok(_) => crash "pop did not undo push"
Err(Empty) => crash "the stack was empty after push"
}
}
target = Fuzz.target_with({
examples: [],
name: "stack-push-pop",
generator: Fuzz.list(Fuzz.u8, 8),
test,
show: |initial| Str.inspect(initial),
})
Replace PLATFORM_URL with the platform URL in the notes of the
latest release.
The target connects the three ideas from the previous chapter:
| Part | Role in this target |
|---|---|
| Generator | Fuzz.list(Fuzz.u8, 8) supplies lists containing up to eight U8 values. |
| Application operation | The test calls Stack.push and Stack.pop. |
| Property | After pushing 0, the popped value must be 0 and the remaining stack must equal the generated initial value. |
Fuzz.keep means the generated case completed normally and satisfied the
property. crash means roc-fuzz must save the case as a failure. show tells
roc-fuzz how to render the generated value for a person.
The application header selects an immutable roc-fuzz release. Install the compatible Roc compiler documented with that release separately. For another project, select a release from GitHub Releases and use the compiler documented with that release. Roc obtains the platform through its normal package mechanism; there is no separate roc-fuzz installer.
2.3. Build and find the bug§
Build a self-contained fuzzing executable:
roc build --fuzz fuzz/stack/main.roc --output=stack-fuzz
Start with the bounded default run:
./stack-fuzz run --report-dir=.roc-fuzz/first-run
roc-fuzz generates initial stacks and repeatedly runs the property. An empty stack passes even with the bug, while a non-empty stack can expose the mismatch between the two ends. The supervisor prints the outcome and report location:
Report: .roc-fuzz/first-run/report.json
The report directory contains report.json, a human summary and the child’s
captured run.log. That log contains libFuzzer’s progress and failure details;
native crash artifacts are under failures/. For this finding, the supervisor
also preserves the exact failing input as original-input.bin. Choose a fresh
report directory when repeating the run.
Saved inputs can contain generator entropy or encoded values. Inspect the
decoded representative with show instead of opening the binary as text:
./stack-fuzz show .roc-fuzz/first-run/original-input.bin
For this target, show prints the generated initial stack. Reproduce the failure
in a fresh process:
./stack-fuzz replay .roc-fuzz/first-run/original-input.bin
Then ask roc-fuzz for a smaller reproducing input:
./stack-fuzz minimize \
.roc-fuzz/first-run/original-input.bin .roc-fuzz/minimized-crash
./stack-fuzz show .roc-fuzz/minimized-crash
./stack-fuzz replay .roc-fuzz/minimized-crash
Minimization is most useful for structured or long inputs, but using the same workflow here establishes the habit.
2.4. Fix and preserve the failure§
The two stack operations disagree about which end is the top. Fix push in
Stack.roc:
push : List(a), a -> List(a)
push = |items, item| List.prepend(items, item)
Rebuild the executable and replay the minimized input. It should now complete without a failed property:
roc build --fuzz fuzz/stack/main.roc --output=stack-fuzz
./stack-fuzz replay .roc-fuzz/minimized-crash
./stack-fuzz run
Retain the exact witness and add its printed Fuzz.saved declaration to the
target’s examples list:
./stack-fuzz retain .roc-fuzz/minimized-crash --name previous-crash --output=fuzz/regressions
After adding the printed declaration, rebuild so the executable contains the new example, then check it:
roc build --fuzz fuzz/stack/main.roc --output=stack-fuzz
./stack-fuzz check
You can also append a normal unit test using the minimized non-empty stack to
Stack.roc:
expect {
initial : List(U8)
initial = [1]
match Stack.pop(Stack.push(initial, 0)) {
Ok({ value, rest }) => value == 0 and rest == initial
Err(Empty) => Bool.False
}
}
Run it with the rest of the module’s tests:
roc test fuzz/stack/Stack.roc
Use the actual value printed by show if minimization found a different
one-element list. The regression test protects this known case on every test
run; the fuzz target continues exploring other values and future implementation
changes.
A bounded run that finds no failure is still a successful run. It means the property held for the cases explored during that run, not that the operation is proved correct.
2.5. Understand a normal run§
By default, run checks every declared example once in a fresh process, then
explores for 60 seconds. It keeps useful inputs under .roc-fuzz/corpus and
saves failures in the run’s report directory under .roc-fuzz/reports/. The corpus is a set
of inputs that reached behavior worth revisiting; later runs reuse it and
continue searching from those discoveries.
During a clean run, NEW means the engine retained an input that reached new
behavior and DONE means the configured bound was reached. The
campaign status glossary explains the remaining
fields and tuning options.
2.6. Design the next target§
Choose one fast application operation and one rule that should hold for every
input, and give it its own target.
Design effective targets
lists the common shapes of such a rule and shows how to generate records,
declare examples and share one executable between properties.
Check what passing does not show
adds goals, trace rules and allocation checks to a target, and
Run and maintain fuzzing campaigns
explains corpora, tuning and unstable failures. A component that breaks in
sequences of calls is better described as a
model, and arithmetic on
fixed-width integers can be
proved. Run TARGET --help for the command
summary and browse the generated API reference for
generator, combinator, and target signatures.
2.7. Repository and release examples§
The repository’s examples/ applications use relative paths to the local platform;
prepare its native inputs before building them. Published releases provide a
roc-fuzz-examples-VERSION.zip download containing complete runnable applications
with that release’s content-addressed platform URL. Neither the platform nor
an archived example pins a compiler: a daily compatibility check runs the latest
release’s archived examples, unchanged, on the newest Roc nightly.
3. Design effective targets§
The first tutorial generated a list of U8 values. Application behavior also accepts
records, lists, strings, or domain types. Build a generator that produces values
close to the operation’s useful input domain, then keep the property focused on
one behavior.
3.1. Start from the operation§
Choose a function that is fast, deterministic, and easy to call in memory. Write the property in one sentence before choosing a generator. If the sentence needs several unrelated “and” clauses, make separate targets. Common property shapes include:
Round trip: decoding an encoded value returns the original value.
Inverse: an operation followed by its inverse returns the starting value.
Idempotence: normalizing twice gives the same result as normalizing once.
Invariant: an operation preserves ordering, length, membership, or another rule of the data structure.
Differential: two independent implementations produce the same result.
Robustness: arbitrary input may return success or an ordinary error, but must not crash or hang.
A practical first set might include one target per parser, encoder/decoder pair or important business invariant. There is no need to fuzz every function. A component whose bugs appear only in sequences of calls is better described as a state machine.
A generator explores only the cases the property can observe. Calling an operation without checking its result finds crashes and resource failures, but cannot find an ordinary wrong answer.
3.2. Share an executable across properties§
Keep properties independent while compiling their shared library code once.
Pass existing target values to Fuzz.suite instead of combining their assertions
or adding a selector byte to their input:
target = Fuzz.suite([json_roundtrip, json_limits, xml_events])
Members may use different input types and generators. Names must be nonempty and unique across the suite; nested suites flatten into the same inventory. Build one executable and select a property at runtime:
roc build --fuzz formats.roc --output=formats
./formats --list-targets
./formats --target=json-roundtrip check
./formats --target=xml-events explore corpus/xml-events --time=60
roc build uses LLVM by default, as required for coverage instrumentation.
Omit --fuzz for an ordinary build with the same compiler settings. Keep the
compiler version and build mode consistent when comparing allocation measurements.
Dev builds (--opt=dev, without --fuzz) also support ordinary checks, replay
and measurements. Existing single-target applications retain their commands and
need no selector.
The runnable examples/multipleTargets/main.roc groups collection and text
properties from separate modules. examples/numberFormats.roc groups signed
and unsigned decimal round trips. Both applications are exercised by the target
inventory, including checks, replay, measurements and exploration.
Each selected property retains its own declared examples, corpus encoding, allocation baseline and report identity. Selection follows supervised workers, replay, minimization and raw libFuzzer worker processes. Keep separate corpus directories for properties whose inputs have different meanings.
3.3. Generate useful values§
roc-fuzz provides generators for numeric values, strings, bytes, and collections. Use a bounded generator when the full type includes values that are irrelevant or too expensive for this target:
port = Fuzz.u8_in(1, 255)
name = Fuzz.str
payload = Fuzz.list(Fuzz.u8, 1024)
Fuzz.list(item_generator, maximum_length) generates a list whose elements come
from item_generator. The maximum is a test-design bound, so choose a size that
reaches meaningful behavior without making each case slow.
Use Fuzz.map when the domain value can be constructed from one generated value,
and Fuzz.map2 when it needs two:
non_empty_bytes = Fuzz.map(
Fuzz.list(Fuzz.u8, 255),
|rest| List.prepend(rest, 1),
)
range = Fuzz.map2(
Fuzz.u8,
Fuzz.u8,
|a, b| if a <= b { start: a, end: b } else { start: b, end: a },
)
Constructing valid values directly gives the search more useful executions. Generation controls bias; property preconditions or validated input types define validity. Encoded examples and their mutations bypass the generator and must pass the same validity checks.
3.4. Build record inputs§
Roc’s record-builder syntax can combine a generator for each field:
Input := { delimiter : Str, value : Str }.{
parser_for : _
encoder_for : _
}
input_generator : Fuzz.Generator(Input)
input_generator = {
delimiter: Fuzz.str,
value: Fuzz.str,
}.Fuzz
Use the resulting generator with Fuzz.target_with:
target = Fuzz.target_with({
examples: [],
name: "split-round-trip",
generator: input_generator,
test,
show: |input| Str.inspect(input),
})
This explicit form is a good default for a generator used by one target. When a
named input type owns a reusable generation policy, define its generator_for
method and use Fuzz.target:
Input := { delimiter : Str, value : Str }.{
parser_for : _
encoder_for : _
generator_for = |_| {
{
delimiter: Fuzz.str,
value: Fuzz.str,
}.Fuzz
}
}
target = Fuzz.target({
examples: [],
name: "split-round-trip",
test,
show: |input| Str.inspect(input),
})
Both forms produce the same kind of typed target. The
advanced explanation describes
how Roc resolves generator_for; using the pattern does not require knowing its
implementation.
3.5. Declare examples and regressions§
examples: [
Fuzz.example({ name: "empty", revision: "1", make: || Input.{ delimiter: ",", value: "" } }),
Fuzz.saved({ name: "previous-crash", revision: "1", bytes: regression_bytes }),
]
A typed example is encoded into real corpus seed bytes; it does not need an inverse generator. Saved declarations keep original artifacts. Every example runs independently of corpus retention, exactly once in a fresh process during checking or acceptance. Increment revisions when an example’s meaning changes. The baseline also checks the actual input digest, even if the revision is unchanged.
3.6. Handle invalid input deliberately§
An ordinary invalid input is not automatically a fuzzing failure. A parser may
return Err for malformed text and still satisfy a robustness property. Return
Fuzz.keep when the observed result is allowed.
Prefer a generator that creates valid domain values. Return Fuzz.reject when a
precondition is awkward to encode and the generated case is outside the property
you are testing. Do not use crash or expect to reject such a case; those mean
roc-fuzz found a failure worth saving.
Watch the report’s attempted, accepted and rejected counts. If most inputs are rejected, redesign the generator so the campaign spends more time in the code that matters.
3.7. Keep saved inputs meaningful§
A saved entropy witness uses the target’s generator; changing that generator can make it produce a different typed value. Encoded witnesses use the format parser instead, so their meaning depends on the parser and input type. Keep the relevant definitions stable when a corpus or failure matters, and retain the original bytes and matching executable for exact historical reproduction.
The generated API reference lists all generators and combinators. When the target produces useful values and passes a short smoke run, declare what its campaigns must reach and tune longer runs.
4. Check what passing does not show§
A property sees the value an operation returns. A campaign that passes shows that no input it ran broke the property; it does not show which cases those inputs reached, or how the code arrived at its answers. A target can check three more things:
Goals name events that some input in a campaign must reach. They are judged once, over the whole campaign, and a campaign that misses one is
inconclusiverather than passed.Trace rules constrain the order and number of named events within one input, such as "decode before check, and check exactly once".
Allocation measurements report allocator statistics for named regions of the property. Assert on them in the property, and fix each declared example’s observations with an accepted baseline that CI compares exactly.
Marking an event, registering trace rules and measuring are effects, so a
target that uses them has an effectful test! and is built with
Fuzz.target_with!. A target made from a
Model declares and marks its machine’s goals itself;
Read goals in the campaign report
shows what that adds.
4.1. Declare campaign goals§
A goal is a named event that some kept input must reach, among the declared examples, the saved corpus and exploration. A trace rule is judged on every input; a goal is judged once, over a campaign.
target = Fuzz.target_with!({
name: "parse",
examples: [],
generator: Fuzz.bytes,
test!: |input| {
match parse(input) {
Ok(_) => Fuzz.mark!("parsed a document")
Err(_) => Fuzz.mark!("refused a document")
}
Fuzz.keep
},
show: Str.inspect,
}).with_goals(["parsed a document", "refused a document"])
with_goals puts the inventory on the target, so the runner knows every goal
before any input runs and can name the ones no input reached.
An input reaches a goal when an event of that name occurs anywhere in its
property: a Fuzz.mark!, or the completion of a Fuzz.measure! region. The
event is an ordinary one, so
trace rules apply to it in its region. Only a
kept input counts: an input that marks a goal and then returns Fuzz.reject,
or that fails, reaches nothing.
Names are unique, nonempty and at most 128 bytes, the limit of an event name,
and a target declares at most 1024. A command run on a target whose inventory
breaks these rules stops before any input with exit status 2, and the
message names the goal at fault. In a suite, each member declares its own goals
before Fuzz.suite combines them; calling with_goals on the combined suite
crashes.
Goals grade a campaign; they do not steer it. During exploration the first
input to reach a goal counts as new coverage, so the corpus keeps a witness for
every goal reached and reduce-corpus preserves one. Nothing directs
exploration toward a goal no input has reached. A target without goals has
exactly the coverage it would have otherwise.
4.2. Grade a campaign with goals§
Each command grades the inputs it runs:
checkgrades the declared examples;exploregrades the corpus it starts from, which includes copies of the examples, and the inputs the search makes; andrungrades the examples, then exploration.
./fuzz-target run .roc-fuzz/corpus --report-dir=.roc-fuzz/evidence --time=60
The console line ends with reached 2 of 3 goals and names up to eight goals
never reached. The report’s goals object holds the tally: status
(reached, unreached, or none_declared), required, the counts, the names
in unreached, and an inventory entry per goal, in declaration order. An entry
gives inputs, the number of kept executions that reached the goal, and
first, its witness: the first input that reached it. A witness’s source is
example, corpus for an input exploration started from, or exploration
for one the search made, with attempt counting exploration’s executions from
one. summary.md lists the goals never reached and then a table of the reached
ones with their witnesses.
A campaign that breaks no rule and leaves a goal unreached is inconclusive,
with exit status 1. It lacks evidence the target asked for, as an exploration
that keeps no input does. Reaching a goal is never a finding, and neither is
missing one. A campaign with poor inputs can pass every property and rule while
reaching few goals; fix it by changing the generator or by declaring an example
that reaches the missing goal.
Pass --allow-unreached-goals where partial evidence is expected, such as a
check whose goals are left to exploration: the outcome then ignores goals,
and the report still lists them, with required false. accept reports goals
and its result does not depend on them.
4.2.1. Keep a goal’s witness§
Exploration saves the first input it ran that reached each goal as
goals/goal-N.bin in the report directory, where N is the goal’s position in
the inventory, counted from zero. Make that input an example, so that every
check reaches the goal without exploring:
./fuzz-target replay .roc-fuzz/evidence/goals/goal-2.bin
./fuzz-target retain .roc-fuzz/evidence/goals/goal-2.bin --name reaches-fork --output=fuzz/regressions
replay runs the one input and names the goals it reached; its report’s
goals has status not_graded, because one input is not a campaign. retain
copies the bytes to fuzz/regressions/reaches-fork.bin and prints a
Fuzz.saved declaration. Add that declaration to the target’s examples and
rebuild: the witness is now a declared example, and check reaches that goal
on every run.
4.3. Measure allocations and validate traces§
Every property callback has an automatic $property region. Decoding and
entropy generation finish before that region starts. Named regions use one
native engine:
Fuzz.measure! : Str, (() => a) => { value : a, stats : Fuzz.Stats }
Fuzz.start_measure! : Str => Fuzz.Measurement
Fuzz.Measurement.finish! : Fuzz.Measurement => Fuzz.Stats
Use test! with Fuzz.target_with! when adding measurements or trace marks to
a target that previously used a pure test. This complete target checks a
prepend operation and its allocation behavior:
app [target] { fuzz: platform "PLATFORM_URL" }
import fuzz.Fuzz
test! : List(U8) => Fuzz.Outcome
test! = |input| {
if input.len() > 32 { return Fuzz.reject }
Fuzz.trace_rules!([Before("prepend", "checked"), Count("checked", 1)])
measured = Fuzz.measure!("prepend", || List.prepend(input, 0))
if measured.value.first() != Ok(0) or measured.value.drop_first(1) != input {
crash "prepend changed the input or inserted the wrong item"
}
if measured.stats.reallocs != 0 { crash "prepend unexpectedly reallocated" }
Fuzz.mark!("checked")
Fuzz.keep
}
target = Fuzz.target_with!({
name: "prepend-quality",
examples: [
Fuzz.example({ name: "empty", revision: "1", make: || [] }),
Fuzz.example({ name: "several", revision: "1", make: || [1.U8, 2, 3] }),
],
generator: Fuzz.list(Fuzz.u8, 32),
test!,
show: Str.inspect,
})
Replace PLATFORM_URL with the release’s platform URL. The property enforces its
size bound for encoded mutations as well as generated values. Inside an
effectful test!, a manual window uses the same engine:
window = Fuzz.start_measure!("manual")
value = List.prepend(input, 0)
stats = window.finish!()
if value.first() != Ok(0) or value.drop_first(1) != input {
crash "prepend changed the input or inserted the wrong item"
}
if stats.reallocs != 0 { crash "prepend unexpectedly reallocated" }
Finish manual windows exactly once, in nesting order. Invalid handles, abandoned windows, instrumentation limits and arithmetic overflow fail explicitly. The returned value is still alive at the measurement boundary. Nested windows are inclusive: a parent contains its children’s allocator operations.
The platform transfers measured results through an opaque ownership container
before finishing the region. This keeps every returned field alive even when
the caller reads only stats or discards the result. The private container is
measurement bookkeeping and is excluded from allocator statistics and explicit
counters in every enclosing region. Ordinary application Box.box allocations
remain counted. The invocation-wide leak check includes both kinds of storage.
What the application’s target expression allocates is bookkeeping in the same
way. The runner
evaluates it once in a process,
so it is in no region’s statistics and no counter, and each input’s leak check
starts with it already live.
4.3.1. Understand the statistics§
allocs,reallocs,deallocsSeparate Roc allocator hook counts. A realloc counts once as a realloc; its internal allocation and release are not counted again.
allocs + reallocsgives the number of allocation requests.requested_bytesSum of each allocation’s requested length and each realloc’s full new length. This includes Roc’s own allocation headers and excludes the host’s bookkeeping header. It measures traffic, rather than RSS or copied bytes.
entry_live_allocs,entry_live_bytesRoc allocations already live at entry, including input storage. Allocations made before a window contribute its entry and peak memory, rather than its allocation count.
exit_live_allocs,exit_live_bytesMemory alive when the window finishes. This can include a returned value and is not itself a leak.
peak_live_bytesActual maximum live requested bytes during the window, including entry-live memory and simultaneous old/new blocks during realloc.
The broader invocation leak check runs after the complete target adapter returns.
It includes input preparation and teardown, which the property region excludes.
--no-detect-leaks disables that check. Metrics remain separate from trace rules
and from diagnostic capture completeness.
Ordinary Roc assertions can inspect any statistic. The allocation assertion
helpers expect_allocs_at_most! and expect_allocs_at_least! take zero-argument
callbacks (|| operation(input)) and count allocations plus reallocations.
Low-level process counters remain available for tightly focused assertions;
assert on differences, never their absolute process-wide totals.
4.3.2. Declare logical trace rules§
Fuzz.trace_rules!([
Before("decode", "checked"),
Count("checked", 1),
Forbidden("fallback"),
])
measured = Fuzz.measure!("decode", || decode(input))
check_result(measured.value)
Fuzz.mark!("checked")
Register rules before the region’s first event. Events are direct marks and
completed immediate-child regions. Before(a, b) requires both events and every
a before every b; Count(event, n) requires exactly n; Forbidden(event)
requires none. A grandchild completion is an event of its immediate parent.
Rules are evaluated online even after diagnostic capture fills. Detailed replay exports ordered events, explicit gaps and unfinished regions. Parent identifiers and occurrence numbers distinguish repeated names. Neither traces nor assertions contain timestamps. Capture truncation does not turn an invalid trace into a passing one and does not invalidate completed allocation statistics.
4.4. Accept an exact allocation baseline§
Allocation observations are deterministic, so each declared example’s
observations can be accepted once and compared exactly on every later check.
TARGET check runs each declared example once in a fresh process.
TARGET accept runs the same complete inventory once and atomically accepts
valid observations. No warm-up or statistical repetition is needed.
The default file is <declared-target-name>_baseline.json in the working
directory: a target named my_target uses my_target_baseline.json. Override it
with --baseline=PATH. Entries are separate by host target and --profile=NAME.
An absent entry reports unbaselined and permits normal execution.
Every example name, revision, exact input SHA-256, region inventory, metric version and statistic must match. Reductions and increases both need explicit acceptance. Failed or rejected examples, assertions, crashes, timeouts, incomplete observations and failed baseline writes preserve the existing accepted file. Check and acceptance never repeat examples to produce a more convenient result.
4.4.1. Review and accept allocation observations§
./fuzz-target check
./fuzz-target accept --profile=default
./fuzz-target check
Commit the accepted file after reviewing it. CI runs check or run and never
accepts changes automatically; TARGET measure INPUT prints one input’s named
observations as JSON for review.
5. Model a component and check it§
A fuzz target usually checks one call. A cache, an index or a protocol breaks
in a sequence of calls, and the sequence that breaks it is rarely the one its
tests make. The Model module describes such a component once, as a state
machine with rules, and checks it two ways: a search of every sequence in a
small world under roc test, and a fuzz target over a large one.
Two runnable examples go with this chapter. examples/queueModel.roc is a
first model in under 60 lines. examples/indexModel/ models a radix tree
taken unedited from another project, and the numbers below come from it.
Each is an application, so roc test runs its search and
roc build --fuzz builds its fuzz target:
roc test examples/queueModel.roc
roc build --fuzz examples/indexModel/main.roc --output=index
./index run corpus --time=60
5.1. Describe the machine§
A Model.Machine(state, action) has four fields: where it starts (init),
what can happen in a state (actions), what happening does (step), and
what must be true (rules). Put the real component in the state beside a
reference that is too plain to get wrong, and apply every action to both:
World : { queue : Queue, items : List(U8) }
machine : Model.Machine(World, [Push(U8), Pop])
machine = {
init: { queue: { front: [], back: [] }, items: [] },
actions: |world| if (world.items.len() < 3) [Push(1), Push(2), Pop] else [Pop],
step: |world, action| match action {
Push(item) => { queue: push(world.queue, item), items: world.items.append(item) }
Pop => { queue: pop(world.queue).1, items: world.items.drop_first(1) }
},
rules: [
Model.always_step("a pop returns the oldest item", |{ before, action, after: _ }| action != Pop or pop(before.queue).0 == before.items.first().map_err(|_| Empty)),
Model.always("the queue holds its items in order", |world| world.queue.front.concat(turned(world.queue.back)) == world.items),
Model.sometimes("the queue holds three items", |world| world.items.len() == 3),
Model.sometimes_step("a pop turns the back list round", |{ before, action, after: _ }| action == Pop and before.queue.front.is_empty() and !before.queue.back.is_empty()),
Model.sometimes_step("a pop finds the queue empty", |{ before, action, after: _ }| action == Pop and before.items.is_empty()),
],
}
An always rule must hold in every state, and an always_step rule on every
step; a step rule is handed the state before, the action and the state after,
so the state needs no field to remember what just happened. A sometimes or
sometimes_step rule is a goal: some state or step must satisfy it. Goals
guard against a model that passes because it never reaches the interesting
cases. An at_rest rule says where the machine may stop, and a state where
nothing can happen, or nothing changes, breaks it as a deadlock.
actions lists only what is possible in a state, and it decides the size of
the world a search covers. Here it is at most three items of two kinds, which
is enough to make pop turn the back list round.
5.2. Search it under roc test§
Model.check visits every state within depth actions of init, nearest
first, and checks every rule on the way. It is a pure function, so it runs in
an ordinary expect:
expect Model.check(machine, { depth: 20 }) == { verdict: Holds(Exhausted), states: 41, depth: 5 }
The verdict says what was shown:
Holds(Exhausted): the search ran out of new states, so no sequence of any length breaks a rule in this world.Holds(Bounded): the depth limit stopped it, and nothing is known beyond.Violated({ rule, trace }): a rule failed, andtraceis a shortest sequence of actions that breaks one.Deadlock({ rule, trace }):traceleads to a resting state that anat_restrule forbids.Unreached({ rule, extent }): no rule failed, and this goal was never reached; withExhaustedit never can be.
Change pop so that it forgets to turn the back list round, and the same
expect fails with
Violated({ rule: "the queue holds its items in order", trace: [Push(1), Push(2), Pop] }).
Paste that trace into Model.replay(machine, trace) to keep it as a
regression.
Model.explore is the same search with the whole report: a shortest witness
for every goal (Model.witness), every rule broken at the failure with
blame: EveryRule, and Model.explain to put it in words. A search
remembers the states it has met and drops a state equal to one already seen.
A state with no hash, such as ReadyIndex, is remembered by a key, and
verify: EveryStep then checks the rules on every state a step makes, so two
different states with one key cannot hide a broken one:
search = |subject| Model.explore(subject, { depth: 100, key: |world| world.reference, verify: EveryStep, blame: EveryRule })
Over six keys chosen to part at bits 0, 1, 62 and 63, the index search visits 729 states and reaches 11 of 11 goals.
5.2.1. Grade a test you already have§
Model.apply takes a path of actions as given, without asking actions
whether each is possible, and reports the goals it never reached. Give it the
schedule of an existing test to see what that test exercises. The radix tree’s
own 96-turn test breaks no rule and reaches 10 of the 11 goals: it never
removes a missing key from a populated index. The search reaches that goal in
two actions, [Insert(0, 10), Remove(1)]. SeededIndex.roc changes one
line of the arm that handles that case; the module’s own tests still pass on
it, and the search fails with that two-action trace.
5.3. Turn the model into a fuzz target§
A search covers only the world actions lists. A fuzz target runs the same
machine, with the same rules and goals, on paths made from the fuzzer’s bytes:
Model.walk_targetEach byte chooses among the possible actions, so every input is a valid path. The world is still the one
actionslists, and the paths can be far longer than a search reaches.Model.path_targetA
decodefunction turns the bytes into actions, which are applied as given. The actions can come from a space far too wide to list, such as full 64-bit keys. Makedecodetotal, so no input is rejected, and make a prefix of the bytes decode to a prefix of the path, so the minimizer shortens the trace.
target = Model.path_target({
name: "index",
machine,
decode: IndexPaths.shaped,
examples: [Fuzz.example({ name: "a tour of every goal", revision: "1", make: || IndexPaths.tour })],
})
A broken rule is a crash, so the runner saves, replays and minimizes it like
any other finding. Built from SeededIndex, that target fails within the
first thousand inputs:
[roc crashed] Violated({ rule: "the length is the number of live keys" }) after [Insert(274877906944, 0), Remove(1)]
Full-width keys reach what the search cannot. Of 26 bugs seeded one at a
time in the index, one breaks forks at bit 32; the six-key search passes it,
because no two of the six keys part at bit 32, and every campaign with shaped
keys found it. How the bytes become keys matters: IndexPaths.shaped makes
each new key one bit away from an earlier key, so a fork at any bit is a few
bytes away.
examples are inputs checked on every run and added to the corpus.
Model.walk_example makes one for a walk target from a trace, such as a
witness from the search. The Fuzz.saved declaration that retain prints
goes into the examples of any of the three targets as it is.
5.4. Read goals in the campaign report§
Each Model target declares the machine’s sometimes and sometimes_step
rules to the runner as
campaign goals and marks the ones an
input reaches, so the report lists every goal with the first input that reached
it and grades the campaign by them. A
campaign over a large world can break no rule and still leave goals unreached,
and it is then inconclusive. Decode the index’s keys with
IndexPaths.uniform, spread at random over all 64 bits, and campaigns of 60
seconds pass every rule while reaching 28 to 31 of the 73 goals. None tests a
fork at bit 39 or below:
index: inconclusive; baseline unbaselined; examples 0; exploration passed (attempted 191515, accepted 191056, rejected 459); goals 29 of 73 reached
Never reached: an insert forks at bit 0
By its rules alone that campaign looks as good as one that reaches every goal. Fix such a campaign by changing how inputs become actions, or by declaring an example that reaches the goal.
5.5. Check one step from any state§
Model.step_from starts at any state, reachable or not, takes each possible
action once and checks the rules. If the rules hold in init and no state
that satisfies them can break them in one step, they hold in every reachable
state, however far away. Model.step_target runs it as a fuzz target on
states from a generator, here for a counter that must stay at or below three:
target = Model.step_target({
name: "counter steps",
machine: counter,
generator: Fuzz.u64_in(0, 3),
examples: [Fuzz.example({ name: "at the top", revision: "1", make: || 3 })],
})
It is worth its cost when a bug lies further from init than any walk goes,
such as one step before a sequence number wraps. The cost is twofold. The
always rules must be strong enough that no unreachable state satisfies
them; until they are, a Broken or Stuck answer may be a state the
component can never be in, and each one means adding the rule that excludes
it. And the generator must make states that satisfy the rules often: the
target rejects any state that already breaks one, and the report’s rejected
count says how often that happened.
5.6. Know the limits§
A search covers only the small world you list. Over six keys it says nothing about a seventh, or about a fork at a bit where those six never part.
A search holds every state it has met in memory, and a state equal to one already met is not checked again. Keep the world small, and keep
==and any search key faithful to everythingstepand the rules read.Goals grade a campaign; they do not steer it. Nothing directs exploration toward a goal no input has reached.
Roc code cannot catch a crash. A crash inside the code under test ends a search, and
roc testreports the failedexpectwith the crash message and no trace. Under a fuzzer, the runner saves the input; a path target’sshowprints that input’s path without running it, and the last action of the minimized input is the one that crashed. A walk target’sshowhas to take the walk, so it crashes too.
6. Prove facts about integer arithmetic§
A fuzz target tries many inputs. The Solve module answers for every input at
once: state a claim about some fixed-width integers, and it either proves the
claim for every value they can take or returns values where it fails. It is at
its best on the questions fuzzing rarely settles: does this sum overflow for
some pair of U64s, does this bounds check let a table past the end, is this
bit trick the same as its definition.
A claim covers only what it says, in fixed-width integers. Use Solve for the
arithmetic at the heart of a check, such as a guard or a calculation, and fuzz
the code around it. Use both on the same definition when you can: the proof
covers every value of the term, and a fuzz target that compares the term with
the compiled code checks that the term means what the code does.
Solve is part of the platform, so an application that imports fuzz.Solve
needs nothing else, and an application that does not pays nothing for it.
6.1. State unknowns and a claim§
The midpoint of a binary search is the classic. Put the proof in an expect
and run roc test:
import fuzz.Solve
naive = |lo, hi| (lo + hi) // 2
expect Solve.prove(
{ lo: Solve.u32, hi: Solve.u32 }.Solve,
|v| {
mid = naive(v.lo, v.hi)
v.lo.lte(v.hi).implies(Solve.all([v.lo.lte(mid), mid.lte(v.hi)]))
},
) == Ok(Crashes({ lo: 1, hi: 4_294_967_295 }))
{ lo: Solve.u32, hi: Solve.u32 }.Solve declares two unknowns. Inside the
claim each is a Solve.Uint, a term that stands for a number not yet chosen.
The claim is a Solve.Claim built from those terms:
``,
-,*,//,%and number literals work on terms as they do onU32.Comparisons are methods,
eq,neq,lt,lte,gtandgte, because Roc’s<must return aBool.Solve.all,Solve.any,impliesandSolve.if_elsestand in forand,orandif, and stop early in the same way.
naive has no type annotation, so the same definition runs on U32s and
builds a term on Solve.Uints. Write the code under test that way and the
function you prove is the function you ship. The answer above covers every pair
of U32s and names one where lo + hi overflows. Change the body to
lo + (hi - lo) // 2 and the same claim is Proved.
The runnable version, with the careful midpoint proved and fuzzed, is
examples/midpoint.roc.
Other unknowns: Solve.u8 to Solve.u64, Solve.uint(width) for any width
from 1 to 64, ranges such as Solve.u64_in(0, 999_999), Solve.bool for a
truth value, and Solve.several(Solve.u8, 8) for a fixed number of them as a
list. A narrow range in a wide type is cheap: Solve.u64_in(0, 999_999)
computes like a U64 but gives the solver only 20 bits to choose.
6.2. Read the answer§
| Answer | Meaning |
|---|---|
Ok(Proved) | The claim is true and evaluates without crashing for every value of the unknowns. |
Ok(Refuted(v)) | v makes the claim false. |
Ok(Crashes(v)) | Evaluating the claim on v overflows or divides by zero, where Roc would crash. |
Err(GaveUp(effort)) | The search spent its budget first. Nothing is known about the claim. |
Err(WidthMismatch(..)) and others | The claim is ill-formed whatever the values: for example an 8-bit term compared with a 16-bit one. |
The record inside Refuted and Crashes is the record of unknowns with numbers
filled in. Compare it with a literal record, as above, or take a number out with
v.lo.value(). Every set of values is run through a plain evaluator of terms
before it is returned, so Refuted and Crashes never depend on the solver
being right. Proved does: it says the solver searched everything and found
nothing. roc-fuzz checks the solver against brute-force enumeration at small
widths in its own tests.
Solve.check(vars, claim, values) runs a claim on ordinary values without the
solver, and term.eval() runs a term with no unknowns left in it. Use them to
test a term against the Roc code it describes; the fuzz target in
examples/midpoint.roc does exactly that on every input.
6.3. Overflow crashes, as in Roc§
A term means what the same expression means in Roc. ``, - and * crash when
the result does not fit the width, and // and % crash on a zero divisor, so
a Proved claim is also proof that nothing in it overflowed. When overflow is
what the code intends, or what you want to ask about, use the other forms:
| Form | Meaning |
|---|---|
a.plus_wrap(b), minus_wrap, times_wrap | Wrap around, as U32.plus_wrap does. Never crash. |
a.plus_overflows(b), minus_overflows, times_overflows | A claim: would the plain form crash? |
a.to_width(33) | The same number in more bits, to compute with a bit to spare. Crashes when narrowing a number that does not fit; to_width_wrap keeps the low bits. |
lt_signed, plus_signed, to_width_signed and the other _signed forms | Read the bits as a two’s complement integer, as I8 to I64 do, and crash where those crash. |
A guard written first protects what follows, because implies, Solve.all and
Solve.if_else evaluate left to right and stop early.
v.y.neq(0).implies((v.x // v.y).lte(v.x)) never divides by zero. Leave the
guard out and the answer is Crashes({ x: 0, y: 0 }), not a wrong verdict.
Signed questions read the same bits differently. The textbook absolute value
crashes on one I32:
absolute = |x| Solve.if_else(x.lt_signed(0), Solve.num(0).minus_signed(x), x)
expect Solve.prove(Solve.map(Solve.u32, |x| { x: x }), |v| absolute(v.x).gte_signed(0))
== Ok(Crashes({ x: 2_147_483_648 }))
The answer is a bit pattern: v.x.value_signed() reads 2,147,483,648 as
I32.lowest, whose negation does not fit.
6.4. Give a question a budget§
The solver counts its work in conflicts: dead ends it meets and learns from. The count depends only on the question, never on the machine or the build, so a budget is not a timeout: a question that fits a budget once fits it every time, and a larger budget never changes an answer that was given.
find,find_near,proveandenumeratestop atSolve.default_budget, a million conflicts, and returnErr(GaveUp(effort)). An optimised build spends a million conflicts in about a minute.find_within,find_near_within,prove_withinandenumerate_withintake the budget as an argument and answerGaveUp(effort)as an ordinary result.Solve.effort(vars, claim, Prove)reports what a question costs, for choosing a budget.
Multiplication of two unknowns is what makes a question hard, and it gets
several times harder with each bit. Proving a * b == b * a with wrapping
products takes about a thousand conflicts at 5 bits and 913,801 at 10 bits,
about forty seconds of an optimised build. At 8 bits it takes about a second
optimised; at 16 bits it gives up at the default budget. Comparisons, sums,
differences, bitwise operations and division by a constant power of two stay
cheap at 64 bits.
roc test uses the default backend, which runs the solver thirty to a hundred
and fifty times slower than roc test --opt=speed. A claim that needs a few
thousand conflicts is comfortable there. For anything larger use --opt=speed,
or give the test a small budget of its own and expect GaveUp.
6.5. Find values and steer them§
Solve.find(vars, claim) returns Ok(Found(v)) with values that make the claim
hold, or Ok(None) when there are none. Solve.enumerate(vars, claim, limit)
lists up to limit different ones.
Solve.find_near(vars, claim, proposed) takes one proposed number per unknown,
in declaration order, and returns the solution nearest them by a fixed rule:
earlier unknowns win, and within a number the higher bits win. A proposal that
already satisfies the claim comes back unchanged, and proposing zeros gives the
smallest solution. The API reference for find_near states the rule in full.
Steering turns a claim into a generator: a fuzzer’s bytes propose and the
solver repairs what does not fit. Build the claim once with Solve.prepare_with
and ask it many times with Solve.ask. Extra claims given to prepare_with cost
nothing until a query assumes them by position. Hold the prepared claim in a
top-level constant, which the compiler works out once; a claim prepared inside
the test is prepared again for every input.
examples/slidingWindow.roc generates the states of a sliding-window link,
three counters that must stay in order with at most eight messages in flight,
and asks for states whose window crosses the wrap of the 16-bit wire numbers.
Almost no random triple of numbers is such a state.
As an input generator Solve complements a hand-written generator; it does not
replace one. Each input costs a solver query. examples/slidingWindow.roc,
three counters and one optional extra claim, runs about 200 inputs a second on
an Apple Silicon Mac. A larger state, a whole link with its frames and
acknowledgements, ran about 15 to 23 inputs a second built by the solver, where
a hand-written generator for the same states ran about 138,000. Reach for it to
build states that satisfy rules you have already written as a claim, and that a
generator would need its own careful code to reach.
6.6. Limits§
Fixed widths only. Every number is 1 to 64 bits wide. There are no unbounded integers, no
U128orI128, no floats and noDec.No lists or strings.
Solve.severalgives a fixed number of unknowns as a list, but the length is not an unknown, and a claim cannot index a list by a term.No signed division or remainder.
//and%are unsigned.Multiplication is costly. Each product of two unknowns builds a multiplier; questions about products slow down several times per bit, as the numbers above show.
times_signedbuilds a multiplier of twice the width.The default backend is slow. Expect thirty to a hundred and fifty times the optimised time under a plain
roc test.A term is not the code. When the claim restates code by hand instead of calling one unannotated definition, nothing ties the two together. Test the term against the code with
Solve.check,evalor a fuzz target.Provedrests on the solver.Refuted,CrashesandFoundare checked by the evaluator;ProvedandNoneare not.Shared terms are told apart by a 64-bit fingerprint.
x.shared()keeps a term that is reused step after step from doubling, and two different shared terms with the same fingerprint would be taken for one. With a thousand shared terms the chance is about one in ten trillion.
The Solve API reference documents every function.
7. Run and maintain fuzzing campaigns§
After the first target works, use these guides to choose bounds, interpret
status output, retain useful inputs, investigate unstable failures, and prepare
longer searches. The same commands run every target, including those made from
a Model. The internals chapter covers the embedded engine
and its raw interface.
7.1. Tune a run§
Give every new target a short, bounded smoke run before a long campaign:
TARGET run \
--time=60 \
--max-input-size=4096 \
--timeout=5 \
--memory-limit=2048 \
--print-final-stats
The most useful limits are:
| Option | Meaning | Starting point |
|---|---|---|
--time=N | Stop after N seconds; 0 is unbounded. | Defaults to 60. |
--runs=N | Stop after N attempted inputs. | Useful for repeatable CI checks. |
--max-input-size=N | Limit corpus input bytes, including framing, for entropy and encoded values. | Start small and raise only when needed. |
--timeout=N | Treat one input taking longer than N seconds as a failure. | A few seconds for a normally fast target. |
--memory-limit=N | Stop when the process exceeds this many MB. | Set from the expected working set. |
--dictionary=FILE | Add important byte tokens to mutations. | Useful for text or binary formats. |
--seed=N | Select the engine’s random seed. | Useful for repeating a campaign with the same runner build and configuration. |
--print-final-stats | Print final execution and resource counters. | Useful in CI and smoke tests. |
--max-input-size bounds the binary input, not necessarily every typed list or
string it produces. Generators control search bias; encoded examples and their
mutations bypass them. Enforce domain and resource limits in property
preconditions or validated input types for both forms, and return Fuzz.reject
before an operation becomes too expensive. Generator bounds help the entropy
path reach those valid values efficiently.
Do not confuse the campaign seed with a saved input. Different engine
builds, coverage layouts, or configurations may generate different
mutation sequences from --seed. Reproduce a failure with its saved
artifact and replay, not with the campaign seed alone.
The captured run.log contains libFuzzer’s compact status fields:
NEW: an input reached behavior not represented by the corpus and was saved.REDUCE: a smaller input preserved previously found behavior.cov: covered edges or blocks.corp: number and total byte size of in-memory corpus entries.exec/s: target executions per second.rss: current process memory use.DONE: the run reached its time or iteration limit.
Coverage growth shows that the fuzzer is exploring. A plateau is a
reason to inspect the target, generator, seeds, and dictionary, not
proof that the code has no bugs. Very low exec/s, steadily growing
rss, or repeated timeouts usually calls for a narrower target or
tighter bounds.
7.2. Maintain a corpus§
A corpus is a collection of small binary inputs that collectively reach useful code. It is not a directory of every attempted input. Use a stable corpus directory across campaigns:
TARGET run quality/corpus/my-target --time=3600 --max-input-size=4096
Declare a few small Fuzz.example values that reach meaningfully different
behavior; they become encoded corpus seeds that the fuzzer can mutate. Use
Fuzz.saved for original entropy or encoded witnesses. Both forms reach the
same property, and their binary bytes need not resemble the value printed by
show. Check manually created seeds with the target executable.
Reduce a large corpus into a new, initially empty directory while preserving coverage:
TARGET reduce-corpus quality/corpus/my-target quality/corpus/my-target-small
For a target with goals, the reduced corpus still holds an input for every goal the original reached.
Keep valuable seeds and fixed crash inputs with the target in version
control. Use a deliberate directory such as fuzz/corpus/<target>/,
document why each seed matters, and replay it in tests. Generated
.roc-fuzz/ directories are ignored at every depth; keep evolving
campaign corpora in local storage or CI caches, and preserve findings as
CI artifacts until reduced to regressions. Run them after code changes
so the target does not silently stop compiling or exercising the
intended behavior.
Dictionaries are most effective when recognizable bytes flow fairly directly into a parser. They may help less when a structural generator heavily transforms the raw input.
Changing a generator can change the typed values produced by entropy witnesses.
Encoded witnesses use the format parser instead. Keep the relevant generator,
parser and input type stable when practical, and use show to check saved inputs
after a change. Preserve original bytes when storage shape matters.
7.3. Diagnose an unstable failure§
Always replay a saved failure in a fresh process. If it does not reproduce, investigate:
a generator or target change that altered the typed value or property;
a different or truncated raw input file;
an executable built from different target code; or
a compiler or runtime defect.
Treat the failure as actionable once its conditions are understood and, ideally, it reproduces from a clean process.
7.4. Know what counts as a failure§
Coverage feedback tells the engine which inputs explore new behavior; it does not tell the runner whether a result is correct. The property in the target is the correctness oracle.
roc-fuzz saves explicit Roc crash and failed expect calls, per-input
timeouts, and process memory-limit failures. A wrong answer that does
not break the target’s property is invisible to the fuzzer, which is why
choosing a strong property matters more than simply calling the function
under test.
7.5. Prepare a long campaign§
Before committing substantial CPU time, check that:
the target tests one named behavior with a meaningful property;
invalid input returns normally unless invalid input crashing is the bug;
the generator creates useful values without excessive rejection;
input sizes and allocations are bounded;
every generated input terminates or is caught by the timeout;
a one-minute run gains coverage without immediate hangs or memory growth;
a deliberate temporary
crashis saved, shown, replayed, and minimized as expected; andthe corpus and fixed failures have a clear place in the repository and CI.
7.6. Command reference§
| Command | Behavior |
|---|---|
TARGET or TARGET run [CORPUS] [OPTIONS] | Check examples and baseline, then explore, with one report. |
TARGET check [OPTIONS] | Run each declared example once in a fresh process and compare the baseline. |
TARGET accept [OPTIONS] | Explicitly accept the complete valid allocation observations. |
TARGET explore [CORPUS] [OPTIONS] | Run coverage-guided exploration independently. |
TARGET examples | List names, revisions and input digests. |
TARGET show INPUT | Display the decoded representative. |
TARGET replay INPUT [--detailed] | Reproduce one input under the supervisor. |
TARGET measure INPUT | Print one input’s named allocation observations as JSON. |
TARGET retain INPUT --name NAME --output DIR | Keep original bytes and print a source declaration. |
TARGET minimize INPUT OUTPUT [OPTIONS] | Minimize a reproducing finding within the campaign budget. |
TARGET reduce-corpus INPUT OUTPUT | Retain coverage-relevant inputs in OUTPUT. |
TARGET raw ... | Advanced libFuzzer controls. |
Friendly execution options include:
| Option | Meaning |
|---|---|
--time=N | Exploration budget in seconds; default 60, 0 unbounded. |
--runs=N | Exploration execution bound. |
--timeout=N | Invocation deadline in seconds; default 10. |
--max-input-size=N | Bound corpus input bytes, from 1 byte through 2 MiB. |
--memory-limit=N | Exploration process RSS limit in MiB. |
--dictionary=FILE | Mutation tokens. |
--seed=N | Exploration random seed; retain input bytes for reproduction. |
--report-dir=DIR | Absent or empty destination for the complete report. |
--baseline=PATH | Override <declared-target-name>_baseline.json. |
--profile=NAME | Select the named baseline profile. |
--detailed | Capture a detailed logical trace for replay. |
--no-detect-leaks | Disable the broader invocation leak check. |
--allow-unreached-goals | Report unreached goals without making the campaign inconclusive. |
Provenance options are --source-revision, --roc-version,
--platform-release and --platform-sha256, each supplied as --name=value.
See Read the evidence for the report these
options are recorded in, and
Accept an exact allocation baseline
for --baseline and --profile.
Minimization and corpus reduction accept --time, --runs, --timeout and
--report-dir. They default to a 60-second campaign budget and require a positive
--time; unbounded exploration remains available with run --time=0 or
explore --time=0. A successful minimization writes the best witness, including
the unchanged original if no reduction was found. Failed minimization preserves
an existing output. Corpus reduction requires an absent or empty output directory
that does not overlap the input directory.
8. Add fuzzing to CI§
Every target executable contains its supervisor, baseline reader and evidence writer. A consumer needs Roc and the compiled target.
roc build --fuzz fuzz/main.roc --output=fuzz-target
./fuzz-target run .roc-fuzz/corpus \
--report-dir=.roc-fuzz/evidence \
--time=60 --timeout=10 --max-input-size=4096 \
--source-revision="$SOURCE_REVISION" \
--roc-version="$ROC_VERSION" \
--platform-release="$ROC_FUZZ_RELEASE" \
--platform-sha256="$ROC_FUZZ_SHA256"
run checks the complete declared example inventory and exact accepted baseline
before exploring. A failed example or baseline change skips exploration and
records the reason in the same report. Each declared example executes once in a
fresh child process. Exploration reuses one instrumented child for efficiency.
The parent writes reports even when a child crashes or exceeds its deadline.
Example preparation also runs in a supervised child: a crashing or nonterminating
maker cannot terminate the supervisor or accept a partial inventory.
Defaults are 60 seconds of exploration, a 10-second per-input deadline and leak
checking. check runs examples and baseline checks without exploration;
explore runs the search independently. A missing
accepted baseline entry reports
unbaselined and allows normal execution. Exploration with zero accepted
executions is inconclusive and exits unsuccessfully, and so is a campaign that
leaves a declared goal unreached. Commit
accepted baselines after review; CI runs check or run and never accepts
changes automatically.
8.1. Read the evidence§
An explicit report directory must be absent or empty. Keep it separate from
inputs and the persistent corpus. Without an override, each invocation chooses
a fresh directory under .roc-fuzz/reports/.
The directory contains:
report.json, followingroc-fuzz-quality/2;summary.mdand the combined childrun.log;original example inputs, worker observations and original trace snapshots;
exploration failure artifacts and
original-input.binfor the last attempted input, with capture completeness and its SHA-256 in the report;goals/, the witness exploration found for each declared goal; andbounded original-run logical traces, including unfinished regions on failure.
The report records the metric version, effective execution controls (including leak checking), preparation status, structured finding kinds and each worker’s exact span within the combined log. Inputs are capped at 2 MiB in the friendly commands; the prepared-inventory JSON transport is capped at 32 MiB.
Use the report’s outcome, baseline status, metric validity, trace-rule result
and capture completeness independently. Missing diagnostic events do not make
allocation statistics invalid; online trace rules continue past capture limits.
A killed writer can leave an incomplete capture, which is explicitly identified.
When a worker returns no result, metric_valid, trace_rules_passed and
capture_complete are null (unknown). Fatal outcomes remain separate from
partial evidence in the original snapshot.
A detailed replay is separate evidence rather than a reconstruction of the
original run:
./fuzz-target replay finding.bin --detailed --report-dir=.roc-fuzz/replay
./fuzz-target measure finding.bin --report-dir=.roc-fuzz/measurement
./fuzz-target retain finding.bin --name previous-crash --output=fuzz/regressions
measure prints a JSON array of named allocation observations. retain keeps
the original bytes and prints a Fuzz.saved source declaration plus the decoded
representative. Keep the binary witness when storage shape matters.
Exit status 0 means success, 1 means a finding, baseline change or inconclusive
campaign, and 2 means an infrastructure/configuration failure. Native child
termination remains separate in the report.
8.2. Keep project policy in the project§
Enumerate your targets in ordinary Blueprint tasks or a CI matrix. Choose valid input domains in properties or validated types, and use generators for bias. Keep resource bounds appropriate for the operation. Acceptance remains a separate explicit task. The repository’s maintainer toolchain can use Nix while consumer tasks use only fetched compilers and self-contained target executables.
8.2.1. GitHub Actions pattern§
After checking out your project and installing Roc, build the target and run verification on each supported host in your CI matrix. Upload evidence even on failure:
- name: Verify quality
run: |
roc build --fuzz fuzz/main.roc --output=fuzz-target
./fuzz-target run --report-dir=.roc-fuzz/verify
- name: Preserve evidence
if: always()
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9
with:
name: quality-${{ runner.os }}
path: .roc-fuzz/verify
if-no-files-found: error
8.3. Coverage limits§
Coverage feedback guides discovery; it is not a proof of correctness or a claim that every source branch ran. A retained corpus and a declared regression inventory serve different purposes: coverage reduction can remove redundant seeds while source-declared examples still run independently on every check. Attempted, accepted and rejected execution counts show whether the property actually exercised useful inputs. A campaign that rejects every input provides no passing evidence.
9. Understand roc-fuzz internals§
This chapter explains how the runner executes a target, how Roc resolves
generator_for, the binary input format behind saved witnesses, and the
low-level libFuzzer escape hatch. Application authors do not need this material
for the normal target workflow.
9.1. Understand the in-process model§
The embedded libFuzzer calls a target thousands of times in the same process. It does not start a clean executable for every generated input. This is what makes it fast. Roc’s purity means target calls cannot leak application state or background work into later calls, and determinism makes saved inputs reliable with the same target and generator.
A reliable target still needs all of the following properties:
Invalid or unusual inputs return ordinary values such as
Err, rather than triggering an intentional assertion or process exit.One input normally finishes in less than 10 milliseconds.
Inputs and allocations have sensible upper bounds.
Every input terminates.
The runner is a poor fit when one test takes a significant fraction of a second, can grow without a practical memory bound, or is expected to terminate the process for invalid input. If a crash, timeout, or memory blow-up would be a bug, it remains a useful fuzzing failure.
The runner evaluates the application’s target once in a process, before any
input, and holds the result until the process exits. Work done in the target
expression, outside the property, is done once in a process; work done in the
property is done for every input. What that expression allocates is outside
every allocation measurement.
A saved entropy input produces the same typed value and result when the target and generator are unchanged. Encoded examples use the binary parser and the same property instead. Keep the executable alongside important failure artifacts when exact historical reproduction matters.
9.2. Understand generator dispatch§
generator_for uses Roc’s ordinary static dispatch. It is a method
associated with the target’s input type, not a runtime interface,
registry, or callback table. Package APIs can require their own methods
with where clauses, so the method does not need to be a
compiler-defined name.
The pattern deliberately mirrors Json.parser_for:
Json.parserequires its result type to have a compatibleparser_formethod and asks that type for a JSON parser.Fuzz.targetrequires its input type to have a compatiblegenerator_formethod and asks that type for a fuzz generator.The checker resolves both to a specific method implementation at compile time. The compiled call has no dynamic-dispatch overhead.
Conceptually, Fuzz.target has this requirement:
target : { name : Str, examples : List(Example(a)), test : a -> Outcome, show : a -> Str } -> Target
where [a.generator_for : FuzzEncoding -> Generator(a)]
FuzzEncoding currently contains the Default policy. Passing a policy
value follows the same shape as JsonEncoding and leaves room for
additional generation policies without changing the method pattern.
Use Fuzz.target when generation is part of a reusable named input
type. Use Fuzz.target_with with an explicit Generator(a) for a local
structural input or when choosing between generators for the same type
in different targets.
9.3. Binary inputs and witness identity§
Structural values use the platform-owned binary format through Roc’s existing
encoder_for and parser_for derivation. Nominal inputs opt in with both methods.
Fuzz.encode(value) creates a versioned encoded-value input; Fuzz.entropy(bytes)
frames generator entropy. Source examples are encoded into actual mutable seeds.
Host preparation copies bytes and releases temporary Roc values before running
an input. Encoding does not invert arbitrary Fuzz.map functions.
The frame is RFZ, version byte 1, form byte (0 entropy, 1 value), then
payload. Bare historical bytes without the reserved RFZ prefix remain entropy.
Artifacts whose interpretation changes across platform versions need their
original executable; cross-version corpus migration is outside this API.
Unsupported versions, malformed values and exceeded decoding budgets reject.
The encoded-value parser allows at most 1 MiB, 4096 value nodes and 128 total
containers, validating counts before allocation.
Generation chooses bias. Preconditions or validated types define validity for
both forms; a range enforced only by a generator cannot protect encoded values.
Logical encoding is not a storage snapshot. Preserve original entropy when
aliasing, capacity or slices are part of a witness. retain copies original
bytes, then prints a saved declaration and a decoded representative.
Float encoding follows Roc’s floating-point value semantics. Do not rely on
NaN payloads surviving compiler operations; use integer bit inputs for
payload-sensitive properties. With the October 27 compiler, dictionary keys
that are structural records or tuples can crash compiler specialization during
codec derivation. --specialize=no avoids that compiler limitation; ordinary
scalar and tag keys work with the default backend.
9.4. Use the libFuzzer interface§
TARGET raw [LIBFUZZER_ARG...] passes arguments directly to the
embedded libFuzzer CLI. Run this for its complete option list:
TARGET raw -help=1
Prefer run, show, replay, minimize, and reduce-corpus for the
normal workflow. Low-level flags such as -max_total_time and
-max_len belong behind raw; run accepts the stable
friendly options.
raw is an escape hatch for libFuzzer features the friendly command layer does
not yet expose directly.
9.5. Further reading§
LLVM libFuzzer documentation covers the in-process execution model, options, corpus behavior, output, and FAQ.
10. Release bundle provenance§
roc-fuzz does not store native archives or objects in Git. The independent
link-inputs.yml producer builds x64-musl and Apple
Silicon inputs on native GitHub-hosted runners, packages them without
libhost.a, and tests the exact archives with fresh hosts and final bundles. It
attests a canonical manifest and each archive but cannot publish. The trusted
default-branch publisher verifies that evidence for the exact same-repository
pull-request ref and SHA before creating an immutable release.
Platform builds restore the reviewed native-libraries.lock.json manifest and
archives, verify sizes and SHA-256 digests on downloads and cache hits, validate
their locked release, source and inventory, and build fresh hosts.
The reviewed content hash is the routine trust anchor, so a valid cache hit uses
zero network and does not contact GitHub’s attestation service. A corrupt cache
entry is discarded and only the exact locked asset may be downloaded again. The
producer attestations are admission evidence checked once by the trusted
publisher. See linker-input setup.
After those consumer tests pass, GitHub’s attestation service creates
signed SLSA build provenance and an SBOM attestation for the exact
.tar.zst bundle. GitHub binds the attestation to the release workflow
and source revision with its OIDC identity, signs it through Sigstore,
and records it in the repository attestations API. No long-lived signing
key is stored in the repository.
Each release also publishes <bundle>.intoto.jsonl for offline
attestation verification, and three files beside the bundle that describe
what it holds:
<bundle>.spdx.json, an SPDX software bill of materials;<bundle>.cdx.json, the same graph in CycloneDX;<bundle>.sbom-manifest.json, the evidence manifest that names the bundle and each SBOM by size and SHA-256.
roc-blueprint’s SBOM tool writes them through roc-automation’s
actions/sbom-sidecars, from the reviewed sbom/composition.json. The tool
checks that file against Blueprint.roc and Blueprint.lock: every input of
the environment is either a component or excluded with a reason. It lists
every member of the archive by digest and binds the documents to the bundle’s
final bytes. The components are the platform itself and the libFuzzer, Zig
runtime, musl and LLVM runtime code in the native inputs; Zig is a build
dependency. What the documents do not establish is stated as incomplete
coverage, not left out.
The build pins the Zig release and the SHA-256 of the libfuzzer-sys source
archive that scripts/native-deps.json names. Both targets are compiled against the headers Zig bundles; the
build reads no installed Apple SDK. The libraries are byte-reproducible, so
anyone with that Zig release can rebuild them from the recorded source revision
and compare digests. Native-library archives and the
final platform bundle are separate published and attested subjects, with
independent versions.
10.1. Verify a release§
Download a bundle from the GitHub release, then run:
gh attestation verify roc-fuzz-<version>.tar.zst \
--repo lukewilliamboswell/roc-fuzz
Verification checks the bundle digest, Sigstore signature, certificate and repository identity, and transparency information. This project does not claim a particular SLSA level; the attestation establishes the workflow and revision that produced the released bundle.
For offline or archived verification, download the matching
<bundle>.intoto.jsonl asset and pass it to GitHub CLI:
gh attestation verify roc-fuzz-<version>.tar.zst \
--bundle roc-fuzz-<version>.tar.zst.intoto.jsonl \
--repo lukewilliamboswell/roc-fuzz
The SBOM documents are attested with the bundle. Each names the bundle’s SHA-256, which must equal the SHA-256 of the downloaded file.
11. Contributing to roc-fuzz§
The platform has four layers:
platform/Fuzz.rocdefines typed generators, record-builder composition, and statically dispatched target construction.platform/Target.rocerases the app’s input type behind closures.platform/main.rocexposes the byte-oriented native boundary and declares the x64-musl and Apple Silicon macOS targets.src/main.zigadapts generated Roc ABI calls to libFuzzer and translates the friendly runner commands.
src/roc_platform_abi.zig is generated from Roc’s ZigGlue.roc.
11.1. Documentation policy§
Every paragraph should help someone use, maintain or assess the current project. Delete superseded instructions and duplicate explanations. Keep implementation history in Git, unresolved work in issues, and release-specific changes on the published release; do not include release notes in the manual. Preserve current compatibility guidance, security boundaries, API contracts and required notices.
Use the shared documentation guide for structure and publishing.
11.2. Toolchain§
roc-fuzz follows the roc-automation manual. Two Roc compilers are involved, and they are not interchangeable:
roc-stableruns the scripts underscripts/and nothing else. It is one nightly release, named inBlueprint.rocand repeated in therocfield of every script header. It changes only through a reviewed pull request.rocchecks, tests, builds and bundles the platform and every application that depends on it. It is the latest published nightly and is not pinned anywhere: the platform, the examples and the test targets carry norocfield. Users install the newest compiler, so that is the one the platform has to work with.
Blueprint.roc declares the tooling environment and Blueprint.lock pins it:
roc-stable, the Roc bundles the scripts depend on, and the programs they
start. roc-blueprint
fetches the compiler archives and uses Nix for the other tools, the same way on
a contributor’s machine and on every CI runner. To work on roc-fuzz you need:
Nix;
the
blueprintcommand, from the roc-blueprint release that the platform URL inBlueprint.rocnames:nix profile install github:lukewilliamboswell/roc-blueprint/VERSION, or the release’s prebuilt binary checked against its published SHA-256;a current Roc nightly installed as
roc.
The environment supplies the Zig release that Blueprint.roc names, from
zig-overlay, to build the host and its
linker inputs and to format the host bindings. scripts/native-deps.json names
the same release, and the supply-chain check holds the two together.
blueprint tasks # list the declared tasks
blueprint run check # everything a pull request must pass that needs no host
blueprint shell # enter the environment and run scripts/*.roc directly
Run blueprint from an ordinary shell. Inside the environment roc-stable is
the pinned compiler and your own roc remains visible. Arguments to a
task follow --, for example blueprint run build-platform -- --target x64musl.
Linker inputs have an independent, content-addressed release cycle;
libhost.a is deliberately outside that cycle and is built with each platform
update. This separation means a host or Roc source change does not rebuild large,
stable runtime inputs. The builder uses zig ar.
Repository examples use relative paths to the working-tree platform. Each
release provides roc-fuzz-examples-VERSION.zip with complete applications,
supporting modules, the cases that describe them, and that release’s exact
platform URL. Nothing else in an archived example differs from the repository.
The Nightly compatibility workflow runs the latest release’s archive, exactly
as published, on the latest nightly every day.
11.2.1. Maintain the tooling§
Review tooling changes in pull requests:
- Upgrade roc-automation
Review the upstream changes and the shared action guidance. Pin the shared actions, nightly workflow, and archive tester checkout in
.github/to the same reviewed full commit SHA. Check the CI, documentation, and release dry run before merging. The shared nightly validates the published examples after the upgrade reachestrunk.- Upgrade the documentation renderer
Change the roc-docs release in
Blueprint.rocand the documentation and release workflow labels. Runblueprint update roc-docsand review the digests for all three development hosts, then build the manual withblueprint run docs.- Update the lock
Run
blueprint update, orblueprint update INPUTto move one input, thenblueprint run check.- Change the tooling compiler
Change the tag in
Fetch("roc-stable", ...)inBlueprint.rocand therocfield of every script to the same tag. The check script fails until they match. Runblueprint update roc-stableto lock the compiler archives for every supported development host.- Upgrade Blueprint
Change the platform URL in the
Blueprint.rocheader, runblueprint checkand then a fullblueprint update, and review the new lock. No workflow names the version:actions/setup-blueprintreads it fromBlueprint.rocand verifies the binary against the checksums roc-automation records, so a release it does not record yet needs that action repinned first.- Update a script dependency
Change the release URL in each script header and under
RocPackagesinBlueprint.roc, adding any new dependency of that dependency (roc-stable deps scripts/check_all.roclists them), then runblueprint update.- Update a platform package
Every application built against the platform fetches and compiles the packages under
packagesinplatform/main.roc. Give each release URL a reviewed component insbom/composition.json, with that URL as itsdownload, its SHA-256 and license, and adependsOnrelationship fromSubjectwith scoperuntime. The supply-chain check refuses a URL without one.THIRD_PARTY_LICENSES.mdlists only what the bundle contains or links, and editing it changes the linker-input fingerprint.- Keep the SBOM composition current
sbom/composition.jsongives every inputBlueprint.rocdeclares (each source, tool, fetched program, script package and task) a disposition. A new task or tool needs an entry there too, or the release dry run’s SBOM step refuses the composition. A change to what the native inputs contain, such as a new library or a new Zig release, changes its components.- Regenerate the host bindings
See Host bindings.
11.3. Repository scripting convention§
Repository-owned automation is written in Roc. Put executable entry points in
scripts/*.roc and reusable logic in scripts/src/*.roc. Use the existing shared
modules for commands, paths, hashing, source edits, archives, and release metadata.
Do not add Python scripts, shell launchers, or build-before-run wrappers to work
around compiler behavior. Keep workflow YAML limited to job orchestration and
small environment/output plumbing; substantive automation belongs in Roc.
Every entry point starts with the #!/usr/bin/env roc-stable shebang, is
committed as executable, and is declared as a Task in Blueprint.roc. CI
calls tasks, never script paths, so a workflow and a contributor run the same
command. A script starts another script through Script.roc_stable! and runs
package work through Script.roc!, which is the roc on PATH. Never use
roc-stable to check, test or bundle the platform. A successful script must
return zero, and a failed script must remain a failure.
A script references every dependency by immutable release URL, and the same URL
is listed under RocPackages in Blueprint.roc. scripts/check_supply_chain.roc
holds each header to Blueprint.roc: the shebang, the roc field, and every
bundle URL. It also fails when a Roc file outside scripts/ carries a roc
field, and when a workflow references an action by anything but a full commit
SHA.
Roc scripts may invoke standard tools such as Git and curl via argument lists,
without shell evaluation. Roc owns selection, validation, and control flow.
Declare a program a script starts under Tools in Blueprint.roc.
Archives are read and written in Roc, by scripts/src/Archive.roc with the
tar, ZIP and gzip packages under RocPackages; no script starts an archiver.
Reading accepts only regular files and directories with portable relative names,
within a size limit: a link, a device, a duplicate or unsafe name, or a damaged
or truncated archive refuses the whole archive before anything is written, and
the script writes each file itself. Packing gives the same bytes for the same
files: each member has mode 0644, owner 0 with no names, and the time
1980-01-01 00:00 UTC. Under the script compiler’s default backend, decompression
is the slow part: unpacking src/glue from a nightly’s 33 MB source archive
takes about six seconds, and packing the documentation site about eight.
Pinned external tools and shared actions remain external dependencies;
for example, the shared documentation builder currently uses Python internally.
That does not justify adding repository-owned Python orchestration.
Pure regression checks belong in shared-module expects imported by
scripts/tooling_tests.roc. Filesystem and process checks belong in
scripts/tooling_integration_tests.roc; both run from scripts/check_all.roc.
11.4. Generate platform inputs§
Generate the current host’s ignored inputs with:
blueprint run build-platform
Pass -- --target x64musl or -- --target arm64mac explicitly in automation.
The default restores the archives selected by native-libraries.lock.json,
rehashes their manifest and target archive even on a cache hit, validates the
complete archive inventory, builds the current host, and writes local
SHA256SUMS. The archive digest is the reviewed authorization for routine use;
the cache key only locates likely bytes. This is why cache hits are still hashed
and why a cache miss downloads the exact locked release rather than rebuilding.
It avoids repeat network traffic without allowing a poisoned or truncated cache
entry to become trusted. Routine restoration does not query GitHub’s attestation
service. Never commit generated archives, objects, or manifests.
The Linker inputs producer, link-inputs.yml, runs on a pull request that
touches the recipe and on dispatch. One Linux job cross-compiles both targets,
and a job on each target runs every case against the candidate. It packages both targets without
libhost.a, tests each candidate through a fresh host and final bundle, emits a
canonical aggregate manifest, and attests that manifest and both archives. It has
no publication authority. Release new inputs for changes to their sources,
runtimes/toolchains, flags, targets, security fixes, or the macOS adapter compiled
into libfuzzer.a. The macOS coverage shim stays with libhost.a.
Publish link inputs runs trusted controller code pinned to a reviewed full
roc-automation commit. It dispatches the producer at the exact same-repository
PR head, verifies the workflow/ref/SHA, hashes and attestations, publishes an
immutable release named from the aggregate manifest hash, and adds only the lock
in a lease-guarded GitHub-signed commit. Candidate code cannot publish, while the
privileged job never executes candidate code. The PR-built release remains the
permanent dependency after merge; rebuilding it would break the evidence-to-byte
identity that the review admitted.
GitHub immutable releases must be enabled before the first publication. The controller checks the resulting release state and refuses to adopt a lock when the hosting policy does not enforce immutability; a content-derived name alone cannot prevent an administrator from replacing assets.
Before adopting a release, review its producer changes, exact source revision, input fingerprint, manifest and archive digests, sizes, target coverage, native link tests, and workflow attestations. Merge with a merge commit so the attested producer SHA and signed lock commit remain reachable. Ordinary pull requests then know only the reviewed lock, cache, verifier, and target files; they never dispatch or reproduce linker inputs.
The libraries are byte-reproducible: the same sources, Zig release and flags give the same bytes on any machine, in any directory, at any time. Nothing is compiled with debug information, which would record the absolute paths of the Zig installation, its cache and the working directory, and archive members are named by file name alone where Zig names them by cache path. The macOS target is compiled against the headers Zig bundles, so it builds on Linux as well as on macOS and reads no installed Apple SDK. Keep it that way: a change that makes two builds of the same commit differ is a defect in the recipe.
A routine pull request never rebuilds the libraries. It hashes a short list of
files and compares the result with the input_fingerprint the lock records;
LinkInputs.fingerprint_inputs is the list:
scripts/native-deps.json: the Zig release, the libFuzzer source, and the recipe revision;the macOS libFuzzer adapter and the stand-in header it is compiled with; and
the licence files packed beside the libraries.
No script, workflow or lock file is in it, so editing tooling never demands a
release. The recipe itself lives in scripts, and that is what the recipe
revision is for: raise recipe_revision when a change to the build alters a
library byte, such as a flag, a target or the list of libraries.
Reproducibility keeps that honest, and three checks guard it:
The
Linker-input recipejob ofci.ymlis part ofCI required. It asks whether the pull request touches the recipe, which is the list inLinkInputs.recipe_paths: the build script, the target definitions, the recipe file, the macOS sources, andBlueprint.rocandBlueprint.lock, which supply Zig. A routine pull request stops there. One that touches the recipe rebuilds both targets and, while the lock claims to be current, requires the result to be byte-identical to the locked release. A change that alters a library without raising the revision fails, naming the files, and cannot merge. So does a change that makes the build irreproducible.The
Linker inputsproducer makes the same comparison when it builds a candidate, and runs every case against it on both targets.The supply-chain check fails when a path in
LinkInputs.recipe_pathsis missing from the producer’spathsfilter, so a file added to the recipe cannot be left out of the trigger.
Run the comparison locally with:
blueprint run build-platform -- --target x64musl --target arm64mac --libraries source --libraries-only
blueprint run link-inputs -- --operation check-source
When the fingerprint changes, or that comparison fails, use this sequence:
Stage the change in a same-repository PR, raising
recipe_revisionif the build recipe changed. ItsPlatform bundlejob fails with a stale-lock error until the new lock is adopted.To inspect a nonpublishing candidate, dispatch
Linker inputson the PR branch withrelease_candidate=trueandexpected_shaset to its exact current head. For example, rungh workflow run link-inputs.yml --ref BRANCH -f release_candidate=true -f expected_sha=SHA, replacingBRANCHandSHA. Review both target tests, the manifest, archive hashes, and attestations. This run does not create a GitHub release or edit the PR.From
trunk, dispatchPublish link inputswithpull-requestset to that PR number:gh workflow run publish-link-inputs.yml --ref trunk -f pull-request=NUMBER. To recover an interrupted publication, also passproducer-runwith the ID of the successful producer run for the current head. The trusted publisher reruns the producer at the exact PR head, publishes the immutable linker-input release, and appends a GitHub-signednative-libraries.lock.json-only commit to the PR. Do not dispatch it from the PR branch or rebuild the inputs after merging.Review that lock commit and revalidate the updated PR. After its required checks pass, merge the PR with a merge commit. Publish a new Roc platform bundle later through the separate
Releaseworkflow, using the adopted lock.
The optional preview in step 2 does not replace the producer run performed by the trusted publisher in step 3. The publisher is the release operation; stop before that dispatch when only candidate validation is authorized.
The fully static build excludes FuzzerInterceptors.cpp. Its wrappers
locate libc functions through dlsym, which is not usable in the static
musl executable. The standard libFuzzer scheduler, mutators, corpus
engine, crash handling, minimizer, and merge engine remain unchanged.
Roc’s compare and switch instrumentation still supplies value feedback.
The macOS target includes FuzzerInterceptors.cpp: its dlsym lookups
work with macOS’s dynamic libSystem. Its deployment target is macOS
11.0, and its only allowed dynamic dependencies are system libraries.
The host makes a goal’s first reach new coverage. For a target that declares
goals it registers one inline 8-bit counter for each, and a PC table of the same
length, through libFuzzer’s __sanitizer_cov_8bit_counters_init and
__sanitizer_cov_pcs_init: the entry points instrumented code calls on both
targets. The region therefore lives in libhost.a and needs no linker section
and no change to libfuzzer.a; on x64musl they are the only sanitizer symbols
libhost.a leaves undefined. A target without goals registers nothing, so
libFuzzer’s Loaded N modules line gains one module of G counters for G goals
and none otherwise; test-targets checks both on each host.
libFuzzer’s extra counters are not an option: the pinned source reads them on
Linux only.
src/macos_sancov.c supplies the public TLS slot required by Roc’s
macOS stack-depth coverage instrumentation.
src/macos_fuzzer_ext_functions.cpp binds the standalone runner hooks
directly because upstream libFuzzer’s Darwin dlsym lookup requires
-export_dynamic, which Roc does not pass. Both files are
repository-owned platform glue covered by the project license; the
native build, show/replay, fuzz, failure-artifact, and packaged-bundle
smoke tests exercise them on Apple Silicon.
11.5. Host bindings§
The host is compiled against src/roc_platform_abi.zig, which roc glue
generates from platform/main.roc. The file is committed. The host build reads
it and never generates it, so the host builds the same way on every runner and
a change to the interface is reviewed as a diff.
The compiler generates the bindings, so a new nightly can change them when
nothing in this repository changed. The Host bindings job of ci.yml
regenerates them with the nightly the run resolved and fails when the committed
file differs. Run the same check locally with:
blueprint run check-glue
The glue specification comes from the source archive attached to that nightly’s
release, verified against the SHA-256 that GitHub records for the asset. For a
compiler built from source, name its checkout with -- --roc-source DIR.
When the check fails and the change did not touch platform/, the compiler
changed the interface. Upgrading is a manual task, because a changed layout or
signature usually needs a matching host change:
Run
blueprint run check-glue -- --updatewith the latest nightly asroc.Review the diff and change the host where a layout or signature changed.
Build the host for every target and run the targets.
Open one pull request with the bindings and the host change.
11.6. Validation§
Every bug fix and significant new behavior should include an automated test at the narrowest useful layer. Changes to public behavior also update the relevant examples, interface documentation, or report schema. A pull request should explain the behavior changed and the validation performed.
The scripts use whichever roc comes first on PATH. To validate with a
compiler under development, put it there:
PATH=/path/to/roc/zig-out/bin:$PATH blueprint run check
blueprint run test-targets -- --operation check --verbose
blueprint run test-targets -- --operation build --verbose
blueprint run test-targets -- --operation seed
blueprint run test-targets -- --operation fuzz --max-total-time 2
blueprint run check needs no native inputs: it formats, tests the scripts,
runs the pin and supply-chain checks, the native allocation/trace engine and
supervisor lifecycle suite, type-checks the platform and runs its
expect tests from platform/main.roc, and type-checks every case in
tests/targets.json. After native inputs are prepared, test-targets
provides the focused operations shown above.
For an application built with Fuzz.suite, add a suites entry in
tests/targets.json with the case name and its members, each containing
name and expected_failure. Both the target driver and release archive use
this inventory to select every member while sharing one executable.
A case is judged by its exit codes: expected_failure makes replay and the
campaign exit 1, and check must pass. To require more, such as a target
whose goals leave check or its campaign inconclusive, add an entry to the
outcomes list. Its target is the case name, or case/member for a suite
member; check and fuzz each give the outcome (passed, finding or
inconclusive) and the goals status (goals: reached, unreached or
none_declared) that the quality and fuzz stages require of report.json.
Seed replay and measurement still follow expected_failure.
test-targets runs each stage of the operation (check, test, build, seed,
measure, quality, fuzz) over every selected case and prints one line per step as it
finishes, with its position, PASS, FAIL or SKIP, and its time in
milliseconds. A failed step does not stop the run: the case’s later stages are
skipped and every other case carries on. The run ends with each failure and the
end of its output, each skip with its note, the counts, the total time and the
slowest steps, and exits non-zero if anything failed. A command’s output is
shown only when its step fails; --verbose shows all of it as it runs. Colour
is used only on a terminal and never when NO_COLOR is set. --target NAME
and --path-prefix PREFIX narrow the selection.
Checked-in examples and test targets use the local platform. The nightly
compatibility workflow uses the latest release’s own archived examples and
immutable bundle. Validation
checks the exact example inventory, Roc formatting and types. After
generating the current host inputs, building creates every
self-contained executable and verifies a static x86-64 ELF on Linux or
an arm64 Mach-O with system-only dynamic dependencies on macOS. Seed
validation renders and replays each deterministic input. The fuzz
operation runs short campaigns and verifies that an intentional Roc
failure is saved byte-for-byte with follow-up commands.
Build the HTML manual, PDF, and generated API reference with:
blueprint run docs
blueprint run site
docs runs roc-docs, the renderer actions/build-docs runs, at the
roc-automation tools release that Blueprint.roc names and Blueprint.lock
pins by digest. It writes the working tree’s manual, PDF and API reference
under .docs-out/. site assembles what GitHub Pages serves: the latest
release’s documentation, restored from the archive that release published, with
the working tree’s under unreleased/.
Keep Mermaid source in the manual. The renderer generates diagrams for the site and PDF during the ordinary documentation build; no prepared diagram registrations or generated images need to be checked in. The final API audit fails if an exposed module or public entry has no rendered documentation. The documentation and release workflows run the same build and audit.
Every case runs the check, test, build, seed, and fuzz
stages by default. To switch off a case’s seed replay or fuzz run, set its
skip_seed or skip_fuzz and add an entry to the skips list in
tests/targets.json with the case name, the operation, a concrete reason and a
full issue URL. The supply-chain check rejects a skip without exactly one such
note, and a note left behind once the case runs again. The driver names every
skip and its reason at the start of each run. A seed skip also switches off
the case’s measure and quality stages; the check, test and build
stages always run. The skips list is the record
of what is switched off now.
A file under trophy-case/repros/ that can run is a case in
tests/targets.json. The one kept there is a deliberate type error that the
compiler once panicked on; blueprint run check requires roc check to report
it.
Four workflows each answer one question:
ci.ymlDoes this change work with today’s compiler? One job runs
blueprint run checkand audits the API reference. One job regenerates the host bindings and compares them with the committed file. One builder cross-compiles the host for both targets around the locked inputs and assembles a single bundle, and a job on each target downloads that bundle and runs every case against it.CI requiredaggregates them.release.ymlDo these exact bytes work? On a pull request it is a dry run under the version
0.0.1-dryrun: it builds the bundle, the examples archive, the SBOM, the documentation archive and the release notes, and tests the archive against the bundle on both targets.Release requiredaggregates it.nightly.ymlDoes the latest release still work with today’s compiler? It runs daily; see Release bundle.
fuzz.ymlHas today’s compiler broken a builtin? Once a day, and only on
trunk, it fuzzes every builtin target intests/targets.jsonon the latest nightly for a few seconds each, about ten minutes in all. It runsblueprint run test-targets -- --operation fuzz --campaign-dir DIR --path-prefix tests/targets/builtins/. The corpus underDIR/corpus/carries over between runs through the Actions cache. Each target’s failing inputs are kept underDIR/failures/and uploaded as thefuzz-failuresartifact. Every target runs before the job fails. Reproduce a failure with the target’sreplaycommand and the kept input, then report it upstream if it is the compiler’s.
A new nightly can fail an untouched pull request. Compare with the latest
Nightly compatibility run and with trunk before treating a failure as a
regression in the change.
Linux CI also rebuilds the checksum-pinned libFuzzer sources with
AddressSanitizer and runs a short native smoke campaign. This detects heap,
stack, use-after-free, and leak errors in the embedded C++ fuzzing engine on
every pull request, every trunk update, and before release publication. Run
the same check locally with
blueprint run native-sanitizers; it requires Clang,
curl, and tar. The sanitizer executable is CI-only and does not change the
static release artifacts.
The Roc driver runs on Linux and Apple Silicon without platform skips. Scripts execute directly with the fixed tooling compiler; compilation errors, warnings, and application failures retain their normal Roc exit status.
Use --suite-root PATH to run an unpacked examples archive containing examples/ and
tests/targets.json. Each invocation has fresh temporary executables and, unless
--campaign-dir names a directory to keep them in, fresh corpora.
Fuzz smoke tests pass corpus directories to libFuzzer; passing an individual seed
file would only replay it. Repository formatting is checked separately, not against
an older release’s frozen source.
Every property callback has an automatic allocation observation. Source examples
run independently of the coverage corpus and can be accepted into an exact
baseline. Explicit named regions use Fuzz.measure! or manual measurement
windows; ordinary Roc assertions inspect their statistics. Existing builtin
regressions also use allocation assertion helpers around specific operations.
The quality stage exercises the real executable’s unbaselined, acceptance and
exact-match workflow for targets with declared examples. The native suite tests
crashes, deadlines, rejected inputs, baseline drift in both directions, original
shared evidence and atomic write failures.
Assert on a difference between two counter reads, never on a raw value: the counter is process-wide and libFuzzer reuses one process across millions of inputs. Only assert zero for a value that is uniquely owned and pre-sized, because copy-on-write allocation is correct when a value is aliased.
Separately, the runner checks after every input that the target freed
everything it allocated, and fails the input otherwise. Pass
--no-detect-leaks to a run to turn that off.
The byte-oriented builtin targets live under tests/targets/builtins/
and use explicit byte generators and Fuzz.keep outcomes. Their original
byte-valued probe results keep aliases alive and are not rejection statuses.
They are regression tests for the compiler and its
builtins: tests/targets.json lists them beside the examples, pull-request CI
runs them, and a release’s examples archive leaves them out. The applications
under examples/ are an end-user gallery and should
prefer Fuzz.target, typed generators, and the .Fuzz record builder.
A multi-file example must live in its own directory with main.roc as
its app root; the test driver enforces this so editor tooling can
discover the project naturally.
11.6.1. Arctangent builtin properties§
The tests/targets/builtins/arctangentDec.roc, arctangentF32.roc, and
arctangentF64.roc targets check atan and atan2 with composed numeric
generators. They also assert that the numeric checks allocate no heap memory;
input generation and diagnostic rendering are outside that measurement.
The float targets check NaN propagation, signed zeros, infinities, range,
quadrants, and odd symmetry. F32 results are compared with F64 results rounded
to F32, allowing two ULP. F64 angles are checked against normalized input
coordinates using sine and cosine, with absolute tolerance 3e-15. Quadrant
checks allow two ULP at the rounded half-pi boundary, while zero and infinity
cases require exact result bits.
The Dec generator composes two U64 values into a signed 128-bit attosecond
payload and varies its magnitude with a shift. It checks axes, range, symmetry,
and agreement between atan(y) and atan2({ x: 1, y }), allowing 128 attoseconds.
Comparison with the separate F64 implementation allows 4e-15 for conversion
and floating-point error. Dec.lowest is tested but excluded from negation
checks because its negation overflows.
These checks supplement the compiler’s high-precision unit tests; shared
algorithms and finite tolerances mean they do not prove correct rounding.
To run just these inventory entries, with a roc on PATH that includes the
atan2 builtins:
blueprint run test-targets -- --operation all --max-total-time 60 \
--target arctangentDec --target arctangentF32 --target arctangentF64
Use the normal runner’s show, replay, and minimize commands to investigate
saved failures, as
the campaign chapter describes.
11.7. Release bundle§
Create a Roc platform bundle after generating both target input sets with:
blueprint run bundle -- --output-dir dist
build_bundle.roc verifies every generated input checksum, then includes the
archives and license notices in
roc bundle. Test the resulting bundle from an external
target with:
blueprint run test-bundle -- dist/<bundle>.tar.zst
11.7.1. What a release contains§
One immutable GitHub release per version holds:
| Asset | Purpose |
|---|---|
The bundle, under the filename roc bundle emits | What users depend on. The filename is its content hash. |
roc-fuzz-examples-VERSION.zip | The examples pinned to this release’s bundle, with the cases that describe them. |
roc-fuzz-docs-VERSION.zip | The manual and API reference for this version. The documentation site restores the latest release’s copy. |
roc-fuzz-VERSION.pdf | The manual. |
<bundle>.spdx.json, <bundle>.cdx.json | The bundle’s SBOM, in SPDX and CycloneDX, written from sbom/composition.json. |
<bundle>.sbom-manifest.json | The evidence manifest binding the bundle and its SBOM documents by digest. |
*.intoto.jsonl | The exported build-provenance attestations for the bundle and the examples archive. |
11.7.2. Write the release notes§
Before dispatching a release, commit a non-empty docs/releases/X.Y.Z.adoc, or
docs/releases/X.Y.Z-rcN.adoc for a release candidate. Keep these publisher
inputs out of the manual’s reading path. The first heading
must be = roc-fuzz VERSION. Release notes are reviewed as documentation and
should explain the release to users: lead with the theme, show notable features
and compatibility changes, name the supported hosts, link to
verification material, and give upgrade or feedback guidance.
Use {platform-url} where the copyable application header needs the
content-addressed bundle URL, and {manual-url} for the release’s PDF. Do not
put a roc field in that header. The build job fills both in after it has made
the bundle, translates the note’s headings and source blocks to GitHub Markdown
with scripts/render_release_notes.roc, and appends links to the bundle’s SBOM
documents and, under Compilers, the output of roc version and
roc-stable version. That record is the release’s statement of what it was
built and tested with. Notes that never use {platform-url}, or that leave a
placeholder unresolved, fail the build.
The committed file keeps its placeholders and is never rewritten after the
release. A pull request renders the highest version under docs/releases/, so
a mistake in the notes being written fails on the pull request that makes it.
While that version is still the latest release, there is nothing to render.
11.7.3. Publish a release§
From the repository’s Actions tab, run Release on trunk with an X.Y.Z
version. The workflow:
rejects a version whose tag or release exists, requires
trunk, and requires the notes file;runs
blueprint run checkand the sanitizer check on that commit;cross-compiles the host for both targets, bundles once, and checks the requested version against the public API with
roc bump --expect, so a breaking change cannot go out as a patch;builds the examples archive with the real release URL, the SBOM, the documentation archive, the manual and the rendered notes;
on each target, serves the bundle on a loopback address and runs the archived examples against it, with an empty package cache;
attests the tested bundle, its SBOM documents and the examples archive; and
publishes from a job that checks out nothing and runs no repository script. roc-automation’s
actions/publish-releasestages a draft release at the tested commit, uploads every asset, downloads each one back and compares it with the tested file, and only then publishes.
After a final release the workflow rebuilds and deploys the documentation site, which leads with the latest release.
The publish job runs in the release environment. Use roc bump before
choosing a version:
roc bump --old <previous release bundle URL> platform/main.roc
A release candidate is the same dispatch with an X.Y.Z-rcN version. It goes
through every step above, holds the same assets, and is published as a
prerelease that is never the latest release. Nightly compatibility and the
documentation site ignore it. Fix what a candidate turns up on trunk and
publish -rc2; a candidate is immutable like any other release.
11.7.4. When a new compiler breaks the latest release§
Nightly compatibility runs every day. It selects the latest Roc nightly and
the latest stable platform release, and runs that release’s examples archive,
unchanged, on both targets with trunk’s scripts. Its report job keeps one
issue, titled "The latest release fails on the latest Roc nightly": opened by
the first failure, commented on by each later one, and closed by the next pass.
A run in which setup failed before any example ran fails without touching the
issue.
A release is immutable. Publish a new version that works with the latest
compiler. Use a patch when the public API permits it. If the latest compiler
cannot check the previous release, compare both APIs with a nightly that can
check both. Reproduce a past combination by dispatching the compatibility
workflow with a nightly-tag and a release-version.
11.7.5. Recover an interrupted publication§
Inspect exactly what exists before retrying. An unfinished draft can be completed from the same run’s artifacts: upload what is missing, verify the complete inventory, then publish. A published release that is incomplete cannot be repaired; publish a new version. Changed bytes are always a new version. Never replace an existing tag or asset, and never rebuild a release from a moving branch.
11.8. Design constraints§
Static dispatch happens while Fuzz.target is specialized for the app’s
input type. Target then erases that type, preventing the native ABI
from depending on every app record or tag-union layout.
The platform supports x64-musl and Apple Silicon macOS. Keep native calls behind the generated bindings, so that a compiler ABI change is caught by the bindings check and by compilation.
11.9. Shared examples archive§
The examples ZIP has one root named
roc-fuzz-examples-VERSION, containing README.md, spec.json, and examples/.
The specification derives from the published examples in tests/targets.json.
Each app requests build_args: ["--fuzz"] and records replay and one-second
seeded smoke cases. Cases keep exact stdout and exit expectations while
stderr_match: "ignore" allows libFuzzer statistics to vary; raw stderr remains
available for diagnosis. Seeds and local harness metadata live under
examples/.roc-fuzz/. The local driver also accepts flat archives.
The release test jobs run the exact ZIP and bundle through the reviewed shared
release-package test-archive utility before publication. Its loopback bundle
replacement preserves the archived sources and verifies the candidate bytes.
The daily Nightly compatibility workflow uses the shared single-job caller
on Linux x86-64 and Apple Silicon. Empty selectors test the latest final release
against the latest nightly and report through the shared compatibility gate.
Diagnostic selector overrides test historical pairs and do not update the issue
about the latest pair. The separate builtin fuzz campaign retains its own
schedule and corpus; its result does not determine release compatibility.
12. Project information§
12.1. Support, feedback, and releases§
Use GitHub issues for reproducible bugs and enhancement requests. Include the roc-fuzz release, Roc compiler version, operating system and architecture, target source or a minimal reproduction, and the relevant command output. Proposed changes use pull requests and follow the contributor guide.
Suspected vulnerabilities follow the private security reporting process and must not be disclosed in a public issue. Published bundles, PDF manuals, documentation archives, checksums, provenance, and human-readable release notes are available from GitHub Releases.
12.2. Origins and acknowledgments§
The foundational and exploratory work for roc-fuzz was created by Brendan Hansknecht. Brendan established the original Roc fuzzing integration, arbitrary input machinery, quality-target suite, and the early trophy case demonstrating the bugs this approach could find.
The platform in this repository extends Brendan’s experiment into a modern Roc
workflow with typed generators, reusable target construction, and a
self-contained executable built directly with roc build --fuzz. This work
would not exist without the foundation he developed.
13. Release downloads§
Find immutable bundles, examples, documentation and release-specific changes on GitHub Releases. Copy a platform URL from the release you intend to use.