Write generators, properties, and state machines in Lean. Hegel generates inputs, shrinks failures, and saves counterexamples for the next run.
import Hegel
open Hegel Hegel.Property
@[hegel_test] def reverseTwice : Property Unit :=
property% (fun xs : List Nat => xs.reverse.reverse == xs)
def main : IO UInt32 := runTests hegel_suite%The frontend uses native libhegel 0.43.1 and Lean 4.36.0. It includes typed generator builders, finite enumeration and filtering, native recursion budgets, source-aware assertions, resource management, pools, sequential and concurrent state machines, forks, structured reports, and persistent replay. The port inventory maps the reference API's feature families to Lean implementations, tests, and explicit language adaptations.
V2 adds deriving Arbitrary, size-aware default generators, dependent data and proof-carrying
subtypes, and compiler-checked test registration. See Lean integration
for examples and supported types. The complete v1 API remains available, and its stable
baseline is preserved at v1.0.0.
Install elan, a C compiler, Python 3, and curl. On macOS, install the Xcode command-line tools. No Haskell toolchain, Rust compiler, or testing server is needed. The first build downloads the platform's static engine archive and header and checks both SHA-256 hashes against engine-lock.json. Cached builds work offline.
git clone https://github.com/alok/hegel-lean.git
cd hegel-lean
lake build hegel_tests hegel_examples
lake test
lake exe hegel_examples
lake exe hegel_examples fail # deliberately fails and shrinks n to 5The supported platforms are Linux x86-64, Linux ARM64, and Apple Silicon macOS. CI tests all three. Windows and Intel macOS are not supported by the build integration.
In another Lake project using the same Lean toolchain:
require «hegel-lean» from git "https://github.com/alok/hegel-lean" @ "main"The immutable v2.0.0 release uses Lean 4.34.0; current main uses Lean 4.36.0.
Run lake update and commit lake-manifest.json to retain the resolved revision. Engine fetching
and native linking propagate to the consumer's executable. Properties run in compiled Lake
executables; the native engine is not loaded into the editor's #eval process.
Mark your test executable with @[test_driver] in lakefile.lean and use
runTests hegel_suite% as its main : IO UInt32. lake test then runs all imported
@[hegel_test] properties. The complete Lean example also demonstrates
derived generators with dependent proof fields: lake exe hegel_lean_examples.
Gen α supports pure, <$>, <*>, and dependent do notation. Public composition records
shrinking spans. Finite alternatives retain enumeration metadata, allowing Gen.filtered and
Gen.mapMaybe to eliminate impossible alternatives before drawing.
| Family | API |
|---|---|
| Numbers | Gen.bool, arbitrary-precision int and nat, signed and unsigned machine widths, float, float32 |
| Text and binary | char, text, bytes, regex, email, url, domain, uri, uuid |
| Alphabets | Unicode categories, explicit inclusion/exclusion, codecs, and named character sets |
| Collections | Lists, arrays, fixed vectors, nonempty lists, unique collections, ordered and hash maps/sets |
| Alternatives | Finite choice, weighted choice, options, pairs, static filtering, bounded dynamic filtering |
| Time | Validated dates, times and datetimes; exact arbitrary-precision picosecond durations |
| Recursion | Explicit depth-bounded recursion or native shared depth/leaf budgets |
| Typed builders | Gen.Builder constructors with type-directed bounds, sizes, alphabets, and recursion modifiers |
def interval : Gen (Int × Int) := do
let lo ← Gen.int (-1000) 1000
let hi ← Gen.int lo (lo + 100)
return (lo, hi)Gen.fin and Gen.vector return values with checked bound and length proofs. Functions can also
be generated by mapping ordinary values to closures; use draw when the result lacks Repr.
Finite enumeration is optional metadata, not a promise to enumerate infinite domains.
Direct low-level generators preserve their existing error API. Invalid configurations in the new builders and higher-level generators produce stable, shrinkable validation failures. Engine invariants and native-handle errors abort the campaign. See generator details.
forAll! records generated values, while draw omits their representation. assert!,
assertEq!, assertNe!, assertProp!, and failure! capture source locations. Their failure
origins include the Lean module and source position, avoiding absolute checkout paths in replay
identities. Explicit-origin assertThat, assertEq, assertNe, and assertProp remain available.
def bounded : Property Unit := do
let n ← forAll! (Gen.int 0 100)
assert! (n < 5) because "expected a small number"
def inspect : IO Unit := do
let report ← check "bounded" bounded { seed := some 42, database := none }
IO.println (← report.renderRich)
for failure in report.failures do
if !failure.blob.isEmpty then
IO.println (reprStr (← replay failure.blob bounded))This property shrinks to n = 5. Blobs require the same engine version and compatible property
code. Changing an assertion's location or the order of draws can invalidate earlier replay.
checkreturns aReportdistinguishing passing, failing, engine/error, and nondeterministic outcomes. Evidence distinguishes reconstructed counterexamples from observations without replay.check!prints the report and raises an IO error for every non-passing outcome.runTestsreturns a process exit code and fits a Lake test driver.- Campaigns with no valid examples cannot pass, including when rejection health checks are suppressed or the selected phases execute nothing.
resource acquire releaseandregisterFinalizerrelease per-case resources in reverse order after workers settle. Every cleanup is attempted. Cleanup errors retain the original evidence and stop the campaign before further execution.annotate,footnote, structural diffs, source excerpts, pool lineage, and worker/round notes support plain, styled, ASCII, and Unicode reporting.Property.ioruns effects on each execution, including shrinking and replay. Reset mutable state in case setup.targetguides generation toward larger finite scores.sampledraws exactly one case and raises an error if it rejects.samplescollects from one generation-only campaign; finite-space exhaustion can return fewer values than requested.
The default database is .hegel/examples, keyed by a stable test name. Set database := none
for ephemeral tests. Settings also controls phases, seed/derandomization, backend, verbosity,
stateful step count, clone depth, health checks, multiple failures, and engine output.
Report.evaluations includes shrinking executions and excludes final evidence reconstruction.
Stateful.Machine combines initial state, weighted rules, and invariants. The native engine
selects rules, rejects unavailable actions, and shrinks action sequences. Pool α tracks values
that rules create, reuse, consume, and transfer, with their lineage retained in reports.
Stateful.Concurrent adds concurrency bounds and rule groups. Dedicated OS threads retain one
cloned engine stream per worker across rounds. A round joins before root-thread invariants run;
rules in different groups do not overlap.
Property.Branch offers pairs, mapping, replication, and bounded fan-out. Bounded replication
caps both active workers and native clones. Results retain input order and every branch settles
before a failure returns. Property.Fork offers spawn, join,
poll, cancel, and scoped. Polling does not discharge a fork's join-or-cancel obligation;
a fork left open after a normal return is a malformed test. Early failure, discard, or exhaustion
cancels and settles open forks while preserving the original outcome and cleanup diagnostics.
Choice streams can replay; real-time thread interleavings cannot be guaranteed to replay. When
the engine reports a nondeterministic failure without a blob, the observed journal is retained.
Cancellation uses Lean's cooperative task cancellation at draw and Property.io boundaries.
A worker blocked forever inside foreign IO cannot be forcibly interrupted by Lean. Shared state
must use suitable synchronization, and clone creation must occur in a consistent order.
See the v1 validation record for suite coverage and the concrete audit fixes. The v2 validation details cover deriving, proof-carrying shrinking, test registration, and downstream Lake use. The November 30 maintenance record covers the libhegel 0.53.2 compatibility tests, evaluation counts and shrinking results.
lake test executes the real pinned engine. Tests cover bounds, enumeration, native recursion,
shrinking minima, exact replay, persistence, source identities, cleanup, pool lifecycle,
sequential schedules, concurrent overlap, worker groups, and error propagation.
python3 scripts/check_ffi.py # compile against every Lean-emitted native prototype
python3 scripts/test_safety.py # unchecked Lean panic must fail in a subprocess
python3 scripts/test_downstream.py # build and execute a separate Lake consumerDavid R. MacIver blog regressions include 13 scenarios across three seeds,
the 70-copies-of-10 stress case, dependent generators, Unicode, and distinct NaN/empty-list
failures. Two discovery probes retain observed coverage misses rather than treating them as
proofs of coverage. CI uploads machine-readable receipts. Run lake exe hegel_maciver_tests
for this suite alone.
The native bridge checks thread ownership, case-family identity, closed handles, and string lengths, including embedded NULs. Each native allocation has an explicit matching release; external-object finalizers provide fallback cleanup.
Lean checks frontend types and proof fields. This is not a formal verification of the engine
or C bridge. Native code, the compiler/runtime, and the ABI remain trusted. Starting a campaign
enables Lean's process-wide fatal-panic policy: an unchecked panic! or out-of-bounds get!
terminates the executable with failure rather than supplying a default value and reporting a
false pass. Ordinary property assertion failures still shrink and replay.
CI runs on pushes, pull requests, manual dispatch, and weekly. Engine updates are deliberate:
python3 scripts/update_engine.py --dry-run # inspect the proposed lock
python3 scripts/update_engine.py
lake build hegel_tests hegel_examples
lake test
python3 scripts/check_ffi.py
python3 scripts/test_safety.py
python3 scripts/test_downstream.pyReview upstream changes and all platform results before accepting a new pin. Engine source,
release tag, artifact URLs, and hashes are recorded in engine-lock.json; builds never silently
follow upstream main. The current engine source
is pinned for inspection. New releases are discovered in the
engine monorepo; legacy libhegel-v* tags
remain available through --tag, and existing locked downloads keep their original URLs.
MIT licensed. See LICENSE and the engine's license. This is an independent frontend.
The API and behavioral contracts were informed by Mercury Technologies' Haskell zizek client at 6b25365, and the regression scenarios by David R. MacIver's writing on property-based testing.