Operations: links, logs, rules and fleets in service · 7 MIN READ
Property-based testing of flight software: generated worlds, shrinking and fuzz targets
Generate scenarios from seeds, state invariants that must hold in every world, find a failing seed for a deliberately weak obstacle planner, shrink it to a minimal counterexample, verify the fixed planner across every seed, and express the same property as a Go fuzz target.
The simulation-testing lesson checked a table of hand-picked worlds, and a table holds only the cases someone thought of. Property-based testing turns the question around: state what must be true in every world, let a generator produce hundreds of worlds nobody would have written down, and when one breaks a property, shrink it until only the cause is left. Flight software suits it, because its invariants are short and its failures hide in combinations of geometry and weather.
drones · A MAP OF THE IDEA
- Generate worlds from seeds
- Check properties per run
- Shrink the failing seed
- Keep it as a regression
Useful when
- Finds combinations nobody would write into a table.
- A shrunk counterexample points straight at the cause.
Watch out
- A generator that never makes the hard cases proves nothing.
- Properties hold only inside an envelope you must write down.
Implementation & operation cost: A seeded generator, a property checker, a greedy shrinker and CI time for a few hundred simulated flights per commit.
Properties, not expected outputs
A property is a statement about every run, not the expected result of one. The program checks four. Fence: never more than 2 m outside the geofence. Obstacles: never closer to a wall than 0.3 m, the distance at which the simulator counts a touch. Reserve: always end on the ground, not crashed, with at least 10 percent charge. Explained: the mission completes, or the timeline holds a note with a reason, from an autopilot failsafe or from the mission's own decision. None of them says how far the drone gets or how long it takes, so tuning does not break them, and the last one turns 'the mission quietly gave up' into a failure. The idea comes from QuickCheck, a Haskell library from 2000; Go's testing/quick package is frozen, and today Go's built-in fuzzing serves the same purpose, as the last code section shows.
Generators: a seed is a world
Generate builds a whole scenario from one seed with a math/rand/v2 PCG source: wind up to 8 m/s from any direction, gusts up to 3 m/s, 30 to 100 percent charge, a square fence whose sides lie 50 to 90 m from home, two to five waypoints and up to three obstacles of 2 to 6 m radius. Two choices matter more than the ranges. The generator aims at trouble: each obstacle stands a few metres to either side of a random leg, because obstacles placed uniformly would rarely be near a route and almost every world would be easy. And it states the envelope: no obstacle within its radius plus 8 m of home or a waypoint, nothing outside the wind range. Properties are promised only inside the envelope, so write it down; a failure outside it is a new requirement, not a bug. Keep the seed in every report: it reproduces the whole world, and the simulator is seeded from it too.
Find, shrink, fix
Plan routes a leg around every obstacle tall enough to hit, keeping clear metres from its wall: it steps sideways from the obstacle's centre, checks that both new legs are clear, recurses for other obstacles and backtracks when a detour lands next to another one. Fly flies the mission with that planner and turns home along the planned path below 30 percent charge, before the autopilot's 20 percent return home flies a straight line through whatever stands in the way. The weak planner keeps 0.3 m, only the airframe; the fixed one keeps 3 m. main runs the weak one over 300 seeds, shrinks the first failure, then runs the fixed one over the same 300 and flies the minimal world with both.
package main
import (
"fmt"
"log"
"maps"
"math"
"math/rand/v2"
"slices"
"strings"
"gopherforge.app/drone"
)
const cruise = 15.0 // m
// Scenario is one generated world and mission.
type Scenario struct {
Seed uint64
Wind drone.Vec3
Gust float64
Battery float64
Fence float64 // half side of a square fence around home, m
Waypoints []drone.Vec3
Obstacles []drone.Obstacle
}
func (sc Scenario) String() string {
return fmt.Sprintf("wind %v gust %.1f, battery %.0f%%, fence ±%.0f m, waypoints %d, obstacles %d",
sc.Wind, sc.Gust, sc.Battery, sc.Fence, len(sc.Waypoints), len(sc.Obstacles))
}
// Generate builds a scenario from a seed: the same seed, the same world.
// Obstacles stand a few metres to either side of a random leg.
func Generate(seed uint64) Scenario {
r := rand.New(rand.NewPCG(seed, 7))
u := func(lo, hi float64) float64 { return lo + (hi-lo)*r.Float64() }
w, dir := u(0, 8), u(0, 2*math.Pi)
sc := Scenario{Seed: seed, Wind: drone.Vec3{X: w * math.Cos(dir), Y: w * math.Sin(dir)}, Gust: u(0, 3), Battery: u(30, 100), Fence: u(50, 90)}
for range 2 + r.IntN(4) {
m := sc.Fence - 20
sc.Waypoints = append(sc.Waypoints, drone.Vec3{X: u(-m, m), Y: u(-m, m), Z: cruise})
}
route := append([]drone.Vec3{{Z: cruise}}, sc.Waypoints...)
for range 1 + r.IntN(3) {
i := r.IntN(len(route) - 1)
a, b := route[i], route[i+1]
o := drone.Obstacle{Name: fmt.Sprintf("obstacle %d", len(sc.Obstacles)+1), Radius: u(2, 6), Height: u(10, 40)}
side := drone.Vec3{X: a.Y - b.Y, Y: b.X - a.X}
c := a.Add(b.Sub(a).Scale(u(0.25, 0.75))).Add(side.Scale(u(-1, 1) * (o.Radius + 4) / side.Len()))
o.X, o.Y = c.X, c.Y
if !slices.ContainsFunc(route, func(q drone.Vec3) bool { return q.Sub(c).Horizontal().Len() < o.Radius+8 }) {
sc.Obstacles = append(sc.Obstacles, o)
}
}
return sc
}
// pointSeg is the horizontal distance from p to the segment ab.
func pointSeg(p, a, b drone.Vec3) float64 {
ab, ap := b.Sub(a).Horizontal(), p.Sub(a).Horizontal()
t := math.Max(0, math.Min(1, (ab.X*ap.X+ab.Y*ap.Y)/max(ab.X*ab.X+ab.Y*ab.Y, 1e-9)))
return ap.Sub(ab.Scale(t)).Len()
}
// Plan returns waypoints from a to b (b included) that keep clear metres
// from every obstacle tall enough to hit, or false when it finds none.
func Plan(a, b drone.Vec3, obs []drone.Obstacle, clear float64, depth int) ([]drone.Vec3, bool) {
ab := b.Sub(a).Horizontal()
for _, o := range obs {
c, need := drone.Vec3{X: o.X, Y: o.Y, Z: a.Z}, o.Radius+clear
if o.Height < a.Z-1 || pointSeg(c, a, b) >= need {
continue
}
if depth == 0 {
return nil, false
}
n := drone.Vec3{X: -ab.Y, Y: ab.X}.Scale(1 / ab.Len()) // sideways, the leg's side first
if ab.X*(c.Y-a.Y)-ab.Y*(c.X-a.X) > 0 {
n = n.Scale(-1)
}
for _, l := range []float64{1.2, 1.5, 2, 2.5} {
for _, d := range []drone.Vec3{c.Add(n.Scale(l * need)), c.Add(n.Scale(-l * need))} {
p1, ok1 := Plan(a, d, obs, clear, depth-1)
if p2, ok2 := Plan(d, b, obs, clear, depth-1); ok1 && ok2 {
return append(p1, p2...), true
}
}
}
return nil, false
}
return []drone.Vec3{b}, true
}
// Result is what one flight measured.
type Result struct {
Reached int // mission waypoints reached
Outside float64 // furthest outside the fence, m
Clearance, Planned float64 // closest to an obstacle's surface: flown, planned
Battery float64 // at the end, %
Landed bool
Notes []drone.Event // the timeline
}
// Fly runs the mission with a planner that keeps clear metres from obstacles,
// and turns home on its planned path below 30% before any failsafe does.
func Fly(sc Scenario, clear float64) (*drone.Sim, Result) {
f := sc.Fence
sim := drone.New(drone.Config{Wind: sc.Wind, Gust: sc.Gust, Battery: sc.Battery, MaxSpeed: 8, Seed: int64(sc.Seed),
Geofence: []drone.Vec3{{X: -f, Y: -f}, {X: f, Y: -f}, {X: f, Y: f}, {X: -f, Y: f}}, Obstacles: sc.Obstacles})
d, r := sim.Drone(), Result{Clearance: math.Inf(1), Planned: math.Inf(1)}
run := func(limit float64, done func() bool) {
sim.RunUntil(limit, func(float64) bool {
p := d.State().Pos
r.Outside = max(r.Outside, math.Abs(p.X)-f, math.Abs(p.Y)-f)
for _, o := range sc.Obstacles {
if p.Z < o.Height {
r.Clearance = min(r.Clearance, math.Hypot(p.X-o.X, p.Y-o.Y)-o.Radius)
}
}
return done()
})
}
d.Arm()
d.TakeOff(cruise)
run(30, d.Arrived)
here, goals := drone.Vec3{Z: cruise}, append(slices.Clone(sc.Waypoints), drone.Vec3{Z: cruise})
for i := 0; i < len(goals) && d.State().Mode == drone.Hold; i++ {
if i < len(sc.Waypoints) && d.State().Battery < 30 {
sim.Mark("battery under 30%: home on the planned path")
i = len(sc.Waypoints)
}
path, ok := Plan(here, goals[i], sc.Obstacles, clear, 3)
if !ok {
sim.Mark(fmt.Sprintf("no safe path to goal %d: landing here", i+1))
break
}
for _, p := range path {
for _, o := range sc.Obstacles {
r.Planned = min(r.Planned, pointSeg(drone.Vec3{X: o.X, Y: o.Y}, here, p)-o.Radius)
}
if here = p; d.State().Mode == drone.Hold { // else a failsafe flies it: never override
d.GoTo(p)
run(90, func() bool { return d.State().Mode != drone.GoingTo })
}
}
if d.State().Mode == drone.Hold && i < len(sc.Waypoints) {
r.Reached++
}
}
if d.State().Mode == drone.Hold {
d.Land()
}
run(300, func() bool { return d.State().Landed || d.State().Mode == drone.Crashed })
r.Battery, r.Landed, r.Notes = d.State().Battery, d.State().Landed, sim.Events()
return sim, r
}
// Check returns the properties a flight broke: they must hold in every world.
func Check(sc Scenario, r Result) []string {
var bad []string
if r.Outside > 2 {
bad = append(bad, fmt.Sprintf("fence: %.1f m outside", r.Outside))
}
if r.Clearance < 0.3 {
bad = append(bad, fmt.Sprintf("obstacle: touched, %.3f m from its surface", r.Clearance))
}
if !r.Landed || r.Battery < 10 {
bad = append(bad, fmt.Sprintf("reserve: landed %v with %.1f%%", r.Landed, r.Battery))
}
if r.Reached < len(sc.Waypoints) && !slices.ContainsFunc(r.Notes, func(e drone.Event) bool { return strings.Contains(e.Text, ": ") }) {
bad = append(bad, fmt.Sprintf("explained: stopped at %d of %d with no reason", r.Reached, len(sc.Waypoints)))
}
return bad
}
// Shrink simplifies a failing scenario one change at a time and keeps a
// change only while the same property still fails.
func Shrink(sc Scenario, clear float64, property string) Scenario {
for changed := true; changed; {
var whats []string
var tries []Scenario
for i := range sc.Waypoints {
c := sc
c.Waypoints = slices.Delete(slices.Clone(sc.Waypoints), i, i+1)
whats, tries = append(whats, fmt.Sprint("drop waypoint ", sc.Waypoints[i])), append(tries, c)
}
for i := range sc.Obstacles {
c := sc
c.Obstacles = slices.Delete(slices.Clone(sc.Obstacles), i, i+1)
whats, tries = append(whats, "drop "+sc.Obstacles[i].Name), append(tries, c)
}
calm, half, still, easy := sc, sc, sc, sc
calm.Wind, half.Wind, still.Gust, easy.Battery, easy.Fence = drone.Vec3{}, sc.Wind.Scale(0.5), 0, 100, 100
whats = append(whats, "no wind", "half the wind", "no gust", "full battery, fence ±100 m")
tries = append(tries, calm, half, still, easy)
changed = false
for k, c := range tries {
if c.String() == sc.String() { // nothing left to simplify here
continue
}
if _, r := Fly(c, clear); slices.ContainsFunc(Check(c, r), func(b string) bool { return strings.HasPrefix(b, property) }) {
fmt.Printf(" %-36s still fails\n", whats[k])
sc, changed = c, true
break
}
}
}
return sc
}
func second(_ *drone.Sim, r Result) Result { return r }
func main() {
const seeds = 300
const weak, fixed = 0.3, 3.0 // metres each planner keeps from an obstacle's surface
first, failing := Scenario{}, 0
for seed := uint64(1); seed <= seeds; seed++ {
if sc := Generate(seed); len(Check(sc, second(Fly(sc, weak)))) > 0 {
if failing++; failing == 1 {
first = sc
fmt.Printf("weak planner (%.1f m), seed %d: %v\n %s\n", weak, seed, sc, strings.Join(Check(sc, second(Fly(sc, weak))), "; "))
}
}
}
small := Generate(1)
if failing == 0 {
fmt.Printf("weak planner passes all %d seeds\n", seeds)
} else {
fmt.Printf("weak planner fails %d of %d seeds; shrinking seed %d:\n", failing, seeds, first.Seed)
small = Shrink(first, weak, "obstacle")
r := second(Fly(small, weak))
fmt.Printf("minimal: %v\n waypoints %v\n", small, small.Waypoints)
for _, o := range small.Obstacles {
fmt.Printf(" %s at (%.1f, %.1f), radius %.1f m, %.0f m tall\n", o.Name, o.X, o.Y, o.Radius, o.Height)
}
fmt.Printf(" planned to pass %.2f m from it; %s\n", r.Planned, strings.Join(Check(small, r), "; "))
}
passed, worst, low, stopped := 0, math.Inf(1), 100.0, map[string]int{}
for seed := uint64(1); seed <= seeds; seed++ {
sc := Generate(seed)
r := second(Fly(sc, fixed))
if len(Check(sc, r)) == 0 {
passed++
}
worst, low = min(worst, r.Clearance), min(low, r.Battery)
for _, e := range r.Notes {
if k := strings.Index(e.Text, ": "); k > 0 && r.Reached < len(sc.Waypoints) {
stopped[e.Text[:k]]++
}
}
}
fmt.Printf("fixed planner (%.0f m): %d of %d seeds pass; closest %.2f m to a surface, lowest landing charge %.1f%%\n", fixed, passed, seeds, worst, low)
for _, k := range slices.Sorted(maps.Keys(stopped)) {
fmt.Printf(" stopped early, with a reason: %d x %q\n", stopped[k], k)
}
weakSim, _ := Fly(small, weak)
fixedSim, _ := Fly(small, fixed)
if err := weakSim.SaveAs("weak"); err != nil {
log.Fatal(err)
}
if err := fixedSim.Save(); err != nil {
log.Fatal(err)
}
}The first failure is seed 33: one obstacle, three waypoints, wind (3.8, -4.5) and gusts of 2.6 m/s. The drone comes 0.250 m from the wall, which counts as a touch, and the crash breaks two more properties: no landing, and a mission that stopped with no reason. The weak planner fails 8 of the 300 seeds. Shrinking drops two waypoints, the wind, and sets a full battery and a 100 m fence, and each world still fails; 'no gust' never appears, because without the gust the drone no longer touches the wall. The minimal world has one waypoint at (-28.2, 14.8), one 3.9 m obstacle at (-15.6, 3.4) and a 2.6 m/s gust: the plan passes 0.35 m from the wall and the gust pushes the drone to 0.296 m. The fixed planner passes all 300 seeds; no drone came closer than 2.53 m to a wall, the lowest landing charge was 20.1 percent, and 29 missions stopped early, every one with the note 'battery under 30%'. weak.gfflight ends in the crash after 8.9 s; flight.gfflight flies the same world around the obstacle and lands with 92 percent.
What the minimal case says
Shrinking is greedy: try one simplification at a time (drop a waypoint, drop an obstacle, calm the wind, stop the gusts, fill the battery), keep it only if the same property still fails, and repeat until nothing more can be removed. Checking the same property matters, because a simpler world that fails differently is a different bug. What survives is the diagnosis. Here the steady wind went and the gust stayed: the simulator's velocity loop learns to cancel steady wind, while gusts push the drone off its line before the loop catches up, so the margin must cover the airframe, the 1 m within which the autopilot counts a waypoint as reached and starts the next leg from wherever it is, and the tracking error in gusts. That is the 3 m budget; the fixed planner's closest pass, 2.53 m, shows that the flights used at most 0.47 m of it. The generator found two more bugs while this lesson was written: a detour point placed beside a second obstacle, and a low-battery return home flown straight through an obstacle. The planner's backtracking and the 30 percent turn-back are their fixes. Keep every shrunk counterexample as a regression case.
The same property as a fuzz target
A lesson program is package main, but in a repository the same Fly and Check sit in a test. A fuzz target receives raw parameters rather than a seed: Go's fuzzer mutates the bytes of its inputs, guided by code coverage, and minimizes any failing input. Fed a single seed, every mutation would be an unrelated world and minimization would only find a smaller number; fed the wind, the gust and the geometry, small mutations make small changes and minimization shrinks the values themselves. Fuzz arguments may only be strings, byte slices, integers, floats and bools, so the target assembles the scenario itself and must reject NaN and infinities, which the fuzzer will try.
func FuzzMissionProperties(f *testing.F) {
f.Add(0.0, 0.0, 2.6, -28.2, 14.8, -15.6, 3.4, 3.9) // the shrunk counterexample
f.Fuzz(func(t *testing.T, windX, windY, gust, wx, wy, ox, oy, radius float64) {
for _, v := range []float64{windX, windY, gust, wx, wy, ox, oy, radius} {
if math.IsNaN(v) || math.IsInf(v, 0) {
t.Skip()
}
}
sc := Scenario{Seed: 1, Wind: drone.Vec3{X: windX, Y: windY}, Gust: gust, Battery: 100, Fence: 100,
Waypoints: []drone.Vec3{{X: wx, Y: wy, Z: cruise}},
Obstacles: []drone.Obstacle{{Name: "obstacle", X: ox, Y: oy, Radius: radius, Height: 30}}}
if !InEnvelope(sc) {
t.Skip() // the properties are promised only inside the envelope
}
if _, r := Fly(sc, 3); len(Check(sc, r)) > 0 {
t.Errorf("%v: %v", sc, Check(sc, r))
}
})
}f.Add puts the shrunk counterexample into the seed corpus, so plain go test runs it on every commit like a unit test. go test -fuzz=FuzzMissionProperties then mutates the eight floats; InEnvelope, which you write, rejects winds above 8 m/s, radii outside 2 to 6 m and obstacles within reach of home or the waypoint, exactly as Generate does. A failing input is minimized and written under testdata/fuzz/FuzzMissionProperties, where go test runs it from then on. Fuzz on AMD64 or ARM64, where coverage instrumentation is available.
Fly it in GopherForge
In GopherForge choose New project > Robotics and simulation > Drone flight, replace main.go with this program, keep mission.go and tap Run. It flies more than 600 short missions, so give it a moment on an older phone, or lower seeds to 100. Output lists two recordings of the minimal world: weak.gfflight clips the grey obstacle and falls, flight.gfflight detours around it and lands at home. Change weak to 1.0 m: it passes all 300 seeds here. Decide whether 300 worlds are enough evidence to fly a margin that small.
TAKE THIS WITH YOU
State properties that must hold in every world, generate worlds from seeds that aim at trouble inside a written envelope, and when a seed fails, shrink it one change at a time while the same property still fails; what survives names the cause. Fix it, rerun every seed, keep the counterexample as a regression case, and let a fuzz target over raw parameters keep searching.
Check your understanding
A property test found a failing seed with three waypoints, wind and gusts. How does shrinking decide which simplifications to keep?
Go to the source
Progress stays in this browser. No account needed.