Jon Reyna

distributed systems & AI infrastructure

Proving a rewrite against the C original

by Jon Reyna

A filter generator for BGP routers is the wrong place to guess whether a rewrite agrees with the original. I compiled C bgpq3 and ran it beside Go bgpsieve on 200 deterministic cases and 6 live queries. Along the way, the oracle caught a bug in the C code.

I.Why an oracle, not unit tests§

Network engineers use bgpq3, written and maintained by Alexandre Snarskii (2007–2026), to turn Internet Routing Registry (IRR) records into router prefix lists and AS-path filters.1 A bad filter on a border router drops customer traffic or leaks a full table to a peer, so nobody swaps out a filter generator on faith.

When I rewrote bgpq3 in Go as bgpsieve to get a standard-library Go package, concurrency safety, and an HTTP service (bgpsieved), unit tests alone weren’t enough. Unit tests check what I think the spec says. For a drop-in command covering nine router formats and 39 short flags, the spec is 4,756 lines of C in bgpq3 (v0.1.38), four files of which (bgpq3.c, bgpq_expander.c, sx_prefix.c, and bgpq3_printer.c) carry almost all of the behavior.

The cleanest proof is differential testing: compile the real C binary, put both commands in front of the same mock IRR server, feed them identical flags and fixtures, and fail if stdout or the exit status differs by a single byte.

II.What exact aggregation has to preserve§

The hardest part of bgpq3 to match isn’t the IRR wire protocol (!i, !g, !6 over TCP port 43) or the vendor syntax.2 It’s exact prefix-list aggregation (-A), which shrinks a filter without changing which routes the router accepts.

Write S(p) for the set of IP addresses covered by a prefix p of length |p|, and write (p,[a,b]) for a prefix-list entry that matches any prefix q with S(q)⊆S(p) and a≤|q|≤b. When two sibling prefixes p0 and p1 of length ℓ+1 share a parent p of length ℓ, their address sets partition S(p):

S ( p0 ) ∪ S ( p1 ) = S ( p ) , S ( p0 ) ∩ S ( p1 ) = ∅ . (1)

Because of (1), if a router’s filter permits both (p0,[a,b]) and (p1,[a,b]) with the same bounds [a,b], then replacing both entries with (p,[a,b]) matches the exact same set of routes. If p itself was also in the input (and a=ℓ+1), the combined range widens to (p,[ℓ,b]). What if p is an exact entry and its children carry a disjoint range [a,b] with a>ℓ+1? Then p stays exact, and the merged range attaches to p as a secondary son entry so the printer emits both lines without inventing any intermediate lengths.

Algorithm A (Exact prefix-list aggregation).

Given the root node n of a binary Patricia radix tree of prefixes, this post-order pass compacts sibling entries into equivalent prefix-length ranges.

  1. A1.[Recurse.]

    If n has a left child, run Algorithm A on n.left. If n has a right child, run Algorithm A on n.right.

  2. A2.[Check siblings.]

    Let ℓ=|n.prefix|. If either child is missing, or if either child does not have prefix length ℓ+1, return.

  3. A3.[Merge exact children.]

    If both children are active exact prefixes (neither glue nor aggregate), mark both children as glue and set n to an aggregate with upper bound ℓ+1. Set n’s lower bound to ℓ+1 if n was glue, or to ℓ if n was already active. If both children also carry matching son ranges, promote one copy to n.son.

  4. A4.[Merge matching ranges.]

    Otherwise, if both children (or one child and the other’s son) are active aggregates with identical bounds [a,b], mark both as glue. If n is glue, copy [a,b] onto n; else if a=ℓ+1, promote n to [ℓ,b]; otherwise attach [a,b] as n.son.

    ▮

In Go (radix/tree_aggregate.go), step A2 and the branch dispatch fit in one short function:

func (t *Tree) aggregateNode(n *node) {
	if n.left != nil {
		t.aggregateNode(n.left)
	}
	if n.right != nil {
		t.aggregateNode(n.right)
	}
	if n.left == nil || n.right == nil {
		return
	}
	nBits := uint8(n.prefix.Bits())
	childBits := int(nBits) + 1
	l, r := n.left, n.right
	if l.prefix.Bits() != childBits ||
		r.prefix.Bits() != childBits {
		return
	}
	// Merge exact siblings, matching ranges, or son chains.
	t.mergeSiblings(n, l, r, nBits)
}

The second aggregation flag, -H (hyper-aggregation), runs Algorithm A first and then makes a top-down pass that keeps only the highest active supernet on each path and discards every more-specific descendant. Unlike -A, -H is intentionally lossy: it shrinks the list further by permitting sub-prefixes that were not registered individually.

III.Wiring the C binary into go test§

The differential suite lives in internal/oracle/diff_test.go and runs on every pull request in CI. A small build script compiles the pinned C bgpq3 commit (v0.1.38) into .cache/bin/bgpq3, and TestCOracleDifferentialSuite builds cmd/bgpsieve into a temporary directory and starts an in-process mock IRRd server (irrdtest.Server).

Both binaries talk to that same loopback TCP port with -h 127.0.0.1:<port>. The mock fixtures cover nested AS-sets, circular references (AS-CYC-A and AS-CYC-B), EXCEPT stoplists, -L depth caps, multi-source shadowing (RIPE vs. RADB), 32-bit and special ASNs (AS23456, AS64512), route-sets with RPSL range operators (^+, ^-, ^25-26), and empty sets.

cOut, cErr, cCode := runCLI(t, cBin, args, tc.env)
goOut, goErr, goCode := runCLI(t, goBin, args, tc.env)

