aien-sovereign-core-mv
AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.
Brought by drakestapleton
GitHub aien-dev/aien-sovereign-core-mv#141 (code only)
Apply it
git checkout -b patch-7baf3b96dc79a248 f2bb53919207c543d3bcd6c4b6ba8881d780c48e curl -fsSL https://interplane.io/drakestapleton/aien-sovereign-core-mv/patches/7baf3b96dc79a248.patch | git am
Provenance
github-import 1
aien-dev/aien-sovereign-core-mv
141
4baa18d048a66badd511e35ad10305162f6504b0
{"kind":"github-import","owner":"aien-dev","repo":"aien-sovereign-core-mv","number":141,"url":"https://github.com/aien-dev/aien-sovereign-core-mv/pull/141","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:36:05Z","metadata":"unavailable","state_derived":true}
Changes
diff --git a/.github/workflows/hardening.yml b/.github/workflows/hardening.yml new file mode 100644 index 00000000..db2c7352 --- /dev/null +++ b/.github/workflows/hardening.yml @@ -0,0 +1,130 @@ +name: Hardening + +# Lane L-E checks. Each check here comes with mutations that prove it catches +# a realistic fault (crates/aien-replay/mutations/). ci.yml is left alone. +# +# - kv-props: property tests on KV fork / append / free / rollback ownership, +# then every kv.mutants mutation must make them fail. +# - trn1-rust: the Rust TRN1 reader must reproduce every line of the shared +# corpus manifests, and switching off any one check must break that. +# - miri: aien-capability and aien-kv-cache unit + integration tests under +# Miri (undefined-behaviour checker, nightly only), plus the KV property +# tests at a low case count, then the Miri-only mutation must be caught. +# +# aien-replay is its own workspace root until the member-line PR lands, so it +# is built with --manifest-path. + +"on": + push: + branches: [main] + paths: + - "crates/aien-replay/**" + - "crates/aien-kv-cache/**" + - "crates/aien-capability/**" + - "crates/aien-platform/**" + - "crates/aien-platform-linux/**" + - ".github/workflows/hardening.yml" + pull_request: + branches: [main] + paths: + - "crates/aien-replay/**" + - "crates/aien-kv-cache/**" + - "crates/aien-capability/**" + - "crates/aien-platform/**" + - "crates/aien-platform-linux/**" + - ".github/workflows/hardening.yml" + workflow_dispatch: + +permissions: + contents: read + +jobs: + kv-props: + name: KV ownership properties + mutants + runs-on: ubuntu-latest + steps: + - name: Checkout Source + uses: actions/checkout@v4 + + - name: Install Stable Rust Toolchain + uses: dtolnay/rust-toolchain@stable + + - name: Fetch dependencies + run: cargo fetch --manifest-path crates/aien-replay/Cargo.toml + + - name: KV ownership property tests + run: cargo test --manifest-path crates/aien-replay/Cargo.toml --test kv_ownership_props + + - name: Every KV mutation must be caught + run: sh crates/aien-replay/mutations/run_mutants.sh native + + miri: + name: Miri (aien-capability, aien-kv-cache) + runs-on: ubuntu-latest + steps: + - name: Checkout Source + uses: actions/checkout@v4 + + - name: Checkout Sibling Protocols Dependency + uses: actions/checkout@v4 + with: + repository: aien-dev/aien-protocols + ref: 7ac6facb630ca7e9a6ab4125b292203fe2bb6687 + path: aien-protocols + + - name: Setup Sibling Dependencies + run: | + mkdir -p ../aien-protocols + cp -r aien-protocols/* ../aien-protocols/ + + - name: Install Nightly Rust Toolchain with Miri + uses: dtolnay/rust-toolchain@nightly + with: + components: miri, rust-src + + - name: Miri setup + run: cargo miri setup + + - name: Miri on aien-capability + run: cargo miri test -p aien-capability + + - name: Miri on aien-kv-cache + run: cargo miri test -p aien-kv-cache + + - name: Miri on KV ownership property tests (8 cases) + run: | + cargo fetch --manifest-path crates/aien-replay/Cargo.toml + cargo miri test --manifest-path crates/aien-replay/Cargo.toml --test kv_ownership_props + + - name: Miri-only mutation must be caught + run: sh crates/aien-replay/mutations/run_mutants.sh miri + + trn1-rust: + name: TRN1 conformance (impl=rust) + check mutants + runs-on: ubuntu-latest + steps: + - name: Checkout Source + uses: actions/checkout@v4 + + # Pinned TRN1 corpus (aien-protocols, lane L-B). Bump the pin when the + # contract corpus changes. + - name: Checkout pinned TRN1 contract corpus + uses: actions/checkout@v4 + with: + repository: aien-dev/aien-protocols + ref: 353b7d4be3f00169545caec1615cffa61f7d311a + path: trn1-protocols + + - name: Install Stable Rust Toolchain + uses: dtolnay/rust-toolchain@stable + + - name: Run shared corpus through the Rust reader + env: + TRN1_VECTORS: ${{ github.workspace }}/trn1-protocols/specs/execution-transcript/vectors + TRN1_REQUIRE: "1" + run: cargo test --manifest-path crates/aien-replay/Cargo.toml --test trn1_conformance -- --nocapture + + - name: Every TRN1 check must be needed by the corpus + env: + TRN1_VECTORS: ${{ github.workspace }}/trn1-protocols/specs/execution-transcript/vectors + run: sh crates/aien-replay/mutations/run_mutants.sh trn1 diff --git a/crates/aien-replay/Cargo.lock b/crates/aien-replay/Cargo.lock new file mode 100644 index 00000000..a76d722d --- /dev/null +++ b/crates/aien-replay/Cargo.lock @@ -0,0 +1,402 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "aien-kv-cache" +version = "0.1.0" +dependencies = [ + "aien-platform", + "aien-platform-linux", + "libc", + "parking_lot", + "serde", +] + +[[package]] +name = "aien-platform" +version = "0.1.0" + +[[package]] +name = "aien-platform-linux" +version = "0.1.0" +dependencies = [ + "aien-platform", + "libc", + "parking_lot", +] + +[[package]] +name = "aien-replay" +version = "0.1.0" +dependencies = [ + "aien-kv-cache", + "proptest", + "sha2", +] + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "libc", + "r-efi", + "wasip2", +] + +[[package]] +name = "libc" +version = "0.2.189" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "smallvec", + "windows-link", +] + +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "proptest" +version = "1.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "37566cb3fdacef14c0737f9546df7cfeadbfbc9fef10991038bf5015d0c80532" +dependencies = [ + "bitflags", + "num-traits", + "rand", + "rand_chacha", + "rand_xorshift", + "regex-syntax", + "unarray", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + +[[package]] +name = "rand" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41" +dependencies = [ + "rand_chacha", + "rand_core", +] + +[[package]] +name = "rand_chacha" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" +dependencies = [ + "ppv-lite86", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" +dependencies = [ + "getrandom", +] + +[[package]] +name = "rand_xorshift" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "513962919efc330f829edb2535844d1b912b0fbe2ca165d613e4e8788bb05a5a" +dependencies = [ + "rand_core", +] + +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags", +] + +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "smallvec" +version = "1.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba467056f1b547ed52077911161fc86985becbc60e8e1857c8a144dab0def891" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8593e8e72159ed2257d083c7a454a85cbf854f37a0966d8d483aff8c8a3ebcee" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unarray" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eaea85b334db583fe3274d12b4cd1880032beab409c0d774be044d4480ab9a94" + +[[package]] +name = "unicode-ident" +version = "1.0.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "wasip2" +version = "1.0.4+wasi-0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "wit-bindgen" +version = "0.57.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" + +[[package]] +name = "zerocopy" +version = "0.8.57" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d35102a9f36d089ccae9e4c6802bc118be4487b80aaffc0ab4e0cf5ce92d2873" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.57" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "146c01f5ab44258da43cf276c74a2763db2ff3969c9c652c3f2de07041d0b2bc" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] diff --git a/crates/aien-replay/Cargo.toml b/crates/aien-replay/Cargo.toml new file mode 100644 index 00000000..aee73ccb --- /dev/null +++ b/crates/aien-replay/Cargo.toml @@ -0,0 +1,22 @@ +[package] +name = "aien-replay" +version = "0.1.0" +edition = "2021" +license = "Apache-2.0 WITH LLVM-exception" +authors = ["Drake Stapleton <aien@aienos.com>"] +repository = "https://github.com/aien-dev/aien-sovereign-core" +description = "TRN1 execution transcript reference reader/verifier (Rust scaffolding per ADR 0024) and KV ownership property tests" +publish = false + +# Standalone for now: this crate is its own workspace root so it builds with +# `cargo test --manifest-path crates/aien-replay/Cargo.toml` without editing the +# shared workspace member list (reserved by PR #138). The follow-up member PR +# deletes this table and adds "crates/aien-replay" to the root members list. +[workspace] + +[dependencies] +sha2 = "0.10" + +[dev-dependencies] +aien-kv-cache = { path = "../aien-kv-cache" } +proptest = { version = "1", default-features = false, features = ["std"] } diff --git a/crates/aien-replay/mutations/kv.mutants b/crates/aien-replay/mutations/kv.mutants new file mode 100644 index 00000000..940cccbe --- /dev/null +++ b/crates/aien-replay/mutations/kv.mutants @@ -0,0 +1,8 @@ +# Mutations of crates/aien-kv-cache/src/lib.rs. Format: id<TAB>sed expression<TAB>what it models. +# Each must be KILLED (a property test fails) for run_mutants.sh native to pass. +fork_no_refcount s#self.blocks\[blk_id\].ref_count += 1;#{}# fork shares blocks without counting the new holder +cow_no_copy s#pool.copy_block(last_blk_id, new_blk);#{}# copy-on-write allocates the private block but forgets to copy the prefix +cow_write_in_place s#if blk.is_shared {#if false {# append writes into a block another branch still reads +cow_no_unshare s#old_blk.ref_count -= 1;#{}# copy-on-write never drops the old holder +free_leak s#self.free_blocks.push(blk_id);#{}# free_sequence forgets to return a block to the free list +rollback_keeps_free_list s#manager.free_blocks = snapshot.free_blocks;#{}# rollback restores tables but not the free list diff --git a/crates/aien-replay/mutations/miri.mutants b/crates/aien-replay/mutations/miri.mutants new file mode 100644 index 00000000..968e82c2 --- /dev/null +++ b/crates/aien-replay/mutations/miri.mutants @@ -0,0 +1,3 @@ +# Mutations that only Miri can see (native tests still pass). Same format. +# run_mutants.sh miri requires each to be KILLED under cargo miri test. +heap_dealloc_wrong_layout s#std::alloc::dealloc(self.ptr, self.layout);#std::alloc::dealloc(self.ptr, std::alloc::Layout::from_size_align_unchecked(self.len, 1));# buffer freed with a different alignment than it was allocated with (undefined behaviour; glibc does not notice) diff --git a/crates/aien-replay/mutations/run_mutants.sh b/crates/aien-replay/mutations/run_mutants.sh new file mode 100755 index 00000000..d6afa91e --- /dev/null +++ b/crates/aien-replay/mutations/run_mutants.sh @@ -0,0 +1,102 @@ +#!/bin/sh +# Prove the KV ownership checks catch realistic faults. +# +# usage: run_mutants.sh native apply each kv.mutants line, run the proptest, +# expect a FAILED test (KILLED) +# run_mutants.sh miri apply each miri.mutants line, expect native +# tests to still pass and `cargo miri test` to fail +# run_mutants.sh trn1 switch off each TRN1 check (trn1.mutants), expect +# the shared corpus test to fail; needs TRN1_VECTORS +# or the sibling ../aien-protocols checkout +# +# Works on a scratch copy; the real tree is never modified. Exit 0 only if +# every mutant is KILLED. A mutant that does not compile counts as BROKEN +# (a bad mutant, not a kill) and fails the run. +set -eu + +mode=${1:-native} +here=$(cd "$(dirname "$0")" && pwd) +root=$(cd "$here/../../.." && pwd) +case "$mode" in +native) table="$here/kv.mutants" ;; +miri) table="$here/miri.mutants" ;; +trn1) table="$here/trn1.mutants" ;; +*) echo "usage: $0 native|miri|trn1" >&2; exit 2 ;; +esac + +work=$(mktemp -d) +trap 'rm -rf "$work"' EXIT INT TERM +mkdir -p "$work/crates" +for c in aien-kv-cache aien-platform aien-platform-linux aien-replay; do + mkdir -p "$work/crates/$c" + (cd "$root/crates/$c" && tar cf - --exclude=./target .) | (cd "$work/crates/$c" && tar xf -) +done +# Minimal workspace root: same [workspace.package] values, only the three +# crates the test needs, so the copy builds without the aien-protocols sibling. +awk '/^members = \[/ { print "members = [\"crates/aien-kv-cache\", \"crates/aien-platform\", \"crates/aien-platform-linux\"]"; skip = 1; next } + skip && /^\]/ { skip = 0; next } + !skip { print }' "$root/Cargo.toml" >"$work/Cargo.toml" + +src="$work/crates/aien-kv-cache/src/lib.rs" +test=kv_ownership_props +if [ "$mode" = trn1 ]; then + src="$work/crates/aien-replay/src/lib.rs" + test=trn1_conformance + vectors=$(cd "${TRN1_VECTORS:-$root/../aien-protocols/specs/execution-transcript/vectors}" && pwd) + export TRN1_VECTORS="$vectors" TRN1_REQUIRE=1 +fi +cp "$src" "$work/lib.rs.orig" +manifest="$work/crates/aien-replay/Cargo.toml" +export CARGO_TARGET_DIR="${MUTANT_TARGET_DIR:-$work/target}" +cargo=${CARGO:-cargo} + +run_native() { $cargo test --offline --manifest-path "$manifest" --test "$test" >"$1" 2>&1; } +run_miri() { $cargo miri test --manifest-path "$manifest" --test "$test" >"$1" 2>&1; } + +fail=0 +killed=0 +total=0 +tab=$(printf '\t') +while IFS="$tab" read -r id expr what; do + case "$id" in '' | '#'*) continue ;; esac + total=$((total + 1)) + cp "$work/lib.rs.orig" "$src" + sed -i "$expr" "$src" + if cmp -s "$src" "$work/lib.rs.orig"; then + echo "BROKEN $id: sed expression matched nothing" + fail=1 + continue + fi + log="$work/$id.log" + if [ "$mode" != miri ]; then + if run_native "$log"; then + echo "SURVIVED $id ($what)" + fail=1 + elif grep -q "test result: FAILED" "$log"; then + echo "KILLED $id ($what)" + killed=$((killed + 1)) + else + echo "BROKEN $id: did not compile" + tail -n 20 "$log" + fail=1 + fi + else + if ! run_native "$log.native"; then + echo "NOTE $id: native tests also fail, so this is not a Miri-only catch" + fi + if run_miri "$log"; then + echo "SURVIVED $id under Miri ($what)" + fail=1 + elif grep -q "Undefined Behavior" "$log"; then + echo "KILLED $id under Miri ($what)" + killed=$((killed + 1)) + else + echo "BROKEN $id: Miri run failed without reporting UB" + tail -n 20 "$log" + fail=1 + fi + fi +done <"$table" + +echo "mode=$mode killed=$killed total=$total" +exit "$fail" diff --git a/crates/aien-replay/mutations/trn1.mutants b/crates/aien-replay/mutations/trn1.mutants new file mode 100644 index 00000000..ab722e14 --- /dev/null +++ b/crates/aien-replay/mutations/trn1.mutants @@ -0,0 +1,28 @@ +# Mutations of crates/aien-replay/src/lib.rs: each switches off one TRN1 check +# through the MUTANT hook. Each must be KILLED by the shared corpus. +magic s#^const MUTANT: &str = "";#const MUTANT: \&str = "magic";# TRN1 check 'magic' switched off +version s#^const MUTANT: &str = "";#const MUTANT: \&str = "version";# TRN1 check 'version' switched off +hdr_flags s#^const MUTANT: &str = "";#const MUTANT: \&str = "hdr_flags";# TRN1 check 'hdr_flags' switched off +producer s#^const MUTANT: &str = "";#const MUTANT: \&str = "producer";# TRN1 check 'producer' switched off +hdr_reserved s#^const MUTANT: &str = "";#const MUTANT: \&str = "hdr_reserved";# TRN1 check 'hdr_reserved' switched off +type s#^const MUTANT: &str = "";#const MUTANT: \&str = "type";# TRN1 check 'type' switched off +subsystem s#^const MUTANT: &str = "";#const MUTANT: \&str = "subsystem";# TRN1 check 'subsystem' switched off +rec_reserved s#^const MUTANT: &str = "";#const MUTANT: \&str = "rec_reserved";# TRN1 check 'rec_reserved' switched off +limit s#^const MUTANT: &str = "";#const MUTANT: \&str = "limit";# TRN1 check 'limit' switched off +seq s#^const MUTANT: &str = "";#const MUTANT: \&str = "seq";# TRN1 check 'seq' switched off +prev s#^const MUTANT: &str = "";#const MUTANT: \&str = "prev";# TRN1 check 'prev' switched off +ident_len s#^const MUTANT: &str = "";#const MUTANT: \&str = "ident_len";# TRN1 check 'ident_len' switched off +end_subsystem s#^const MUTANT: &str = "";#const MUTANT: \&str = "end_subsystem";# TRN1 check 'end_subsystem' switched off +cap_op s#^const MUTANT: &str = "";#const MUTANT: \&str = "cap_op";# TRN1 check 'cap_op' switched off +crash_seq s#^const MUTANT: &str = "";#const MUTANT: \&str = "crash_seq";# TRN1 check 'crash_seq' switched off +crumb_shape s#^const MUTANT: &str = "";#const MUTANT: \&str = "crumb_shape";# TRN1 check 'crumb_shape' switched off +argus_flag s#^const MUTANT: &str = "";#const MUTANT: \&str = "argus_flag";# TRN1 check 'argus_flag' switched off +end_annot s#^const MUTANT: &str = "";#const MUTANT: \&str = "end_annot";# TRN1 check 'end_annot' switched off +body_reserved s#^const MUTANT: &str = "";#const MUTANT: \&str = "body_reserved";# TRN1 check 'body_reserved' switched off +crumb_digest s#^const MUTANT: &str = "";#const MUTANT: \&str = "crumb_digest";# TRN1 check 'crumb_digest' switched off +input_digest s#^const MUTANT: &str = "";#const MUTANT: \&str = "input_digest";# TRN1 check 'input_digest' switched off +argus_cont s#^const MUTANT: &str = "";#const MUTANT: \&str = "argus_cont";# TRN1 check 'argus_cont' switched off +argus_link s#^const MUTANT: &str = "";#const MUTANT: \&str = "argus_link";# TRN1 check 'argus_link' switched off +end_count s#^const MUTANT: &str = "";#const MUTANT: \&str = "end_count";# TRN1 check 'end_count' switched off +trailing s#^const MUTANT: &str = "";#const MUTANT: \&str = "trailing";# TRN1 check 'trailing' switched off +truncated s#^const MUTANT: &str = "";#const MUTANT: \&str = "truncated";# TRN1 check 'truncated' switched off diff --git a/crates/aien-replay/src/lib.rs b/crates/aien-replay/src/lib.rs new file mode 100644 index 00000000..180efcf1 --- /dev/null +++ b/crates/aien-replay/src/lib.rs @@ -0,0 +1,391 @@ +//! aien-replay: Rust reference reader/verifier for the TRN1 execution +//! transcript (aien-protocols `specs/execution-transcript/`, contract 0.1.0, +//! wire schema 1). +//! +//! ADR 0024: Rust here is scaffolding. Omega is the destination. This crate +//! only reads bytes, applies the spec's check order (section 7) and prints the +//! spec's outcome lines (section 8). It writes nothing and imports no runtime. + +use sha2::{Digest, Sha256}; + +pub type Hash = [u8; 32]; + +pub const HEADER_LEN: usize = 48; +pub const RECORD_HEADER_LEN: usize = 56; +pub const MAX_RECORDS: u64 = 4096; +pub const MAX_IDENT: u32 = 65536; +pub const MAX_ANNOT: u32 = 65536; +pub const MAX_INPUT_CONTENT: u32 = 4096; +const T_END: u16 = 0xFFFF; + +/// Refusal codes, spec section 6. +pub mod code { + pub const MAGIC: i32 = -1; + pub const VERSION: i32 = -2; + pub const LENGTH: i32 = -3; + pub const NONCANONICAL: i32 = -4; + pub const UNKNOWN: i32 = -5; + pub const SHAPE: i32 = -6; + pub const GAP: i32 = -7; + pub const CHAIN: i32 = -8; + pub const DIGEST: i32 = -9; + pub const TRUNCATED: i32 = -10; +} + +/// Mutation hook. `mutations/run_mutants.sh trn1` rewrites this constant to +/// the name of one check, which switches that check off, and requires the +/// shared corpus to notice. In the real build it names no check. +const MUTANT: &str = ""; +#[inline(always)] +fn on(check: &str) -> bool { + MUTANT != check +} + +/// Subsystem registry, spec section 5.2. +pub fn subsystem_name(id: u16) -> Option<&'static str> { + Some(match id { + 0 => "transcript", + 1 => "omega-world", + 2 => "omega-cortex", + 3 => "omega-jspace", + 4 => "aienos-kernel", + 5 => "aienos-argus", + 6 => "aienos-store", + 7 => "sovcore-runtime", + 8 => "sovcore-scheduler", + 9 => "sovcore-kv", + 10 => "external", + _ => return None, + }) +} + +enum IdentRule { + Exact(u32), + ExternalInput, + Crumb, +} + +/// Record type registry, spec section 5.1. None = unknown type. +fn ident_rule(t: u16) -> Option<IdentRule> { + use IdentRule::*; + Some(match t { + 1 => Exact(32), + 2 | 3 | 5 => Exact(24), + 4 | 14 => Exact(40), + 6 | 10 | 13 => Exact(48), + 7 => Exact(32), + 8 | 9 => Exact(56), + 11 => ExternalInput, + 12 => Exact(16), + 15 => Crumb, + 16 => Exact(200), + T_END => Exact(16), + _ => return None, + }) +} + +/// An accepted transcript. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Accepted { + pub records: u64, + pub run_id: Hash, + pub final_digest: Hash, + /// Per record (index 0 = record 1): compared digest and subsystem id. + pub compared: Vec<(Hash, u16)>, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Verdict { + Accept(Accepted), + Refuse { code: i32, event: u64 }, +} + +fn u16le(b: &[u8]) -> u16 { + u16::from_le_bytes([b[0], b[1]]) +} +fn u32le(b: &[u8]) -> u32 { + u32::from_le_bytes(b[..4].try_into().expect("4 bytes")) +} +fn u64le(b: &[u8]) -> u64 { + u64::from_le_bytes(b[..8].try_into().expect("8 bytes")) +} +fn zero(b: &[u8]) -> bool { + b.iter().all(|&x| x == 0) +} +fn sha(parts: &[&[u8]]) -> Hash { + let mut h = Sha256::new(); + for p in parts { + h.update(p); + } + h.finalize().into() +} + +/// RX_CRUMB canonical bytes (spec 5.3): true if they parse to exactly their length. +fn crumb_shape(c: &[u8]) -> bool { + let mut o = 0usize; + let need = |o: usize, k: usize| c.len() - o >= k; + if !need(o, 36) { + return false; + } + let id = u64le(c); + o += 36; + for (limit, each) in [(8u32, 24usize), (8, 16), (8, 24)] { + if !need(o, 4) { + return false; + } + let k = u32le(&c[o..]); + o += 4; + if k > limit || !need(o, k as usize * each) { + return false; + } + o += k as usize * each; + } + if !need(o, 8) { + return false; // reason i32 + n_parents u32 + } + let parents = u32le(&c[o + 4..]); + o += 8; + if parents > 65 { + return false; + } + for _ in 0..parents { + if !need(o, 8) { + return false; + } + let p = u64le(&c[o..]); + o += 8; + if p >= 1 && p < id { + if !need(o, 32) { + return false; + } + o += 32; + } + } + o == c.len() +} + +/// Reserved fields inside an identity (step 9). True if all are zero. +fn ident_reserved_ok(t: u16, id: &[u8]) -> bool { + match t { + 3 => u32le(&id[20..]) == 0, + 6 | 11 | 12 | 14 => u32le(&id[4..]) == 0, + 7 => zero(&id[5..8]), + 10 => u32le(&id[12..]) == 0, + 16 => zero(&id[129..136]), + T_END => u64le(&id[8..]) == 0, + _ => true, + } +} + +/// Verify one transcript buffer, spec section 7 check order. +pub fn verify(b: &[u8]) -> Verdict { + let refuse = |code, event| Verdict::Refuse { code, event }; + let n = b.len(); + + // Header. + if n < 4 { + return refuse(code::LENGTH, 0); + } + if on("magic") && &b[..4] != b"TRN1" { + return refuse(code::MAGIC, 0); + } + if n < 6 { + return refuse(code::LENGTH, 0); + } + if on("version") && u16le(&b[4..]) != 1 { + return refuse(code::VERSION, 0); + } + if n < HEADER_LEN { + return refuse(code::LENGTH, 0); + } + if on("hdr_flags") && u16le(&b[6..]) != 0 { + return refuse(code::NONCANONICAL, 0); + } + let producer = u16le(&b[40..]); + if on("producer") && (producer == 0 || subsystem_name(producer).is_none()) { + return refuse(code::UNKNOWN, 0); + } + if on("hdr_reserved") && !zero(&b[42..48]) { + return refuse(code::NONCANONICAL, 0); + } + let run_id: Hash = b[8..40].try_into().expect("32 bytes"); + let mut prev = sha(&[&b[..HEADER_LEN]]); + let mut o = HEADER_LEN; + let mut compared = Vec::new(); + let mut argus_after: Option<Hash> = None; + + for k in 1u64.. { + // 1. record header present + if o == n { + return if on("truncated") { + refuse(code::TRUNCATED, k) + } else { + refuse(0, k) + }; + } + if n - o < RECORD_HEADER_LEN || k > MAX_RECORDS { + return refuse(code::LENGTH, k); + } + let r = &b[o..]; + let (t, sub) = (u16le(r), u16le(&r[2..])); + let (ilen, alen) = (u32le(&r[4..]), u32le(&r[8..])); + // 2. known type and subsystem + let rule = ident_rule(t); + if on("type") && rule.is_none() { + return refuse(code::UNKNOWN, k); + } + if on("subsystem") && subsystem_name(sub).is_none() { + return refuse(code::UNKNOWN, k); + } + // 3. reserved + if on("rec_reserved") && u32le(&r[12..]) != 0 { + return refuse(code::NONCANONICAL, k); + } + // 4. length limits + if on("limit") && (ilen > MAX_IDENT || alen > MAX_ANNOT) { + return refuse(code::LENGTH, k); + } + // 5. sequence + if on("seq") && u64le(&r[16..]) != k { + return refuse(code::GAP, k); + } + // 6. chain + if on("prev") && r[24..56] != prev { + return refuse(code::CHAIN, k); + } + // 7. body present + let body = ilen as u64 + alen as u64; + if ((n - o - RECORD_HEADER_LEN) as u64) < body { + return refuse(code::LENGTH, k); + } + let rec_len = RECORD_HEADER_LEN + body as usize; + let id = &r[RECORD_HEADER_LEN..RECORD_HEADER_LEN + ilen as usize]; + + // 8. shape + let len_ok = match rule { + Some(IdentRule::Exact(x)) => ilen == x, + Some(IdentRule::ExternalInput) => (48..=48 + MAX_INPUT_CONTENT).contains(&ilen), + Some(IdentRule::Crumb) => ilen >= 32, + None => true, // only reachable with the "type" check mutated off + }; + if on("ident_len") && !len_ok { + return refuse(code::SHAPE, k); + } + // Body fields below are read only when the length is right, so a + // mutated-off length check cannot index out of range. + if on("end_subsystem") && (t == T_END) != (sub == 0) { + return refuse(code::SHAPE, k); + } + if on("cap_op") && t == 7 && len_ok && !(1..=6).contains(&id[4]) { + return refuse(code::SHAPE, k); + } + if on("crash_seq") && t == 13 && len_ok && u64le(&id[8..]) >= k { + return refuse(code::SHAPE, k); + } + if on("crumb_shape") && t == 15 && ilen >= 32 && !crumb_shape(&id[32..]) { + return refuse(code::SHAPE, k); + } + if on("argus_flag") && t == 16 && len_ok && id[128] > 1 { + return refuse(code::SHAPE, k); + } + if on("end_annot") && t == T_END && alen != 0 { + return refuse(code::SHAPE, k); + } + // 9. reserved fields inside the identity + if on("body_reserved") && len_ok && !ident_reserved_ok(t, id) { + return refuse(code::NONCANONICAL, k); + } + // 10. embedded digests + if t == 15 + && ilen >= 32 + && on("crumb_digest") + && sha(&[b"AIEN_RX_CAUSAL_V1", &id[32..]]) != id[..32] + { + return refuse(code::DIGEST, k); + } + if t == 11 && ilen > 48 && on("input_digest") && sha(&[&id[48..]]) != id[16..48] { + return refuse(code::DIGEST, k); + } + if t == 16 && len_ok { + let before: Hash = id[136..168].try_into().expect("32 bytes"); + let after: Hash = id[168..200].try_into().expect("32 bytes"); + if on("argus_cont") && argus_after.is_some_and(|a| a != before) { + return refuse(code::DIGEST, k); + } + let want = if id[128] != 0 { + sha(&[&before, &id[..128]]) + } else { + before + }; + if on("argus_link") && want != after { + return refuse(code::DIGEST, k); + } + argus_after = Some(after); + } + + // record digest (chain) and compared digest (replay) + prev = sha(&[&r[..rec_len]]); + let cmp = sha(&[b"AIEN_TRN1_CMP", &r[0..4], &r[16..24], &r[4..8], id]); + compared.push((cmp, sub)); + o += rec_len; + + // 11. END + if t == T_END { + if on("end_count") && (ilen < 8 || u64le(id) != k) { + return refuse(code::GAP, k); + } + if on("trailing") && o != n { + return refuse(code::LENGTH, k + 1); + } + return Verdict::Accept(Accepted { + records: k, + run_id, + final_digest: prev, + compared, + }); + } + } + unreachable!("record loop only exits by return") +} + +fn hex(d: &Hash) -> String { + d.iter().map(|x| format!("{x:02x}")).collect() +} + +/// Verify outcome line, spec section 8. +pub fn verdict_line(v: &Verdict) -> String { + match v { + Verdict::Accept(a) => format!( + "ok records={} run={} final={}", + a.records, + hex(&a.run_id), + hex(&a.final_digest) + ), + Verdict::Refuse { code, event } => format!("refuse {code} event={event}"), + } +} + +/// Compare outcome line, spec section 8: expected first, actual second. +pub fn compare_line(expected: &Verdict, actual: &Verdict) -> String { + let (e, a) = match (expected, actual) { + (Verdict::Refuse { code, event }, _) => { + return format!("refuse expected {code} event={event}") + } + (_, Verdict::Refuse { code, event }) => { + return format!("refuse actual {code} event={event}") + } + (Verdict::Accept(e), Verdict::Accept(a)) => (e, a), + }; + for (i, (x, y)) in e.compared.iter().zip(&a.compared).enumerate() { + if x.0 != y.0 { + return format!( + "DIVERGENCE event={} expected={} actual={} subsystem={}", + i + 1, + hex(&x.0), + hex(&y.0), + subsystem_name(x.1).unwrap_or("?") + ); + } + } + format!("MATCH through {}", e.records.min(a.records)) +} diff --git a/crates/aien-replay/tests/kv_ownership_props.rs b/crates/aien-replay/tests/kv_ownership_props.rs new file mode 100644 index 00000000..2c2e0a64 --- /dev/null +++ b/crates/aien-replay/tests/kv_ownership_props.rs @@ -0,0 +1,318 @@ +//! Property tests: KV block ownership under fork / append / free / reserve. +//! +//! A random program of KV operations runs against `AienKvManager` and against +//! a tiny reference model (each live sequence = the list of token values it +//! should read back). After every step the checks below must hold. Each check +//! has a named mutation in `mutations/kv.mutants` that it is known to catch; +//! `mutations/run_mutants.sh` proves that. +//! +//! - ownership: every block's ref_count equals the number of block tables +//! that hold it; `is_shared` is true exactly when ref_count > 1. +//! - conservation: free blocks + referenced blocks == pool size (no leak, no +//! double free), and every block a sequence holds is not on the free list. +//! - content: every sequence reads back exactly the values written to it, so +//! a write to one branch never shows up in another (copy-on-write isolation). +//! - rollback: reserve_token followed by rollback leaves the manager state +//! identical to before the reservation. +//! +//! Known gap, not a property here: fork onto a sequence id that already exists +//! (see `fork_onto_live_child_leaks_blocks` below). + +use aien_kv_cache::{AienKvManager, HeapUnifiedBuffer, KvDType, KvPoolConfig}; +use proptest::prelude::*; +use std::collections::BTreeMap; + +const TOTAL_BLOCKS: usize = 24; +const BLOCK_SIZE: usize = 4; +const SEQ_IDS: u64 = 6; +const KV_DIM: usize = 2; + +type Mgr = AienKvManager<HeapUnifiedBuffer>; +type Model = BTreeMap<u64, Vec<f32>>; + +fn new_mgr() -> Mgr { + let cfg = KvPoolConfig { + num_blocks: TOTAL_BLOCKS, + block_size: BLOCK_SIZE, + num_layers: 1, + num_kv_heads: 1, + head_dim: KV_DIM, + dtype: KvDType::Fp32, + }; + let buf = HeapUnifiedBuffer::allocate(cfg.total_bytes(), 64).expect("heap buffer"); + AienKvManager::with_buffer(TOTAL_BLOCKS, BLOCK_SIZE, cfg, buf).expect("manager") +} + +#[derive(Debug, Clone)] +enum Op { + Alloc { seq: u64, n: usize }, + Fork { parent: u64, child: u64 }, + Append { seq: u64 }, + Free { seq: u64 }, + ReserveRollback { seq: u64 }, + ReserveCommit { seq: u64 }, +} + +fn op() -> impl Strategy<Value = Op> { + let s = 0..SEQ_IDS; + prop_oneof![ + 1 => (s.clone(), 0usize..10).prop_map(|(seq, n)| Op::Alloc { seq, n }), + 3 => (s.clone(), s.clone()).prop_map(|(parent, child)| Op::Fork { parent, child }), + 4 => s.clone().prop_map(|seq| Op::Append { seq }), + 1 => s.clone().prop_map(|seq| Op::Free { seq }), + 2 => s.clone().prop_map(|seq| Op::ReserveRollback { seq }), + 1 => s.prop_map(|seq| Op::ReserveCommit { seq }), + ] +} + +/// Everything about the manager that a caller can observe, for equality. +#[derive(Debug, PartialEq)] +struct Observed { + tables: Vec<(u64, Vec<usize>, usize)>, + blocks: Vec<(usize, usize, bool)>, + free: usize, + content: Vec<(u64, Vec<f32>)>, +} + +fn observe(mgr: &Mgr, model: &Model) -> Observed { + let mut tables = Vec::new(); + let mut content = Vec::new(); + for &seq in model.keys() { + if let Some(t) = mgr.get_block_table(seq) { + tables.push((seq, t.block_ids.clone(), t.total_tokens)); + content.push(( + seq, + mgr.gather_layer_kv(seq, 0) + .map(|kv| kv.0) + .unwrap_or_default(), + )); + } + } + let blocks = (0..TOTAL_BLOCKS) + .map(|b| { + let blk = mgr.get_block(b).expect("block exists"); + (blk.ref_count, blk.num_tokens, blk.is_shared) + }) + .collect(); + Observed { + tables, + blocks, + free: mgr.free_block_count(), + content, + } +} + +fn token_value(counter: &mut u32) -> f32 { + *counter += 1; + *counter as f32 +} + +fn write_token(mgr: &mut Mgr, block: usize, slot: usize, val: f32) { + let k = [val; KV_DIM]; + let v = [-val; KV_DIM]; + mgr.write_explicit_token_kv(block, 0, slot, &k, &v) + .expect("pool attached"); +} + +fn check(mgr: &Mgr, model: &Model) -> Result<(), TestCaseError> { + prop_assert_eq!( + mgr.active_sequence_count(), + model.len(), + "live sequence count" + ); + + let mut holders = vec![0usize; TOTAL_BLOCKS]; + for (&seq, values) in model { + let t = mgr + .get_block_table(seq) + .ok_or_else(|| TestCaseError::fail(format!("seq {seq} has no table")))?; + prop_assert_eq!(t.total_tokens, values.len(), "seq {} token count", seq); + prop_assert_eq!( + t.block_ids.len(), + values.len().div_ceil(BLOCK_SIZE), + "seq {} block count", + seq + ); + let mut in_blocks = 0; + for (i, &b) in t.block_ids.iter().enumerate() { + holders[b] += 1; + let n = mgr.get_block(b).expect("block").num_tokens; + if i + 1 < t.block_ids.len() { + prop_assert_eq!(n, BLOCK_SIZE, "seq {} non-tail block {} not full", seq, b); + } + in_blocks += n; + } + prop_assert_eq!( + in_blocks, + values.len(), + "seq {} tokens recorded in blocks", + seq + ); + + // content: what the sequence reads back is exactly what was written to it + let (k, v) = mgr.gather_layer_kv(seq, 0).map_err(TestCaseError::fail)?; + let want_k: Vec<f32> = values.iter().flat_map(|&x| [x; KV_DIM]).collect(); + let want_v: Vec<f32> = values.iter().flat_map(|&x| [-x; KV_DIM]).collect(); + prop_assert_eq!(k, want_k, "seq {} K content", seq); + prop_assert_eq!(v, want_v, "seq {} V content", seq); + } + + let mut referenced = 0; + for (b, &h) in holders.iter().enumerate() { + let blk = mgr.get_block(b).expect("block"); + prop_assert_eq!(blk.ref_count, h, "block {} ref_count vs holders", b); + if blk.ref_count > 0 { + referenced += 1; + prop_assert_eq!( + blk.is_shared, + blk.ref_count > 1, + "block {} is_shared flag", + b + ); + } + } + prop_assert_eq!( + mgr.free_block_count() + referenced, + TOTAL_BLOCKS, + "free + referenced must equal pool size (leak or double free)" + ); + Ok(()) +} + +fn apply( + mgr: &mut Mgr, + model: &mut Model, + counter: &mut u32, + op: &Op, +) -> Result<(), TestCaseError> { + match *op { + Op::Alloc { seq, n } => { + if model.contains_key(&seq) { + // existing sequence: the call returns its table and changes nothing + mgr.allocate_sequence(seq, &[0; 3]) + .map_err(TestCaseError::fail)?; + return Ok(()); + } + let prompt: Vec<u32> = (0..n as u32).collect(); + if mgr.allocate_sequence(seq, &prompt).is_ok() { + let mut vals = Vec::with_capacity(n); + for pos in 0..n { + let val = token_value(counter); + mgr.write_token_kv(seq, pos, 0, &[val; KV_DIM], &[-val; KV_DIM]) + .map_err(TestCaseError::fail)?; + vals.push(val); + } + model.insert(seq, vals); + } + } + Op::Fork { parent, child } => { + if model.contains_key(&child) { + return Ok(()); // known gap, see fork_onto_live_child_leaks_blocks + } + match mgr.fork_sequence(parent, child) { + Ok(_) => { + let vals = model + .get(&parent) + .cloned() + .ok_or_else(|| TestCaseError::fail("fork of missing parent succeeded"))?; + model.insert(child, vals); + } + Err(_) => prop_assert!(!model.contains_key(&parent), "fork of live parent refused"), + } + } + Op::Append { seq } => { + if let Ok((block, slot)) = mgr.append_token_with_slot(seq) { + let vals = model + .get_mut(&seq) + .ok_or_else(|| TestCaseError::fail("append to missing seq succeeded"))?; + prop_assert_eq!(slot, vals.len() % BLOCK_SIZE, "slot for seq {}", seq); + let val = token_value(counter); + write_token(mgr, block, slot, val); + vals.push(val); + } + } + Op::Free { seq } => { + let ok = mgr.free_sequence(seq).is_ok(); + prop_assert_eq!( + ok, + model.remove(&seq).is_some(), + "free result for seq {}", + seq + ); + } + Op::ReserveRollback { seq } => { + let before = observe(mgr, model); + if let Ok(r) = mgr.reserve_token(seq) { + prop_assert!(model.contains_key(&seq), "reserve on missing seq succeeded"); + mgr.rollback(r).map_err(TestCaseError::fail)?; + } + let after = observe(mgr, model); + prop_assert_eq!(before, after, "reserve+rollback must restore state"); + } + Op::ReserveCommit { seq } => { + if let Ok(r) = mgr.reserve_token(seq) { + let (block, slot) = (r.block_id, r.slot); + mgr.commit(r).map_err(TestCaseError::fail)?; + let vals = model + .get_mut(&seq) + .ok_or_else(|| TestCaseError::fail("reserve on missing seq succeeded"))?; + let val = token_value(counter); + write_token(mgr, block, slot, val); + vals.push(val); + } + } + } + Ok(()) +} + +/// Case count: PROPTEST_CASES if set, else 256 (8 under Miri, which is slow). +fn cases() -> u32 { + std::env::var("PROPTEST_CASES") + .ok() + .and_then(|s| s.parse().ok()) + .unwrap_or(if cfg!(miri) { 8 } else { 256 }) +} + +proptest! { + #![proptest_config(ProptestConfig { + cases: cases(), + failure_persistence: None, + ..ProptestConfig::default() + })] + + #[test] + fn kv_ownership_holds_under_random_programs(ops in prop::collection::vec(op(), 1..60)) { + let mut mgr = new_mgr(); + let mut model = Model::new(); + let mut counter = 0u32; + for op in &ops { + apply(&mut mgr, &mut model, &mut counter, op)?; + check(&mgr, &model)?; + } + // drain: freeing every live sequence returns the whole pool + let live: Vec<u64> = model.keys().copied().collect(); + for seq in live { + mgr.free_sequence(seq).map_err(TestCaseError::fail)?; + model.remove(&seq); + check(&mgr, &model)?; + } + prop_assert_eq!(mgr.free_block_count(), TOTAL_BLOCKS); + } +} + +/// Known gap: forking onto a sequence id that is still live overwrites its +/// block table without releasing the old blocks, so they never return to the +/// free list. Fixing it needs an edit to aien-kv-cache/src/lib.rs (reserved by +/// PR #138). Run with `--ignored` to see it fail. +#[test] +#[ignore = "known leak in fork_sequence onto a live child id; fix belongs to the aien-kv-cache owner"] +fn fork_onto_live_child_leaks_blocks() { + let mut mgr = new_mgr(); + mgr.allocate_sequence(1, &[1, 2, 3, 4, 5]).unwrap(); + mgr.allocate_sequence(2, &[1, 2, 3]).unwrap(); + // fork_sequence either refuses or releases seq 2's old block + let _ = mgr.fork_sequence(1, 2); + mgr.free_sequence(1).unwrap(); + mgr.free_sequence(2).unwrap(); + assert_eq!(mgr.free_block_count(), TOTAL_BLOCKS, "blocks leaked"); +} diff --git a/crates/aien-replay/tests/trn1_conformance.rs b/crates/aien-replay/tests/trn1_conformance.rs new file mode 100644 index 00000000..22afcebb --- /dev/null +++ b/crates/aien-replay/tests/trn1_conformance.rs @@ -0,0 +1,79 @@ +//! TRN1 shared corpus through the Rust reader (spec section 9). +//! +//! TRN1_VECTORS points at aien-protocols `specs/execution-transcript/vectors` +//! (default: the sibling checkout `../aien-protocols` next to this repo). +//! With TRN1_REQUIRE=1 a missing corpus is a failure; otherwise the test +//! prints NOT_RUN and passes, so a plain local `cargo test` does not need the +//! sibling checkout. + +use aien_replay::{compare_line, verdict_line, verify, Verdict}; +use std::path::{Path, PathBuf}; + +fn vectors_dir() -> PathBuf { + std::env::var_os("TRN1_VECTORS") + .map(PathBuf::from) + .unwrap_or_else(|| { + Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../../aien-protocols/specs/execution-transcript/vectors") + }) +} + +fn load(dir: &Path, name: &str) -> Verdict { + let bytes = std::fs::read(dir.join(name)).unwrap_or_else(|e| panic!("read {name}: {e}")); + verify(&bytes) +} + +fn lines(dir: &Path, manifest: &str) -> Vec<String> { + std::fs::read_to_string(dir.join(manifest)) + .unwrap_or_else(|e| panic!("read {manifest}: {e}")) + .lines() + .filter(|l| !l.is_empty() && !l.starts_with('#')) + .map(str::to_owned) + .collect() +} + +#[test] +fn trn1_shared_corpus() { + let dir = vectors_dir(); + if !dir.join("expected.txt").exists() { + assert!( + std::env::var("TRN1_REQUIRE").as_deref() != Ok("1"), + "TRN1_REQUIRE=1 but no corpus at {}", + dir.display() + ); + println!( + "TRN1_CONFORMANCE impl=rust NOT_RUN (no corpus at {})", + dir.display() + ); + return; + } + + let (mut pass, mut fail) = (0u32, 0u32); + for line in lines(&dir, "expected.txt") { + let (file, want) = line.split_once(' ').expect("<file> <verdict>"); + let got = verdict_line(&load(&dir, file)); + if got == want { + pass += 1; + } else { + fail += 1; + println!("MISMATCH {file}\n expected: {want}\n got: {got}"); + } + } + for line in lines(&dir, "compare.txt") { + let mut parts = line.splitn(3, ' '); + let (e, a, want) = ( + parts.next().expect("expected file"), + parts.next().expect("actual file"), + parts.next().expect("compare line"), + ); + let got = compare_line(&load(&dir, e), &load(&dir, a)); + if got == want { + pass += 1; + } else { + fail += 1; + println!("MISMATCH {e} {a}\n expected: {want}\n got: {got}"); + } + } + println!("TRN1_CONFORMANCE impl=rust pass={pass} fail={fail}"); + assert!(pass > 0 && fail == 0, "pass={pass} fail={fail}"); +}