From 16d1c769afc67e06f07639f6fd9de8136974e282 Mon Sep 17 00:00:00 2001 From: Adam Getchell Date: Sat, 8 Aug 2026 09:02:12 -0700 Subject: [PATCH 1/4] feat(api)!: expose reported Metropolis transitions - return typed reports that distinguish candidate success from acceptance - add a compiled ten-proposal quickstart with replayable provenance - pin and validate the self-contained archival Doxygen site BREAKING CHANGE: attempt_transition(manifold, move, trial) now returns MetropolisTransition instead of bool; use .accepted() for the previous result. Closes #114 --- CMakeLists.txt | 3 + Justfile | 6 +- README.md | 60 ++- REFERENCES.md | 2 +- cmake/RunCppApiQuickstartTest.cmake | 58 +++ docs/Doxyfile | 18 +- docs/api-boundary.md | 27 ++ docs/arithmetic-backend-evaluation.md | 2 +- docs/comparison-harness.md | 2 +- docs/cpp-api-quickstart.md | 76 ++++ docs/metropolis-hastings.md | 10 +- docs/reproducibility.md | 2 + examples/CMakeLists.txt | 22 + examples/cpp_api_quickstart.cpp | 156 +++++++ include/Ergodic_moves_3.hpp | 30 ++ include/Foliated_triangulation.hpp | 203 +++++++-- include/Formatters.hpp | 10 +- include/Geometry.hpp | 1 + include/Manifold.hpp | 29 +- include/Metropolis.hpp | 133 +++++- include/Move_always.hpp | 12 +- include/Move_command.hpp | 27 +- include/Move_outcome.hpp | 77 +++- include/Move_run.hpp | 4 +- include/Move_strategy.hpp | 4 +- include/Move_tracker.hpp | 35 +- include/Mpfr_value.hpp | 38 ++ include/Random.hpp | 31 +- include/Runtime_config.hpp | 84 +++- include/S3Action.hpp | 13 + include/Settings.hpp | 5 +- include/Utilities.hpp | 174 ++++++-- pyproject.toml | 1 + scripts/doxygen.sh | 30 +- scripts/tests/test_validate_generated_site.py | 191 ++++++++ scripts/validate_generated_site.py | 412 ++++++++++++++++++ tests/Metropolis_test.cpp | 109 ++++- tests/Move_outcome_test.cpp | 31 ++ tests/Move_tracker_test.cpp | 12 + tests/Public_api_consumer.cpp | 14 + tests/Utilities_test.cpp | 20 + 41 files changed, 1973 insertions(+), 201 deletions(-) create mode 100644 cmake/RunCppApiQuickstartTest.cmake create mode 100644 docs/cpp-api-quickstart.md create mode 100644 examples/CMakeLists.txt create mode 100644 examples/cpp_api_quickstart.cpp create mode 100644 scripts/tests/test_validate_generated_site.py create mode 100755 scripts/validate_generated_site.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 653b36e76..cfc49c217 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -225,6 +225,9 @@ endif() # Header files include_directories(BEFORE ${PROJECT_BINARY_DIR} ${PROJECT_SOURCE_DIR}/include) +# Compiled public-API example +add_subdirectory(examples) + # doctest if(ENABLE_TESTING) enable_testing() diff --git a/Justfile b/Justfile index 6e4fc9c4f..33b3852fc 100644 --- a/Justfile +++ b/Justfile @@ -10,7 +10,7 @@ ccache_version := "4.13.6" cgal_benchmark_binary := if os_family() == "windows" { "out/build/reference/tests/CDT_cgal_benchmark.exe" } else { "out/build/reference/tests/CDT_cgal_benchmark" } cmake_minimum_version := "4.4.0" cmake_version := "4.4.1" -doxygen_version := "1.17.0" +doxygen_version := "1.16.1" git_cliff_version := "2.13.1" graphviz_version := "15.1.0" just_version := "1.58.0" @@ -381,12 +381,12 @@ default: # Generate the API documentation in docs/html for local inspection or publishing. [group('workflows')] docs: - ./scripts/doxygen.sh build "{{ doxygen_version }}" "{{ graphviz_version }}" + ./scripts/doxygen.sh build "{{ doxygen_version }}" "{{ graphviz_version }}" "{{ python_version }}" # Validate the generated API documentation without modifying the worktree. [group('workflows')] docs-check: - ./scripts/doxygen.sh check "{{ doxygen_version }}" "{{ graphviz_version }}" + ./scripts/doxygen.sh check "{{ doxygen_version }}" "{{ graphviz_version }}" "{{ python_version }}" # Apply safe automatic formatting to C++/Python source and the Justfile. [group('workflows')] diff --git a/README.md b/README.md index 4e4de8c81..471e95dc7 100644 --- a/README.md +++ b/README.md @@ -68,6 +68,10 @@ Arbitrary-precision numbers and functions are by [MPFR] and [GMP]. [Doxygen] provides automated document generation. The supported C++ namespace and per-header contract are recorded in the [C++ API boundary](docs/api-boundary.md). +The compiled [C++ API quickstart](docs/cpp-api-quickstart.md) demonstrates +validated construction, ten reported Metropolis proposals with separate +candidate-success and acceptance results, aggregate accounting, and a verified +persistence round trip. The exact CGAL version, kernel, TDS, metadata, lifetime, TBB, benchmark, and upgrade policies are recorded in the [CGAL 6.2 integration contract](docs/cgal-integration.md). @@ -84,13 +88,13 @@ Python and JSON Schema provide the local, offline cross-implementation compariso ### Regression-oracle scope The principal reason to preserve this implementation is its causality-filtering Delaunay construction path in -[`include/Foliated_triangulation.hpp`](include/Foliated_triangulation.hpp). `find_invalid_timevalue_cells` classifies +[`include/Foliated_triangulation.hpp`](https://github.com/acgetchell/CDT-plusplus/blob/main/include/Foliated_triangulation.hpp). `find_invalid_timevalue_cells` classifies cells from stored vertex time labels, `has_valid_timevalues` provides the predicate, `find_bad_vertex` selects a vertex responsible for an acausal local configuration, and `fix_timevalues` removes offending vertices through CGAL so the cavity is retriangulated until the foliation contract is satisfied. The deterministic doctest scenario **"Detecting and fixing problems with vertices and cells"** in -[`tests/Foliated_triangulation_test.cpp`](tests/Foliated_triangulation_test.cpp) exercises this path with fixed points +[`tests/Foliated_triangulation_test.cpp`](https://github.com/acgetchell/CDT-plusplus/blob/main/tests/Foliated_triangulation_test.cpp) exercises this path with fixed points and time labels. Its inputs, detected bad vertex, final initialization state, cell counts, and causal classification are the first comparison fixture for `causal-triangulations`; exact Monte Carlo trajectories are not required to match. @@ -241,15 +245,17 @@ Windows development. ### Current reference-suite status With the pinned baseline, the reference configuration and build succeed on -macOS with AppleClang. The cross-platform `just build` command runs all 128 +macOS with AppleClang. The cross-platform `just build` command runs all 131 CTest registrations through `scripts/build.sh` on Unix and `scripts/build.bat` -on Windows: 104 doctest scenarios, 23 CLI integration tests, and one -arithmetic-backend correctness test. The same `reference-smoke` preset is the +on Windows: 106 doctest scenarios, 23 CLI integration tests, one compiled C++ +API example, and one arithmetic-backend correctness test. The same +`reference-smoke` preset is the supported local and CI contract; there are no overlapping focused registrations that can pass while omitting another doctest suite. The current -`parallel` preset also registers 128 tests: 103 ordinary doctest scenarios, one +`parallel` preset also registers 129 tests: 103 ordinary doctest scenarios, one parallel launcher containing five scenarios, the same 23 CLI integration -tests, and the arithmetic correctness test. The parallel-enabled +tests, the C++ API example, and the arithmetic correctness test. The +parallel-enabled AddressSanitizer configuration exercises the same replayable stress contract. ## Setup @@ -266,7 +272,7 @@ The smallest pkgx-assisted host setup is: - pkgx - Just, used by the recipes and `scripts/pkgx-build.sh` to resolve the repository's tool-version pins - Python 3.14 for native dependency bootstrap, and uv when checking or running the Python support scripts -- Doxygen 1.17.0 and Graphviz 15.1.0 when checking or generating API documentation; pkgx can supply both +- Doxygen 1.16.1 and Graphviz 15.1.0 when checking or generating API documentation; pkgx can supply both The pkgx build and documentation launchers supply their required tools ephemerally, including Git, Bash, CMake, Ninja, Python, Doxygen, Graphviz, M4, Autoconf, Autoconf Archive, Automake, GNU Libtool, Texinfo, and pkg-config. If @@ -289,7 +295,7 @@ development environment. ### Developer workflow -The repository-root [Justfile](Justfile) provides the same small command vocabulary used by the related projects: +The repository-root `Justfile` provides the same small command vocabulary used by the related projects: ```bash just check # Fast, non-mutating local checks @@ -346,7 +352,7 @@ pkgx-first; because pkgx does not currently publish its CMake and Ninja packages for Windows, that job uses the exact Justfile pins available as PyPI wheels through `uv tool install --no-build`. -[pinact](https://github.com/suzuki-shunsuke/pinact) uses [`.pinact.yaml`](.pinact.yaml) to retain immutable action +[pinact](https://github.com/suzuki-shunsuke/pinact) uses [`.pinact.yaml`](https://github.com/acgetchell/CDT-plusplus/blob/main/.pinact.yaml) to retain immutable action SHAs, readable release comments, and a seven-day release cooldown. `just update-actions` uses an installed pinact, Go, or a pkgx-provided Go fallback, then requires `yamllint`, `actionlint`, and `zizmor` to pass. Direct third-party Python dependencies install only from locked wheels. The uv environment provides `clang-format` and `yamllint`; @@ -501,6 +507,9 @@ links (in 2+1 spacetime), and the timelike faces (in 3+1 spacetime). Online documentation is at . +The compiled [C++ API quickstart](docs/cpp-api-quickstart.md) is the canonical +end-to-end public API example and is embedded verbatim in the generated site. + The scientific transition, proposal-ratio, geometry-delta, counter, and precision contracts are recorded in [`docs/metropolis-hastings.md`](docs/metropolis-hastings.md). @@ -522,8 +531,11 @@ just docs-check ``` To generate the same publishable output used by the documentation workflow, run `just docs`; it writes `docs/html/` -only after strict generation succeeds. Both recipes require the pinned Doxygen and Graphviz versions and use pkgx -ephemerally when matching local tools are unavailable. `USE_MATHJAX` allows [MathJax] to render LaTeX formulae, and +only after strict generation and generated-site validation succeed. Both recipes require Doxygen 1.16.1 and Graphviz +15.1.0 and use pkgx ephemerally when matching local tools are unavailable. Doxygen 1.16.1 is the archival pin because +1.17.0 duplicates linked labels, emits broken alphabetical-index fragments for this repository, and injects an unused +Mermaid CDN dependency. `scripts/validate_generated_site.py` preserves that bounded workaround by checking the actual +HTML, local links and fragments, duplicate IDs and link labels, and required assets. `USE_MATHJAX` allows [MathJax] to render LaTeX formulae, and `HAVE_DOT` enables [GraphViz] diagrams. Documentation validation is intentionally separate from the cross-platform `just ci` contract. The documentation workflow runs `just docs` on Ubuntu and publishes its output to the `gh-pages` branch. @@ -531,7 +543,7 @@ branch. ## Citing CDT++ If CDT++ contributes to published work, cite the software using -[`CITATION.cff`](CITATION.cff) and cite the scientific methods relevant to the +[`CITATION.cff`](https://github.com/acgetchell/CDT-plusplus/blob/main/CITATION.cff) and cite the scientific methods relevant to the work from [`REFERENCES.md`](REFERENCES.md). The software citation records the current declared release, `1.0.0-rc3`. Advance its version and release date together with the CMake, vcpkg, Python-tooling, Doxygen, and CLI metadata for @@ -540,13 +552,15 @@ subsequent releases. ## Testing Run `just build`; it selects `scripts/build.sh` on Unix or `scripts\build.bat` -on Windows, builds the test target, and executes all 128 CTest entries: 104 +on Windows, builds the test target, and executes all 131 CTest entries: 106 doctest scenarios, 23 executable integration tests covering normal CLI use and -invalid-boundary rejection, and one arithmetic-backend correctness test +invalid-boundary rejection, one compiled C++ API example, and one +arithmetic-backend correctness test labeled `scientific`. The parallel-enabled AddressSanitizer and `parallel` configurations register 103 ordinary doctest scenarios, one launcher containing five scenarios labeled `unit`, `parallel`, and `configuration`, the -same 23 integration tests, and the arithmetic test, for 128 CTest entries. +same 23 integration tests, the C++ API example, and the arithmetic test, for 129 +CTest entries. Every process-level test is labeled `integration`, and invalid-input tests also carry the `cli-boundary` subcategory. Run `just ci` for the complete local validation gate. @@ -617,7 +631,7 @@ separate branch-coverage rate. ### Static Analysis -Python 3.14 is selected by [`.python-version`](.python-version), uv locks the environment in `uv.lock`, Ruff owns +Python 3.14 is selected by [`.python-version`](https://github.com/acgetchell/CDT-plusplus/blob/main/.python-version), uv locks the environment in `uv.lock`, Ruff owns Python formatting and linting, and ty owns static type checking. Run `just python-sync` once and then use `just python-check` or `just python-fix`; both commands are also part of the repository-wide validation recipes. @@ -709,13 +723,11 @@ Optional: ## Issues -- [vcpkg]'s version of [date] has an unfixed bug [#23637] which produces `use-of-uninitialized-value` in [MemorySanitizer]. -- [vcpkg] has issues with `fontconfig:arm64-osx` [#40623]. -- [vcpkg] fails to build [gmp] on Linux (which breaks CI) [#45336] +Current work and known limitations are tracked in the +[CDT++ GitHub issue tracker](https://github.com/acgetchell/CDT-plusplus/issues). +The README does not duplicate a hardcoded issue list because tracker state +changes independently of repository releases. -[#45336]: https://github.com/microsoft/vcpkg/issues/45336 -[#40623]: https://github.com/microsoft/vcpkg/issues/40623 -[#23637]: https://github.com/microsoft/vcpkg/issues/23637 [CDT]: REFERENCES.md#cdt-framework-2001 [CGAL]: REFERENCES.md#cgal-triangulations [CMake]: https://www.cmake.org @@ -743,7 +755,7 @@ Optional: [C++]: https://isocpp.org/ [Pitchfork Layout]: https://api.csswg.org/bikeshed/?force=1&url=https://raw.githubusercontent.com/vector-of-bool/pitchfork/develop/data/spec.bs#tld.docs [PCG]: REFERENCES.md#pcg-random-number-generators -[TestU01]: http://simul.iro.umontreal.ca/testu01/tu01.html +[TestU01]: https://simul.iro.umontreal.ca/testu01/ [CONTRIBUTING.md]: https://github.com/acgetchell/CDT-plusplus/blob/main/.github/CONTRIBUTING.md [CODE_OF_CONDUCT.md]: https://github.com/acgetchell/CDT-plusplus/blob/main/.github/CODE_OF_CONDUCT.md [GitHub Actions]: https://github.com/features/actions diff --git a/REFERENCES.md b/REFERENCES.md index dfe3777c5..0bcec92e3 100644 --- a/REFERENCES.md +++ b/REFERENCES.md @@ -3,7 +3,7 @@ ## How to Cite This Software If CDT++ contributes to research or a project, cite it using the structured -metadata in [`CITATION.cff`](CITATION.cff). GitHub and other citation tools can +metadata in [`CITATION.cff`](https://github.com/acgetchell/CDT-plusplus/blob/main/CITATION.cff). GitHub and other citation tools can generate BibTeX, APA, and additional formats from that file. Quick citation for the current declared release: diff --git a/cmake/RunCppApiQuickstartTest.cmake b/cmake/RunCppApiQuickstartTest.cmake new file mode 100644 index 000000000..926e1664f --- /dev/null +++ b/cmake/RunCppApiQuickstartTest.cmake @@ -0,0 +1,58 @@ +if(NOT DEFINED TEST_EXECUTABLE OR NOT EXISTS "${TEST_EXECUTABLE}") + message(FATAL_ERROR "TEST_EXECUTABLE must name a built executable") +endif() + +if(NOT DEFINED TEST_OUTPUT OR TEST_OUTPUT STREQUAL "") + message(FATAL_ERROR "TEST_OUTPUT must name the quickstart payload") +endif() + +execute_process( + COMMAND "${TEST_EXECUTABLE}" "${TEST_OUTPUT}" + RESULT_VARIABLE run_result + OUTPUT_VARIABLE run_output + ERROR_VARIABLE run_error) +if(NOT run_result EQUAL 0) + message(FATAL_ERROR "C++ API quickstart failed:\n${run_output}\n${run_error}") +endif() + +set(move_pattern "[(](2,3|3,2|2,6|6,2|4,4)[)]") +set(result_pattern "accepted=(yes|no), successful=(yes|no)") +foreach(proposal RANGE 1 10) + if(NOT run_output + MATCHES "proposal ${proposal}: move ${move_pattern}, ${result_pattern}") + message( + FATAL_ERROR + "Quickstart did not report proposal ${proposal} completely:\n${run_output}") + endif() +endforeach() + +string( + REGEX MATCHALL + "proposal [0-9]+: move ${move_pattern}, ${result_pattern}" + proposal_lines "${run_output}") +list(LENGTH proposal_lines proposal_count) +if(NOT proposal_count EQUAL 10) + message(FATAL_ERROR "Expected 10 proposal reports, found ${proposal_count}:\n${run_output}") +endif() + +if(NOT run_output + MATCHES + "There were 10 proposed moves with [0-9]+ accepted moves and [0-9]+ rejected moves[.]") + message(FATAL_ERROR "Quickstart aggregate proposal summary is missing:\n${run_output}") +endif() +if(NOT run_output + MATCHES + "There were 10 candidate construction attempts with [0-9]+ successful candidates and [0-9]+ failed candidates[.]") + message(FATAL_ERROR "Quickstart candidate summary is missing:\n${run_output}") +endif() + +if(NOT EXISTS "${TEST_OUTPUT}" OR NOT EXISTS "${TEST_OUTPUT}.meta") + message(FATAL_ERROR "Quickstart did not publish its payload and metadata sidecar") +endif() +file(READ "${TEST_OUTPUT}.meta" metadata) +if(NOT metadata MATCHES "transition_trace[.]count=10") + message(FATAL_ERROR "Quickstart metadata does not record all ten transitions:\n${metadata}") +endif() +if(NOT metadata MATCHES "configured_attempts=10") + message(FATAL_ERROR "Quickstart metadata does not record its explicit attempt plan:\n${metadata}") +endif() diff --git a/docs/Doxyfile b/docs/Doxyfile index 860f0bf41..644108cbe 100644 --- a/docs/Doxyfile +++ b/docs/Doxyfile @@ -1,4 +1,4 @@ -# Doxyfile 1.17.0 +# Doxyfile 1.16.1 # This file describes the settings to be used by the documentation system # doxygen (www.doxygen.org) for a project. @@ -476,25 +476,25 @@ EXTRACT_ALL = NO # be included in the documentation. # The default value is: NO. -EXTRACT_PRIVATE = YES +EXTRACT_PRIVATE = NO # If the EXTRACT_PRIV_VIRTUAL tag is set to YES, documented private virtual # methods of a class will be included in the documentation. # The default value is: NO. -EXTRACT_PRIV_VIRTUAL = YES +EXTRACT_PRIV_VIRTUAL = NO # If the EXTRACT_PACKAGE tag is set to YES, all members with package or internal # scope will be included in the documentation. # The default value is: NO. -EXTRACT_PACKAGE = YES +EXTRACT_PACKAGE = NO # If the EXTRACT_STATIC tag is set to YES, all static members of a file will be # included in the documentation. # The default value is: NO. -EXTRACT_STATIC = YES +EXTRACT_STATIC = NO # If the EXTRACT_LOCAL_CLASSES tag is set to YES, classes (and structs) defined # locally in source files will be included in the documentation. If set to NO, @@ -502,7 +502,7 @@ EXTRACT_STATIC = YES # for Java sources. # The default value is: YES. -EXTRACT_LOCAL_CLASSES = YES +EXTRACT_LOCAL_CLASSES = NO # This flag is only useful for Objective-C code. If set to YES, local methods, # which are defined in the implementation section but not in the interface are @@ -781,7 +781,7 @@ WARNINGS = YES # will automatically be disabled. # The default value is: YES. -WARN_IF_UNDOCUMENTED = NO +WARN_IF_UNDOCUMENTED = YES # If the WARN_IF_DOC_ERROR tag is set to YES, doxygen will generate warnings for # potential errors in the documentation, such as not documenting some parameters @@ -798,7 +798,7 @@ WARN_IF_DOC_ERROR = YES # EXTRACT_ALL is set to YES then this flag will automatically be disabled. # The default value is: NO. -WARN_NO_PARAMDOC = NO +WARN_NO_PARAMDOC = YES # If the WARN_AS_ERROR tag is set to FAIL_ON_WARNINGS then Doxygen completes the # run, reports all warnings, and returns a non-zero status afterward. @@ -963,7 +963,7 @@ EXCLUDE_SYMBOLS = cdt::detail::* \ # that contain example code fragments that are included (see the \include # command). -EXAMPLE_PATH = +EXAMPLE_PATH = examples # If the value of the EXAMPLE_PATH tag contains directories, you can use the # EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp and diff --git a/docs/api-boundary.md b/docs/api-boundary.md index 909e8d495..360bdb89d 100644 --- a/docs/api-boundary.md +++ b/docs/api-boundary.md @@ -14,6 +14,12 @@ platform-required `NOMINMAX` definition are preprocessing exceptions rather than C++ API declarations. The formatter specializations remain in `fmt`, as required by that library's customization contract. +The [C++ API quickstart](cpp-api-quickstart.md) is the canonical runnable +consumer of this boundary. CMake compiles it from the same source embedded in +the generated documentation, and CTest exercises its validated construction, +ten explicitly reported Metropolis proposals, aggregate summary accounting, +and persistence round trip. + ## Header classification | Header | Supported surface | Internal, customization, or experimental surface | @@ -87,3 +93,24 @@ versioned binary library. `BUILD_SHARED_LIBS` alone does not establish an ABI promise. The supported contract is C++23 source compatibility within the 1.0 surface documented here; `detail` and `experimental` declarations may change without compatibility shims. + +## Generated reference policy + +The canonical Doxygen configuration extracts documented public and protected +declarations while excluding private, package/internal, static, file-local, +`detail`, and `experimental` symbols from the supported reference surface. +Source-browser pages may still show implementation text; visibility there does +not promote a declaration into the supported API. + +The canonical configuration enables documentation-error, undocumented-symbol, +parameter, and return warnings. Because Doxygen also emits completeness warnings +for excluded implementation namespaces and source-browser entry points, the +repository wrapper classifies the completed warning log: only completeness noise +for `detail`, `experimental`, and recognized `src` entry-point artifacts is +ignored. The wrapper temporarily disables Doxygen's undifferentiated +fail-on-warning status so it can perform that classification after generation; +it then fails on every non-exempt warning. Malformed documentation and every +supported-public-surface warning are fatal. `just docs-check` builds the site +with the repository-pinned Doxygen and Graphviz versions, then validates the +warning policy, generated local links, fragments, identifiers, rendered labels, +and required assets without modifying the worktree. diff --git a/docs/arithmetic-backend-evaluation.md b/docs/arithmetic-backend-evaluation.md index ccd36a36e..7e71dfc40 100644 --- a/docs/arithmetic-backend-evaluation.md +++ b/docs/arithmetic-backend-evaluation.md @@ -105,7 +105,7 @@ The default preserves current behavior; a Boost-only consumer uses: When the feature is absent, a vcpkg CMake wrapper sets `CGAL_DISABLE_GMP=ON` and `CGAL_CMAKE_EXACT_NT_BACKEND=BOOST_BACKEND`. The candidate port and standalone consumer live under -[`tests/cgal_no_gmp_probe`](../tests/cgal_no_gmp_probe). They are a one-time +[`tests/cgal_no_gmp_probe`](https://github.com/acgetchell/CDT-plusplus/tree/main/tests/cgal_no_gmp_probe). They are a one-time evaluation fixture, not a production overlay or root-CI dependency contract; shipping a downstream fork would recreate the maintenance burden this work is meant to remove. diff --git a/docs/comparison-harness.md b/docs/comparison-harness.md index ab9b04c74..17f38feed 100644 --- a/docs/comparison-harness.md +++ b/docs/comparison-harness.md @@ -10,7 +10,7 @@ legality, or acceptance decisions. Each producer writes exactly one UTF-8 JSON object to standard output and may write diagnostics to standard error. The committed CDT++ `cdt-reference-raw-v1` document is validated directly against -[`result-v1.schema.json`](../reference/schema/result-v1.schema.json). +[`result-v1.schema.json`](https://github.com/acgetchell/CDT-plusplus/blob/main/reference/schema/result-v1.schema.json). Every bundle copies that canonical result, and the harness checks the live CDT++ payload against it before using the live C++ payload as the reference for the Rust comparison. When live C++ output includes transition observations, diff --git a/docs/cpp-api-quickstart.md b/docs/cpp-api-quickstart.md new file mode 100644 index 000000000..dc4d7e3bc --- /dev/null +++ b/docs/cpp-api-quickstart.md @@ -0,0 +1,76 @@ +# C++ API quickstart + +This is the canonical end-to-end example for the supported C++23 API. Its +source is built as `CDT_cpp_api_quickstart` in every normal CMake build and run +by CTest when `ENABLE_TESTING` is enabled, so the documentation cannot drift +silently away from the public headers. + +## Workflow + +The example validates raw configuration values before constructing a manifold, +splits a fixed root seed into named initialization and transition streams, +asks the strategy to sample and resolve ten proposals through the public +one-transition Metropolis API. Every proposal prints its move kind, whether +candidate construction and validation succeeded, and whether the +Metropolis-Hastings criterion accepted and committed it. The existing strategy +summary then reports the aggregate proposal and candidate counters. + +“Successful” and “accepted” describe different stages. A successful proposal +produced a valid candidate; it may still be rejected by Metropolis-Hastings. An +accepted proposal is necessarily successful and replaces the canonical state. +The one-argument `attempt_transition()` overload returns both facts in a typed +transition report, so callers do not need to infer an individual outcome from +aggregate counters. + +Finally, the example writes the resulting triangulation with a provenance +sidecar. Reading the payload back verifies the sidecar checksum, recorded +geometry, and topology fingerprints before the example compares the finite +simplex counts. Because the one-transition API does not complete a configured +move pass, the artifact records zero completed passes and a transition-trace +count of ten. Its optional `configured_attempts=10` field identifies the +explicit one-step execution plan independently of the pass cadence retained by +the strategy. + +After Pachner evolution, the canonical state is required to preserve the CGAL +triangulation data structure and CDT causal manifold invariants. A bistellar +flip is not required to preserve CGAL's geometric Delaunay predicate, so the +round-trip check deliberately tests `tds().is_valid()` rather than +`Delaunay_t<3>::is_valid()`. + +The strategy owns the named transition stream and draws each move kind, +acceptance trial, and candidate site in sequence. This preserves single +ownership of the stream and makes the complete sequence replayable from the +recorded root seed. + +\include cpp_api_quickstart.cpp + +## Build and run + +From the repository root: + +```bash +cmake --preset reference +cmake --build --preset reference --target CDT_cpp_api_quickstart +./out/build/reference/examples/CDT_cpp_api_quickstart /tmp/cdt-quickstart.off +ctest --test-dir out/build/reference -R '^cpp-api-quickstart$' --output-on-failure +``` + +The program accepts zero or one argument. Without an argument it writes +`cdt-quickstart.off` and `cdt-quickstart.off.meta` in the current directory. +With an argument, the sidecar is written next to that payload by appending +`.meta` to its name. + +## Failure and ownership behavior + +Configuration, construction, move execution, and persistence failures are +reported on standard error and produce a nonzero exit status. A caller-owned +random stream may already have advanced when a later operation throws; replay +therefore starts from the recorded root seed and named stream, not from an +engine object retained after failure. + +CGAL handles and facet or edge descriptors borrow from the exact triangulation +that produced them. Do not use them with a copied triangulation or after an +invalidating topology mutation. `delaunay_snapshot()` instead returns an owning, +detached triangulation suitable for persistence or transfer across an ownership +boundary. See the [multithreaded CGAL contract](multithreading.md) for the full +lifetime and synchronization policy. diff --git a/docs/metropolis-hastings.md b/docs/metropolis-hastings.md index 5a015993d..9029ef568 100644 --- a/docs/metropolis-hastings.md +++ b/docs/metropolis-hastings.md @@ -91,6 +91,14 @@ candidate can still be rejected by Metropolis-Hastings. `failed` means the raw site was inapplicable or candidate construction violated an invariant; every failure is therefore also a rejection. +The one-argument `attempt_transition()` overload samples and resolves one +transition from the strategy-owned stream. Its `MetropolisTransition` report +names the move and exposes both `successful()` and `accepted()`, so an +individual decision does not have to be inferred from these aggregate +counters. The `attempt_transition(move, trial)` overload returns the same +report while accepting deterministic inputs for focused tests and controlled +experiments. + ## Numerical policy The action, action difference, exponential, proposal ratio, and acceptance @@ -122,7 +130,7 @@ a delta whose positive MPFR probability lies below `long double` range. Combinatorial fields and deterministic decisions are exact. The published cross-language protocol in -[`reference/fixtures/v1/protocol.json`](../reference/fixtures/v1/protocol.json) +[`reference/fixtures/v1/protocol.json`](https://github.com/acgetchell/CDT-plusplus/blob/main/reference/fixtures/v1/protocol.json) names separate absolute and relative tolerances for coordinates, closed-form actions, and probabilities. Randomized post-repair simplex counts are implementation-specific rather than covered by a generic percentage. diff --git a/docs/reproducibility.md b/docs/reproducibility.md index 275d32cb1..667feb917 100644 --- a/docs/reproducibility.md +++ b/docs/reproducibility.md @@ -85,6 +85,8 @@ manifest. The manifest records: - requested and actual topology dimensions and counts; - foliation parameters and, for simulations, the action parameters and pass cadence; +- the optional configured-attempt count for callers using explicit one-step + transitions; - the maximum requested Delaunay thread count; - completed passes and the transition-trace fingerprint; - a canonical placement fingerprint derived from sorted finite vertices and diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt new file mode 100644 index 000000000..472de4e96 --- /dev/null +++ b/examples/CMakeLists.txt @@ -0,0 +1,22 @@ +add_executable(CDT_cpp_api_quickstart cpp_api_quickstart.cpp) +target_compile_features(CDT_cpp_api_quickstart PRIVATE cxx_std_23) +target_link_libraries( + CDT_cpp_api_quickstart + PRIVATE project_options + project_warnings + date::date-tz + fmt::fmt-header-only + spdlog::spdlog_header_only + CGAL::CGAL) + +if(ENABLE_TESTING) + add_test( + NAME cpp-api-quickstart + COMMAND + ${CMAKE_COMMAND} + "-DTEST_EXECUTABLE=$" + "-DTEST_OUTPUT=${CMAKE_CURRENT_BINARY_DIR}/cpp-api-quickstart.off" + -P ${PROJECT_SOURCE_DIR}/cmake/RunCppApiQuickstartTest.cmake) + set_tests_properties(cpp-api-quickstart PROPERTIES LABELS "example;integration" + TIMEOUT 30) +endif() diff --git a/examples/cpp_api_quickstart.cpp b/examples/cpp_api_quickstart.cpp new file mode 100644 index 000000000..b589b5807 --- /dev/null +++ b/examples/cpp_api_quickstart.cpp @@ -0,0 +1,156 @@ +/******************************************************************************* + Causal Dynamical Triangulations in C++ using CGAL + + Copyright © 2026 Adam Getchell + ******************************************************************************/ + +#include + +#include +#include +#include +#include +#include + +#include "Manifold.hpp" +#include "Metropolis.hpp" +#include "Move_tracker.hpp" +#include "Random.hpp" +#include "Runtime_config.hpp" +#include "Utilities.hpp" + +namespace +{ + inline constexpr std::size_t QUICKSTART_TRANSITIONS = 10; + + [[nodiscard]] constexpr auto yes_no(bool const value) noexcept + -> std::string_view + { return value ? "yes" : "no"; } + + [[nodiscard]] auto same_finite_counts( + cdt::Delaunay_t<3> const& restored, + cdt::manifolds::Manifold_3 const& expected) -> bool + { + return restored.number_of_vertices() == + static_cast(expected.N0()) && + restored.number_of_finite_edges() == + static_cast(expected.N1()) && + restored.number_of_finite_facets() == + static_cast(expected.N2()) && + restored.number_of_finite_cells() == + static_cast(expected.N3()); + } +} // namespace + +auto main(int argc, char* argv[]) -> int +try +{ + if (argc > 2) + { + fmt::print(stderr, "usage: {} [output.off]\n", argv[0]); + return 2; + } + + auto const output = argc == 2 ? std::filesystem::path{argv[1]} + : std::filesystem::path{"cdt-quickstart.off"}; + auto const triangulation_config = cdt::runtime_config::make_triangulation( + true, false, 64, 3, 3, 1.0, 1.0, cdt::RandomSeed{92}, 1); + auto const simulation_config = cdt::runtime_config::make_simulation( + triangulation_config, 0.6L, 1.1L, 0.1L, 1, 1, false); + + cdt::Random root_random{triangulation_config.seed()}; + auto initialization_random = + root_random.split(cdt::random_streams::initialization); + auto const initialization_stream = initialization_random.stream(); + cdt::manifolds::Manifold_3 initial{ + triangulation_config.simplices(), triangulation_config.timeslices(), + initialization_random, triangulation_config.initial_radius(), + triangulation_config.foliation_spacing()}; + if (!initial.is_correct_with_diagnostics()) + { + fmt::print(stderr, "initial triangulation failed validation\n"); + return 1; + } + + auto provenance = cdt::utilities::make_reproducibility_metadata( + initial, triangulation_config.seed(), + cdt::utilities::ArtifactKind::INITIAL_TRIANGULATION); + provenance.initialization_stream = initialization_stream; + provenance.desired_simplices = triangulation_config.simplices(); + provenance.desired_timeslices = triangulation_config.timeslices(); + provenance.configured_attempts = + static_cast(QUICKSTART_TRANSITIONS); + provenance.max_threads = + static_cast(triangulation_config.threads()); + + cdt::Metropolis_3 strategy{ + simulation_config.alpha(), + simulation_config.k(), + simulation_config.lambda(), + simulation_config.passes(), + simulation_config.checkpoint(), + simulation_config.write_files(), + root_random.split(cdt::random_streams::transitions), + provenance}; + auto evolved = initial; + fmt::print("=== Ten explicit Metropolis proposals ===\n"); + for (std::size_t index = 0; index < QUICKSTART_TRANSITIONS; ++index) + { + auto const transition = strategy.attempt_transition(evolved); + if (transition.accepted() && !transition.successful()) + { + fmt::print(stderr, "accepted transition lacked a valid candidate\n"); + return 1; + } + fmt::print("proposal {}: move {}, accepted={}, successful={}\n", index + 1, + transition.move(), yes_no(transition.accepted()), + yes_no(transition.successful())); + } + strategy.print_results(); + + if (!initial.is_correct_with_diagnostics() || + !evolved.is_correct_with_diagnostics()) + { + fmt::print(stderr, "Metropolis transitions failed manifold validation\n"); + return 1; + } + if (strategy.proposed().total() != + static_cast(QUICKSTART_TRANSITIONS) || + strategy.accepted().total() + strategy.rejected().total() != + static_cast(QUICKSTART_TRANSITIONS) || + strategy.succeeded().total() + strategy.failed().total() != + static_cast(QUICKSTART_TRANSITIONS)) + { + fmt::print(stderr, "Metropolis summary counters are inconsistent\n"); + return 1; + } + + auto const final_metadata = strategy.reproducibility_metadata( + evolved, cdt::utilities::ArtifactKind::FINAL_TRIANGULATION, 0); + cdt::utilities::write_file(output, evolved.delaunay_snapshot(), + final_metadata); + auto const restored = cdt::utilities::read_file>(output); + // Pachner moves preserve the TDS and CDT invariants, not necessarily CGAL's + // geometric Delaunay predicate. + if (!restored.tds().is_valid() || !same_finite_counts(restored, evolved)) + { + fmt::print( + stderr, + "persisted triangulation failed round-trip checks: tds_valid={}, " + "counts=({},{},{},{}) expected=({},{},{},{})\n", + restored.tds().is_valid(), restored.number_of_vertices(), + restored.number_of_finite_edges(), restored.number_of_finite_facets(), + restored.number_of_finite_cells(), evolved.N0(), evolved.N1(), + evolved.N2(), evolved.N3()); + return 1; + } + + fmt::print("wrote and verified {} with {} finite simplices\n", + output.string(), evolved.N3()); + return 0; +} +catch (std::exception const& error) +{ + fmt::print(stderr, "quickstart failed: {}\n", error.what()); + return 1; +} diff --git a/include/Ergodic_moves_3.hpp b/include/Ergodic_moves_3.hpp index c02c7a449..1b9732a12 100644 --- a/include/Ergodic_moves_3.hpp +++ b/include/Ergodic_moves_3.hpp @@ -40,14 +40,23 @@ namespace cdt::ergodic_moves { + /// Three-dimensional spherical CDT manifold operated on by this move set. using Manifold = manifolds::Manifold_3; + /// Fallible manifold transformation returned by public move functions. using Expected = MoveResult; + /// Three-dimensional CGAL cell handle. using Cell_handle = Cell_handle_t<3>; + /// Collection of three-dimensional cell handles. using Cell_container = std::vector; + /// Three-dimensional CGAL edge descriptor. using Edge_handle = Edge_handle_t<3>; + /// Collection of three-dimensional edge descriptors. using Edge_container = std::vector; + /// Three-dimensional CGAL vertex handle. using Vertex_handle = Vertex_handle_t<3>; + /// Collection of three-dimensional vertex handles. using Vertex_container = std::vector; + /// Three-dimensional Delaunay triangulation used by move implementations. using Delaunay = Delaunay_t<3>; namespace detail @@ -679,6 +688,10 @@ namespace cdt::ergodic_moves /// @details Unlike do_23_move(), this samples exactly one of the N3(2,2) /// cells. An inapplicable selected cell is a rejected proposal rather than a /// reason to condition the proposal distribution on the movable subset. + /// @tparam Generator Uniform random bit generator type. + /// @param t_manifold Source manifold, which remains unchanged. + /// @param generator Caller-owned generator advanced by site sampling. + /// @return Proposed manifold, or a structured reason the site was rejected. template [[nodiscard]] inline auto propose_23_move(Manifold const& t_manifold, Generator& generator) -> Expected @@ -840,6 +853,10 @@ namespace cdt::ergodic_moves /// @brief Propose one (3,2) site for Metropolis-Hastings. /// @details The raw proposal domain is the set of timelike edges. Selecting /// a nonflippable edge produces a self-transition. + /// @tparam Generator Uniform random bit generator type. + /// @param t_manifold Source manifold, which remains unchanged. + /// @param generator Caller-owned generator advanced by site sampling. + /// @return Proposed manifold, or a structured reason the site was rejected. template [[nodiscard]] inline auto propose_32_move(Manifold const& t_manifold, Generator& generator) -> Expected @@ -1108,6 +1125,10 @@ namespace cdt::ergodic_moves /// @details Exactly one uniformly selected (1,3) cell is examined. An /// inapplicable raw site is returned as a failed proposal so Metropolis- /// Hastings can account for it as a self-transition. + /// @tparam Generator Uniform random bit generator type. + /// @param t_manifold Source manifold, which remains unchanged. + /// @param generator Caller-owned generator advanced by site sampling. + /// @return Proposed manifold, or a structured reason the site was rejected. template [[nodiscard]] inline auto propose_26_move(Manifold const& t_manifold, Generator& generator) -> Expected @@ -1380,6 +1401,11 @@ namespace cdt::ergodic_moves } // do_62_move() /// @brief Propose one vertex as a (6,2) site for Metropolis-Hastings. + /// @tparam Generator Uniform random bit generator type. + /// @param t_manifold Source manifold, which remains unchanged. + /// @param generator Caller-owned generator advanced by site sampling and + /// replacement-point construction. + /// @return Proposed manifold, or a structured reason the site was rejected. template [[nodiscard]] inline auto propose_62_move(Manifold const& t_manifold, Generator& generator) -> Expected @@ -1778,6 +1804,10 @@ namespace cdt::ergodic_moves /// @brief Propose one spacelike edge as a (4,4) site. /// @details Selecting an edge that is not the pivot of a causal four-cell /// complex is an explicit self-transition. + /// @tparam Generator Uniform random bit generator type. + /// @param t_manifold Source manifold, which remains unchanged. + /// @param generator Caller-owned generator advanced by site sampling. + /// @return Proposed manifold, or a structured reason the site was rejected. template [[nodiscard]] inline auto propose_44_move(Manifold const& t_manifold, Generator& generator) -> Expected diff --git a/include/Foliated_triangulation.hpp b/include/Foliated_triangulation.hpp index 7fbea5be9..dd8d9521d 100644 --- a/include/Foliated_triangulation.hpp +++ b/include/Foliated_triangulation.hpp @@ -51,31 +51,55 @@ namespace cdt { + /// @brief Delaunay triangulation type for `dimension` spatial dimensions. + /// @tparam dimension Compile-time triangulation dimension. template using Delaunay_t = typename detail::TriangulationTraits::Delaunay; + /// @brief Cartesian point type used by a triangulation dimension. + /// @tparam dimension Compile-time triangulation dimension. template using Point_t = typename detail::TriangulationTraits::Point; + /// @brief Point/time-label pairs used to build a causal triangulation. + /// @tparam dimension Compile-time point dimension. template using Causal_vertices_t = std::vector, Int_precision>>; + /// @brief Mutable CGAL cell handle for a triangulation dimension. + /// @details A handle borrows from the triangulation that produced it. It must + /// not be used with a copy or after an invalidating mutation of its owner. + /// @tparam dimension Compile-time triangulation dimension. template using Cell_handle_t = typename detail::TriangulationTraits::Cell_handle; + /// @brief CGAL facet descriptor for a triangulation dimension. + /// @details The embedded cell handle borrows from its source triangulation + /// and follows that triangulation's invalidation rules. + /// @tparam dimension Compile-time triangulation dimension. template using Facet_t = typename detail::TriangulationTraits::Facet; + /// @brief CGAL edge descriptor for a triangulation dimension. + /// @details The embedded cell handle borrows from its source triangulation + /// and follows that triangulation's invalidation rules. + /// @tparam dimension Compile-time triangulation dimension. template using Edge_handle_t = typename detail::TriangulationTraits::Edge_handle; + /// @brief Mutable CGAL vertex handle for a triangulation dimension. + /// @details A handle borrows from the triangulation that produced it. It must + /// not be used with a copy or after an invalidating mutation of its owner. + /// @tparam dimension Compile-time triangulation dimension. template using Vertex_handle_t = typename detail::TriangulationTraits::Vertex_handle; + /// @brief CGAL random point generator on a sphere of matching dimension. + /// @tparam dimension Compile-time point dimension. template using Spherical_points_generator_t = typename detail::TriangulationTraits< dimension>::Spherical_points_generator; @@ -328,28 +352,42 @@ namespace cdt enum class CellType { // 3D simplices - THREE_ONE = 31, // (3,1) - TWO_TWO = 22, // (2,2) - ONE_THREE = 13, // (1,3) - ACAUSAL = 99, // The vertex timevalues differ by > 1 or are all equal - UNCLASSIFIED = 0 // An error happened classifying cell + THREE_ONE = 31, ///< Three lower-slice and one upper-slice vertices. + TWO_TWO = 22, ///< Two vertices on each adjacent slice. + ONE_THREE = 13, ///< One lower-slice and three upper-slice vertices. + ACAUSAL = 99, ///< Vertex times differ by more than one or are all equal. + UNCLASSIFIED = 0 ///< Classification could not determine a causal type. }; /// @brief Causal classification of an edge by its endpoint timeslices. enum class EdgeType { - SPACELIKE, - TIMELIKE + SPACELIKE, ///< Both endpoints lie on the same timeslice. + TIMELIKE ///< Endpoints lie on adjacent timeslices. }; } // namespace cdt namespace cdt::foliated_triangulations { + /// @namespace cdt::foliated_triangulations + /// @brief Supported construction, inspection, classification, and repair + /// operations for foliated Delaunay triangulations. + /// @details CGAL handles and descriptors returned by these operations borrow + /// from the triangulation named by the function. All handles supplied to one + /// operation must be valid and belong to that same triangulation. Copying a + /// triangulation does not transfer handle provenance, and topology mutation + /// may invalidate outstanding handles, iterators, circulators, and + /// descriptors. + /// @see [Multithreaded CGAL contract](../docs/multithreading.md) + /// @brief Create causal vertices from vertices and timevalues /// @tparam dimension Dimensionality of the manifold /// @param vertices The vertices of the manifold /// @param timevalues The timevalue of each vertex /// @return A container of vertices that have an associated timevalue + /// @throws std::length_error If the spans have different lengths. + /// @throws std::out_of_range If a timevalue cannot be represented by + /// `Int_precision`. template [[nodiscard]] auto make_causal_vertices( std::span const> vertices, @@ -378,7 +416,8 @@ namespace cdt::foliated_triangulations /// edges are 1-d simplices connecting 0-d vertices. /// @tparam dimension The dimensionality of the triangulation /// @param delaunay The triangulation - /// @returns Container of all the finite edges in the triangulation + /// @returns Borrowed finite-edge descriptors tied to @p delaunay and subject + /// to its mutation-invalidation rules. template [[nodiscard]] auto collect_edges(Delaunay_t const& delaunay) { @@ -394,11 +433,13 @@ namespace cdt::foliated_triangulations return init_edges; } // collect_edges - /// @brief Returns the vertex containing the given point + /// @brief Find the vertex whose stored point equals the requested point. /// @tparam dimension The dimensionality of the triangulation /// @param delaunay The triangulation /// @param point The point to find the vertex for - /// @returns The vertex containing the given point + /// @returns A handle borrowing from @p delaunay, or `std::nullopt` when no + /// vertex stores @p point. The handle is subject to the triangulation's + /// mutation-invalidation rules. /// @see /// https://doc.cgal.org/latest/Triangulation_3/classCGAL_1_1Triangulation__3.html#a5b45572c663e5d2c10f26e7be421e140 template @@ -421,7 +462,10 @@ namespace cdt::foliated_triangulations /// @param vh2 The second vertex /// @param vh3 The third vertex /// @param vh4 The fourth vertex - /// @returns The cell containing the vertices + /// @pre All four handles are valid and belong to @p delaunay. + /// @returns A cell handle borrowing from @p delaunay, or `std::nullopt` when + /// those vertices do not form a cell. The returned handle is subject to the + /// triangulation's mutation-invalidation rules. /// @see /// https://doc.cgal.org/latest/Triangulation_3/classCGAL_1_1Triangulation__3.html#a8766c9a0c2a84203be31537e5e015646 template @@ -451,6 +495,7 @@ namespace cdt::foliated_triangulations /// @tparam dimension The dimensionality of the simplices /// @param t_vertices The container of vertices /// @returns The maximum timevalue in the container + /// @throws std::invalid_argument If @p t_vertices is empty. template [[nodiscard]] auto find_max_timevalue(Container const& t_vertices) -> Int_precision @@ -467,6 +512,7 @@ namespace cdt::foliated_triangulations /// @tparam dimension The dimensionality of the simplices /// @param t_vertices The container of vertices /// @returns The minimum timevalue in the container + /// @throws std::invalid_argument If @p t_vertices is empty. template [[nodiscard]] auto find_min_timevalue(Container const& t_vertices) -> Int_precision @@ -557,13 +603,16 @@ namespace cdt::foliated_triangulations /// /// \f[t=\frac{R-I+S}{S}\f] /// - /// Where R is radius, I is INITIAL_RADIUS, and S is RADIAL_SEPARATION + /// Where R is radius, I is the initial radius, and S is the foliation + /// spacing. /// /// @tparam dimension Dimensionality of the vertex /// @param t_vertex The vertex /// @param t_initial_radius The initial radius of the radial foliation /// @param t_foliation_spacing The spacing between successive leaves - /// @returns The effective radius of the vertex + /// @pre @p t_vertex is a valid handle and both geometric parameters are + /// finite, with @p t_foliation_spacing greater than zero. + /// @returns The timeslice label implied by the vertex radius. template [[nodiscard]] auto expected_timevalue( Vertex_handle_t const& t_vertex, double t_initial_radius, @@ -600,7 +649,8 @@ namespace cdt::foliated_triangulations /// @brief Obtain all finite vertices in the Delaunay triangulation /// @tparam dimension Dimensionality of the Delaunay triangulation /// @param t_triangulation The Delaunay triangulation - /// @returns A container of finite vertices + /// @returns Borrowed finite-vertex handles tied to @p t_triangulation and + /// subject to its mutation-invalidation rules. template [[nodiscard]] auto collect_vertices( Delaunay_t const& t_triangulation) @@ -637,7 +687,8 @@ namespace cdt::foliated_triangulations /// @brief Obtain all finite cells in the Delaunay triangulation /// @tparam dimension Dimensionality of the Delaunay triangulation /// @param t_triangulation The triangulation - /// @returns A container of finite cells + /// @returns Borrowed finite-cell handles tied to @p t_triangulation and + /// subject to its mutation-invalidation rules. template [[nodiscard]] auto collect_cells(Delaunay_t const& t_triangulation) -> std::vector> @@ -653,8 +704,9 @@ namespace cdt::foliated_triangulations } // collect_cells /// @brief Extracts vertices from cells - /// @param t_cells The cells from which to extract vertices - /// @returns All of the vertices contained in the cells + /// @param t_cells Valid cells that all belong to one triangulation. + /// @returns Borrowed handles for all vertices contained in @p t_cells. They + /// retain the cells' source-triangulation lifetime and invalidation rules. template [[nodiscard]] auto get_vertices_from_cells( std::vector> const& t_cells) @@ -674,10 +726,11 @@ namespace cdt::foliated_triangulations /// @brief Obtain vertices with incorrect timevalues /// @tparam dimension Dimensionality of vertices and cells - /// @param t_cells Container of cells to check + /// @param t_cells Valid cells that all belong to one triangulation. /// @param t_initial_radius The initial radius of the radial foliation /// @param t_foliation_spacing The spacing between successive leaves - /// @return A container of vertices with incorrect timevalues + /// @return Borrowed handles for vertices with incorrect timevalues, retaining + /// the source triangulation's lifetime and invalidation rules. template [[nodiscard]] auto find_incorrect_vertices( std::vector> const& t_cells, @@ -701,7 +754,8 @@ namespace cdt::foliated_triangulations /// @param t_triangulation The Delaunay triangulation /// @param t_initial_radius The initial radius of the radial foliation /// @param t_foliation_spacing The spacing between successive leaves - /// @return A container of vertices with incorrect timevalues + /// @return Borrowed handles for vertices with incorrect timevalues, tied to + /// @p t_triangulation and subject to its mutation-invalidation rules. template [[nodiscard]] auto find_incorrect_vertices( Delaunay_t const& t_triangulation, double t_initial_radius, @@ -716,9 +770,10 @@ namespace cdt::foliated_triangulations /// @details Changes vertex->info() to the correct timevalue using /// foliated_triangulations::expected_timevalue /// @tparam dimension Dimensionality of vertices and cells - /// @param t_cells Container of cells to check + /// @param t_cells Valid cells that all belong to one triangulation. /// @param t_initial_radius The initial radius of the radial foliation - /// @param t_foliation_spacing + /// @param t_foliation_spacing Positive finite spacing between successive + /// leaves. /// @return True if any vertex->info() was fixed template [[nodiscard]] auto fix_vertices( @@ -843,7 +898,8 @@ namespace cdt::foliated_triangulations /// @brief Check all finite cells in the Delaunay triangulation /// @tparam dimension Dimensionality of the Delaunay triangulation /// @param t_triangulation The Delaunay triangulation - /// @return A container of cells that are not classified correctly + /// @return Borrowed handles for incorrectly classified cells, tied to + /// @p t_triangulation and subject to its mutation-invalidation rules. template [[nodiscard]] auto find_incorrect_cells( Delaunay_t const& t_triangulation) @@ -859,6 +915,8 @@ namespace cdt::foliated_triangulations } // find_incorrect_cells /// @brief Fix simplices with the wrong type + /// @details Only cell metadata is changed; the triangulation topology and + /// its handles are not replaced by this operation. /// @tparam dimension The dimensionality of the simplices /// @param t_triangulation The Delaunay triangulation /// @return True if cells->info() was fixed @@ -960,8 +1018,11 @@ namespace cdt::foliated_triangulations /// @details *Warning!* Turning on debugging info will generate gigabytes /// of logs. /// @tparam dimension The dimensionality of the simplices - /// @param t_facets A container of facets - /// @return Contiguous container with spacelike facets per timeslice + /// @param t_facets Facets whose cell handles are valid and belong to one + /// triangulation. + /// @return Contiguous container with spacelike facets per timeslice. The + /// facet descriptors borrow from the source triangulation and follow its + /// mutation-invalidation rules. template [[nodiscard]] auto collect_spacelike_facets(Container const& t_facets) -> std::vector>> @@ -1020,8 +1081,11 @@ namespace cdt::foliated_triangulations /// @brief Collect spacelike facets into a container indexed by time value /// @tparam dimension The dimensionality of the simplices - /// @param t_facets A container of facets - /// @return Container with spacelike facets per timeslice + /// @param t_facets Facets whose cell handles are valid and belong to one + /// triangulation. + /// @return Container with spacelike facets per timeslice. The facet + /// descriptors borrow from the source triangulation and follow its + /// mutation-invalidation rules. template [[nodiscard]] auto volume_per_timeslice(Container const& t_facets) -> std::multimap> @@ -1044,7 +1108,9 @@ namespace cdt::foliated_triangulations /// fix_vertices() should be called before this function. /// @tparam dimension The dimensionality of the cells and triangulation /// @param t_triangulation The Delaunay triangulation - /// @return A container of invalid cells; empty means the foliation is valid + /// @return Borrowed handles for invalid cells, tied to @p t_triangulation and + /// subject to its mutation-invalidation rules; empty means the foliation is + /// valid. template [[nodiscard]] auto find_invalid_timevalue_cells( Delaunay_t const& t_triangulation) @@ -1063,6 +1129,9 @@ namespace cdt::foliated_triangulations } // find_invalid_timevalue_cells /// @brief Check whether all cell timevalues form a valid foliation. + /// @tparam dimension Compile-time triangulation dimension. + /// @param triangulation Triangulation whose finite cells are classified. + /// @return Whether every finite cell has a supported causal classification. template [[nodiscard]] auto has_valid_timevalues( Delaunay_t const& triangulation) -> bool @@ -1070,8 +1139,9 @@ namespace cdt::foliated_triangulations /// @brief Find the vertex that is causing a cell's foliation to be invalid /// @tparam dimension Dimensionality of the cell - /// @param cell The cell to check - /// @return The offending vertex + /// @param cell Valid cell handle from the triangulation being repaired. + /// @return A borrowed handle to the offending vertex in @p cell, with the + /// same source-triangulation lifetime and invalidation rules. template [[nodiscard]] auto find_bad_vertex(Cell_handle_t const& cell) -> Vertex_handle_t @@ -1102,7 +1172,9 @@ namespace cdt::foliated_triangulations } // find_bad_vertex /// @brief Fix the vertices of a cell to be consistent with the foliation - /// + /// @details Removes selected vertices from the triangulation. A successful + /// repair changes its topology and may invalidate any outstanding handles, + /// iterators, circulators, and facet or edge descriptors. /// @tparam dimension Dimensionality of the triangulation /// @param t_triangulation The Delaunay triangulation /// @return True if incorrectly foliated simplices were fixed @@ -1149,6 +1221,12 @@ namespace cdt::foliated_triangulations /// @param generator Caller-owned random stream whose state is maintained by /// the caller and advanced during this call /// @return A container of (vertex, timevalue) pairs + /// @throws std::invalid_argument If a count is less than two, a radius or + /// spacing is non-finite or nonpositive, or the parameters cannot populate a + /// triangulation. + /// @throws std::out_of_range If a layer population cannot be represented by + /// `Int_precision`. + /// @note Once sampling begins, an exception does not roll back @p generator. template [[nodiscard]] auto make_foliated_ball(Int_precision const t_simplices, Int_precision const t_timeslices, @@ -1241,6 +1319,11 @@ namespace cdt::foliated_triangulations /// grid and can safely outlive this call. Its subsequent range operations /// are sequential; in a TBB-enabled build, callers can attach a compatible /// lock grid that they own to re-enable parallel execution. + /// @throws std::invalid_argument If the generation parameters are invalid or + /// the generated point set cannot form a nonempty unique triangulation. + /// @throws std::out_of_range If a generated layer population cannot be + /// represented by `Int_precision`. + /// @note Once sampling begins, an exception does not roll back @p generator. /// @see [CGAL triangulations](../REFERENCES.md#cgal-triangulations) template [[nodiscard]] auto make_triangulation(Int_precision const t_simplices, @@ -1310,6 +1393,16 @@ namespace cdt::foliated_triangulations /// triangulation has validly foliated vertices and cells, and has further /// containers for the various sub-simplicial complexes of the /// triangulation. + /// Member functions on the same object must not be invoked concurrently. + /// Use owning snapshots when topology must cross an ownership or concurrency + /// boundary. + /// Supported Pachner moves preserve the triangulation-data-structure and + /// causal manifold invariants, but are not required to preserve CGAL's + /// geometric Delaunay predicate. Use is_correct() for canonical simulation + /// states and is_initialized() when the geometric Delaunay property is also + /// required. + /// @see [Concurrency, ownership, and handle + /// lifetime](../docs/multithreading.md) template <> class [[nodiscard("This contains data!")]] FoliatedTriangulation<3> // NOLINT { @@ -1458,6 +1551,7 @@ namespace cdt::foliated_triangulations FoliatedTriangulation() = default; /// @brief Copy Constructor + /// @param other Triangulation to copy. FoliatedTriangulation(FoliatedTriangulation const& other) : FoliatedTriangulation{} { @@ -1475,6 +1569,8 @@ namespace cdt::foliated_triangulations /// @brief Copy assignment operator /// @details Builds a complete copy before replacing the current value. + /// @param other Triangulation to copy. + /// @returns This triangulation after replacement. auto operator=(FoliatedTriangulation const& other) -> FoliatedTriangulation& { if (this == &other) { return *this; } @@ -1486,9 +1582,12 @@ namespace cdt::foliated_triangulations /// @brief Move constructor /// @details The invariant-bearing Delaunay state transfers its lock owner /// and detaches the moved-from triangulation as one operation. + /// @param other Triangulation whose state is transferred. FoliatedTriangulation(FoliatedTriangulation&& other) noexcept = default; /// @brief Move assignment operator + /// @param other Triangulation whose state is transferred. + /// @returns This triangulation after replacement. auto operator=(FoliatedTriangulation&& other) noexcept -> FoliatedTriangulation& { @@ -1535,6 +1634,8 @@ namespace cdt::foliated_triangulations /// @param triangulation Delaunay triangulation /// @param initial_radius Radius of first timeslice /// @param foliation_spacing Radial separation between timeslices + /// @pre @p initial_radius and @p foliation_spacing are finite and positive. + /// @throws std::invalid_argument if @p triangulation is empty. explicit FoliatedTriangulation( Delaunay triangulation, double const initial_radius = INITIAL_RADIUS, double const foliation_spacing = FOLIATION_SPACING) @@ -1571,6 +1672,11 @@ namespace cdt::foliated_triangulations /// advanced during construction /// @param t_initial_radius Radius of the first timeslice /// @param t_foliation_spacing Radial separation between timeslices + /// @throws std::invalid_argument if the counts or geometry are invalid, the + /// generated points are not unique, or construction produces no vertices. + /// @throws std::out_of_range if a layer population cannot be represented. + /// @note The caller-owned @p generator may have advanced if construction + /// fails after sampling begins. FoliatedTriangulation(Int_precision const t_simplices, Int_precision const t_timeslices, cdt::Random& generator, @@ -1589,6 +1695,9 @@ namespace cdt::foliated_triangulations /// consumed during construction /// @param t_initial_radius Radius of the first timeslice /// @param t_foliation_spacing Radial separation between timeslices + /// @throws std::invalid_argument if the counts or geometry are invalid, the + /// generated points are not unique, or construction produces no vertices. + /// @throws std::out_of_range if a layer population cannot be represented. FoliatedTriangulation(Int_precision const t_simplices, Int_precision const t_timeslices, cdt::Random&& generator, @@ -1603,6 +1712,10 @@ namespace cdt::foliated_triangulations /// FoliatedTriangulation /// @param t_initial_radius Radius of first timeslice /// @param t_foliation_spacing Radial separation between timeslices + /// @pre @p t_initial_radius and @p t_foliation_spacing are finite and + /// positive. + /// @throws std::invalid_argument if @p causal_vertices is empty or contains + /// duplicate geometric points. explicit FoliatedTriangulation( Causal_vertices_t<3> const& causal_vertices, double const t_initial_radius = INITIAL_RADIUS, @@ -1620,7 +1733,9 @@ namespace cdt::foliated_triangulations [[nodiscard]] auto is_foliated() const -> bool { return has_valid_timevalues<3>(triangulation()); } // is_foliated - /// @return True if the triangulation is Delaunay + /// @return True if CGAL's geometric Delaunay validity predicate holds. + /// @note This property is expected after initialization but is not a + /// postcondition of supported Pachner moves. [[nodiscard]] auto is_delaunay() const -> bool { return triangulation().is_valid(); } // is_delaunay @@ -1636,7 +1751,10 @@ namespace cdt::foliated_triangulations return has_consistent_structure() && is_tds_valid() && check_all_cells(); } - /// @return True if the essential class invariants hold + /// @return True if the essential simulation-state invariants hold. + /// @details This deliberately checks TDS, causal, and structural + /// consistency without requiring the geometric Delaunay predicate, which + /// supported Pachner moves need not preserve. [[nodiscard]] auto is_correct() const -> bool { return is_structurally_correct(); } // is_correct @@ -1646,8 +1764,8 @@ namespace cdt::foliated_triangulations [[nodiscard]] auto is_correct_with_diagnostics() const -> bool { return is_structurally_correct() && has_consistent_derived_state(); } - /// @return True if the Foliated Triangulation has been initialized - /// correctly + /// @return True if both the simulation-state invariants and CGAL's + /// geometric Delaunay predicate hold. [[nodiscard]] auto is_initialized() const -> bool { return is_correct() && is_delaunay(); } // is_initialized @@ -1706,7 +1824,8 @@ namespace cdt::foliated_triangulations /// @return Dimensionality of triangulation data structure (int) [[nodiscard]] auto dimension() const { return triangulation().dimension(); } - /// @return Number of spacelike facets on a timeslice + /// @param timevalue Timeslice whose facets are counted. + /// @return Number of spacelike facets on the requested timeslice. [[nodiscard]] auto spacelike_face_count( Int_precision const timevalue) const noexcept -> std::size_t { @@ -1760,7 +1879,8 @@ namespace cdt::foliated_triangulations /// /// \f[R=I+S(t-1)\f] /// - /// Where I is INITIAL_RADIUS, S is RADIAL_SEPARATION, and t is timevalue + /// Where I is the initial radius, S is the foliation spacing, and t is the + /// timevalue. /// /// @param t_vertex The vertex to check /// @return The expected radial distance of the vertex with that timevalue @@ -1789,6 +1909,10 @@ namespace cdt::foliated_triangulations } // check_all_vertices /// @brief Fix vertices with wrong timevalues after foliation + /// @details Publishes a fully rebuilt triangulation only when a change is + /// required. Any handles obtained from an earlier owning snapshot remain + /// tied to that snapshot, not to the replacement stored here. + /// @return Whether any vertex timevalue was changed. [[nodiscard]] auto fix_vertices() -> bool { Delaunay updated{triangulation()}; @@ -1864,6 +1988,10 @@ namespace cdt::foliated_triangulations } // check_all_cells /// @brief Fix all cells in the triangulation + /// @details Publishes a fully rebuilt triangulation only when a change is + /// required. Any handles obtained from an earlier owning snapshot remain + /// tied to that snapshot, not to the replacement stored here. + /// @return Whether any cell classification was changed. [[nodiscard]] auto fix_cells() -> bool { Delaunay updated{triangulation()}; @@ -1936,6 +2064,7 @@ namespace cdt::foliated_triangulations } // collect_faces }; + /// Three-dimensional foliated Delaunay triangulation. using FoliatedTriangulation_3 = FoliatedTriangulation<3>; } // namespace cdt::foliated_triangulations diff --git a/include/Formatters.hpp b/include/Formatters.hpp index 911e98072..cdfe7af2d 100644 --- a/include/Formatters.hpp +++ b/include/Formatters.hpp @@ -25,11 +25,17 @@ namespace fmt template struct formatter> { - // Format specification handling - keeping it simple for now + /// @brief Accept only the default point format specification. + /// @param ctx Format-specification parser context. + /// @return Iterator at the first unconsumed format character. constexpr auto parse(format_parse_context& ctx) -> decltype(ctx.begin()) { return ctx.begin(); } - // Format the point as a string with coordinates + /// @brief Format a point using its stream insertion representation. + /// @tparam FormatContext fmt output context type. + /// @param point Point to format. + /// @param ctx Output context. + /// @return Iterator following the formatted point. template auto format(CGAL::Point_3 const& point, FormatContext& ctx) const -> decltype(ctx.out()) diff --git a/include/Geometry.hpp b/include/Geometry.hpp index e2ea9b245..877eeea69 100644 --- a/include/Geometry.hpp +++ b/include/Geometry.hpp @@ -109,6 +109,7 @@ namespace cdt } // swap }; // struct Geometry<3> + /// Three-dimensional simplex-count geometry. using Geometry_3 = Geometry<3>; } // namespace cdt diff --git a/include/Manifold.hpp b/include/Manifold.hpp index 8e5542254..8c0458716 100644 --- a/include/Manifold.hpp +++ b/include/Manifold.hpp @@ -75,15 +75,21 @@ namespace cdt::manifolds Manifold() = default; /// @brief Default copy ctor + /// @param other Manifold to copy. Manifold(Manifold const& other) = default; /// @brief Default copy assignment + /// @param other Manifold to copy. + /// @returns This manifold after replacement. auto operator=(Manifold const& other) -> Manifold& = default; /// @brief Default move ctor + /// @param other Manifold whose state is transferred. Manifold(Manifold&& other) noexcept = default; /// @brief Default move assignment + /// @param other Manifold whose state is transferred. + /// @returns This manifold after replacement. auto operator=(Manifold&& other) noexcept -> Manifold& { if (this != &other) { swap(other, *this); } @@ -115,6 +121,11 @@ namespace cdt::manifolds /// advanced during construction /// @param t_initial_radius Radius of the first timeslice /// @param t_foliation_spacing Radial separation between timeslices + /// @throws std::invalid_argument if the counts or geometry are invalid, the + /// generated points are not unique, or construction produces no vertices. + /// @throws std::out_of_range if a layer population cannot be represented. + /// @note The caller-owned @p generator may have advanced if construction + /// fails after sampling begins. Manifold(Int_precision const t_desired_simplices, Int_precision const t_desired_timeslices, cdt::Random& generator, double const t_initial_radius = INITIAL_RADIUS, @@ -132,6 +143,9 @@ namespace cdt::manifolds /// during construction /// @param t_initial_radius Radius of the first timeslice /// @param t_foliation_spacing Radial separation between timeslices + /// @throws std::invalid_argument if the counts or geometry are invalid, the + /// generated points are not unique, or construction produces no vertices. + /// @throws std::out_of_range if a layer population cannot be represented. Manifold(Int_precision const t_desired_simplices, Int_precision const t_desired_timeslices, cdt::Random&& generator, double const t_initial_radius = INITIAL_RADIUS, @@ -141,10 +155,13 @@ namespace cdt::manifolds {} /// @brief Construct manifold from Causal_vertices - /// Pass-by-value-then-move. /// @param causal_vertices Causal_vertices to place into the Manifold /// @param t_initial_radius Radius of first timeslice /// @param t_foliation_spacing Radial separation between timeslices + /// @pre @p t_initial_radius and @p t_foliation_spacing are finite and + /// positive. + /// @throws std::invalid_argument if @p causal_vertices is empty or contains + /// duplicate geometric points. explicit Manifold(Causal_vertices_t<3> const& causal_vertices, double const t_initial_radius = INITIAL_RADIUS, double const t_foliation_spacing = FOLIATION_SPACING) @@ -158,6 +175,8 @@ namespace cdt::manifolds /// @details The source remains unchanged. The returned triangulation caches /// and geometry are constructed together, so failure cannot publish a /// partially updated state. + /// @returns A rebuilt manifold with mutually consistent topology and + /// geometry caches. [[nodiscard]] auto updated() const -> Manifold { #ifndef NDEBUG @@ -213,11 +232,11 @@ namespace cdt::manifolds [[nodiscard]] auto dimensionality() const { return m_triangulation.dimension(); } - /// @brief Initial radius of the first timeslice + /// @returns Initial radius of the first timeslice. [[nodiscard]] auto initial_radius() const { return m_triangulation.initial_radius(); } - /// @brief Radial separation between timeslices + /// @returns Radial separation between timeslices. [[nodiscard]] auto foliation_spacing() const { return m_triangulation.foliation_spacing(); } @@ -246,7 +265,8 @@ namespace cdt::manifolds /// @returns Number of 2D faces in geometry data structure [[nodiscard]] auto N2() const { return m_geometry.N2; } - /// @returns Number of spacelike faces on a timeslice + /// @param timevalue Timeslice whose faces are counted. + /// @returns Number of spacelike faces on the requested timeslice. [[nodiscard]] auto spacelike_face_count( Int_precision const timevalue) const noexcept -> std::size_t { return m_triangulation.spacelike_face_count(timevalue); } @@ -349,6 +369,7 @@ namespace cdt::manifolds } // print_details }; + /// Three-dimensional spherical CDT manifold. using Manifold_3 = Manifold<3>; } // namespace cdt::manifolds diff --git a/include/Metropolis.hpp b/include/Metropolis.hpp index 289f9eb78..a6f40021b 100644 --- a/include/Metropolis.hpp +++ b/include/Metropolis.hpp @@ -17,12 +17,12 @@ #ifndef INCLUDE_METROPOLIS_HPP_ #define INCLUDE_METROPOLIS_HPP_ +#include #include #include #include -#include #include -#include +#include // CDT headers #include "Ergodic_moves_3.hpp" @@ -127,6 +127,9 @@ namespace cdt /// @param passes Number of passes of ergodic moves on triangulation. /// @param checkpoint Print/write output for every n=checkpoint passes. /// @param write_files Whether checkpoints may write triangulation files. + /// @throws std::invalid_argument If a coupling is non-finite or either + /// cadence value is nonpositive. + /// @throws std::domain_error If `alpha` is not greater than 1/2. [[maybe_unused]] MoveStrategy(long double const alpha, long double const k, long double const lambda, Int_precision const passes, @@ -145,6 +148,18 @@ namespace cdt /// @details Seed, transition-stream, action, and cadence provenance are /// derived from the actual constructor arguments. Caller metadata supplies /// initialization and requested-state context only. + /// @param alpha Timelike edge length. + /// @param k Normalized Newton constant. + /// @param lambda Normalized cosmological constant. + /// @param passes Number of passes to execute. + /// @param checkpoint Interval between checkpoint events. + /// @param write_files Whether checkpoint events may write files. + /// @param random Transition random-number stream owned by this strategy. + /// @param reproducibility Optional initialization and requested-state + /// provenance to merge with the effective run configuration. + /// @throws std::invalid_argument If a coupling is non-finite or either + /// cadence value is nonpositive. + /// @throws std::domain_error If `alpha` is not greater than 1/2. [[maybe_unused]] MoveStrategy( long double const alpha, long double const k, long double const lambda, Int_precision const passes, Int_precision const checkpoint, @@ -178,6 +193,16 @@ namespace cdt } /// @brief Construct a replayable run with an explicit RNG seed. + /// @param alpha Timelike edge length. + /// @param k Normalized Newton constant. + /// @param lambda Normalized cosmological constant. + /// @param passes Number of passes to execute. + /// @param checkpoint Interval between checkpoint events. + /// @param write_files Whether checkpoint events may write files. + /// @param seed Root seed for the transition stream. + /// @throws std::invalid_argument If a coupling is non-finite or either + /// cadence value is nonpositive. + /// @throws std::domain_error If `alpha` is not greater than 1/2. MoveStrategy(long double const alpha, long double const k, long double const lambda, Int_precision const passes, Int_precision const checkpoint, bool const write_files, @@ -232,6 +257,11 @@ namespace cdt { return m_run_statistics.transition_count; } /// @brief Materialize output provenance for the supplied canonical state. + /// @param manifold Canonical state represented by the output artifact. + /// @param artifact Kind of artifact being described. + /// @param completed_passes Number of passes completed before output. + /// @returns Provenance populated from the effective run configuration and + /// the supplied state. [[nodiscard]] auto reproducibility_metadata( ManifoldType const& manifold, utilities::ArtifactKind const artifact, Int_precision const completed_passes) const @@ -270,7 +300,8 @@ namespace cdt -> Geometry const& { return m_run_statistics.geometry; } - /// @returns The inverse Pachner move + /// @param move Pachner move whose inverse is requested. + /// @returns The inverse move, or an empty optional for an unknown value. [[nodiscard]] static constexpr auto reverse_move( move_tracker::MoveType const move) noexcept -> std::optional @@ -287,7 +318,9 @@ namespace cdt return std::nullopt; } - /// @returns The number of raw sites from which a move type is proposed + /// @param geometry Geometry whose proposal sites are counted. + /// @param move Move type whose raw proposal domain is requested. + /// @returns The number of raw sites from which the move is proposed. [[nodiscard]] static constexpr auto proposal_site_count( Geometry const& geometry, move_tracker::MoveType const move) noexcept -> Int_precision @@ -308,6 +341,10 @@ namespace cdt /// @details Move types are uniform. A raw site is then uniform within its /// type-specific domain. Inapplicable sites remain explicit /// self-transitions. + /// @param geometry Geometry defining the raw proposal sites. + /// @param move Move type selected uniformly before the site selection. + /// @returns Probability of selecting one particular raw proposal site, or + /// zero when the move has no proposal sites. [[nodiscard]] static auto proposal_probability( Geometry const& geometry, move_tracker::MoveType const move) -> mpfr_values::Value @@ -324,6 +361,13 @@ namespace cdt /// @brief Calculate the Hastings reverse-to-forward proposal ratio /// @see [Metropolis-Hastings /// algorithm](../REFERENCES.md#metropolis-hastings-algorithm) + /// @param current Geometry before applying the proposed move. + /// @param proposed Geometry after applying the proposed move. + /// @param move Forward move type. + /// @returns Reverse proposal probability divided by the forward proposal + /// probability. + /// @throws std::invalid_argument If move has no recognized inverse. + /// @throws std::logic_error If either proposal probability is zero. [[nodiscard]] static auto hastings_ratio( Geometry const& current, Geometry const& proposed, @@ -347,6 +391,9 @@ namespace cdt /// @brief Calculate the action factor \f$e^{S(T)-S(T')}\f$ /// @see [Three-dimensional CDT /// action](../REFERENCES.md#three-dimensional-cdt-2001) + /// @param current Geometry before applying the proposed move. + /// @param proposed Geometry after applying the proposed move. + /// @returns Exponential of the current action minus the proposed action. [[nodiscard]] auto action_ratio( Geometry const& current, Geometry const& proposed) const @@ -360,7 +407,12 @@ namespace cdt mpfr_values::subtract(current_action, proposed_action)); } + /// @param current Geometry before applying the proposed move. + /// @param proposed Geometry after applying the proposed move. + /// @param move Forward move type. /// @returns \f$\min(1, q(T|T')/q(T'|T)e^{S(T)-S(T')})\f$ + /// @throws std::invalid_argument If move has no recognized inverse. + /// @throws std::logic_error If either proposal probability is zero. [[nodiscard]] auto acceptance_probability( Geometry const& current, Geometry const& proposed, @@ -422,11 +474,12 @@ namespace cdt return metadata; } - auto attempt_transition(ManifoldType& current, + auto resolve_transition(ManifoldType& current, CommandResults& command_results, RunStatistics& statistics, move_tracker::MoveType const move, - long double const trial_value) -> bool + long double const trial_value) + -> ergodic_moves::MoveOutcome { if (!std::isfinite(trial_value) || trial_value < 0.0L || trial_value > 1.0L) @@ -443,9 +496,9 @@ namespace cdt { ++command_results.failed[move]; ++statistics.rejected[move]; - record_transition(statistics, move, - ergodic_moves::outcome_from(candidate.error())); - return false; + auto const outcome = ergodic_moves::outcome_from(candidate.error()); + record_transition(statistics, move, outcome); + return outcome; } if (!ergodic_moves::detail::check_move(current, *candidate, move)) { @@ -453,7 +506,7 @@ namespace cdt ++statistics.rejected[move]; record_transition(statistics, move, ergodic_moves::MoveOutcome::EXECUTION_FAILED); - return false; + return ergodic_moves::MoveOutcome::EXECUTION_FAILED; } ++command_results.succeeded[move]; @@ -466,13 +519,24 @@ namespace cdt ++statistics.accepted[move]; record_transition(statistics, move, ergodic_moves::MoveOutcome::METROPOLIS_ACCEPTED); - return true; + return ergodic_moves::MoveOutcome::METROPOLIS_ACCEPTED; } ++statistics.rejected[move]; record_transition(statistics, move, ergodic_moves::MoveOutcome::METROPOLIS_REJECTED); - return false; + return ergodic_moves::MoveOutcome::METROPOLIS_REJECTED; + } + + [[nodiscard]] auto sample_transition(ManifoldType& current, + CommandResults& command_results, + RunStatistics& statistics) + -> ergodic_moves::MetropolisTransition + { + auto const move = move_tracker::generate_random_move_3(m_generator); + auto const trial_value = utilities::generate_probability(m_generator); + return {move, resolve_transition(current, command_results, statistics, + move, trial_value)}; } [[nodiscard]] auto execute_pass(ManifoldType current, @@ -480,14 +544,11 @@ namespace cdt Int_precision const attempts) -> PassResult { auto command_results = CommandResults{}; - std::uniform_real_distribution acceptance_draw{0.0L, 1.0L}; for (auto move_attempt = Int_precision{0}; move_attempt < attempts; ++move_attempt) { - auto const move = move_tracker::generate_random_move_3(m_generator); - static_cast(attempt_transition(current, command_results, - statistics, move, - acceptance_draw(m_generator))); + static_cast( + sample_transition(current, command_results, statistics)); } return {.manifold = std::move(current), .command_results = std::move(command_results), @@ -560,27 +621,50 @@ namespace cdt } public: - /// @brief Attempt and immediately resolve one Markov transition + /// @brief Resolve one caller-selected Markov transition. /// @param current Canonical state, updated only after a successful MH /// accept /// @param move Uniformly selected move type /// @param trial_value Uniform draw in [0,1], injectable for focused tests - /// @returns True only when a valid candidate is accepted and committed + /// @returns The selected move kind and its final transition outcome. + /// @throws std::invalid_argument if @p trial_value is not finite or lies + /// outside the closed interval [0,1]. In that case @p current and the run + /// statistics remain unchanged. [[nodiscard]] auto attempt_transition(ManifoldType& current, move_tracker::MoveType const move, - long double const trial_value) -> bool + long double const trial_value) + -> ergodic_moves::MetropolisTransition { - return attempt_transition(current, m_command_results, m_run_statistics, - move, trial_value); + return {move, resolve_transition(current, m_command_results, + m_run_statistics, move, trial_value)}; } + /// @brief Sample and immediately resolve one Markov transition. + /// @details The owned transition stream supplies the move kind, acceptance + /// trial, and candidate-site draws. The report distinguishes candidate + /// success from Metropolis-Hastings acceptance. + /// @param current Canonical state, updated only when the sampled candidate + /// is accepted. + /// @returns The sampled move kind and its final transition outcome. + [[nodiscard]] auto attempt_transition(ManifoldType& current) + -> ergodic_moves::MetropolisTransition + { return sample_transition(current, m_command_results, m_run_statistics); } + /// @brief Initialize the cached action geometry from the canonical manifold + /// @param manifold Canonical state whose geometry becomes the cache. void initialize(ManifoldType const& manifold) { m_run_statistics.geometry = manifold.geometry(); } /// @brief Execute a fresh run while continuing the owned random stream. - /// @details Counters, transition statistics, and checkpoint events are - /// replaced only after the invocation completes. + /// @details The input remains unchanged. Counters, transition statistics, + /// and checkpoint events are replaced only after the invocation completes. + /// If an exception escapes, the owned random stream may already have + /// advanced even though those published results remain unchanged. + /// @param t_manifold Initial canonical state for the run. + /// @returns Canonical state after all configured passes complete. + /// @throws std::filesystem::filesystem_error if checkpoint output is + /// enabled and persistence fails; also propagates failures from move + /// generation and validation. [[nodiscard]] auto operator()(ManifoldType const& t_manifold) -> ManifoldType { @@ -625,6 +709,7 @@ namespace cdt { print_results(m_command_results, m_run_statistics); } }; // Metropolis + /// Metropolis-Hastings move strategy for the supported 3D manifold. using Metropolis_3 = MoveStrategy; } // namespace cdt diff --git a/include/Move_always.hpp b/include/Move_always.hpp index b2ded5aa3..95ceee1ae 100644 --- a/include/Move_always.hpp +++ b/include/Move_always.hpp @@ -168,8 +168,15 @@ namespace cdt { return m_command_results.failed; } /// @brief Execute a fresh run while continuing the owned random stream. - /// @details Counters and checkpoint events are replaced only after the - /// invocation completes. + /// @details The input remains unchanged. Counters and checkpoint events are + /// replaced only after the invocation completes. If an exception escapes, + /// the owned random stream may already have advanced even though those + /// published results remain unchanged. + /// @param t_manifold Initial canonical state for the run. + /// @returns Canonical state after all configured passes complete. + /// @throws std::filesystem::filesystem_error if checkpoint output is + /// enabled and persistence fails; also propagates failures from move + /// generation and validation. [[nodiscard]] auto operator()(ManifoldType const& t_manifold) -> ManifoldType { @@ -201,6 +208,7 @@ namespace cdt void print_results() const { print_results(m_command_results); } }; + /// Always-accept-applicable move strategy for the supported 3D manifold. using MoveAlways_3 = MoveStrategy; } // namespace cdt diff --git a/include/Move_command.hpp b/include/Move_command.hpp index e71209a58..271f4466d 100644 --- a/include/Move_command.hpp +++ b/include/Move_command.hpp @@ -18,6 +18,8 @@ namespace cdt { + /// @brief Queue and execute requested moves against a three-dimensional + /// manifold while tracking attempted and successful transitions. template requires(ManifoldType::dimension == 3) class MoveCommand @@ -60,10 +62,9 @@ namespace cdt /** * \brief MoveCommand ctor * \param t_manifold The manifold to perform moves on - * \details The manifold to perform moves upon should be copied by value - * into the MoveCommand to ensure moves are executed atomically and either - * succeed or fail and can be discarded without affecting the original - * manifold. + * \details The manifold is copied or moved by value so the caller's source + * is not modified. Each completed move is committed independently; a queue + * execution is not one transaction. */ explicit MoveCommand(ManifoldType t_manifold) : m_manifold{std::move(t_manifold)} @@ -71,18 +72,21 @@ namespace cdt /** * \brief Access the result manifold without transferring ownership + * \return Mutable reference valid for the lifetime of this command */ [[nodiscard]] auto result() & noexcept -> ManifoldType& { return m_manifold; } /** * \brief Access the result manifold without transferring ownership + * \return Const reference valid for the lifetime of this command */ [[nodiscard]] auto result() const& noexcept -> ManifoldType const& { return m_manifold; } /** * \brief Consume the result manifold + * \return Manifold moved out of this command */ [[nodiscard]] auto result() && noexcept -> ManifoldType { return std::move(m_manifold); } @@ -91,18 +95,21 @@ namespace cdt /** * \brief Attempted moves by MoveCommand + * \return Read-only attempted-move counters */ [[nodiscard]] auto attempted() const noexcept -> Counter const& { return m_attempted; } /** * \brief Successful moves by MoveCommand + * \return Read-only successful-move counters */ [[nodiscard]] auto succeeded() const noexcept -> Counter const& { return m_succeeded; } /** * \brief Failed moves by MoveCommand + * \return Read-only failed-move counters */ [[nodiscard]] auto failed() const noexcept -> Counter const& { return m_failed; } @@ -126,11 +133,18 @@ namespace cdt /** * \brief The number of moves on the queue + * \return Number of queued moves */ [[nodiscard]] auto size() const noexcept { return m_moves.size(); } /** * \brief Execute all moves in the queue on the manifold + * \details Completed moves remain committed. If an exception escapes while + * attempting the current move, its attempted counter has been incremented, + * the move remains queued, earlier moves and their counters remain + * committed, and \p generator may already have advanced. + * \tparam Generator Uniform random bit generator type + * \param generator Generator advanced by stochastic move selection */ template void execute(Generator& generator) @@ -167,6 +181,11 @@ namespace cdt } // execute /// @brief Apply one queued move using the caller-owned random stream. + /// @tparam Generator Uniform random bit generator type. + /// @param manifold Source manifold, which remains unchanged. + /// @param move Pachner move to attempt. + /// @param generator Generator advanced by stochastic move selection. + /// @return Moved manifold, or a structured failure reason. template [[nodiscard]] static auto apply_random_move( ManifoldType const& manifold, move_tracker::MoveType const move, diff --git a/include/Move_outcome.hpp b/include/Move_outcome.hpp index 2d2c722ee..0defdeccd 100644 --- a/include/Move_outcome.hpp +++ b/include/Move_outcome.hpp @@ -21,13 +21,13 @@ namespace cdt::ergodic_moves /// @brief Actionable reasons a raw move request cannot produce a new state. enum class MoveFailure : std::uint8_t { - NO_CANDIDATE, - INVALID_TOPOLOGY, - CAUSAL_INVALIDITY, - STALE_CANDIDATE, - EXECUTION_FAILURE, - INVARIANT_VIOLATION, - UNKNOWN_MOVE + NO_CANDIDATE, ///< No raw proposal site is available. + INVALID_TOPOLOGY, ///< The proposal site is not in the triangulation. + CAUSAL_INVALIDITY, ///< The proposal violates a causal move invariant. + STALE_CANDIDATE, ///< A prepared proposal no longer resolves. + EXECUTION_FAILURE, ///< CGAL rejected the prepared mutation. + INVARIANT_VIOLATION, ///< A post-mutation manifold check failed. + UNKNOWN_MOVE ///< The requested move kind is unsupported. }; /// @brief Typed error returned by move preparation or private execution. @@ -35,7 +35,9 @@ namespace cdt::ergodic_moves /// derived at the presentation boundary rather than stored in the hot path. struct MoveError { - MoveFailure category; + /// Structured rejection or execution-failure category. + MoveFailure category; + /// Pachner move whose proposal or execution failed. move_tracker::MoveType requested_move; /// @returns The structured rejection or execution-failure category. @@ -68,7 +70,9 @@ namespace cdt::ergodic_moves return "The move failed for an unknown reason."; } - auto operator==(MoveError const&) const -> bool = default; + /// @param other Error to compare. + /// @return Whether category and requested move are equal. + auto operator==(MoveError const& other) const -> bool = default; }; /// @brief Value returned by a fallible Pachner-move transformation. @@ -78,14 +82,57 @@ namespace cdt::ergodic_moves /// @brief Typed state used to route proposal and execution accounting. enum class MoveOutcome : std::uint8_t { - INAPPLICABLE = 0, - METROPOLIS_ACCEPTED = 1, - METROPOLIS_REJECTED = 2, - EXECUTION_FAILED = 3, - SUCCEEDED = 4 + INAPPLICABLE = 0, ///< The sampled raw site cannot support the move. + METROPOLIS_ACCEPTED = 1, ///< Metropolis-Hastings accepted the proposal. + METROPOLIS_REJECTED = 2, ///< Metropolis-Hastings rejected the proposal. + EXECUTION_FAILED = 3, ///< Mutation failed after proposal preparation. + SUCCEEDED = 4 ///< The requested transition completed. + }; + + /// @brief Result of one fully sampled Metropolis-Hastings transition. + /// @details Candidate success and Metropolis acceptance are distinct: a + /// valid candidate may still be rejected and leave the canonical state + /// unchanged. + class MetropolisTransition + { + move_tracker::MoveType m_move; + MoveOutcome m_outcome; + + public: + /// @param move Sampled Pachner move kind. + /// @param outcome Final accounting outcome for the transition. + constexpr MetropolisTransition(move_tracker::MoveType const move, + MoveOutcome const outcome) noexcept + : m_move{move}, m_outcome{outcome} + {} + + /// @returns The sampled Pachner move kind. + [[nodiscard]] constexpr auto move() const noexcept -> move_tracker::MoveType + { return m_move; } + + /// @returns The final transition-accounting outcome. + [[nodiscard]] constexpr auto outcome() const noexcept -> MoveOutcome + { return m_outcome; } + + /// @returns Whether proposal construction and validation succeeded. + [[nodiscard]] constexpr auto successful() const noexcept -> bool + { + return m_outcome == MoveOutcome::METROPOLIS_ACCEPTED || + m_outcome == MoveOutcome::METROPOLIS_REJECTED; + } + + /// @returns Whether Metropolis-Hastings accepted and committed the move. + [[nodiscard]] constexpr auto accepted() const noexcept -> bool + { return m_outcome == MoveOutcome::METROPOLIS_ACCEPTED; } + + /// @param other Transition report to compare. + /// @return Whether move and outcome are equal. + auto operator==(MetropolisTransition const& other) const -> bool = default; }; /// @brief Classify a structured move error for counter accounting. + /// @param error Structured move failure. + /// @return The counter outcome associated with `error`. [[nodiscard]] constexpr auto outcome_from(MoveError const error) noexcept -> MoveOutcome { @@ -104,6 +151,8 @@ namespace cdt::ergodic_moves } /// @brief Enable direct formatting through fmt/spdlog. + /// @param error Structured move failure. + /// @return Stable human-readable diagnostic text. [[nodiscard]] constexpr auto format_as(MoveError const error) noexcept -> std::string_view { return error.message(); } diff --git a/include/Move_run.hpp b/include/Move_run.hpp index 7a32fd950..d24b4ef69 100644 --- a/include/Move_run.hpp +++ b/include/Move_run.hpp @@ -26,8 +26,8 @@ namespace cdt /// @brief Reasons raw move-run cadence cannot become a domain value. enum class MoveRunCadenceError { - NONPOSITIVE_PASSES, - NONPOSITIVE_CHECKPOINT + NONPOSITIVE_PASSES, ///< The requested pass count is not positive. + NONPOSITIVE_CHECKPOINT ///< The checkpoint interval is not positive. }; /// @brief Positive pass count and checkpoint interval for a move run. diff --git a/include/Move_strategy.hpp b/include/Move_strategy.hpp index 9d1339d9e..f98a49d7f 100644 --- a/include/Move_strategy.hpp +++ b/include/Move_strategy.hpp @@ -20,8 +20,8 @@ namespace cdt */ enum class MoveStrategyKind { - MOVE_ALWAYS, - METROPOLIS + MOVE_ALWAYS, ///< Execute every applicable proposal. + METROPOLIS ///< Apply Metropolis-Hastings acceptance. }; /** diff --git a/include/Move_tracker.hpp b/include/Move_tracker.hpp index dd33a4ac9..4147e714d 100644 --- a/include/Move_tracker.hpp +++ b/include/Move_tracker.hpp @@ -18,12 +18,14 @@ #include #include #include +#include #include #include "Settings.hpp" namespace cdt::move_tracker { + /// Number of supported Pachner move kinds in three dimensions. inline constexpr std::size_t NUMBER_OF_3D_MOVES = 5; /** @@ -31,13 +33,31 @@ namespace cdt::move_tracker */ enum class [[nodiscard("This contains data!")]] MoveType { - TWO_THREE = 0, - THREE_TWO = 1, - TWO_SIX = 2, - SIX_TWO = 3, - FOUR_FOUR = 4 + TWO_THREE = 0, ///< Replace two tetrahedra with three. + THREE_TWO = 1, ///< Replace three tetrahedra with two. + TWO_SIX = 2, ///< Replace two tetrahedra with six. + SIX_TWO = 3, ///< Replace six tetrahedra with two. + FOUR_FOUR = 4 ///< Exchange a causal four-tetrahedron diamond. }; + /// @brief Enable direct formatting through fmt/spdlog. + /// @param move Pachner move kind. + /// @return Stable tuple notation for the move. + [[nodiscard]] constexpr auto format_as(MoveType const move) noexcept + -> std::string_view + { + using enum MoveType; + switch (move) + { + case TWO_THREE: return "(2,3)"; + case THREE_TWO: return "(3,2)"; + case TWO_SIX: return "(2,6)"; + case SIX_TWO: return "(6,2)"; + case FOUR_FOUR: return "(4,4)"; + } + return "unknown"; + } + /** * \brief Convert enum to integer * \tparam Enumeration The enum type @@ -68,7 +88,10 @@ namespace cdt::move_tracker return moves[move_choice]; } // move_from_index - /// Generate a uniformly distributed 3D ergodic move from caller-owned RNG. + /// @brief Generate a uniformly distributed 3D move from caller-owned RNG. + /// @tparam Generator Uniform random bit generator type. + /// @param generator Generator whose state advances during sampling. + /// @return One uniformly sampled MoveType. template [[nodiscard]] inline auto generate_random_move_3(Generator& generator) -> MoveType diff --git a/include/Mpfr_value.hpp b/include/Mpfr_value.hpp index 0d360503a..aa9d9f364 100644 --- a/include/Mpfr_value.hpp +++ b/include/Mpfr_value.hpp @@ -19,6 +19,7 @@ namespace cdt::mpfr_values { + /// @brief Owning arbitrary-precision floating-point value used by CDT++. using Value = CGAL::Gmpfr; /// MPFR round-to-nearest with ties to an even significand. @@ -31,11 +32,15 @@ namespace cdt::mpfr_values static_assert(std::is_nothrow_destructible_v, "MPFR values must release their resources without throwing."); + /// @brief Precision in bits assigned to values created by this namespace. inline constexpr auto precision = static_cast(PRECISION); + /// @return An exact zero at the project precision. [[nodiscard]] inline auto zero() -> Value { return Value{0, precision}; } + /// @param value Signed integer to represent exactly. + /// @return `value` converted at the project precision. [[nodiscard]] inline auto from_integer(long const value) -> Value { auto result = zero(); @@ -43,6 +48,8 @@ namespace cdt::mpfr_values return result; } + /// @param value Binary floating-point value to convert. + /// @return `value` rounded to the project precision. [[nodiscard]] inline auto from_long_double(long double const value) -> Value { auto result = zero(); @@ -50,6 +57,10 @@ namespace cdt::mpfr_values return result; } + /// @param value Null-terminated base-10 representation. + /// @return The parsed value at the project precision. + /// @throws std::invalid_argument if `value` is null or is not a valid MPFR + /// decimal representation. [[nodiscard]] inline auto from_decimal(char const* value) -> Value { if (value == nullptr) @@ -64,6 +75,7 @@ namespace cdt::mpfr_values return result; } + /// @return The MPFR constant pi rounded to the project precision. [[nodiscard]] inline auto pi() -> Value { auto result = zero(); @@ -71,6 +83,9 @@ namespace cdt::mpfr_values return result; } + /// @param left Left operand. + /// @param right Right operand. + /// @return `left + right` rounded according to rounding_mode. [[nodiscard]] inline auto add(Value const& left, Value const& right) -> Value { auto result = zero(); @@ -78,6 +93,9 @@ namespace cdt::mpfr_values return result; } + /// @param left Left operand. + /// @param right Right operand. + /// @return `left - right` rounded according to rounding_mode. [[nodiscard]] inline auto subtract(Value const& left, Value const& right) -> Value { @@ -86,6 +104,9 @@ namespace cdt::mpfr_values return result; } + /// @param left Left operand. + /// @param right Right operand. + /// @return `left * right` rounded according to rounding_mode. [[nodiscard]] inline auto multiply(Value const& left, Value const& right) -> Value { @@ -94,6 +115,9 @@ namespace cdt::mpfr_values return result; } + /// @param numerator Dividend. + /// @param denominator Divisor. + /// @return `numerator / denominator` with MPFR exceptional-value semantics. [[nodiscard]] inline auto divide(Value const& numerator, Value const& denominator) -> Value { @@ -102,6 +126,8 @@ namespace cdt::mpfr_values return result; } + /// @param value Input value. + /// @return The MPFR square root of `value`. [[nodiscard]] inline auto square_root(Value const& value) -> Value { auto result = zero(); @@ -109,6 +135,8 @@ namespace cdt::mpfr_values return result; } + /// @param value Input value. + /// @return The MPFR inverse hyperbolic sine of `value`. [[nodiscard]] inline auto inverse_hyperbolic_sine(Value const& value) -> Value { auto result = zero(); @@ -116,6 +144,8 @@ namespace cdt::mpfr_values return result; } + /// @param value Input value in the MPFR arccosine domain. + /// @return The MPFR arccosine of `value` in radians. [[nodiscard]] inline auto arc_cosine(Value const& value) -> Value { auto result = zero(); @@ -123,6 +153,8 @@ namespace cdt::mpfr_values return result; } + /// @param value Input value. + /// @return The additive inverse of `value`. [[nodiscard]] inline auto negate(Value const& value) -> Value { auto result = zero(); @@ -130,6 +162,8 @@ namespace cdt::mpfr_values return result; } + /// @param value Input value. + /// @return The MPFR exponential of `value`. [[nodiscard]] inline auto exponential(Value const& value) -> Value { auto result = zero(); @@ -137,9 +171,13 @@ namespace cdt::mpfr_values return result; } + /// @param value MPFR value to narrow. + /// @return The nearest representable `double` under rounding_mode. [[nodiscard]] inline auto to_double(Value const& value) -> double { return mpfr_get_d(value.fr(), rounding_mode); } + /// @param value MPFR value to narrow. + /// @return The nearest representable `long double` under rounding_mode. [[nodiscard]] inline auto to_long_double(Value const& value) -> long double { return mpfr_get_ld(value.fr(), rounding_mode); } } // namespace cdt::mpfr_values diff --git a/include/Random.hpp b/include/Random.hpp index 83de00db9..041856713 100644 --- a/include/Random.hpp +++ b/include/Random.hpp @@ -27,14 +27,18 @@ namespace cdt public: constexpr RandomSeed() noexcept = default; + /// @param value Root entropy value to retain. explicit constexpr RandomSeed(std::uint64_t const value) noexcept : m_value{value} {} + /// @return The retained root entropy value. [[nodiscard]] constexpr auto value() const noexcept -> std::uint64_t { return m_value; } - [[nodiscard]] auto operator==(RandomSeed const&) const noexcept + /// @param other Seed to compare. + /// @return Whether both seeds retain the same value. + [[nodiscard]] auto operator==(RandomSeed const& other) const noexcept -> bool = default; }; @@ -45,36 +49,52 @@ namespace cdt public: constexpr RandomStream() noexcept = default; + /// @param value PCG sequence selector to retain. explicit constexpr RandomStream(std::uint64_t const value) noexcept : m_value{value} {} + /// @return The retained PCG sequence selector. [[nodiscard]] constexpr auto value() const noexcept -> std::uint64_t { return m_value; } - [[nodiscard]] auto operator==(RandomStream const&) const noexcept + /// @param other Stream selector to compare. + /// @return Whether both selectors retain the same value. + [[nodiscard]] auto operator==(RandomStream const& other) const noexcept -> bool = default; }; + /// @param seed Seed to expose to fmt-compatible formatting. + /// @return The seed's unsigned representation. [[nodiscard]] constexpr auto format_as(RandomSeed const seed) noexcept -> std::uint64_t { return seed.value(); } + /// @param stream Stream selector to expose to fmt-compatible formatting. + /// @return The selector's unsigned representation. [[nodiscard]] constexpr auto format_as(RandomStream const stream) noexcept -> std::uint64_t { return stream.value(); } + /// @param output Destination stream. + /// @param seed Seed to write as an unsigned integer. + /// @return `output` after insertion. inline auto operator<<(std::ostream& output, RandomSeed const seed) -> std::ostream& { return output << seed.value(); } + /// @param output Destination stream. + /// @param stream Stream selector to write as an unsigned integer. + /// @return `output` after insertion. inline auto operator<<(std::ostream& output, RandomStream const stream) -> std::ostream& { return output << stream.value(); } namespace random_streams { + /// Stream reserved for initial triangulation generation. inline constexpr RandomStream initialization{0}; + /// Stream reserved for stochastic state transitions. inline constexpr RandomStream transitions{1}; } // namespace random_streams @@ -92,6 +112,7 @@ namespace cdt class Random final { public: + /// Unsigned result type required by `std::uniform_random_bit_generator`. using result_type = pcg64::result_type; private: @@ -113,6 +134,7 @@ namespace cdt Random() : Random{entropy_seed()} {} /// @brief Construct a root stream from a raw seed value. + /// @param seed Root seed recorded for the run. explicit Random(std::uint64_t const seed) : Random{RandomSeed{seed}} {} /// @brief Construct a reproducible PCG stream without consulting entropy. @@ -124,12 +146,15 @@ namespace cdt : m_seed{seed}, m_stream{stream}, m_engine{seed.value(), stream.value()} {} + /// @return The minimum value the engine can generate. [[nodiscard]] static constexpr auto min() noexcept -> result_type { return pcg64::min(); } + /// @return The maximum value the engine can generate. [[nodiscard]] static constexpr auto max() noexcept -> result_type { return pcg64::max(); } + /// @return The next value from this engine, advancing its state. [[nodiscard]] auto operator()() -> result_type { return m_engine(); } /// @returns The effective root seed for replaying this run. @@ -140,6 +165,8 @@ namespace cdt { return m_stream; } /// @brief Create a fresh reproducible stream from the same root seed. + /// @param stream PCG sequence selector for the new engine. + /// @return A new engine at the beginning of the selected sequence. [[nodiscard]] auto split(RandomStream const stream) const -> Random { return Random{m_seed, stream}; } }; diff --git a/include/Runtime_config.hpp b/include/Runtime_config.hpp index 19dc54b52..5dac7a2f2 100644 --- a/include/Runtime_config.hpp +++ b/include/Runtime_config.hpp @@ -59,30 +59,43 @@ namespace cdt::runtime_config {} public: - Triangulation(Triangulation const&) = default; - Triangulation(Triangulation&&) noexcept = default; - auto operator=(Triangulation const&) -> Triangulation& = default; - auto operator=(Triangulation&&) noexcept -> Triangulation& = default; - ~Triangulation() = default; - + /// @param other Validated configuration to copy. + Triangulation(Triangulation const& other) = default; + /// @param other Validated configuration to move. + Triangulation(Triangulation&& other) noexcept = default; + /// @param other Validated configuration to copy. + /// @return This configuration after assignment. + auto operator=(Triangulation const& other) -> Triangulation& = default; + /// @param other Validated configuration to move. + /// @return This configuration after assignment. + auto operator=(Triangulation&& other) noexcept -> Triangulation& = default; + ~Triangulation() = default; + + /// @return Validated spatial-topology label. [[nodiscard]] auto topology() const noexcept -> Topology { return m_topology; } + /// @return Requested target number of simplices. [[nodiscard]] auto simplices() const noexcept -> Int_precision { return m_simplices; } + /// @return Requested number of timeslices. [[nodiscard]] auto timeslices() const noexcept -> Int_precision { return m_timeslices; } + /// @return Validated dimensionality, currently always three. [[nodiscard]] auto dimensions() const noexcept -> Int_precision { return m_dimensions; } + /// @return Positive finite radius of the initial timeslice. [[nodiscard]] auto initial_radius() const noexcept -> double { return m_initial_radius; } + /// @return Positive finite spacing between successive timeslices. [[nodiscard]] auto foliation_spacing() const noexcept -> double { return m_foliation_spacing; } + /// @return Root random seed retained for reproducibility. [[nodiscard]] auto seed() const noexcept -> cdt::RandomSeed { return m_seed; } @@ -125,28 +138,41 @@ namespace cdt::runtime_config {} public: - Simulation(Simulation const&) = default; - Simulation(Simulation&&) noexcept = default; - auto operator=(Simulation const&) -> Simulation& = default; - auto operator=(Simulation&&) noexcept -> Simulation& = default; - ~Simulation() = default; - + /// @param other Validated simulation configuration to copy. + Simulation(Simulation const& other) = default; + /// @param other Validated simulation configuration to move. + Simulation(Simulation&& other) noexcept = default; + /// @param other Validated simulation configuration to copy. + /// @return This configuration after assignment. + auto operator=(Simulation const& other) -> Simulation& = default; + /// @param other Validated simulation configuration to move. + /// @return This configuration after assignment. + auto operator=(Simulation&& other) noexcept -> Simulation& = default; + ~Simulation() = default; + + /// @return Validated triangulation configuration retained by this run. [[nodiscard]] auto triangulation() const noexcept -> Triangulation const& { return m_triangulation; } + /// @return Wick-rotation parameter, greater than 1/2. [[nodiscard]] auto alpha() const noexcept -> long double { return m_alpha; } + /// @return Finite inverse Newton coupling. [[nodiscard]] auto k() const noexcept -> long double { return m_k; } + /// @return Finite cosmological coupling. [[nodiscard]] auto lambda() const noexcept -> long double { return m_lambda; } + /// @return Positive number of configured move passes. [[nodiscard]] auto passes() const noexcept -> Int_precision { return m_passes; } + /// @return Positive checkpoint interval in move passes. [[nodiscard]] auto checkpoint() const noexcept -> Int_precision { return m_checkpoint; } + /// @return Whether the simulation should publish persistence artifacts. [[nodiscard]] auto write_files() const noexcept -> bool { return m_write_files; } }; @@ -255,7 +281,25 @@ namespace cdt::runtime_config } } // namespace detail - /// Validate raw triangulation options and narrow them into project types. + /// @brief Validate raw triangulation options and narrow them into project + /// types. + /// @param spherical Whether spherical topology was selected. + /// @param toroidal Whether toroidal topology was selected; currently + /// rejected. + /// @param simplices Requested target number of simplices; must be at least + /// two. + /// @param timeslices Requested number of timeslices; must be at least two. + /// @param dimensions Requested dimensionality; must equal three. + /// @param initial_radius Positive finite radius of the first timeslice. + /// @param foliation_spacing Positive finite spacing between timeslices. + /// @param seed Root random seed to retain. + /// @param threads Positive maximum concurrency; serial builds require one. + /// @return A configuration containing only validated domain values. + /// @throws std::invalid_argument for conflicting/unsupported topology, + /// invalid dimensions or counts, non-finite/non-positive geometry, or an + /// unsupported serial-build thread count. + /// @throws std::out_of_range when a count exceeds a project type or generated + /// population bound. [[nodiscard]] inline auto make_triangulation( bool const spherical, bool const toroidal, long long const simplices, long long const timeslices, long long const dimensions, @@ -309,7 +353,19 @@ namespace cdt::runtime_config checked_threads}; } - /// Validate the complete simulation configuration. + /// @brief Validate the complete simulation configuration. + /// @param triangulation Previously validated triangulation configuration. + /// @param alpha Finite Wick-rotation parameter greater than 1/2. + /// @param k Finite inverse Newton coupling. + /// @param lambda Finite cosmological coupling. + /// @param passes Positive number of move passes. + /// @param checkpoint Positive checkpoint interval in move passes. + /// @param write_files Whether the run should publish persistence artifacts. + /// @return A complete validated simulation configuration. + /// @throws std::invalid_argument for non-finite couplings or non-positive + /// cadence values. + /// @throws std::domain_error if `alpha` is not greater than 1/2. + /// @throws std::out_of_range when a cadence value exceeds Int_precision. [[nodiscard]] inline auto make_simulation( Triangulation const& triangulation, long double const alpha, long double const k, long double const lambda, long long const passes, diff --git a/include/S3Action.hpp b/include/S3Action.hpp index 02a2ca679..c13727dc4 100644 --- a/include/S3Action.hpp +++ b/include/S3Action.hpp @@ -30,6 +30,9 @@ namespace cdt::s3_action { + /// @brief Finite physical couplings used to evaluate the Euclidean action. + /// @details Construct instances with make_physical_parameters() so invalid + /// or non-finite coupling combinations are rejected at the API boundary. class PhysicalParameters { long double m_alpha; @@ -47,11 +50,21 @@ namespace cdt::s3_action -> PhysicalParameters; public: + /// @return Wick-rotation parameter, constrained to be greater than 1/2. [[nodiscard]] constexpr auto alpha() const noexcept { return m_alpha; } + /// @return Inverse Newton coupling supplied at construction. [[nodiscard]] constexpr auto k() const noexcept { return m_k; } + /// @return Cosmological coupling supplied at construction. [[nodiscard]] constexpr auto lambda() const noexcept { return m_lambda; } }; + /// @brief Validate physical couplings for three-dimensional action APIs. + /// @param alpha Wick-rotation parameter; must be finite and greater than 1/2. + /// @param k Inverse Newton coupling; must be finite. + /// @param lambda Cosmological coupling; must be finite. + /// @return Validated coupling values. + /// @throws std::invalid_argument if any coupling is non-finite. + /// @throws std::domain_error if `alpha` is not greater than 1/2. [[nodiscard]] inline auto make_physical_parameters(long double const alpha, long double const k, long double const lambda) diff --git a/include/Settings.hpp b/include/Settings.hpp index 16946ac39..664795e2b 100644 --- a/include/Settings.hpp +++ b/include/Settings.hpp @@ -30,8 +30,10 @@ namespace cdt using Int_precision = std::int32_t; #ifdef _WIN32 +/// Cross-platform spelling of the current function signature for diagnostics. #define CDT_PRETTY_FUNCTION __FUNCSIG__ #else +/// Cross-platform spelling of the current function signature for diagnostics. #define CDT_PRETTY_FUNCTION __PRETTY_FUNCTION__ #endif @@ -41,8 +43,9 @@ namespace cdt /// Sets the precision for MPFR. inline constexpr Int_precision PRECISION = 256; - /// Default foliated triangulation spacings + /// Default initial radius for generated foliated triangulations. inline constexpr double INITIAL_RADIUS = 1.0; + /// Default distance between successive foliated timeslices. inline constexpr double FOLIATION_SPACING = 1.0; /// Sets epsilon values for floating point comparisons diff --git a/include/Utilities.hpp b/include/Utilities.hpp index 06e397440..ddd6d3aaf 100644 --- a/include/Utilities.hpp +++ b/include/Utilities.hpp @@ -66,10 +66,12 @@ namespace cdt { + /// @brief Spatial-topology label stored by configuration and persistence + /// APIs. enum class Topology { - TOROIDAL, - SPHERICAL + TOROIDAL, ///< Reserved for toroidal slices; construction is unsupported. + SPHERICAL ///< Supported spherical spatial slices. }; /// @brief Convert Topology to string output @@ -90,11 +92,12 @@ namespace cdt namespace cdt::utilities { + /// @brief Persistence artifact represented by a triangulation payload. enum class ArtifactKind { - INITIAL_TRIANGULATION, - CHECKPOINT, - FINAL_TRIANGULATION + INITIAL_TRIANGULATION, ///< Initial state before stochastic transitions. + CHECKPOINT, ///< Intermediate snapshot during a move run. + FINAL_TRIANGULATION ///< Final state after the configured move run. }; /// @brief Provenance recorded next to every stochastic triangulation. @@ -105,36 +108,41 @@ namespace cdt::utilities /// responsible for supplying truthful run configuration and RNG provenance. struct Reproducibility_metadata { - ArtifactKind artifact{ArtifactKind::FINAL_TRIANGULATION}; - cdt::RandomSeed seed{}; + ArtifactKind artifact{ + ArtifactKind::FINAL_TRIANGULATION}; ///< Artifact role. + cdt::RandomSeed seed{}; ///< Root seed for the recorded run. cdt::RandomStream initialization_stream{ - cdt::random_streams::initialization}; - cdt::RandomStream transition_stream{cdt::random_streams::transitions}; - Topology topology{Topology::SPHERICAL}; - Int_precision dimension{}; - Int_precision desired_simplices{}; - Int_precision desired_timeslices{}; - Int_precision actual_vertices{}; - Int_precision actual_edges{}; - Int_precision actual_faces{}; - Int_precision actual_simplices{}; - Int_precision minimum_timeslice{}; - Int_precision maximum_timeslice{}; - double initial_radius{}; - double foliation_spacing{}; - std::optional alpha; - std::optional k; - std::optional lambda; - std::optional configured_passes; - std::optional checkpoint_interval; - std::optional completed_passes; - std::optional max_threads; - std::optional transition_trace; - std::optional transition_count; - std::optional placement_fingerprint; - std::optional topology_fingerprint; + cdt::random_streams::initialization}; ///< Initialization stream. + cdt::RandomStream transition_stream{ + cdt::random_streams::transitions}; ///< Transition stream. + Topology topology{Topology::SPHERICAL}; ///< Spatial-topology label. + Int_precision dimension{}; ///< Spatial dimension. + Int_precision desired_simplices{}; ///< Requested simplex target. + Int_precision desired_timeslices{}; ///< Requested timeslice count. + Int_precision actual_vertices{}; ///< Persisted finite vertices. + Int_precision actual_edges{}; ///< Persisted finite edges. + Int_precision actual_faces{}; ///< Persisted finite faces. + Int_precision actual_simplices{}; ///< Persisted finite simplices. + Int_precision minimum_timeslice{}; ///< Minimum persisted time label. + Int_precision maximum_timeslice{}; ///< Maximum persisted time label. + double initial_radius{}; ///< Initial spherical radius. + double foliation_spacing{}; ///< Radius increment per slice. + std::optional alpha; ///< Optional Wick-rotation parameter. + std::optional k; ///< Optional inverse Newton coupling. + std::optional lambda; ///< Optional cosmological coupling. + std::optional configured_passes; ///< Requested move passes. + std::optional configured_attempts; ///< Explicit attempts. + std::optional checkpoint_interval; ///< Checkpoint cadence. + std::optional completed_passes; ///< Passes before snapshot. + std::optional max_threads; ///< Configured concurrency. + std::optional transition_trace; ///< Ordered trace hash. + std::optional transition_count; ///< Hashed transitions. + std::optional placement_fingerprint; ///< Coordinate hash. + std::optional topology_fingerprint; ///< Incidence hash. }; + /// @param payload Triangulation payload path. + /// @return Sidecar path formed by appending `.meta`. [[nodiscard]] inline auto metadata_filename( std::filesystem::path const& payload) -> std::filesystem::path { @@ -637,6 +645,7 @@ namespace cdt::utilities append_optional("k", metadata.k); append_optional("lambda", metadata.lambda); append_optional("configured_passes", metadata.configured_passes); + append_optional("configured_attempts", metadata.configured_attempts); append_optional("checkpoint_interval", metadata.checkpoint_interval); append_optional("completed_passes", metadata.completed_passes); append_optional("parallel.max_threads", metadata.max_threads); @@ -1114,6 +1123,13 @@ namespace cdt::utilities "Persistence metadata contains an invalid run configuration", path, std::make_error_code(std::errc::illegal_byte_sequence)); } + if (values.contains("configured_attempts") && + parse_integer_field("configured_attempts") <= 0) + { + throw std::filesystem::filesystem_error( + "Persistence metadata contains invalid configured attempts", path, + std::make_error_code(std::errc::illegal_byte_sequence)); + } if (artifact == ArtifactKind::CHECKPOINT && !values.contains("completed_passes")) @@ -1661,6 +1677,10 @@ namespace cdt::utilities return filename; } // make_filename + /// @brief Generate the conventional state-derived OFF filename. + /// @tparam ManifoldType Supported manifold type. + /// @param manifold Manifold whose geometry and foliation name the artifact. + /// @return Timestamped OFF path. template [[nodiscard]] auto make_filename(ManifoldType const& manifold) { @@ -1671,6 +1691,10 @@ namespace cdt::utilities } // make_filename /// @brief Generate a filename that records the effective run seed. + /// @tparam ManifoldType Supported manifold type. + /// @param manifold Manifold whose state names the artifact. + /// @param seed Effective root seed. + /// @return OFF path containing the seed. template [[nodiscard]] auto make_filename(ManifoldType const& manifold, cdt::RandomSeed const seed) @@ -1682,6 +1706,11 @@ namespace cdt::utilities } /// @brief Generate a checkpoint filename that records seed and pass. + /// @tparam ManifoldType Supported manifold type. + /// @param manifold Manifold whose state names the artifact. + /// @param seed Effective root seed. + /// @param completed_passes Number of completed move passes. + /// @return OFF path containing seed and pass count. template [[nodiscard]] auto make_filename(ManifoldType const& manifold, cdt::RandomSeed const seed, @@ -1712,10 +1741,14 @@ namespace cdt::utilities /// @brief Write triangulation to file /// @details This function writes the Delaunay triangulation in the manifold /// to an OFF file. http://www.geomview.org/docs/html/OFF.html#OFF Provides - /// strong exception-safety. + /// strong exception-safety for the destination file. Writes are serialized + /// within the process and validated before an atomic replacement. /// @tparam TriangulationType The type of triangulation /// @param filename The filename to write to /// @param triangulation The triangulation to write + /// @throws std::logic_error for a same-thread reentrant write. + /// @throws std::filesystem::filesystem_error if serialization, validation, + /// or replacement fails. template void write_file(std::filesystem::path const& filename, TriangulationType const& triangulation) @@ -1723,9 +1756,20 @@ namespace cdt::utilities detail::write_payload(filename, triangulation, std::nullopt); } // write_file - /// @brief Atomically replace a triangulation and its verifiable provenance. + /// @brief Replace a triangulation and its verifiable provenance atomically + /// per file. /// @details Derives payload-dependent metadata from the triangulation and - /// validates the complete typed manifest before either file is published. + /// validates both temporary files before publishing the manifest and then + /// the payload. The pair is not a filesystem transaction: interruption + /// between replacements can leave a detectable checksum mismatch, which + /// read_file() rejects. + /// @tparam TriangulationType Supported Delaunay triangulation type. + /// @param filename Destination OFF path. + /// @param triangulation Triangulation payload to serialize. + /// @param metadata Run configuration and stochastic provenance. + /// @throws std::logic_error for a same-thread reentrant write. + /// @throws std::filesystem::filesystem_error if serialization, validation, + /// or either replacement fails. template void write_file(std::filesystem::path const& filename, TriangulationType const& triangulation, @@ -1733,6 +1777,9 @@ namespace cdt::utilities { detail::write_payload(filename, triangulation, metadata); } /// @brief Fingerprint vertices, causal metadata, and abstract finite cells. + /// @tparam ManifoldType Supported manifold type. + /// @param manifold Manifold to fingerprint without mutation. + /// @return Stable topology fingerprint independent of handle identity. template [[nodiscard]] auto canonical_topology_fingerprint( ManifoldType const& manifold) -> std::uint64_t @@ -1742,6 +1789,9 @@ namespace cdt::utilities } /// @brief Fingerprint finite vertex coordinates and timeslice metadata. + /// @tparam ManifoldType Supported manifold type. + /// @param manifold Manifold to fingerprint without mutation. + /// @return Stable placement fingerprint independent of handle identity. template [[nodiscard]] auto canonical_placement_fingerprint( ManifoldType const& manifold) -> std::uint64_t @@ -1751,6 +1801,11 @@ namespace cdt::utilities } /// @brief Build provenance from a canonical manifold state. + /// @tparam ManifoldType Supported manifold type. + /// @param manifold Canonical state summarized by the metadata. + /// @param seed Effective root seed. + /// @param artifact Artifact role to record. + /// @return Reconciled geometry, foliation, seed, and fingerprint metadata. template [[nodiscard]] auto make_reproducibility_metadata(ManifoldType const& manifold, cdt::RandomSeed const seed, @@ -1776,6 +1831,9 @@ namespace cdt::utilities } /// @brief Refresh state-dependent provenance after a transition sequence. + /// @tparam ManifoldType Supported manifold type. + /// @param metadata Metadata record to update in place. + /// @param manifold Canonical state supplying counts and fingerprints. template void update_reproducibility_state(Reproducibility_metadata& metadata, ManifoldType const& manifold) @@ -1800,6 +1858,8 @@ namespace cdt::utilities /// implemented using the << operator for triangulations. /// @tparam ManifoldType The manifold type /// @param t_universe The simplicial manifold + /// @throws std::logic_error for a same-thread reentrant write. + /// @throws std::filesystem::filesystem_error if persistence fails. template void write_file(ManifoldType const& t_universe) { @@ -1809,6 +1869,11 @@ namespace cdt::utilities } // write_file /// @brief Write a triangulation with the effective seed in its filename. + /// @tparam ManifoldType Supported manifold type. + /// @param t_universe Manifold to serialize. + /// @param seed Effective root seed. + /// @throws std::logic_error for a same-thread reentrant write. + /// @throws std::filesystem::filesystem_error if persistence fails. template void write_file(ManifoldType const& t_universe, cdt::RandomSeed const seed) { @@ -1819,6 +1884,12 @@ namespace cdt::utilities } /// @brief Write a checkpoint with its effective seed and pass in its name. + /// @tparam ManifoldType Supported manifold type. + /// @param t_universe Manifold to serialize. + /// @param seed Effective root seed. + /// @param completed_passes Number of completed move passes. + /// @throws std::logic_error for a same-thread reentrant write. + /// @throws std::filesystem::filesystem_error if persistence fails. template void write_file(ManifoldType const& t_universe, cdt::RandomSeed const seed, Int_precision const completed_passes) @@ -1831,6 +1902,13 @@ namespace cdt::utilities } /// @brief Write a named stochastic artifact and its complete provenance. + /// @tparam ManifoldType Supported manifold type. + /// @param universe Manifold to serialize. + /// @param metadata Complete artifact and stochastic provenance. + /// @throws std::invalid_argument if checkpoint metadata omits completed + /// passes. + /// @throws std::logic_error for a same-thread reentrant write. + /// @throws std::filesystem::filesystem_error if persistence fails. template void write_file(ManifoldType const& universe, Reproducibility_metadata const& metadata) @@ -1853,6 +1931,8 @@ namespace cdt::utilities /// @tparam TriangulationType The type of triangulation /// @param filename The file to read from /// @returns A Delaunay triangulation + /// @throws std::filesystem::filesystem_error if the payload or sidecar is + /// missing, unreadable, malformed, or inconsistent. template [[nodiscard]] auto read_file(std::filesystem::path const& filename) -> TriangulationType @@ -1872,6 +1952,9 @@ namespace cdt::utilities /// @brief Roll a die using a caller-supplied /// `std::uniform_random_bit_generator` + /// @tparam Generator Uniform random bit generator type. + /// @param generator Generator whose state advances during sampling. + /// @return Uniform integer in the closed interval [1, 6]. template [[nodiscard]] inline auto die_roll(Generator& generator) { @@ -1909,6 +1992,12 @@ namespace cdt::utilities /// @brief Generate random integers by calling generate_random, preserves /// template argument deduction + /// @tparam Generator Uniform random bit generator type. + /// @tparam IntegerType Integral result type. + /// @param generator Generator whose state advances during sampling. + /// @param t_min_value Inclusive lower bound. + /// @param t_max_value Inclusive upper bound. + /// @return Uniformly sampled integer in the requested closed interval. template [[nodiscard]] auto generate_random_int(Generator& generator, @@ -1921,6 +2010,11 @@ namespace cdt::utilities } // generate_random_int() /// @brief Generate a random timeslice + /// @tparam Generator Uniform random bit generator type. + /// @tparam IntegerType Integral timeslice type. + /// @param generator Generator whose state advances during sampling. + /// @param t_max_timeslice Inclusive positive upper timeslice bound. + /// @return Uniformly sampled timeslice in [1, `t_max_timeslice`]. template [[nodiscard]] auto generate_random_timeslice(Generator& generator, @@ -1933,6 +2027,12 @@ namespace cdt::utilities /// @brief Generate random real numbers by calling generate_random, /// preserves template argument deduction + /// @tparam Generator Uniform random bit generator type. + /// @tparam FloatingPointType Floating-point result type. + /// @param generator Generator whose state advances during sampling. + /// @param t_min_value Inclusive lower bound. + /// @param t_max_value Exclusive upper bound. + /// @return Uniformly sampled real value in the requested interval. template [[nodiscard]] auto generate_random_real(Generator& generator, @@ -1945,6 +2045,9 @@ namespace cdt::utilities } // generate_random_real() /// @brief Generate a probability + /// @tparam Generator Uniform random bit generator type. + /// @param generator Generator whose state advances during sampling. + /// @return Uniform long-double sample in [0, 1). template [[nodiscard]] inline auto generate_probability(Generator& generator) { @@ -2141,6 +2244,7 @@ namespace cdt::utilities return population; } // expected_points_per_timeslice + /// @brief Validated simplex-population bounds for generated triangulations. struct Generated_population_bounds { /// Base population used to construct the spherical layers. diff --git a/pyproject.toml b/pyproject.toml index f9df8debd..c2d2e00bf 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -40,6 +40,7 @@ source-exclude = [ "scripts/release_check.py", "scripts/semgrep_fixture_config.py", "scripts/tests/**", + "scripts/validate_generated_site.py", "scripts/validate_viewer_artifacts.py", ] diff --git a/scripts/doxygen.sh b/scripts/doxygen.sh index 179d7063b..f0dee2a1b 100755 --- a/scripts/doxygen.sh +++ b/scripts/doxygen.sh @@ -3,15 +3,16 @@ set -euo pipefail usage() { - echo "Usage: $0 " >&2 + echo "Usage: $0 " >&2 exit 2 } -[[ $# -eq 3 ]] || usage +[[ $# -eq 4 ]] || usage mode="$1" doxygen_version="$2" graphviz_version="$3" +python_version="$4" [[ "$mode" == "check" || "$mode" == "build" ]] || usage repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" @@ -29,14 +30,22 @@ graphviz_matches() { [[ "$installed_version" == "$graphviz_version" ]] } -if ! doxygen_matches || ! graphviz_matches; then +python_matches() { + command -v python3 >/dev/null 2>&1 && + [[ "$(python3 -c 'import platform; print(platform.python_version())')" == "$python_version" ]] +} + +if ! doxygen_matches || ! graphviz_matches || ! python_matches; then if command -v pkgx >/dev/null 2>&1 && [[ -z "${CDT_DOXYGEN_TOOLCHAIN_ACTIVE:-}" ]]; then export CDT_DOXYGEN_TOOLCHAIN_ACTIVE=1 - exec pkgx "+doxygen.nl@$doxygen_version" "+graphviz.org@$graphviz_version" -- \ - "$0" "$mode" "$doxygen_version" "$graphviz_version" + exec pkgx \ + "+doxygen.nl@$doxygen_version" \ + "+graphviz.org@$graphviz_version" \ + "+python.org@$python_version" \ + -- "$0" "$mode" "$doxygen_version" "$graphviz_version" "$python_version" fi - echo "Doxygen $doxygen_version and Graphviz $graphviz_version are required." >&2 + echo "Doxygen $doxygen_version, Graphviz $graphviz_version, and Python $python_version are required." >&2 echo "Install those versions or install pkgx so the repository can provide them ephemerally." >&2 exit 1 fi @@ -48,13 +57,18 @@ cleanup() { trap cleanup EXIT config_output="$temporary_output" +warning_log="$temporary_output/doxygen-warnings.log" +config_warning_log="$warning_log" if command -v cygpath >/dev/null 2>&1; then config_output="$(cygpath -m "$temporary_output")" + config_warning_log="$(cygpath -m "$warning_log")" fi { cat docs/Doxyfile printf '\nOUTPUT_DIRECTORY = "%s"\n' "$config_output" + printf 'WARN_AS_ERROR = NO\n' + printf 'WARN_LOGFILE = "%s"\n' "$config_warning_log" } | doxygen - generated_html="$temporary_output/html" @@ -63,6 +77,10 @@ if [[ ! -f "$generated_html/index.html" ]]; then exit 1 fi +python3 scripts/validate_generated_site.py \ + --warning-log "$warning_log" \ + "$generated_html" + if [[ "$mode" == "build" ]]; then published_html="$repo_root/docs/html" rm -rf "$published_html" diff --git a/scripts/tests/test_validate_generated_site.py b/scripts/tests/test_validate_generated_site.py new file mode 100644 index 000000000..9cad72997 --- /dev/null +++ b/scripts/tests/test_validate_generated_site.py @@ -0,0 +1,191 @@ +"""Tests for the generated Doxygen site validator.""" + +import tempfile +import unittest +from pathlib import Path + +from scripts import validate_generated_site + + +class GeneratedSiteValidationTests(unittest.TestCase): + """Exercise archival pages, references, identifiers, and regression checks.""" + + def _valid_site(self) -> Path: + """Create the smallest complete generated-site contract.""" + root = Path(self.enterContext(tempfile.TemporaryDirectory())) + target_fragments = validate_generated_site.REQUIRED_TARGETS + for relative, fragments in target_fragments.items(): + anchors = "".join(f'

