# Tsonnet #48 - The devil in the details #4

> Source: <https://dev.to/bitmaybewise/tsonnet-48-the-devil-in-the-details-4-17nj>
> Published: 2026-12-04 01:10:27+00:00

**Recommendation:** 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.
More in the playbook "Evals and testing for LLM apps": <https://wpnews.pro/playbooks/evals-testing>

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)
