# Backend conformance testing

The Numeric CI workflow runs `moon check --target all --deny-warn` and debug and release tests on wasm, wasm-gc, JavaScript and native. Native jobs use Linux GCC and macOS Clang with `-march=native -ffp-contract=off`; the build-plan gate checks the compiler path and contraction flag on every linked test artifact. Native package settings retain `-O2 -fwrapv -fno-strict-aliasing` because `cc-flags` overrides default optimization flags. Package settings apply at the native linking package, so downstream executable packages must repeat this policy; the library cannot enforce compiler flags on its consumers.

Each backend prints ordered `LUNA_BITS <case> <16 lowercase hex digits>` records. The gate rejects missing, duplicate, malformed, reordered or changed records, checks every transcript against the committed oracle, and compares all ten backend, compiler and optimization-mode transcripts. Logs and bit transcripts are downloadable CI artifacts. The wasm-gc job also runs `moon test --enable-coverage` and publishes summary and Cobertura coverage reports. While the module has no library source outside test files, as in the current empty root API, there is nothing to instrument; the job then records that the report was skipped instead of failing.

The bootstrap corpus checks core binary64 bit transport (signed zeros, subnormal and normal boundaries, finite extremes and infinities), signed 64-bit conversion around ties at 2^53 and at the integer endpoints, and a non-fused multiply-add. It does not implement or certify future luna-utils numerical APIs. Add operation-specific probes and cross-check oracle fixtures alongside each new API. NaN payload transport and canonicalization are deliberately excluded until the API and canonicalization policy in issue #25 are defined; raw NaN equality is not promised by this corpus.

The offline generator `tools/generate_oracles.py` uses CPython IEEE binary64 `float(int)` and exact `fractions.Fraction` operands. It rounds the product before the sum for the contraction probe: `(1 + 2^-27) * (1 - 2^-27)` rounds to 1, and subtracting 1 yields positive zero; a single rounding instead yields -2^-54. The generated probe XORs each operand's bit pattern with a mask derived from the process argument count, which is zero at run time and asserted to be zero, so an optimizing C compiler cannot constant-fold the expression and the multiply-add is evaluated at run time in both debug and release builds. Building the probe with `-ffp-contract=fast` makes it fail in both modes with Apple Clang, confirming that it detects contraction rather than a value fixed at compile time; with a constant array of operands, release builds folded the expression and the probe passed even under `-ffp-contract=fast`. The relevant model is IEEE 754-2019 binary64, roundTiesToEven, separate multiplication and addition, and contraction control (§10.4). These finite samples establish regression evidence, not a universal proof or formal verification. ISO/IEC 10967-1 language-independent arithmetic does not override the specific IEEE representation and rounding model used here.

The integer-conversion suite keeps the generated source small: it embeds one table of inputs per format and loops over targets, modes and directions at run time instead of expanding every combination into source lines. Each input emits one `LUNA_BITS` record whose value is an FNV-1a fold of all results for that input (all four targets, all five directions plus the default functions, presence, checked value and saturating value), computed by the Python oracle from exact integer arithmetic and compared on every backend; each result is also checked individually against the exact rounded integer in the table so that a failure names the input, target, mode and direction. `.moonignore` keeps `testdata`, `tools`, `.github` and the `src/ci_probe` test package out of the published package (`moon package --list` shows what is shipped).

Run `python3 tools/generate_oracles.py --check`, `python3 tools/test_ci_harness.py` and `python3 tools/run_backend_tests.py <backend>` locally. Run `python3 tools/generate_oracles.py` only when intentionally updating the committed fixtures; MoonBit's formatter is required. The generator runs offline and introduces no package dependency. CI installs the pinned MoonBit toolchain version from its official installer (`MOONBIT_INSTALL_VERSION` in the workflow), records it and fails if the installed `moonc` differs; bump the pin deliberately and rerun every gate. Pushes run the workflow only on `main`; pull requests run it on every update. Fixture drift fails rather than updating expected values. Linux GCC and macOS Clang acceptance requires the hosted CI jobs, not a claim based solely on a local macOS run.

