diff --git a/.github/workflows/benchmark.yaml b/.github/workflows/benchmark.yaml index 08783270..04126ace 100644 --- a/.github/workflows/benchmark.yaml +++ b/.github/workflows/benchmark.yaml @@ -20,7 +20,9 @@ jobs: steps: - uses: actions/checkout@v3 - name: Install Rust - run: rustup update stable + run: | + rustup toolchain install 1.99.0 --profile minimal + rustup default 1.99.0 - uses: ./.github/actions/setup-rust with: shared-key: benchmark-rust @@ -48,9 +50,9 @@ jobs: cache: yarn cache-dependency-path: 'bindings/nodejs/yarn.lock' - name: Install Rust - uses: dtolnay/rust-toolchain@stable + uses: dtolnay/rust-toolchain@1.99.0 with: - toolchain: stable + toolchain: 1.99.0 targets: x86_64-unknown-linux-gnu - uses: ./.github/actions/setup-rust with: @@ -75,7 +77,9 @@ jobs: with: python-version: '3.13' - name: Install Rust - run: rustup update stable + run: | + rustup toolchain install 1.99.0 --profile minimal + rustup default 1.99.0 - uses: ./.github/actions/setup-rust with: shared-key: benchmark-python diff --git a/.github/workflows/go.yaml b/.github/workflows/go.yaml index 4ce1e83f..c6ce5e38 100644 --- a/.github/workflows/go.yaml +++ b/.github/workflows/go.yaml @@ -45,7 +45,7 @@ jobs: - uses: actions-rs/toolchain@v1 with: - toolchain: stable + toolchain: 1.99.0 override: true target: ${{ matrix.settings.target }} - uses: ./.github/actions/setup-rust diff --git a/.github/workflows/node.yaml b/.github/workflows/node.yaml index c8a24492..026bbfe9 100644 --- a/.github/workflows/node.yaml +++ b/.github/workflows/node.yaml @@ -31,7 +31,6 @@ jobs: settings: - host: windows-latest target: 'x86_64-pc-windows-msvc' - toolchain: '1.99' build: | yarn build -- --target x86_64-pc-windows-msvc -- --locked @@ -123,9 +122,9 @@ jobs: cache-dependency-path: 'bindings/nodejs/yarn.lock' - name: Install - uses: dtolnay/rust-toolchain@stable + uses: dtolnay/rust-toolchain@1.99.0 with: - toolchain: ${{ matrix.settings.toolchain || 'stable' }} + toolchain: 1.99.0 targets: ${{ matrix.settings.target }} - name: Rust cache + sccache (+ zig for linux legs) @@ -162,6 +161,14 @@ jobs: path: bindings/nodejs/index.d.ts if-no-files-found: error + - name: Upload JS binding + if: ${{ matrix.settings.target == 'wasm32-wasip1' }} + uses: actions/upload-artifact@v4 + with: + name: js-binding + path: bindings/nodejs/index.js + if-no-files-found: error + - name: Upload artifact ${{ matrix.settings.target }} if: ${{ matrix.settings.target != 'wasm32-wasip1' }} uses: actions/upload-artifact@v4 @@ -255,6 +262,12 @@ jobs: name: typings path: bindings/nodejs + - name: Download JS binding + uses: actions/download-artifact@v4 + with: + name: js-binding + path: bindings/nodejs + - name: Test bindings (native) if: ${{ !matrix.settings.image }} run: | @@ -308,6 +321,12 @@ jobs: name: typings path: bindings/nodejs + - name: Download JS binding + uses: actions/download-artifact@v4 + with: + name: js-binding + path: bindings/nodejs + - name: Test bindings (wasm) run: yarn test:wasm @@ -352,6 +371,12 @@ jobs: name: typings path: bindings/nodejs + - name: Download JS binding + uses: actions/download-artifact@v4 + with: + name: js-binding + path: bindings/nodejs + - name: List all artifacts run: ls -la ../../artifacts @@ -369,6 +394,17 @@ jobs: run: ls ./ shell: bash + - name: Verify JS binding version + run: | + version=$(node -p "require('./package.json').version") + stale=$(grep -o "bindingPackageVersion !== '[^']*'" index.js | grep -v "'$version'" || true) + if [ -n "$stale" ] || ! grep -q "bindingPackageVersion !== '$version'" index.js; then + echo "index.js does not check for version $version:" + echo "$stale" | sort | uniq -c + exit 1 + fi + shell: bash + - name: Lerna publish run: yarn lerna publish from-package --dist-tag ${{ contains(github.ref, '-beta') && 'beta' || 'latest' }} --no-verify-access --yes env: diff --git a/.github/workflows/python.yaml b/.github/workflows/python.yaml index f448b413..e557013f 100644 --- a/.github/workflows/python.yaml +++ b/.github/workflows/python.yaml @@ -62,6 +62,7 @@ jobs: args: ${{ matrix.args }} manylinux: ${{ matrix.manylinux || 'auto' }} sccache: 'true' + rust-toolchain: 1.99.0 - name: Upload wheels uses: actions/upload-artifact@v4 diff --git a/.github/workflows/release-please.yaml b/.github/workflows/release-please.yaml index 952bc3ea..e2599388 100644 --- a/.github/workflows/release-please.yaml +++ b/.github/workflows/release-please.yaml @@ -71,7 +71,7 @@ jobs: ref: ${{ steps.release.outputs.pr-branch }} token: ${{ secrets.PAT }} - - uses: dtolnay/rust-toolchain@stable + - uses: dtolnay/rust-toolchain@1.99.0 if: steps.release.outputs.pr-branch - name: Update Cargo.lock on release PR diff --git a/.github/workflows/rust.yaml b/.github/workflows/rust.yaml index 177fefef..19a73340 100644 --- a/.github/workflows/rust.yaml +++ b/.github/workflows/rust.yaml @@ -48,7 +48,9 @@ jobs: steps: - uses: actions/checkout@v3 - name: Install Rust - run: rustup update stable + run: | + rustup toolchain install 1.99.0 --profile minimal + rustup default 1.99.0 - uses: ./.github/actions/setup-rust with: shared-key: rust-test-${{ matrix.os }}-${{ matrix.features.key }} @@ -65,7 +67,9 @@ jobs: steps: - uses: actions/checkout@v3 - name: Install Rust - run: rustup update stable + run: | + rustup toolchain install 1.99.0 --profile minimal --component rustfmt + rustup default 1.99.0 - run: cargo fmt --all -- --check release: @@ -80,7 +84,9 @@ jobs: - uses: actions/checkout@v3 - name: Install Rust - run: rustup update stable + run: | + rustup toolchain install 1.99.0 --profile minimal + rustup default 1.99.0 - name: Login to Crates.IO run: cargo login ${{ secrets.CRATES_TOKEN }} diff --git a/.github/workflows/uniffi.yaml b/.github/workflows/uniffi.yaml index 3fb12a14..1caa8a9f 100644 --- a/.github/workflows/uniffi.yaml +++ b/.github/workflows/uniffi.yaml @@ -20,6 +20,8 @@ jobs: id-token: write env: OUTPUT_NAME: zen_uniffi + CARGO_TARGET_X86_64_UNKNOWN_LINUX_MUSL_RUSTFLAGS: '-C target-feature=-crt-static' + CARGO_TARGET_AARCH64_UNKNOWN_LINUX_MUSL_RUSTFLAGS: '-C target-feature=-crt-static' strategy: fail-fast: true @@ -27,7 +29,6 @@ jobs: settings: - host: windows-latest target: 'x86_64-pc-windows-msvc' - toolchain: '1.99' output: '{0}.dll' lib_dir: 'win32-x86-64' - host: macos-latest @@ -46,6 +47,14 @@ jobs: target: 'aarch64-unknown-linux-gnu' output: 'lib{0}.so' lib_dir: 'linux-aarch64' + - host: ubuntu-latest + target: 'x86_64-unknown-linux-musl' + output: 'lib{0}.so' + lib_dir: 'linux-musl-x86-64' + - host: ubuntu-latest + target: 'aarch64-unknown-linux-musl' + output: 'lib{0}.so' + lib_dir: 'linux-musl-aarch64' - host: ubuntu-latest target: 's390x-unknown-linux-gnu' output: 'lib{0}.so' @@ -59,9 +68,8 @@ jobs: - uses: actions/checkout@v3 - name: Setup Rust Toolchain - uses: dtolnay/rust-toolchain@stable + uses: dtolnay/rust-toolchain@1.99.0 with: - toolchain: ${{ matrix.settings.toolchain || 'stable' }} target: ${{ matrix.settings.target }} - uses: ./.github/actions/setup-rust @@ -76,18 +84,24 @@ jobs: - name: Build (zig, linux) if: ${{ matrix.settings.host == 'ubuntu-latest' }} working-directory: ${{ env.UNIFFI_DIRECTORY }} - run: cargo zigbuild --lib --release --locked --target ${{ matrix.settings.target }}.${{ env.GLIBC_VERSION }} ${{ matrix.settings.extra_args }} + run: | + TARGET="${{ matrix.settings.target }}" + case "$TARGET" in + *-musl) ZIG_TARGET="$TARGET" ;; + *) ZIG_TARGET="$TARGET.$GLIBC_VERSION" ;; + esac + cargo zigbuild --lib --release --locked --target "$ZIG_TARGET" ${{ matrix.settings.extra_args }} - name: Build (native) if: ${{ matrix.settings.host != 'ubuntu-latest' }} uses: houseabsolute/actions-rust-cross@v1 with: working-directory: ${{ env.UNIFFI_DIRECTORY }} target: ${{ matrix.settings.target }} - toolchain: ${{ matrix.settings.toolchain || 'stable' }} + toolchain: 1.99.0 args: '--lib --release --locked ${{ matrix.settings.extra_args }}' - name: Verify max glibc requirement - if: ${{ matrix.settings.host == 'ubuntu-latest' }} + if: ${{ matrix.settings.host == 'ubuntu-latest' && !endsWith(matrix.settings.target, '-musl') }} run: | LIB="target/${{ matrix.settings.target }}/release/lib${{ env.OUTPUT_NAME }}.so" MAX=$(grep -aoE 'GLIBC_2\.[0-9]+(\.[0-9]+)?' "$LIB" | sort -uV | tail -1) @@ -98,6 +112,16 @@ jobs: exit 1 fi + - name: Verify musl library links libc dynamically + if: ${{ endsWith(matrix.settings.target, '-musl') }} + run: | + LIB="target/${{ matrix.settings.target }}/release/lib${{ env.OUTPUT_NAME }}.so" + readelf -d "$LIB" | grep NEEDED + if ! readelf -d "$LIB" | grep -q 'NEEDED.*libc\.so'; then + echo "::error::$LIB does not link libc dynamically" + exit 1 + fi + - name: Upload artifact uses: actions/upload-artifact@v4 with: @@ -133,7 +157,7 @@ jobs: dotnet-version: '8.0.x' - name: Setup Rust Toolchain - uses: dtolnay/rust-toolchain@stable + uses: dtolnay/rust-toolchain@1.99.0 - uses: ./.github/actions/setup-rust with: @@ -188,6 +212,68 @@ jobs: - name: Run C# tests run: dotnet test tests/csharp + test-musl: + name: Test musl (Java, Kotlin, C#) - ${{ matrix.settings.lib_dir }} + needs: [ build ] + runs-on: ${{ matrix.settings.host }} + permissions: + contents: read + id-token: write + strategy: + fail-fast: true + matrix: + settings: + - host: ubuntu-latest + lib_dir: 'linux-musl-x86-64' + - host: ubuntu-24.04-arm + lib_dir: 'linux-musl-aarch64' + defaults: + run: + working-directory: ${{ env.UNIFFI_DIRECTORY }} + + steps: + - uses: actions/checkout@v3 + + - name: Setup Rust Toolchain + uses: dtolnay/rust-toolchain@1.99.0 + + - uses: ./.github/actions/setup-rust + with: + shared-key: uniffi-test-musl-${{ matrix.settings.lib_dir }} + sccache-bucket: ${{ secrets.SCCACHE_S3_BUCKET }} + sccache-region: ${{ secrets.SCCACHE_AWS_REGION }} + sccache-role-arn: ${{ secrets.SCCACHE_AWS_ROLE_ARN }} + + - name: Download musl native library + uses: actions/download-artifact@v4 + with: + name: ${{ matrix.settings.lib_dir }} + path: ${{ env.UNIFFI_DIRECTORY }}/build/generated/resources/${{ matrix.settings.lib_dir }} + + - name: Install uniffi-bindgen-java + run: cargo install uniffi-bindgen-java --version 0.4.2 --locked + + - name: Install uniffi-bindgen-cs + run: cargo install uniffi-bindgen-cs --git https://github.com/gorules/uniffi-bindgen-cs --rev d080b41 + + - name: Build unstripped host library for binding generation + env: + CARGO_PROFILE_RELEASE_STRIP: 'none' + run: cargo build --lib --release --locked + + - name: Generate Java, Kotlin and C# sources + run: | + LIB=../../target/release/libzen_uniffi.so + uniffi-bindgen-java generate --out-dir build/generated/java "$LIB" + cargo run --locked --bin uniffi-bindgen -- generate --library "$LIB" --language kotlin --out-dir build/generated/kotlin + uniffi-bindgen-cs --library "$LIB" --config uniffi.toml --out-dir build/generated/csharp + + - name: Run Java and Kotlin tests (Alpine) + run: docker run --rm -v "$GITHUB_WORKSPACE:/work" -w /work/${{ env.UNIFFI_DIRECTORY }} eclipse-temurin:23-jdk-alpine ./gradlew testJava testKotlin --no-daemon + + - name: Run C# tests (Alpine) + run: docker run --rm -v "$GITHUB_WORKSPACE:/work" -w /work/${{ env.UNIFFI_DIRECTORY }} mcr.microsoft.com/dotnet/sdk:8.0-alpine dotnet test tests/csharp + test-swift: name: Test (Swift) runs-on: macos-latest @@ -202,7 +288,7 @@ jobs: - uses: actions/checkout@v3 - name: Setup Rust Toolchain - uses: dtolnay/rust-toolchain@stable + uses: dtolnay/rust-toolchain@1.99.0 - uses: ./.github/actions/setup-rust with: @@ -232,7 +318,7 @@ jobs: release-java-kotlin: runs-on: ubuntu-latest environment: release - needs: [ build, test-jvm-dotnet ] + needs: [ build, test-jvm-dotnet, test-musl ] if: "github.ref_type == 'tag'" defaults: run: @@ -247,7 +333,7 @@ jobs: distribution: 'temurin' - name: Setup Rust Toolchain - uses: dtolnay/rust-toolchain@stable + uses: dtolnay/rust-toolchain@1.99.0 - uses: ./.github/actions/setup-rust with: @@ -306,7 +392,7 @@ jobs: release-csharp: runs-on: ubuntu-latest environment: release - needs: [ build, test-jvm-dotnet ] + needs: [ build, test-jvm-dotnet, test-musl ] permissions: id-token: write # Required for OIDC if: "github.ref_type == 'tag'" @@ -323,7 +409,7 @@ jobs: dotnet-version: '8.0.x' - name: Setup Rust Toolchain - uses: dtolnay/rust-toolchain@stable + uses: dtolnay/rust-toolchain@1.99.0 - uses: ./.github/actions/setup-rust with: @@ -416,7 +502,7 @@ jobs: - uses: actions/checkout@v3 - name: Setup Rust Toolchain - uses: dtolnay/rust-toolchain@stable + uses: dtolnay/rust-toolchain@1.99.0 with: target: ${{ matrix.settings.target }} @@ -452,7 +538,7 @@ jobs: - uses: actions/checkout@v3 - name: Setup Rust Toolchain - uses: dtolnay/rust-toolchain@stable + uses: dtolnay/rust-toolchain@1.99.0 - uses: ./.github/actions/setup-rust with: @@ -632,7 +718,7 @@ jobs: - uses: actions/checkout@v3 - name: Setup Rust Toolchain - uses: dtolnay/rust-toolchain@stable + uses: dtolnay/rust-toolchain@1.99.0 - uses: ./.github/actions/setup-rust with: diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 72e9084b..4167cfd6 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,13 +1,13 @@ { - "core/engine": "2.1.6", - "core/expression": "2.1.6", - "core/types": "2.1.6", - "core/template": "2.1.6", - "core/macros": "2.1.6", - "bindings/nodejs": "2.1.9", - "bindings/python": "2.1.6", - "bindings/uniffi": "2.1.6", - "bindings/c": "2.1.6", - "benchmark/rust": "0.0.23", - "core/expression_repl": "2.0.8" + "core/engine": "2.1.8", + "core/expression": "2.1.8", + "core/types": "2.1.8", + "core/template": "2.1.8", + "core/macros": "2.1.8", + "bindings/nodejs": "2.1.12", + "bindings/python": "2.1.8", + "bindings/uniffi": "2.1.9", + "bindings/c": "2.1.8", + "benchmark/rust": "0.0.25", + "core/expression_repl": "2.0.10" } diff --git a/Cargo.lock b/Cargo.lock index bbc2df9f..630ff4a0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1212,7 +1212,7 @@ dependencies = [ [[package]] name = "expression_repl" -version = "2.0.8" +version = "2.0.10" dependencies = [ "colored", "rustyline", @@ -1496,10 +1496,12 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0de51e6874e94e7bf76d726fc5d13ba782deca734ff60d5bb2fb2607c7406555" dependencies = [ "cfg-if", + "js-sys", "libc", "r-efi 6.0.0", "wasip2", "wasip3", + "wasm-bindgen", ] [[package]] @@ -2502,6 +2504,18 @@ dependencies = [ "libc", ] +[[package]] +name = "nix" +version = "0.31.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d" +dependencies = [ + "bitflags 2.13.0", + "cfg-if", + "cfg_aliases", + "libc", +] + [[package]] name = "nohash-hasher" version = "0.2.0" @@ -3953,7 +3967,7 @@ dependencies = [ "libc", "log", "memchr", - "nix", + "nix 0.29.0", "radix_trie", "unicode-segmentation", "unicode-width", @@ -5218,9 +5232,9 @@ checksum = "6af6ae20167a9ece4bcb41af5b80f8a1f1df981f6391189ce00fd257af04126a" [[package]] name = "typed-path" -version = "0.12.3" +version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e28f89b80c87b8fb0cf04ab448d5dd0dd0ade2f8891bae878de66a75a28600e" +checksum = "9ce898823d8cd0f028662d2f349694b1af0a5cc9be83f1d213a00d3147445e1e" [[package]] name = "typenum" @@ -6043,7 +6057,7 @@ dependencies = [ [[package]] name = "zen-benchmark" -version = "0.0.23" +version = "0.0.25" dependencies = [ "mimalloc", "rust_decimal", @@ -6057,7 +6071,7 @@ dependencies = [ [[package]] name = "zen-engine" -version = "2.1.6" +version = "2.1.8" dependencies = [ "ahash 0.8.12", "anyhow", @@ -6109,7 +6123,7 @@ dependencies = [ [[package]] name = "zen-expression" -version = "2.1.6" +version = "2.1.8" dependencies = [ "ahash 0.8.12", "anyhow", @@ -6142,7 +6156,7 @@ dependencies = [ [[package]] name = "zen-ffi" -version = "2.1.6" +version = "2.1.8" dependencies = [ "anyhow", "cbindgen", @@ -6159,7 +6173,7 @@ dependencies = [ [[package]] name = "zen-macros" -version = "2.1.6" +version = "2.1.8" dependencies = [ "proc-macro2", "quote", @@ -6169,7 +6183,7 @@ dependencies = [ [[package]] name = "zen-nodejs" -version = "2.1.9" +version = "2.1.12" dependencies = [ "ahash 0.8.12", "iana-time-zone", @@ -6189,7 +6203,7 @@ dependencies = [ [[package]] name = "zen-python" -version = "2.1.6" +version = "2.1.8" dependencies = [ "anyhow", "either", @@ -6208,7 +6222,7 @@ dependencies = [ [[package]] name = "zen-tmpl" -version = "2.1.6" +version = "2.1.8" dependencies = [ "serde", "serde_json", @@ -6218,7 +6232,7 @@ dependencies = [ [[package]] name = "zen-types" -version = "2.1.6" +version = "2.1.8" dependencies = [ "ahash 0.8.12", "hipstr", @@ -6234,7 +6248,7 @@ dependencies = [ [[package]] name = "zen-uniffi" -version = "2.1.6" +version = "2.1.9" dependencies = [ "async-trait", "serde", @@ -6327,15 +6341,19 @@ dependencies = [ [[package]] name = "zip" -version = "8.6.0" +version = "9.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2d04a6b5381502aa6087c94c669499eb1602eb9c5e8198e534de571f7154809b" +checksum = "23f17fbc870bfac28c6228aed7d6e6df352e26bf7015c4313727e16a7a01ce5e" dependencies = [ "crc32fast", "flate2", + "getrandom 0.4.2", "indexmap", + "libc", "memchr", + "nix 0.31.3", "typed-path", + "windows-sys 0.61.2", ] [[package]] diff --git a/benchmark/rust/Cargo.toml b/benchmark/rust/Cargo.toml index 6ca6fb90..41ec150c 100644 --- a/benchmark/rust/Cargo.toml +++ b/benchmark/rust/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "zen-benchmark" -version = "0.0.23" +version = "0.0.25" edition = "2021" publish = false diff --git a/bindings/c/CHANGELOG.md b/bindings/c/CHANGELOG.md index d9ab2eeb..749ebacd 100644 --- a/bindings/c/CHANGELOG.md +++ b/bindings/c/CHANGELOG.md @@ -1,5 +1,9 @@ # Changelog +## [2.1.8](https://github.com/gorules/zen/compare/go-v2.1.7...go-v2.1.8) (2026-11-19) + +## [2.1.7](https://github.com/gorules/zen/compare/go-v2.1.6...go-v2.1.7) (2026-11-09) + ## [2.1.6](https://github.com/gorules/zen/compare/go-v2.1.5...go-v2.1.6) (2026-10-21) ## [2.1.5](https://github.com/gorules/zen/compare/go-v2.1.4...go-v2.1.5) (2026-10-20) diff --git a/bindings/c/Cargo.toml b/bindings/c/Cargo.toml index 9c5c4b36..ccd830db 100644 --- a/bindings/c/Cargo.toml +++ b/bindings/c/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "zen-ffi" -version = "2.1.6" +version = "2.1.8" edition = "2021" license = "MIT" publish = false diff --git a/bindings/nodejs/.gitignore b/bindings/nodejs/.gitignore index 74e32af8..8ea09e7f 100644 --- a/bindings/nodejs/.gitignore +++ b/bindings/nodejs/.gitignore @@ -2,6 +2,7 @@ *.internal.js *.tgz index.d.ts +/index.js *.wasm npm/ zen-engine.wasip1* diff --git a/bindings/nodejs/CHANGELOG.md b/bindings/nodejs/CHANGELOG.md index da1bd306..7c6c9f00 100644 --- a/bindings/nodejs/CHANGELOG.md +++ b/bindings/nodejs/CHANGELOG.md @@ -1,5 +1,21 @@ # Changelog +## [2.1.12](https://github.com/gorules/zen/compare/nodejs-v2.1.11...nodejs-v2.1.12) (2026-11-19) + + +### Bug Fixes + +* table analysis memory ([#570](https://github.com/gorules/zen/issues/570)) ([1944ebe](https://github.com/gorules/zen/commit/1944ebe01feb2b11b5197c7b16f4ae1e9d26ccf3)) + +## [2.1.11](https://github.com/gorules/zen/compare/nodejs-v2.1.10...nodejs-v2.1.11) (2026-11-11) + + +### Bug Fixes + +* **nodejs:** stop committing the generated index.js loader ([#567](https://github.com/gorules/zen/issues/567)) ([d07a610](https://github.com/gorules/zen/commit/d07a610eb3359160bad5152c649d882ef7213891)) + +## [2.1.10](https://github.com/gorules/zen/compare/nodejs-v2.1.9...nodejs-v2.1.10) (2026-11-09) + ## [2.1.9](https://github.com/gorules/zen/compare/nodejs-v2.1.8...nodejs-v2.1.9) (2026-10-21) ## [2.1.8](https://github.com/gorules/zen/compare/nodejs-v2.1.7...nodejs-v2.1.8) (2026-10-20) diff --git a/bindings/nodejs/Cargo.toml b/bindings/nodejs/Cargo.toml index 2be0e581..2763c909 100644 --- a/bindings/nodejs/Cargo.toml +++ b/bindings/nodejs/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "zen-nodejs" -version = "2.1.9" +version = "2.1.12" edition = "2021" license = "MIT" publish = false diff --git a/bindings/nodejs/index.js b/bindings/nodejs/index.js deleted file mode 100644 index 2b0fa7b4..00000000 --- a/bindings/nodejs/index.js +++ /dev/null @@ -1,805 +0,0 @@ -/* eslint-disable */ -// @ts-nocheck -/* auto-generated by NAPI-RS */ - -const { readFileSync } = require('fs') -let nativeBinding = null -// Which artifact actually loaded. The WASI fallback chain overwrites it with -// the flavor it resolved; the late native retry below leaves it alone because -// it only runs while no WASI candidate has been loaded. -let __napiLoadedBindingTarget = 'native' -const loadErrors = [] - -const isMusl = () => { - let musl = false - if (process.platform === 'linux') { - musl = isMuslFromFilesystem() - if (musl === null) { - musl = isMuslFromReport() - } - if (musl === null) { - musl = isMuslFromChildProcess() - } - } - return musl -} - -const isFileMusl = (f) => f.includes('libc.musl-') || f.includes('ld-musl-') - -const isMuslFromFilesystem = () => { - try { - return readFileSync('/usr/bin/ldd', 'utf-8').includes('musl') - } catch { - return null - } -} - -const isMuslFromReport = () => { - let report = null - if (process.report && typeof process.report.getReport === 'function') { - process.report.excludeNetwork = true - report = process.report.getReport() - } - if (!report) { - return null - } - if (report.header && report.header.glibcVersionRuntime) { - return false - } - if (Array.isArray(report.sharedObjects)) { - if (report.sharedObjects.some(isFileMusl)) { - return true - } - } - return false -} - -const isMuslFromChildProcess = () => { - try { - return require('child_process').execSync('ldd --version', { encoding: 'utf8' }).includes('musl') - } catch (e) { - // If we reach this case, we don't know if the system is musl or not, so is better to just fallback to false - return false - } -} - -function requireNative() { - if (process.env.NAPI_RS_NATIVE_LIBRARY_PATH) { - try { - const overrideBinding = require(process.env.NAPI_RS_NATIVE_LIBRARY_PATH) - // The override may be a generated WASI loader, which already reports its - // own flavor. Adopt it: `module.exports` aliases this object, so claiming - // 'native' would both misreport the artifact and overwrite the loader's - // marker through the alias. - __napiLoadedBindingTarget = - overrideBinding && typeof overrideBinding.__napiBindingTarget === 'string' - ? overrideBinding.__napiBindingTarget - : 'native' - return overrideBinding - } catch (err) { - loadErrors.push(err) - } - } else if (process.platform === 'android') { - if (process.arch === 'arm64') { - try { - return require('./zen-engine.android-arm64.node') - } catch (e) { - loadErrors.push(e) - } - try { - const binding = require('@gorules/zen-engine-android-arm64') - const bindingPackageVersion = require('@gorules/zen-engine-android-arm64/package.json').version - if (bindingPackageVersion !== '2.1.4' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 2.1.4 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) - } - return binding - } catch (e) { - loadErrors.push(e) - } - } else if (process.arch === 'arm') { - try { - return require('./zen-engine.android-arm-eabi.node') - } catch (e) { - loadErrors.push(e) - } - try { - const binding = require('@gorules/zen-engine-android-arm-eabi') - const bindingPackageVersion = require('@gorules/zen-engine-android-arm-eabi/package.json').version - if (bindingPackageVersion !== '2.1.4' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 2.1.4 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) - } - return binding - } catch (e) { - loadErrors.push(e) - } - } else { - loadErrors.push(new Error(`Unsupported architecture on Android ${process.arch}`)) - } - } else if (process.platform === 'win32') { - if (process.arch === 'x64') { - if ((process.config && process.config.variables && process.config.variables.shlib_suffix === 'dll.a') || (process.config && process.config.variables && process.config.variables.node_target_type === 'shared_library')) { - try { - return require('./zen-engine.win32-x64-gnu.node') - } catch (e) { - loadErrors.push(e) - } - try { - const binding = require('@gorules/zen-engine-win32-x64-gnu') - const bindingPackageVersion = require('@gorules/zen-engine-win32-x64-gnu/package.json').version - if (bindingPackageVersion !== '2.1.4' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 2.1.4 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) - } - return binding - } catch (e) { - loadErrors.push(e) - } - } else { - try { - return require('./zen-engine.win32-x64-msvc.node') - } catch (e) { - loadErrors.push(e) - } - try { - const binding = require('@gorules/zen-engine-win32-x64-msvc') - const bindingPackageVersion = require('@gorules/zen-engine-win32-x64-msvc/package.json').version - if (bindingPackageVersion !== '2.1.4' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 2.1.4 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) - } - return binding - } catch (e) { - loadErrors.push(e) - } - } - } else if (process.arch === 'ia32') { - try { - return require('./zen-engine.win32-ia32-msvc.node') - } catch (e) { - loadErrors.push(e) - } - try { - const binding = require('@gorules/zen-engine-win32-ia32-msvc') - const bindingPackageVersion = require('@gorules/zen-engine-win32-ia32-msvc/package.json').version - if (bindingPackageVersion !== '2.1.4' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 2.1.4 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) - } - return binding - } catch (e) { - loadErrors.push(e) - } - } else if (process.arch === 'arm64') { - try { - return require('./zen-engine.win32-arm64-msvc.node') - } catch (e) { - loadErrors.push(e) - } - try { - const binding = require('@gorules/zen-engine-win32-arm64-msvc') - const bindingPackageVersion = require('@gorules/zen-engine-win32-arm64-msvc/package.json').version - if (bindingPackageVersion !== '2.1.4' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 2.1.4 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) - } - return binding - } catch (e) { - loadErrors.push(e) - } - } else { - loadErrors.push(new Error(`Unsupported architecture on Windows: ${process.arch}`)) - } - } else if (process.platform === 'darwin') { - try { - return require('./zen-engine.darwin-universal.node') - } catch (e) { - loadErrors.push(e) - } - try { - const binding = require('@gorules/zen-engine-darwin-universal') - const bindingPackageVersion = require('@gorules/zen-engine-darwin-universal/package.json').version - if (bindingPackageVersion !== '2.1.4' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 2.1.4 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) - } - return binding - } catch (e) { - loadErrors.push(e) - } - if (process.arch === 'x64') { - try { - return require('./zen-engine.darwin-x64.node') - } catch (e) { - loadErrors.push(e) - } - try { - const binding = require('@gorules/zen-engine-darwin-x64') - const bindingPackageVersion = require('@gorules/zen-engine-darwin-x64/package.json').version - if (bindingPackageVersion !== '2.1.4' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 2.1.4 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) - } - return binding - } catch (e) { - loadErrors.push(e) - } - } else if (process.arch === 'arm64') { - try { - return require('./zen-engine.darwin-arm64.node') - } catch (e) { - loadErrors.push(e) - } - try { - const binding = require('@gorules/zen-engine-darwin-arm64') - const bindingPackageVersion = require('@gorules/zen-engine-darwin-arm64/package.json').version - if (bindingPackageVersion !== '2.1.4' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 2.1.4 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) - } - return binding - } catch (e) { - loadErrors.push(e) - } - } else { - loadErrors.push(new Error(`Unsupported architecture on macOS: ${process.arch}`)) - } - } else if (process.platform === 'freebsd') { - if (process.arch === 'x64') { - try { - return require('./zen-engine.freebsd-x64.node') - } catch (e) { - loadErrors.push(e) - } - try { - const binding = require('@gorules/zen-engine-freebsd-x64') - const bindingPackageVersion = require('@gorules/zen-engine-freebsd-x64/package.json').version - if (bindingPackageVersion !== '2.1.4' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 2.1.4 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) - } - return binding - } catch (e) { - loadErrors.push(e) - } - } else if (process.arch === 'arm64') { - try { - return require('./zen-engine.freebsd-arm64.node') - } catch (e) { - loadErrors.push(e) - } - try { - const binding = require('@gorules/zen-engine-freebsd-arm64') - const bindingPackageVersion = require('@gorules/zen-engine-freebsd-arm64/package.json').version - if (bindingPackageVersion !== '2.1.4' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 2.1.4 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) - } - return binding - } catch (e) { - loadErrors.push(e) - } - } else { - loadErrors.push(new Error(`Unsupported architecture on FreeBSD: ${process.arch}`)) - } - } else if (process.platform === 'linux') { - if (process.arch === 'x64') { - if (isMusl()) { - try { - return require('./zen-engine.linux-x64-musl.node') - } catch (e) { - loadErrors.push(e) - } - try { - const binding = require('@gorules/zen-engine-linux-x64-musl') - const bindingPackageVersion = require('@gorules/zen-engine-linux-x64-musl/package.json').version - if (bindingPackageVersion !== '2.1.4' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 2.1.4 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) - } - return binding - } catch (e) { - loadErrors.push(e) - } - } else { - try { - return require('./zen-engine.linux-x64-gnu.node') - } catch (e) { - loadErrors.push(e) - } - try { - const binding = require('@gorules/zen-engine-linux-x64-gnu') - const bindingPackageVersion = require('@gorules/zen-engine-linux-x64-gnu/package.json').version - if (bindingPackageVersion !== '2.1.4' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 2.1.4 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) - } - return binding - } catch (e) { - loadErrors.push(e) - } - } - } else if (process.arch === 'arm64') { - if (isMusl()) { - try { - return require('./zen-engine.linux-arm64-musl.node') - } catch (e) { - loadErrors.push(e) - } - try { - const binding = require('@gorules/zen-engine-linux-arm64-musl') - const bindingPackageVersion = require('@gorules/zen-engine-linux-arm64-musl/package.json').version - if (bindingPackageVersion !== '2.1.4' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 2.1.4 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) - } - return binding - } catch (e) { - loadErrors.push(e) - } - } else { - try { - return require('./zen-engine.linux-arm64-gnu.node') - } catch (e) { - loadErrors.push(e) - } - try { - const binding = require('@gorules/zen-engine-linux-arm64-gnu') - const bindingPackageVersion = require('@gorules/zen-engine-linux-arm64-gnu/package.json').version - if (bindingPackageVersion !== '2.1.4' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 2.1.4 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) - } - return binding - } catch (e) { - loadErrors.push(e) - } - } - } else if (process.arch === 'arm') { - if (isMusl()) { - try { - return require('./zen-engine.linux-arm-musleabihf.node') - } catch (e) { - loadErrors.push(e) - } - try { - const binding = require('@gorules/zen-engine-linux-arm-musleabihf') - const bindingPackageVersion = require('@gorules/zen-engine-linux-arm-musleabihf/package.json').version - if (bindingPackageVersion !== '2.1.4' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 2.1.4 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) - } - return binding - } catch (e) { - loadErrors.push(e) - } - } else { - try { - return require('./zen-engine.linux-arm-gnueabihf.node') - } catch (e) { - loadErrors.push(e) - } - try { - const binding = require('@gorules/zen-engine-linux-arm-gnueabihf') - const bindingPackageVersion = require('@gorules/zen-engine-linux-arm-gnueabihf/package.json').version - if (bindingPackageVersion !== '2.1.4' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 2.1.4 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) - } - return binding - } catch (e) { - loadErrors.push(e) - } - } - } else if (process.arch === 'loong64') { - if (isMusl()) { - try { - return require('./zen-engine.linux-loong64-musl.node') - } catch (e) { - loadErrors.push(e) - } - try { - const binding = require('@gorules/zen-engine-linux-loong64-musl') - const bindingPackageVersion = require('@gorules/zen-engine-linux-loong64-musl/package.json').version - if (bindingPackageVersion !== '2.1.4' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 2.1.4 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) - } - return binding - } catch (e) { - loadErrors.push(e) - } - } else { - try { - return require('./zen-engine.linux-loong64-gnu.node') - } catch (e) { - loadErrors.push(e) - } - try { - const binding = require('@gorules/zen-engine-linux-loong64-gnu') - const bindingPackageVersion = require('@gorules/zen-engine-linux-loong64-gnu/package.json').version - if (bindingPackageVersion !== '2.1.4' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 2.1.4 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) - } - return binding - } catch (e) { - loadErrors.push(e) - } - } - } else if (process.arch === 'riscv64') { - if (isMusl()) { - try { - return require('./zen-engine.linux-riscv64-musl.node') - } catch (e) { - loadErrors.push(e) - } - try { - const binding = require('@gorules/zen-engine-linux-riscv64-musl') - const bindingPackageVersion = require('@gorules/zen-engine-linux-riscv64-musl/package.json').version - if (bindingPackageVersion !== '2.1.4' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 2.1.4 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) - } - return binding - } catch (e) { - loadErrors.push(e) - } - } else { - try { - return require('./zen-engine.linux-riscv64-gnu.node') - } catch (e) { - loadErrors.push(e) - } - try { - const binding = require('@gorules/zen-engine-linux-riscv64-gnu') - const bindingPackageVersion = require('@gorules/zen-engine-linux-riscv64-gnu/package.json').version - if (bindingPackageVersion !== '2.1.4' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 2.1.4 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) - } - return binding - } catch (e) { - loadErrors.push(e) - } - } - } else if (process.arch === 'ppc64') { - try { - return require('./zen-engine.linux-ppc64-gnu.node') - } catch (e) { - loadErrors.push(e) - } - try { - const binding = require('@gorules/zen-engine-linux-ppc64-gnu') - const bindingPackageVersion = require('@gorules/zen-engine-linux-ppc64-gnu/package.json').version - if (bindingPackageVersion !== '2.1.4' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 2.1.4 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) - } - return binding - } catch (e) { - loadErrors.push(e) - } - } else if (process.arch === 's390x') { - try { - return require('./zen-engine.linux-s390x-gnu.node') - } catch (e) { - loadErrors.push(e) - } - try { - const binding = require('@gorules/zen-engine-linux-s390x-gnu') - const bindingPackageVersion = require('@gorules/zen-engine-linux-s390x-gnu/package.json').version - if (bindingPackageVersion !== '2.1.4' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 2.1.4 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) - } - return binding - } catch (e) { - loadErrors.push(e) - } - } else { - loadErrors.push(new Error(`Unsupported architecture on Linux: ${process.arch}`)) - } - } else if (process.platform === 'openharmony') { - if (process.arch === 'arm64') { - try { - return require('./zen-engine.openharmony-arm64.node') - } catch (e) { - loadErrors.push(e) - } - try { - const binding = require('@gorules/zen-engine-openharmony-arm64') - const bindingPackageVersion = require('@gorules/zen-engine-openharmony-arm64/package.json').version - if (bindingPackageVersion !== '2.1.4' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 2.1.4 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) - } - return binding - } catch (e) { - loadErrors.push(e) - } - } else if (process.arch === 'x64') { - try { - return require('./zen-engine.openharmony-x64.node') - } catch (e) { - loadErrors.push(e) - } - try { - const binding = require('@gorules/zen-engine-openharmony-x64') - const bindingPackageVersion = require('@gorules/zen-engine-openharmony-x64/package.json').version - if (bindingPackageVersion !== '2.1.4' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 2.1.4 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) - } - return binding - } catch (e) { - loadErrors.push(e) - } - } else if (process.arch === 'arm') { - try { - return require('./zen-engine.openharmony-arm.node') - } catch (e) { - loadErrors.push(e) - } - try { - const binding = require('@gorules/zen-engine-openharmony-arm') - const bindingPackageVersion = require('@gorules/zen-engine-openharmony-arm/package.json').version - if (bindingPackageVersion !== '2.1.4' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 2.1.4 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) - } - return binding - } catch (e) { - loadErrors.push(e) - } - } else { - loadErrors.push(new Error(`Unsupported architecture on OpenHarmony: ${process.arch}`)) - } - } else { - loadErrors.push(new Error(`Unsupported OS: ${process.platform}, architecture: ${process.arch}`)) - } -} - -function createLoadErrorChain(errors) { - return errors.reduce((previous, current) => { - let message - try { - message = - current && typeof current.message === 'string' - ? current.message - : String(current) - } catch { - message = 'Unknown error' - } - const error = new Error(message) - error.cause = previous - return error - }, null) -} - -// NAPI_RS_FORCE_WASI is a tri-state flag: -// unset / any other value → native binding preferred, WASI is only a fallback -// 'true' → prefer WASI, but retain native as a lazy fallback -// 'error' → require WASI without initializing a native fallback -// Treating any non-empty string as truthy (the historical behavior) meant -// NAPI_RS_FORCE_WASI=false, NAPI_RS_FORCE_WASI=0, etc. inadvertently triggered -// the WASI path, causing ENOENT for packages shipped without a .wasi.cjs file. -// -// NAPI_RS_WASI_FLAVOR selects one exact generated flavor and implies strict -// WASI loading. It never crosses into another flavor or falls back to native. -const __napiWasiFlavors = ['wasm32-wasip1'] -const __napiWasiFlavor = process.env.NAPI_RS_WASI_FLAVOR -const __napiWasiFlavorRequested = - typeof __napiWasiFlavor === 'string' && __napiWasiFlavor.length > 0 -if ( - __napiWasiFlavorRequested && - __napiWasiFlavors.indexOf(__napiWasiFlavor) === -1 -) { - throw new Error( - 'Unsupported WASI flavor "' + - __napiWasiFlavor + - '". Available flavors: ' + - __napiWasiFlavors.join(', '), - ) -} -const forceWasiError = process.env.NAPI_RS_FORCE_WASI === 'error' -const forceWasi = - process.env.NAPI_RS_FORCE_WASI === 'true' || - forceWasiError || - __napiWasiFlavorRequested - -if (!forceWasi) { - nativeBinding = requireNative() -} - -if (!nativeBinding || forceWasi) { - let wasiBinding = null - let wasiBindingLoaded = false - const wasiBindingErrors = [] - const __napiWasiResolveCandidate = (specifier, isPackage, localArtifacts) => { - try { - require.resolve(specifier) - } catch (resolveError) { - if (!resolveError || resolveError.code !== 'MODULE_NOT_FOUND') { - throw resolveError - } - if (isPackage) { - try { - require.resolve(specifier + '/package.json') - } catch (packageError) { - if (packageError && packageError.code === 'MODULE_NOT_FOUND') { - return resolveError - } - // An exports restriction proves the package exists even when its - // package.json is not public. Preserve the root resolution failure. - throw resolveError - } - // The package exists but its main/export target is broken. - throw resolveError - } - return resolveError - } - if (localArtifacts) { - let artifactError = null - for (let i = 0; i < localArtifacts.length; i++) { - try { - require.resolve(localArtifacts[i]) - return null - } catch (resolveError) { - if (!resolveError || resolveError.code !== 'MODULE_NOT_FOUND') { - throw resolveError - } - artifactError = resolveError - } - } - return artifactError - } - return null - } - if (!wasiBindingLoaded && (!__napiWasiFlavorRequested || __napiWasiFlavor === 'wasm32-wasip1')) { - let candidateError = null - let candidateFailed = false - try { - candidateError = __napiWasiResolveCandidate('./zen-engine.wasip1.cjs', false, ['./zen-engine.wasm32-wasip1.debug.wasm', './zen-engine.wasm32-wasip1.wasm']) - candidateFailed = candidateError !== null - if (!candidateFailed) { - wasiBinding = require('./zen-engine.wasip1.cjs') - nativeBinding = wasiBinding - __napiLoadedBindingTarget = 'wasm32-wasip1' - wasiBindingLoaded = true - } - } catch (err) { - candidateError = err - candidateFailed = true - } - if (candidateFailed) { - wasiBindingErrors.push(candidateError) - loadErrors.push(candidateError) - } - } - if (!wasiBindingLoaded && (!__napiWasiFlavorRequested || __napiWasiFlavor === 'wasm32-wasip1')) { - let candidateError = null - let candidateFailed = false - try { - candidateError = __napiWasiResolveCandidate('@gorules/zen-engine-wasm32-wasip1', true, undefined) - candidateFailed = candidateError !== null - if (!candidateFailed) { - if (process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - const bindingPackageVersion = require('@gorules/zen-engine-wasm32-wasip1/package.json').version - if (bindingPackageVersion !== '2.1.4') { - throw new Error(`WASI binding package version mismatch, expected 2.1.4 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) - } - } - wasiBinding = require('@gorules/zen-engine-wasm32-wasip1') - nativeBinding = wasiBinding - __napiLoadedBindingTarget = 'wasm32-wasip1' - wasiBindingLoaded = true - } - } catch (err) { - candidateError = err - candidateFailed = true - } - if (candidateFailed) { - wasiBindingErrors.push(candidateError) - loadErrors.push(candidateError) - } - } - if ( - !wasiBindingLoaded && - forceWasi && - !forceWasiError && - !__napiWasiFlavorRequested - ) { - nativeBinding = requireNative() - } - if ((forceWasiError || __napiWasiFlavorRequested) && !wasiBindingLoaded) { - const error = new Error( - __napiWasiFlavorRequested - ? 'WASI binding for flavor "' + __napiWasiFlavor + '" not found' - : 'WASI binding not found and NAPI_RS_FORCE_WASI is set to error', - ) - error.cause = createLoadErrorChain(wasiBindingErrors) - throw error - } -} - -if (!nativeBinding) { - if (loadErrors.length > 0) { - const error = new Error( - `Cannot find native binding. ` + - `npm has a bug related to optional dependencies (https://github.com/npm/cli/issues/4828). ` + - 'Please try `npm i` again after removing both package-lock.json and node_modules directory.', - ) - // assign instead of the `new Error(message, { cause })` options form, - // which Node < 16.9 silently ignores - error.cause = createLoadErrorChain(loadErrors) - throw error - } - throw new Error(`Failed to load native binding`) -} - -function __napiStampBindingTarget(exportsObject, target) { - if ( - Object.prototype.hasOwnProperty.call(exportsObject, '__napiBindingTarget') - ) { - if (exportsObject.__napiBindingTarget === target) { - // Already ours: the root entry aliases the object it loaded, so a WASI - // fallback candidate — or a `NAPI_RS_NATIVE_LIBRARY_PATH` override that - // is a generated loader — arrives already stamped with this same value. - return target - } - const error = new Error( - '`__napiBindingTarget` is reserved by the generated binding loader, but the loaded binding already exports it. Rename the export, e.g. #[napi(js_name = "...")].', - ) - error.code = 'ERR_NAPI_BINDING_TARGET_CONFLICT' - throw error - } - if (!Object.isExtensible(exportsObject)) { - // A `#[napi(module_exports)]` hook may seal or freeze this object - // (`Object::seal` / `Object::freeze`). Reporting the artifact is metadata, - // never a reason to fail an otherwise successful load, so the stamp is - // skipped. What a consumer still sees then follows the entry point: the - // browser and deferred loaders declare `__napiBindingTarget` at module - // level and go on reporting it, while the CommonJS entries hand back this - // very object as `module.exports`, so there the value is absent. - return target - } - try { - // [[Define]], not [[Set]]: an ordinary assignment walks the prototype - // chain, so an inherited accessor could swallow the value or throw and - // fail an otherwise successful load. The descriptor is what a successful - // assignment would have produced. - Object.defineProperty(exportsObject, '__napiBindingTarget', { - configurable: true, - enumerable: true, - value: target, - writable: true, - }) - } catch { - // Same rule as the non-extensible skip above: reporting the artifact is - // metadata, never a reason to fail an otherwise successful load. An exotic - // object (a Proxy whose defineProperty trap refuses) is skipped, not - // thrown over. - } - // The CommonJS loaders assign this return value so `cjs-module-lexer` — and - // therefore Node's CJS -> ESM named export detection — can see - // `__napiBindingTarget` statically. - return target -} -// Stamp before the alias, not after. The guard only reads `nativeBinding` -// (`hasOwnProperty` plus a comparison), which is safe against any addon -// accessor; an assignment is not, because a `#[napi(module_exports)]` hook can -// expose a getter reporting this very value and a setter that throws. So the -// assignment lands on the loader's own `module.exports`, still the original -// object here, and the alias below replaces it. -// -// The assignment is what keeps the marker a statically visible CommonJS export: -// `cjs-module-lexer` is Node's CJS -> ESM named export detection, it cannot see -// a bare call, and the later `module.exports = nativeBinding` does not undo the -// detection. The assignment itself always succeeds — its target is this -// loader's own, still extensible `module.exports` — and the alias below then -// discards the value it wrote. What a consumer reads is whatever the guard put -// on `nativeBinding`, so on a frozen binding, where the guard skips, the -// linked import resolves to `undefined`. -module.exports.__napiBindingTarget = __napiStampBindingTarget(nativeBinding, __napiLoadedBindingTarget) -module.exports = nativeBinding -module.exports.BindingRuntimeFlavor = nativeBinding.BindingRuntimeFlavor -module.exports.configureAsyncRuntime = nativeBinding.configureAsyncRuntime -module.exports.getAsyncRuntimeConfig = nativeBinding.getAsyncRuntimeConfig -module.exports.getAsyncRuntimeMetrics = nativeBinding.getAsyncRuntimeMetrics -module.exports.getCurrentThreadTaskHostContractVersion = nativeBinding.getCurrentThreadTaskHostContractVersion -module.exports.isCurrentThreadHostRegistrationActive = nativeBinding.isCurrentThreadHostRegistrationActive -module.exports.registerCurrentThreadTaskHost = nativeBinding.registerCurrentThreadTaskHost -module.exports.registerTimerHost = nativeBinding.registerTimerHost -module.exports.reserveCurrentThreadHostRegistration = nativeBinding.reserveCurrentThreadHostRegistration -module.exports.resetAsyncRuntimeMetrics = nativeBinding.resetAsyncRuntimeMetrics -module.exports.unregisterCurrentThreadTaskHost = nativeBinding.unregisterCurrentThreadTaskHost -module.exports.unregisterTimerHost = nativeBinding.unregisterTimerHost -module.exports.Workspace = nativeBinding.Workspace -module.exports.ZenDecision = nativeBinding.ZenDecision -module.exports.ZenDecisionContent = nativeBinding.ZenDecisionContent -module.exports.ZenEngine = nativeBinding.ZenEngine -module.exports.ZenEngineHandlerRequest = nativeBinding.ZenEngineHandlerRequest -module.exports.evaluateExpression = nativeBinding.evaluateExpression -module.exports.evaluateExpressionSync = nativeBinding.evaluateExpressionSync -module.exports.evaluateUnaryExpression = nativeBinding.evaluateUnaryExpression -module.exports.evaluateUnaryExpressionSync = nativeBinding.evaluateUnaryExpressionSync -module.exports.overrideConfig = nativeBinding.overrideConfig -module.exports.renderTemplate = nativeBinding.renderTemplate -module.exports.renderTemplateSync = nativeBinding.renderTemplateSync -module.exports.slotBatch = nativeBinding.slotBatch diff --git a/bindings/nodejs/package.json b/bindings/nodejs/package.json index f707e97c..a45a7b5e 100644 --- a/bindings/nodejs/package.json +++ b/bindings/nodejs/package.json @@ -1,7 +1,7 @@ { "name": "@gorules/zen-engine", "description": "Open-source Business Rules Engine for Node.js, powered by Rust", - "version": "2.1.9", + "version": "2.1.12", "main": "index.js", "browser": "browser.js", "types": "./index.d.ts", diff --git a/bindings/nodejs/src/policy.rs b/bindings/nodejs/src/policy.rs index 0a9429c1..3d3a1b4a 100644 --- a/bindings/nodejs/src/policy.rs +++ b/bindings/nodejs/src/policy.rs @@ -2,9 +2,10 @@ use std::collections::HashMap; use std::sync::Arc; use napi::anyhow::anyhow; -use napi::bindgen_prelude::{FnArgs, FunctionRef}; +use napi::bindgen_prelude::{Either3, FnArgs, FunctionRef, Object, Uint8Array}; use napi::Env; use napi_derive::napi; +use serde::de::DeserializeOwned; use serde_json::Value; use zen_engine::policy::PolicyDocument; @@ -12,6 +13,19 @@ use zen_engine::workspace; type ResolverRef = FunctionRef, Option>; +type JsonInput<'env> = Either3>; + +fn parse_json_input(env: &Env, input: JsonInput) -> Result { + match input { + Either3::A(bytes) => serde_json::from_slice(bytes.as_ref()).map_err(|e| e.to_string()), + Either3::B(text) => serde_json::from_str(&text).map_err(|e| e.to_string()), + Either3::C(object) => { + let value: Value = env.from_js_value(object).map_err(|e| e.to_string())?; + serde_json::from_value(value).map_err(|e| e.to_string()) + } + } +} + #[napi(object)] pub struct PolicyChanges { pub cursor: i64, @@ -594,16 +608,26 @@ impl Workspace { } #[napi] - pub fn set_document(&mut self, path: String, document: Value) -> napi::Result<()> { + pub fn set_document( + &mut self, + env: Env, + path: String, + #[napi(ts_arg_type = "Uint8Array | string | object")] document: JsonInput, + ) -> napi::Result<()> { let doc: zen_engine::model::DecisionContent = - serde_json::from_value(document).map_err(|e| anyhow!("Invalid document: {e}"))?; + parse_json_input(&env, document).map_err(|e| anyhow!("Invalid document: {e}"))?; self.inner.set_document(path, doc); Ok(()) } #[napi] - pub fn set_policy(&mut self, path: String, document: Value) -> napi::Result<()> { - let doc: PolicyDocument = serde_json::from_value(document) + pub fn set_policy( + &mut self, + env: Env, + path: String, + #[napi(ts_arg_type = "Uint8Array | string | object")] document: JsonInput, + ) -> napi::Result<()> { + let doc: PolicyDocument = parse_json_input(&env, document) .map_err(|e| anyhow!("Invalid policy document: {e}"))?; self.inner.set_policy(path, doc); Ok(()) @@ -985,9 +1009,14 @@ impl Workspace { } #[napi(ts_return_type = "PolicyTrace")] - pub fn enhance_graph_trace(&self, path: String, trace: Value) -> napi::Result { + pub fn enhance_graph_trace( + &self, + env: Env, + path: String, + #[napi(ts_arg_type = "Uint8Array | string | object")] trace: JsonInput, + ) -> napi::Result { let trace_map: workspace::GraphTraceMap = - serde_json::from_value(trace).map_err(|e| napi::Error::from_reason(e.to_string()))?; + parse_json_input(&env, trace).map_err(napi::Error::from_reason)?; let result = self .inner .enhance_graph_trace(&Arc::from(path.as_str()), &trace_map) diff --git a/bindings/nodejs/test/workspace-large.spec.ts b/bindings/nodejs/test/workspace-large.spec.ts new file mode 100644 index 00000000..a44c81ae --- /dev/null +++ b/bindings/nodejs/test/workspace-large.spec.ts @@ -0,0 +1,55 @@ +import { describe, expect, it } from '@jest/globals'; + +const { Workspace } = require('../index.js'); + +const lookupTable = (rows: number) => ({ + nodes: [ + { id: 'in', name: 'request', type: 'inputNode', content: { schema: '' }, position: { x: 0, y: 0 } }, + { + id: 'table', + name: 'lookup', + type: 'decisionTableNode', + position: { x: 300, y: 0 }, + content: { + hitPolicy: 'first', + inputs: [{ id: 'code', name: 'Code', field: 'code' }], + outputs: [{ id: 'rate', name: 'Rate', field: 'rate' }], + rules: Array.from({ length: rows }, (_, row) => ({ + _id: `r${row}`, + code: `"C${row}"`, + rate: String(row), + })), + passThrough: true, + }, + }, + { id: 'out', name: 'response', type: 'outputNode', content: { schema: '' }, position: { x: 600, y: 0 } }, + ], + edges: [ + { id: 'e1', type: 'edge', sourceId: 'in', targetId: 'table' }, + { id: 'e2', type: 'edge', sourceId: 'table', targetId: 'out' }, + ], +}); + +describe('Workspace large documents', () => { + const rows = 300_000; + const content = lookupTable(rows); + const text = JSON.stringify(content); + + it.each<[string, () => unknown]>([ + ['an object', () => content], + ['a JSON string', () => text], + ['a Buffer', () => Buffer.from(text)], + ['a Uint8Array', () => new TextEncoder().encode(text)], + ])('loads more than a million JSON values from %s', (_, document) => { + const ws = new Workspace(); + ws.setDocument('lookup', document()); + expect(ws.isGraph('lookup')).toBe(true); + expect(ws.paths()).toEqual(['lookup']); + expect(ws.inputs({ policyPath: 'lookup' }).map((input: any) => input.path)).toEqual(['code']); + }); + + it('reports invalid JSON text', () => { + const ws = new Workspace(); + expect(() => ws.setDocument('broken', '{ "nodes": ')).toThrow(/Invalid document/); + }); +}); diff --git a/bindings/python/CHANGELOG.md b/bindings/python/CHANGELOG.md index 030631f1..625bea15 100644 --- a/bindings/python/CHANGELOG.md +++ b/bindings/python/CHANGELOG.md @@ -1,5 +1,9 @@ # Changelog +## [2.1.8](https://github.com/gorules/zen/compare/python-v2.1.7...python-v2.1.8) (2026-11-19) + +## [2.1.7](https://github.com/gorules/zen/compare/python-v2.1.6...python-v2.1.7) (2026-11-09) + ## [2.1.6](https://github.com/gorules/zen/compare/python-v2.1.5...python-v2.1.6) (2026-10-21) ## [2.1.5](https://github.com/gorules/zen/compare/python-v2.1.4...python-v2.1.5) (2026-10-20) diff --git a/bindings/python/Cargo.toml b/bindings/python/Cargo.toml index ae9e587e..40116406 100644 --- a/bindings/python/Cargo.toml +++ b/bindings/python/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "zen-python" -version = "2.1.6" +version = "2.1.8" edition = "2021" license = "MIT" publish = false diff --git a/bindings/uniffi/CHANGELOG.md b/bindings/uniffi/CHANGELOG.md index eaedddc6..bc741b4b 100644 --- a/bindings/uniffi/CHANGELOG.md +++ b/bindings/uniffi/CHANGELOG.md @@ -1,5 +1,16 @@ # Changelog +## [2.1.9](https://github.com/gorules/zen/compare/uniffi-v2.1.8...uniffi-v2.1.9) (2026-11-19) + +## [2.1.8](https://github.com/gorules/zen/compare/uniffi-v2.1.7...uniffi-v2.1.8) (2026-11-11) + + +### Features + +* **uniffi:** add linux musl builds for Java, Kotlin and C# ([#564](https://github.com/gorules/zen/issues/564)) ([c318119](https://github.com/gorules/zen/commit/c318119c1fabe59d18f596d111ee6682de37264c)) + +## [2.1.7](https://github.com/gorules/zen/compare/uniffi-v2.1.6...uniffi-v2.1.7) (2026-11-09) + ## [2.1.6](https://github.com/gorules/zen/compare/uniffi-v2.1.5...uniffi-v2.1.6) (2026-10-21) ## [2.1.5](https://github.com/gorules/zen/compare/uniffi-v2.1.4...uniffi-v2.1.5) (2026-10-20) diff --git a/bindings/uniffi/Cargo.toml b/bindings/uniffi/Cargo.toml index fe9fb90b..55cc8907 100644 --- a/bindings/uniffi/Cargo.toml +++ b/bindings/uniffi/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "zen-uniffi" -version = "2.1.6" +version = "2.1.9" edition = "2024" license = "MIT" publish = false diff --git a/bindings/uniffi/Makefile b/bindings/uniffi/Makefile index ddd63781..abac350c 100644 --- a/bindings/uniffi/Makefile +++ b/bindings/uniffi/Makefile @@ -11,10 +11,14 @@ ifeq ($(UNAME_S),Darwin) endif else LIB_NAME := libzen_uniffi.so + LINUX_PREFIX := $(if $(shell ldd --version 2>&1 | grep -i musl),linux-musl,linux) + ifeq ($(LINUX_PREFIX),linux-musl) + export RUSTFLAGS += -C target-feature=-crt-static + endif ifeq ($(UNAME_M),aarch64) - PLATFORM_DIR := linux-aarch64 + PLATFORM_DIR := $(LINUX_PREFIX)-aarch64 else - PLATFORM_DIR := linux-x86-64 + PLATFORM_DIR := $(LINUX_PREFIX)-x86-64 endif endif diff --git a/bindings/uniffi/build.gradle.kts b/bindings/uniffi/build.gradle.kts index 546c874a..c571ae34 100644 --- a/bindings/uniffi/build.gradle.kts +++ b/bindings/uniffi/build.gradle.kts @@ -39,7 +39,7 @@ sourceSets { val kotlin by creating { kotlin { - srcDirs("lib/kotlin", "build/generated/kotlin") + srcDirs("lib/kotlin", "lib/kotlin-jvm", "build/generated/kotlin") } resources { srcDirs("build/generated/resources") @@ -133,6 +133,24 @@ tasks { dependsOn(patchJavaNativeLoader) } + val patchKotlinNativeLoader by creating { + doLast { + val namespaceLibrary = file("build/generated/kotlin/io/gorules/zen_engine/kotlin/zen_uniffi.kt") + val lookup = "System.getProperty(\"uniffi.component.\$componentName.libraryOverride\")" + if (namespaceLibrary.exists() && !namespaceLibrary.readText().contains("MuslLibraryResolver")) { + val source = namespaceLibrary.readText() + if (!source.contains(lookup)) { + throw GradleException("Kotlin library override lookup not found in ${namespaceLibrary.path}") + } + namespaceLibrary.writeText(source.replace(lookup, "$lookup ?: MuslLibraryResolver.libraryPath")) + } + } + } + + named(sourceSets["kotlin"].getCompileTaskName("kotlin")) { + dependsOn(patchKotlinNativeLoader) + } + val testJava by creating(Test::class) { group = "verification" testClassesDirs = sourceSets["testsJava"].output.classesDirs @@ -184,6 +202,7 @@ tasks { archiveBaseName.set("zen_engine_kotlin") archiveClassifier.set("sources") from(sourceSets["kotlin"].kotlin) + dependsOn(patchKotlinNativeLoader) } val generateKotlinAndroidSourcesJar by creating(Jar::class) { diff --git a/bindings/uniffi/lib/java/io/gorules/zen_engine/NativeLibraryExtractor.java b/bindings/uniffi/lib/java/io/gorules/zen_engine/NativeLibraryExtractor.java index 2e3971f0..9e6eec00 100644 --- a/bindings/uniffi/lib/java/io/gorules/zen_engine/NativeLibraryExtractor.java +++ b/bindings/uniffi/lib/java/io/gorules/zen_engine/NativeLibraryExtractor.java @@ -2,9 +2,11 @@ package io.gorules.zen_engine; import java.io.IOException; import java.io.InputStream; +import java.io.UncheckedIOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardCopyOption; +import java.util.stream.Stream; final class NativeLibraryExtractor { private NativeLibraryExtractor() {} @@ -22,12 +24,13 @@ final class NativeLibraryExtractor { platform = "win32-x86-64"; fileName = "zen_uniffi.dll"; } else { + String prefix = isMusl() ? "linux-musl-" : "linux-"; if (arch.contains("aarch64")) { - platform = "linux-aarch64"; + platform = prefix + "aarch64"; } else if (arch.contains("s390x")) { platform = "linux-s390x"; } else { - platform = "linux-x86-64"; + platform = prefix + "x86-64"; } fileName = "libzen_uniffi.so"; } @@ -47,4 +50,12 @@ final class NativeLibraryExtractor { throw new UnsatisfiedLinkError("failed to extract zen_uniffi native library: " + e.getMessage()); } } + + private static boolean isMusl() { + try (Stream lines = Files.lines(Path.of("/proc/self/maps"))) { + return lines.anyMatch(line -> line.contains("/ld-musl-") || line.contains("/libc.musl-")); + } catch (IOException | UncheckedIOException e) { + return false; + } + } } diff --git a/bindings/uniffi/lib/kotlin-jvm/io/gorules/zen_engine/kotlin/MuslLibraryResolver.kt b/bindings/uniffi/lib/kotlin-jvm/io/gorules/zen_engine/kotlin/MuslLibraryResolver.kt new file mode 100644 index 00000000..3566cddd --- /dev/null +++ b/bindings/uniffi/lib/kotlin-jvm/io/gorules/zen_engine/kotlin/MuslLibraryResolver.kt @@ -0,0 +1,46 @@ +package io.gorules.zen_engine.kotlin + +import java.io.File +import java.io.IOException +import java.nio.file.Files +import java.nio.file.StandardCopyOption + +internal object MuslLibraryResolver { + private const val FILE_NAME = "libzen_uniffi.so" + + val libraryPath: String? by lazy { resolve() } + + private fun resolve(): String? { + val os = System.getProperty("os.name").lowercase() + if (!os.contains("linux") || !isMusl()) { + return null + } + + val arch = System.getProperty("os.arch").lowercase() + val platform = if (arch.contains("aarch64")) "linux-musl-aarch64" else "linux-musl-x86-64" + val resource = "/$platform/$FILE_NAME" + val input = MuslLibraryResolver::class.java.getResourceAsStream(resource) + ?: throw UnsatisfiedLinkError("zen_uniffi native library not found on classpath: $resource") + + return try { + input.use { + val dir = Files.createTempDirectory("zen_uniffi") + dir.toFile().deleteOnExit() + val lib = dir.resolve(FILE_NAME) + lib.toFile().deleteOnExit() + Files.copy(it, lib, StandardCopyOption.REPLACE_EXISTING) + lib.toAbsolutePath().toString() + } + } catch (e: IOException) { + throw UnsatisfiedLinkError("failed to extract zen_uniffi native library: ${e.message}") + } + } + + private fun isMusl(): Boolean = try { + File("/proc/self/maps").useLines { lines -> + lines.any { it.contains("/ld-musl-") || it.contains("/libc.musl-") } + } + } catch (e: IOException) { + false + } +} diff --git a/bindings/uniffi/nuget/GoRules.ZenEngine.csproj b/bindings/uniffi/nuget/GoRules.ZenEngine.csproj index af1e2e99..2702304a 100644 --- a/bindings/uniffi/nuget/GoRules.ZenEngine.csproj +++ b/bindings/uniffi/nuget/GoRules.ZenEngine.csproj @@ -56,6 +56,18 @@ PackagePath="runtimes/linux-arm64/native/" Visible="false" /> + + + + + + true false GoRules.ZenEngine.Tests + linux-musl- + linux- @@ -23,11 +25,11 @@ Condition="$([MSBuild]::IsOSPlatform('OSX')) And '$([System.Runtime.InteropServices.RuntimeInformation]::OSArchitecture)' == 'X64'" CopyToOutputDirectory="PreserveNewest" Link="libzen_uniffi.dylib" /> - - diff --git a/core/engine/CHANGELOG.md b/core/engine/CHANGELOG.md index 3dc2db46..11eadea9 100644 --- a/core/engine/CHANGELOG.md +++ b/core/engine/CHANGELOG.md @@ -1,5 +1,37 @@ # Changelog +## [2.1.8](https://github.com/gorules/zen/compare/zen-engine-v2.1.7...zen-engine-v2.1.8) (2026-11-19) + + +### Bug Fixes + +* table analysis memory ([#570](https://github.com/gorules/zen/issues/570)) ([1944ebe](https://github.com/gorules/zen/commit/1944ebe01feb2b11b5197c7b16f4ae1e9d26ccf3)) + + +### Dependencies + +* The following workspace dependencies were updated + * dependencies + * zen-types bumped from 2.1.7 to 2.1.8 + * zen-expression bumped from 2.1.7 to 2.1.8 + * zen-tmpl bumped from 2.1.7 to 2.1.8 + +## [2.1.7](https://github.com/gorules/zen/compare/zen-engine-v2.1.6...zen-engine-v2.1.7) (2026-11-09) + + +### Bug Fixes + +* **engine:** upgrade zip to version 9 and reject cloaked archives ([#556](https://github.com/gorules/zen/issues/556)) ([99c3511](https://github.com/gorules/zen/commit/99c3511a21e56f893fa59ddff163d211c66a1227)) + + +### Dependencies + +* The following workspace dependencies were updated + * dependencies + * zen-types bumped from 2.1.6 to 2.1.7 + * zen-expression bumped from 2.1.6 to 2.1.7 + * zen-tmpl bumped from 2.1.6 to 2.1.7 + ## [2.1.6](https://github.com/gorules/zen/compare/zen-engine-v2.1.5...zen-engine-v2.1.6) (2026-10-21) diff --git a/core/engine/Cargo.toml b/core/engine/Cargo.toml index 6f5bc950..d8af8b28 100644 --- a/core/engine/Cargo.toml +++ b/core/engine/Cargo.toml @@ -3,7 +3,7 @@ authors = ["GoRules Team "] description = "Business rules engine" name = "zen-engine" license = "MIT" -version = "2.1.6" +version = "2.1.8" edition = "2021" repository = "https://github.com/gorules/zen.git" homepage = "https://gorules.io" @@ -31,15 +31,15 @@ rust_decimal = { workspace = true, features = ["maths-nopanic"] } fixedbitset = "0.5" tokio = { workspace = true, features = ["sync", "time"] } rquickjs = { version = "0.10", features = ["macro", "loader", "rust-alloc", "futures", "either", "properties"] } -zen-types = { path = "../types", version = "2.1.6" } -zen-expression = { path = "../expression", version = "2.1.6" } -zen-tmpl = { path = "../template", version = "2.1.6" } +zen-types = { path = "../types", version = "2.1.8" } +zen-expression = { path = "../expression", version = "2.1.8" } +zen-tmpl = { path = "../template", version = "2.1.8" } smallvec = { version = "1", features = ["union"] } nohash-hasher = { workspace = true } downcast-rs = { version = "2.0", features = ["std", "sync"] } arc-swap = "1" flate2 = { version = "1", features = ["rust_backend"] } -zip = { version = "8", default-features = false, features = ["deflate-flate2"] } +zip = { version = "9.0.5", default-features = false, features = ["deflate-flate2"] } swc_ts_fast_strip = "53.0.0" swc_common = "23" swc_ecma_parser = "41" diff --git a/core/engine/src/analysis/table/cover.rs b/core/engine/src/analysis/table/cover.rs new file mode 100644 index 00000000..0f0d563e --- /dev/null +++ b/core/engine/src/analysis/table/cover.rs @@ -0,0 +1,201 @@ +use std::rc::Rc; + +use ahash::HashMap; + +use super::cell::CellConstraint; +use super::gaps::{Bits, Dense, Space}; +use super::partition::Partition; +use super::value_set::ValueSet; +use super::verify::{Budget, MAX_FRAGMENTS, MAX_MINIMIZE}; + +pub(super) struct Coverage { + space: Space, + columns: usize, + bits: Vec, + opaque: Vec, + coverable: Vec, + remaining: Vec, + next: Vec, + prefix: Vec, +} + +impl Coverage { + pub(super) fn new(cells: &[Vec], columns: usize) -> Option { + let mut set_of: Vec>> = Vec::with_capacity(columns); + let mut sets_of: Vec> = Vec::with_capacity(columns); + let everything = ValueSet::all(); + for column in 0..columns { + let mut index: HashMap<&ValueSet, u32> = HashMap::default(); + let mut distinct: Vec<&ValueSet> = Vec::new(); + let ids: Vec> = cells + .iter() + .map(|row| match &row[column] { + CellConstraint::Known(set) => Some(*index.entry(set).or_insert_with(|| { + distinct.push(set); + distinct.len() as u32 - 1 + })), + _ => None, + }) + .collect(); + set_of.push(ids); + sets_of.push(distinct); + } + let atoms = sets_of + .iter() + .map(|sets| Dense::atoms(sets.iter().copied())); + if !Dense::fits(cells.len(), atoms) { + return None; + } + let mut partitions: Vec = Vec::with_capacity(columns); + let mut atoms_of: Vec>> = Vec::with_capacity(columns); + for distinct in sets_of { + let owned: Vec = distinct.into_iter().cloned().collect(); + let partition = Partition::new(&everything, &owned); + atoms_of.push(owned.iter().map(|set| partition.touching(set)).collect()); + partitions.push(partition); + } + let layouts: Vec<_> = partitions.iter().map(Partition::layout).collect(); + let widths: Vec = layouts.iter().map(|layout| layout.atoms).collect(); + let space = Space::new(layouts); + let stride = space.stride(); + + let mut opaque_ids: HashMap, u32> = HashMap::default(); + let mut bits = vec![0u64; cells.len() * stride]; + let mut opaque = vec![0u32; cells.len() * columns]; + let mut coverable = vec![true; cells.len()]; + for (row, row_cells) in cells.iter().enumerate() { + let words = &mut bits[row * stride..(row + 1) * stride]; + for (column, (axis, cell)) in space.axes().iter().zip(row_cells).enumerate() { + let words = &mut words[axis.range()]; + match (cell, set_of[column][row]) { + (CellConstraint::Known(set), Some(id)) => { + coverable[row] &= !set.is_empty(); + atoms_of[column][id as usize] + .iter() + .for_each(|&atom| Bits::set(words, atom)); + } + (cell, _) => { + (0..widths[column]).for_each(|atom| Bits::set(words, atom)); + if let CellConstraint::Opaque(atom) = cell { + let next = opaque_ids.len() as u32 + 1; + opaque[row * columns + column] = + *opaque_ids.entry(atom.clone()).or_insert(next); + } + } + } + } + } + Some(Self { + space, + columns, + bits, + opaque, + coverable, + remaining: Vec::new(), + next: Vec::new(), + prefix: Vec::new(), + }) + } + + fn projects(&self, earlier: usize, row: usize) -> bool { + let columns = self.columns; + self.coverable[earlier] + && self.opaque[earlier * columns..(earlier + 1) * columns] + .iter() + .zip(&self.opaque[row * columns..(row + 1) * columns]) + .all(|(&theirs, &own)| theirs == 0 || theirs == own) + } + + pub(super) fn covered_by( + &mut self, + row: usize, + requirements: &[Vec], + budget: &mut Budget, + ) -> Option>> { + let mut cited: Vec = Vec::new(); + for earlier in requirements { + let coverers: Vec = earlier + .iter() + .copied() + .filter(|&e| self.projects(e, row)) + .collect(); + let Some(used) = self.cover(row, &coverers, budget)? else { + return Some(None); + }; + cited.extend(self.minimize(row, used, budget)?); + } + cited.sort_unstable(); + cited.dedup(); + Some(Some(cited)) + } + + fn cover( + &mut self, + row: usize, + coverers: &[usize], + budget: &mut Budget, + ) -> Option>> { + let Self { + space, + columns, + bits, + remaining, + next, + prefix, + .. + } = self; + let stride = space.stride(); + remaining.clear(); + remaining.extend_from_slice(&bits[row * stride..(row + 1) * stride]); + let mut used = Vec::new(); + for &earlier in coverers { + let cut = &bits[earlier * stride..(earlier + 1) * stride]; + next.clear(); + let mut touched = false; + for fragment in remaining.chunks_exact(stride) { + budget.spend(*columns)?; + match space.subtract(fragment, cut, prefix, next) { + true => touched = true, + false => next.extend_from_slice(fragment), + } + } + if next.len() / stride > MAX_FRAGMENTS { + return None; + } + if touched { + used.push(earlier); + } + std::mem::swap(remaining, next); + if remaining.is_empty() { + return Some(Some(used)); + } + } + Some(None) + } + + fn minimize( + &mut self, + row: usize, + used: Vec, + budget: &mut Budget, + ) -> Option> { + if used.len() > MAX_MINIMIZE { + return Some(used); + } + let mut kept = used; + let mut i = kept.len(); + while i > 0 { + i -= 1; + let candidate: Vec = kept + .iter() + .enumerate() + .filter(|(j, _)| *j != i) + .map(|(_, &earlier)| earlier) + .collect(); + if self.cover(row, &candidate, budget)?.is_some() { + kept.remove(i); + } + } + Some(kept) + } +} diff --git a/core/engine/src/analysis/table/gaps.rs b/core/engine/src/analysis/table/gaps.rs new file mode 100644 index 00000000..fff453bc --- /dev/null +++ b/core/engine/src/analysis/table/gaps.rs @@ -0,0 +1,665 @@ +use std::ops::Range; +use std::rc::Rc; + +use ahash::{HashMap, HashSet}; +use rust_decimal::Decimal; + +use super::intern::Interner; +use super::partition::Layout; +use super::value_set::{Bound, StringSet, ValueSet}; +use super::verify::MAX_FRAGMENTS; + +const DIRECT_ROWS: usize = 8; +const WORD: usize = u64::BITS as usize; + +pub(super) struct Dense; + +impl Dense { + const REGION_WORDS: usize = 128; + const TABLE_WORDS: usize = 16 << 20; + + pub(super) fn atoms<'s>(sets: impl IntoIterator) -> usize { + let mut strings: HashSet<&Rc> = HashSet::default(); + let mut points: HashSet = HashSet::default(); + for set in sets { + match &set.strings { + StringSet::Finite(keys) | StringSet::CoFinite(keys) => strings.extend(keys), + } + for interval in set.numbers.intervals() { + for bound in [interval.lo, interval.hi] { + if let Bound::Inclusive(point) | Bound::Exclusive(point) = bound { + points.insert(point); + } + } + } + } + strings.len() + 2 * points.len() + 6 + } + + pub(super) fn fits(rows: usize, atoms: impl Iterator) -> bool { + let stride: usize = atoms.map(Bits::words).sum(); + stride <= Self::REGION_WORDS && rows.saturating_mul(stride) <= Self::TABLE_WORDS + } +} + +pub(super) struct Bits; + +impl Bits { + pub(super) fn words(atoms: usize) -> usize { + atoms.div_ceil(WORD).max(1) + } + + pub(super) fn has(words: &[u64], atom: usize) -> bool { + words[atom / WORD] >> (atom % WORD) & 1 == 1 + } + + pub(super) fn set(words: &mut [u64], atom: usize) { + words[atom / WORD] |= 1 << (atom % WORD); + } + + pub(super) fn ones(words: &[u64]) -> impl Iterator + '_ { + words.iter().enumerate().flat_map(|(index, &word)| { + let mut rest = word; + std::iter::from_fn(move || { + (rest != 0).then(|| { + let atom = index * WORD + rest.trailing_zeros() as usize; + rest &= rest - 1; + atom + }) + }) + }) + } +} + +pub(super) struct Axis { + offset: usize, + words: usize, + atoms: usize, + strings: usize, + rest: Option, + numbers: Range, + piece_of: Vec, + last_piece: u32, + string_mask: Vec, + number_mask: Vec, + tail_mask: Vec, + consecutive: Vec, +} + +impl Axis { + fn new(layout: Layout, offset: usize) -> Self { + let words = Bits::words(layout.atoms); + let mut string_mask = vec![0u64; words]; + let mut number_mask = vec![0u64; words]; + let mut tail_mask = vec![0u64; words]; + let mut consecutive = vec![0u64; words]; + (0..layout.strings).for_each(|atom| Bits::set(&mut string_mask, atom)); + layout + .numbers + .clone() + .for_each(|atom| Bits::set(&mut number_mask, atom)); + (layout.numbers.end..layout.atoms).for_each(|atom| Bits::set(&mut tail_mask, atom)); + for (index, pair) in layout.piece_of.windows(2).enumerate() { + if pair[1] == pair[0] + 1 { + Bits::set(&mut consecutive, layout.numbers.start + index); + } + } + Self { + offset, + words, + atoms: layout.atoms, + strings: layout.strings, + rest: layout.rest, + numbers: layout.numbers, + piece_of: layout.piece_of, + last_piece: layout.last_piece, + string_mask, + number_mask, + tail_mask, + consecutive, + } + } + + pub(super) fn range(&self) -> Range { + self.offset..self.offset + self.words + } + + fn piece(&self, atom: usize) -> u32 { + self.piece_of[atom - self.numbers.start] + } + + fn localize(&self, bounds: &[u64], scratch: &mut Scratch) -> usize { + let words = self.words; + let distinct = scratch.sets.len() as u32; + for buffer in [ + &mut scratch.mentioned, + &mut scratch.starts, + &mut scratch.ends, + &mut scratch.count_mask, + ] { + buffer.clear(); + buffer.resize(words, 0); + } + for id in 0..distinct { + let set = scratch.sets.get(id); + let flip = match self.rest { + Some(rest) if Bits::has(set, rest) => u64::MAX, + _ => 0, + }; + for index in 0..words { + scratch.mentioned[index] |= (set[index] ^ flip) & self.string_mask[index]; + let numbers = set[index] & self.number_mask[index]; + let after = match set.get(index + 1) { + Some(next) => (next & self.number_mask[index + 1]) << (WORD - 1), + None => 0, + }; + let before = match index { + 0 => 0, + _ => { + (set[index - 1] & self.number_mask[index - 1] & self.consecutive[index - 1]) + >> (WORD - 1) + } + }; + let continues = numbers & self.consecutive[index] & ((numbers >> 1) | after); + let continued = numbers & (((numbers & self.consecutive[index]) << 1) | before); + scratch.ends[index] |= numbers & !continues; + scratch.starts[index] |= numbers & !continued; + } + } + + scratch.marks.clear(); + for atom in Bits::ones(&scratch.ends) { + let piece = self.piece(atom); + if piece < self.last_piece { + scratch.marks.push(piece / 2); + } + } + for atom in Bits::ones(&scratch.starts) { + let piece = self.piece(atom); + if piece >= 1 { + scratch.marks.push((piece - 1) / 2); + } + } + scratch.marks.sort_unstable(); + scratch.marks.dedup(); + + scratch.order.clear(); + let mut lump: Option = None; + for index in 0..words { + let strings = bounds[index] & self.string_mask[index]; + scratch.mentioned[index] &= strings; + let unlisted = strings & !scratch.mentioned[index]; + if lump.is_none() && unlisted != 0 { + lump = Some(index * WORD + unlisted.trailing_zeros() as usize); + } + } + scratch + .order + .extend(Bits::ones(&scratch.mentioned).map(|a| a as u32)); + let lump = lump.or(self.rest.filter(|&rest| Bits::has(bounds, rest))); + scratch.lump = lump.map(|atom| atom as u32); + scratch.order.extend(scratch.lump); + + let mut below = 0usize; + let mut previous: Option = None; + for index in 0..words { + let mut numbers = bounds[index] & self.number_mask[index]; + while numbers != 0 { + let atom = index * WORD + numbers.trailing_zeros() as usize; + numbers &= numbers - 1; + let piece = self.piece(atom); + let point = piece / 2; + while scratch.marks.get(below).is_some_and(|&mark| mark < point) { + below += 1; + } + let marked = piece % 2 == 1 && scratch.marks.get(below) == Some(&point); + let local = 2 * below as u32 + u32::from(marked); + if previous != Some(local) { + previous = Some(local); + scratch.order.push(atom as u32); + } + } + } + for index in 0..words { + let mut tail = bounds[index] & self.tail_mask[index]; + while tail != 0 { + scratch + .order + .push((index * WORD + tail.trailing_zeros() as usize) as u32); + tail &= tail - 1; + } + } + + if scratch.slot_of.len() < self.atoms { + scratch.slot_of.resize(self.atoms, 0); + } + for (slot, &atom) in scratch.order.iter().enumerate() { + scratch.slot_of[atom as usize] = slot as u32; + Bits::set(&mut scratch.count_mask, atom as usize); + } + + (0..distinct) + .map(|id| { + scratch + .sets + .get(id) + .iter() + .zip(&scratch.count_mask) + .map(|(set, mask)| (set & mask).count_ones() as usize) + .sum::() + }) + .sum() + } + + fn group(&self, scratch: &mut Scratch) { + let slots = scratch.order.len(); + if scratch.touched.len() < slots { + scratch.touched.resize_with(slots, Vec::new); + } + scratch.touched[..slots].iter_mut().for_each(Vec::clear); + for id in 0..scratch.sets.len() as u32 { + let set = scratch.sets.get(id); + for index in 0..self.words { + let mut local = set[index] & scratch.count_mask[index]; + while local != 0 { + let atom = index * WORD + local.trailing_zeros() as usize; + local &= local - 1; + scratch.touched[scratch.slot_of[atom] as usize].push(id); + } + } + } + + scratch.lookup.clear(); + scratch.group_of.clear(); + scratch.leader.clear(); + for slot in 0..slots { + let ids = &scratch.touched[slot]; + let hash = ids.iter().fold(0x9E37_79B9_7F4A_7C15u64, |hash, &id| { + (hash ^ u64::from(id)).wrapping_mul(0xA24B_AED4_963E_E407) + }); + let mut probe = 0u32; + let group = loop { + match scratch.lookup.get(&(hash, ids.len(), probe)) { + Some(&group) + if scratch.touched[scratch.leader[group as usize] as usize] == *ids => + { + break group; + } + Some(_) => probe += 1, + None => { + let group = scratch.leader.len() as u32; + scratch.lookup.insert((hash, ids.len(), probe), group); + scratch.leader.push(slot as u32); + break group; + } + } + }; + scratch.group_of.push(group); + } + } + + fn masks(&self, bounds: &[u64], scratch: &Scratch) -> Vec { + let mut masks = vec![0u64; scratch.leader.len() * self.words]; + let lump = scratch.lump.map(|atom| scratch.slot_of[atom as usize]); + let mut piece_slot = 0u32; + for atom in Bits::ones(bounds) { + let own = || scratch.slot_of[atom]; + let slot = if atom < self.strings { + match Bits::has(&scratch.mentioned, atom) { + true => Some(own()), + false => lump, + } + } else if Some(atom) == self.rest { + lump + } else if self.numbers.contains(&atom) { + if Bits::has(&scratch.count_mask, atom) { + piece_slot = own(); + } + Some(piece_slot) + } else { + Some(own()) + }; + let Some(slot) = slot else { + continue; + }; + let group = scratch.group_of[slot as usize] as usize; + Bits::set( + &mut masks[group * self.words..(group + 1) * self.words], + atom, + ); + } + masks + } +} + +pub(super) struct Space { + axes: Vec, + stride: usize, +} + +impl Space { + pub(super) fn new(layouts: Vec) -> Self { + let mut stride = 0; + let axes = layouts + .into_iter() + .map(|layout| { + let axis = Axis::new(layout, stride); + stride += axis.words; + axis + }) + .collect(); + Self { axes, stride } + } + + pub(super) fn stride(&self) -> usize { + self.stride + } + + pub(super) fn axes(&self) -> &[Axis] { + &self.axes + } + + fn full(&self) -> Vec { + let mut region = vec![0u64; self.stride]; + for axis in &self.axes { + (0..axis.atoms).for_each(|atom| Bits::set(&mut region[axis.range()], atom)); + } + region + } + + fn meets(&self, cut: &[u64], region: &[u64]) -> bool { + self.axes + .iter() + .all(|axis| axis.range().any(|index| cut[index] & region[index] != 0)) + } + + fn within(region: &[u64], cut: &[u64]) -> bool { + region.iter().zip(cut).all(|(set, cut)| set & !cut == 0) + } + + pub(super) fn subtract( + &self, + fragment: &[u64], + cut: &[u64], + prefix: &mut Vec, + out: &mut Vec, + ) -> bool { + if !self.meets(cut, fragment) { + return false; + } + prefix.clear(); + prefix.extend_from_slice(fragment); + for axis in &self.axes { + let range = axis.range(); + if range.clone().any(|index| prefix[index] & !cut[index] != 0) { + let start = out.len(); + out.extend_from_slice(prefix); + for index in range.clone() { + out[start + index] = prefix[index] & !cut[index]; + } + } + for index in range { + prefix[index] &= cut[index]; + } + } + true + } +} + +#[derive(Default)] +struct Scratch { + sets: Interner, + of_row: Vec, + key: Vec, + mentioned: Vec, + starts: Vec, + ends: Vec, + count_mask: Vec, + marks: Vec, + order: Vec, + lump: Option, + slot_of: Vec, + touched: Vec>, + lookup: HashMap<(u64, usize, u32), u32>, + group_of: Vec, + leader: Vec, + counts: Vec, +} + +struct Best { + axis: usize, + score: usize, + masks: Vec, + ids: Vec>, + of_row: Vec, + distinct: usize, +} + +struct Piece { + bits: Vec, + rows: Vec, +} + +struct Split { + axis: usize, + pieces: Vec, +} + +pub(super) struct Found { + pub(super) patterns: Vec>, + pub(super) fragments: Vec, +} + +pub(super) struct Gaps<'c> { + space: &'c Space, + cuts: &'c [u64], + work: usize, + patterns: Vec>, + fragments: Vec, + scratch: Scratch, +} + +impl<'c> Gaps<'c> { + pub(super) fn new(space: &'c Space, cuts: &'c [u64], work: usize) -> Self { + Self { + space, + cuts, + work, + patterns: space + .axes + .iter() + .map(|axis| Interner::new(axis.words)) + .collect(), + fragments: Vec::new(), + scratch: Scratch::default(), + } + } + + pub(super) fn run(mut self, rows: usize) -> Option { + let region = self.space.full(); + self.uncovered(region, (0..rows as u32).collect())?; + Some(Found { + patterns: self.patterns, + fragments: self.fragments, + }) + } + + fn spend(&mut self, amount: usize) -> Option<()> { + self.work = self.work.checked_sub(amount.max(1))?; + Some(()) + } + + fn cut(&self, row: u32) -> &'c [u64] { + let cuts: &'c [u64] = self.cuts; + let start = row as usize * self.space.stride; + &cuts[start..start + self.space.stride] + } + + fn emit(&mut self, region: &[u64]) { + for (axis, patterns) in self.space.axes.iter().zip(self.patterns.iter_mut()) { + self.fragments.push(patterns.intern(®ion[axis.range()])); + } + } + + fn uncovered(&mut self, region: Vec, rows: Vec) -> Option<()> { + let space = self.space; + self.spend(rows.len() * space.axes.len())?; + let rows: Vec = rows + .into_iter() + .filter(|&row| space.meets(self.cut(row), ®ion)) + .collect(); + if rows.is_empty() { + self.emit(®ion); + return Some(()); + } + if rows + .iter() + .any(|&row| Space::within(®ion, self.cut(row))) + { + return Some(()); + } + if rows.len() > DIRECT_ROWS { + if let Some(split) = self.split(®ion, &rows) { + let range = space.axes[split.axis].range(); + for piece in split.pieces { + let mut narrowed = region.clone(); + narrowed[range.clone()].copy_from_slice(&piece.bits); + self.uncovered(narrowed, piece.rows)?; + } + return Some(()); + } + } + self.subtract_all(region, &rows) + } + + fn subtract_all(&mut self, region: Vec, rows: &[u32]) -> Option<()> { + let space = self.space; + let stride = space.stride; + let dims = space.axes.len(); + let mut remaining = region; + let mut next: Vec = Vec::new(); + let mut prefix: Vec = Vec::with_capacity(stride); + for &row in rows { + let cut = self.cut(row); + next.clear(); + for fragment in remaining.chunks_exact(stride) { + self.spend(dims)?; + if !space.subtract(fragment, cut, &mut prefix, &mut next) { + next.extend_from_slice(fragment); + } + } + if next.len() / stride > MAX_FRAGMENTS { + return None; + } + std::mem::swap(&mut remaining, &mut next); + if remaining.is_empty() { + return Some(()); + } + } + for fragment in remaining.chunks_exact(stride) { + self.emit(fragment); + } + Some(()) + } + + fn split(&mut self, region: &[u64], rows: &[u32]) -> Option { + let space = self.space; + let scratch = &mut self.scratch; + let mut best: Option = None; + for (index, axis) in space.axes.iter().enumerate() { + let bounds = ®ion[axis.range()]; + scratch.sets.reset(axis.words); + scratch.of_row.clear(); + for &row in rows { + let start = row as usize * space.stride + axis.offset; + let cut = &self.cuts[start..start + axis.words]; + scratch.key.clear(); + scratch + .key + .extend(cut.iter().zip(bounds).map(|(cut, bound)| cut & bound)); + scratch.of_row.push(scratch.sets.intern(&scratch.key)); + } + let distinct = scratch.sets.len(); + if distinct == 1 && scratch.sets.get(0) == bounds { + continue; + } + if axis.localize(bounds, scratch) > self.work { + return None; + } + axis.group(scratch); + let groups = scratch.leader.len(); + if groups < 2 { + continue; + } + scratch.counts.clear(); + scratch.counts.resize(distinct, 0); + for &id in &scratch.of_row { + scratch.counts[id as usize] += 1; + } + let score: usize = scratch + .leader + .iter() + .map(|&slot| { + scratch.touched[slot as usize] + .iter() + .map(|&id| scratch.counts[id as usize]) + .sum::() + }) + .sum(); + self.work = self.work.checked_sub((score + groups).max(1))?; + if best.as_ref().is_none_or(|best| score < best.score) { + best = Some(Best { + axis: index, + score, + masks: axis.masks(bounds, scratch), + ids: scratch + .leader + .iter() + .map(|&slot| scratch.touched[slot as usize].clone()) + .collect(), + of_row: scratch.of_row.clone(), + distinct, + }); + } + } + let best = best?; + let words = space.axes[best.axis].words; + let mut starts = vec![0u32; best.distinct + 1]; + for &id in &best.of_row { + starts[id as usize + 1] += 1; + } + for id in 0..best.distinct { + starts[id + 1] += starts[id]; + } + let mut cursor = starts.clone(); + let mut by_set = vec![0u32; rows.len()]; + for (&row, &id) in rows.iter().zip(&best.of_row) { + by_set[cursor[id as usize] as usize] = row; + cursor[id as usize] += 1; + } + let pieces = best + .ids + .iter() + .zip(best.masks.chunks_exact(words)) + .map(|(ids, mask)| { + let mut piece_rows: Vec = ids + .iter() + .flat_map(|&id| { + by_set[starts[id as usize] as usize..starts[id as usize + 1] as usize] + .iter() + .copied() + }) + .collect(); + piece_rows.sort_unstable(); + Piece { + bits: mask.to_vec(), + rows: piece_rows, + } + }) + .collect(); + Some(Split { + axis: best.axis, + pieces, + }) + } +} diff --git a/core/engine/src/analysis/table/index.rs b/core/engine/src/analysis/table/index.rs index 983bf4ee..752fbc23 100644 --- a/core/engine/src/analysis/table/index.rs +++ b/core/engine/src/analysis/table/index.rs @@ -3,6 +3,7 @@ use std::rc::Rc; use ahash::HashMap; use super::cell::CellConstraint; +use super::merge::CellKeys; use super::partition::Points; use rust_decimal::Decimal; @@ -107,6 +108,7 @@ pub(super) struct RowIndex { stamp: Vec, query: usize, blocking: bool, + overlaps: HashMap<(u32, u32, u32), bool>, } enum Keys<'a> { @@ -139,6 +141,7 @@ impl RowIndex { stamp: vec![0; cells.len()], query: 0, blocking: false, + overlaps: HashMap::default(), } } @@ -224,7 +227,24 @@ impl RowIndex { } } - pub(super) fn candidates(&mut self, cells: &[Vec], row: usize) -> Vec { + fn may_overlap(cell: &CellConstraint, earlier: &CellConstraint) -> bool { + match (Self::keys(cell), earlier) { + (Keys::Exact(_) | Keys::Numbers(_), CellConstraint::Opaque(_)) => false, + (Keys::Exact(set), CellConstraint::Known(earlier)) => earlier.intersects(set), + (Keys::Numbers(_), CellConstraint::Known(earlier)) => { + cell.known_set().is_some_and(|own| earlier.intersects(&own)) + } + _ => true, + } + } + + pub(super) fn candidates( + &mut self, + cells: &[Vec], + keys: &CellKeys<'_>, + row: usize, + ) -> Vec { + const REMEMBERED: usize = 1 << 20; let row_cells = &cells[row]; let driver = row_cells .iter() @@ -237,42 +257,52 @@ impl RowIndex { }; let mut out: Vec = Vec::new(); self.drive(driver, Self::keys(&row_cells[driver]), row, |e| out.push(e)); + let own = keys.row(row); + let overlaps = &mut self.overlaps; out.retain(|&e| { + let theirs = keys.row(e); row_cells.iter().enumerate().all(|(col, cell)| { - col == driver - || match (Self::keys(cell), &cells[e][col]) { - (Keys::Exact(_) | Keys::Numbers(_), CellConstraint::Opaque(_)) => false, - (Keys::Exact(set), CellConstraint::Known(earlier)) => { - earlier.intersects(set) - } - (Keys::Numbers(_), CellConstraint::Known(earlier)) => { - cell.known_set().is_some_and(|own| earlier.intersects(&own)) - } - _ => true, - } + if col == driver { + return true; + } + let pair = (col as u32, own[col], theirs[col]); + if let Some(&known) = overlaps.get(&pair) { + debug_assert_eq!(known, Self::may_overlap(cell, &cells[e][col])); + return known; + } + let found = Self::may_overlap(cell, &cells[e][col]); + if overlaps.len() < REMEMBERED { + overlaps.insert(pair, found); + } + found }) }); out.sort_unstable(); out } - pub(super) fn overlapping( + pub(super) fn overlapping>( &mut self, - region: &[ValueSet], + region: &[S], limit: usize, visit: impl FnMut(usize), ) -> bool { let driver = region .iter() .enumerate() - .filter_map(|(col, set)| Some((col, self.estimate(col, Self::set_keys(set))?))) + .filter_map(|(col, set)| Some((col, self.estimate(col, Self::set_keys(set.borrow()))?))) .min_by_key(|(_, size)| *size) .filter(|(_, size)| *size < limit) .map(|(col, _)| col); let Some(driver) = driver else { return false; }; - self.drive(driver, Self::set_keys(®ion[driver]), usize::MAX, visit); + self.drive( + driver, + Self::set_keys(region[driver].borrow()), + usize::MAX, + visit, + ); true } diff --git a/core/engine/src/analysis/table/intern.rs b/core/engine/src/analysis/table/intern.rs new file mode 100644 index 00000000..344ca3b7 --- /dev/null +++ b/core/engine/src/analysis/table/intern.rs @@ -0,0 +1,122 @@ +pub(super) struct Interner { + stride: usize, + data: Vec, + slots: Vec, + len: usize, +} + +impl> Default for Interner { + fn default() -> Self { + Self::new(0) + } +} + +impl> Interner { + const INITIAL_SLOTS: usize = 16; + + pub(super) fn new(stride: usize) -> Self { + Self { + stride, + data: Vec::new(), + slots: vec![0; Self::INITIAL_SLOTS], + len: 0, + } + } + + pub(super) fn reset(&mut self, stride: usize) { + self.stride = stride; + self.data.clear(); + self.slots.iter_mut().for_each(|slot| *slot = 0); + self.len = 0; + } + + pub(super) fn len(&self) -> usize { + self.len + } + + pub(super) fn stride(&self) -> usize { + self.stride + } + + pub(super) fn get(&self, id: u32) -> &[T] { + let start = id as usize * self.stride; + &self.data[start..start + self.stride] + } + + pub(super) fn intern(&mut self, key: &[T]) -> u32 { + debug_assert_eq!(key.len(), self.stride); + if (self.len + 1) * 2 > self.slots.len() { + self.grow(); + } + let mask = self.slots.len() - 1; + let mut slot = Self::hash(key) as usize & mask; + loop { + match self.slots[slot] { + 0 => { + let id = self.len as u32; + self.slots[slot] = id + 1; + self.data.extend_from_slice(key); + self.len += 1; + return id; + } + taken if self.get(taken - 1) == key => return taken - 1, + _ => slot = (slot + 1) & mask, + } + } + } + + fn grow(&mut self) { + let mask = self.slots.len() * 2 - 1; + let mut slots = vec![0u32; mask + 1]; + for id in 0..self.len as u32 { + let mut slot = Self::hash(self.get(id)) as usize & mask; + while slots[slot] != 0 { + slot = (slot + 1) & mask; + } + slots[slot] = id + 1; + } + self.slots = slots; + } + + fn hash(key: &[T]) -> u64 { + let mut hash: u64 = 0x9E37_79B9_7F4A_7C15; + for &part in key { + hash = (hash ^ part.into()).wrapping_mul(0xA24B_AED4_963E_E407); + hash ^= hash >> 29; + } + hash + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn interns_equal_keys_once_and_keeps_insertion_order() { + let mut interner: Interner = Interner::new(2); + let ids: Vec = (0..500u64) + .map(|i| interner.intern(&[i % 97, i % 3])) + .collect(); + assert_eq!(interner.len(), 97 * 3); + assert_eq!(ids[0], 0); + assert_eq!(ids[1], 1); + for (i, id) in ids.iter().enumerate() { + let i = i as u64; + assert_eq!(interner.get(*id), &[i % 97, i % 3]); + } + interner.reset(1); + assert_eq!(interner.len(), 0); + assert_eq!(interner.intern(&[7]), 0); + assert_eq!(interner.intern(&[7]), 0); + assert_eq!(interner.intern(&[8]), 1); + } + + #[test] + fn empty_keys_share_one_id() { + let mut interner: Interner = Interner::new(0); + assert_eq!(interner.intern(&[]), 0); + assert_eq!(interner.intern(&[]), 0); + assert_eq!(interner.len(), 1); + } +} diff --git a/core/engine/src/analysis/table/merge.rs b/core/engine/src/analysis/table/merge.rs index 74496cd1..bdee7e3a 100644 --- a/core/engine/src/analysis/table/merge.rs +++ b/core/engine/src/analysis/table/merge.rs @@ -1,22 +1,22 @@ -use std::collections::BTreeSet; -use std::rc::Rc; +use std::borrow::Cow; use std::sync::Arc; use ahash::HashMap; use super::cell::CellConstraint; use super::index::RowIndex; +use super::intern::Interner; use super::print::CellText; -use super::value_set::{StringSet, ValueSet}; +use super::value_set::{StringSet, Strings, ValueSet}; use super::verify::{Finding, HitMode, VerifyTable}; const COMPRESS_BUDGET: usize = 50_000_000; const MAX_ROUNDS: usize = 8; -#[derive(Clone)] -struct Row { - rule: HashMap, Arc>, - cells: Vec, +struct Row<'a> { + rule: Cow<'a, HashMap, Arc>>, + cells: Cow<'a, [CellConstraint]>, + output: u32, fixed: bool, barrier: bool, stale: Vec, @@ -41,26 +41,123 @@ impl Work { } } +pub(super) struct CellKeys<'c> { + columns: usize, + given: HashMap<&'c CellConstraint, u32>, + made: HashMap, + of: Vec, + pending: Vec, +} + +impl<'c> CellKeys<'c> { + const ANY: u32 = 0; + const PENDING: u32 = u32::MAX; + + pub(super) fn new(cells: &'c [Vec], columns: usize) -> Self { + let mut given: HashMap<&'c CellConstraint, u32> = HashMap::default(); + let mut of = Vec::with_capacity(cells.len() * columns); + for row in cells { + for cell in row { + of.push(match cell { + CellConstraint::Any => Self::ANY, + CellConstraint::Known(set) if set.is_all() => Self::ANY, + other => { + let next = given.len() as u32 + 1; + *given.entry(other).or_insert(next) + } + }); + } + } + Self { + columns, + given, + made: HashMap::default(), + of, + pending: Vec::new(), + } + } + + fn id(&mut self, cell: &CellConstraint) -> u32 { + match cell { + CellConstraint::Any => Self::ANY, + CellConstraint::Known(set) if set.is_all() => Self::ANY, + other => match self.given.get(other).or_else(|| self.made.get(other)) { + Some(&id) => id, + None => { + let id = (self.given.len() + self.made.len()) as u32 + 1; + self.made.insert(other.clone(), id); + id + } + }, + } + } + + pub(super) fn row(&self, row: usize) -> &[u32] { + &self.of[row * self.columns..(row + 1) * self.columns] + } + + fn touch(&mut self, row: usize, col: usize) { + let slot = row * self.columns + col; + if self.of[slot] != Self::PENDING { + self.of[slot] = Self::PENDING; + self.pending.push(slot); + } + } + + fn settle(&mut self, rows: &[Option]) { + for slot in std::mem::take(&mut self.pending) { + let (row, col) = (slot / self.columns, slot % self.columns); + self.of[slot] = match &rows[row] { + Some(row) => self.id(&row.cells[col]), + None => Self::ANY, + }; + } + } +} + impl VerifyTable<'_> { pub(super) fn compress( &self, cells: &[Vec], satisfiable: &[bool], warned: &[bool], + keys: CellKeys<'_>, + outputs: &[u32], + ) -> Option { + let found = self.compressed(cells, satisfiable, warned, keys, outputs); + #[cfg(test)] + assert_eq!( + found, + super::merge_reference::Legacy(self).compress(cells, satisfiable, warned), + "table compression diverged from the reference implementation" + ); + found + } + + fn compressed( + &self, + cells: &[Vec], + satisfiable: &[bool], + warned: &[bool], + mut keys: CellKeys, + outputs: &[u32], ) -> Option { if self.rules.len() < 2 { return None; } + let all = ValueSet::all(); let mut rows: Vec> = self .rules .iter() .zip(cells) .zip(satisfiable) .zip(warned) - .map(|(((rule, cells), satisfiable), warned)| { + .zip(outputs) + .map(|((((rule, cells), satisfiable), warned), &output)| { Some(Row { - rule: rule.clone(), - cells: cells.clone(), + rule: Cow::Borrowed(rule), + cells: Cow::Borrowed(cells.as_slice()), + output, fixed: !satisfiable || *warned, barrier: *warned, stale: Vec::new(), @@ -75,44 +172,37 @@ impl VerifyTable<'_> { for _ in 0..MAX_ROUNDS { let mut changed = false; if self.mode != HitMode::Collect { - changed |= self.drop_shadowed(&mut rows, &mut work, &mut index); - changed |= self.absorb(&mut rows, &mut work, &mut index); + changed |= self.drop_shadowed(&mut rows, &mut work, &mut index, &all); + changed |= self.absorb(&mut rows, &mut work, &mut index, &all); } for col in 0..self.inputs.len() { - changed |= self.merge_column(&mut rows, col, &mut work, &mut index); + changed |= + self.merge_column(&mut rows, col, &mut work, &mut index, &mut keys, &all); } if !changed || work.remaining == 0 { break; } } + if rows.iter().flatten().count() >= before { + return None; + } let rules: Vec<_> = rows .into_iter() .flatten() .map(|mut row| { for &col in &row.stale { if let CellConstraint::Known(set) = &row.cells[col] { - if let Some(text) = self.cell_text(col, set, &ValueSet::all(), false) { + if let Some(text) = self.cell_text(col, set, &all, false) { row.rule + .to_mut() .insert(self.inputs[col].id.clone(), Arc::from(text.as_str())); } } } - row.rule + row.rule.into_owned() }) .collect(); - (rules.len() < before).then_some(Finding::CompressibleTable { before, rules }) - } - - fn output_key(&self, row: &Row) -> Vec { - self.outputs - .iter() - .map(|col| { - row.rule - .get(&col.id) - .map(|c| c.trim().to_string()) - .unwrap_or_default() - }) - .collect() + Some(Finding::CompressibleTable { before, rules }) } fn collects(&self, row: &Row) -> bool { @@ -121,21 +211,17 @@ impl VerifyTable<'_> { .any(|col| col.collect && row.rule.get(&col.id).is_some_and(|c| !c.trim().is_empty())) } - fn cell_key(cell: &CellConstraint) -> CellConstraint { - match cell { - CellConstraint::Known(set) if set.is_all() => CellConstraint::Any, - other => other.clone(), - } - } - - fn region(row: &Row) -> Vec { + fn region<'r>(row: &'r Row, all: &'r ValueSet) -> Vec<&'r ValueSet> { row.cells .iter() - .map(|cell| cell.known_set().unwrap_or_else(ValueSet::all)) + .map(|cell| match cell { + CellConstraint::Known(set) => set, + _ => all, + }) .collect() } - fn catches(row: &Row, region: &[ValueSet]) -> bool { + fn catches(row: &Row, region: &[&ValueSet]) -> bool { row.cells .iter() .zip(region) @@ -149,7 +235,7 @@ impl VerifyTable<'_> { inner .cells .iter() - .zip(&outer.cells) + .zip(outer.cells.iter()) .all(|(a, b)| match (a, b) { (_, CellConstraint::Any) => true, (CellConstraint::Opaque(x), CellConstraint::Opaque(y)) => x == y, @@ -163,7 +249,7 @@ impl VerifyTable<'_> { rows: &[Option], from: usize, to: usize, - region: &[ValueSet], + region: &[&ValueSet], work: &mut Work, index: &mut RowIndex, ) -> bool { @@ -207,6 +293,7 @@ impl VerifyTable<'_> { rows: &mut [Option], work: &mut Work, index: &mut RowIndex, + all: &ValueSet, ) -> bool { if self.mode != HitMode::RowFirst { return false; @@ -225,7 +312,7 @@ impl VerifyTable<'_> { { continue; } - let region = Self::region(inner_row); + let region = Self::region(inner_row, all); let mut earlier: Vec = Vec::new(); let indexed = index.overlapping(®ion, inner, |e| { if e < inner { @@ -252,11 +339,17 @@ impl VerifyTable<'_> { changed } - fn absorb(&self, rows: &mut [Option], work: &mut Work, index: &mut RowIndex) -> bool { - let mut buckets: HashMap, Vec> = HashMap::default(); + fn absorb( + &self, + rows: &mut [Option], + work: &mut Work, + index: &mut RowIndex, + all: &ValueSet, + ) -> bool { + let mut buckets: HashMap> = HashMap::default(); for (idx, row) in rows.iter().enumerate() { if let Some(row) = row.as_ref().filter(|r| !r.fixed && !self.collects(r)) { - buckets.entry(self.output_key(row)).or_default().push(idx); + buckets.entry(row.output).or_default().push(idx); } } let mut changed = false; @@ -270,42 +363,45 @@ impl VerifyTable<'_> { } for (id, group) in groups.iter().enumerate() { for &inner in group { - let Some(inner_row) = rows[inner].as_ref() else { - continue; - }; - let region = Self::region(inner_row); - let mut outers: Vec = Vec::new(); - let indexed = index.overlapping(®ion, group.len(), |e| { - if group_of[e] == id { - outers.push(e); - } - }); - if indexed { - outers.sort_unstable(); - } else { - outers = group.clone(); - } - let mut absorbed = false; - for outer in outers { - if outer == inner { - continue; - } - if !work.spend(inner_row.cells.len()) { - return changed; - } - let Some(outer_row) = rows[outer].as_ref() else { + let absorbed = { + let Some(inner_row) = rows[inner].as_ref() else { continue; }; - if !Self::within(inner_row, outer_row) { - continue; + let region = Self::region(inner_row, all); + let mut outers: Vec = Vec::new(); + let indexed = index.overlapping(®ion, group.len(), |e| { + if group_of[e] == id { + outers.push(e); + } + }); + if indexed { + outers.sort_unstable(); + } else { + outers = group.clone(); } - if outer < inner - || Self::clear_between(rows, inner, outer, ®ion, work, index) - { - absorbed = true; - break; + let mut absorbed = false; + for outer in outers { + if outer == inner { + continue; + } + if !work.spend(inner_row.cells.len()) { + return changed; + } + let Some(outer_row) = rows[outer].as_ref() else { + continue; + }; + if !Self::within(inner_row, outer_row) { + continue; + } + if outer < inner + || Self::clear_between(rows, inner, outer, ®ion, work, index) + { + absorbed = true; + break; + } } - } + absorbed + }; if absorbed { rows[inner] = None; changed = true; @@ -315,44 +411,64 @@ impl VerifyTable<'_> { changed } + #[allow(clippy::too_many_arguments)] fn merge_column( &self, rows: &mut [Option], col: usize, work: &mut Work, index: &mut RowIndex, + keys: &mut CellKeys, + all: &ValueSet, ) -> bool { - let mut buckets: HashMap<(Vec, Vec), Vec> = - HashMap::default(); + let columns = self.inputs.len(); + keys.settle(rows); + let mut buckets: Interner = Interner::new(columns); + let mut key: Vec = Vec::with_capacity(columns); + let mut members: Vec<(u32, usize)> = Vec::new(); for (idx, row) in rows.iter().enumerate() { let Some(row) = row.as_ref().filter(|r| !r.fixed) else { continue; }; - if row.cells[col].known_set().is_none() { + if matches!(row.cells[col], CellConstraint::Opaque(_)) { continue; } if !work.spend(row.cells.len()) { return false; } - let others: Vec = row - .cells - .iter() - .enumerate() - .filter(|(i, _)| *i != col) - .map(|(_, cell)| Self::cell_key(cell)) - .collect(); - buckets - .entry((self.output_key(row), others)) - .or_default() - .push(idx); + key.clear(); + key.push(row.output); + key.extend( + keys.row(idx) + .iter() + .enumerate() + .filter(|(i, _)| *i != col) + .map(|(_, &id)| id), + ); + members.push((buckets.intern(&key), idx)); + } + let mut starts = vec![0usize; buckets.len() + 1]; + for &(bucket, _) in &members { + starts[bucket as usize + 1] += 1; + } + for bucket in 0..buckets.len() { + starts[bucket + 1] += starts[bucket]; + } + let mut cursor = starts.clone(); + let mut grouped = vec![0usize; members.len()]; + for &(bucket, idx) in &members { + grouped[cursor[bucket as usize]] = idx; + cursor[bucket as usize] += 1; } let mut changed = false; - let mut groups: Vec> = buckets.into_values().filter(|g| g.len() > 1).collect(); - groups.sort_unstable_by_key(|g| g[0]); - for group in groups { + for bucket in 0..buckets.len() { + let group = &grouped[starts[bucket]..starts[bucket + 1]]; + if group.len() < 2 { + continue; + } let mut keep = group[0]; for &next in &group[1..] { - if self.merge_into(rows, keep, next, col, work, index) { + if self.merge_into(rows, keep, next, col, work, index, keys, all) { changed = true; } else { keep = next; @@ -365,6 +481,7 @@ impl VerifyTable<'_> { changed } + #[allow(clippy::too_many_arguments)] fn merge_into( &self, rows: &mut [Option], @@ -373,6 +490,8 @@ impl VerifyTable<'_> { col: usize, work: &mut Work, index: &mut RowIndex, + keys: &mut CellKeys, + all: &ValueSet, ) -> bool { let (Some(keep_row), Some(next_row)) = (rows[keep].as_ref(), rows[next].as_ref()) else { return false; @@ -387,30 +506,31 @@ impl VerifyTable<'_> { { return false; } - let fresh: BTreeSet> = - b.iter().filter(|key| !a.contains(*key)).cloned().collect(); + let fresh: Strings = b.iter().filter(|key| !a.contains(key)).cloned().collect(); if fresh.iter().any(|key| CellText::string(key).is_none()) { return false; } - let mut moved = Self::region(next_row); - moved[col] = ValueSet { + let added = ValueSet { strings: StringSet::Finite(fresh.clone()), ..ValueSet::empty() }; + let mut moved = Self::region(next_row, all); + moved[col] = &added; if !Self::clear_between(rows, keep, next, &moved, work, index) { return false; } if let Some(row) = rows[keep].as_mut() { if let CellConstraint::Known(ValueSet { - strings: StringSet::Finite(keys), + strings: StringSet::Finite(members), .. - }) = &mut row.cells[col] + }) = &mut row.cells.to_mut()[col] { - keys.extend(fresh.iter().cloned()); + members.extend(fresh.iter().cloned()); } if !row.stale.contains(&col) { row.stale.push(col); } + keys.touch(keep, col); index.insert_strings(col, &fresh, keep); } rows[next] = None; @@ -425,35 +545,33 @@ impl VerifyTable<'_> { if (self.mode == HitMode::Collect || self.collects(keep_row)) && a.intersects(&b) { return false; } - let moved: Vec = Self::region(next_row) - .into_iter() - .enumerate() - .map(|(idx, set)| if idx == col { set.difference(&a) } else { set }) - .collect(); + let outside = b.difference(&a); + let mut moved = Self::region(next_row, all); + moved[col] = &outside; if !Self::clear_between(rows, keep, next, &moved, work, index) { return false; } let union = a.union(&b); - let Some(text) = self.cell_text(col, &union, &ValueSet::all(), self.inputs[col].dated) - else { + let Some(text) = self.cell_text(col, &union, all, self.inputs[col].dated) else { return false; }; let id = self.inputs[col].id.clone(); if let Some(row) = rows[keep].as_mut() { - row.rule.insert(id, Arc::from(text.as_str())); + row.rule.to_mut().insert(id, Arc::from(text.as_str())); row.stale.retain(|&stale| stale != col); - row.cells[col] = if text.is_empty() { + row.cells.to_mut()[col] = if text.is_empty() { CellConstraint::Any } else { CellConstraint::Known(union) }; + keys.touch(keep, col); index.insert(&row.cells, keep); } rows[next] = None; true } - fn plain(cell: &CellConstraint) -> Option<&BTreeSet>> { + fn plain(cell: &CellConstraint) -> Option<&Strings> { match cell { CellConstraint::Known(set) if set.numbers.is_empty() && set.bools == 0 && !set.null && !set.other => @@ -481,7 +599,12 @@ impl VerifyTable<'_> { let (CellConstraint::Known(set), Some(domain)) = (cell, &col.domain) else { continue; }; - if !domain.is_empty() && domain.difference(set).is_empty() { + debug_assert_eq!( + domain.is_subset(set), + domain.difference(set).is_empty(), + "subset check disagrees with the difference for {set:?}" + ); + if !domain.is_empty() && domain.is_subset(set) { findings.push(Finding::CellCoversDomain { row, col: col.id.clone(), diff --git a/core/engine/src/analysis/table/merge_reference.rs b/core/engine/src/analysis/table/merge_reference.rs new file mode 100644 index 00000000..61889af0 --- /dev/null +++ b/core/engine/src/analysis/table/merge_reference.rs @@ -0,0 +1,474 @@ +use std::sync::Arc; + +use ahash::HashMap; + +use super::cell::CellConstraint; +use super::index::RowIndex; +use super::print::CellText; +use super::value_set::{StringSet, Strings, ValueSet}; +use super::verify::{Finding, HitMode, VerifyTable}; + +const COMPRESS_BUDGET: usize = 50_000_000; +const MAX_ROUNDS: usize = 8; + +#[derive(Clone)] +struct Row { + rule: HashMap, Arc>, + cells: Vec, + fixed: bool, + barrier: bool, + stale: Vec, +} + +struct Work { + remaining: usize, +} + +impl Work { + fn spend(&mut self, amount: usize) -> bool { + match self.remaining.checked_sub(amount.max(1)) { + Some(left) => { + self.remaining = left; + true + } + None => { + self.remaining = 0; + false + } + } + } +} + +pub(super) struct Legacy<'t, 'r>(pub(super) &'t VerifyTable<'r>); + +impl Legacy<'_, '_> { + pub(super) fn compress( + &self, + cells: &[Vec], + satisfiable: &[bool], + warned: &[bool], + ) -> Option { + if self.0.rules.len() < 2 { + return None; + } + let mut rows: Vec> = self + .0 + .rules + .iter() + .zip(cells) + .zip(satisfiable) + .zip(warned) + .map(|(((rule, cells), satisfiable), warned)| { + Some(Row { + rule: rule.clone(), + cells: cells.clone(), + fixed: !satisfiable || *warned, + barrier: *warned, + stale: Vec::new(), + }) + }) + .collect(); + let before = rows.len(); + let mut work = Work { + remaining: COMPRESS_BUDGET, + }; + let mut index = RowIndex::blocking(cells, self.0.inputs.len()); + for _ in 0..MAX_ROUNDS { + let mut changed = false; + if self.0.mode != HitMode::Collect { + changed |= self.drop_shadowed(&mut rows, &mut work, &mut index); + changed |= self.absorb(&mut rows, &mut work, &mut index); + } + for col in 0..self.0.inputs.len() { + changed |= self.merge_column(&mut rows, col, &mut work, &mut index); + } + if !changed || work.remaining == 0 { + break; + } + } + let rules: Vec<_> = rows + .into_iter() + .flatten() + .map(|mut row| { + for &col in &row.stale { + if let CellConstraint::Known(set) = &row.cells[col] { + if let Some(text) = self.0.cell_text(col, set, &ValueSet::all(), false) { + row.rule + .insert(self.0.inputs[col].id.clone(), Arc::from(text.as_str())); + } + } + } + row.rule + }) + .collect(); + (rules.len() < before).then_some(Finding::CompressibleTable { before, rules }) + } + + fn output_key(&self, row: &Row) -> Vec { + self.0 + .outputs + .iter() + .map(|col| { + row.rule + .get(&col.id) + .map(|c| c.trim().to_string()) + .unwrap_or_default() + }) + .collect() + } + + fn collects(&self, row: &Row) -> bool { + self.0 + .outputs + .iter() + .any(|col| col.collect && row.rule.get(&col.id).is_some_and(|c| !c.trim().is_empty())) + } + + fn cell_key(cell: &CellConstraint) -> CellConstraint { + match cell { + CellConstraint::Known(set) if set.is_all() => CellConstraint::Any, + other => other.clone(), + } + } + + fn region(row: &Row) -> Vec { + row.cells + .iter() + .map(|cell| cell.known_set().unwrap_or_else(ValueSet::all)) + .collect() + } + + fn catches(row: &Row, region: &[ValueSet]) -> bool { + row.cells + .iter() + .zip(region) + .all(|(cell, wanted)| match cell { + CellConstraint::Known(set) => set.intersects(wanted), + _ => !wanted.is_empty(), + }) + } + + fn within(inner: &Row, outer: &Row) -> bool { + inner + .cells + .iter() + .zip(&outer.cells) + .all(|(a, b)| match (a, b) { + (_, CellConstraint::Any) => true, + (CellConstraint::Opaque(x), CellConstraint::Opaque(y)) => x == y, + (CellConstraint::Opaque(_), _) | (_, CellConstraint::Opaque(_)) => false, + (CellConstraint::Known(a), CellConstraint::Known(b)) => a.is_subset(b), + (CellConstraint::Any, CellConstraint::Known(b)) => b.is_all(), + }) + } + + fn clear_between( + rows: &[Option], + from: usize, + to: usize, + region: &[ValueSet], + work: &mut Work, + index: &mut RowIndex, + ) -> bool { + let (low, high) = (from.min(to), from.max(to)); + if !work.spend(high - low) + || rows[low + 1..high] + .iter() + .flatten() + .any(|between| between.barrier) + { + return false; + } + let mut visited = 0usize; + let mut clear = true; + let indexed = index.overlapping(region, to.saturating_sub(from), |e| { + visited += 1; + if clear && from < e && e < to { + if let Some(between) = &rows[e] { + clear = !Self::catches(between, region); + } + } + }); + if indexed { + return work.spend(visited) && clear; + } + if !work.spend(to.saturating_sub(from)) { + return false; + } + rows[from + 1..to] + .iter() + .flatten() + .all(|between| !Self::catches(between, region)) + } + + fn fills(row: &Row, id: &Arc) -> bool { + row.rule.get(id).is_some_and(|c| !c.trim().is_empty()) + } + + fn drop_shadowed( + &self, + rows: &mut [Option], + work: &mut Work, + index: &mut RowIndex, + ) -> bool { + if self.0.mode != HitMode::RowFirst { + return false; + } + let mut changed = false; + for inner in 1..rows.len() { + let shadowed = { + let Some(inner_row) = rows[inner].as_ref() else { + continue; + }; + if inner_row.fixed + || self + .0 + .outputs + .iter() + .any(|col| Self::fills(inner_row, &col.id)) + { + continue; + } + let region = Self::region(inner_row); + let mut earlier: Vec = Vec::new(); + let indexed = index.overlapping(®ion, inner, |e| { + if e < inner { + earlier.push(e); + } + }); + if !indexed { + earlier = (0..inner).collect(); + } + if !work.spend(earlier.len()) { + return changed; + } + earlier.iter().any(|&e| { + rows[e] + .as_ref() + .is_some_and(|outer| !outer.fixed && Self::within(inner_row, outer)) + }) + }; + if shadowed { + rows[inner] = None; + changed = true; + } + } + changed + } + + fn absorb(&self, rows: &mut [Option], work: &mut Work, index: &mut RowIndex) -> bool { + let mut buckets: HashMap, Vec> = HashMap::default(); + for (idx, row) in rows.iter().enumerate() { + if let Some(row) = row.as_ref().filter(|r| !r.fixed && !self.collects(r)) { + buckets.entry(self.output_key(row)).or_default().push(idx); + } + } + let mut changed = false; + let mut groups: Vec> = buckets.into_values().filter(|g| g.len() > 1).collect(); + groups.sort_unstable_by_key(|g| g[0]); + let mut group_of: Vec = vec![usize::MAX; rows.len()]; + for (id, group) in groups.iter().enumerate() { + for &row in group { + group_of[row] = id; + } + } + for (id, group) in groups.iter().enumerate() { + for &inner in group { + let Some(inner_row) = rows[inner].as_ref() else { + continue; + }; + let region = Self::region(inner_row); + let mut outers: Vec = Vec::new(); + let indexed = index.overlapping(®ion, group.len(), |e| { + if group_of[e] == id { + outers.push(e); + } + }); + if indexed { + outers.sort_unstable(); + } else { + outers = group.clone(); + } + let mut absorbed = false; + for outer in outers { + if outer == inner { + continue; + } + if !work.spend(inner_row.cells.len()) { + return changed; + } + let Some(outer_row) = rows[outer].as_ref() else { + continue; + }; + if !Self::within(inner_row, outer_row) { + continue; + } + if outer < inner + || Self::clear_between(rows, inner, outer, ®ion, work, index) + { + absorbed = true; + break; + } + } + if absorbed { + rows[inner] = None; + changed = true; + } + } + } + changed + } + + fn merge_column( + &self, + rows: &mut [Option], + col: usize, + work: &mut Work, + index: &mut RowIndex, + ) -> bool { + let mut buckets: HashMap<(Vec, Vec), Vec> = + HashMap::default(); + for (idx, row) in rows.iter().enumerate() { + let Some(row) = row.as_ref().filter(|r| !r.fixed) else { + continue; + }; + if row.cells[col].known_set().is_none() { + continue; + } + if !work.spend(row.cells.len()) { + return false; + } + let others: Vec = row + .cells + .iter() + .enumerate() + .filter(|(i, _)| *i != col) + .map(|(_, cell)| Self::cell_key(cell)) + .collect(); + buckets + .entry((self.output_key(row), others)) + .or_default() + .push(idx); + } + let mut changed = false; + let mut groups: Vec> = buckets.into_values().filter(|g| g.len() > 1).collect(); + groups.sort_unstable_by_key(|g| g[0]); + for group in groups { + let mut keep = group[0]; + for &next in &group[1..] { + if self.merge_into(rows, keep, next, col, work, index) { + changed = true; + } else { + keep = next; + } + if work.remaining == 0 { + return changed; + } + } + } + changed + } + + fn merge_into( + &self, + rows: &mut [Option], + keep: usize, + next: usize, + col: usize, + work: &mut Work, + index: &mut RowIndex, + ) -> bool { + let (Some(keep_row), Some(next_row)) = (rows[keep].as_ref(), rows[next].as_ref()) else { + return false; + }; + if let (false, Some(a), Some(b)) = ( + self.0.inputs[col].dated, + Self::plain(&keep_row.cells[col]), + Self::plain(&next_row.cells[col]), + ) { + if (self.0.mode == HitMode::Collect || self.collects(keep_row)) + && b.iter().any(|key| a.contains(key)) + { + return false; + } + let fresh: Strings = b.iter().filter(|key| !a.contains(key)).cloned().collect(); + if fresh.iter().any(|key| CellText::string(key).is_none()) { + return false; + } + let mut moved = Self::region(next_row); + moved[col] = ValueSet { + strings: StringSet::Finite(fresh.clone()), + ..ValueSet::empty() + }; + if !Self::clear_between(rows, keep, next, &moved, work, index) { + return false; + } + if let Some(row) = rows[keep].as_mut() { + if let CellConstraint::Known(ValueSet { + strings: StringSet::Finite(keys), + .. + }) = &mut row.cells[col] + { + keys.extend(fresh.iter().cloned()); + } + if !row.stale.contains(&col) { + row.stale.push(col); + } + index.insert_strings(col, &fresh, keep); + } + rows[next] = None; + return true; + } + let (Some(a), Some(b)) = ( + keep_row.cells[col].known_set(), + next_row.cells[col].known_set(), + ) else { + return false; + }; + if (self.0.mode == HitMode::Collect || self.collects(keep_row)) && a.intersects(&b) { + return false; + } + let moved: Vec = Self::region(next_row) + .into_iter() + .enumerate() + .map(|(idx, set)| if idx == col { set.difference(&a) } else { set }) + .collect(); + if !Self::clear_between(rows, keep, next, &moved, work, index) { + return false; + } + let union = a.union(&b); + let Some(text) = self + .0 + .cell_text(col, &union, &ValueSet::all(), self.0.inputs[col].dated) + else { + return false; + }; + let id = self.0.inputs[col].id.clone(); + if let Some(row) = rows[keep].as_mut() { + row.rule.insert(id, Arc::from(text.as_str())); + row.stale.retain(|&stale| stale != col); + row.cells[col] = if text.is_empty() { + CellConstraint::Any + } else { + CellConstraint::Known(union) + }; + index.insert(&row.cells, keep); + } + rows[next] = None; + true + } + + fn plain(cell: &CellConstraint) -> Option<&Strings> { + match cell { + CellConstraint::Known(set) + if set.numbers.is_empty() && set.bools == 0 && !set.null && !set.other => + { + match &set.strings { + StringSet::Finite(keys) if !keys.is_empty() => Some(keys), + _ => None, + } + } + _ => None, + } + } +} diff --git a/core/engine/src/analysis/table/missing.rs b/core/engine/src/analysis/table/missing.rs index 2dbbd537..00c35111 100644 --- a/core/engine/src/analysis/table/missing.rs +++ b/core/engine/src/analysis/table/missing.rs @@ -2,29 +2,28 @@ use std::sync::Arc; use std::rc::Rc; -use ahash::HashMap; -use serde_json::{Map, Value}; +use ahash::{HashMap, RandomState}; use zen_expression::intellisense::values::cell::FieldPath; use zen_expression::intellisense::{IntelliSense, ReadDependency}; use super::cell::CellConstraint; +use super::gaps::{Bits, Dense, Gaps, Space}; +use super::intern::Interner; use super::partition::Partition; -use super::print::{CellText, DateDay}; use super::value_set::{NumberSet, StringSet, ValueKind, ValueSet}; -use super::verify::{Finding, GapCase, Region, VerifyTable, MAX_FRAGMENTS}; +use super::verify::{Finding, GapAxis, GapTable, GapValues, VerifyTable}; const GAP_BUDGET: usize = 10_000_000; -const DIRECT_ROWS: usize = 8; -struct Dimension { - columns: Vec, - domain: ValueSet, - path: Option>, - label: Arc, - prefer: Option, - dated: bool, - integer: bool, - input: bool, +pub(super) struct Dimension { + pub(super) columns: Vec, + pub(super) domain: ValueSet, + pub(super) path: Option>, + pub(super) label: Arc, + pub(super) prefer: Option, + pub(super) dated: bool, + pub(super) integer: bool, + pub(super) input: bool, } struct Field { @@ -64,6 +63,127 @@ impl Field { } } +pub(super) enum Pool { + Patterns { + patterns: Interner, + unions: HashMap<(u32, u32), u32>, + joined: Vec, + }, + Sets { + sets: Vec, + index: HashMap<(u64, u32), u32>, + unions: HashMap<(u32, u32), u32>, + }, +} + +impl Pool { + pub(super) fn sets(sets: Vec, index: HashMap<(u64, u32), u32>) -> Self { + Pool::Sets { + sets, + index, + unions: HashMap::default(), + } + } + + fn patterns(patterns: Interner) -> Self { + Pool::Patterns { + patterns, + unions: HashMap::default(), + joined: Vec::new(), + } + } + + fn len(&self) -> usize { + match self { + Pool::Patterns { patterns, .. } => patterns.len(), + Pool::Sets { sets, .. } => sets.len(), + } + } + + fn is_empty(&self, value: u32) -> bool { + match self { + Pool::Patterns { .. } => false, + Pool::Sets { sets, .. } => sets[value as usize].is_empty(), + } + } + + pub(super) fn intern( + sets: &mut Vec, + index: &mut HashMap<(u64, u32), u32>, + set: ValueSet, + ) -> u32 { + let hash = RandomState::with_seeds(11, 13, 17, 19).hash_one(&set); + let mut probe = 0u32; + loop { + match index.get(&(hash, probe)) { + Some(&id) if sets[id as usize] == set => return id, + Some(_) => probe += 1, + None => { + let id = sets.len() as u32; + index.insert((hash, probe), id); + sets.push(set); + return id; + } + } + } + } + + fn union(&mut self, a: u32, b: u32) -> u32 { + match self { + Pool::Patterns { + patterns, + unions, + joined, + } => { + if let Some(&id) = unions.get(&(a, b)) { + return id; + } + joined.clear(); + joined.extend( + patterns + .get(a) + .iter() + .zip(patterns.get(b)) + .map(|(left, right)| left | right), + ); + let id = patterns.intern(joined); + unions.insert((a, b), id); + id + } + Pool::Sets { + sets, + index, + unions, + } => { + if let Some(&id) = unions.get(&(a, b)) { + return id; + } + let joined = sets[a as usize].union(&sets[b as usize]); + let id = Self::intern(sets, index, joined); + unions.insert((a, b), id); + id + } + } + } + + fn keep(self, used: &[u32]) -> GapValues { + match self { + Pool::Patterns { patterns, .. } => GapValues::Patterns { + words: patterns.stride(), + data: used + .iter() + .flat_map(|&value| patterns.get(value).iter().copied()) + .collect(), + }, + Pool::Sets { mut sets, .. } => GapValues::Sets( + used.iter() + .map(|&value| std::mem::take(&mut sets[value as usize])) + .collect(), + ), + } + } +} + impl VerifyTable<'_> { pub(super) fn missing( &self, @@ -78,60 +198,226 @@ impl VerifyTable<'_> { if dims.is_empty() || dims.iter().any(|d| d.domain.is_empty()) { return Some(None); } - let cuts: Vec = cells + match self.missing_dense(dims, cells, satisfiable) { + Err(dims) => self.missing_sets(dims, cells, satisfiable), + Ok(found) => { + #[cfg(test)] + { + let cases = |found: &Option>| match found { + Some(Some(Finding::MissingCases { cases, total })) => { + Some(Some((cases.cases().collect::>(), *total))) + } + Some(_) => Some(None), + None => None, + }; + let expected = + self.missing_sets(self.dimensions(is, cells), cells, satisfiable); + assert_eq!( + cases(&found), + cases(&expected), + "gap analysis diverged between the dense and set-based paths" + ); + } + found + } + } + } + + fn gap_axis(&self, dim: Dimension, atoms: Vec, values: GapValues) -> GapAxis { + let first = dim.columns.first().map(|&first| &self.inputs[first]); + GapAxis { + label: dim.label, + column: first.map(|input| input.id.clone()), + subject: first + .and_then(|input| input.subject.as_ref()) + .map(|subject| subject.join(".")), + path: dim.path, + input: dim.input, + dated: dim.dated, + prefer: dim.prefer, + domain: dim.domain, + atoms, + values, + } + } + + fn missing_dense( + &self, + dims: Vec, + cells: &[Vec], + satisfiable: &[bool], + ) -> Result>, Vec> { + let rows: Vec<&Vec> = cells .iter() .zip(satisfiable) .filter(|(_, satisfiable)| **satisfiable) - .map(|(row_cells, _)| { - dims.iter() - .map(|d| { - d.columns - .iter() - .fold(ValueSet::all(), |acc, &col| match &row_cells[col] { + .map(|(row_cells, _)| row_cells) + .collect(); + + let atoms = dims.iter().map(|dim| { + let mentioned = rows.iter().flat_map(|row_cells| { + dim.columns.iter().filter_map(|&col| match &row_cells[col] { + CellConstraint::Known(set) => Some(set), + _ => None, + }) + }); + Dense::atoms(mentioned.chain(std::iter::once(&dim.domain))) + }); + if !Dense::fits(rows.len(), atoms) { + return Err(dims); + } + + let mut cut_of_row: Vec> = Vec::with_capacity(dims.len()); + let mut cut_sets: Vec> = Vec::with_capacity(dims.len()); + for dim in &dims { + let mut index: HashMap = HashMap::default(); + let mut distinct: Vec = Vec::new(); + let of_row: Vec = rows + .iter() + .map(|row_cells| { + let cut = + dim.columns.iter().fold(ValueSet::all(), |acc, &col| { + match &row_cells[col] { CellConstraint::Known(set) => acc.intersect(set), _ => acc, - }) - }) - .collect() - }) - .collect(); - let mut gaps = Gaps { - cuts: &cuts, - work: GAP_BUDGET, - out: Vec::new(), - }; - gaps.uncovered( - dims.iter().map(|d| d.domain.clone()).collect(), - (0..cuts.len()).collect(), - )?; - let remaining: Vec = gaps - .out - .into_iter() - .filter_map(|mut fragment| { - for (dim, set) in dims.iter().zip(fragment.iter_mut()) { - if dim.integer { - set.numbers = set.numbers.integral(); + } + }); + match index.get(&cut) { + Some(&id) => id, + None => { + let id = distinct.len() as u32; + index.insert(cut.clone(), id); + distinct.push(cut); + id + } } - } - fragment - .iter() - .all(|set| !set.is_empty()) - .then_some(fragment) - }) - .collect(); - if remaining.is_empty() { - return Some(None); + }) + .collect(); + distinct.push(dim.domain.clone()); + cut_of_row.push(of_row); + cut_sets.push(distinct); } - let remaining = Self::merge(remaining); - let total = remaining.len(); - let cases = remaining - .iter() - .map(|fragment| self.case(&dims, fragment)) - .collect(); - Some(Some(Finding::MissingCases { cases, total })) + let mut partitions: Vec = Vec::with_capacity(dims.len()); + let mut cut_atoms: Vec>> = Vec::with_capacity(dims.len()); + for (dim, sets) in dims.iter().zip(&cut_sets) { + let partition = Partition::new(&dim.domain, sets); + cut_atoms.push( + sets[..sets.len() - 1] + .iter() + .map(|cut| partition.touching(cut)) + .collect(), + ); + partitions.push(partition); + } + drop(cut_sets); + + let space = Space::new(partitions.iter().map(Partition::layout).collect()); + let stride = space.stride(); + let mut cuts = vec![0u64; rows.len() * stride]; + for ((axis, of_row), atoms) in space.axes().iter().zip(&cut_of_row).zip(&cut_atoms) { + for (row, &id) in of_row.iter().enumerate() { + let start = row * stride; + let words = &mut cuts[start..start + stride][axis.range()]; + atoms[id as usize] + .iter() + .for_each(|&atom| Bits::set(words, atom)); + } + } + drop(cut_of_row); + drop(cut_atoms); + + let Some(found) = Gaps::new(&space, &cuts, GAP_BUDGET).run(rows.len()) else { + return Ok(None); + }; + drop(cuts); + + let width = dims.len(); + let mut pools: Vec = Vec::with_capacity(width); + let mut value_of: Vec>> = Vec::with_capacity(width); + for ((dim, partition), patterns) in dims.iter().zip(&partitions).zip(found.patterns) { + if !dim.integer { + pools.push(Pool::patterns(patterns)); + value_of.push(None); + continue; + } + let mut sets: Vec = Vec::new(); + let mut index: HashMap<(u64, u32), u32> = HashMap::default(); + let atoms = partition.atoms(); + let values = (0..patterns.len() as u32) + .map(|pattern| { + let mut set = Partition::union( + Bits::ones(patterns.get(pattern)).map(|atom| &atoms[atom]), + ); + set.numbers = set.numbers.integral(); + Pool::intern(&mut sets, &mut index, set) + }) + .collect(); + pools.push(Pool::sets(sets, index)); + value_of.push(Some(values)); + } + + let mut remaining: Vec = Vec::with_capacity(found.fragments.len()); + for fragment in found.fragments.chunks_exact(width) { + let start = remaining.len(); + remaining.extend(fragment.iter().zip(&value_of).map( + |(&pattern, values)| match values { + Some(values) => values[pattern as usize], + None => pattern, + }, + )); + let empty = remaining[start..] + .iter() + .zip(&pools) + .any(|(&value, pool)| pool.is_empty(value)); + if empty { + remaining.truncate(start); + } + } + drop(found.fragments); + drop(value_of); + if remaining.is_empty() { + return Ok(Some(None)); + } + + let atoms = partitions.into_iter().map(Partition::into_atoms).collect(); + Ok(Some(Some( + self.missing_cases_of(dims, atoms, pools, remaining), + ))) } - fn dimensions(&self, is: &mut IntelliSense, cells: &[Vec]) -> Vec { + pub(super) fn missing_cases_of( + &self, + dims: Vec, + atoms: Vec>, + mut pools: Vec, + remaining: Vec, + ) -> Finding { + let width = dims.len(); + let mut rows = Self::merge(remaining, &mut pools); + let total = rows.len() / width; + let mut axes: Vec = Vec::with_capacity(width); + for (index, ((dim, atoms), pool)) in dims.into_iter().zip(atoms).zip(pools).enumerate() { + let mut renamed = vec![u32::MAX; pool.len()]; + let mut used: Vec = Vec::new(); + for row in rows.chunks_exact_mut(width) { + let value = row[index] as usize; + if renamed[value] == u32::MAX { + renamed[value] = used.len() as u32; + used.push(value as u32); + } + row[index] = renamed[value]; + } + axes.push(self.gap_axis(dim, atoms, pool.keep(&used))); + } + let cases = Rc::new(GapTable { axes, rows }); + Finding::MissingCases { cases, total } + } + + pub(super) fn dimensions( + &self, + is: &mut IntelliSense, + cells: &[Vec], + ) -> Vec { let fields: Vec> = self .inputs .iter() @@ -214,30 +500,28 @@ impl VerifyTable<'_> { (!domain.is_empty()).then_some(domain) } - fn merge(mut fragments: Vec) -> Vec { - let dims = fragments.first().map_or(0, Vec::len); + fn merge(mut fragments: Vec, pools: &mut [Pool]) -> Vec { + let width = pools.len(); + let mut keys: Interner = Interner::new(width - 1); + let mut key: Vec = Vec::with_capacity(width); loop { let mut changed = false; - for dim in (0..dims).rev() { - let mut buckets: HashMap, usize> = HashMap::default(); - let mut merged: Vec = Vec::with_capacity(fragments.len()); - for fragment in fragments.drain(..) { - let key: Vec = fragment - .iter() - .enumerate() - .filter(|(idx, _)| *idx != dim) - .map(|(_, set)| set.clone()) - .collect(); - match buckets.get(&key) { - Some(&idx) => { - merged[idx][dim] = merged[idx][dim].union(&fragment[dim]); - changed = true; - } - None => { - buckets.insert(key, merged.len()); - merged.push(fragment); - } + for dim in (0..width).rev() { + keys.reset(width - 1); + let mut merged: Vec = Vec::with_capacity(fragments.len()); + for fragment in fragments.chunks_exact(width) { + key.clear(); + key.extend_from_slice(&fragment[..dim]); + key.extend_from_slice(&fragment[dim + 1..]); + let known = keys.len() as u32; + let slot = keys.intern(&key) as usize; + if slot as u32 == known { + merged.extend_from_slice(fragment); + continue; } + let at = slot * width + dim; + merged[at] = pools[dim].union(merged[at], fragment[dim]); + changed = true; } fragments = merged; } @@ -246,200 +530,4 @@ impl VerifyTable<'_> { } } } - - fn case(&self, dims: &[Dimension], fragment: &Region) -> GapCase { - let mut parts = Vec::new(); - let mut cells = Some(Vec::new()); - let mut example = Some(Map::new()); - for (dim, set) in dims.iter().zip(fragment) { - match CellText::of(set, &dim.domain, dim.dated) { - Some(text) if text.is_empty() => continue, - Some(text) => { - if !dim.input { - example = None; - } - if let (Some(list), Some(&first)) = (cells.as_mut(), dim.columns.first()) { - match self.cell_text(first, set, &dim.domain, dim.dated) { - Some(cell) => list.push((self.inputs[first].id.clone(), cell)), - None => cells = None, - } - } - parts.push((dim.label.clone(), text)); - } - None => { - cells = None; - parts.push((dim.label.clone(), "…".to_string())); - } - } - let value = match dim.dated { - true => DateDay::example(set), - false => set.example(dim.prefer), - }; - match (&dim.path, value, example.as_mut()) { - (Some(path), Some(value), Some(root)) => Self::insert(root, path, value), - _ => example = None, - } - } - GapCase { - parts, - cells, - example: example.filter(|root| !root.is_empty()).map(Value::Object), - } - } -} - -type Atoms = Vec<(ValueSet, Vec)>; - -struct Split { - dim: usize, - score: usize, - groups: Atoms, - of_row: Vec, - distinct: usize, -} - -struct Gaps<'c> { - cuts: &'c [Region], - work: usize, - out: Vec, -} - -impl Gaps<'_> { - fn spend(&mut self, amount: usize) -> Option<()> { - self.work = self.work.checked_sub(amount.max(1))?; - Some(()) - } - - fn uncovered(&mut self, region: Region, rows: Vec) -> Option<()> { - self.spend(rows.len() * region.len())?; - let rows: Vec = rows - .into_iter() - .filter(|&row| { - self.cuts[row] - .iter() - .zip(®ion) - .all(|(cut, set)| cut.intersects(set)) - }) - .collect(); - if rows.is_empty() { - self.out.push(region); - return Some(()); - } - let covered = rows.iter().any(|&row| { - region - .iter() - .zip(&self.cuts[row]) - .all(|(set, cut)| set.is_subset(cut)) - }); - if covered { - return Some(()); - } - if rows.len() > DIRECT_ROWS { - if let Some((dim, atoms)) = self.split(®ion, &rows) { - for (atom, atom_rows) in atoms { - let mut piece = region.clone(); - piece[dim] = atom; - self.uncovered(piece, atom_rows)?; - } - return Some(()); - } - } - self.subtract_all(region, &rows) - } - - fn subtract_all(&mut self, region: Region, rows: &[usize]) -> Option<()> { - let mut remaining = vec![region]; - let cuts = self.cuts; - for &row in rows { - let cut: Vec<&ValueSet> = cuts[row].iter().collect(); - let mut next = Vec::with_capacity(remaining.len()); - for fragment in remaining { - self.spend(fragment.len())?; - match VerifyTable::subtract(&fragment, &cut) { - Some(pieces) => next.extend(pieces), - None => next.push(fragment), - } - } - if next.len() > MAX_FRAGMENTS { - return None; - } - remaining = next; - if remaining.is_empty() { - return Some(()); - } - } - self.out.extend(remaining); - Some(()) - } - - fn split(&mut self, region: &Region, rows: &[usize]) -> Option<(usize, Atoms)> { - let mut best: Option = None; - for (dim, bounds) in region.iter().enumerate() { - let mut sets: Vec = Vec::new(); - let mut index: HashMap = HashMap::default(); - let mut of_row: Vec = Vec::with_capacity(rows.len()); - for &row in rows { - let set = self.cuts[row][dim].intersect(bounds); - let next = sets.len(); - let slot = *index.entry(set.clone()).or_insert(next); - if slot == next { - sets.push(set); - } - of_row.push(slot); - } - if sets.iter().all(|set| set == bounds) { - continue; - } - let partition = Partition::new(bounds, &sets); - if partition.touches(&sets) > self.work { - return None; - } - let groups = partition.groups(&sets); - if groups.len() < 2 { - continue; - } - let mut count = vec![0usize; sets.len()]; - for &slot in &of_row { - count[slot] += 1; - } - let score: usize = groups - .iter() - .map(|(_, ids)| ids.iter().map(|&id| count[id]).sum::()) - .sum(); - self.spend(score + groups.len())?; - if best.as_ref().is_none_or(|split| score < split.score) { - best = Some(Split { - dim, - score, - groups, - of_row, - distinct: sets.len(), - }); - } - } - let Split { - dim, - groups, - of_row, - distinct, - .. - } = best?; - let split = groups - .into_iter() - .map(|(atom, ids)| { - let mut touching = vec![false; distinct]; - for id in ids { - touching[id] = true; - } - let atom_rows = rows - .iter() - .zip(&of_row) - .filter(|(_, slot)| touching[**slot]) - .map(|(&row, _)| row) - .collect(); - (atom, atom_rows) - }) - .collect(); - Some((dim, split)) - } } diff --git a/core/engine/src/analysis/table/mod.rs b/core/engine/src/analysis/table/mod.rs index 984c411d..57f781b0 100644 --- a/core/engine/src/analysis/table/mod.rs +++ b/core/engine/src/analysis/table/mod.rs @@ -1,9 +1,17 @@ mod cache; mod constraints; +mod cover; +mod gaps; mod index; +mod intern; mod merge; +#[cfg(test)] +mod merge_reference; mod missing; mod partition; +mod sets; +#[cfg(test)] +mod tests; mod verify; mod witness; @@ -26,8 +34,11 @@ use serde_json::{Map, Value}; pub(crate) use value_set::ValueSet; use print::CellText; +use std::fmt::Write as _; +use std::rc::Rc; use value_set::StringSet; -use verify::{Finding, GapCase}; + +use verify::{Finding, GapCase, GapTable}; pub(crate) struct TableColumn; @@ -412,7 +423,7 @@ impl VerifyTable<'_> { } fn missing_cases( - cases: Vec, + cases: Rc, total: usize, location: &impl Fn(Option>) -> DiagnosticLocation, ) -> Diagnostic { @@ -426,40 +437,45 @@ impl VerifyTable<'_> { .collect::>() .join(" and ") }; - let descriptions: Vec = cases.iter().map(describe).collect(); - let shown: Vec = descriptions.iter().take(5).cloned().collect(); + let mut shown: Vec = Vec::with_capacity(5); + let mut json_cases = String::from("["); + for (index, case) in cases.cases().enumerate() { + let description = describe(&case); + if index < 5 { + shown.push(description.clone()); + } + let mut entry = Map::new(); + entry.insert("description".into(), Value::String(description)); + if let Some(cells) = case.cells { + let cells: Map = cells + .into_iter() + .map(|(col, text)| (col.to_string(), Value::String(text))) + .collect(); + entry.insert("cells".into(), Value::Object(cells)); + } + if let Some(example) = case.example { + entry.insert("example".into(), example); + } + if index > 0 { + json_cases.push(','); + } + let _ = write!(json_cases, "{}", Value::Object(entry)); + } + json_cases.push(']'); + json_cases.shrink_to_fit(); let more = total.saturating_sub(shown.len()); let noun = if total == 1 { "case" } else { "cases" }; let mut message = format!("no row matches {total} input {noun}: {}", shown.join("; ")); if more > 0 { message.push_str(&format!("; and {more} more")); } - let json_cases: Vec = cases - .iter() - .zip(&descriptions) - .map(|(case, description)| { - let mut entry = Map::new(); - entry.insert("description".into(), Value::String(description.clone())); - if let Some(cells) = &case.cells { - let cells: Map = cells - .iter() - .map(|(col, text)| (col.to_string(), Value::String(text.clone()))) - .collect(); - entry.insert("cells".into(), Value::Object(cells)); - } - if let Some(example) = &case.example { - entry.insert("example".into(), example.clone()); - } - Value::Object(entry) - }) - .collect(); let mut diagnostic = Diagnostic::hint(DiagnosticCode::MissingCases, location(None), message); diagnostic.args = DiagnosticArgs::from([ ("count", total.to_string()), ("shown", shown.join("; ")), ("more", more.to_string()), - ("cases", Value::Array(json_cases).to_string()), + ("cases", json_cases), ]); diagnostic } diff --git a/core/engine/src/analysis/table/partition.rs b/core/engine/src/analysis/table/partition.rs index d2e5bdd4..ac1166bb 100644 --- a/core/engine/src/analysis/table/partition.rs +++ b/core/engine/src/analysis/table/partition.rs @@ -4,7 +4,7 @@ use std::rc::Rc; use ahash::HashMap; use rust_decimal::Decimal; -use super::value_set::{Bound, Interval, NumberSet, StringSet, ValueSet}; +use super::value_set::{Bound, Interval, NumberSet, StringSet, Strings, ValueSet}; pub(super) struct Points(Vec); @@ -93,7 +93,44 @@ pub(super) struct Partition { other: Option, } +pub(super) struct Layout { + pub(super) atoms: usize, + pub(super) strings: usize, + pub(super) rest: Option, + pub(super) numbers: std::ops::Range, + pub(super) piece_of: Vec, + pub(super) last_piece: u32, +} + impl Partition { + pub(super) fn layout(&self) -> Layout { + let piece_of: Vec = self + .pieces + .iter() + .enumerate() + .filter(|(_, atom)| atom.is_some()) + .map(|(piece, _)| piece as u32) + .collect(); + let strings = self.strings.len(); + let start = strings + usize::from(self.string_rest.is_some()); + Layout { + atoms: self.atoms.len(), + strings, + rest: self.string_rest, + numbers: start..start + piece_of.len(), + piece_of, + last_piece: self.pieces.len().saturating_sub(1) as u32, + } + } + + pub(super) fn atoms(&self) -> &[ValueSet] { + &self.atoms + } + + pub(super) fn into_atoms(self) -> Vec { + self.atoms + } + pub(super) fn touches(&self, sets: &[ValueSet]) -> usize { let mut present = Vec::with_capacity(self.pieces.len() + 1); present.push(0usize); @@ -179,7 +216,7 @@ impl Partition { } } for key in keys { - let single = StringSet::Finite(BTreeSet::from([key.clone()])); + let single = StringSet::Finite(Strings::one(key.clone())); if !region.strings.intersect(&single).is_empty() { partition.strings.insert(key, partition.atoms.len()); partition.atoms.push(ValueSet { @@ -231,7 +268,7 @@ impl Partition { partition } - fn touching(&self, set: &ValueSet) -> Vec { + pub(super) fn touching(&self, set: &ValueSet) -> Vec { let mut out = Vec::new(); match &set.strings { StringSet::Finite(keys) => out.extend(keys.iter().filter_map(|k| self.strings.get(k))), @@ -239,7 +276,7 @@ impl Partition { out.extend( self.strings .iter() - .filter(|(k, _)| !excluded.contains(*k)) + .filter(|(k, _)| !excluded.contains(k)) .map(|(_, &a)| a), ); out.extend(self.string_rest); @@ -264,7 +301,7 @@ impl Partition { out } - fn union<'a>(atoms: impl Iterator) -> ValueSet { + pub(super) fn union<'a>(atoms: impl Iterator) -> ValueSet { let mut strings: BTreeSet> = BTreeSet::new(); let mut rest: Option = None; let mut intervals: Vec = Vec::new(); @@ -280,8 +317,8 @@ impl Partition { out.other |= atom.other; } out.strings = match rest { - Some(rest) => rest.union(&StringSet::Finite(strings)), - None => StringSet::Finite(strings), + Some(rest) => rest.union(&StringSet::Finite(strings.into())), + None => StringSet::Finite(strings.into()), }; out.numbers = NumberSet::from_intervals(intervals); out diff --git a/core/engine/src/analysis/table/sets.rs b/core/engine/src/analysis/table/sets.rs new file mode 100644 index 00000000..4463f0d5 --- /dev/null +++ b/core/engine/src/analysis/table/sets.rs @@ -0,0 +1,245 @@ +use ahash::HashMap; + +use super::cell::CellConstraint; +use super::missing::{Dimension, Pool}; +use super::partition::Partition; +use super::value_set::ValueSet; +use super::verify::{Finding, Region, VerifyTable, MAX_FRAGMENTS}; + +const GAP_BUDGET: usize = 10_000_000; +const DIRECT_ROWS: usize = 8; + +impl VerifyTable<'_> { + pub(super) fn missing_sets( + &self, + dims: Vec, + cells: &[Vec], + satisfiable: &[bool], + ) -> Option> { + let cuts: Vec = cells + .iter() + .zip(satisfiable) + .filter(|(_, satisfiable)| **satisfiable) + .map(|(row_cells, _)| { + dims.iter() + .map(|d| { + d.columns + .iter() + .fold(ValueSet::all(), |acc, &col| match &row_cells[col] { + CellConstraint::Known(set) => acc.intersect(set), + _ => acc, + }) + }) + .collect() + }) + .collect(); + let mut gaps = Gaps { + cuts: &cuts, + work: GAP_BUDGET, + out: Vec::new(), + }; + gaps.uncovered( + dims.iter().map(|d| d.domain.clone()).collect(), + (0..cuts.len()).collect(), + )?; + let remaining: Vec = gaps + .out + .into_iter() + .filter_map(|mut fragment| { + for (dim, set) in dims.iter().zip(fragment.iter_mut()) { + if dim.integer { + set.numbers = set.numbers.integral(); + } + } + fragment + .iter() + .all(|set| !set.is_empty()) + .then_some(fragment) + }) + .collect(); + drop(cuts); + if remaining.is_empty() { + return Some(None); + } + let mut values: Vec> = dims.iter().map(|_| Vec::new()).collect(); + let mut indexes: Vec> = + dims.iter().map(|_| HashMap::default()).collect(); + let mut rows: Vec = Vec::with_capacity(remaining.len() * dims.len()); + for fragment in remaining { + for ((set, sets), index) in fragment.into_iter().zip(&mut values).zip(&mut indexes) { + rows.push(Pool::intern(sets, index, set)); + } + } + let atoms = dims.iter().map(|_| Vec::new()).collect(); + let pools = values + .into_iter() + .zip(indexes) + .map(|(sets, index)| Pool::sets(sets, index)) + .collect(); + Some(Some(self.missing_cases_of(dims, atoms, pools, rows))) + } +} + +type Atoms = Vec<(ValueSet, Vec)>; + +struct Split { + dim: usize, + score: usize, + groups: Atoms, + of_row: Vec, + distinct: usize, +} + +struct Gaps<'c> { + cuts: &'c [Region], + work: usize, + out: Vec, +} + +impl Gaps<'_> { + fn spend(&mut self, amount: usize) -> Option<()> { + self.work = self.work.checked_sub(amount.max(1))?; + Some(()) + } + + fn uncovered(&mut self, region: Region, rows: Vec) -> Option<()> { + self.spend(rows.len() * region.len())?; + let rows: Vec = rows + .into_iter() + .filter(|&row| { + self.cuts[row] + .iter() + .zip(®ion) + .all(|(cut, set)| cut.intersects(set)) + }) + .collect(); + if rows.is_empty() { + self.out.push(region); + return Some(()); + } + let covered = rows.iter().any(|&row| { + region + .iter() + .zip(&self.cuts[row]) + .all(|(set, cut)| set.is_subset(cut)) + }); + if covered { + return Some(()); + } + if rows.len() > DIRECT_ROWS { + if let Some((dim, atoms)) = self.split(®ion, &rows) { + for (atom, atom_rows) in atoms { + let mut piece = region.clone(); + piece[dim] = atom; + self.uncovered(piece, atom_rows)?; + } + return Some(()); + } + } + self.subtract_all(region, &rows) + } + + fn subtract_all(&mut self, region: Region, rows: &[usize]) -> Option<()> { + let mut remaining = vec![region]; + let cuts = self.cuts; + for &row in rows { + let cut: Vec<&ValueSet> = cuts[row].iter().collect(); + let mut next = Vec::with_capacity(remaining.len()); + for fragment in remaining { + self.spend(fragment.len())?; + match VerifyTable::subtract(&fragment, &cut) { + Some(pieces) => next.extend(pieces), + None => next.push(fragment), + } + } + if next.len() > MAX_FRAGMENTS { + return None; + } + remaining = next; + if remaining.is_empty() { + return Some(()); + } + } + self.out.extend(remaining); + Some(()) + } + + fn split(&mut self, region: &Region, rows: &[usize]) -> Option<(usize, Atoms)> { + let mut best: Option = None; + for (dim, bounds) in region.iter().enumerate() { + let mut sets: Vec = Vec::new(); + let mut index: HashMap = HashMap::default(); + let mut of_row: Vec = Vec::with_capacity(rows.len()); + for &row in rows { + let set = self.cuts[row][dim].intersect(bounds); + let next = sets.len(); + let slot = *index.entry(set.clone()).or_insert(next); + if slot == next { + sets.push(set); + } + of_row.push(slot); + } + if sets.iter().all(|set| set == bounds) { + continue; + } + let partition = Partition::new(bounds, &sets); + if partition.touches(&sets) > self.work { + return None; + } + let groups = partition.groups(&sets); + if groups.len() < 2 { + continue; + } + let mut count = vec![0usize; sets.len()]; + for &slot in &of_row { + count[slot] += 1; + } + let score: usize = groups + .iter() + .map(|(_, ids)| ids.iter().map(|&id| count[id]).sum::()) + .sum(); + self.spend(score + groups.len())?; + if best.as_ref().is_none_or(|split| score < split.score) { + best = Some(Split { + dim, + score, + groups, + of_row, + distinct: sets.len(), + }); + } + } + let Split { + dim, + groups, + of_row, + distinct, + .. + } = best?; + let mut starts = vec![0usize; distinct + 1]; + for &slot in &of_row { + starts[slot + 1] += 1; + } + for slot in 0..distinct { + starts[slot + 1] += starts[slot]; + } + let mut cursor = starts.clone(); + let mut by_slot = vec![0usize; rows.len()]; + for (&row, &slot) in rows.iter().zip(&of_row) { + by_slot[cursor[slot]] = row; + cursor[slot] += 1; + } + let split = groups + .into_iter() + .map(|(atom, ids)| { + let mut atom_rows: Vec = ids + .into_iter() + .flat_map(|id| by_slot[starts[id]..starts[id + 1]].iter().copied()) + .collect(); + atom_rows.sort_unstable(); + (atom, atom_rows) + }) + .collect(); + Some((dim, split)) + } +} diff --git a/core/engine/src/analysis/table/tests.rs b/core/engine/src/analysis/table/tests.rs new file mode 100644 index 00000000..c24b497e --- /dev/null +++ b/core/engine/src/analysis/table/tests.rs @@ -0,0 +1,315 @@ +use serde_json::{json, Map, Value}; + +use crate::model::DecisionContent; +use crate::policy::{DiagnosticCode, Workspace}; + +struct Rng(u64); + +impl Rng { + fn next(&mut self) -> u64 { + self.0 ^= self.0 << 13; + self.0 ^= self.0 >> 7; + self.0 ^= self.0 << 17; + self.0 + } + + fn below(&mut self, bound: usize) -> usize { + (self.next() % bound as u64) as usize + } + + fn chance(&mut self, percent: usize) -> bool { + self.below(100) < percent + } + + fn pick<'a, T>(&mut self, items: &'a [T]) -> &'a T { + &items[self.below(items.len())] + } +} + +#[derive(Clone, Copy, PartialEq)] +enum Kind { + Number, + Integer, + Text, + Choice, + Flag, + Untyped, +} + +const KINDS: [Kind; 6] = [ + Kind::Number, + Kind::Integer, + Kind::Text, + Kind::Choice, + Kind::Flag, + Kind::Untyped, +]; +const WORDS: [&str; 6] = ["red", "green", "blue", "amber", "teal", "plum"]; +const POINTS: [&str; 9] = ["0", "5", "10", "12.5", "20", "25", "40", "60", "100"]; + +fn number_cell(rng: &mut Rng) -> String { + let a = *rng.pick(&POINTS); + let b = *rng.pick(&POINTS); + match rng.below(16) { + 0 | 1 => String::new(), + 2 => format!("> {a}"), + 3 => format!(">= {a}"), + 4 => format!("< {a}"), + 5 => format!("<= {a}"), + 6 => format!("[{a}..{b}]"), + 7 => format!("[{a}..{b})"), + 8 => format!("({a}..{b}]"), + 9 => a.to_string(), + 10 => format!("{a}, {b}"), + 11 => format!("< {a}, > {b}"), + 12 => format!("!= {a}"), + 13 => format!(">= {a} and < {b}"), + 14 => format!("not in [{a}, {b}]"), + _ => "null".to_string(), + } +} + +fn text_cell(rng: &mut Rng) -> String { + let a = *rng.pick(&WORDS); + let b = *rng.pick(&WORDS); + match rng.below(9) { + 0 | 1 => String::new(), + 2 | 3 => format!("\"{a}\""), + 4 => format!("\"{a}\", \"{b}\""), + 5 => format!("not in [\"{a}\", \"{b}\"]"), + 6 => format!("!= \"{a}\""), + 7 => "null".to_string(), + _ => "len($) > 3".to_string(), + } +} + +fn flag_cell(rng: &mut Rng) -> String { + match rng.below(5) { + 0 => String::new(), + 1 | 2 => "true".to_string(), + 3 => "false".to_string(), + _ => "true, false".to_string(), + } +} + +fn cell(rng: &mut Rng, kind: Kind) -> String { + match kind { + Kind::Number | Kind::Integer => number_cell(rng), + Kind::Text | Kind::Choice => text_cell(rng), + Kind::Flag => flag_cell(rng), + Kind::Untyped => match rng.below(3) { + 0 => number_cell(rng), + 1 => text_cell(rng), + _ => flag_cell(rng), + }, + } +} + +fn schema_of(kind: Kind, nullable: bool) -> Option { + let typed = |name: &str| match nullable { + true => json!({ "type": [name, "null"] }), + false => json!({ "type": name }), + }; + match kind { + Kind::Number => Some(typed("number")), + Kind::Integer => Some(typed("integer")), + Kind::Text => Some(typed("string")), + Kind::Choice => Some(json!({ "enum": WORDS[..4] })), + Kind::Flag => Some(typed("boolean")), + Kind::Untyped => None, + } +} + +fn random_graph(rng: &mut Rng, rows: usize, columns: usize) -> DecisionContent { + let kinds: Vec = (0..columns).map(|_| *rng.pick(&KINDS)).collect(); + let shared = columns > 1 && rng.chance(15); + let mut properties = Map::new(); + let mut required = Vec::new(); + let mut inputs = Vec::new(); + for (index, kind) in kinds.iter().enumerate() { + let field = match shared && index == columns - 1 { + true => "f0".to_string(), + false => format!("f{index}"), + }; + let kind = match shared && index == columns - 1 { + true => kinds[0], + false => *kind, + }; + if let Some(schema) = schema_of(kind, rng.chance(20)) { + properties.entry(field.clone()).or_insert(schema); + if rng.chance(80) && !required.contains(&json!(field)) { + required.push(json!(field)); + } + } + inputs.push( + json!({ "id": format!("c{index}"), "name": format!("Column {index}"), "field": field }), + ); + } + let schema = json!({ "type": "object", "properties": properties, "required": required }); + let collect = rng.chance(15); + let rules: Vec = (0..rows) + .map(|row| { + let mut rule = Map::new(); + rule.insert("_id".into(), json!(format!("r{row}"))); + for (index, kind) in kinds.iter().enumerate() { + let kind = match shared && index == columns - 1 { + true => kinds[0], + false => *kind, + }; + rule.insert(format!("c{index}"), json!(cell(rng, kind))); + } + rule.insert("o".into(), json!(format!("{}", rng.below(4)))); + Value::Object(rule) + }) + .collect(); + serde_json::from_value(json!({ + "nodes": [ + { "id": "in", "name": "request", "type": "inputNode", "content": { "schema": schema.to_string() } }, + { "id": "dt", "name": "table", "type": "decisionTableNode", "content": { + "hitPolicy": if collect { "collect" } else { "first" }, + "inputs": inputs, + "outputs": [ { "id": "o", "name": "Out", "field": "out" } ], + "rules": rules, + "passThrough": true + } }, + { "id": "out", "name": "out", "type": "outputNode", "content": {} } + ], + "edges": [ + { "id": "e1", "sourceId": "in", "targetId": "dt" }, + { "id": "e2", "sourceId": "dt", "targetId": "out" } + ] + })) + .expect("graph") +} + +struct Reported { + missing: bool, + incomplete: bool, + compressible: bool, + unreachable: bool, +} + +fn reported(content: DecisionContent) -> Reported { + let mut workspace = Workspace::new(); + workspace.set_document("g", content); + let diagnostics = workspace.diagnostics("g"); + let has = |code: DiagnosticCode| diagnostics.iter().any(|d| d.code == code); + Reported { + missing: has(DiagnosticCode::MissingCases), + incomplete: has(DiagnosticCode::TableChecksIncomplete), + compressible: has(DiagnosticCode::CompressibleTable), + unreachable: has(DiagnosticCode::UnreachableRule), + } +} + +#[test] +fn table_checks_match_the_reference_on_random_tables() { + let mut rng = Rng(0x5EED_1234_ABCD_0001); + let mut with_gaps = 0; + let mut compressible = 0; + let mut unreachable = 0; + let mut split = 0; + for round in 0..1500 { + let rows = match round % 10 { + 0 => 1 + rng.below(8), + 9 => 60 + rng.below(240), + _ => 9 + rng.below(50), + }; + let columns = 1 + rng.below(5); + let found = reported(random_graph(&mut rng, rows, columns)); + with_gaps += usize::from(found.missing); + compressible += usize::from(found.compressible); + unreachable += usize::from(found.unreachable); + split += usize::from(rows > 8); + } + assert!(with_gaps > 300, "only {with_gaps} tables reported gaps"); + assert!( + compressible > 200, + "only {compressible} tables were compressible" + ); + assert!( + unreachable > 200, + "only {unreachable} tables had unreachable rows" + ); + assert!(split > 1000, "only {split} tables reached the split path"); +} + +fn range_heavy(rng: &mut Rng, rows: usize, columns: usize) -> DecisionContent { + let mut properties = Map::new(); + let inputs: Vec = (0..columns) + .map(|index| { + properties.insert(format!("n{index}"), json!({ "type": "number" })); + json!({ "id": format!("c{index}"), "name": format!("N{index}"), "field": format!("n{index}") }) + }) + .collect(); + let required: Vec = properties.keys().cloned().collect(); + let schema = json!({ "type": "object", "properties": properties, "required": required }); + let rules: Vec = (0..rows) + .map(|row| { + let mut rule = Map::new(); + rule.insert("_id".into(), json!(format!("r{row}"))); + for index in 0..columns { + let step = [1usize, 5, 10, 50, 100, 500][index % 6]; + let low = rng.below(60) * step; + let high = low + (1 + rng.below(6)) * step; + let cell = match rng.below(5) { + 0 => format!("[{low}..{high})"), + 1 => format!(">= {low} and < {high}"), + 2 => format!("> {low}"), + 3 => format!("<= {high}"), + _ => String::new(), + }; + rule.insert(format!("c{index}"), json!(cell)); + } + rule.insert("o".into(), json!(format!("{}", rng.below(9)))); + Value::Object(rule) + }) + .collect(); + serde_json::from_value(json!({ + "nodes": [ + { "id": "in", "name": "request", "type": "inputNode", "content": { "schema": schema.to_string() } }, + { "id": "dt", "name": "table", "type": "decisionTableNode", "content": { + "hitPolicy": "first", + "inputs": inputs, + "outputs": [ { "id": "o", "name": "Out", "field": "out" } ], + "rules": rules, + "passThrough": true + } }, + { "id": "out", "name": "out", "type": "outputNode", "content": {} } + ], + "edges": [ + { "id": "e1", "sourceId": "in", "targetId": "dt" }, + { "id": "e2", "sourceId": "dt", "targetId": "out" } + ] + })) + .expect("graph") +} + +#[test] +fn table_checks_match_the_reference_on_range_heavy_tables() { + let mut rng = Rng(0x0BAD_CAFE_F00D_0002); + let mut with_gaps = 0; + let mut incomplete = 0; + for (rows, columns) in [(40, 3), (80, 4), (120, 6), (200, 5), (300, 6)] { + let found = reported(range_heavy(&mut rng, rows, columns)); + with_gaps += usize::from(found.missing); + incomplete += usize::from(found.incomplete); + } + assert!(with_gaps >= 2, "only {with_gaps} tables reported gaps"); + assert_eq!(with_gaps + incomplete, 5); +} + +#[test] +#[ignore] +fn table_checks_match_the_reference_when_the_budget_runs_out() { + let mut rng = Rng(0x0DDB_A11C_0FFE_0003); + let mut incomplete = 0; + let mut complete = 0; + for (rows, columns) in [(300, 3), (1000, 6), (2000, 6), (4000, 6), (4000, 9)] { + let found = reported(range_heavy(&mut rng, rows, columns)); + incomplete += usize::from(found.incomplete); + complete += usize::from(!found.incomplete); + } + assert!(incomplete >= 1, "no table exhausted the budget"); + assert!(complete >= 1, "no table finished inside the budget"); +} diff --git a/core/engine/src/analysis/table/verify.rs b/core/engine/src/analysis/table/verify.rs index 7e592485..6a91ef9d 100644 --- a/core/engine/src/analysis/table/verify.rs +++ b/core/engine/src/analysis/table/verify.rs @@ -6,14 +6,19 @@ use serde_json::{Map, Value}; use zen_expression::intellisense::IntelliSense; use super::cell::CellConstraint; +use super::cover::Coverage; +use super::gaps::Bits; use super::index::RowIndex; +use super::intern::Interner; +use super::merge::CellKeys; +use super::partition::Partition; use super::print::{CellText, DateDay}; use super::value_set::{ValueKind, ValueSet}; pub(crate) const MAX_INPUTS: usize = 30; pub(super) const MAX_FRAGMENTS: usize = 100_000; const TOTAL_BUDGET: usize = 20_000_000; -const MAX_MINIMIZE: usize = 12; +pub(super) const MAX_MINIMIZE: usize = 12; #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub(crate) enum HitMode { @@ -74,7 +79,7 @@ pub(crate) enum Finding { redundant: bool, }, MissingCases { - cases: Vec, + cases: Rc, total: usize, }, CompressibleTable { @@ -103,10 +108,138 @@ pub(crate) struct GapCase { pub(crate) example: Option, } +#[derive(Debug, Clone, PartialEq)] +pub(crate) enum GapValues { + Patterns { words: usize, data: Vec }, + Sets(Vec), +} + +#[derive(Debug, Clone, PartialEq)] +pub(crate) struct GapAxis { + pub(super) label: Arc, + pub(super) column: Option>, + pub(super) subject: Option, + pub(super) path: Option>, + pub(super) input: bool, + pub(super) dated: bool, + pub(super) prefer: Option, + pub(super) domain: ValueSet, + pub(super) atoms: Vec, + pub(super) values: GapValues, +} + +struct GapValue { + text: Option, + cell: Option, + example: Option, +} + +impl GapAxis { + fn len(&self) -> usize { + match &self.values { + GapValues::Patterns { words, data } => data.len() / words, + GapValues::Sets(sets) => sets.len(), + } + } + + fn set(&self, value: usize) -> ValueSet { + match &self.values { + GapValues::Sets(sets) => sets[value].clone(), + GapValues::Patterns { words, data } => Partition::union( + Bits::ones(&data[value * words..(value + 1) * words]).map(|atom| &self.atoms[atom]), + ), + } + } + + fn describe(&self, value: usize) -> GapValue { + let set = self.set(value); + let text = CellText::of(&set, &self.domain, self.dated); + let skipped = text.as_ref().is_some_and(String::is_empty); + let cell = match (&text, &self.subject) { + _ if skipped => None, + (None, _) => None, + (Some(_), Some(subject)) => CellText::standard(&set, &self.domain, self.dated, subject), + (Some(text), None) => Some(text.clone()), + }; + let example = match (skipped, self.dated) { + (true, _) => None, + (false, true) => DateDay::example(&set), + (false, false) => set.example(self.prefer), + }; + GapValue { + text, + cell, + example, + } + } +} + +#[derive(Debug, Clone, PartialEq)] +pub(crate) struct GapTable { + pub(super) axes: Vec, + pub(super) rows: Vec, +} + +impl GapTable { + pub(crate) fn cases(&self) -> impl Iterator + '_ { + let mut described: Vec>> = self + .axes + .iter() + .map(|axis| (0..axis.len()).map(|_| None).collect()) + .collect(); + self.rows + .chunks_exact(self.axes.len().max(1)) + .map(move |row| self.case(row, &mut described)) + } + + fn case(&self, row: &[u32], described: &mut [Vec>]) -> GapCase { + let mut parts = Vec::new(); + let mut cells = Some(Vec::new()); + let mut example = Some(Map::new()); + for ((axis, described), &value) in self.axes.iter().zip(described.iter_mut()).zip(row) { + let value = match &mut described[value as usize] { + Some(value) => value, + slot => slot.insert(axis.describe(value as usize)), + }; + match &value.text { + Some(text) if text.is_empty() => continue, + Some(text) => { + if !axis.input { + example = None; + } + if let (Some(list), Some(column)) = (cells.as_mut(), &axis.column) { + match &value.cell { + Some(cell) => list.push((column.clone(), cell.clone())), + None => cells = None, + } + } + parts.push((axis.label.clone(), text.clone())); + } + None => { + cells = None; + parts.push((axis.label.clone(), "…".to_string())); + } + } + match (&axis.path, &value.example, example.as_mut()) { + (Some(path), Some(value), Some(root)) => { + VerifyTable::insert(root, path, value.clone()) + } + _ => example = None, + } + } + GapCase { + parts, + cells, + example: example.filter(|root| !root.is_empty()).map(Value::Object), + } + } +} + pub(super) type Region = Vec; type Coverer<'c> = (usize, Vec<&'c ValueSet>); +#[cfg_attr(test, derive(Clone))] pub(super) struct Budget { pub(super) remaining: usize, } @@ -193,30 +326,29 @@ impl<'a> VerifyTable<'a> { if self.inputs.is_empty() { return findings; } - let cells: Vec> = self - .rules - .iter() - .map(|rule| { - self.inputs - .iter() - .map(|col| { - let source = rule.get(&col.id).map(|c| c.as_ref()).unwrap_or(""); - match &col.subject { - Some(subject) => { - CellConstraint::parse_subject(is, source, subject, col.dated) - } - None => CellConstraint::parse( - is, - source, - col.unary, - col.analyzable, - col.dated, - ), - } - }) - .collect() - }) - .collect(); + let mut parsed: Vec> = + self.inputs.iter().map(|_| HashMap::default()).collect(); + let mut cells: Vec> = Vec::with_capacity(self.rules.len()); + for (row, rule) in self.rules.iter().enumerate() { + let mut row_cells = Vec::with_capacity(self.inputs.len()); + for (index, (col, known)) in self.inputs.iter().zip(parsed.iter_mut()).enumerate() { + let source = rule.get(&col.id).map(|c| c.as_ref()).unwrap_or(""); + if let Some(&first) = known.get(source) { + row_cells.push(cells[first][index].clone()); + continue; + } + let cell = match &col.subject { + Some(subject) => CellConstraint::parse_subject(is, source, subject, col.dated), + None => CellConstraint::parse(is, source, col.unary, col.analyzable, col.dated), + }; + if !matches!(cell, CellConstraint::Opaque(_)) { + known.insert(source, row); + } + row_cells.push(cell); + } + cells.push(row_cells); + } + drop(parsed); let mut satisfiable = vec![true; self.rules.len()]; for (row, row_cells) in cells.iter().enumerate() { @@ -239,9 +371,18 @@ impl<'a> VerifyTable<'a> { }; let mut index = (self.mode != HitMode::Collect).then(|| RowIndex::new(&cells, self.inputs.len())); + let mut regions = index + .as_ref() + .and_then(|_| Coverage::new(&cells, self.inputs.len())); let mut reported: Vec = satisfiable.iter().map(|s| !s).collect(); let mut warned: Vec = vec![false; self.rules.len()]; - let mut seen: HashMap<(Vec, Vec), usize> = HashMap::default(); + let keys = CellKeys::new(&cells, self.inputs.len()); + let outputs = self.output_ids(); + let mut seen: Interner = Interner::new(self.inputs.len() + 1); + let mut first_with: Vec = Vec::new(); + let mut signature: Vec = Vec::with_capacity(self.inputs.len() + 1); + #[cfg(test)] + let mut seen_sets: HashMap<(Vec, Vec), usize> = HashMap::default(); let mut blocked_by: HashMap = HashMap::default(); for row in 0..self.rules.len() { if let Some(index) = index.as_mut().filter(|_| row > 0) { @@ -252,29 +393,46 @@ impl<'a> VerifyTable<'a> { if !satisfiable[row] { continue; } - match seen.entry(self.row_signature(&cells[row], row)) { - std::collections::hash_map::Entry::Occupied(first) => { - let of = *first.get(); - reported[row] = true; - let redundant = self.mode != HitMode::Collect && !self.contributes_collect(row); - findings.push(Finding::DuplicateRule { row, of, redundant }); - continue; - } - std::collections::hash_map::Entry::Vacant(slot) => { - slot.insert(row); - } + signature.clear(); + signature.extend_from_slice(keys.row(row)); + signature.push(outputs[row]); + let fresh = seen.len(); + let slot = seen.intern(&signature) as usize; + #[cfg(test)] + assert_eq!( + *seen_sets + .entry(self.row_signature(&cells[row], row)) + .or_insert(row), + first_with.get(slot).copied().unwrap_or(row), + "duplicate detection diverged from the reference at row {row}" + ); + if slot < fresh { + let of = first_with[slot]; + reported[row] = true; + let redundant = self.mode != HitMode::Collect && !self.contributes_collect(row); + findings.push(Finding::DuplicateRule { row, of, redundant }); + continue; } + first_with.push(row); if coverage_incomplete { continue; } let Some(index) = index.as_mut() else { continue; }; - let Some(requirements) = self.requirements(row, || index.candidates(&cells, row)) + let Some(requirements) = + self.requirements(row, || index.candidates(&cells, &keys, row)) else { continue; }; - match self.dead(&cells, row, &requirements, &mut budget, index) { + match self.dead( + &cells, + row, + &requirements, + &mut budget, + index, + regions.as_mut(), + ) { Some(Some(covered_by)) => { reported[row] = true; let redundant = self.blank_outputs(row) @@ -284,8 +442,16 @@ impl<'a> VerifyTable<'a> { warned[row] = !redundant; let same_conditions = !redundant && covered_by.len() == 1 - && self.row_signature(&cells[row], row).0 - == self.row_signature(&cells[covered_by[0]], covered_by[0]).0; + && keys.row(row) == keys.row(covered_by[0]); + #[cfg(test)] + assert_eq!( + same_conditions, + !redundant + && covered_by.len() == 1 + && self.row_signature(&cells[row], row).0 + == self.row_signature(&cells[covered_by[0]], covered_by[0]).0, + "row conditions comparison diverged from the reference at row {row}" + ); let blocker = match covered_by.as_slice() { [only] if !same_conditions || self.catch_all_row(*only) => Some(*only), _ => None, @@ -326,7 +492,7 @@ impl<'a> VerifyTable<'a> { None => gaps_incomplete = true, } } - findings.extend(self.compress(&cells, &satisfiable, &warned)); + findings.extend(self.compress(&cells, &satisfiable, &warned, keys, &outputs)); findings.extend(self.covering_cells(&cells, &satisfiable)); findings.extend(self.unproduced(is, &reported)); if coverage_incomplete || gaps_incomplete { @@ -407,6 +573,22 @@ impl<'a> VerifyTable<'a> { self.rules[row].get(id).map(|c| c.trim()).unwrap_or("") } + fn output_ids(&self) -> Vec { + let mut ids: HashMap, u32> = HashMap::default(); + (0..self.rules.len()) + .map(|row| { + let key: Vec<&str> = self + .outputs + .iter() + .map(|col| self.text(row, &col.id)) + .collect(); + let next = ids.len() as u32; + *ids.entry(key).or_insert(next) + }) + .collect() + } + + #[cfg(test)] fn row_signature( &self, cells: &[CellConstraint], @@ -473,6 +655,53 @@ impl<'a> VerifyTable<'a> { requirements: &[Vec], budget: &mut Budget, index: &RowIndex, + coverage: Option<&mut Coverage>, + ) -> Option>> { + let Some(coverage) = coverage else { + return Self::dead_sets(cells, row, requirements, budget, index); + }; + #[cfg(test)] + let mut shadow = budget.clone(); + let found = Self::covered(cells, row, requirements, budget, index, coverage); + #[cfg(test)] + { + let expected = Self::dead_sets(cells, row, requirements, &mut shadow, index); + assert_eq!( + (&found, budget.remaining), + (&expected, shadow.remaining), + "row coverage diverged between the dense and set-based paths at row {row}" + ); + } + found + } + + fn covered( + cells: &[Vec], + row: usize, + requirements: &[Vec], + budget: &mut Budget, + index: &RowIndex, + coverage: &mut Coverage, + ) -> Option>> { + let region: Region = cells[row] + .iter() + .map(|cell| cell.known_set().unwrap_or_else(ValueSet::all)) + .collect(); + for earlier in requirements { + budget.spend(earlier.len())?; + if Self::escapes(cells, row, ®ion, earlier, index) { + return Some(None); + } + } + coverage.covered_by(row, requirements, budget) + } + + fn dead_sets( + cells: &[Vec], + row: usize, + requirements: &[Vec], + budget: &mut Budget, + index: &RowIndex, ) -> Option>> { let region: Region = cells[row] .iter() diff --git a/core/engine/src/loader/config.rs b/core/engine/src/loader/config.rs index a8cfbcdd..ff7761c4 100644 --- a/core/engine/src/loader/config.rs +++ b/core/engine/src/loader/config.rs @@ -48,14 +48,15 @@ impl LoaderConfig { use std::io::Read; let mut archive = zip::ZipArchive::new(std::io::Cursor::new(bytes))?; + archive.validate_header_consistency()?; let loader = MemoryLoader::default(); for index in 0..archive.len() { let mut entry = archive.by_index(index)?; - if !entry.is_file() || !entry.name().ends_with(".json") { + let key = entry.name()?.to_string(); + if !entry.is_file() || !key.ends_with(".json") { continue; } - let key = entry.name().to_string(); let mut buffer = Vec::with_capacity(entry.size() as usize); entry.read_to_end(&mut buffer)?; let content: DecisionContent = serde_json::from_slice(&buffer)?; @@ -119,4 +120,26 @@ mod tests { assert!(loader.load("graph.json").await.is_ok()); assert!(loader.load("missing.json").await.is_err()); } + + #[test] + fn zip_config_rejects_cloaked_entry_names() { + use std::io::Write; + + let mut cursor = std::io::Cursor::new(Vec::new()); + { + let mut writer = zip::ZipWriter::new(&mut cursor); + writer + .start_file("graph.json", zip::write::SimpleFileOptions::default()) + .unwrap(); + writer.write_all(GRAPH_JSON.as_bytes()).unwrap(); + writer.finish().unwrap(); + } + + let mut bytes = cursor.into_inner(); + let local_name = 30..30 + "graph.json".len(); + assert_eq!(&bytes[local_name.clone()], b"graph.json"); + bytes[local_name].copy_from_slice(b"other.json"); + + assert!(LoaderConfig::Zip { bytes }.into_loader().is_err()); + } } diff --git a/core/engine/src/workspace/db.rs b/core/engine/src/workspace/db.rs index d6baf353..b7317c29 100644 --- a/core/engine/src/workspace/db.rs +++ b/core/engine/src/workspace/db.rs @@ -823,11 +823,7 @@ impl Db { return d; } let value = if snap.graphs.contains_key(path) { - Arc::new( - self.graph_analysis(path) - .map(|analysis| analysis.diagnostics.clone()) - .unwrap_or_default(), - ) + Arc::new(self.graph_table_diagnostics(path)) } else { Arc::new(self.compute_policy_diagnostics(path)) }; diff --git a/core/engine/src/workspace/graph/analysis.rs b/core/engine/src/workspace/graph/analysis.rs index a5782bb5..17e23d5c 100644 --- a/core/engine/src/workspace/graph/analysis.rs +++ b/core/engine/src/workspace/graph/analysis.rs @@ -15,7 +15,7 @@ use zen_expression::intellisense::ArmTest; use crate::analysis::nullable::{NullableOperand, OnError}; use crate::analysis::table::{ - Bound, HitMode, Interval, NumberSet, PathConstraints, TableColumn, VerifyTable, + Bound, HitMode, Interval, NumberSet, PathConstraints, TableColumn, VerifyInput, VerifyOutput, }; use crate::model::GraphContent; use crate::policy::blocks::{ @@ -63,9 +63,20 @@ impl GraphNodeAnalysis { } } +#[derive(Debug)] +pub(crate) struct GraphTableCheck { + pub(crate) at: usize, + pub(crate) node: Arc, + pub(crate) mode: HitMode, + pub(crate) inputs: Vec, + pub(crate) outputs: Vec, + pub(crate) fallible: Vec, +} + #[derive(Debug)] pub struct GraphAnalysis { pub diagnostics: Vec, + pub(crate) table_checks: Vec, pub signature: GraphSignature, pub nodes: HashMap, GraphNodeAnalysis>, pub inferred_inputs: Vec>, @@ -103,6 +114,7 @@ pub(crate) struct GraphAnalyzer<'a> { path: Arc, content: &'a GraphContent, diagnostics: Vec, + table_checks: Vec, validate: bool, unchecked: bool, nodes_scope: VariableType, @@ -158,6 +170,7 @@ impl<'a> GraphAnalyzer<'a> { path, content, diagnostics: Vec::new(), + table_checks: Vec::new(), validate: false, unchecked: false, nodes_scope: VariableType::Any, @@ -234,6 +247,7 @@ impl<'a> GraphAnalyzer<'a> { let input = self.graph_input_signature(); GraphAnalysis { diagnostics: self.diagnostics, + table_checks: self.table_checks, signature: GraphSignature { input, output }, nodes, inferred_inputs, @@ -1573,7 +1587,9 @@ impl<'a> GraphAnalyzer<'a> { .collect(), DecisionTableHitPolicy::Collect => Vec::new(), }; - let table = VerifyTable { + let check = GraphTableCheck { + at: self.diagnostics.len(), + node: node.id.clone(), mode: match content.hit_policy { DecisionTableHitPolicy::First => HitMode::RowFirst, DecisionTableHitPolicy::Collect => HitMode::Collect, @@ -1621,20 +1637,9 @@ impl<'a> GraphAnalyzer<'a> { }) }) .collect(), - rules: &content.rules, fallible, }; - let diagnostics = table.diagnostics( - &mut intellisense.borrow_mut(), - |row| Self::row_key(&content.rules[row], row), - |expression_id| match expression_id { - Some(id) => { - DiagnosticLocation::expression(self.path.clone(), node.id.clone(), id, None) - } - None => DiagnosticLocation::block(self.path.clone(), node.id.clone()), - }, - ); - self.diagnostics.extend(diagnostics); + self.table_checks.push(check); } fn declared_output_type( diff --git a/core/engine/src/workspace/graph/queries.rs b/core/engine/src/workspace/graph/queries.rs index 3bb75b73..fc53bb84 100644 --- a/core/engine/src/workspace/graph/queries.rs +++ b/core/engine/src/workspace/graph/queries.rs @@ -10,8 +10,12 @@ use crate::workspace::graph::analysis::{ }; use crate::workspace::reads::ReadView; +use crate::analysis::table::VerifyTable; +use crate::model::DecisionNodeKind; use crate::policy::queries::scope::VariableTypeScope; -use crate::workspace::types::{InputProperty, OutputProperty, PropertyKind, ScopeRequest}; +use crate::workspace::types::{ + Diagnostic, DiagnosticLocation, InputProperty, OutputProperty, PropertyKind, ScopeRequest, +}; impl Db { pub(crate) fn graph_analysis(&self, path: &Arc) -> Option> { @@ -33,6 +37,52 @@ impl Db { Some(analysis) } + pub(crate) fn graph_table_diagnostics(&self, path: &Arc) -> Vec { + let Some(analysis) = self.graph_analysis(path) else { + return Vec::new(); + }; + let snap = self.snapshot(); + let content = snap.graphs.get(path).and_then(|doc| doc.as_graph()); + let (Some(content), false) = (content, analysis.table_checks.is_empty()) else { + return analysis.diagnostics.clone(); + }; + let intellisense = self.graph_intellisense(); + let mut out = Vec::with_capacity(analysis.diagnostics.len()); + let mut cursor = 0; + for check in &analysis.table_checks { + out.extend(analysis.diagnostics[cursor..check.at].iter().cloned()); + cursor = check.at; + let rules = content.nodes.iter().find_map(|node| match &node.kind { + DecisionNodeKind::DecisionTableNode { content } if node.id == check.node => { + Some(&content.rules) + } + _ => None, + }); + let Some(rules) = rules else { + continue; + }; + let table = VerifyTable { + mode: check.mode, + inputs: check.inputs.clone(), + outputs: check.outputs.clone(), + rules, + fallible: check.fallible.clone(), + }; + out.extend(table.diagnostics( + &mut intellisense.borrow_mut(), + |row| GraphAnalyzer::row_key(&rules[row], row), + |expression_id| match expression_id { + Some(id) => { + DiagnosticLocation::expression(path.clone(), check.node.clone(), id, None) + } + None => DiagnosticLocation::block(path.clone(), check.node.clone()), + }, + )); + } + out.extend(analysis.diagnostics[cursor..].iter().cloned()); + out + } + pub(crate) fn is_graph(&self, path: &str) -> bool { self.snapshot().graphs.contains_key(path) } diff --git a/core/engine/tests/table_scaling.rs b/core/engine/tests/table_scaling.rs new file mode 100644 index 00000000..4e0e0228 --- /dev/null +++ b/core/engine/tests/table_scaling.rs @@ -0,0 +1,602 @@ +use std::alloc::{GlobalAlloc, Layout, System}; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::Mutex; + +use serde_json::{json, Map, Value}; +use zen_engine::model::DecisionContent; +use zen_engine::policy::{DiagnosticCode, Workspace}; +use zen_engine::workspace::ScopeRequest; + +struct Counting; + +static LIVE: AtomicUsize = AtomicUsize::new(0); +static PEAK: AtomicUsize = AtomicUsize::new(0); +static MEASURING: Mutex<()> = Mutex::new(()); + +unsafe impl GlobalAlloc for Counting { + unsafe fn alloc(&self, layout: Layout) -> *mut u8 { + let live = LIVE.fetch_add(layout.size(), Ordering::Relaxed) + layout.size(); + PEAK.fetch_max(live, Ordering::Relaxed); + System.alloc(layout) + } + + unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { + LIVE.fetch_sub(layout.size(), Ordering::Relaxed); + System.dealloc(ptr, layout) + } + + unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 { + if new_size >= layout.size() { + let grown = new_size - layout.size(); + let live = LIVE.fetch_add(grown, Ordering::Relaxed) + grown; + PEAK.fetch_max(live, Ordering::Relaxed); + } else { + LIVE.fetch_sub(layout.size() - new_size, Ordering::Relaxed); + } + System.realloc(ptr, layout, new_size) + } +} + +#[global_allocator] +static GLOBAL: Counting = Counting; + +const MIB: usize = 1024 * 1024; + +fn peak_of(work: impl FnOnce() -> T) -> (T, usize) { + let before = LIVE.load(Ordering::Relaxed); + PEAK.store(before, Ordering::Relaxed); + let result = work(); + (result, PEAK.load(Ordering::Relaxed).saturating_sub(before)) +} + +struct Rng(u64); + +impl Rng { + fn below(&mut self, bound: usize) -> usize { + self.0 ^= self.0 << 13; + self.0 ^= self.0 >> 7; + self.0 ^= self.0 << 17; + (self.0 % bound as u64) as usize + } +} + +fn range_table(seed: u64, rows: usize, columns: usize) -> DecisionContent { + let mut rng = Rng(seed); + let mut properties = Map::new(); + let inputs: Vec = (0..columns) + .map(|index| { + properties.insert(format!("n{index}"), json!({ "type": "number" })); + json!({ "id": format!("c{index}"), "name": format!("N{index}"), "field": format!("n{index}") }) + }) + .collect(); + let required: Vec = properties.keys().cloned().collect(); + let schema = json!({ "type": "object", "properties": properties, "required": required }); + let rules: Vec = (0..rows) + .map(|row| { + let mut rule = Map::new(); + rule.insert("_id".into(), json!(format!("r{row}"))); + for index in 0..columns { + let cell = match index % 6 { + 3 => ["12", "24", "36", "48", "60", "> 60", "<= 36", ""][rng.below(8)] + .to_string(), + 4 => ["< 0.2", "[0.2..0.35)", "[0.35..0.45)", ">= 0.45", ""][rng.below(5)] + .to_string(), + kind => { + let (floor, span, step) = [ + (18, 62, 1), + (2, 78, 5000), + (30, 55, 10), + (0, 0, 0), + (0, 0, 0), + (1, 90, 1000), + ][kind]; + let low = (floor + rng.below(span)) * step; + let high = low + (1 + rng.below(6)) * step; + match rng.below(5) { + 0 => format!("[{low}..{high})"), + 1 => format!(">= {low} and < {high}"), + 2 => format!("> {low}"), + 3 => format!("<= {high}"), + _ => String::new(), + } + } + }; + rule.insert(format!("c{index}"), json!(cell)); + } + rule.insert("o".into(), json!(format!("{}", rng.below(9)))); + Value::Object(rule) + }) + .collect(); + serde_json::from_value(json!({ + "nodes": [ + { "id": "in", "name": "request", "type": "inputNode", "content": { "schema": schema.to_string() } }, + { "id": "dt", "name": "table", "type": "decisionTableNode", "content": { + "hitPolicy": "first", + "inputs": inputs, + "outputs": [ { "id": "o", "name": "Out", "field": "out" } ], + "rules": rules, + "passThrough": true + } }, + { "id": "out", "name": "out", "type": "outputNode", "content": {} } + ], + "edges": [ + { "id": "e1", "sourceId": "in", "targetId": "dt" }, + { "id": "e2", "sourceId": "dt", "targetId": "out" } + ] + })) + .expect("graph") +} + +struct Measured { + peak: usize, + payload: usize, + cases: usize, + incomplete: bool, +} + +fn diagnose(content: DecisionContent) -> Measured { + let mut workspace = Workspace::new(); + workspace.set_document("g", content); + let (diagnostics, peak) = peak_of(|| workspace.diagnostics("g")); + let payload = diagnostics + .iter() + .map(|d| d.message.len() + d.args.values().map(String::len).sum::()) + .sum(); + let cases = diagnostics + .iter() + .find(|d| d.code == DiagnosticCode::MissingCases) + .and_then(|d| d.args.get("count")) + .and_then(|count| count.parse().ok()) + .unwrap_or(0); + let incomplete = diagnostics + .iter() + .any(|d| d.code == DiagnosticCode::TableChecksIncomplete); + Measured { + peak, + payload, + cases, + incomplete, + } +} + +#[test] +fn schema_queries_stay_small_on_range_heavy_tables() { + let _guard = MEASURING + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + for rows in [500, 1000, 2000] { + let mut workspace = Workspace::new(); + workspace.set_document("g", range_table(0xA11C_E5ED_0000_0001, rows, 6)); + let request = ScopeRequest::for_policy("g"); + let (inputs, input_peak) = peak_of(|| workspace.inputs(&request)); + let (outputs, output_peak) = peak_of(|| workspace.outputs(&request)); + assert_eq!(inputs.len(), 6, "{rows} rows"); + assert!(!outputs.is_empty(), "{rows} rows"); + assert!( + input_peak < 8 * MIB, + "{rows} rows: deriving inputs peaked at {} KiB", + input_peak / 1024 + ); + assert!( + output_peak < 8 * MIB, + "{rows} rows: deriving outputs peaked at {} KiB", + output_peak / 1024 + ); + let diagnostics = workspace.diagnostics("g"); + assert!( + diagnostics.iter().any(|d| matches!( + d.code, + DiagnosticCode::MissingCases | DiagnosticCode::TableChecksIncomplete + )), + "{rows} rows: table checks still run for diagnostics" + ); + } +} + +fn mixed_table(seed: u64, rows: usize) -> DecisionContent { + let mut rng = Rng(seed); + let regions = [ + "north", "south", "east", "west", "central", "coastal", "inland", "island", + ]; + let terms = ["12", "24", "36", "48", "60", "> 60", "<= 36", ""]; + let ratios = ["< 0.2", "[0.2..0.35)", "[0.35..0.45)", ">= 0.45", ""]; + let spans: [(usize, usize, usize); 4] = [ + (18, 80, 1), + (10_000, 400_000, 5_000), + (1_000, 900_000, 1_000), + (300, 850, 10), + ]; + let mut properties = Map::new(); + properties.insert("region".into(), json!({ "type": "string" })); + let mut inputs = vec![json!({ "id": "region", "name": "Region", "field": "region" })]; + for index in 0..6 { + properties.insert(format!("n{index}"), json!({ "type": "number" })); + inputs.push(json!({ "id": format!("c{index}"), "name": format!("N{index}"), "field": format!("n{index}") })); + } + let required: Vec = properties.keys().cloned().collect(); + let schema = json!({ "type": "object", "properties": properties, "required": required }); + let rules: Vec = (0..rows) + .map(|row| { + let mut rule = Map::new(); + rule.insert("_id".into(), json!(format!("r{row}"))); + rule.insert( + "region".into(), + json!(format!("\"{}\"", regions[rng.below(regions.len())])), + ); + for (index, (min, max, step)) in spans.iter().enumerate() { + let low = (min / step + rng.below(max / step - min / step)) * step; + let high = low + (1 + rng.below(6)) * step; + let cell = match rng.below(5) { + 0 => format!("[{low}..{high})"), + 1 => format!(">= {low} and < {high}"), + 2 => format!("> {low}"), + 3 => format!("<= {high}"), + _ => String::new(), + }; + rule.insert(format!("c{index}"), json!(cell)); + } + rule.insert("c4".into(), json!(terms[rng.below(terms.len())])); + rule.insert("c5".into(), json!(ratios[rng.below(ratios.len())])); + rule.insert("o".into(), json!(format!("{}", rng.below(9)))); + Value::Object(rule) + }) + .collect(); + serde_json::from_value(json!({ + "nodes": [ + { "id": "in", "name": "request", "type": "inputNode", "content": { "schema": schema.to_string() } }, + { "id": "dt", "name": "table", "type": "decisionTableNode", "content": { + "hitPolicy": "first", + "inputs": inputs, + "outputs": [ { "id": "o", "name": "Out", "field": "out" } ], + "rules": rules, + "passThrough": true + } }, + { "id": "out", "name": "out", "type": "outputNode", "content": {} } + ], + "edges": [ + { "id": "e1", "sourceId": "in", "targetId": "dt" }, + { "id": "e2", "sourceId": "dt", "targetId": "out" } + ] + })) + .expect("graph") +} + +#[test] +fn finished_checks_on_range_heavy_tables_cost_memory_in_proportion_to_their_report() { + let _guard = MEASURING + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + for rows in [250, 500, 1000, 1500] { + let measured = diagnose(mixed_table(0x5EED_F00D_0000_0004, rows)); + assert!(!measured.incomplete, "{rows} rows: checks did not finish"); + assert!( + measured.cases > 1000, + "{rows} rows: {} missing cases", + measured.cases + ); + assert!( + measured.peak <= 4 * measured.payload + 2 * MIB, + "{rows} rows: peak {} KiB for {} KiB of diagnostics ({} missing cases)", + measured.peak / 1024, + measured.payload / 1024, + measured.cases + ); + } +} + +fn banded_table(bands: usize, columns: usize, hole_every: usize) -> DecisionContent { + let mut properties = Map::new(); + let inputs: Vec = (0..columns) + .map(|index| { + properties.insert(format!("n{index}"), json!({ "type": "number", "minimum": 0, "exclusiveMaximum": bands * 10 })); + json!({ "id": format!("c{index}"), "name": format!("N{index}"), "field": format!("n{index}") }) + }) + .collect(); + let required: Vec = properties.keys().cloned().collect(); + let schema = json!({ "type": "object", "properties": properties, "required": required }); + let mut rules: Vec = Vec::new(); + for combination in 0..bands.pow(columns as u32) { + let picks: Vec = (0..columns) + .map(|index| combination / bands.pow(index as u32) % bands) + .collect(); + if (combination.wrapping_mul(2_654_435_761) >> 7) % hole_every == 0 { + continue; + } + let mut rule = Map::new(); + rule.insert("_id".into(), json!(format!("r{combination}"))); + for (index, band) in picks.iter().enumerate() { + rule.insert( + format!("c{index}"), + json!(format!("[{}..{})", band * 10, (band + 1) * 10)), + ); + } + rule.insert("o".into(), json!(format!("{}", combination % 7))); + rules.push(Value::Object(rule)); + } + serde_json::from_value(json!({ + "nodes": [ + { "id": "in", "name": "request", "type": "inputNode", "content": { "schema": schema.to_string() } }, + { "id": "dt", "name": "table", "type": "decisionTableNode", "content": { + "hitPolicy": "first", + "inputs": inputs, + "outputs": [ { "id": "o", "name": "Out", "field": "out" } ], + "rules": rules, + "passThrough": true + } }, + { "id": "out", "name": "out", "type": "outputNode", "content": {} } + ], + "edges": [ + { "id": "e1", "sourceId": "in", "targetId": "dt" }, + { "id": "e2", "sourceId": "dt", "targetId": "out" } + ] + })) + .expect("graph") +} + +#[test] +fn missing_cases_cost_memory_in_proportion_to_their_number() { + let _guard = MEASURING + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + for bands in [6, 9, 12, 15] { + let measured = diagnose(banded_table(bands, 3, 3)); + assert!(!measured.incomplete, "{bands} bands: checks did not finish"); + assert!(measured.cases > 0, "{bands} bands: no missing cases"); + assert!( + measured.peak <= 4 * measured.payload + 8 * MIB, + "{bands} bands: peak {} KiB for {} KiB of diagnostics ({} missing cases)", + measured.peak / 1024, + measured.payload / 1024, + measured.cases + ); + } +} + +#[test] +fn range_heavy_table_checks_stay_within_a_fixed_ceiling() { + let _guard = MEASURING + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + let mut finished = 0; + let mut incomplete = 0; + for (rows, columns) in [ + (250, 6), + (500, 5), + (1000, 5), + (2000, 5), + (1000, 6), + (4000, 6), + (8000, 6), + ] { + let measured = diagnose(range_table(0xB0B5_CAFE_0000_0002, rows, columns)); + finished += usize::from(!measured.incomplete); + incomplete += usize::from(measured.incomplete); + assert!( + measured.peak <= 4 * measured.payload + 64 * MIB, + "{rows}x{columns}: peak {} KiB for {} KiB of diagnostics ({} missing cases)", + measured.peak / 1024, + measured.payload / 1024, + measured.cases + ); + } + assert!( + finished >= 2, + "only {finished} tables finished their checks" + ); + assert!( + incomplete >= 2, + "only {incomplete} tables exhausted the budget" + ); +} + +fn decision_graph( + schema: Value, + inputs: Value, + outputs: Value, + rules: Vec, +) -> DecisionContent { + serde_json::from_value(json!({ + "nodes": [ + { "id": "in", "name": "request", "type": "inputNode", "content": { "schema": schema.to_string() } }, + { "id": "dt", "name": "table", "type": "decisionTableNode", "content": { + "hitPolicy": "first", + "inputs": inputs, + "outputs": outputs, + "rules": rules, + "passThrough": true + } }, + { "id": "out", "name": "out", "type": "outputNode", "content": {} } + ], + "edges": [ + { "id": "e1", "sourceId": "in", "targetId": "dt" }, + { "id": "e2", "sourceId": "dt", "targetId": "out" } + ] + })) + .expect("graph") +} + +fn lookup_table(rows: usize) -> DecisionContent { + let schema = json!({ + "type": "object", + "properties": { "status": { "type": "number" }, "code": { "type": "string" } }, + "required": ["status", "code"] + }); + let rules = (0..rows) + .map(|row| { + let status = ["200", "400", "500"][row % 3]; + json!({ + "_id": format!("r{row}"), + "s": status, + "c": format!("'CODE_{row:06}'"), + "o": format!("'REASON_{row:06}'") + }) + }) + .collect(); + decision_graph( + schema, + json!([ + { "id": "s", "name": "Status", "field": "status" }, + { "id": "c", "name": "Code", "field": "code" } + ]), + json!([ { "id": "o", "name": "Reason", "field": "reason" } ]), + rules, + ) +} + +fn banded_grid(rows: usize) -> DecisionContent { + let schema = json!({ + "type": "object", + "properties": { + "amount": { "type": "number" }, + "region": { "type": "string" }, + "tier": { "type": "string" }, + "flag": { "type": "boolean" }, + "age": { "type": "number" } + }, + "required": ["amount", "region", "tier", "flag", "age"] + }); + let regions = [ + "\"north\", \"south\"", + "\"east\"", + "\"west\", \"central\"", + "\"coastal\"", + ]; + let tiers = ["\"basic\"", "\"plus\"", "\"premium\""]; + let ages = [(18, 30), (30, 45), (45, 65), (65, 120)]; + let rules = (0..rows) + .map(|row| { + let band = row / (regions.len() * tiers.len() * 2 * ages.len()); + let (low, high) = ages[row % ages.len()]; + let region = regions[row / (tiers.len() * 2 * ages.len()) % regions.len()]; + let tier = tiers[row / (2 * ages.len()) % tiers.len()]; + let flag = match row / ages.len() % 2 { + 0 => "true", + _ => "false", + }; + json!({ + "_id": format!("r{row}"), + "a": format!(">= {} and < {}", band * 1000, (band + 1) * 1000), + "r": region, + "t": tier, + "f": flag, + "g": format!("[{low}..{high})"), + "o": format!("{}", band as f64 * 0.001) + }) + }) + .collect(); + decision_graph( + schema, + json!([ + { "id": "a", "name": "Amount", "field": "amount" }, + { "id": "r", "name": "Region", "field": "region" }, + { "id": "t", "name": "Tier", "field": "tier" }, + { "id": "f", "name": "Flag", "field": "flag" }, + { "id": "g", "name": "Age", "field": "age" } + ]), + json!([ { "id": "o", "name": "Rate", "field": "rate" } ]), + rules, + ) +} + +#[test] +fn lookup_tables_with_one_value_per_row_grow_linearly() { + let _guard = MEASURING + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + let small = diagnose(lookup_table(10_000)); + let large = diagnose(lookup_table(40_000)); + assert!( + large.peak <= 6 * small.peak, + "four times the rows took {} KiB after {} KiB", + large.peak / 1024, + small.peak / 1024 + ); + assert!( + large.peak <= 40_000 * 2 * 1024, + "40,000 lookup rows peaked at {} KiB", + large.peak / 1024 + ); +} + +#[test] +fn compressible_grids_stay_under_two_kibibytes_a_row() { + let _guard = MEASURING + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + for rows in [20_000, 40_000] { + let mut workspace = Workspace::new(); + workspace.set_document("g", banded_grid(rows)); + let (diagnostics, peak) = peak_of(|| workspace.diagnostics("g")); + assert!( + diagnostics + .iter() + .any(|d| d.code == DiagnosticCode::CompressibleTable), + "{rows} rows: the grid should be reported as compressible" + ); + assert!( + peak <= rows * 2 * 1024 + 8 * MIB, + "{rows} rows peaked at {} KiB", + peak / 1024 + ); + } +} + +fn merging_lookup(rows: usize) -> DecisionContent { + let schema = json!({ + "type": "object", + "properties": { "status": { "type": "number" }, "code": { "type": "string" } }, + "required": ["status", "code"] + }); + let rules = (0..rows) + .map(|row| { + let code = row * 7919 % rows; + let status = ["200", "400", "500"][row % 3]; + json!({ + "_id": format!("r{row}"), + "s": status, + "c": format!("'CODE_{code:06}'"), + "o": "'BLOCKED'" + }) + }) + .collect(); + decision_graph( + schema, + json!([ + { "id": "s", "name": "Status", "field": "status" }, + { "id": "c", "name": "Code", "field": "code" } + ]), + json!([ { "id": "o", "name": "Reason", "field": "reason" } ]), + rules, + ) +} + +#[test] +fn lookup_rows_that_merge_into_one_cell_grow_linearly() { + let _guard = MEASURING + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + let mut peaks = Vec::new(); + for rows in [10_000, 20_000, 40_000] { + let mut workspace = Workspace::new(); + workspace.set_document("g", merging_lookup(rows)); + let (diagnostics, peak) = peak_of(|| workspace.diagnostics("g")); + assert!( + diagnostics + .iter() + .any(|d| d.code == DiagnosticCode::CompressibleTable), + "{rows} rows: the lookup should be reported as compressible" + ); + assert!( + peak <= rows * 2 * 1024 + 2 * MIB, + "{rows} rows peaked at {} KiB", + peak / 1024 + ); + peaks.push(peak); + } + assert!( + peaks[1] <= 3 * peaks[0], + "twice the rows took {} KiB after {} KiB", + peaks[1] / 1024, + peaks[0] / 1024 + ); +} diff --git a/core/engine/tests/trace_golden.rs b/core/engine/tests/trace_golden.rs index 823b6256..c4f8c962 100644 --- a/core/engine/tests/trace_golden.rs +++ b/core/engine/tests/trace_golden.rs @@ -27,7 +27,7 @@ fn canonical(v: Value) -> Value { let mut out = serde_json::Map::new(); for (k, x) in entries { let x = match k.as_str() { - "performance" | "duration" | "msSinceRun" => Value::Null, + "performance" | "duration" | "msSinceRun" | "engineVersion" => Value::Null, _ => canonical(x), }; out.insert(k, x); @@ -374,7 +374,7 @@ fn golden() -> HashMap> { let kind = v["kind"].as_str().unwrap().to_string(); let suite = v["suite"].as_str().unwrap().to_string(); let case = v["case"].as_u64().unwrap() as usize; - let outcome = std::sync::Arc::new(v["outcome"].clone()); + let outcome = std::sync::Arc::new(canonical(v["outcome"].clone())); for variant in v["variants"].as_array().unwrap() { out.insert( ( diff --git a/core/expression/CHANGELOG.md b/core/expression/CHANGELOG.md index 3513d25c..23aa2797 100644 --- a/core/expression/CHANGELOG.md +++ b/core/expression/CHANGELOG.md @@ -1,5 +1,35 @@ # Changelog +## [2.1.8](https://github.com/gorules/zen/compare/zen-expression-v2.1.7...zen-expression-v2.1.8) (2026-11-19) + + +### Bug Fixes + +* table analysis memory ([#570](https://github.com/gorules/zen/issues/570)) ([1944ebe](https://github.com/gorules/zen/commit/1944ebe01feb2b11b5197c7b16f4ae1e9d26ccf3)) + + +### Dependencies + +* The following workspace dependencies were updated + * dependencies + * zen-macros bumped from 2.1.7 to 2.1.8 + * zen-types bumped from 2.1.7 to 2.1.8 + +## [2.1.7](https://github.com/gorules/zen/compare/zen-expression-v2.1.6...zen-expression-v2.1.7) (2026-11-09) + + +### Miscellaneous + +* **zen-expression:** Synchronize core versions + + +### Dependencies + +* The following workspace dependencies were updated + * dependencies + * zen-macros bumped from 2.1.6 to 2.1.7 + * zen-types bumped from 2.1.6 to 2.1.7 + ## [2.1.6](https://github.com/gorules/zen/compare/zen-expression-v2.1.5...zen-expression-v2.1.6) (2026-10-21) diff --git a/core/expression/Cargo.toml b/core/expression/Cargo.toml index 104e6387..8a8a612d 100644 --- a/core/expression/Cargo.toml +++ b/core/expression/Cargo.toml @@ -3,7 +3,7 @@ authors = ["GoRules Team "] description = "Zen Expression Language" name = "zen-expression" license = "MIT" -version = "2.1.6" +version = "2.1.8" edition = "2021" rust-version = "1.88" repository = "https://github.com/gorules/zen.git" @@ -31,8 +31,8 @@ nohash-hasher = { workspace = true } strsim = "0.11" iana-time-zone = "0.1" -zen-macros = { path = "../macros", version = "2.1.6" } -zen-types = { path = "../types", version = "2.1.6" } +zen-macros = { path = "../macros", version = "2.1.8" } +zen-types = { path = "../types", version = "2.1.8" } [dev-dependencies] criterion = { workspace = true } diff --git a/core/expression/src/intellisense/values/mod.rs b/core/expression/src/intellisense/values/mod.rs index ddae18a5..7c97473a 100644 --- a/core/expression/src/intellisense/values/mod.rs +++ b/core/expression/src/intellisense/values/mod.rs @@ -1,3 +1,4 @@ pub mod cell; pub mod print; +pub mod strings; pub mod value_set; diff --git a/core/expression/src/intellisense/values/strings.rs b/core/expression/src/intellisense/values/strings.rs new file mode 100644 index 00000000..c790f70b --- /dev/null +++ b/core/expression/src/intellisense/values/strings.rs @@ -0,0 +1,343 @@ +use std::cmp::Ordering; +use std::collections::{btree_set, BTreeSet}; +use std::fmt; +use std::hash::{Hash, Hasher}; +use std::rc::Rc; +use std::slice; + +#[derive(Clone)] +pub struct Strings(Repr); + +#[derive(Clone)] +#[allow(clippy::box_collection)] +enum Repr { + One(Rc), + Few(Box<[Rc]>), + Many(Box>>), +} + +impl Strings { + const FEW: usize = 32; + + pub fn new() -> Self { + Self(Repr::Few(Box::default())) + } + + pub fn one(value: Rc) -> Self { + Self(Repr::One(value)) + } + + fn sorted(values: Vec>) -> Self { + if values.len() > Self::FEW { + return Self(Repr::Many(Box::new(values.into_iter().collect()))); + } + match <[Rc; 1]>::try_from(values) { + Ok([only]) => Self(Repr::One(only)), + Err(values) => Self(Repr::Few(values.into_boxed_slice())), + } + } + + pub fn len(&self) -> usize { + match &self.0 { + Repr::One(_) => 1, + Repr::Few(values) => values.len(), + Repr::Many(values) => values.len(), + } + } + + pub fn is_empty(&self) -> bool { + self.len() == 0 + } + + pub fn iter(&self) -> Iter<'_> { + Iter(match &self.0 { + Repr::One(only) => Walk::List(slice::from_ref(only).iter()), + Repr::Few(values) => Walk::List(values.iter()), + Repr::Many(values) => Walk::Tree(values.iter()), + }) + } + + pub fn contains(&self, value: &str) -> bool { + match &self.0 { + Repr::One(only) => &**only == value, + Repr::Few(values) => values.binary_search_by(|held| (**held).cmp(value)).is_ok(), + Repr::Many(values) => values.contains(value), + } + } + + pub fn union(&self, other: &Self) -> Self { + if other.is_empty() { + return self.clone(); + } + if self.is_empty() { + return other.clone(); + } + let mut out = Vec::with_capacity(self.len() + other.len()); + let mut left = self.iter().peekable(); + let mut right = other.iter().peekable(); + loop { + let order = match (left.peek(), right.peek()) { + (Some(a), Some(b)) => a.cmp(b), + (Some(_), None) => Ordering::Less, + (None, Some(_)) => Ordering::Greater, + (None, None) => break, + }; + match order { + Ordering::Less => out.extend(left.next().cloned()), + Ordering::Greater => out.extend(right.next().cloned()), + Ordering::Equal => { + out.extend(left.next().cloned()); + right.next(); + } + } + } + Self::sorted(out) + } + + pub fn intersection(&self, other: &Self) -> Self { + let (small, large) = if self.len() <= other.len() { + (self, other) + } else { + (other, self) + }; + Self::sorted( + small + .iter() + .filter(|value| large.contains(value)) + .cloned() + .collect(), + ) + } + + pub fn difference(&self, other: &Self) -> Self { + if other.is_empty() { + return self.clone(); + } + Self::sorted( + self.iter() + .filter(|value| !other.contains(value)) + .cloned() + .collect(), + ) + } +} + +impl Default for Strings { + fn default() -> Self { + Self::new() + } +} + +impl PartialEq for Strings { + fn eq(&self, other: &Self) -> bool { + self.len() == other.len() && self.iter().eq(other.iter()) + } +} + +impl Eq for Strings {} + +impl Hash for Strings { + fn hash(&self, state: &mut H) { + state.write_usize(self.len()); + for value in self { + value.hash(state); + } + } +} + +impl fmt::Debug for Strings { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_set().entries(self).finish() + } +} + +impl FromIterator> for Strings { + fn from_iter>>(values: I) -> Self { + let mut values: Vec> = values.into_iter().collect(); + if !values.windows(2).all(|pair| pair[0] < pair[1]) { + values.sort_unstable(); + values.dedup(); + } + Self::sorted(values) + } +} + +impl From>> for Strings { + fn from(values: BTreeSet>) -> Self { + if values.len() > Self::FEW { + return Self(Repr::Many(Box::new(values))); + } + Self::sorted(values.into_iter().collect()) + } +} + +impl Extend> for Strings { + fn extend>>(&mut self, values: I) { + if let Repr::Many(held) = &mut self.0 { + held.extend(values); + return; + } + let mut all: Vec> = self.iter().cloned().collect(); + all.extend(values); + *self = all.into_iter().collect(); + } +} + +impl<'a> IntoIterator for &'a Strings { + type Item = &'a Rc; + type IntoIter = Iter<'a>; + + fn into_iter(self) -> Iter<'a> { + self.iter() + } +} + +#[derive(Clone)] +pub struct Iter<'a>(Walk<'a>); + +#[derive(Clone)] +enum Walk<'a> { + List(slice::Iter<'a, Rc>), + Tree(btree_set::Iter<'a, Rc>), +} + +impl<'a> Iterator for Iter<'a> { + type Item = &'a Rc; + + fn next(&mut self) -> Option { + match &mut self.0 { + Walk::List(values) => values.next(), + Walk::Tree(values) => values.next(), + } + } + + fn size_hint(&self) -> (usize, Option) { + match &self.0 { + Walk::List(values) => values.size_hint(), + Walk::Tree(values) => values.size_hint(), + } + } +} + +impl DoubleEndedIterator for Iter<'_> { + fn next_back(&mut self) -> Option { + match &mut self.0 { + Walk::List(values) => values.next_back(), + Walk::Tree(values) => values.next_back(), + } + } +} + +impl ExactSizeIterator for Iter<'_> {} + +#[cfg(test)] +mod tests { + use super::*; + use std::collections::hash_map::DefaultHasher; + + struct Random(u64); + + impl Random { + fn next(&mut self) -> u64 { + self.0 ^= self.0 << 13; + self.0 ^= self.0 >> 7; + self.0 ^= self.0 << 17; + self.0 + } + + fn below(&mut self, limit: usize) -> usize { + (self.next() % limit as u64) as usize + } + + fn values(&mut self, pool: &[Rc]) -> Vec> { + let size = match self.below(6) { + 0 => 0, + 1 => 1, + 2 => 2 + self.below(6), + 3 => Strings::FEW - 1 + self.below(3), + _ => self.below(pool.len()), + }; + (0..size) + .map(|_| pool[self.below(pool.len())].clone()) + .collect() + } + } + + fn pool(size: usize) -> Vec> { + (0..size) + .map(|i| Rc::from(format!("v{:03}", (i * 37) % size))) + .collect() + } + + fn hash_of(value: &impl Hash) -> u64 { + let mut hasher = DefaultHasher::new(); + value.hash(&mut hasher); + hasher.finish() + } + + fn listed(set: &Strings) -> Vec> { + set.iter().cloned().collect() + } + + fn expected<'a>(values: impl Iterator>) -> Vec> { + values.cloned().collect() + } + + #[test] + fn matches_a_tree_set_on_random_inputs() { + let pool = pool(120); + let mut random = Random(0x9e37_79b9_7f4a_7c15); + for _ in 0..4_000 { + let (left, right) = (random.values(&pool), random.values(&pool)); + let (a, b): (Strings, Strings) = ( + left.iter().cloned().collect(), + right.iter().cloned().collect(), + ); + let (x, y): (BTreeSet>, BTreeSet>) = ( + left.iter().cloned().collect(), + right.iter().cloned().collect(), + ); + + assert_eq!(listed(&a), expected(x.iter())); + assert_eq!(a.len(), x.len()); + assert_eq!(a.is_empty(), x.is_empty()); + assert_eq!(listed(&a.union(&b)), expected(x.union(&y))); + assert_eq!(listed(&a.intersection(&b)), expected(x.intersection(&y))); + assert_eq!(listed(&a.difference(&b)), expected(x.difference(&y))); + assert_eq!( + a.iter().rev().cloned().collect::>(), + x.iter().rev().cloned().collect::>() + ); + for value in &pool { + assert_eq!(a.contains(value), x.contains(value)); + } + assert_eq!(a == b, x == y); + assert_eq!(hash_of(&a), hash_of(&x)); + assert_eq!(format!("{a:?}"), format!("{x:?}")); + assert_eq!(Strings::from(x.clone()), a); + + let mut grown = a.clone(); + grown.extend(right.iter().cloned()); + assert_eq!(grown, a.union(&b)); + assert_eq!(hash_of(&grown), hash_of(&a.union(&b))); + } + } + + #[test] + fn grows_one_value_at_a_time_across_every_size() { + let pool = pool(200); + let mut set = Strings::new(); + let mut tree = BTreeSet::new(); + for value in &pool { + set.extend([value.clone()]); + tree.insert(value.clone()); + assert_eq!(listed(&set), expected(tree.iter())); + assert_eq!(set, tree.iter().cloned().collect::()); + } + } + + #[test] + fn stays_three_words_wide() { + assert!(size_of::() <= 3 * size_of::()); + } +} diff --git a/core/expression/src/intellisense/values/value_set.rs b/core/expression/src/intellisense/values/value_set.rs index d63a8a19..8fb95097 100644 --- a/core/expression/src/intellisense/values/value_set.rs +++ b/core/expression/src/intellisense/values/value_set.rs @@ -5,6 +5,8 @@ use std::rc::Rc; use rust_decimal::Decimal; use serde_json::Value; +pub use super::strings::Strings; + #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum Bound { Unbounded, @@ -307,19 +309,19 @@ impl NumberSet { #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub enum StringSet { - Finite(BTreeSet>), - CoFinite(BTreeSet>), + Finite(Strings), + CoFinite(Strings), } impl Default for StringSet { fn default() -> Self { - StringSet::Finite(BTreeSet::new()) + StringSet::Finite(Strings::new()) } } impl StringSet { pub fn all() -> Self { - StringSet::CoFinite(BTreeSet::new()) + StringSet::CoFinite(Strings::new()) } pub fn is_empty(&self) -> bool { @@ -339,31 +341,23 @@ impl StringSet { pub fn union(&self, other: &Self) -> Self { match (self, other) { - (StringSet::Finite(a), StringSet::Finite(b)) => { - StringSet::Finite(a.union(b).cloned().collect()) - } + (StringSet::Finite(a), StringSet::Finite(b)) => StringSet::Finite(a.union(b)), (StringSet::CoFinite(a), StringSet::CoFinite(b)) => { - StringSet::CoFinite(a.intersection(b).cloned().collect()) + StringSet::CoFinite(a.intersection(b)) } (StringSet::Finite(f), StringSet::CoFinite(c)) | (StringSet::CoFinite(c), StringSet::Finite(f)) => { - StringSet::CoFinite(c.difference(f).cloned().collect()) + StringSet::CoFinite(c.difference(f)) } } } pub fn intersect(&self, other: &Self) -> Self { match (self, other) { - (StringSet::Finite(a), StringSet::Finite(b)) => { - StringSet::Finite(a.intersection(b).cloned().collect()) - } - (StringSet::CoFinite(a), StringSet::CoFinite(b)) => { - StringSet::CoFinite(a.union(b).cloned().collect()) - } + (StringSet::Finite(a), StringSet::Finite(b)) => StringSet::Finite(a.intersection(b)), + (StringSet::CoFinite(a), StringSet::CoFinite(b)) => StringSet::CoFinite(a.union(b)), (StringSet::Finite(f), StringSet::CoFinite(c)) - | (StringSet::CoFinite(c), StringSet::Finite(f)) => { - StringSet::Finite(f.difference(c).cloned().collect()) - } + | (StringSet::CoFinite(c), StringSet::Finite(f)) => StringSet::Finite(f.difference(c)), } } @@ -456,7 +450,7 @@ impl ValueSet { pub fn string(s: &str) -> Self { Self { - strings: StringSet::Finite(BTreeSet::from([Rc::from(s)])), + strings: StringSet::Finite(Strings::one(Rc::from(s))), ..Self::empty() } } @@ -531,8 +525,8 @@ impl ValueSet { } out.numbers = NumberSet::from_intervals(intervals); out.strings = match cofinite { - Some(acc) => acc.union(&StringSet::Finite(finite)), - None => StringSet::Finite(finite), + Some(acc) => acc.union(&StringSet::Finite(finite.into())), + None => StringSet::Finite(finite.into()), }; out } @@ -693,7 +687,7 @@ mod tests { let pair = ValueSet::strings([Rc::from("gold"), Rc::from("silver")]); assert_eq!( pair.difference(&gold).strings, - StringSet::Finite(BTreeSet::from([Rc::from("silver")])) + StringSet::Finite(Strings::one(Rc::from("silver"))) ); } diff --git a/core/expression_repl/CHANGELOG.md b/core/expression_repl/CHANGELOG.md index 72984f0f..6d61810f 100644 --- a/core/expression_repl/CHANGELOG.md +++ b/core/expression_repl/CHANGELOG.md @@ -86,6 +86,14 @@ * dependencies * zen-expression bumped from 2.1.5 to 2.1.6 +* The following workspace dependencies were updated + * dependencies + * zen-expression bumped from 2.1.6 to 2.1.7 + +* The following workspace dependencies were updated + * dependencies + * zen-expression bumped from 2.1.7 to 2.1.8 + ## [1.0.0-beta.0](https://github.com/gorules/zen/compare/expression_repl-v0.55.1...expression_repl-v1.0.0-beta.0) (2026-06-25) diff --git a/core/expression_repl/Cargo.toml b/core/expression_repl/Cargo.toml index 98888dd6..b5c23960 100644 --- a/core/expression_repl/Cargo.toml +++ b/core/expression_repl/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "expression_repl" -version = "2.0.8" +version = "2.0.10" edition = "2021" publish = false @@ -10,5 +10,5 @@ publish = false colored = "3" rustyline = "15" serde_json = { workspace = true } -zen-expression = { path = "../expression", version = "2.1.6" } +zen-expression = { path = "../expression", version = "2.1.8" } diff --git a/core/macros/CHANGELOG.md b/core/macros/CHANGELOG.md index ad02bcd1..037974d9 100644 --- a/core/macros/CHANGELOG.md +++ b/core/macros/CHANGELOG.md @@ -1,5 +1,19 @@ # Changelog +## [2.1.8](https://github.com/gorules/zen/compare/zen-macros-v2.1.7...zen-macros-v2.1.8) (2026-11-19) + + +### Miscellaneous + +* **zen-macros:** Synchronize core versions + +## [2.1.7](https://github.com/gorules/zen/compare/zen-macros-v2.1.6...zen-macros-v2.1.7) (2026-11-09) + + +### Miscellaneous + +* **zen-macros:** Synchronize core versions + ## [2.1.6](https://github.com/gorules/zen/compare/zen-macros-v2.1.5...zen-macros-v2.1.6) (2026-10-21) diff --git a/core/macros/Cargo.toml b/core/macros/Cargo.toml index a2dcd205..5c3f48aa 100644 --- a/core/macros/Cargo.toml +++ b/core/macros/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "zen-macros" description = "Zen Helper Macros" -version = "2.1.6" +version = "2.1.8" edition = "2024" license = "MIT" repository = "https://github.com/gorules/zen.git" diff --git a/core/template/CHANGELOG.md b/core/template/CHANGELOG.md index f5a882bb..db4e07b3 100644 --- a/core/template/CHANGELOG.md +++ b/core/template/CHANGELOG.md @@ -1,5 +1,33 @@ # Changelog +## [2.1.8](https://github.com/gorules/zen/compare/zen-tmpl-v2.1.7...zen-tmpl-v2.1.8) (2026-11-19) + + +### Miscellaneous + +* **zen-tmpl:** Synchronize core versions + + +### Dependencies + +* The following workspace dependencies were updated + * dependencies + * zen-expression bumped from 2.1.7 to 2.1.8 + +## [2.1.7](https://github.com/gorules/zen/compare/zen-tmpl-v2.1.6...zen-tmpl-v2.1.7) (2026-11-09) + + +### Miscellaneous + +* **zen-tmpl:** Synchronize core versions + + +### Dependencies + +* The following workspace dependencies were updated + * dependencies + * zen-expression bumped from 2.1.6 to 2.1.7 + ## [2.1.6](https://github.com/gorules/zen/compare/zen-tmpl-v2.1.5...zen-tmpl-v2.1.6) (2026-10-21) diff --git a/core/template/Cargo.toml b/core/template/Cargo.toml index 87dc4ecb..2991f4c7 100644 --- a/core/template/Cargo.toml +++ b/core/template/Cargo.toml @@ -3,13 +3,13 @@ authors = ["GoRules Team "] description = "Zen Template Language" name = "zen-tmpl" license = "MIT" -version = "2.1.6" +version = "2.1.8" edition = "2021" repository = "https://github.com/gorules/zen.git" homepage = "https://gorules.io" [dependencies] -zen-expression = { path = "../expression", version = "2.1.6" } +zen-expression = { path = "../expression", version = "2.1.8" } thiserror = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } diff --git a/core/types/CHANGELOG.md b/core/types/CHANGELOG.md index eaa16792..0fdbf6a5 100644 --- a/core/types/CHANGELOG.md +++ b/core/types/CHANGELOG.md @@ -1,5 +1,19 @@ # Changelog +## [2.1.8](https://github.com/gorules/zen/compare/zen-types-v2.1.7...zen-types-v2.1.8) (2026-11-19) + + +### Miscellaneous + +* **zen-types:** Synchronize core versions + +## [2.1.7](https://github.com/gorules/zen/compare/zen-types-v2.1.6...zen-types-v2.1.7) (2026-11-09) + + +### Miscellaneous + +* **zen-types:** Synchronize core versions + ## [2.1.6](https://github.com/gorules/zen/compare/zen-types-v2.1.5...zen-types-v2.1.6) (2026-10-21) diff --git a/core/types/Cargo.toml b/core/types/Cargo.toml index 4f6c9d1a..8860747d 100644 --- a/core/types/Cargo.toml +++ b/core/types/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "zen-types" description = "Zen Core Types" -version = "2.1.6" +version = "2.1.8" edition = "2024" rust-version = "1.88" license = "MIT"