Tsonnet #48 - The devil in the details #4 A developer building Tsonnet, an OCaml Jsonnet interpreter, discovered that the hand-written QCheck generator in test/test_env.ml only produced 13 of the AST's 22 expr constructors, silently skipping nine variants including If, Closure, FunctionDef, FunctionCall and LazyDefault, so property tests passed without ever exercising them. The fix re-exports the AST type from the library with representation exposed and attaches per-variant generator attributes in the test module, keeping the qcheck dependency out of the production build while enforcing generator coverage against the type definition. Welcome to the Tsonnet https://gitlab.com/bitmaybewise/tsonnet series If you're not following along, check out how it all started in the first post of the series https://dev.to/bitmaybewise/tsonnet-0-from-zero-to-interpreter-54na . In the previous post, we replaced the proactive cycle-checking AST walk with on-demand detection during translation: That post was about cycles the type checker could not see. This one is about tests that could not see the AST — and unlike the cycles, no one was ever going to get an error message for it. test/test env.ml carried a hand-written generator for expr : js let rec gen expr sized n = if n <= 0 then QCheck.Gen.oneofl Unit else QCheck.Gen.frequency 1, QCheck.Gen.return Unit ; 1, QCheck.Gen.map fun pos - Null pos pos gen ; 1, QCheck.Gen.map2 fun pos n - Number pos, n pos gen gen number ; ... 2, QCheck.Gen.map2 fun pos exprs - Array pos, exprs pos gen QCheck.Gen.list size QCheck.Gen.int range 0 3 gen expr sized n-1 ; ... Across the 22 constructors of expr , it produced 13: Unit , Null , Number , Bool , String , Ident , Array , ParsedObject , BinOp , UnaryOp , Local , Seq , IndexedExpr . Never produced: If , Closure , FunctionDef , FunctionCall , ObjectFieldAccess , EvaluatedObject , RuntimeObject , ObjectPtr , LazyDefault . object entry had the same problem — only ObjectField and ObjectExpr , never ObjectConditionalField . Those nine are exactly the variants the last posts added. Each one landed in lib/ast.ml , compiled, passed the suite, and left the generator untouched. Every QCheck property in that file quantified over the 13 constructors the generator remembered, and the checkmarks were honest about it. A property that holds over 13 of 22 constructors is still a true property. It is just not the property the green tick implies. The generator was hand-written in test/ for a reason. lib/ast.ml used to derive it: diff --git a/lib/ast.ml b/lib/ast.ml index 4d5ec4d..4301795 100644 --- a/lib/ast.ml +++ b/lib/ast.ml @@ -20,19 +20,19 @@ type bin op = | In | ShiftLeft | ShiftRight - @@deriving qcheck, show + @@deriving show type unary op = | Plus | Minus | Not | BitwiseNot - @@deriving qcheck, show + @@deriving show type number = | Int of int | Float of float - @@deriving qcheck, show + @@deriving show Which meant the library was preprocessed by a testing ppx: diff --git a/lib/dune b/lib/dune index 22e9961..3d34ffd 100644 --- a/lib/dune +++ b/lib/dune @@ -4,7 +4,7 @@ backend bisect ppx libraries yojson preprocess - pps ppx deriving.show ppx deriving qcheck + pps ppx deriving.show menhir modules parser The binary that interprets Jsonnet was being preprocessed with ppx deriving qcheck and depending on qcheck-core . I wanted that gone. Deriving in lib/ enforces the generator against the AST but drags a test library into the production build. Writing the generator by hand in test/ keeps the dependency clean but enforces nothing. I picked neither for four posts, and the nine missing constructors are the price paid. OCaml lets you re-export a type together with its representation: open Tsonnet Ast module Env = Tsonnet Env type expr = Tsonnet Ast.expr = terminal variants can appear in any stage, representable in the final JSON | Unit | Null of position | Number of position number | Bool of position bool | String of position string | EvaluatedObject of position string expr list @gen gen small list QCheck.Gen.pair QCheck.Gen.string gen expr sized n / 2 interpreted variants were parsed, interpreted and transformed, but are not terminal, and are waiting to be transformed into terminal variants | Ident of position string | Array of position expr list @gen gen small list gen expr sized n / 2 | ParsedObject of position object entry list @gen gen small list gen object entry sized n / 2 | RuntimeObject of position expr Env.Map.t @gen gen expr env map ObjectFields.t @gen gen object fields ... @@deriving qcheck The compiler checks this declaration against Tsonnet Ast.expr constructor by constructor, field by field, including arities and field names. Add a variant upstream without adding it here and test/test ast gen.ml stops compiling. That is the enforcement I lost when the deriver left lib/ , recovered without the dependency. It is a duplicate of the type definition, and I'm inclined to keep it, because it is what avoids the drift we have at the moment. The deriver runs in the test stanza only: diff --git a/test/dune b/test/dune index 933f549..c7e1ac0 100644 --- a/test/dune +++ b/test/dune @@ -1,3 +1,5 @@ - tests - names test env test interpreter test type - libraries tsonnet alcotest qcheck-core qcheck-alcotest + test + name test main + libraries tsonnet alcotest qcheck-core qcheck-alcotest + preprocess + pps ppx deriving qcheck show expr readable Two variants now carry runtime payloads that are useless in an assertion message: RuntimeObject holds an expr Env.Map.t , and ObjectPtr holds an Env.env id . diff --git a/lib/ast.ml b/lib/ast.ml index 4d5ec4d..4301795 100644 --- a/lib/ast.ml +++ b/lib/ast.ml @@ -82,6 +82,9 @@ type expr = | Ident of position string | Array of position expr list | ParsedObject of position object entry list + @opaque is consumed by ppx deriving.show ppxlib accepts the bare form + for deriving.show.opaque : it keeps env maps and ids out of show expr + debug output. It is not a QCheck attribute -- generators live in test/. | RuntimeObject of position expr Env.Map.t @opaque ObjectFields.t | ObjectPtr of Env.env id @opaque object scope | ObjectFieldAccess of position object scope expr list @opaque is ppx deriving.show 's, not QCheck's. QCheck's counterpart is @gen ... , and it lives in the test re-export because that is where the deriver runs. Same bracket syntax, two different ppxs, one of which is not allowed in lib/ anymore. With the re-export, a generator branch for every constructor exists by construction. That is shape. Nothing yet says the branch is ever sampled , and nothing says the payload generators are worth sampling. gen position currently returns dummy pos , for instance — reachable, and useless. So test/test ast gen.ml ends with a coverage guard. It samples the generator once, walks every node, and counts tags: js let sample stats = let st = fresh in let gen = QCheck.Gen.sized fun n - gen expr sized min n 3 in let values = QCheck.Gen.generate ~rand: Random.State.make | 42 | ~n:samples gen in List.iter fun e - st.max depth := max st.max depth visit expr st e values; st samples is 2000, and the seed is fixed so the report is reproducible. Counting tags needs a tag function, and that function is deliberately exhaustive: Single source of tag names. Exhaustive on purpose: adding a constructor to the AST is a compile error here instead of a silent hole in expected . let tag of expr : expr - string = function | Unit - "Unit" | Null - "Null" | Number - "Number" ... | LazyDefault - "LazyDefault" visit children is a second exhaustive match, so a new constructor breaks compilation in two more places before any test runs. The expected lists are split by provenance, because the generator reaches nodes that parsed input never produces: Tags reachable from parsed source: every one of these is built by lib/parser.mly . let source expr tags = "Null"; "Number"; "Bool"; "String"; "Ident"; "Array"; "ParsedObject"; "ObjectFieldAccess"; "BinOp"; "UnaryOp"; "Local"; "Seq"; "IndexedExpr"; "FunctionDef"; "FunctionCall"; "Closure"; "If"; Tags the interpreter fabricates internally, never seen in parsed input. The generator reaches them, but with empty/dummy payloads see test pinned payloads ; real ones are covered by interpreter fixtures. let interpreted expr tags = "Unit"; "EvaluatedObject"; "RuntimeObject"; "ObjectPtr"; "LazyDefault"; The comparison runs in both directions: php let missing expected tbl = List.filter fun k - count tbl k = 0 expected let unexpected expected tbl = List.filter fun k - not List.mem k expected observed tbl A one-way check only sees constructors that vanished from the generator. It cannot see a constructor that was added to the AST and immediately generated, which is precisely the case the re-export creates. The derived generator emits the new branch on the next run, observed picks up a tag that expected does not know, and the test fails before the hole becomes a habit. Same treatment for the nested types: object entry , call arg , object scope , bin op , unary op , number . Two things about the derived generator were unusable as-is, both of them exponential. The first: recursive list fields get QCheck.Gen.list , which sizes lists up to 10 000 elements. Every level multiplies, so a tree of Array nodes explodes. The fix is a @gen override on each recursive list field: A bounded list generator: without this, the derived generator would use QCheck.Gen.list which sizes lists up to 10 000 elements for every recursive list field, blowing up the generated AST size exponentially. let gen small list elems = QCheck.Gen.list size QCheck.Gen.int range 0 3 elems The size still has to shrink with depth, so each field asks for gen expr sized n / 2 . That belongs in the attribute because the deriver gives you no other handle on a per-field generator. The second: fuel. QCheck.Gen.sized hands the generator an unbounded size, and the code ppx deriving qcheck emits rebuilds its frequency branches as fresh closures at every node — roughly fifteen times the allocation per recursion level. A fuel above 3 makes generation take long enough that the coverage suite becomes something I skip. The derived gen expr uses QCheck.Gen.sized with an unbounded fuel, but the code generated by ppx deriving qcheck allocates ~15x more per recursion level the frequency branches are rebuilt as fresh closures at every node , so a fuel much above 3 makes generation unbearably slow. Capping the fuel to 3 keeps generation fast while every expr variant remains reachable. let arbitrary expr = QCheck.make QCheck.Gen.sized fun n - gen expr sized min n 3 Capping fuel is the kind of fix that quietly turns a coverage test into a shallow-tree test, so there is an assertion that the cap still produces something: The generator is capped with min n 3 and ppx deriving qcheck halves the size on every recursion level, so ~4 is the deepest tree it can build. let test nesting depth = report ; let st = Lazy.force st in Alcotest. check bool "generator nests at least 4 levels deep" true st.max depth = 4 Three generators are pinned to constants: js let gen position : position QCheck.Gen.t = QCheck.Gen.return dummy pos let gen env id : Env.env id QCheck.Gen.t = QCheck.Gen.map fun i - Env.EnvId i QCheck.Gen.int let gen expr env map = QCheck.Gen.return Env.Map.empty let gen object fields = QCheck.Gen.return ObjectFields.empty Positions are all dummy pos , environments are all empty, object fields are all empty. So RuntimeObject is generated in name only: the constructor shows up in the tree, with nothing inside it. The guard proves reachability, not realism. Rather than leave a comment claiming more than the generator does, the guard asserts the gap: PAYLOAD GAPS: the payload generators are pinned to constants for now, so these counts are 0 and RuntimeObject is only present structurally empty fields, empty env . Asserting the current behaviour keeps the suite green; when the generators start producing real positions/envs/fields these fail and the checks must be flipped back. Real interpreted nodes are covered by the interpreter fixtures, not by this generator. let test pinned payloads = report ; let st = Lazy.force st in Alcotest. check int "RuntimeObject fields pinned to empty" 0 st.runtime obj with fields ; Alcotest. check int "env maps pinned to empty" 0 st.exprs with env ; Alcotest. check int "positions pinned to dummy pos" 0 Hashtbl.length st.positions The day those generators improve, this test fails instead of passing quietly with a stale comment. A coverage guard that documents its own gaps is worth more than one that claims coverage it does not have. Once test env.ml needed Test ast gen.arbitrary expr , the three-binary layout stopped working. Each module ended with its own Alcotest.run , which calls exit at module initialisation, so two modules cannot share a helper in the same process. Each file now exposes a tests value: js let tests = "find var", test case "Undefined variable" Quick test undefined variable; QCheck alcotest.to alcotest test lookup; ; "add local when not present", test case "adds new variable when not present" Quick test add local when not present adds new variable; test case "preserves existing variable when present" Quick test add local when not present preserves existing variable; ; And a single entry point runs all of them: Single entry point for the test suite. Each module exposes a tests value instead of calling Alcotest.run itself. That keeps all suites in one process, so test modules can share helpers e.g. Test ast gen.arbitrary expr without a module initializer calling Alcotest.run and exiting before the other suites run. let = Alcotest.run "Tsonnet" List.concat Test ast gen.tests; Test env.tests; Test interpreter.tests; Test type.tests; The rest of the test env , test interpreter , and test type diffs is that mechanical last-line change. I'm intentionally dropping those hunks to keep this post cleaner. With ppx deriving qcheck gone from lib/dune , the build broke. lib/dune had been requesting ppx deriving.show for a while, but ppx deriving was never declared as a dependency of the project. It resolved because ppx deriving qcheck depends on ppx deriving = 6.1.0 , and that package was declared :with-test . A test-only dependency was propping up the production preprocess. diff --git a/dune-project b/dune-project index 69a3134..6985049 100644 --- a/dune-project +++ b/dune-project @@ -40,11 +40,12 @@ :with-test = 0.25 ppxlib - and - :with-test - = 0.36.0 + = 0.36.0 + ppx deriving + = 6.1.1 ppx deriving qcheck - and :with-test + and :with-test + = 0.7 ; bisect ppx ; and ; :with-test diff --git a/tsonnet.opam b/tsonnet.opam index 4383c08..e751815 100644 --- a/tsonnet.opam +++ b/tsonnet.opam @@ -16,8 +16,9 @@ depends: "alcotest" {with-test & = "1.8.0" & < "2.0.0"} "qcheck-core" {with-test & = "0.25"} "qcheck-alcotest" {with-test & = "0.25"} - "ppxlib" {with-test & = "0.36.0"} - "ppx deriving qcheck" {with-test} + "ppxlib" {= "0.36.0"} + "ppx deriving" {= "6.1.1"} + "ppx deriving qcheck" {with-test & = "0.7"} "yojson" { = "2.2.2" & < "3.0.0"} "odoc" {with-doc} ppxlib and ppx deriving lose :with-test because lib/dune needs them; ppx deriving qcheck keeps it, pinned to 0.7, because only test/dune uses it now. A clean clone would have failed long before this post. My switch had the package installed and dune was happy to use it. bash $ dune test --force qcheck random seed: 172489963 Testing Tsonnet'. This run has ID F64A8FDW'. OK reachability 0 every source-level ex... OK reachability 1 every interpreter-onl... OK reachability 2 no unlisted expr cons... OK reachability 3 every nested construc... OK generation quality 0 nesting depth. OK generation quality 1 pinned payloads. ... OK translate object 6 nested object preserv... Full test results in build/default/test/ build/ tests/Tsonnet'. Test Successful in 0.139s. 24 tests run. Alcotest captures stdout per test, so the coverage report does not land in the terminal. It ends up next to the test: bash $ cat build/default/test/ build/ tests/Tsonnet/reachability.000.output 2000 samples, max depth 4 source-level expr missing: none interpreter-only expr missing: none expr generated but unlisted: none expr counts: Null=631, Number=617, Bool=601, String=594, Ident=627, Array=144, ParsedObject=146, ObjectFieldAccess=148, BinOp=156, UnaryOp=163, Local=136, Seq=148, IndexedExpr=148, FunctionDef=136, FunctionCall=161, Closure=158, If=173, Unit=588, EvaluatedObject=148, RuntimeObject=148, ObjectPtr=152, LazyDefault=150 object entry missing: none call arg missing: none object scope missing: none bin op missing: none unary op missing: none number missing: none distinct non-dummy positions: 0 RuntimeObject with non-empty fields: 0 exprs carrying a non-empty env: 0 Every constructor present, none unlisted, depth 4. The last three zeroes are the debt. The AST deriver lives in the test suite now, and adding a variant is a compile error in lib/ast.ml , in the re-export, in tag of expr , and in visit children . Drift stopped being a thing I have to remember. Duplicating the type declaration is ugly. Uglier is a suite that confidently tests the AST ignoring type variants. The entire diff can be seen here https://gitlab.com/-/snippets/6070130 . Thanks for reading Bit Maybe Wise The generator now covers every constructor — your inbox has no such guarantee. Subscribe https://bitmaybewise.com/ and get sampled. Photo by Zulfugar Karimov https://unsplash.com/@zulfugarkarimov on Unsplash https://unsplash.com