{fragment}

' for fragment in fragments) + body = anchors + if relative == "index.html": + body += """ + + + +fixture +""" + target = root / relative + target.parent.mkdir(parents=True, exist_ok=True) + target.write_text(f"{body}", encoding="utf-8") + + for relative in validate_generated_site.REQUIRED_ASSETS: + target = root / relative + target.parent.mkdir(parents=True, exist_ok=True) + if relative == "doxygen.css": + target.write_text("@media (prefers-color-scheme: dark) {}\n", encoding="utf-8") + elif target.suffix in {".css", ".js"}: + target.write_text("/* generated test asset */\n", encoding="utf-8") + else: + target.write_bytes(b"generated test asset") + (root / "graph.svg").write_text("\n\n", encoding="utf-8") + return root + + def test_complete_site_validates(self) -> None: + """The bounded archival surface passes without network access.""" + site = self._valid_site() + + page_count = validate_generated_site.validate(site) + + self.assertEqual(page_count, len(validate_generated_site.REQUIRED_TARGETS)) + + def test_missing_local_page_and_fragment_are_rejected(self) -> None: + """Every generated local page and fragment reference must resolve.""" + for reference, diagnostic in ( + ("missing.html", "missing local target"), + ("index.html#missing", "missing fragment"), + ): + with self.subTest(reference=reference): + site = self._valid_site() + (site / "index.html").write_text( + (site / "index.html").read_text(encoding="utf-8") + f'broken', + encoding="utf-8", + ) + + with self.assertRaisesRegex(validate_generated_site.GeneratedSiteError, diagnostic): + validate_generated_site.validate(site) + + def test_duplicate_identifier_is_rejected(self) -> None: + """A page cannot publish two targets under the same HTML id.""" + site = self._valid_site() + (site / "index.html").write_text( + (site / "index.html").read_text(encoding="utf-8") + '
', + encoding="utf-8", + ) + + with self.assertRaisesRegex(validate_generated_site.GeneratedSiteError, "duplicate id 'introduction'"): + validate_generated_site.validate(site) + + def test_doxygen_117_duplicate_link_label_is_rejected(self) -> None: + """Doxygen 1.17's immediately repeated linked prose must remain caught.""" + site = self._valid_site() + (site / "index.html").write_text( + (site / "index.html").read_text(encoding="utf-8") + '

IntroductionIntroduction

', + encoding="utf-8", + ) + + with self.assertRaisesRegex(validate_generated_site.GeneratedSiteError, "duplicated rendered link label 'Introduction'"): + validate_generated_site.validate(site) + + def test_literal_markdown_in_rendered_prose_is_rejected(self) -> None: + """A Markdown link emitted as prose is not accepted as rendered output.""" + site = self._valid_site() + (site / "index.html").write_text( + (site / "index.html").read_text(encoding="utf-8") + "

The [Justfile](Justfile) defines commands.

", + encoding="utf-8", + ) + + with self.assertRaisesRegex(validate_generated_site.GeneratedSiteError, "literal Markdown link"): + validate_generated_site.validate(site) + + def test_missing_stylesheet_asset_is_rejected(self) -> None: + """Local CSS resources are part of the self-contained site contract.""" + site = self._valid_site() + (site / "doxygen.css").write_text( + '@media (prefers-color-scheme: dark) {}\n.hero { background: url("missing.png"); }\n', + encoding="utf-8", + ) + + with self.assertRaisesRegex(validate_generated_site.GeneratedSiteError, "missing stylesheet asset 'missing.png'"): + validate_generated_site.validate(site) + + def test_unused_mermaid_client_is_rejected(self) -> None: + """The archive must not acquire Doxygen 1.17's unused CDN dependency.""" + site = self._valid_site() + (site / "menu.js").write_text( + "import mermaid from 'https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.esm.min.mjs';\n", + encoding="utf-8", + ) + + with self.assertRaisesRegex(validate_generated_site.GeneratedSiteError, "unused Mermaid client dependency"): + validate_generated_site.validate(site) + + def test_scoped_implementation_completeness_warnings_are_ignored(self) -> None: + """Only completeness noise from unsupported symbols and source artifacts is ignored.""" + root = Path(self.enterContext(tempfile.TemporaryDirectory())) + warning_log = root / "warnings.log" + warning_log.write_text( + "include/A.hpp:1: warning: Member helper (function) of namespace cdt::detail is not documented.\n" + ":1: warning: parameters of member cdt::module::detail::helper are not documented\n" + "include/Legacy.hpp:1: warning: Member old (function) of namespace cdt::experimental::old is not documented.\n" + "src/cdt.cpp:1: warning: Member main(int argc) (function) of file cdt.cpp is not documented.\n" + "src/cdt.cpp:1: warning: parameters of member main are not documented\n" + ":1: warning: parameters of member catch are not documented\n" + "
:1: warning: parameters of member main are not documented\n", + encoding="utf-8", + ) + + ignored = validate_generated_site.validate_warning_log(warning_log) + + self.assertEqual(ignored, 7) + + def test_public_completeness_warning_is_rejected(self) -> None: + """An undocumented supported symbol must fail documentation validation.""" + root = Path(self.enterContext(tempfile.TemporaryDirectory())) + warning_log = root / "warnings.log" + warning_log.write_text( + "include/Public.hpp:1: warning: Member run (function) of namespace cdt is not documented.\n", + encoding="utf-8", + ) + + with self.assertRaisesRegex(validate_generated_site.GeneratedSiteError, "Public.hpp.*run"): + validate_generated_site.validate_warning_log(warning_log) + + def test_public_parameter_warning_is_rejected(self) -> None: + """Missing caller-contract details on a supported function remain fatal.""" + root = Path(self.enterContext(tempfile.TemporaryDirectory())) + warning_log = root / "warnings.log" + warning_log.write_text( + "include/Public.hpp:1: warning: parameters of member cdt::run are not documented\n", + encoding="utf-8", + ) + + with self.assertRaisesRegex(validate_generated_site.GeneratedSiteError, "parameters of member cdt::run"): + validate_generated_site.validate_warning_log(warning_log) + + def test_public_main_parameter_warning_is_rejected(self) -> None: + """The source-entry exemption must not hide a public header declaration.""" + root = Path(self.enterContext(tempfile.TemporaryDirectory())) + warning_log = root / "warnings.log" + warning_log.write_text( + "include/Public.hpp:1: warning: parameters of member main are not documented\n", + encoding="utf-8", + ) + + with self.assertRaisesRegex(validate_generated_site.GeneratedSiteError, "Public.hpp.*member main"): + validate_generated_site.validate_warning_log(warning_log) + + def test_malformed_internal_documentation_warning_is_rejected(self) -> None: + """Internal scope never excuses broken Doxygen markup or references.""" + root = Path(self.enterContext(tempfile.TemporaryDirectory())) + warning_log = root / "warnings.log" + warning_log.write_text( + "include/Internal.hpp:1: warning: unable to resolve reference to cdt::detail::missing\n", + encoding="utf-8", + ) + + with self.assertRaisesRegex(validate_generated_site.GeneratedSiteError, "unable to resolve reference"): + validate_generated_site.validate_warning_log(warning_log) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/validate_generated_site.py b/scripts/validate_generated_site.py new file mode 100755 index 000000000..77f624f18 --- /dev/null +++ b/scripts/validate_generated_site.py @@ -0,0 +1,412 @@ +#!/usr/bin/env python3 +"""Validate the self-contained generated Doxygen HTML site.""" + +import argparse +import re +import sys +from collections import Counter +from dataclasses import dataclass +from html.parser import HTMLParser +from pathlib import Path +from typing import override +from urllib.parse import unquote, urlsplit + +REFERENCE_ATTRIBUTES = ("href", "src", "data", "poster") +SKIPPED_SCHEMES = frozenset({"data", "http", "https", "javascript", "mailto", "tel"}) +LITERAL_MARKDOWN_LINK = re.compile(r"\[[^\]\n]+\]\([^\)\n]+\)") +CSS_URL = re.compile(r"url\(\s*(?P['\"]?)(?P[^)'\"]+)(?P=quote)\s*\)") +WHITESPACE = re.compile(r"\s+") +COMPLETENESS_WARNING = re.compile(r"(?:\bis not documented[.]?$|\b(?:parameters|return type) of member .+ (?:are|is) not documented$)") +INTERNAL_SYMBOL = re.compile(r"(?:::|\b)detail(?:::|\s)|\bcdt::experimental::") +SOURCE_ARTIFACT = re.compile( + r"(?:Member (?:catch|main|Timer)\b.*\bis not documented[.]?$|" + r"parameters of member (?:catch|main)\b.*\bare not documented$)" +) +PSEUDO_SOURCE_ARTIFACT = re.compile(r"^<(?:catch|main)>:\d+: warning: ") + +REQUIRED_ASSETS = ( + "S3-7-27528-I1-R1.png", + "clipboard.js", + "cookie.js", + "doxygen.css", + "dynsections.js", + "menu.js", + "menudata.js", + "search/search.css", + "search/search.js", + "search/searchdata.js", + "tabs.css", +) +REQUIRED_TARGETS = { + "index.html": ("developer-workflow", "documentation", "introduction"), + "md__r_e_f_e_r_e_n_c_e_s.html": ("metropolis-hastings-algorithm",), + "md_docs_2api-boundary.html": ("generated-reference-policy", "header-classification"), + "md_docs_2comparison-harness.html": (), + "md_docs_2cpp-api-quickstart.html": ( + "workflow", + "build-and-run", + "failure-and-ownership-behavior", + ), + "md_docs_2ergodic-moves.html": (), + "md_docs_2metropolis-hastings.html": (), + "md_docs_2reproducibility.html": (), + "md_docs_2viewer.html": (), +} + + +class GeneratedSiteError(ValueError): + """The generated site violates its archival publication contract.""" + + +@dataclass(frozen=True) +class Reference: + """One URL-bearing HTML or CSS attribute.""" + + source: Path + line: int + value: str + + +def _normalized_text(value: str) -> str: + """Collapse rendered whitespace for stable duplicate-label comparisons.""" + return WHITESPACE.sub(" ", value).strip() + + +class _DocumentParser(HTMLParser): + """Collect link targets, resource references, and rendered prose evidence.""" + + def __init__(self, source: Path) -> None: + super().__init__(convert_charrefs=True) + self.source = source + self.ids: list[tuple[int, str]] = [] + self.targets: set[str] = set() + self.references: list[Reference] = [] + self.prose: list[tuple[int, str]] = [] + self.duplicate_link_labels: list[tuple[int, str]] = [] + self._element_stack: list[tuple[str, bool]] = [] + self._suppressed_depth = 0 + self._anchor_chunks: list[str] | None = None + self._anchor_is_doxygen_link = False + self._pending_anchor: tuple[int, str] | None = None + + def _add_reference(self, value: str) -> None: + self.references.append(Reference(self.source, self.getpos()[0], value)) + + def _collect_identifiers(self, attributes: dict[str, str | None]) -> None: + """Collect fragment targets without treating matching id/name as duplicates.""" + identifier = attributes.get("id") + if identifier: + self.ids.append((self.getpos()[0], identifier)) + self.targets.add(identifier) + name = attributes.get("name") + if name: + self.targets.add(name) + + def _collect_references(self, attributes: dict[str, str | None]) -> None: + """Collect ordinary and responsive resource references.""" + for attribute in REFERENCE_ATTRIBUTES: + value = attributes.get(attribute) + if value: + self._add_reference(value) + srcset = attributes.get("srcset") + if srcset: + for candidate in srcset.split(","): + value = candidate.strip().split(maxsplit=1)[0] + if value: + self._add_reference(value) + + def _push_element(self, tag: str, classes: frozenset[str]) -> None: + """Track elements whose contents are code rather than rendered prose.""" + suppressed_here = tag in {"code", "pre", "script", "style"} or bool(classes & {"fragment", "line"}) + self._element_stack.append((tag, suppressed_here)) + if suppressed_here: + self._suppressed_depth += 1 + + @override + def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None: + """Collect identifiers and URL-bearing attributes from one element.""" + if self._pending_anchor is not None: + self._pending_anchor = None + + attributes = dict(attrs) + self._collect_identifiers(attributes) + self._collect_references(attributes) + classes = frozenset((attributes.get("class") or "").split()) + self._push_element(tag, classes) + + if tag == "a": + self._anchor_chunks = [] + self._anchor_is_doxygen_link = "el" in classes + + @override + def handle_startendtag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None: + """Process one self-closing element without retaining stack state.""" + self.handle_starttag(tag, attrs) + self.handle_endtag(tag) + + @override + def handle_endtag(self, tag: str) -> None: + """Close parser state and retain one Doxygen link label for regression checks.""" + if tag == "a" and self._anchor_chunks is not None: + label = _normalized_text("".join(self._anchor_chunks)) + if label and self._anchor_is_doxygen_link: + self._pending_anchor = (self.getpos()[0], label) + self._anchor_chunks = None + self._anchor_is_doxygen_link = False + + for index in range(len(self._element_stack) - 1, -1, -1): + element, _ = self._element_stack[index] + if element != tag: + continue + removed = self._element_stack[index:] + del self._element_stack[index:] + self._suppressed_depth -= sum(suppressed for _, suppressed in removed) + break + + @override + def handle_data(self, data: str) -> None: + """Collect anchor text and prose while detecting Doxygen 1.17 label duplication.""" + if self._anchor_chunks is not None: + self._anchor_chunks.append(data) + elif self._pending_anchor is not None: + line, label = self._pending_anchor + rendered = _normalized_text(data) + if rendered: + if rendered.startswith(label): + self.duplicate_link_labels.append((line, label)) + self._pending_anchor = None + + if self._suppressed_depth == 0 and data: + self.prose.append((self.getpos()[0], data)) + + +def _parse_document(path: Path) -> _DocumentParser: + """Parse one generated HTML document with path-specific diagnostics.""" + parser = _DocumentParser(path) + try: + parser.feed(path.read_text(encoding="utf-8")) + parser.close() + except (OSError, UnicodeError) as error: + message = f"{path}: cannot parse generated HTML: {error}" + raise GeneratedSiteError(message) from error + return parser + + +def _relative(path: Path, root: Path) -> str: + """Return a stable site-relative path for diagnostics.""" + return path.relative_to(root).as_posix() + + +def _warning_message(line: str) -> str: + """Return the diagnostic text following Doxygen's warning prefix.""" + _, separator, message = line.partition("warning: ") + return message if separator else line + + +def _is_ignored_completeness_warning(line: str) -> bool: + """Whether *line* documents an intentionally unsupported implementation symbol.""" + message = _warning_message(line) + if COMPLETENESS_WARNING.search(message) is None: + return False + if INTERNAL_SYMBOL.search(message) is not None: + return True + normalized = line.replace("\\", "/") + source_path = f"/{normalized.lstrip('/')}" + originates_in_source = "/src/" in source_path or PSEUDO_SOURCE_ARTIFACT.search(line) is not None + return originates_in_source and SOURCE_ARTIFACT.search(message) is not None + + +def validate_warning_log(path: Path) -> int: + """Reject every Doxygen warning except scoped implementation-completeness noise.""" + try: + lines = path.read_text(encoding="utf-8").splitlines() + except (OSError, UnicodeError) as error: + message = f"cannot read Doxygen warning log {path}: {error}" + raise GeneratedSiteError(message) from error + + warnings = [line for line in lines if line.strip()] + ignored_count = 0 + actionable = [] + for line in warnings: + if _is_ignored_completeness_warning(line): + ignored_count += 1 + else: + actionable.append(line) + if actionable: + message = "Doxygen public documentation validation failed:\n" + "\n".join(f"- {line}" for line in actionable) + raise GeneratedSiteError(message) + return ignored_count + + +def _resolve_local_target(reference: Reference, root: Path) -> tuple[Path, str] | None: + """Resolve one local reference, returning its target path and fragment.""" + parsed = urlsplit(reference.value) + if parsed.scheme.lower() in SKIPPED_SCHEMES or reference.value.startswith("//"): + return None + if parsed.scheme: + return None + + path_text = unquote(parsed.path) + if path_text.startswith("/"): + target = root / path_text.lstrip("/") + elif path_text: + target = reference.source.parent / path_text + else: + target = reference.source + return target.resolve(), unquote(parsed.fragment) + + +def _validate_required_pages(root: Path, documents: dict[Path, _DocumentParser]) -> list[str]: + """Validate the archival pages and stable GitHub-style fragments.""" + errors: list[str] = [] + for relative, fragments in REQUIRED_TARGETS.items(): + target = (root / relative).resolve() + document = documents.get(target) + if document is None: + errors.append(f"missing required page: {relative}") + continue + errors.extend(f"missing required fragment: {relative}#{fragment}" for fragment in fragments if fragment not in document.targets) + return errors + + +def _validate_required_features(root: Path, documents: dict[Path, _DocumentParser]) -> list[str]: + """Validate the generated assets and presentation features retained for v1.""" + errors = [f"missing required asset: {relative}" for relative in REQUIRED_ASSETS if not (root / relative).is_file()] + + index_path = (root / "index.html").resolve() + if index_path in documents: + index_text = index_path.read_text(encoding="utf-8") + for marker, feature in ( + ('name="viewport"', "responsive viewport"), + ("codefold.init", "code folding"), + ('src="clipboard.js"', "copy controls"), + ): + if marker not in index_text: + errors.append(f"index.html is missing required {feature} markup") + + stylesheet = root / "doxygen.css" + if stylesheet.is_file() and "prefers-color-scheme: dark" not in stylesheet.read_text(encoding="utf-8"): + errors.append("doxygen.css is missing automatic dark-mode styling") + + graphviz_outputs = sorted(root.rglob("*.svg")) + if not any("Generated by graphviz" in item.read_text(encoding="utf-8", errors="ignore") for item in graphviz_outputs): + errors.append("no generated Graphviz SVG was found") + return errors + + +def _document_content_errors(source_name: str, document: _DocumentParser) -> list[str]: + """Return duplicate-identifier, duplicate-label, and literal-Markdown errors.""" + errors: list[str] = [] + counts = Counter(identifier for _, identifier in document.ids) + errors.extend(f"{source_name}: duplicate id {identifier!r} ({count} occurrences)" for identifier, count in sorted(counts.items()) if count > 1) + errors.extend(f"{source_name}:{line}: duplicated rendered link label {label!r}" for line, label in document.duplicate_link_labels) + for line, prose in document.prose: + match = LITERAL_MARKDOWN_LINK.search(prose) + if match is not None: + errors.append(f"{source_name}:{line}: literal Markdown link {match.group(0)!r}") + return errors + + +def _reference_error( + reference: Reference, + source_name: str, + root: Path, + documents: dict[Path, _DocumentParser], +) -> str | None: + """Return one local-reference diagnostic, or None when it resolves.""" + resolved = _resolve_local_target(reference, root) + if resolved is None: + return None + target, fragment = resolved + try: + target.relative_to(root) + except ValueError: + return f"{source_name}:{reference.line}: local reference escapes the site: {reference.value!r}" + if target.is_dir(): + target = target / "index.html" + if not target.is_file(): + return f"{source_name}:{reference.line}: missing local target {reference.value!r}" + if not fragment or target.suffix.lower() not in {".htm", ".html"}: + return None + target_document = documents.get(target.resolve()) + if target_document is None or fragment not in target_document.targets: + return f"{source_name}:{reference.line}: missing fragment {reference.value!r}" + return None + + +def _validate_documents(root: Path, documents: dict[Path, _DocumentParser]) -> list[str]: + """Validate identifiers, prose, and local HTML/resource references.""" + errors: list[str] = [] + for source, document in sorted(documents.items()): + source_name = _relative(source, root) + errors.extend(_document_content_errors(source_name, document)) + errors.extend(error for reference in document.references if (error := _reference_error(reference, source_name, root, documents)) is not None) + return errors + + +def _validate_css(root: Path) -> list[str]: + """Validate local assets referenced from generated stylesheets.""" + errors: list[str] = [] + for stylesheet in sorted(root.rglob("*.css")): + for line_number, line in enumerate(stylesheet.read_text(encoding="utf-8").splitlines(), start=1): + for match in CSS_URL.finditer(line): + value = match.group("url").strip() + reference = Reference(stylesheet.resolve(), line_number, value) + resolved = _resolve_local_target(reference, root) + if resolved is None: + continue + target, _ = resolved + try: + target.relative_to(root) + except ValueError: + errors.append(f"{_relative(stylesheet.resolve(), root)}:{line_number}: stylesheet reference escapes the site: {value!r}") + continue + if not target.is_file(): + errors.append(f"{_relative(stylesheet.resolve(), root)}:{line_number}: missing stylesheet asset {value!r}") + return errors + + +def validate(site: Path) -> int: + """Validate *site* and return its generated HTML page count.""" + root = site.resolve() + if not root.is_dir(): + message = f"generated site directory does not exist: {root}" + raise GeneratedSiteError(message) + + documents = {item.resolve(): _parse_document(item.resolve()) for item in sorted(root.rglob("*.html"))} + errors = _validate_required_pages(root, documents) + errors.extend(_validate_required_features(root, documents)) + errors.extend(_validate_documents(root, documents)) + errors.extend(_validate_css(root)) + + for item in sorted(root.rglob("*")): + if not item.is_file() or item.suffix.lower() not in {".css", ".html", ".js"}: + continue + text = item.read_text(encoding="utf-8") + if "mermaid.esm" in text or "cdn.jsdelivr.net/npm/mermaid" in text: + errors.append(f"{_relative(item.resolve(), root)}: unused Mermaid client dependency") + + if errors: + message = "generated site validation failed:\n" + "\n".join(f"- {error}" for error in sorted(set(errors))) + raise GeneratedSiteError(message) + return len(documents) + + +def main(argv: list[str] | None = None) -> int: + """Run the generated-site validator CLI.""" + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--warning-log", type=Path, help="Doxygen warning log to classify before site validation") + parser.add_argument("site", nargs="?", type=Path, default=Path("docs/html"), help="generated HTML root") + arguments = parser.parse_args(argv) + try: + ignored_warnings = validate_warning_log(arguments.warning_log) if arguments.warning_log else 0 + page_count = validate(arguments.site) + except (GeneratedSiteError, OSError, UnicodeError) as error: + print(error, file=sys.stderr) + return 1 + print(f"Generated site validation complete ({page_count} HTML pages, {ignored_warnings} scoped implementation warnings).") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tests/Metropolis_test.cpp b/tests/Metropolis_test.cpp index d72122c28..07fa94935 100644 --- a/tests/Metropolis_test.cpp +++ b/tests/Metropolis_test.cpp @@ -632,11 +632,15 @@ SCENARIO("Metropolis transitions are sequential and failure-aware" * WHEN("Two always-accepted candidates are executed sequentially.") { - REQUIRE(strategy.attempt_transition( - manifold, move_tracker::MoveType::TWO_SIX, 0.0L)); + REQUIRE(strategy + .attempt_transition(manifold, move_tracker::MoveType::TWO_SIX, + 0.0L) + .accepted()); auto const after_first = manifold.geometry(); - REQUIRE(strategy.attempt_transition( - manifold, move_tracker::MoveType::TWO_SIX, 0.0L)); + REQUIRE(strategy + .attempt_transition(manifold, move_tracker::MoveType::TWO_SIX, + 0.0L) + .accepted()); THEN("The second candidate starts from the first committed state.") { @@ -663,11 +667,12 @@ SCENARIO("Metropolis transitions are sequential and failure-aware" * WHEN("The impossible proposal is attempted.") { - auto const accepted = strategy.attempt_transition( + auto const transition = strategy.attempt_transition( manifold, move_tracker::MoveType::SIX_TWO, 0.0L); THEN("It is an explicit rejected self-transition.") { - CHECK_FALSE(accepted); + CHECK_FALSE(transition.accepted()); + CHECK_FALSE(transition.successful()); CHECK_EQ(manifold.delaunay_snapshot(), before); CHECK_EQ(strategy.proposed().total(), 1); CHECK_EQ(strategy.accepted().total(), 0); @@ -678,6 +683,95 @@ SCENARIO("Metropolis transitions are sequential and failure-aware" * } } } + + GIVEN("A strategy initialized from a valid manifold.") + { + auto manifold = minimal_26_manifold(); + auto const before = manifold.delaunay_snapshot(); + Metropolis_3 strategy(Alpha, 0.0L, 0.0L, 1, 1, false, cdt::RandomSeed{31}); + strategy.initialize(manifold); + auto const geometry_before = strategy.geometry(); + auto const trace_before = strategy.transition_trace(); + + WHEN("A caller supplies an invalid acceptance trial.") + { + constexpr std::array invalid_trials{ + -std::numeric_limits::epsilon(), + 1.0L + std::numeric_limits::epsilon(), + std::numeric_limits::infinity(), + std::numeric_limits::quiet_NaN()}; + + for (auto const invalid_trial : invalid_trials) + { + CAPTURE(invalid_trial); + CHECK_THROWS_AS( + static_cast(strategy.attempt_transition( + manifold, move_tracker::MoveType::TWO_SIX, invalid_trial)), + std::invalid_argument); + } + + THEN("The canonical state and all run statistics remain unchanged.") + { + CHECK_EQ(manifold.delaunay_snapshot(), before); + CHECK_EQ(strategy.geometry().N3, geometry_before.N3); + CHECK_EQ(strategy.geometry().N3_31, geometry_before.N3_31); + CHECK_EQ(strategy.geometry().N3_13, geometry_before.N3_13); + CHECK_EQ(strategy.geometry().N3_31_13, geometry_before.N3_31_13); + CHECK_EQ(strategy.geometry().N3_22, geometry_before.N3_22); + CHECK_EQ(strategy.geometry().N2, geometry_before.N2); + CHECK_EQ(strategy.geometry().N1, geometry_before.N1); + CHECK_EQ(strategy.geometry().N1_TL, geometry_before.N1_TL); + CHECK_EQ(strategy.geometry().N1_SL, geometry_before.N1_SL); + CHECK_EQ(strategy.geometry().N0, geometry_before.N0); + CHECK_EQ(strategy.proposed().total(), 0); + CHECK_EQ(strategy.accepted().total(), 0); + CHECK_EQ(strategy.rejected().total(), 0); + CHECK_EQ(strategy.attempted().total(), 0); + CHECK_EQ(strategy.succeeded().total(), 0); + CHECK_EQ(strategy.failed().total(), 0); + CHECK_EQ(strategy.transition_count(), 0); + CHECK_EQ(strategy.transition_trace(), trace_before); + } + } + } + + GIVEN("Equivalent manifolds and strategies using the same random stream.") + { + auto first_state = minimal_26_manifold(); + auto replay_state = first_state; + Metropolis_3 first(Alpha, 0.0L, 0.0L, 1, 1, false, cdt::RandomSeed{37}); + Metropolis_3 replay(Alpha, 0.0L, 0.0L, 1, 1, false, cdt::RandomSeed{37}); + + WHEN("Random one-step transitions are replayed.") + { + for (auto attempt = 0; attempt < 10; ++attempt) + { + auto const succeeded_before = first.succeeded().total(); + auto const accepted_before = first.accepted().total(); + auto const transition = first.attempt_transition(first_state); + auto const replayed = replay.attempt_transition(replay_state); + + CAPTURE(attempt); + CHECK_EQ(transition.move(), replayed.move()); + CHECK_EQ(transition.outcome(), replayed.outcome()); + CHECK_EQ(first.proposed().total(), attempt + 1); + CHECK_EQ(first.attempted().total(), attempt + 1); + CHECK_EQ(first.succeeded().total(), + succeeded_before + (transition.successful() ? 1 : 0)); + CHECK_EQ(first.accepted().total(), + accepted_before + (transition.accepted() ? 1 : 0)); + if (transition.accepted()) { CHECK(transition.successful()); } + CHECK_EQ(first_state.delaunay_snapshot(), + replay_state.delaunay_snapshot()); + } + + THEN("The complete transition trace is reproducible.") + { + CHECK_EQ(first.transition_trace(), replay.transition_trace()); + CHECK_EQ(first.transition_count(), replay.transition_count()); + } + } + } } SCENARIO("Using the Metropolis algorithm" * doctest::test_suite("metropolis")) @@ -854,6 +948,7 @@ SCENARIO("Metropolis provenance is derived from the actual run" * .k = 2.0L, .lambda = 3.0L, .configured_passes = 100, + .configured_attempts = 10, .checkpoint_interval = 50}; constexpr auto seed = cdt::RandomSeed{92}; constexpr auto transition_stream = cdt::RandomStream{17}; @@ -875,11 +970,13 @@ SCENARIO("Metropolis provenance is derived from the actual run" * REQUIRE(metadata.k); REQUIRE(metadata.lambda); REQUIRE(metadata.configured_passes); + REQUIRE(metadata.configured_attempts); REQUIRE(metadata.checkpoint_interval); CHECK_EQ(*metadata.alpha, 0.6L); CHECK_EQ(*metadata.k, 1.1L); CHECK_EQ(*metadata.lambda, 0.1L); CHECK_EQ(*metadata.configured_passes, 2); + CHECK_EQ(*metadata.configured_attempts, 10); CHECK_EQ(*metadata.checkpoint_interval, 1); } } diff --git a/tests/Move_outcome_test.cpp b/tests/Move_outcome_test.cpp index b42c73cf6..250f6b69d 100644 --- a/tests/Move_outcome_test.cpp +++ b/tests/Move_outcome_test.cpp @@ -22,6 +22,7 @@ namespace { + using cdt::ergodic_moves::MetropolisTransition; using cdt::ergodic_moves::MoveError; using cdt::ergodic_moves::MoveFailure; using cdt::ergodic_moves::MoveOutcome; @@ -102,6 +103,16 @@ static_assert(static_cast(MoveOutcome::METROPOLIS_ACCEPTED) == 1); static_assert(static_cast(MoveOutcome::METROPOLIS_REJECTED) == 2); static_assert(static_cast(MoveOutcome::EXECUTION_FAILED) == 3); static_assert(static_cast(MoveOutcome::SUCCEEDED) == 4); +static_assert(std::is_trivially_copyable_v); +static_assert(MetropolisTransition{MoveType::TWO_THREE, + MoveOutcome::METROPOLIS_ACCEPTED} + .accepted()); +static_assert(MetropolisTransition{MoveType::TWO_THREE, + MoveOutcome::METROPOLIS_REJECTED} + .successful()); +static_assert(!MetropolisTransition{MoveType::TWO_THREE, + MoveOutcome::INAPPLICABLE} + .successful()); TEST_CASE("Move failures have stable diagnostics and accounting outcomes" * doctest::test_suite("move_outcome")) @@ -123,6 +134,26 @@ TEST_CASE("Move failures have stable diagnostics and accounting outcomes" * } } +TEST_CASE("Metropolis transition reports distinguish success from acceptance" * + doctest::test_suite("move_outcome")) +{ + auto const accepted = + MetropolisTransition{MoveType::TWO_SIX, MoveOutcome::METROPOLIS_ACCEPTED}; + auto const rejected = MetropolisTransition{MoveType::THREE_TWO, + MoveOutcome::METROPOLIS_REJECTED}; + auto const failed = + MetropolisTransition{MoveType::FOUR_FOUR, MoveOutcome::EXECUTION_FAILED}; + + CHECK_EQ(accepted.move(), MoveType::TWO_SIX); + CHECK_EQ(accepted.outcome(), MoveOutcome::METROPOLIS_ACCEPTED); + CHECK(accepted.successful()); + CHECK(accepted.accepted()); + CHECK(rejected.successful()); + CHECK_FALSE(rejected.accepted()); + CHECK_FALSE(failed.successful()); + CHECK_FALSE(failed.accepted()); +} + SCENARIO("Move error equality includes failure and move identity" * doctest::test_suite("move_outcome")) { diff --git a/tests/Move_tracker_test.cpp b/tests/Move_tracker_test.cpp index bad9f99e4..4032f4c7a 100644 --- a/tests/Move_tracker_test.cpp +++ b/tests/Move_tracker_test.cpp @@ -11,6 +11,7 @@ #include "Move_tracker.hpp" #include +#include #include #include @@ -115,6 +116,17 @@ SCENARIO("Integer to move type conversion" * } } +SCENARIO("Move types have stable tuple formatting" * + doctest::test_suite("move_tracker")) +{ + CHECK_EQ(fmt::format("{}", MoveType::TWO_THREE), "(2,3)"); + CHECK_EQ(fmt::format("{}", MoveType::THREE_TWO), "(3,2)"); + CHECK_EQ(fmt::format("{}", MoveType::TWO_SIX), "(2,6)"); + CHECK_EQ(fmt::format("{}", MoveType::SIX_TWO), "(6,2)"); + CHECK_EQ(fmt::format("{}", MoveType::FOUR_FOUR), "(4,4)"); + CHECK_EQ(format_as(static_cast(-1)), "unknown"); +} + SCENARIO("MoveTracker functionality" * doctest::test_suite("move_tracker")) { spdlog::debug("MoveTracker functionality.\n"); diff --git a/tests/Public_api_consumer.cpp b/tests/Public_api_consumer.cpp index 7a264a0bc..86cb7bc78 100644 --- a/tests/Public_api_consumer.cpp +++ b/tests/Public_api_consumer.cpp @@ -3,6 +3,7 @@ #include #include #include +#include #include #include @@ -93,6 +94,19 @@ static_assert(requires { { cdt::Metropolis_3::reverse_move(cdt::move_tracker::MoveType::TWO_THREE) } -> std::same_as>; + { + cdt::move_tracker::format_as(cdt::move_tracker::MoveType::TWO_THREE) + } -> std::same_as; +}); + +static_assert(requires(cdt::Metropolis_3& strategy, Manifold& manifold) { + { + strategy.attempt_transition(manifold) + } -> std::same_as; + { + strategy.attempt_transition(manifold, + cdt::move_tracker::MoveType::TWO_THREE, 0.5L) + } -> std::same_as; }); static_assert(requires(Manifold const& manifold, cdt::Random& random) { diff --git a/tests/Utilities_test.cpp b/tests/Utilities_test.cpp index 5863a033a..34d3ddda0 100644 --- a/tests/Utilities_test.cpp +++ b/tests/Utilities_test.cpp @@ -570,6 +570,7 @@ SCENARIO("Reading and writing Delaunay triangulations to files" * metadata.k = 1.1L; metadata.lambda = 0.1L; metadata.configured_passes = 10; + metadata.configured_attempts = 17; metadata.checkpoint_interval = 2; metadata.completed_passes = 4; metadata.max_threads = 4; @@ -603,6 +604,7 @@ SCENARIO("Reading and writing Delaunay triangulations to files" * CHECK_NE(contents.find("desired.simplices=64"), std::string::npos); CHECK_NE(contents.find("alpha=0.6"), std::string::npos); CHECK_NE(contents.find("completed_passes=4"), std::string::npos); + CHECK_NE(contents.find("configured_attempts=17"), std::string::npos); CHECK_NE(contents.find("parallel.max_threads=4"), std::string::npos); CHECK_NE(contents.find("transition_trace.fnv1a64=0000000000001234"), std::string::npos); @@ -861,6 +863,24 @@ SCENARIO("File serialization reports complete failures" * } } + WHEN("An explicit transition plan has no attempts.") + { + auto const filename = directory.file("invalid-configured-attempts.off"); + auto metadata = make_reproducibility_metadata( + manifold, cdt::RandomSeed{92}, ArtifactKind::CHECKPOINT); + metadata.completed_passes = 2; + metadata.configured_attempts = 1; + write_file(filename, triangulation, metadata); + replace_metadata_field(metadata_filename(filename), "configured_attempts", + "0"); + + THEN("The impossible execution plan is rejected.") + { + CHECK_THROWS_AS(static_cast(read_file>(filename)), + std::filesystem::filesystem_error); + } + } + WHEN("Caller-supplied payload-derived provenance is stale.") { auto const filename = directory.file("reconciled-provenance.off"); From e955ee643caa5e081314dfc6c5a5168bc1f17319 Mon Sep 17 00:00:00 2001 From: Adam Getchell Date: Sat, 8 Aug 2026 09:37:44 -0700 Subject: [PATCH 2/4] fix(api): harden transition and documentation validation - Reject unknown move kinds before counter access and recognize completed transitions as successful. - Prevent stale quickstart artifacts and strengthen generated-site contract enforcement. - Pin scientific fixtures and metadata to the reviewed immutable revision. --- REFERENCES.md | 2 +- cmake/RunCppApiQuickstartTest.cmake | 2 + docs/arithmetic-backend-evaluation.md | 2 +- docs/comparison-harness.md | 2 +- docs/metropolis-hastings.md | 2 +- include/Ergodic_moves_3.hpp | 2 +- include/Metropolis.hpp | 10 ++++ include/Move_outcome.hpp | 3 +- scripts/tests/test_validate_generated_site.py | 47 ++++++++++++++++++- scripts/validate_generated_site.py | 42 ++++++++++++----- tests/Metropolis_test.cpp | 31 ++++++++++++ tests/Move_outcome_test.cpp | 2 + 12 files changed, 126 insertions(+), 21 deletions(-) diff --git a/REFERENCES.md b/REFERENCES.md index 0bcec92e3..c5cadb236 100644 --- a/REFERENCES.md +++ b/REFERENCES.md @@ -3,7 +3,7 @@ ## How to Cite This Software If CDT++ contributes to research or a project, cite it using the structured -metadata in [`CITATION.cff`](https://github.com/acgetchell/CDT-plusplus/blob/main/CITATION.cff). GitHub and other citation tools can +metadata in [`CITATION.cff`](https://github.com/acgetchell/CDT-plusplus/blob/16d1c769afc67e06f07639f6fd9de8136974e282/CITATION.cff). GitHub and other citation tools can generate BibTeX, APA, and additional formats from that file. Quick citation for the current declared release: diff --git a/cmake/RunCppApiQuickstartTest.cmake b/cmake/RunCppApiQuickstartTest.cmake index 926e1664f..185e9a576 100644 --- a/cmake/RunCppApiQuickstartTest.cmake +++ b/cmake/RunCppApiQuickstartTest.cmake @@ -6,6 +6,8 @@ if(NOT DEFINED TEST_OUTPUT OR TEST_OUTPUT STREQUAL "") message(FATAL_ERROR "TEST_OUTPUT must name the quickstart payload") endif() +file(REMOVE "${TEST_OUTPUT}" "${TEST_OUTPUT}.meta") + execute_process( COMMAND "${TEST_EXECUTABLE}" "${TEST_OUTPUT}" RESULT_VARIABLE run_result diff --git a/docs/arithmetic-backend-evaluation.md b/docs/arithmetic-backend-evaluation.md index 7e71dfc40..1cc675e65 100644 --- a/docs/arithmetic-backend-evaluation.md +++ b/docs/arithmetic-backend-evaluation.md @@ -105,7 +105,7 @@ The default preserves current behavior; a Boost-only consumer uses: When the feature is absent, a vcpkg CMake wrapper sets `CGAL_DISABLE_GMP=ON` and `CGAL_CMAKE_EXACT_NT_BACKEND=BOOST_BACKEND`. The candidate port and standalone consumer live under -[`tests/cgal_no_gmp_probe`](https://github.com/acgetchell/CDT-plusplus/tree/main/tests/cgal_no_gmp_probe). They are a one-time +[`tests/cgal_no_gmp_probe`](https://github.com/acgetchell/CDT-plusplus/tree/16d1c769afc67e06f07639f6fd9de8136974e282/tests/cgal_no_gmp_probe). They are a one-time evaluation fixture, not a production overlay or root-CI dependency contract; shipping a downstream fork would recreate the maintenance burden this work is meant to remove. diff --git a/docs/comparison-harness.md b/docs/comparison-harness.md index 17f38feed..ea2210224 100644 --- a/docs/comparison-harness.md +++ b/docs/comparison-harness.md @@ -10,7 +10,7 @@ legality, or acceptance decisions. Each producer writes exactly one UTF-8 JSON object to standard output and may write diagnostics to standard error. The committed CDT++ `cdt-reference-raw-v1` document is validated directly against -[`result-v1.schema.json`](https://github.com/acgetchell/CDT-plusplus/blob/main/reference/schema/result-v1.schema.json). +[`result-v1.schema.json`](https://github.com/acgetchell/CDT-plusplus/blob/16d1c769afc67e06f07639f6fd9de8136974e282/reference/schema/result-v1.schema.json). Every bundle copies that canonical result, and the harness checks the live CDT++ payload against it before using the live C++ payload as the reference for the Rust comparison. When live C++ output includes transition observations, diff --git a/docs/metropolis-hastings.md b/docs/metropolis-hastings.md index 9029ef568..ff27e4342 100644 --- a/docs/metropolis-hastings.md +++ b/docs/metropolis-hastings.md @@ -130,7 +130,7 @@ a delta whose positive MPFR probability lies below `long double` range. Combinatorial fields and deterministic decisions are exact. The published cross-language protocol in -[`reference/fixtures/v1/protocol.json`](https://github.com/acgetchell/CDT-plusplus/blob/main/reference/fixtures/v1/protocol.json) +[`reference/fixtures/v1/protocol.json`](https://github.com/acgetchell/CDT-plusplus/blob/16d1c769afc67e06f07639f6fd9de8136974e282/reference/fixtures/v1/protocol.json) names separate absolute and relative tolerances for coordinates, closed-form actions, and probabilities. Randomized post-repair simplex counts are implementation-specific rather than covered by a generic percentage. diff --git a/include/Ergodic_moves_3.hpp b/include/Ergodic_moves_3.hpp index 1b9732a12..02c99bbef 100644 --- a/include/Ergodic_moves_3.hpp +++ b/include/Ergodic_moves_3.hpp @@ -1404,7 +1404,7 @@ namespace cdt::ergodic_moves /// @tparam Generator Uniform random bit generator type. /// @param t_manifold Source manifold, which remains unchanged. /// @param generator Caller-owned generator advanced by site sampling and - /// replacement-point construction. + /// ordering incident-edge flip paths. /// @return Proposed manifold, or a structured reason the site was rejected. template [[nodiscard]] inline auto propose_62_move(Manifold const& t_manifold, diff --git a/include/Metropolis.hpp b/include/Metropolis.hpp index a6f40021b..3af62c3d9 100644 --- a/include/Metropolis.hpp +++ b/include/Metropolis.hpp @@ -487,6 +487,14 @@ namespace cdt throw std::invalid_argument("MH trial value must lie in [0, 1]."); } + if (!reverse_move(move)) + { + return ergodic_moves::outcome_from( + ergodic_moves::MoveError{ + .category = ergodic_moves::MoveFailure::UNKNOWN_MOVE, + .requested_move = move}); + } + statistics.geometry = current.geometry(); ++statistics.proposed[move]; ++command_results.attempted[move]; @@ -622,6 +630,8 @@ namespace cdt public: /// @brief Resolve one caller-selected Markov transition. + /// @details An unsupported move value returns an execution-failed report + /// without mutating @p current or the run statistics. /// @param current Canonical state, updated only after a successful MH /// accept /// @param move Uniformly selected move type diff --git a/include/Move_outcome.hpp b/include/Move_outcome.hpp index 0defdeccd..49c73f8f0 100644 --- a/include/Move_outcome.hpp +++ b/include/Move_outcome.hpp @@ -118,7 +118,8 @@ namespace cdt::ergodic_moves [[nodiscard]] constexpr auto successful() const noexcept -> bool { return m_outcome == MoveOutcome::METROPOLIS_ACCEPTED || - m_outcome == MoveOutcome::METROPOLIS_REJECTED; + m_outcome == MoveOutcome::METROPOLIS_REJECTED || + m_outcome == MoveOutcome::SUCCEEDED; } /// @returns Whether Metropolis-Hastings accepted and committed the move. diff --git a/scripts/tests/test_validate_generated_site.py b/scripts/tests/test_validate_generated_site.py index 9cad72997..5c5072566 100644 --- a/scripts/tests/test_validate_generated_site.py +++ b/scripts/tests/test_validate_generated_site.py @@ -48,6 +48,49 @@ def test_complete_site_validates(self) -> None: self.assertEqual(page_count, len(validate_generated_site.REQUIRED_TARGETS)) + def test_missing_required_page_is_rejected(self) -> None: + """Every archival page must be present even when nothing links to it.""" + site = self._valid_site() + (site / "md_docs_2viewer.html").unlink() + + with self.assertRaisesRegex(validate_generated_site.GeneratedSiteError, "missing required page"): + validate_generated_site.validate(site) + + def test_missing_required_asset_is_rejected(self) -> None: + """Every archival asset must be present even when another check also references it.""" + site = self._valid_site() + (site / "clipboard.js").unlink() + + with self.assertRaisesRegex(validate_generated_site.GeneratedSiteError, "missing required asset"): + validate_generated_site.validate(site) + + def test_missing_dark_mode_styling_is_rejected(self) -> None: + """The generated stylesheet must preserve automatic dark-mode styling.""" + site = self._valid_site() + (site / "doxygen.css").write_text("/* generated test asset */\n", encoding="utf-8") + + with self.assertRaisesRegex(validate_generated_site.GeneratedSiteError, "missing automatic dark-mode styling"): + validate_generated_site.validate(site) + + def test_missing_graphviz_output_is_rejected(self) -> None: + """The generated site must contain at least one Graphviz SVG.""" + site = self._valid_site() + (site / "graph.svg").unlink() + + with self.assertRaisesRegex(validate_generated_site.GeneratedSiteError, "no generated Graphviz SVG was found"): + validate_generated_site.validate(site) + + def test_local_reference_escaping_site_is_rejected(self) -> None: + """Local references cannot leave the self-contained site root.""" + site = self._valid_site() + (site / "index.html").write_text( + (site / "index.html").read_text(encoding="utf-8") + 'escape', + encoding="utf-8", + ) + + with self.assertRaisesRegex(validate_generated_site.GeneratedSiteError, "local reference escapes the site"): + validate_generated_site.validate(site) + def test_missing_local_page_and_fragment_are_rejected(self) -> None: """Every generated local page and fragment reference must resolve.""" for reference, diagnostic in ( @@ -143,11 +186,11 @@ def test_public_completeness_warning_is_rejected(self) -> None: root = Path(self.enterContext(tempfile.TemporaryDirectory())) warning_log = root / "warnings.log" warning_log.write_text( - "include/Public.hpp:1: warning: Member run (function) of namespace cdt is not documented.\n", + "include/Public.hpp:1: warning: Member detail (function) of namespace cdt is not documented.\n", encoding="utf-8", ) - with self.assertRaisesRegex(validate_generated_site.GeneratedSiteError, "Public.hpp.*run"): + with self.assertRaisesRegex(validate_generated_site.GeneratedSiteError, "Public.hpp.*detail"): validate_generated_site.validate_warning_log(warning_log) def test_public_parameter_warning_is_rejected(self) -> None: diff --git a/scripts/validate_generated_site.py b/scripts/validate_generated_site.py index 77f624f18..669d65a2a 100755 --- a/scripts/validate_generated_site.py +++ b/scripts/validate_generated_site.py @@ -17,7 +17,7 @@ CSS_URL = re.compile(r"url\(\s*(?P['\"]?)(?P[^)'\"]+)(?P=quote)\s*\)") WHITESPACE = re.compile(r"\s+") COMPLETENESS_WARNING = re.compile(r"(?:\bis not documented[.]?$|\b(?:parameters|return type) of member .+ (?:are|is) not documented$)") -INTERNAL_SYMBOL = re.compile(r"(?:::|\b)detail(?:::|\s)|\bcdt::experimental::") +INTERNAL_SYMBOL = re.compile(r"::detail(?:::|\s)|\bcdt::experimental::") SOURCE_ARTIFACT = re.compile( r"(?:Member (?:catch|main|Timer)\b.*\bis not documented[.]?$|" r"parameters of member (?:catch|main)\b.*\bare not documented$)" @@ -58,6 +58,17 @@ class GeneratedSiteError(ValueError): """The generated site violates its archival publication contract.""" +TextCache = dict[Path, str] + + +def _decoded_text(path: Path, text_cache: TextCache, *, errors: str = "strict") -> str: + """Decode one generated file once for all validation passes.""" + resolved = path.resolve() + if resolved not in text_cache: + text_cache[resolved] = resolved.read_text(encoding="utf-8", errors=errors) + return text_cache[resolved] + + @dataclass(frozen=True) class Reference: """One URL-bearing HTML or CSS attribute.""" @@ -180,11 +191,11 @@ def handle_data(self, data: str) -> None: self.prose.append((self.getpos()[0], data)) -def _parse_document(path: Path) -> _DocumentParser: +def _parse_document(path: Path, text_cache: TextCache) -> _DocumentParser: """Parse one generated HTML document with path-specific diagnostics.""" parser = _DocumentParser(path) try: - parser.feed(path.read_text(encoding="utf-8")) + parser.feed(_decoded_text(path, text_cache)) parser.close() except (OSError, UnicodeError) as error: message = f"{path}: cannot parse generated HTML: {error}" @@ -269,13 +280,17 @@ def _validate_required_pages(root: Path, documents: dict[Path, _DocumentParser]) return errors -def _validate_required_features(root: Path, documents: dict[Path, _DocumentParser]) -> list[str]: +def _validate_required_features( + root: Path, + documents: dict[Path, _DocumentParser], + text_cache: TextCache, +) -> list[str]: """Validate the generated assets and presentation features retained for v1.""" errors = [f"missing required asset: {relative}" for relative in REQUIRED_ASSETS if not (root / relative).is_file()] index_path = (root / "index.html").resolve() if index_path in documents: - index_text = index_path.read_text(encoding="utf-8") + index_text = _decoded_text(index_path, text_cache) for marker, feature in ( ('name="viewport"', "responsive viewport"), ("codefold.init", "code folding"), @@ -285,11 +300,11 @@ def _validate_required_features(root: Path, documents: dict[Path, _DocumentParse errors.append(f"index.html is missing required {feature} markup") stylesheet = root / "doxygen.css" - if stylesheet.is_file() and "prefers-color-scheme: dark" not in stylesheet.read_text(encoding="utf-8"): + if stylesheet.is_file() and "prefers-color-scheme: dark" not in _decoded_text(stylesheet, text_cache): errors.append("doxygen.css is missing automatic dark-mode styling") graphviz_outputs = sorted(root.rglob("*.svg")) - if not any("Generated by graphviz" in item.read_text(encoding="utf-8", errors="ignore") for item in graphviz_outputs): + if not any("Generated by graphviz" in _decoded_text(item, text_cache, errors="ignore") for item in graphviz_outputs): errors.append("no generated Graphviz SVG was found") return errors @@ -344,11 +359,11 @@ def _validate_documents(root: Path, documents: dict[Path, _DocumentParser]) -> l return errors -def _validate_css(root: Path) -> list[str]: +def _validate_css(root: Path, text_cache: TextCache) -> list[str]: """Validate local assets referenced from generated stylesheets.""" errors: list[str] = [] for stylesheet in sorted(root.rglob("*.css")): - for line_number, line in enumerate(stylesheet.read_text(encoding="utf-8").splitlines(), start=1): + for line_number, line in enumerate(_decoded_text(stylesheet, text_cache).splitlines(), start=1): for match in CSS_URL.finditer(line): value = match.group("url").strip() reference = Reference(stylesheet.resolve(), line_number, value) @@ -373,16 +388,17 @@ def validate(site: Path) -> int: message = f"generated site directory does not exist: {root}" raise GeneratedSiteError(message) - documents = {item.resolve(): _parse_document(item.resolve()) for item in sorted(root.rglob("*.html"))} + text_cache: TextCache = {} + documents = {item.resolve(): _parse_document(item.resolve(), text_cache) for item in sorted(root.rglob("*.html"))} errors = _validate_required_pages(root, documents) - errors.extend(_validate_required_features(root, documents)) + errors.extend(_validate_required_features(root, documents, text_cache)) errors.extend(_validate_documents(root, documents)) - errors.extend(_validate_css(root)) + errors.extend(_validate_css(root, text_cache)) for item in sorted(root.rglob("*")): if not item.is_file() or item.suffix.lower() not in {".css", ".html", ".js"}: continue - text = item.read_text(encoding="utf-8") + text = _decoded_text(item, text_cache) if "mermaid.esm" in text or "cdn.jsdelivr.net/npm/mermaid" in text: errors.append(f"{_relative(item.resolve(), root)}: unused Mermaid client dependency") diff --git a/tests/Metropolis_test.cpp b/tests/Metropolis_test.cpp index 07fa94935..56c9833f4 100644 --- a/tests/Metropolis_test.cpp +++ b/tests/Metropolis_test.cpp @@ -735,6 +735,37 @@ SCENARIO("Metropolis transitions are sequential and failure-aware" * } } + GIVEN("An unsupported move value and an initialized strategy.") + { + auto manifold = minimal_26_manifold(); + auto const before = manifold.delaunay_snapshot(); + Metropolis_3 strategy(Alpha, 0.0L, 0.0L, 1, 1, false, cdt::RandomSeed{37}); + strategy.initialize(manifold); + auto const unknown = static_cast(255); + + WHEN("The unsupported move is submitted through the public API.") + { + auto const transition = strategy.attempt_transition(manifold, unknown, 0.0L); + + THEN("It is rejected before state or accounting is mutated.") + { + CHECK_EQ(transition.move(), unknown); + CHECK_EQ(transition.outcome(), + ergodic_moves::MoveOutcome::EXECUTION_FAILED); + CHECK_FALSE(transition.successful()); + CHECK_FALSE(transition.accepted()); + CHECK_EQ(manifold.delaunay_snapshot(), before); + CHECK_EQ(strategy.proposed().total(), 0); + CHECK_EQ(strategy.accepted().total(), 0); + CHECK_EQ(strategy.rejected().total(), 0); + CHECK_EQ(strategy.attempted().total(), 0); + CHECK_EQ(strategy.succeeded().total(), 0); + CHECK_EQ(strategy.failed().total(), 0); + CHECK_EQ(strategy.transition_count(), 0); + } + } + } + GIVEN("Equivalent manifolds and strategies using the same random stream.") { auto first_state = minimal_26_manifold(); diff --git a/tests/Move_outcome_test.cpp b/tests/Move_outcome_test.cpp index 250f6b69d..7bff22908 100644 --- a/tests/Move_outcome_test.cpp +++ b/tests/Move_outcome_test.cpp @@ -110,6 +110,8 @@ static_assert(MetropolisTransition{MoveType::TWO_THREE, static_assert(MetropolisTransition{MoveType::TWO_THREE, MoveOutcome::METROPOLIS_REJECTED} .successful()); +static_assert(MetropolisTransition{MoveType::TWO_THREE, MoveOutcome::SUCCEEDED} + .successful()); static_assert(!MetropolisTransition{MoveType::TWO_THREE, MoveOutcome::INAPPLICABLE} .successful()); From f183f072b44b3fe3b677090b8e5cd4983c193932 Mon Sep 17 00:00:00 2001 From: Adam Getchell Date: Sat, 8 Aug 2026 09:46:18 -0700 Subject: [PATCH 3/4] style(api): format transition validation --- include/Metropolis.hpp | 7 +++---- tests/Metropolis_test.cpp | 3 ++- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/include/Metropolis.hpp b/include/Metropolis.hpp index 3af62c3d9..91a0e5055 100644 --- a/include/Metropolis.hpp +++ b/include/Metropolis.hpp @@ -489,10 +489,9 @@ namespace cdt if (!reverse_move(move)) { - return ergodic_moves::outcome_from( - ergodic_moves::MoveError{ - .category = ergodic_moves::MoveFailure::UNKNOWN_MOVE, - .requested_move = move}); + return ergodic_moves::outcome_from(ergodic_moves::MoveError{ + .category = ergodic_moves::MoveFailure::UNKNOWN_MOVE, + .requested_move = move}); } statistics.geometry = current.geometry(); diff --git a/tests/Metropolis_test.cpp b/tests/Metropolis_test.cpp index 56c9833f4..64ed58a53 100644 --- a/tests/Metropolis_test.cpp +++ b/tests/Metropolis_test.cpp @@ -745,7 +745,8 @@ SCENARIO("Metropolis transitions are sequential and failure-aware" * WHEN("The unsupported move is submitted through the public API.") { - auto const transition = strategy.attempt_transition(manifold, unknown, 0.0L); + auto const transition = + strategy.attempt_transition(manifold, unknown, 0.0L); THEN("It is rejected before state or accounting is mutated.") { From 70ab238eb07271a7754266407f9f61e28e199b49 Mon Sep 17 00:00:00 2001 From: Adam Getchell Date: Sat, 8 Aug 2026 11:06:20 -0700 Subject: [PATCH 4/4] test(api): verify unknown moves preserve transition traces --- tests/Metropolis_test.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tests/Metropolis_test.cpp b/tests/Metropolis_test.cpp index 64ed58a53..6681bfde6 100644 --- a/tests/Metropolis_test.cpp +++ b/tests/Metropolis_test.cpp @@ -741,7 +741,8 @@ SCENARIO("Metropolis transitions are sequential and failure-aware" * auto const before = manifold.delaunay_snapshot(); Metropolis_3 strategy(Alpha, 0.0L, 0.0L, 1, 1, false, cdt::RandomSeed{37}); strategy.initialize(manifold); - auto const unknown = static_cast(255); + auto const unknown = static_cast(255); + auto const trace_before = strategy.transition_trace(); WHEN("The unsupported move is submitted through the public API.") { @@ -763,6 +764,7 @@ SCENARIO("Metropolis transitions are sequential and failure-aware" * CHECK_EQ(strategy.succeeded().total(), 0); CHECK_EQ(strategy.failed().total(), 0); CHECK_EQ(strategy.transition_count(), 0); + CHECK_EQ(strategy.transition_trace(), trace_before); } } }