Sources: [official MoonBit native package options](https://docs.moonbitlang.com/en/latest/toolchain/moon/package.html#native-backend-link-options), [MoonBit contraction report #2262](https://github.com/moonbitlang/moon/issues/2262), and [Python numeric conversion documentation](https://docs.python.org/3/library/functions.html#float).

The #25 representation corpus is generated by `tools/float_oracles.py`, invoked by `tools/generate_oracles.py`. Python arbitrary-precision integer field extraction supplies expectations for both widths, all classes and signs, payload boundaries and portable numeric results. For #24 round-to-integral directions, an independent model decodes finite encodings to exact `fractions.Fraction` values, applies floor, ceiling, truncation or the specified tie rule, and re-encodes the integral result while preserving the sign of zero. It does not reproduce the implementation's exponent-mask algorithm. The generated test emits actual outputs as `LUNA_BITS`, with binary32 zero-extended to 64 bits, classification encoded by a documented test-only ID, and `None` encoded as all ones. The checked-in JSON records include inputs, calls and expected outputs.

For #23 extrema and ordering, the offline oracle constructs a boundary set containing signed zeros, the largest positive subnormal, the largest negative subnormal, `1.0`, the smallest negative normal, infinities, and positive and negative qNaN/sNaN encodings with payloads, including `+qNaN` payload 2, `-qNaN` payload 0, and both `+1` and `-1`. Python integer key transforms provide a cross-check for all-pairs raw totalOrder and portable numeric order; integer comparisons also determine minimum and maximum, which return a canonical positive quiet NaN when an input is NaN, while preserving signed-zero selection. All results are emitted as `LUNA_BITS` records and checked against every backend transcript.

## Randomized audit

The fixed corpora above pin chosen boundary cases. The randomized audit complements them with seeded cases for every public function of `float` and `float/binary32`. `tools/random_audit.py --seed S --count N --write` generates `src/ci_probe/random_audit_wbtest.mbt` (not committed) with inputs and expected results; every expected value comes from integer fields and exact `fractions.Fraction` arithmetic in the script, never from the library. The families are classification and predicates, NaN canonicalization, sign operations (raw and portable), payload get and set, raw and portable totalOrder, minimum and maximum, the five rounding directions of roundToIntegral, the sixteen integer conversions in all five directions (including the neighbours of `±2^31`, `2^32`, `±2^63` and `2^64`), sorting, and `Int64`/`UInt64` to binary32. Pairs are biased toward equal values, opposite signs, signed zeros, infinities and NaNs.

`tools/run_audit.py <backend> --seed S --count N` runs the test in debug and release on one backend and writes a transcript and a JSON summary to `_build/audit/`. A mismatch prints `LUNA_AUDIT <family> <case> <details>`. The same seed regenerates the same cases, so a failing nightly seed can be replayed locally. Pull requests run seed 1 with 400 cases per family on every backend; the nightly workflow runs a seed taken from the date with 20,000 cases per family on all five CI configurations.

Three further checks keep the audit honest. `tools/test_audit_models.py` checks the exact models against CPython's IEEE conversions. `tools/api_audit.py` fails when a public function in a generated `.mbti` file is not called by the audit. `tools/mutation_check.py` injects known bugs (a wrong tie rule, a range boundary one off, a flipped zero selection) and fails when the audit does not notice one. A mismatch that is understood and tracked can be listed in `tools/known_issues.json` with its issue; the report then shows it separately instead of failing, and prints a reminder when the entry stops reproducing. The nightly job aggregates all results with `tools/audit_report.py` into a Markdown report that is attached to the run and shown in its summary.

## Compiler matrix

The same optimization that makes release builds fast can change how a value is stored, and a miscompiled operation then shows only for one storage form on one backend and one mode. `tools/compiler_matrix.py` checks the numeric types Luna-Flow actually uses (`Int`, `UInt`, `Int64`, `UInt64`, `UInt16`, `Double`, `Float`, `Bool`, `Char`; `tools/usage_census.py` lists the counts behind that choice) in these storage forms: directly, in an `Option`, as an array element read with `get` or an index, in a `FixedArray`, a tuple, a struct field, an enum payload, a closure capture, a generic call, a mutable local, and as a compile-time constant. Each combination runs about two dozen conversions, shifts, arithmetic, bitwise, comparison and bit-count operations on boundary values (zero, one, the sign bit, the maximum, the minimum, `2^k ± 1`).

No expected value is computed. The result must not depend on the storage form, and debug and release builds must print the same cells. For the integer, `Bool` and `Char` types every backend must also agree; `Float` and `Double` follow each backend's own float implementation by design, so they are compared only across storage forms and between debug and release on the same backend. `tools/run_matrix.py <backend>` runs the matrix and the pull request CI and the daily workflow call it; `tools/audit_report.py` compares all backends in the daily report. A finding that is understood and tracked is listed under `matrix` in `tools/known_issues.json`.

On 2026-10-13 the matrix ran 18,084 cells on each of wasm, wasm-gc, js and native in debug and release (144,672 in total). The only finding was the tracked [native release `UInt?` payload bug](https://github.com/moonbitlang/core/issues/4388), seen in `to_uint64`, `to_double` and shifts of a `UInt` taken from an `Option` or from `Array::get`.

The host operations that every package builds on are audited as well, against exact models and without any luna-utils code under test. The `arith` families check `+`, `-`, `*`, `/` and `sqrt` of `Double` and `Float` (round to nearest even) on random encodings, powers of two that scale results into the subnormal and overflow ranges, cancellation, half-ulp addition ties and the overflow edge. The `conv_*` families check the integer to floating point conversions of core: `Int`, `UInt`, `Int64` and `UInt64` to `Double`, and `Int`, `UInt`, `Int64` and `UInt64` to `Float`. A 5,000-case run on wasm, wasm-gc, js and native in debug and release found no mismatch except the two tracked ones: `Int64` and `UInt64` to `Float` on js round twice because core follows the backend (listed in `tools/known_issues.json`), and the native release `UInt?` bug of [#42](https://github.com/Luna-Flow/luna-utils/issues/42).

The compiler matrix also checks one relation between operations instead of between storage forms: adding a literal `0.0` must give the same bits as adding a runtime zero. It reports that the compiler folds `x + 0.0` to `x` on every backend, which is wrong for `-0` ([#62](https://github.com/Luna-Flow/luna-utils/issues/62)); the finding is in `tools/known_issues.json`, where an entry may name `*` for the backend and mode and a `relation`.

