← Back to Demos & Examples

39_debugger_coverage_and_fuzzing.vk

Raw .vk
// examples/39_debugger_coverage_and_fuzzing.vk
// Demonstrates deterministic property fuzzing and automatic delta-debugging counterexample
// shrinking (`testing/fuzz`) across byte slices, UTF-8 strings, and homoiconic Veko blocks.

use [fz = testing/fuzz]

encode-tlv = fn [tag i64, payload bytes] bytes [
	mut out = bytes/with-cap (3 + (len payload))
	_ = bytes/push mut out (tag & 0xff)
	_ = bytes/push-u16-be mut out (len payload)
	_ = bytes/push-all mut out payload
	out
]

decode-tlv = fn [frame bytes] bytes [
	if (len frame) < 3 [ return (err 'truncated TLV header') ]
	plen = bytes/get-u16-be frame 1
	if (3 + plen) != (len frame) [ return (err 'TLV length mismatch') ]
	frame[3..(3 + plen)]
]

main = fn [] any [
	cfg = fz/FuzzConfig { seed = 20261203, runs = 120, max_len = 48 }

	// 1. Property holds: TLV round-trip preserves arbitrary byte slices
	tlv_ok = fz/fuzz-bytes cfg fn [raw bytes] any [
		dec = decode-tlv (encode-tlv 7 raw)
		if err? dec [ return dec ]
		bytes/eq dec raw
	]
	chk = fz/assert-fuzz tlv_ok 'tlv-roundtrip'
	if err? chk [ return chk ]

	// 2. Planted byte-parser bug: automatic delta-debugging shrinks random input down to 2 bytes!
	bug_bytes = fz/fuzz-bytes cfg fn [buf bytes] any [
		// Planted defect whenever any byte >= 0xC0 is followed anywhere by a byte >= 0x80
		mut seen_hi = false
		mut i = 0
		while i < (len buf) [
			if seen_hi and buf[i] >= 0x80 [
				return (err 'unhandled multi-byte marker')
			]
			if buf[i] >= 0xC0 [ seen_hi = true ]
			i = i + 1
		]
		true
	]
	if bug_bytes.ok or (len bug_bytes.shrunk_input) != 2 [
		return (err `expected 2-byte shrunk reproducer, got {mold bug_bytes}`)
	]

	// 3. Homoiconic block fuzzer shrinks nested block failure to 1-element minimal block `[.ping]`
	bug_blk = fz/fuzz-block cfg fn [blk block] any [
		mut i = 0
		while i < (len blk) [
			el = blk[i]
			if (type-of el) == .enum_sym and el == .ping [
				return (err 'unexpected .ping token in AST block')
			]
			i = i + 1
		]
		true
	]
	if bug_blk.ok or bug_blk.shrunk_input != [.ping] [
		return (err `expected shrunk block [.ping], got {mold bug_blk.shrunk_input}`)
	]

	println `[Example 39 OK] tlv_runs={tlv_ok.runs} | shrunk_bytes={len bug_bytes.shrunk_input}B | shrunk_block={mold bug_blk.shrunk_input}`
	0
]

main