{"slug": "tsonnet-48-the-devil-in-the-details-4", "title": "Tsonnet #48 - The devil in the details #4", "summary": "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.", "body_md": "Welcome to the [Tsonnet](https://gitlab.com/bitmaybewise/tsonnet) series!\n\nIf 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).\n\nIn the previous post, we replaced the proactive cycle-checking AST walk with on-demand detection during translation:\n\nThat 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.\n\n`test/test_env.ml` carried a hand-written generator for `expr`:\n\n``` js\nlet rec gen_expr_sized n =\n  if n <= 0\n    then QCheck.Gen.oneofl [Unit]\n    else\n      QCheck.Gen.frequency [\n        (1, QCheck.Gen.return Unit);\n        (1, QCheck.Gen.map (fun pos -> Null pos) pos_gen);\n        (1, QCheck.Gen.map2 (fun pos n -> Number (pos, n)) pos_gen gen_number);\n        ...\n        (2, QCheck.Gen.map2\n          (fun pos exprs -> Array (pos, exprs))\n          pos_gen\n          (QCheck.Gen.list_size (QCheck.Gen.int_range 0 3) (gen_expr_sized (n-1))));\n        ...\n      ]\n```\n\nAcross the 22 constructors of `expr`, it produced 13: `Unit`, `Null`, `Number`, `Bool`, `String`, `Ident`, `Array`, `ParsedObject`, `BinOp`, `UnaryOp`, `Local`, `Seq`, `IndexedExpr`.\n\nNever produced: `If`, `Closure`, `FunctionDef`, `FunctionCall`, `ObjectFieldAccess`, `EvaluatedObject`, `RuntimeObject`, `ObjectPtr`, `LazyDefault`. `object_entry` had the same problem — only `ObjectField` and `ObjectExpr`, never `ObjectConditionalField`.\n\nThose 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.\n\nA property that holds over 13 of 22 constructors is still a true property. It is just not the property the green tick implies.\n\nThe generator was hand-written in `test/` for a reason. `lib/ast.ml` used to derive it:\n\n```\ndiff --git a/lib/ast.ml b/lib/ast.ml\nindex 4d5ec4d..4301795 100644\n--- a/lib/ast.ml\n+++ b/lib/ast.ml\n@@ -20,19 +20,19 @@ type bin_op =\n   | In\n   | ShiftLeft\n   | ShiftRight\n-  [@@deriving qcheck, show]\n+  [@@deriving show]\n\n type unary_op =\n   | Plus\n   | Minus\n   | Not\n   | BitwiseNot\n-  [@@deriving qcheck, show]\n+  [@@deriving show]\n\n type number =\n   | Int of int\n   | Float of float\n-  [@@deriving qcheck, show]\n+  [@@deriving show]\n```\n\nWhich meant the library was preprocessed by a testing ppx:\n\n```\ndiff --git a/lib/dune b/lib/dune\nindex 22e9961..3d34ffd 100644\n--- a/lib/dune\n+++ b/lib/dune\n@@ -4,7 +4,7 @@\n   (backend bisect_ppx))\n  (libraries yojson)\n  (preprocess\n-  (pps ppx_deriving.show ppx_deriving_qcheck)))\n+  (pps ppx_deriving.show)))\n\n (menhir\n  (modules parser))\n```\n\nThe binary that interprets Jsonnet was being preprocessed with `ppx_deriving_qcheck` and depending on `qcheck-core`. I wanted that gone.\n\nDeriving 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.\n\nOCaml lets you re-export a type together with its representation:\n\n```\nopen Tsonnet__Ast\n\nmodule Env = Tsonnet__Env\n\ntype expr = Tsonnet__Ast.expr =\n  (* terminal variants can appear in any stage, representable in the final JSON *)\n  | Unit\n  | Null of position\n  | Number of position * number\n  | Bool of position * bool\n  | String of position * string\n  | EvaluatedObject of position * ((string * expr) list\n      [@gen (gen_small_list (QCheck.Gen.pair QCheck.Gen.string (gen_expr_sized (n / 2))))])\n\n  (* interpreted variants were parsed, interpreted and transformed,\n    but are not terminal, and are waiting to be transformed into terminal variants *)\n  | Ident of position * string\n  | Array of position * (expr list [@gen (gen_small_list (gen_expr_sized (n / 2)))])\n  | ParsedObject of position * (object_entry list\n      [@gen (gen_small_list (gen_object_entry_sized (n / 2)))])\n  | RuntimeObject of position * (expr Env.Map.t [@gen gen_expr_env_map])\n      * (ObjectFields.t [@gen gen_object_fields])\n  ...\n[@@deriving qcheck]\n```\n\nThe 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.\n\nIt 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.\n\nThe deriver runs in the test stanza only:\n\n```\ndiff --git a/test/dune b/test/dune\nindex 933f549..c7e1ac0 100644\n--- a/test/dune\n+++ b/test/dune\n@@ -1,3 +1,5 @@\n-(tests\n- (names test_env test_interpreter test_type)\n- (libraries tsonnet alcotest qcheck-core qcheck-alcotest))\n+(test\n+ (name test_main)\n+ (libraries tsonnet alcotest qcheck-core qcheck-alcotest)\n+ (preprocess\n+  (pps ppx_deriving_qcheck)))\n```\n\n`show_expr` readable\nTwo 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`.\n\n```\ndiff --git a/lib/ast.ml b/lib/ast.ml\nindex 4d5ec4d..4301795 100644\n--- a/lib/ast.ml\n+++ b/lib/ast.ml\n@@ -82,6 +82,9 @@ type expr =\n   | Ident of position * string\n   | Array of position * expr list\n   | ParsedObject of position * object_entry list\n+  (* [@opaque] is consumed by [ppx_deriving.show] (ppxlib accepts the bare form\n+     for [deriving.show.opaque]): it keeps env maps and ids out of [show_expr]\n+     debug output. It is not a QCheck attribute -- generators live in test/. *)\n   | RuntimeObject of position * (expr Env.Map.t [@opaque]) * ObjectFields.t\n   | ObjectPtr of (Env.env_id [@opaque]) * object_scope\n   | ObjectFieldAccess of position * object_scope * expr list\n```\n\n`[@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. \n\nWith 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.\n\nSo `test/test_ast_gen.ml` ends with a coverage guard. It samples the generator once, walks every node, and counts tags:\n\n``` js\nlet sample_stats () =\n  let st = fresh () in\n  let gen = QCheck.Gen.sized (fun n -> gen_expr_sized (min n 3)) in\n  let values =\n    QCheck.Gen.generate ~rand:(Random.State.make [| 42 |]) ~n:samples gen\n  in\n  List.iter (fun e -> st.max_depth := max !(st.max_depth) (visit_expr st e)) values;\n  st\n```\n\n`samples` is 2000, and the seed is fixed so the report is reproducible.\n\nCounting tags needs a tag function, and that function is deliberately exhaustive:\n\n```\n(* Single source of tag names. Exhaustive on purpose: adding a constructor to\n   the AST is a compile error here instead of a silent hole in [expected_*]. *)\nlet tag_of_expr : expr -> string = function\n  | Unit -> \"Unit\"\n  | Null _ -> \"Null\"\n  | Number _ -> \"Number\"\n  ...\n  | LazyDefault _ -> \"LazyDefault\"\n```\n\n`visit_children` is a second exhaustive match, so a new constructor breaks compilation in two more places before any test runs.\n\nThe expected lists are split by provenance, because the generator reaches nodes that parsed input never produces:\n\n```\n(* Tags reachable from parsed source: every one of these is built by\n   [lib/parser.mly]. *)\nlet source_expr_tags = [\n  \"Null\"; \"Number\"; \"Bool\"; \"String\"; \"Ident\"; \"Array\"; \"ParsedObject\";\n  \"ObjectFieldAccess\"; \"BinOp\"; \"UnaryOp\"; \"Local\"; \"Seq\"; \"IndexedExpr\";\n  \"FunctionDef\"; \"FunctionCall\"; \"Closure\"; \"If\";\n]\n\n(* Tags the interpreter fabricates internally, never seen in parsed input.\n   The generator reaches them, but with empty/dummy payloads (see\n   [test_pinned_payloads]); real ones are covered by interpreter fixtures. *)\nlet interpreted_expr_tags = [\n  \"Unit\"; \"EvaluatedObject\"; \"RuntimeObject\"; \"ObjectPtr\"; \"LazyDefault\";\n]\n```\n\nThe comparison runs in both directions:\n\n``` php\nlet missing expected tbl = List.filter (fun k -> count tbl k = 0) expected\n\nlet unexpected expected tbl =\n  List.filter (fun k -> not (List.mem k expected)) (observed tbl)\n```\n\nA 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.\n\nSame treatment for the nested types: `object_entry`, `call_arg`, `object_scope`, `bin_op`, `unary_op`, `number`.\n\nTwo things about the derived generator were unusable as-is, both of them exponential.\n\nThe 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:\n\n```\n(* A bounded list generator: without this, the derived generator would use\n   [QCheck.Gen.list] (which sizes lists up to 10_000 elements) for every\n   recursive list field, blowing up the generated AST size exponentially. *)\nlet gen_small_list elems = QCheck.Gen.list_size (QCheck.Gen.int_range 0 3) elems\n```\n\nThe 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.\n\nThe 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.\n\n```\n(* The derived [gen_expr] uses [QCheck.Gen.sized] with an unbounded fuel, but\n   the code generated by [ppx_deriving_qcheck] allocates ~15x more per recursion\n   level (the [frequency] branches are rebuilt as fresh closures at every node),\n   so a fuel much above 3 makes generation unbearably slow. Capping the fuel to\n   3 keeps generation fast while every [expr] variant remains reachable. *)\nlet arbitrary_expr =\n  QCheck.make (QCheck.Gen.sized (fun n -> gen_expr_sized (min n 3)))\n```\n\nCapping 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:\n\n```\n(* The generator is capped with [min n 3] and ppx_deriving_qcheck halves the\n   size on every recursion level, so ~4 is the deepest tree it can build. *)\nlet test_nesting_depth () =\n  report ();\n  let st = Lazy.force st in\n  Alcotest.(check bool) \"generator nests at least 4 levels deep\" true (!(st.max_depth) >= 4)\n```\n\nThree generators are pinned to constants:\n\n``` js\nlet gen_position : position QCheck.Gen.t = QCheck.Gen.return dummy_pos\n\nlet gen_env_id : Env.env_id QCheck.Gen.t =\n  QCheck.Gen.map (fun i -> Env.EnvId i) QCheck.Gen.int\n\nlet gen_expr_env_map = QCheck.Gen.return Env.Map.empty\n\nlet gen_object_fields = QCheck.Gen.return ObjectFields.empty\n```\n\nPositions 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.\n\nRather than leave a comment claiming more than the generator does, the guard asserts the gap:\n\n```\n(* PAYLOAD GAPS: the payload generators are pinned to constants for now, so\n   these counts are 0 and [RuntimeObject] is only present structurally (empty\n   fields, empty env). Asserting the current behaviour keeps the suite green;\n   when the generators start producing real positions/envs/fields these fail and\n   the checks must be flipped back. Real interpreted nodes are covered by the\n   interpreter fixtures, not by this generator. *)\nlet test_pinned_payloads () =\n  report ();\n  let st = Lazy.force st in\n  Alcotest.(check int) \"RuntimeObject fields pinned to empty\"\n    0 !(st.runtime_obj_with_fields);\n  Alcotest.(check int) \"env maps pinned to empty\"\n    0 !(st.exprs_with_env);\n  Alcotest.(check int) \"positions pinned to dummy_pos\"\n    0 (Hashtbl.length st.positions)\n```\n\nThe 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.\n\nOnce `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.\n\nEach file now exposes a `tests` value:\n\n``` js\nlet tests = [\n  \"find_var\", [\n    test_case \"Undefined variable\" `Quick test_undefined_variable;\n    QCheck_alcotest.to_alcotest test_lookup;\n  ];\n  \"add_local_when_not_present\", [\n    test_case \"adds new variable when not present\" `Quick test_add_local_when_not_present_adds_new_variable;\n    test_case \"preserves existing variable when present\" `Quick test_add_local_when_not_present_preserves_existing_variable;\n  ];\n]\n```\n\nAnd a single entry point runs all of them:\n\n```\n(* Single entry point for the test suite.\n\n   Each module exposes a [tests] value instead of calling [Alcotest.run]\n   itself. That keeps all suites in one process, so test modules can share\n   helpers (e.g. [Test_ast_gen.arbitrary_expr]) without a module initializer\n   calling [Alcotest.run] and exiting before the other suites run. *)\n\nlet () =\n  Alcotest.run \"Tsonnet\"\n    (List.concat [\n       Test_ast_gen.tests;\n       Test_env.tests;\n       Test_interpreter.tests;\n       Test_type.tests;\n     ])\n```\n\nThe 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.\n\nWith `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.\n\n```\ndiff --git a/dune-project b/dune-project\nindex 69a3134..6985049 100644\n--- a/dune-project\n+++ b/dune-project\n@@ -40,11 +40,12 @@\n     :with-test\n     (= 0.25)))\n   (ppxlib\n-   (and\n-    :with-test\n-    (= 0.36.0)))\n+   (= 0.36.0))\n+  (ppx_deriving\n+   (= 6.1.1))\n   (ppx_deriving_qcheck\n-   (and :with-test))\n+   (and :with-test\n+        (= 0.7)))\n   ; (bisect_ppx\n   ;  (and\n   ;   :with-test\ndiff --git a/tsonnet.opam b/tsonnet.opam\nindex 4383c08..e751815 100644\n--- a/tsonnet.opam\n+++ b/tsonnet.opam\n@@ -16,8 +16,9 @@ depends: [\n   \"alcotest\" {with-test & >= \"1.8.0\" & < \"2.0.0\"}\n   \"qcheck-core\" {with-test & = \"0.25\"}\n   \"qcheck-alcotest\" {with-test & = \"0.25\"}\n-  \"ppxlib\" {with-test & = \"0.36.0\"}\n-  \"ppx_deriving_qcheck\" {with-test}\n+  \"ppxlib\" {= \"0.36.0\"}\n+  \"ppx_deriving\" {= \"6.1.1\"}\n+  \"ppx_deriving_qcheck\" {with-test & = \"0.7\"}\n   \"yojson\" {>= \"2.2.2\" & < \"3.0.0\"}\n   \"odoc\" {with-doc}\n ]\n```\n\n`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.\n\n``` bash\n$ dune test --force\nqcheck random seed: 172489963\nTesting `Tsonnet'.\nThis run has ID `F64A8FDW'.\n\n  [OK]          reachability                        0   every source-level ex...\n  [OK]          reachability                        1   every interpreter-onl...\n  [OK]          reachability                        2   no unlisted expr cons...\n  [OK]          reachability                        3   every nested construc...\n  [OK]          generation quality                  0   nesting depth.\n  [OK]          generation quality                  1   pinned payloads.\n  ...\n  [OK]          translate_object                    6   nested object preserv...\n\nFull test results in `_build/default/test/_build/_tests/Tsonnet'.\nTest Successful in 0.139s. 24 tests run.\n```\n\nAlcotest captures stdout per test, so the coverage report does not land in the terminal. It ends up next to the test:\n\n``` bash\n$ cat _build/default/test/_build/_tests/Tsonnet/reachability.000.output\n2000 samples, max depth 4\nsource-level expr missing: none\ninterpreter-only expr missing: none\nexpr generated but unlisted: none\nexpr 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\nobject_entry missing: none\ncall_arg missing: none\nobject_scope missing: none\nbin_op missing: none\nunary_op missing: none\nnumber missing: none\ndistinct non-dummy positions: 0\nRuntimeObject with non-empty fields: 0\nexprs carrying a non-empty env: 0\n```\n\nEvery constructor present, none unlisted, depth 4. The last three zeroes are the debt.\n\nThe 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.\n\nDuplicating the type declaration is ugly. Uglier is a suite that confidently tests the AST ignoring type variants.\n\nThe entire diff can be seen [here](https://gitlab.com/-/snippets/6070130).\n\nThanks for reading Bit Maybe Wise! The generator now covers every constructor — your inbox has no such guarantee. [Subscribe](https://bitmaybewise.com/) and get sampled.\n\nPhoto by [Zulfugar Karimov](https://unsplash.com/@zulfugarkarimov) on [Unsplash](https://unsplash.com)", "url": "https://wpnews.pro/news/tsonnet-48-the-devil-in-the-details-4", "canonical_source": "https://dev.to/bitmaybewise/tsonnet-48-the-devil-in-the-details-4-17nj", "published_at": "2026-12-04 01:10:27+00:00", "updated_at": "2026-12-04 01:16:25.989792+00:00", "lang": "en", "topics": ["developer-tools", "ai-tools"], "entities": ["Tsonnet", "OCaml", "QCheck", "Jsonnet", "ppx_deriving_qcheck"], "also_reported_by": [], "takeaway": "Re-exporting the AST type with its representation and attaching per-constructor generator attributes in the test module forces the generator to cover all 22 expr variants, unlike a hand-written generator that silently skipped nine.", "recommendation": {"advice": "Derive or exhaustively match test-data generators against the full type so every constructor is exercised; a hand-written generator can silently skip variants and make property tests pass on partial coverage.", "playbook": "evals-testing", "playbook_url": "https://wpnews.pro/playbooks/evals-testing"}, "alternates": {"html": "https://wpnews.pro/news/tsonnet-48-the-devil-in-the-details-4", "markdown": "https://wpnews.pro/news/tsonnet-48-the-devil-in-the-details-4.md", "text": "https://wpnews.pro/news/tsonnet-48-the-devil-in-the-details-4.txt", "jsonld": "https://wpnews.pro/news/tsonnet-48-the-devil-in-the-details-4.jsonld"}}