diff --git a/Bench/Micro/spatial_query_bench.cpp b/Bench/Micro/spatial_query_bench.cpp index 7fc8ca6..13212eb 100644 --- a/Bench/Micro/spatial_query_bench.cpp +++ b/Bench/Micro/spatial_query_bench.cpp @@ -26,10 +26,16 @@ struct Lcg { } }; +struct TimingSummary { + std::uint64_t p50 = 0; + std::uint64_t p95 = 0; + std::uint64_t p99 = 0; +}; + template -std::uint64_t MedianNanoseconds(Function&& function) +TimingSummary MeasureNanoseconds(Function&& function) { - std::array samples{}; + std::array samples{}; std::uint64_t checksum = 0; for (std::size_t i = 0; i < samples.size(); ++i) { @@ -40,10 +46,14 @@ std::uint64_t MedianNanoseconds(Function&& function) std::chrono::duration_cast(stop - start).count()); } std::sort(samples.begin(), samples.end()); - // Keep observable work outside the timed region. if (checksum == 0xFFFFFFFFFFFFFFFFull) std::cerr << "checksum sentinel\n"; - return samples[samples.size() / 2]; + + const auto percentile = [&](std::size_t numerator) { + const std::size_t rank = (samples.size() * numerator + 99u) / 100u; + return samples[std::min(rank == 0 ? 0u : rank - 1u, samples.size() - 1u)]; + }; + return {percentile(50), percentile(95), percentile(99)}; } std::uint64_t RunQueries(const std::vector& xy, @@ -123,9 +133,11 @@ int main() constexpr float radius = 8.0f; constexpr float cell_size = 4.0f; - std::cout << "# synthetic calibration only; do not treat CI timing as certification\n"; - std::cout << "points,queries,cell_size,radius,baseline_total_ns,grid_stable_total_ns," - "grid_unordered_total_ns\n"; + std::cout << "# profile=spatial.synthetic.v1 seed=0x12345678 samples=31\n"; + std::cout << "# synthetic calibration only; CI timing is never certification\n"; + std::cout << "points,queries,cell_size,radius,baseline_p50_ns,baseline_p95_ns,baseline_p99_ns," + "grid_stable_p50_ns,grid_stable_p95_ns,grid_stable_p99_ns," + "grid_unordered_p50_ns,grid_unordered_p95_ns,grid_unordered_p99_ns\n"; for (const std::size_t point_count : sizes) { @@ -148,19 +160,21 @@ int main() return 2; } - const auto baseline_ns = MedianNanoseconds( - [&] { return RunQueries(xy, centers, radius, baseline); }); - const auto stable_ns = MedianNanoseconds([&] { + const TimingSummary baseline_ns = + MeasureNanoseconds([&] { return RunQueries(xy, centers, radius, baseline); }); + const TimingSummary stable_ns = MeasureNanoseconds([&] { return RunGridQueries(grid, xy, centers, radius, candidate, sc2opt::kernel::hot::SpatialOrder::InputOrder); }); - const auto unordered_ns = MedianNanoseconds([&] { + const TimingSummary unordered_ns = MeasureNanoseconds([&] { return RunGridQueries(grid, xy, centers, radius, candidate, sc2opt::kernel::hot::SpatialOrder::Unordered); }); std::cout << point_count << ',' << query_count << ',' << cell_size << ',' << radius << ',' - << baseline_ns << ',' << stable_ns << ',' << unordered_ns << '\n'; + << baseline_ns.p50 << ',' << baseline_ns.p95 << ',' << baseline_ns.p99 << ',' + << stable_ns.p50 << ',' << stable_ns.p95 << ',' << stable_ns.p99 << ',' + << unordered_ns.p50 << ',' << unordered_ns.p95 << ',' << unordered_ns.p99 << '\n'; } return 0; diff --git a/CMakeLists.txt b/CMakeLists.txt index 683c924..d221f9e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -80,6 +80,18 @@ target_link_libraries(sc2opt INTERFACE sc2opt_adapters ) +if(SC2OPT_BUILD_TESTS OR SC2OPT_BUILD_BENCHMARKS) + add_library(sc2opt_proof STATIC + Proof/Profiles.cpp + Proof/Manifest.cpp + ) + add_library(sc2opt::proof ALIAS sc2opt_proof) + target_include_directories(sc2opt_proof PUBLIC include) + target_link_libraries(sc2opt_proof PUBLIC sc2opt_tuner) + target_compile_features(sc2opt_proof PUBLIC cxx_std_20) + sc2opt_apply_warnings(sc2opt_proof) +endif() + if(SC2OPT_BUILD_PYTHON) find_package(Python COMPONENTS Interpreter Development.Module REQUIRED) set(PYBIND11_FINDPYTHON ON) @@ -130,6 +142,18 @@ if(SC2OPT_BUILD_TESTS) sc2opt_apply_warnings(sc2opt_runtime_optimization_tests) add_test(NAME sc2opt_runtime_optimization_tests COMMAND sc2opt_runtime_optimization_tests) + add_executable(sc2opt_deep_contract_tests tests/deep_contract_tests.cpp) + target_link_libraries(sc2opt_deep_contract_tests PRIVATE sc2opt) + target_compile_features(sc2opt_deep_contract_tests PRIVATE cxx_std_20) + sc2opt_apply_warnings(sc2opt_deep_contract_tests) + add_test(NAME sc2opt_deep_contract_tests COMMAND sc2opt_deep_contract_tests) + + add_executable(sc2opt_manifest_tests tests/manifest_tests.cpp) + target_link_libraries(sc2opt_manifest_tests PRIVATE sc2opt_proof) + target_compile_features(sc2opt_manifest_tests PRIVATE cxx_std_20) + sc2opt_apply_warnings(sc2opt_manifest_tests) + add_test(NAME sc2opt_manifest_tests COMMAND sc2opt_manifest_tests) + add_executable(sc2opt_synthetic_cpp_consumer examples/synthetic_cpp_consumer.cpp) target_link_libraries(sc2opt_synthetic_cpp_consumer PRIVATE sc2opt) target_compile_features(sc2opt_synthetic_cpp_consumer PRIVATE cxx_std_20) diff --git a/Outputs/README.md b/Outputs/README.md index c766426..46d6c9b 100644 --- a/Outputs/README.md +++ b/Outputs/README.md @@ -3,3 +3,13 @@ Generated benchmark, tuning, hardware/workload and certification manifests live here when explicitly produced for a run/release. They are not source authority and are git-ignored by default unless a reviewed fixture/baseline is intentionally committed. Every consumable output must carry enough provenance to answer: what source/build produced this, on what hardware/workload, with what correctness status and confidence? + +S30 provides a standard-library JSON writer plus `schemas/sc2aiopt-certification-v1.schema.json`. The writer fails closed when proof layers skip required gates, a synthetic workload attempts to claim representative proof, benchmark records are malformed, or identity/provenance is missing. + +Proof layers are ordered: + +```text +source/design -> build/tests -> representative benchmark -> consumer integration -> ladder/runtime +``` + +A later layer cannot be asserted without all earlier layers. This keeps CI/build success from being misrepresented as runtime certification. diff --git a/Profiles/README.md b/Profiles/README.md index 6182fe0..dfc6bd1 100644 --- a/Profiles/README.md +++ b/Profiles/README.md @@ -1,5 +1,8 @@ # Profiles -Profiles describe the environment/workload under which a candidate was measured: CPU/hardware capabilities, OS, compiler, flags, source revision, workload identity and relevant SC2 build/data version. +Hardware and workload profiles make benchmark evidence contextual rather than universal. -Profiles are evidence inputs/outputs. They are not permission to silently enable hardware-specific code; capability and net-benefit gates still apply. +- `spatial.synthetic.v1.json` is a deterministic synthetic calibration workload. It is useful for equivalence and rough crossover discovery but **cannot** claim representative benchmark proof. +- `representative.template.json` defines the minimum identity shape for a consumer-supplied replay/game/workload corpus. The template itself is not evidence and must never be treated as certified data. + +Representative profiles should identify the exact corpus (preferably a content hash), SC2 build/data version, selection rule and workload family. Hardware identity belongs in generated evidence/manifests rather than being hard-coded as source truth. diff --git a/Profiles/representative.template.json b/Profiles/representative.template.json new file mode 100644 index 0000000..0af7bed --- /dev/null +++ b/Profiles/representative.template.json @@ -0,0 +1,16 @@ +{ + "schema_version": 1, + "id": "REPLACE_ME", + "family": "REPLACE_ME", + "version": "1", + "kind": "representative", + "sc2_build": "75689", + "data_version": "B89B5D6FA7CBF6452E721311BFBC6CB2", + "corpus_identity": "sha256:REPLACE_ME", + "source": { + "description": "Representative replay/game/workload corpus supplied by the consumer proof flow", + "selection_rule": "REPLACE_ME", + "cases": [] + }, + "certification_role": "not-valid-until-all-placeholders-are-replaced-and-proven" +} diff --git a/Profiles/spatial.synthetic.v1.json b/Profiles/spatial.synthetic.v1.json new file mode 100644 index 0000000..ac8a2d5 --- /dev/null +++ b/Profiles/spatial.synthetic.v1.json @@ -0,0 +1,19 @@ +{ + "schema_version": 1, + "id": "spatial.synthetic.v1", + "family": "spatial-radius-query", + "version": "1", + "kind": "synthetic", + "sc2_build": "75689", + "data_version": "B89B5D6FA7CBF6452E721311BFBC6CB2", + "corpus_identity": "generator:lcg-1664525-1013904223;seed:0x12345678", + "generator": { + "coordinate_domain": [0.0, 128.0], + "point_counts": [8, 16, 32, 64, 128, 256, 512], + "query_count": 256, + "radius": 8.0, + "cell_size": 4.0, + "timing_samples": 31 + }, + "certification_role": "synthetic-calibration-only" +} diff --git a/Proof/Manifest.cpp b/Proof/Manifest.cpp new file mode 100644 index 0000000..e2f7096 --- /dev/null +++ b/Proof/Manifest.cpp @@ -0,0 +1,163 @@ +#include "sc2opt/proof/Manifest.hpp" + +#include +#include +#include + +namespace sc2opt::proof { +namespace { + +bool BenchmarkValid(const BenchmarkRecord& record) noexcept +{ + return record.samples > 0 && std::isfinite(record.mean_total_cost_ns) && + record.mean_total_cost_ns >= 0.0 && record.p50_ns <= record.p95_ns && + record.p95_ns <= record.p99_ns; +} + +bool ProofOrderValid(const ProofLayers& proof) noexcept +{ + if (proof.build_tests && !proof.source_design) + return false; + if (proof.representative_benchmark && !proof.build_tests) + return false; + if (proof.consumer_integration && !proof.representative_benchmark) + return false; + if (proof.ladder_runtime && !proof.consumer_integration) + return false; + return true; +} + +void WriteJsonString(std::ostream& out, std::string_view value) +{ + static constexpr char hex[] = "0123456789abcdef"; + out.put('"'); + for (const unsigned char ch : value) + { + switch (ch) + { + case '"': out << "\\\""; break; + case '\\': out << "\\\\"; break; + case '\b': out << "\\b"; break; + case '\f': out << "\\f"; break; + case '\n': out << "\\n"; break; + case '\r': out << "\\r"; break; + case '\t': out << "\\t"; break; + default: + if (ch < 0x20u) + { + out << "\\u00" << hex[(ch >> 4u) & 0x0fu] << hex[ch & 0x0fu]; + } + else + { + out.put(static_cast(ch)); + } + break; + } + } + out.put('"'); +} + +void WriteBool(std::ostream& out, bool value) +{ + out << (value ? "true" : "false"); +} + +} // namespace + +ManifestIssue ValidateManifest(const CertificationManifestView& manifest) noexcept +{ + if (manifest.schema_version != kCertificationManifestSchemaVersion) + return ManifestIssue::SchemaVersion; + if (manifest.source_revision.empty() || manifest.generated_utc.empty()) + return ManifestIssue::MissingIdentity; + if (!IsValid(manifest.hardware)) + return ManifestIssue::InvalidHardware; + if (!IsValid(manifest.workload)) + return ManifestIssue::InvalidWorkload; + if (!ProofOrderValid(manifest.proof)) + return ManifestIssue::InvalidProofOrder; + if (manifest.proof.representative_benchmark && + (manifest.workload.kind != WorkloadKind::Representative || manifest.benchmarks.empty())) + { + return ManifestIssue::MissingRepresentativeEvidence; + } + + for (const BenchmarkRecord& record : manifest.benchmarks) + { + if (!BenchmarkValid(record)) + return ManifestIssue::InvalidBenchmark; + if (manifest.proof.representative_benchmark && !record.correctness_passed) + return ManifestIssue::InvalidBenchmark; + } + + return ManifestIssue::None; +} + +bool WriteCertificationManifestJson(std::ostream& out, + const CertificationManifestView& manifest) +{ + if (ValidateManifest(manifest) != ManifestIssue::None) + return false; + + out << "{\n \"schema_version\": " << manifest.schema_version << ",\n \"source_revision\": "; + WriteJsonString(out, manifest.source_revision); + out << ",\n \"generated_utc\": "; + WriteJsonString(out, manifest.generated_utc); + out << ",\n \"hardware\": {\n \"id\": "; + WriteJsonString(out, manifest.hardware.id); + out << ",\n \"cpu\": "; + WriteJsonString(out, manifest.hardware.cpu); + out << ",\n \"os\": "; + WriteJsonString(out, manifest.hardware.os); + out << ",\n \"compiler\": "; + WriteJsonString(out, manifest.hardware.compiler); + out << ",\n \"build_config\": "; + WriteJsonString(out, manifest.hardware.build_config); + out << "\n },\n \"workload\": {\n \"id\": "; + WriteJsonString(out, manifest.workload.id); + out << ",\n \"family\": "; + WriteJsonString(out, manifest.workload.family); + out << ",\n \"version\": "; + WriteJsonString(out, manifest.workload.version); + out << ",\n \"kind\": "; + WriteJsonString(out, manifest.workload.kind == WorkloadKind::Representative ? "representative" + : "synthetic"); + out << ",\n \"sc2_build\": "; + WriteJsonString(out, manifest.workload.sc2_build); + out << ",\n \"data_version\": "; + WriteJsonString(out, manifest.workload.data_version); + out << ",\n \"corpus_identity\": "; + WriteJsonString(out, manifest.workload.corpus_identity); + out << "\n },\n \"proof\": {\n \"source_design\": "; + WriteBool(out, manifest.proof.source_design); + out << ",\n \"build_tests\": "; + WriteBool(out, manifest.proof.build_tests); + out << ",\n \"representative_benchmark\": "; + WriteBool(out, manifest.proof.representative_benchmark); + out << ",\n \"consumer_integration\": "; + WriteBool(out, manifest.proof.consumer_integration); + out << ",\n \"ladder_runtime\": "; + WriteBool(out, manifest.proof.ladder_runtime); + out << "\n },\n \"benchmarks\": ["; + + for (std::size_t i = 0; i < manifest.benchmarks.size(); ++i) + { + const BenchmarkRecord& record = manifest.benchmarks[i]; + out << (i == 0 ? "\n" : ",\n") << " {\"candidate\": " << record.candidate + << ", \"workload_size\": " << record.workload_size + << ", \"samples\": " << record.samples + << ", \"mean_total_cost_ns\": " << std::setprecision(17) + << record.mean_total_cost_ns << ", \"p50_ns\": " << record.p50_ns + << ", \"p95_ns\": " << record.p95_ns << ", \"p99_ns\": " << record.p99_ns + << ", \"correctness_passed\": "; + WriteBool(out, record.correctness_passed); + out << '}'; + } + + if (!manifest.benchmarks.empty()) + out << '\n'; + out << " ]\n}\n"; + return static_cast(out); +} + +} // namespace sc2opt::proof diff --git a/Proof/Profiles.cpp b/Proof/Profiles.cpp new file mode 100644 index 0000000..4db0425 --- /dev/null +++ b/Proof/Profiles.cpp @@ -0,0 +1,18 @@ +#include "sc2opt/proof/Profiles.hpp" + +namespace sc2opt::proof { + +bool IsValid(const HardwareProfileView& profile) noexcept +{ + return !profile.id.empty() && !profile.cpu.empty() && !profile.os.empty() && + !profile.compiler.empty() && !profile.build_config.empty(); +} + +bool IsValid(const WorkloadProfileView& profile) noexcept +{ + return !profile.id.empty() && !profile.family.empty() && !profile.version.empty() && + !profile.sc2_build.empty() && !profile.data_version.empty() && + !profile.corpus_identity.empty(); +} + +} // namespace sc2opt::proof diff --git a/docs/PROOF_AND_OUTPUTS.md b/docs/PROOF_AND_OUTPUTS.md new file mode 100644 index 0000000..081391a --- /dev/null +++ b/docs/PROOF_AND_OUTPUTS.md @@ -0,0 +1,35 @@ +# Proof and outputs — S28-S30 + +## S28 deep tests + +The deterministic deep-contract suite adds property/fuzz-style coverage without a fuzzing runtime dependency: + +- geometry symmetry and boundary invariants across thousands of generated cases; +- filtering equivalence against an independent reference predicate; +- spatial-grid exact InputOrder equivalence against brute force across generated worlds, cell sizes, radii and strict/inclusive boundaries; +- unordered spatial membership equivalence; +- non-finite input fail-closed regression coverage. + +The generator seed is fixed so failures are reproducible in CI. Dedicated sanitizer/fuzzer toolchain integration remains S31. + +## S29 benchmark/workload profiles + +Workloads have explicit identity, SC2 build/data version, family, version, kind and corpus identity. Synthetic and representative evidence are different types of proof. + +The spatial microbenchmark now records p50/p95/p99 from 31 samples and declares its deterministic profile/seed in output. CI timing remains synthetic calibration data and is explicitly not certification. + +`Profiles/representative.template.json` is only a contract/template. It cannot become evidence until a real consumer corpus replaces all placeholders and receives a stable corpus identity/hash. + +## S30 consumable outputs + +`sc2opt_proof` is a separate proof-only library and is **not linked by `sc2opt::sc2opt`**. It validates hardware/workload identity and writes a versioned certification JSON manifest with benchmark records and proof-layer status. + +The writer enforces monotonic proof layers: + +```text +source/design -> build/tests -> representative benchmark -> consumer integration -> ladder/runtime +``` + +Representative benchmark proof additionally requires a representative workload and non-empty correctness-passing benchmark evidence. This prevents a green CI run or synthetic benchmark from being serialized as a stronger certification than it really is. + +The JSON schema is published under `schemas/` for BotOps and other consumers. diff --git a/docs/STATUS.md b/docs/STATUS.md index 49d75e0..01b7916 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -9,11 +9,12 @@ SC2AIOptimize is pre-V1. Implementation presence is not runtime/performance cert - **S09-S14 — Kernel/Hot:** merged. Geometry, filtering and spatial baseline/candidate contracts are correctness-tested; spatial optimisation remains **certified OFF by default** until target-workload crossover evidence exists. - **S15-S19 — Kernel/Compute:** merged. Deterministic score reduction, reference/bounded influence, Dijkstra/A* pathing, footprint placement and minimal caller-supplied combat evaluation are present with correctness contracts. - **S20-S24 — Tuner:** merged. Net-benefit baseline/OFF selection, validated TunableRegistry, repeated champion/challenger evidence, baseline-only/reset mode, context/crossover selection and versioned provenance persistence are present. +- **S25-S27 — runtime optimisation:** merged. Fixed-storage telemetry, compile-time-disabled timing, generic latency hysteresis governor, crossover calibration and an explicit control-overhead cheapness gate are present. ## Current work -- **S25-S27 — runtime optimisation:** fixed-storage telemetry, compile-time-disabled instrumentation, generic latency hysteresis governor, crossover auto-calibration and explicit tuner/control-overhead cheapness gate. +- **S28-S30 — proof/output:** deterministic deep contract/property tests, reproducible workload profiles, p50/p95/p99 benchmark output and a proof-only versioned certification-manifest contract for BotOps/consumers. ## Not yet claimed -No target-hardware crossover, bot integration, ladder-runtime speedup, behavioural equivalence or V1 release certification is claimed yet. Those require the later deep-test, benchmark/profile/output and hardening slices plus representative consumer evidence. +No target-hardware crossover, bot integration, ladder-runtime speedup, behavioural equivalence or V1 release certification is claimed yet. S31 toolchain hardening and S32 integrated certification remain outstanding, as do representative consumer evidence and target-hardware measurements. diff --git a/include/sc2opt/proof/Manifest.hpp b/include/sc2opt/proof/Manifest.hpp new file mode 100644 index 0000000..7a420cf --- /dev/null +++ b/include/sc2opt/proof/Manifest.hpp @@ -0,0 +1,60 @@ +#pragma once + +#include "sc2opt/proof/Profiles.hpp" +#include "sc2opt/tuner/NetBenefit.hpp" + +#include +#include +#include +#include +#include + +namespace sc2opt::proof { + +inline constexpr std::uint32_t kCertificationManifestSchemaVersion = 1; + +struct ProofLayers { + bool source_design = false; + bool build_tests = false; + bool representative_benchmark = false; + bool consumer_integration = false; + bool ladder_runtime = false; +}; + +struct BenchmarkRecord { + tuner::CandidateId candidate = tuner::kBaselineCandidate; + std::size_t workload_size = 0; + std::uint64_t samples = 0; + double mean_total_cost_ns = 0.0; + std::uint64_t p50_ns = 0; + std::uint64_t p95_ns = 0; + std::uint64_t p99_ns = 0; + bool correctness_passed = false; +}; + +struct CertificationManifestView { + std::uint32_t schema_version = kCertificationManifestSchemaVersion; + std::string_view source_revision; + std::string_view generated_utc; + HardwareProfileView hardware{}; + WorkloadProfileView workload{}; + ProofLayers proof{}; + std::span benchmarks{}; +}; + +enum class ManifestIssue : std::uint8_t { + None, + SchemaVersion, + MissingIdentity, + InvalidHardware, + InvalidWorkload, + InvalidProofOrder, + MissingRepresentativeEvidence, + InvalidBenchmark +}; + +[[nodiscard]] ManifestIssue ValidateManifest(const CertificationManifestView& manifest) noexcept; +[[nodiscard]] bool WriteCertificationManifestJson(std::ostream& out, + const CertificationManifestView& manifest); + +} // namespace sc2opt::proof diff --git a/include/sc2opt/proof/Profiles.hpp b/include/sc2opt/proof/Profiles.hpp new file mode 100644 index 0000000..9345816 --- /dev/null +++ b/include/sc2opt/proof/Profiles.hpp @@ -0,0 +1,31 @@ +#pragma once + +#include +#include + +namespace sc2opt::proof { + +enum class WorkloadKind : std::uint8_t { Synthetic = 0, Representative = 1 }; + +struct HardwareProfileView { + std::string_view id; + std::string_view cpu; + std::string_view os; + std::string_view compiler; + std::string_view build_config; +}; + +struct WorkloadProfileView { + std::string_view id; + std::string_view family; + std::string_view version; + WorkloadKind kind = WorkloadKind::Synthetic; + std::string_view sc2_build; + std::string_view data_version; + std::string_view corpus_identity; +}; + +[[nodiscard]] bool IsValid(const HardwareProfileView& profile) noexcept; +[[nodiscard]] bool IsValid(const WorkloadProfileView& profile) noexcept; + +} // namespace sc2opt::proof diff --git a/schemas/sc2aiopt-certification-v1.schema.json b/schemas/sc2aiopt-certification-v1.schema.json new file mode 100644 index 0000000..7ffd355 --- /dev/null +++ b/schemas/sc2aiopt-certification-v1.schema.json @@ -0,0 +1,69 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://github.com/Valessc2/SC2AIOptimize/schemas/sc2aiopt-certification-v1.schema.json", + "title": "SC2AIOptimize certification manifest v1", + "type": "object", + "additionalProperties": false, + "required": ["schema_version", "source_revision", "generated_utc", "hardware", "workload", "proof", "benchmarks"], + "properties": { + "schema_version": {"const": 1}, + "source_revision": {"type": "string", "minLength": 1}, + "generated_utc": {"type": "string", "minLength": 1}, + "hardware": { + "type": "object", + "additionalProperties": false, + "required": ["id", "cpu", "os", "compiler", "build_config"], + "properties": { + "id": {"type": "string", "minLength": 1}, + "cpu": {"type": "string", "minLength": 1}, + "os": {"type": "string", "minLength": 1}, + "compiler": {"type": "string", "minLength": 1}, + "build_config": {"type": "string", "minLength": 1} + } + }, + "workload": { + "type": "object", + "additionalProperties": false, + "required": ["id", "family", "version", "kind", "sc2_build", "data_version", "corpus_identity"], + "properties": { + "id": {"type": "string", "minLength": 1}, + "family": {"type": "string", "minLength": 1}, + "version": {"type": "string", "minLength": 1}, + "kind": {"enum": ["synthetic", "representative"]}, + "sc2_build": {"type": "string", "minLength": 1}, + "data_version": {"type": "string", "minLength": 1}, + "corpus_identity": {"type": "string", "minLength": 1} + } + }, + "proof": { + "type": "object", + "additionalProperties": false, + "required": ["source_design", "build_tests", "representative_benchmark", "consumer_integration", "ladder_runtime"], + "properties": { + "source_design": {"type": "boolean"}, + "build_tests": {"type": "boolean"}, + "representative_benchmark": {"type": "boolean"}, + "consumer_integration": {"type": "boolean"}, + "ladder_runtime": {"type": "boolean"} + } + }, + "benchmarks": { + "type": "array", + "items": { + "type": "object", + "additionalProperties": false, + "required": ["candidate", "workload_size", "samples", "mean_total_cost_ns", "p50_ns", "p95_ns", "p99_ns", "correctness_passed"], + "properties": { + "candidate": {"type": "integer", "minimum": 0}, + "workload_size": {"type": "integer", "minimum": 0}, + "samples": {"type": "integer", "minimum": 1}, + "mean_total_cost_ns": {"type": "number", "minimum": 0}, + "p50_ns": {"type": "integer", "minimum": 0}, + "p95_ns": {"type": "integer", "minimum": 0}, + "p99_ns": {"type": "integer", "minimum": 0}, + "correctness_passed": {"type": "boolean"} + } + } + } + } +} diff --git a/tests/deep_contract_tests.cpp b/tests/deep_contract_tests.cpp new file mode 100644 index 0000000..0aa92ef --- /dev/null +++ b/tests/deep_contract_tests.cpp @@ -0,0 +1,203 @@ +#include "sc2opt/kernel/hot/Filtering.hpp" +#include "sc2opt/kernel/hot/Geometry.hpp" +#include "sc2opt/kernel/hot/SpatialGrid.hpp" +#include "sc2opt/model/WorldView.hpp" + +#include +#include +#include +#include +#include +#include +#include + +namespace { + +int failures = 0; + +void Check(bool condition, std::string_view message) +{ + if (!condition) + { + ++failures; + std::cerr << "FAIL: " << message << '\n'; + } +} + +struct Lcg { + std::uint32_t state = 0x6d2b79f5u; + + std::uint32_t Next() noexcept + { + state = state * 1664525u + 1013904223u; + return state; + } + + float Coordinate() noexcept + { + const auto signed_value = static_cast(Next() % 32769u) - 16384; + return static_cast(signed_value) / 64.0f; + } + + float Positive(float maximum) noexcept + { + return static_cast(Next() & 0xffffu) * (maximum / 65535.0f); + } +}; + +void TestGeometryProperties() +{ + using namespace sc2opt::kernel::hot; + Lcg rng; + for (int i = 0; i < 5000; ++i) + { + const Vec2 a{rng.Coordinate(), rng.Coordinate()}; + const Vec2 b{rng.Coordinate(), rng.Coordinate()}; + const float radius = rng.Positive(64.0f); + const float ab = DistanceSquared(a, b); + const float ba = DistanceSquared(b, a); + Check(ab >= 0.0f && ab == ba, "distance squared symmetry/non-negative"); + if (WithinRadius(a, b, radius, BoundaryMode::Strict)) + Check(WithinRadius(a, b, radius, BoundaryMode::Inclusive), + "strict radius implies inclusive radius"); + } + + Check(!WithinRadius({0.0f, 0.0f}, {0.0f, 0.0f}, -1.0f), + "negative radius rejected"); + Check(!WithinRadius({0.0f, 0.0f}, {1.0f, 0.0f}, + std::numeric_limits::quiet_NaN()), + "NaN radius fails closed"); +} + +bool ReferenceMatch(const sc2opt::model::UnitView& unit, + sc2opt::kernel::hot::UnitFilter filter) noexcept +{ + using namespace sc2opt::kernel::hot; + if ((unit.flags & filter.required_flags) != filter.required_flags) + return false; + if ((unit.flags & filter.excluded_flags) != 0u) + return false; + if (filter.consumer_type_id != kAnyConsumerType && + unit.consumer_type_id != filter.consumer_type_id) + { + return false; + } + return unit.health >= filter.minimum_health; +} + +void TestFilteringProperties() +{ + using namespace sc2opt; + Lcg rng; + for (int iteration = 0; iteration < 300; ++iteration) + { + const std::size_t count = 1u + (rng.Next() % 128u); + std::vector units(count); + for (std::size_t i = 0; i < count; ++i) + { + units[i].tag = i + 1; + units[i].consumer_type_id = rng.Next() % 8u; + units[i].flags = rng.Next() & 0x0fu; + units[i].health = rng.Positive(500.0f); + } + + kernel::hot::UnitFilter filter{}; + filter.required_flags = rng.Next() & 0x0fu; + filter.excluded_flags = rng.Next() & 0x0fu; + filter.consumer_type_id = (rng.Next() & 1u) != 0u ? rng.Next() % 8u + : kernel::hot::kAnyConsumerType; + filter.minimum_health = rng.Positive(500.0f); + + std::vector expected; + for (std::size_t i = 0; i < units.size(); ++i) + { + if (ReferenceMatch(units[i], filter)) + expected.push_back(static_cast(i)); + } + + std::vector actual(count); + const auto result = kernel::hot::FilterUnitIndices(units, filter, actual); + Check(result && result.written == expected.size(), "filter property count"); + Check(std::equal(expected.begin(), expected.end(), actual.begin()), + "filter property ordering/content"); + } +} + +void TestSpatialFuzzEquivalence() +{ + using namespace sc2opt::kernel::hot; + Lcg rng; + constexpr float cell_sizes[] = {1.0f, 2.0f, 4.0f, 8.0f, 16.0f}; + + for (int world = 0; world < 80; ++world) + { + const std::size_t point_count = 1u + (rng.Next() % 192u); + std::vector xy(point_count * 2u); + for (float& value : xy) + value = rng.Coordinate(); + + SpatialGrid2D grid; + const float cell_size = cell_sizes[rng.Next() % 5u]; + Check(grid.SetCellSize(cell_size) == SpatialStatus::Ok, "fuzz cell size accepted"); + Check(grid.Rebuild(xy) == SpatialStatus::Ok, "fuzz grid rebuild"); + + std::vector reference(point_count); + std::vector stable(point_count); + std::vector unordered(point_count); + + for (int query = 0; query < 40; ++query) + { + const Vec2 center{rng.Coordinate(), rng.Coordinate()}; + const float radius = rng.Positive(48.0f); + const BoundaryMode boundary = (rng.Next() & 1u) != 0u ? BoundaryMode::Inclusive + : BoundaryMode::Strict; + + const auto baseline = RadiusQueryBruteForce(xy, center, radius, reference, boundary); + const auto ordered = + grid.Query(center, radius, stable, SpatialOrder::InputOrder, boundary); + const auto loose = grid.Query(center, radius, unordered, SpatialOrder::Unordered, + boundary); + + Check(baseline && ordered && loose, "fuzz spatial query statuses"); + if (!baseline || !ordered || !loose) + continue; + + Check(baseline.written == ordered.written && baseline.written == loose.written, + "fuzz spatial count equivalence"); + Check(std::equal(reference.begin(), reference.begin() + baseline.written, + stable.begin()), + "fuzz stable spatial order equivalence"); + + std::vector expected(reference.begin(), + reference.begin() + baseline.written); + std::vector actual(unordered.begin(), unordered.begin() + loose.written); + std::sort(expected.begin(), expected.end()); + std::sort(actual.begin(), actual.end()); + Check(expected == actual, "fuzz unordered spatial membership equivalence"); + } + } + + SpatialGrid2D grid; + const float nan = std::numeric_limits::quiet_NaN(); + const std::vector invalid{0.0f, 0.0f, nan, 1.0f}; + Check(grid.Rebuild(invalid) == SpatialStatus::NonFiniteCoordinate, + "non-finite spatial input fails closed"); +} + +} // namespace + +int main() +{ + TestGeometryProperties(); + TestFilteringProperties(); + TestSpatialFuzzEquivalence(); + + if (failures == 0) + { + std::cout << "SC2AIOptimize deep contract tests passed\n"; + return 0; + } + + std::cerr << failures << " deep contract test(s) failed\n"; + return 1; +} diff --git a/tests/manifest_tests.cpp b/tests/manifest_tests.cpp new file mode 100644 index 0000000..32b6e6e --- /dev/null +++ b/tests/manifest_tests.cpp @@ -0,0 +1,79 @@ +#include "sc2opt/proof/Manifest.hpp" + +#include +#include +#include +#include +#include + +namespace { + +int failures = 0; + +void Check(bool condition, std::string_view message) +{ + if (!condition) + { + ++failures; + std::cerr << "FAIL: " << message << '\n'; + } +} + +void TestProfilesAndManifest() +{ + using namespace sc2opt::proof; + + const HardwareProfileView hardware{"test-hw", "Example CPU", "linux", "gcc-14", "Release"}; + const WorkloadProfileView workload{"dense-fight-v1", "spatial", "1", WorkloadKind::Representative, + "75689", "B89", "sha256:abc123"}; + const std::array records{ + BenchmarkRecord{0, 128, 100, 1000.0, 900, 1200, 1400, true}, + BenchmarkRecord{1, 128, 100, 600.0, 550, 800, 950, true}, + }; + + CertificationManifestView manifest{}; + manifest.source_revision = "abc\"def\\ghi"; + manifest.generated_utc = "2026-08-19T00:00:00Z"; + manifest.hardware = hardware; + manifest.workload = workload; + manifest.proof = {true, true, true, false, false}; + manifest.benchmarks = records; + + Check(ValidateManifest(manifest) == ManifestIssue::None, "valid manifest"); + std::ostringstream out; + Check(WriteCertificationManifestJson(out, manifest), "manifest writer succeeds"); + const std::string json = out.str(); + Check(json.find("abc\\\"def\\\\ghi") != std::string::npos, + "manifest JSON escapes identity strings"); + Check(json.find("\"candidate\": 1") != std::string::npos, + "manifest contains candidate records"); + + CertificationManifestView invalid_order = manifest; + invalid_order.proof = {true, true, false, false, true}; + Check(ValidateManifest(invalid_order) == ManifestIssue::InvalidProofOrder, + "proof layers cannot skip gates"); + + CertificationManifestView synthetic_claim = manifest; + synthetic_claim.workload.kind = WorkloadKind::Synthetic; + Check(ValidateManifest(synthetic_claim) == ManifestIssue::MissingRepresentativeEvidence, + "synthetic workload cannot claim representative benchmark proof"); + + CertificationManifestView bad_benchmark = manifest; + const std::array bad_records{BenchmarkRecord{1, 128, 10, 1.0, 100, 90, 110, true}}; + bad_benchmark.benchmarks = bad_records; + Check(ValidateManifest(bad_benchmark) == ManifestIssue::InvalidBenchmark, + "invalid benchmark quantile order rejected"); +} + +} // namespace + +int main() +{ + TestProfilesAndManifest(); + if (failures == 0) + { + std::cout << "SC2AIOptimize manifest tests passed\n"; + return 0; + } + return 1; +}