================== Correctness checks ================== **Status:** implemented. The checks below run in CI through ``.github/workflows/correctness.yml`` and ``.github/workflows/c-cpp.yml``. This page describes four checks: sanitizer builds of the test suite, finite-difference checks of the kernel derivatives, fuzzers for the configuration/structure parsers and checked C API calls, and a comparison of a GP posterior with scikit-learn. Sanitizer builds ---------------- ``scripts/run_sanitizer_matrix.sh`` drives the sanitizer matrix: - always: AddressSanitizer + UndefinedBehaviorSanitizer - optional when the toolchain supports it: ThreadSanitizer and/or MemorySanitizer For every configured sanitizer build, the script runs the full meson suite and then reruns the C API executables (``test_capi_c99``, ``test_capi_surface``, ``test_capi_gp_neb`` and ``test_capi_periodic_band``) explicitly. Each libFuzzer target is then run for ``FUZZ_SECONDS`` seconds. The ASan matrix run defaults to ``ASAN_DETECT_LEAKS=1``. No leak is suppressed: a leak in gpridge code is fixed, and a leak in a subproject is fixed by a patch listed in that subproject's wrap file. .. code:: bash CC=clang CXX=clang++ FUZZ_SECONDS=300 SANITIZER_USE_OPENBLAS=false scripts/run_sanitizer_matrix.sh The Python tests run under the same sanitizers with ``scripts/run_sanitized_pytest.sh``, which takes a sanitized build tree configured with ``-Dwith_python=true`` and ``-Dwith_ira=false``: .. code:: bash CC=clang CXX=clang++ FC=gfortran meson setup build-sanitize-python \ --buildtype=debugoptimized -Db_lundef=false -Db_sanitize=address,undefined \ -Dwith_ira=false -Dwith_python=true -Dwith_tests=true -Duse_hdf5=false \ -Ddo_install=false scripts/run_sanitized_pytest.sh build-sanitize-python ``-Dwith_ira=false`` is required, as in the matrix. IRA is built with the Fortran compiler and links that compiler's sanitizer runtime, which is not the Clang runtime of the rest of the build, and ``gprn`` then aborts with "linked against incompatible ASan runtimes". ``meson setup`` refuses the combination and names the option. The script configures a missing build directory with these options, stops on an existing one that was configured differently, and builds the tree before it runs the tests. The interpreter is not instrumented, so the script preloads the two runtimes into it, writes the reports to files in the build tree and runs ``python/tests`` without the tests marked ``sanitizer_incompatible``. Those are ``test_core_tls.py``, which removes ``LD_PRELOAD`` on purpose, and ``test_docs_examples.py``, whose blocks start compilers and ``cargo`` that would inherit the preload; the Meson ``docs`` suite runs the same blocks. Leak detection is off for this run because the interpreter and NumPy keep allocations until exit. ``tests/sanitizers/ubsan.supp`` lists the one nanobind report that UndefinedBehaviorSanitizer raises, with its justification. AddressSanitizer + UndefinedBehaviorSanitizer can still be run directly: .. code:: bash CC=clang CXX=clang++ meson setup build-asan --buildtype=debugoptimized \ -Db_lundef=false -Db_sanitize=address,undefined \ -Dwith_ira=false -Dwith_tests=true -Duse_capnp=true -Drgpot:with_rpc=true \ -Dwith_fuzzers=true meson compile -C build-asan ASAN_OPTIONS=halt_on_error=1:detect_leaks=1 \ UBSAN_OPTIONS=halt_on_error=1:print_stacktrace=1 \ meson test -C build-asan Clang links the sanitizer runtime into each program and leaves its symbols undefined in a shared library, so the build needs ``-Db_lundef=false``. It also needs ``-Dwith_ira=false``, for the reason given above. With ``halt_on_error=1``, UndefinedBehaviorSanitizer stops a test at its first report, so the report fails the test instead of only printing a line. GCC 13 and 14 do not build this configuration. With the ``null``, ``nonnull-attribute`` or ``returns-nonnull-attribute`` check of ``-fsanitize=undefined``, GCC does not accept a ``static_assert`` that compares a pointer into a ``constexpr`` array with ``nullptr``, and rgpot's ``CxxLayout.cc`` has such assertions. Kernel properties ----------------- ``test_kernel_properties`` has three tests of 53 trials each, one trial for each bit of the binary64 significand. A failing sample is reproducible, because the inputs come from a ``std::mt19937_64`` engine with the default seed, which the C++ standard fixes. The first test checks the squared-exponential pullback kernel and the Matérn 5/2 kernel in three dimensions, and the second test checks the inverse-distance Sexpat kernel on a diatomic. For each kernel, these two tests compare the energy-gradient blocks with centred differences of the energy covariance and the gradient-gradient block with centred differences of a gradient-energy block. They also check that swapping the two inputs and their channels gives the same covariance. The third test compares the first and second derivatives of the pullback kernel with respect to the log length scale with centred differences. A difference quotient moves one coordinate ``x`` by the step :: h = cbrt(epsilon) max(1, |x|) where ``epsilon`` is the binary64 machine epsilon. A centred difference has a truncation error of order ``h^2`` and a roundoff error of order ``epsilon/h``, so this step makes both of order ``cbrt(epsilon)^2``. The test compares the quotient at ``h`` with the quotient at ``2h``, and the gap between them estimates the truncation error. The tolerance is that gap plus ``sqrt(epsilon) max(1, |q_h|, |q_2h|)`` for the roundoff, where ``q_h`` and ``q_2h`` are the two quotients. ``sqrt(epsilon)`` is about 406 times ``cbrt(epsilon)^2``, so this term leaves a wide margin. The symmetry check has a tolerance of ``gamma_n max(1, |k|, |k'|)`` for the two covariances ``k`` and ``k'``, where ``n`` is the number of coordinates and :: gamma_n = n u / (1 - n u) for the binary64 unit roundoff ``u = epsilon/2``. Configuration, structure and checked-C API fuzzers -------------------------------------------------- ``gprn`` reads its configuration from a file in Tom's Obvious, Minimal Language (TOML) or in the Cap'n Proto binary format. ``-Dwith_fuzzers=true`` builds a libFuzzer target for each format and needs Clang, ``-Duse_capnp=true`` and ``-Dwith_tests=true``. ``fuzz_toml_config`` writes each input to a file with the ``.toml`` suffix and loads it with ``gpr::io::loadInputParametersFromToml``. ``fuzz_binary_config`` writes each input to a file with the ``.bin`` suffix, opens it with ``gpr::io::UnifiedConfigMessage`` and copies the root of the message, which reads every field that the message reaches. ``gprn`` opens its configuration file with ``UnifiedConfigMessage``, which calls the TOML loader for a ``.toml`` file and maps any other file as Cap'n Proto words. The checked C ABI entry points in ``gpr/capi/gpridge_c.h`` each have a dedicated fuzzer target: - ``fuzz_capi_train_checked`` - ``fuzz_capi_update_checked`` - ``fuzz_capi_predict_checked`` - ``fuzz_capi_predict_variance_checked`` - ``fuzz_capi_predict_full_checked`` - ``fuzz_capi_predict_batch_checked`` - ``fuzz_capi_predict_hessian_action_checked`` - ``fuzz_capi_prediction_supported_checked`` Each harness exercises short buffers, NaN/Inf payloads, zero or negative dimensions, and untrained-model calls. ``fuzz_structure_con`` covers user-provided structure parsing by feeding ``.con`` inputs through ``readcon::rkr_read_first_frame`` and ``gpr::io::loadAtomsConfigurationFromFrame``. A parser that rejects an input with an exception gives the expected outcome, and the fuzzer moves on to the next input. A sanitizer report, a leak, a crash or a ``std::bad_alloc`` ends the run, and libFuzzer writes the input that caused it to a file in the working directory. The seeds are under ``tests/fuzz/corpus/``. ``toml/representative`` sets every fixed table of :doc:`the configuration keys <../reference/config_keys>`, and ``test_capnp_neb_loader`` checks that the loader accepts it, so the fuzzer starts from an input that reaches every table. ``toml/minimal`` is an empty ``[band]`` table. ``toml/non-ascii-bare-key`` is the bare key ``bÞҤd_`` on a line of its own, on which the non-ASCII whitespace classifier of toml++ 3.4.0 reaches ``TOML_UNREACHABLE``. With the toml++ commit that ``subprojects/tomlplusplus.wrap`` pins, the loader reports a parse error for it. ``toml/date-times`` has one value of each TOML date and time type, with a space between the date and the time of the local date-time, so the fuzzer starts from inputs that reach the date and time parser. The loader parses that file and then rejects its four keys as unknown. ``toml/out-of-range-float`` is an input that ``fuzz_toml_config`` found. It sets ``nimages`` to a float of about 7.8e19, beyond the range of ``int64_t``. The pinned toml++ converts a float for an integer key to ``int64_t`` before any range check. That conversion is undefined for a value beyond the range of ``int64_t``. The loader therefore checks that the float is finite, whole and within the range of the key. Otherwise it throws ``gpr::io::ConfigValueRangeError`` before any conversion. ``test_capnp_neb_loader`` checks that the loader rejects this seed with that error. ``binary/word-aligned`` is a single zero word, which passes the whole-word size check and reaches the Cap'n Proto decoder. ``capi_checked/`` seeds the checked C API harnesses. ``structure/`` seeds the structure parser harness. The pre-commit hooks for trailing whitespace and final newlines skip ``tests/fuzz/corpus/``. Each seed therefore keeps its exact bytes. The fuzzers are part of the sanitizer build above, and they run from the source root: .. code:: bash mkdir -p build-asan/fuzz-corpus/toml build-asan/fuzz-corpus/binary export ASAN_OPTIONS=halt_on_error=1:detect_leaks=1 export UBSAN_OPTIONS=halt_on_error=1:print_stacktrace=1 build-asan/tests/fuzz_toml_config build-asan/fuzz-corpus/toml tests/fuzz/corpus/toml build-asan/tests/fuzz_binary_config build-asan/fuzz-corpus/binary tests/fuzz/corpus/binary Each fuzzer reads the inputs in both directories and writes each new input that reaches new code to the first one. It runs until it finds an error or until it is interrupted, and ``-max_total_time=SECONDS`` sets a time limit. Independent GP posterior ------------------------ ``python/tests/test_sklearn_reference_gp.py`` conditions a GP on the energies and gradients of three diatomic geometries and compares its posterior at a fourth geometry with ``sklearn.gaussian_process.GaussianProcessRegressor``. The GPRidge model has no output normalization and runs ``optimize`` with ``max_iter`` set to 0. That call conditions the model on the data, and even without iterations its first call fits the signal variance. The scikit-learn model therefore takes the signal variance, length scale, likelihood noise and jitter from the fitted GPRidge model. The three energies average to zero, which is the constant prior mean that GPRidge subtracts, so the scikit-learn prior has zero mean. GPRidge reports the variance of a noisy observation and scikit-learn reports the variance of the latent function, so the test adds the likelihood noise to the scikit-learn variance. The jitter is 1e-6, and each check runs at a likelihood noise of 1e-4 and of 1e-6. With the dense solver, the test compares the posterior mean and variance of the energy and of the six gradient components with scikit-learn. With the HS-SVD stable-basis solver, it compares the same mean and variance with those of the dense solver. Both fits must give the same signal variance, and the test checks that first. The scikit-learn kernel is a squared-exponential kernel on ``z = sqrt(2)/r``, extended with its derivatives with respect to the Cartesian coordinates. The Sexpat squared distance adds ``2 (1/r - 1/r')^2 / l^2`` for each atom pair, which equals ``(z - z')^2 / l^2``, so the two kernels agree. The comparison allows a relative error of :: kappa(K) gamma_n / (1 - kappa(K) gamma_n) where ``K`` is the training covariance with the noise and the jitter on its diagonal, ``n`` is the size of ``K`` and ``kappa(K)`` is its condition number. This bounds the relative error of the solution of a linear system with ``K`` when ``K`` carries a relative perturbation of at most ``gamma_n``, and the test never allows less than ``sqrt(epsilon)``. The error is relative to the largest component of the compared vector, so it also covers a component that is zero, such as the mean of a gradient component that the data do not excite. The comparison is at the fourth geometry because the HS-SVD basis of this fixture keeps 6 of its 21 components. At a training geometry, its variance gives each left-out component about 3.6e-12, the rounding level of its spectrum, which keeps the joint covariance positive semidefinite. At a noise of 1e-6 that exceeds the bound above, so ``HssvdDualVarianceMatchesDenseSexpat`` in ``tests/gpr/ml/GaussianProcessRegressionTest.cpp`` compares the two solvers at training geometries instead, with a basis that keeps every component. The Python bindings job of ``.github/workflows/c-cpp.yml`` runs the test with the rest of ``python/tests/``. CI -- ``.github/workflows/correctness.yml`` has two jobs. The workflow runs ``scripts/run_sanitizer_matrix.sh`` with Clang and ``FUZZ_SECONDS=300``. That script configures ASan+UBSan, then TSan and/or MSan where available, runs the full meson suite and explicit C API tests for each configured sanitizer, and finally fuzzes every parser and checked-C-API target for ``FUZZ_SECONDS`` seconds with ``halt_on_error=1``, ``detect_leaks=1`` and ``print_stacktrace=1``. Missing fuzz targets or sanitizer build failures are hard failures for the matrix job. Neither the ASan nor the TSan leg allowlists failing tests by default; optional overrides accept only explicit per-test-case names (``:``) and never allowlist process-exit or sanitizer reports. A longer local run keeps the same corpora and increases ``FUZZ_SECONDS``.