if tc.expectFail {
	if cCode <= 0 || goCode != 1 {
		t.Fatalf("exit mismatch: c=%d go=%d", cCode, goCode)
	}
	return
}
if tc.jsonEqual {
	assertJSONSemanticallyEqual(t, cOut, goOut)
	return
}
if goOut != cOut {
	t.Fatalf("mismatch for %v:\nC:\n%sGo:\n%s",
		args, cOut, goOut)
}

Table 1 summarizes the suite as it runs on every commit, alongside the polite live smoke suite (test/integration/live_irrd_test.go) that runs six small queries against rr.ntt.net:43.

Table 1. Differential checks between C bgpq3 (v0.1.38) and Go bgpsieve.

SuiteCasesComparisonNetwork
Router formats & flags 171 Exact byte-for-byte stdout 103 via mock IRRd
JSON output (-j) 10 Parsed JSON deep equality Mock IRRd / static
Invalid flag combinations19Both exit non-zeroNone
Live IRRd smoke (rr.ntt.net) 6 Exact byte-for-byte stdout Live TCP 43

IV.When the oracle itself is wrong§

A differential test only tells you that two programs disagree; it doesn’t tell you which one is right. Early on, almost every diff pointed to a subtle detail I had missed in Go: an extra trailing space in a vendor’s empty-list fallback, how -a and -f interact depending on flag order, or the exact regex grouping of Cisco and JunOS AS-path filters.

Eight times, though, reading the C source behind a diff showed a real bug in bgpq3 v0.1.38. Rather than reproduce crashes or silent data loss, I documented and tested those eight divergences separately in TestIntentionalCBugFixes.

One of them turned up only because the oracle tested a combination I hadn’t thought to audit by hand. In mixed address-family mode (-x, supported on JunOS, JSON, and -F), bgpq3 passed maxlen = 0 to sx_prefix_range_parse when parsing IPv6 prefix ranges such as 2001:db8:2::/48^49-49. The parser clamped the upper bound to zero and silently dropped the route from the generated filter.

The other seven were just as concrete: an /65535 typo in the ASN table that mis-indexed AS65535; -F reading before the format pointer on a trailing \n; an uninitialized maximum length on single-length ranges like ^25; Cisco and Huawei -f 0 emitting deny .* for a single ASN; Cisco extended ACLs printing host 0.0.0.0 instead of host 255.255.255.255 for a /32; leading-zero IPv4 octets from RADB being parsed as octal (010.0.0.0/24 turning into 8.0.0.0/24); and Nokia classic -NG omitting its closing exit and commit.

V.What the oracle doesn’t prove§

Matching a single-shot CLI proves the core math, expansion, and formatting, and it let me add features bgpq3 never had (bogon stripping, prefix caps, Go templates, and a public HTTP demo at bgpsieve.jonreyna.dev) without drifting from the baseline.3

It does not prove that a long-lived HTTP server survives hostile traffic. Putting bgpsieved on the internet took a separate round of fuzzing, race testing, and a security audit that caught memory-exhaustion paths, router-config injection in name and match, and per-IP rate-limit edge cases that a CLI tool never faces. The oracle gives you a floor for correctness; everything above the CLI still has to earn its keep on its own.

Exercises

  1. 1.[10]

    Why does the oracle compare -j JSON output by unmarshaling both documents instead of checking goOut == cOut, while every router-config vendor is compared byte for byte?

  2. ▸2.[M20]

    Prove that Algorithm A preserves the exact set of permitted prefixes, and give a two-prefix counterexample showing that hyper-aggregation (-H) does not.

  3. 3.[25]

    Suppose you add a new vendor formatter or flag to a drop-in rewrite and generate your differential test cases automatically. What failure mode does a blind “record C’s stdout as golden” harness miss, and how does the RS-MIXED-V6RANGE case illustrate it?

Answers to exercises

  1. 1.

    JSON allows arbitrary insignificant whitespace and key ordering, so two encoders can emit different bytes for the same data structure; reflect.DeepEqual on decoded values tests semantic equality without coupling the Go encoder to C’s formatting quirks. Router configs, by contrast, are often diffed line by line in GitOps pipelines or Ansible checks, so stray spaces or blank lines cause spurious config churn.

  2. 2.

    Each step in Algorithm A merges only when two siblings of length ℓ+1 cover both halves of their parent of length ℓ and carry the exact same length interval [a,b] (or both are exact ℓ+1 prefixes, which is [ℓ+1,ℓ+1]). By (1), a route q has S(q)⊆S(p) with a≤|q|≤b if and only if S(q)⊆S(p0) or S(q)⊆S(p1) with the same bounds (or q=p when p itself was active and the lower bound drops to ℓ). For -H, take the two prefixes 192.0.2.0/24 and 192.0.2.0/25: -A keeps them exact, whereas -H collapses them to 192.0.2.0/24 alone, dropping the /25 entry (or, with 192.0.2.0/25 and 192.0.2.128/25, -H emits 192.0.2.0/24 which permits /24 even though only the two /25s were in the input).

  3. 3.

    If you treat the C binary as infallible and auto-bless its output as ground truth, you faithfully clone its silent bugs too. In RS-MIXED-V6RANGE, C bgpq3 -x returned exit code 0 and valid JunOS config, simply omitting 2001:db8:2::/48^49-49. Catching that requires both independent assertions on expected prefixes and reading the C source whenever a diff appears.

  1. Alexandre Snarskii, bgpq3 (v0.1.38), BSD 2-Clause, at github.com/snar/bgpq3.  ↩

  2. IRRd’s persistent TCP mode starts with !!, selects sources with !s, expands AS-sets with !i<set>,1, and fetches IPv4 and IPv6 routes with !g<as> and !6<as>.  ↩

  3. The public demo at bgpsieve.jonreyna.dev runs bgpsieved on a five-node Raspberry Pi k3s cluster managed with Flux, behind a Cloudflare Tunnel. ↩