diff --git a/.github/DISCUSSION_TEMPLATE/q-a.yml b/.github/DISCUSSION_TEMPLATE/q-a.yml index 6ed5d12..427014e 100644 --- a/.github/DISCUSSION_TEMPLATE/q-a.yml +++ b/.github/DISCUSSION_TEMPLATE/q-a.yml @@ -10,7 +10,7 @@ body: id: package-version attributes: label: Package and version - placeholder: "packvium-native-rust 1.8.0 (Rust)" + placeholder: "packvium-native-rust 1.9.0 (Rust)" validations: required: true - type: textarea diff --git a/.github/DISCUSSION_TEMPLATE/show-and-tell.yml b/.github/DISCUSSION_TEMPLATE/show-and-tell.yml index 6aa24ba..d1ddf42 100644 --- a/.github/DISCUSSION_TEMPLATE/show-and-tell.yml +++ b/.github/DISCUSSION_TEMPLATE/show-and-tell.yml @@ -16,7 +16,7 @@ body: id: package-version attributes: label: Package and version - placeholder: "packvium-native-rust 1.8.0 (Rust)" + placeholder: "packvium-native-rust 1.9.0 (Rust)" validations: required: false - type: textarea diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml index 1a949f3..799c36d 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.yml +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -33,8 +33,8 @@ body: id: version attributes: label: Package version - description: The exact version installed, for example 1.8.0. - placeholder: "1.8.0" + description: The exact version installed, for example 1.9.0. + placeholder: "1.9.0" validations: required: true - type: input diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml index 3f11eee..ced8846 100644 --- a/.github/ISSUE_TEMPLATE/feature_request.yml +++ b/.github/ISSUE_TEMPLATE/feature_request.yml @@ -29,7 +29,7 @@ body: id: version attributes: label: Package version - placeholder: "1.8.0" + placeholder: "1.9.0" validations: required: true - type: textarea diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 27bae9f..516d67c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -13,7 +13,7 @@ jobs: rust: runs-on: ubuntu-latest steps: - - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0 - uses: dtolnay/rust-toolchain@46511b1c83438f0dd37c02d843619ece5a4abb5b # 1.97.1 with: components: rustfmt, clippy @@ -33,13 +33,13 @@ jobs: os: [ubuntu-24.04, ubuntu-24.04-arm, macos-latest, macos-15-intel, windows-latest] python: ["3.9", "3.14"] steps: - - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0 # The components rust-toolchain.toml names, installed up front: left to maturin's first # `cargo metadata`, rustup tries to add rustfmt over the runner's own cargo-fmt and fails. - uses: dtolnay/rust-toolchain@46511b1c83438f0dd37c02d843619ece5a4abb5b # 1.97.1 with: components: rustfmt, clippy - - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5 + - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6.3.0 with: python-version: ${{ matrix.python }} - run: python -m pip install "maturin>=1.9.4,<2" @@ -59,11 +59,11 @@ jobs: - {target: x86_64-apple-darwin, platform: darwin-x64, runner: macos-15-intel} - {target: x86_64-pc-windows-msvc, platform: win32-x64-msvc, runner: windows-latest} steps: - - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0 - uses: dtolnay/rust-toolchain@46511b1c83438f0dd37c02d843619ece5a4abb5b # 1.97.1 with: targets: ${{ matrix.target }} - - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 + - uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0 with: {node-version: "22"} - run: cargo build --release --locked -p packvium-node-native --target ${{ matrix.target }} - run: node scripts/stage-node-addon.mjs ${{ matrix.target }} @@ -74,7 +74,7 @@ jobs: (cd bindings/node && npm pack --dry-run) (cd bindings/node/npm/${{ matrix.platform }} && npm pack --dry-run) - if: matrix.platform == 'linux-x64-gnu' - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 + uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0 with: name: addon-linux-x64-gnu path: bindings/node/packvium-native.linux-x64-gnu.node @@ -88,11 +88,11 @@ jobs: matrix: node: ["16", "18", "20", "22", "24", "26"] steps: - - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 - - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0 + - uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0 with: node-version: ${{ matrix.node }} - - uses: actions/download-artifact@fa0a91b85d4f404e444e00e005971372dc801d16 # v4.1.8 + - uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7.0.0 with: {name: addon-linux-x64-gnu, path: bindings/node} - run: node tests/node/addon.test.mjs @@ -108,16 +108,16 @@ jobs: - {target: x86_64-apple-darwin, library: libpackvium_ffi.dylib, runner: macos-15-intel} - {target: x86_64-pc-windows-msvc, library: packvium_ffi.dll, runner: windows-latest} steps: - - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0 - uses: dtolnay/rust-toolchain@46511b1c83438f0dd37c02d843619ece5a4abb5b # 1.97.1 with: targets: ${{ matrix.target }} - - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5 + - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6.3.0 with: {python-version: "3.13"} - run: cargo build --release --locked -p packvium-ffi --target ${{ matrix.target }} - run: python tests/ffi/ffi_smoke.py target/${{ matrix.target }}/release/${{ matrix.library }} - if: matrix.target == 'x86_64-unknown-linux-gnu' - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 + uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0 with: name: ffi-linux-x64 path: target/${{ matrix.target }}/release/${{ matrix.library }} @@ -133,8 +133,8 @@ jobs: matrix: php: ["8.2", "8.3", "8.4", "8.5"] steps: - - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 - - uses: actions/download-artifact@fa0a91b85d4f404e444e00e005971372dc801d16 # v4.1.8 + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0 + - uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7.0.0 with: {name: ffi-linux-x64, path: lib} - uses: shivammathur/setup-php@f3e473d116dcccaddc5834248c87452386958240 # v2 with: @@ -160,7 +160,7 @@ jobs: contents: read pull-requests: write steps: - - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0 - uses: actions/dependency-review-action@a1d282b36b6f3519aa1f3fc636f609c47dddb294 # v5.0.0 with: fail-on-severity: low diff --git a/.github/workflows/rc.yml b/.github/workflows/rc.yml index d39348c..2f446d0 100644 --- a/.github/workflows/rc.yml +++ b/.github/workflows/rc.yml @@ -17,7 +17,7 @@ jobs: verify-tag: runs-on: ubuntu-latest steps: - - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0 # The tag and every packaged version must agree. Without this, `git tag v0.2.0` on a # tree that still says 0.1.0 publishes 0.1.0 under a name that claims otherwise, and the # mistake is only visible after it is public and immutable. diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 50e0d53..c87a303 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -26,7 +26,7 @@ jobs: verify-tag: runs-on: ubuntu-latest steps: - - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0 # The tag and every packaged version must agree. Without this, `git tag v0.2.0` on a # tree that still says 0.1.0 publishes 0.1.0 under a name that claims otherwise, and the # mistake is only visible after it is public and immutable. @@ -66,9 +66,9 @@ jobs: runs-on: ${{ matrix.arch == 'aarch64' && 'ubuntu-24.04-arm' || 'ubuntu-latest' }} container: quay.io/pypa/manylinux_2_28_${{ matrix.arch }} steps: - - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0 - name: Install the pinned Rust toolchain - run: curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal --default-toolchain 1.97.1 + run: curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal --default-toolchain 1.97.1 --component rustfmt,clippy - name: Build an abi3-py39 manylinux_2_28 wheel working-directory: bindings/python run: | @@ -81,7 +81,7 @@ jobs: "$python" -m pip install --quiet --no-index --find-links bindings/python/dist packvium-native-rust "$python" -m unittest discover -s tests/python -v done - - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 + - uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0 with: name: wheel-linux-${{ matrix.arch }} path: bindings/python/dist/*.whl @@ -94,9 +94,13 @@ jobs: os: [macos-15, macos-15-intel, windows-latest] runs-on: ${{ matrix.os }} steps: - - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0 + # The components rust-toolchain.toml names, installed up front: left to maturin's first + # `cargo metadata`, rustup tries to add rustfmt over the runner's own cargo-fmt and fails. - uses: dtolnay/rust-toolchain@46511b1c83438f0dd37c02d843619ece5a4abb5b # 1.97.1 - - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5 + with: + components: rustfmt, clippy + - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6.3.0 with: python-version: "3.9" - run: python -m pip install "maturin>=1.9.4,<2" @@ -105,12 +109,12 @@ jobs: - run: python -m pip install --no-index --find-links bindings/python/dist packvium-native-rust - run: python -m unittest discover -s tests/python -v # Test the exact floor-built wheel on the newest interpreter before publishing it. - - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5 + - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6.3.0 with: python-version: "3.14" - run: python -m pip install --no-index --find-links bindings/python/dist packvium-native-rust - run: python -m unittest discover -s tests/python -v - - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 + - uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0 with: name: wheel-${{ matrix.os }} path: bindings/python/dist/*.whl @@ -127,16 +131,16 @@ jobs: - {target: x86_64-pc-windows-msvc, platform: win32-x64-msvc, runner: windows-latest} runs-on: ${{ matrix.runner }} steps: - - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0 - uses: dtolnay/rust-toolchain@46511b1c83438f0dd37c02d843619ece5a4abb5b # 1.97.1 with: targets: ${{ matrix.target }} - - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 + - uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0 with: {node-version: "22"} - run: cargo build --release --locked -p packvium-node-native --target ${{ matrix.target }} - run: node scripts/stage-node-addon.mjs ${{ matrix.target }} - run: node tests/node/addon.test.mjs - - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 + - uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0 with: name: addon-${{ matrix.platform }} path: bindings/node/npm/${{ matrix.platform }}/packvium-native.${{ matrix.platform }}.node @@ -154,11 +158,11 @@ jobs: - {target: x86_64-pc-windows-msvc, library: packvium_ffi.dll, asset: packvium_ffi-x86_64-pc-windows-msvc.dll, runner: windows-latest} runs-on: ${{ matrix.runner }} steps: - - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0 - uses: dtolnay/rust-toolchain@46511b1c83438f0dd37c02d843619ece5a4abb5b # 1.97.1 with: targets: ${{ matrix.target }} - - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5 + - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6.3.0 with: {python-version: "3.13"} - run: cargo build --release --locked -p packvium-ffi --target ${{ matrix.target }} - run: python tests/ffi/ffi_smoke.py target/${{ matrix.target }}/release/${{ matrix.library }} @@ -167,7 +171,7 @@ jobs: run: | mkdir -p assets cp "target/${{ matrix.target }}/release/${{ matrix.library }}" "assets/${{ matrix.asset }}" - - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 + - uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0 with: name: ffi-${{ matrix.target }} path: assets/${{ matrix.asset }} @@ -182,14 +186,14 @@ jobs: id-token: write # the attestation attestations: write # build provenance, so a consumer can verify where a file came from steps: - - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 - - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0 + - uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0 with: {node-version: "22"} - - uses: actions/download-artifact@fa0a91b85d4f404e444e00e005971372dc801d16 # v4.1.8 + - uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7.0.0 with: {pattern: wheel-*, path: dist, merge-multiple: true} - - uses: actions/download-artifact@fa0a91b85d4f404e444e00e005971372dc801d16 # v4.1.8 + - uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7.0.0 with: {pattern: addon-*, path: addons} - - uses: actions/download-artifact@fa0a91b85d4f404e444e00e005971372dc801d16 # v4.1.8 + - uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7.0.0 with: {pattern: ffi-*, path: assets, merge-multiple: true} - name: Five wheels, four addons and five libraries, no more and no fewer run: | @@ -239,11 +243,11 @@ jobs: dist/*.whl packages/*.tgz assets/* - - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 + - uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0 with: {name: wheels, path: dist/*.whl} - - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 + - uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0 with: {name: npm-packages, path: packages/*.tgz} - - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 + - uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0 with: {name: release-assets, path: assets/*} publish-pypi: @@ -253,7 +257,7 @@ jobs: permissions: id-token: write # OIDC, for Trusted Publishing and PyPI's own attestations steps: - - uses: actions/download-artifact@fa0a91b85d4f404e444e00e005971372dc801d16 # v4.1.8 + - uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7.0.0 with: {name: wheels, path: dist} # A re-run after a partial upload finishes the release instead of failing on the files # already there; PyPI never lets an existing file be replaced, so nothing is overwritten. @@ -269,7 +273,7 @@ jobs: permissions: id-token: write # npm Trusted Publishing and provenance steps: - - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 + - uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0 with: {node-version: "22", registry-url: "https://registry.npmjs.org"} # npm's OIDC trusted publishing needs npm 11.5.1 or newer; Node 22 still bundles npm 10, # which performs no OIDC exchange at all. The publish then goes out unauthenticated and @@ -277,7 +281,7 @@ jobs: # rather than a missing credential. - run: npm install -g npm@^11.5.1 - run: npm --version - - uses: actions/download-artifact@fa0a91b85d4f404e444e00e005971372dc801d16 # v4.1.8 + - uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7.0.0 with: {name: npm-packages, path: packages} # Platform packages first: the root package names them as optional dependencies, and a # pin must never point at a version the registry does not serve. @@ -307,8 +311,8 @@ jobs: permissions: contents: write # the Release is the only thing this workflow writes to the repository steps: - - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 - - uses: actions/download-artifact@fa0a91b85d4f404e444e00e005971372dc801d16 # v4.1.8 + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0 + - uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7.0.0 with: {name: release-assets, path: assets} - name: Create the GitHub Release from the tag, with the C libraries attached env: diff --git a/CHANGELOG.md b/CHANGELOG.md index 8813c74..a6067fc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,12 @@ PyPI, `@packvium/native` and its platform packages on npm, and the C library on Releases. The format follows [Keep a Changelog](https://keepachangelog.com/1.1.0/) and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [1.9.0] + +The compiled engines rebuilt on the 1.9.0 core: the centre of gravity is checked under a support +ratio, a length past `2^53 - 1` ticks or an empty side is refused with a pointer, nesting under a +clearance agrees with the other engines, and `exact_small` is 9-28% faster where it runs. + ## [1.8.0] The first release of the compiled engines. Each binary is built from the Rust source in this diff --git a/CITATION.cff b/CITATION.cff index 9e94698..a23a13b 100644 --- a/CITATION.cff +++ b/CITATION.cff @@ -5,7 +5,7 @@ type: software authors: - name: "Packvium contributors" website: "https://packvium.com" -version: "1.8.0" +version: "1.9.0" license: MIT url: "https://packvium.com" repository-code: "https://github.com/toxakara/packvium-native" diff --git a/Cargo.lock b/Cargo.lock index 624aa13..2450eed 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -288,7 +288,7 @@ checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" [[package]] name = "packvium-core" -version = "1.8.0" +version = "1.9.0" dependencies = [ "libc", "serde", @@ -300,7 +300,7 @@ dependencies = [ [[package]] name = "packvium-ffi" -version = "1.8.0" +version = "1.9.0" dependencies = [ "packvium-core", "serde_json", @@ -308,7 +308,7 @@ dependencies = [ [[package]] name = "packvium-node-native" -version = "1.8.0" +version = "1.9.0" dependencies = [ "napi", "napi-build", @@ -318,7 +318,7 @@ dependencies = [ [[package]] name = "packvium-python-native" -version = "1.8.0" +version = "1.9.0" dependencies = [ "packvium-core", "pyo3", diff --git a/Cargo.toml b/Cargo.toml index aca319f..e32efaa 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -9,7 +9,7 @@ members = [ default-members = ["crates/packvium-core", "crates/packvium-ffi"] [workspace.package] -version = "1.8.0" +version = "1.9.0" edition = "2024" rust-version = "1.88" license = "MIT" @@ -26,4 +26,4 @@ thiserror = "2.0.19" # package hashes too; default features off, it needs nothing from std. sha2 = { version = "0.10.9", default-features = false } web-time = "1.1.0" -packvium-core = { path = "crates/packvium-core", version = "1.8.0" } +packvium-core = { path = "crates/packvium-core", version = "1.9.0" } diff --git a/bindings/node/index.js b/bindings/node/index.js index 6b47a5c..1172c16 100644 --- a/bindings/node/index.js +++ b/bindings/node/index.js @@ -13,7 +13,7 @@ 'use strict'; /** The release this loader belongs to; a binary from any other release is refused. */ -const EXPECTED_VERSION = '1.8.0'; +const EXPECTED_VERSION = '1.9.0'; function firstLoadable(attempts) { const failures = []; diff --git a/bindings/node/npm/darwin-arm64/package.json b/bindings/node/npm/darwin-arm64/package.json index 4196775..f9d5678 100644 --- a/bindings/node/npm/darwin-arm64/package.json +++ b/bindings/node/npm/darwin-arm64/package.json @@ -1,6 +1,6 @@ { "name": "@packvium/native-darwin-arm64", - "version": "1.8.0", + "version": "1.9.0", "cpu": [ "arm64" ], diff --git a/bindings/node/npm/darwin-x64/package.json b/bindings/node/npm/darwin-x64/package.json index 9c7d4b9..18f422b 100644 --- a/bindings/node/npm/darwin-x64/package.json +++ b/bindings/node/npm/darwin-x64/package.json @@ -1,6 +1,6 @@ { "name": "@packvium/native-darwin-x64", - "version": "1.8.0", + "version": "1.9.0", "cpu": [ "x64" ], diff --git a/bindings/node/npm/linux-x64-gnu/package.json b/bindings/node/npm/linux-x64-gnu/package.json index 8515094..e763c3b 100644 --- a/bindings/node/npm/linux-x64-gnu/package.json +++ b/bindings/node/npm/linux-x64-gnu/package.json @@ -1,6 +1,6 @@ { "name": "@packvium/native-linux-x64-gnu", - "version": "1.8.0", + "version": "1.9.0", "cpu": [ "x64" ], diff --git a/bindings/node/npm/win32-x64-msvc/package.json b/bindings/node/npm/win32-x64-msvc/package.json index e0f876f..5842d1d 100644 --- a/bindings/node/npm/win32-x64-msvc/package.json +++ b/bindings/node/npm/win32-x64-msvc/package.json @@ -1,6 +1,6 @@ { "name": "@packvium/native-win32-x64-msvc", - "version": "1.8.0", + "version": "1.9.0", "cpu": [ "x64" ], diff --git a/bindings/node/package.json b/bindings/node/package.json index 3b056f0..7fd36f9 100644 --- a/bindings/node/package.json +++ b/bindings/node/package.json @@ -1,6 +1,6 @@ { "name": "@packvium/native", - "version": "1.8.0", + "version": "1.9.0", "description": "Compiled Rust engine for @packvium/engine. Not meant to be installed directly.", "license": "MIT", "main": "index.js", @@ -31,9 +31,9 @@ "url": "https://github.com/toxakara/packvium-native/issues" }, "optionalDependencies": { - "@packvium/native-darwin-arm64": "1.8.0", - "@packvium/native-darwin-x64": "1.8.0", - "@packvium/native-win32-x64-msvc": "1.8.0", - "@packvium/native-linux-x64-gnu": "1.8.0" + "@packvium/native-darwin-arm64": "1.9.0", + "@packvium/native-darwin-x64": "1.9.0", + "@packvium/native-win32-x64-msvc": "1.9.0", + "@packvium/native-linux-x64-gnu": "1.9.0" } } diff --git a/bindings/python/pyproject.toml b/bindings/python/pyproject.toml index 7bcb4b4..ba43187 100644 --- a/bindings/python/pyproject.toml +++ b/bindings/python/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "maturin" [project] name = "packvium-native-rust" -version = "1.8.0" +version = "1.9.0" requires-python = ">=3.9" description = "Compiled Rust backend for Packvium, consumed by the packvium-native selector" readme = "README.md" diff --git a/codemeta.json b/codemeta.json index ad216af..a87a577 100644 --- a/codemeta.json +++ b/codemeta.json @@ -3,7 +3,7 @@ "@type": "SoftwareSourceCode", "name": "Packvium native engines: Python wheels, Node addons and the C library", "description": "Compiled Rust backend for Packvium, consumed by the packvium-native selector", - "version": "1.8.0", + "version": "1.9.0", "license": "https://spdx.org/licenses/MIT", "author": [ { diff --git a/crates/packvium-core/src/api.rs b/crates/packvium-core/src/api.rs index 474760e..ce70249 100644 --- a/crates/packvium-core/src/api.rs +++ b/crates/packvium-core/src/api.rs @@ -1855,9 +1855,27 @@ fn parse_aabb(map: &Map, unit: &str) -> PackResult { fn parse_point(value: Option<&Value>, unit: &str) -> PackResult { let point = value.and_then(Value::as_object); Ok(Point { - x: parse_optional_length(point.and_then(|value| value.get("x")), unit)?.0, - y: parse_optional_length(point.and_then(|value| value.get("y")), unit)?.0, - z: parse_optional_length(point.and_then(|value| value.get("z")), unit)?.0, + x: parse_optional_length( + point + .and_then(|value| value.get("x")) + .filter(|value| !value.is_null()), + unit, + )? + .0, + y: parse_optional_length( + point + .and_then(|value| value.get("y")) + .filter(|value| !value.is_null()), + unit, + )? + .0, + z: parse_optional_length( + point + .and_then(|value| value.get("z")) + .filter(|value| !value.is_null()), + unit, + )? + .0, }) } diff --git a/crates/packvium-core/src/commerce/document.rs b/crates/packvium-core/src/commerce/document.rs index 378b7e7..53cba30 100644 --- a/crates/packvium-core/src/commerce/document.rs +++ b/crates/packvium-core/src/commerce/document.rs @@ -477,6 +477,9 @@ fn publish_catalog_version( let effective_at = optional(fields, "effective_at") .map(|found| integer(found, &format!("{path}.effective_at"))) .transpose()?; + if published_at < 0 || effective_at.is_some_and(|value| value < 0) { + return fail(path, "effective_at and published_at cannot be negative"); + } let note = match optional(fields, "note") { None => String::new(), Some(found) => text(found, &format!("{path}.note"))?, diff --git a/crates/packvium-core/src/commerce/mod.rs b/crates/packvium-core/src/commerce/mod.rs index 896c5de..c515353 100644 --- a/crates/packvium-core/src/commerce/mod.rs +++ b/crates/packvium-core/src/commerce/mod.rs @@ -141,6 +141,9 @@ pub fn catalog_version_info_json(input: &str) -> Result bool { @@ -139,6 +139,11 @@ fn values_equal(left: &Value, right: &Value) -> bool { (Value::Array(a), Value::Array(b)) => { a.len() == b.len() && a.iter().zip(b).all(|(x, y)| values_equal(x, y)) } + (Value::Object(a), Value::Object(b)) => { + a.len() == b.len() + && a.iter() + .all(|(key, value)| b.get(key).is_some_and(|other| values_equal(value, other))) + } _ => false, } } @@ -150,6 +155,10 @@ fn contains(haystack: &Value, needle: &Value) -> bool { Value::String(part) => text.contains(part.as_str()), _ => false, }, + Value::Object(entries) => match needle { + Value::String(key) => entries.contains_key(key), + _ => false, + }, _ => false, } } @@ -305,7 +314,10 @@ pub fn decide( // context, so one permissive rule can never quietly override a more specific denial. let pool = if rejects.is_empty() { allows } else { rejects }; let winner = pool.into_iter().min_by(|left, right| { - (-left.priority, &left.rule_id).cmp(&(-right.priority, &right.rule_id)) + right + .priority + .cmp(&left.priority) + .then_with(|| left.rule_id.cmp(&right.rule_id)) }); match winner { diff --git a/crates/packvium-core/src/lib.rs b/crates/packvium-core/src/lib.rs index 5de000e..8c52129 100644 --- a/crates/packvium-core/src/lib.rs +++ b/crates/packvium-core/src/lib.rs @@ -28,6 +28,7 @@ mod sequence; mod solver; mod solvers; mod spatial_index; +mod support_polygon; mod units; mod validation; mod value_text; diff --git a/crates/packvium-core/src/model.rs b/crates/packvium-core/src/model.rs index f5087b6..5432397 100644 --- a/crates/packvium-core/src/model.rs +++ b/crates/packvium-core/src/model.rs @@ -265,7 +265,7 @@ pub fn crushed(placements: &[Placement], loads: &[i128]) -> Option<(String, Stri let Some(limit) = item.max_compression_pressure_kpa else { continue; }; - if crush_exceeded(limit, *load, placement.envelope_dimensions.base_area()) { + if crush_exceeded(limit, *load, placement.dimensions.base_area()) { return Some(("crush_violation".into(), placement.instance.id())); } } @@ -984,10 +984,7 @@ impl PackedContainer { for (index, placement) in self.placements.iter().enumerate() { for other in self.placements.iter().skip(index + 1) { if valid_nesting(placement, other) { - overlap = overlap.saturating_add( - placement.instance.item.nesting_height.unwrap_or_default().0 as i128 - * placement.envelope_dimensions.base_area(), - ); + overlap = overlap.saturating_add(nested_overlap(placement, other)); } } } @@ -1360,6 +1357,43 @@ fn ceil_div(a: i128, b: i128) -> i128 { -(-a).div_euclid(b) } +/// The physical space a valid nesting pair shares. The pair sinks by `nesting_height` +/// envelope to envelope, so under a clearance the items themselves overlap by twice the +/// clearance less, over their own footprint rather than the envelope's. Equal to +/// `nesting_height x base area` with no clearance. `O(1)`. +pub fn nested_overlap(lower: &Placement, upper: &Placement) -> i128 { + let (a, b) = (lower.box_(), upper.box_()); + let height = i128::from(a.z2().min(b.z2()) - a.origin.z.max(b.origin.z)); + if height > 0 { + a.overlap_area_xy(b).saturating_mul(height) + } else { + 0 + } +} + +/// The bottom of layer `layer` in a column of identical envelopes `height` tall that each sink +/// `nesting` into the one beneath. Only a directly adjacent pair may overlap: +/// once `2 x nesting > height` a third copy sunk into the second would reach into the first, +/// so the column nests in pairs, the third resting on the pair. `O(1)`. +pub(crate) fn column_layer_z(layer: i64, height: i64, nesting: i64) -> i64 { + if 2 * nesting <= height { + return layer * (height - nesting); + } + layer / 2 * (2 * height - nesting) + layer % 2 * (height - nesting) +} + +/// How many layers `column_layer_z` fits under `room`. `O(1)`. +pub(crate) fn column_layers(room: i64, height: i64, nesting: i64) -> i64 { + if room < height { + return 0; + } + if 2 * nesting <= height { + return (room - height) / (height - nesting) + 1; + } + let pair = 2 * height - nesting; + 2 * (room / pair) + i64::from(room % pair >= height) +} + pub fn valid_nesting(a: &Placement, b: &Placement) -> bool { if a.instance.item.id != b.instance.item.id { return false; @@ -2295,4 +2329,24 @@ mod tests { SIDE as i128 * SIDE as i128 * SIDE as i128 / 2 ); } + + #[test] + fn a_nest_deeper_than_half_the_height_goes_in_pairs() { + // 120-tick cups nesting 100: a third sunk into the second would reach the first. + let bottoms: Vec = (0..5) + .map(|layer| column_layer_z(layer, 120, 100)) + .collect(); + assert_eq!(bottoms, [0, 20, 140, 160, 280]); + assert_eq!(column_layers(400, 120, 100), 5); + assert_eq!(column_layers(399, 120, 100), 4); + assert_eq!(column_layers(119, 120, 100), 0); + } + + #[test] + fn a_nest_of_at_most_half_the_height_chains_every_layer() { + let bottoms: Vec = (0..3).map(|layer| column_layer_z(layer, 100, 50)).collect(); + assert_eq!(bottoms, [0, 50, 100]); + assert_eq!(column_layers(200, 100, 50), 3); + assert_eq!(column_layers(280, 100, 40), 4); + } } diff --git a/crates/packvium-core/src/rebalance.rs b/crates/packvium-core/src/rebalance.rs index d3c92c0..7a56339 100644 --- a/crates/packvium-core/src/rebalance.rs +++ b/crates/packvium-core/src/rebalance.rs @@ -85,6 +85,12 @@ fn candidate_points(container: &PackedContainer) -> Vec { points.insert((box_.x2(), box_.origin.y, box_.origin.z)); points.insert((box_.origin.x, box_.y2(), box_.origin.z)); points.insert((box_.origin.x, box_.origin.y, box_.z2())); + if let Some(depth) = placement.instance.item.nesting_height { + let nested_z = box_.z2() - depth.0; + if nested_z >= 0 { + points.insert((box_.origin.x, box_.origin.y, nested_z)); + } + } } let mut points = points .into_iter() @@ -168,22 +174,25 @@ pub fn rebalance_weight( break; } let source_index = (0..working.len()) - .max_by_key(|index| weights[*index]) + .max_by_key(|index| (weights[*index], std::cmp::Reverse(*index))) .unwrap(); let mut placements = (0..working[source_index].placements.len()).collect::>(); placements.sort_by_key(|index| { - std::cmp::Reverse( - working[source_index].placements[*index] - .instance - .item - .weight - .0, + ( + std::cmp::Reverse( + working[source_index].placements[*index] + .instance + .item + .weight + .0, + ), + *index, ) }); let mut destinations = (0..working.len()) .filter(|index| *index != source_index) .collect::>(); - destinations.sort_by_key(|index| weights[*index]); + destinations.sort_by_key(|index| (weights[*index], *index)); let mut committed = None; 'search: for placement_index in placements { @@ -582,4 +591,74 @@ mod tests { assert!(IndependentValidator.validate(&request, &trial).valid); } } + + #[test] + fn a_nesting_item_offers_the_point_where_the_next_one_sinks_into_it() { + let mut tote = item("tote", 100, 1); + tote.nesting_height = Some(Length(5)); + let packed = PackedContainer { + container: container(), + sequence: 1, + placements: vec![placement(&tote, 1, 0, 0)], + lattice_summary: None, + lattice_items: Vec::new(), + }; + + let points = candidate_points(&packed); + + assert!(points.contains(&Point { x: 0, y: 0, z: 5 }), "{points:?}"); + assert!(points.contains(&Point { x: 0, y: 0, z: 10 }), "{points:?}"); + } + + #[test] + fn tied_heaviest_containers_select_the_first_and_consider_nesting_points() { + let mut tote = item("tote", 100, 4); + tote.nesting_height = Some(Length(5)); + let mut narrow = container(); + narrow.inner_dimensions = Dimensions { + length: Length(10), + width: Length(10), + height: Length(15), + }; + narrow.quantity = Some(3); + let request = PackingRequest { + items: vec![tote.clone()], + containers: vec![narrow.clone()], + config: PackingConfig::default(), + output_length_unit: "ticks".into(), + output_weight_unit: "ticks".into(), + catalog_versions_used: Vec::new(), + fixed_placements: Vec::new(), + fixed_containers: Vec::new(), + }; + let original = result(vec![ + PackedContainer { + container: narrow.clone(), + sequence: 1, + placements: vec![placement(&tote, 1, 0, 0), placement(&tote, 2, 0, 5)], + lattice_summary: None, + lattice_items: Vec::new(), + }, + PackedContainer { + container: narrow.clone(), + sequence: 2, + placements: vec![placement(&tote, 3, 0, 0), placement(&tote, 4, 0, 5)], + lattice_summary: None, + lattice_items: Vec::new(), + }, + PackedContainer { + container: narrow, + sequence: 3, + placements: Vec::new(), + lattice_summary: None, + lattice_items: Vec::new(), + }, + ]); + + let balanced = rebalance_weight(&request, &original, 1); + + assert_eq!(balanced.moves.len(), 1); + assert_eq!(balanced.moves[0].from_container_id, "box#1"); + assert_eq!(balanced.moves[0].to_container_id, "box#3"); + } } diff --git a/crates/packvium-core/src/request_errors.rs b/crates/packvium-core/src/request_errors.rs index f7964d4..c37a3a7 100644 --- a/crates/packvium-core/src/request_errors.rs +++ b/crates/packvium-core/src/request_errors.rs @@ -11,7 +11,7 @@ use crate::canonical_json::{MAX_EXACT_MAGNITUDE, json_integer, json_spelling, sp use crate::error::RequestError; use crate::fixed::unknown_keys; use crate::made_to_measure::MadeToMeasure; -use crate::units::{MeasureKind, measure_ticks}; +use crate::units::{MeasureKind, Overflowed, measure_ticks, overflowed_measure}; use serde_json::{Map, Value}; use std::collections::BTreeSet; @@ -84,6 +84,14 @@ const CONFIGURATION_FIELDS: [&str; 20] = [ "time_limit_ms", ]; const SIDES: [&str; 3] = ["length", "width", "height"]; +/// The admission ceiling every engine refuses past: a length is a tick count +/// every engine holds exactly, JavaScript's `Number` included, and a box encloses no more than +/// the bound path can sum, so `volume x 10^6` stays inside `i128`. +const MAX_LENGTH_TICKS: u64 = MAX_EXACT_MAGNITUDE; +const MAX_VOLUME_TICKS3: i128 = 10_i128.pow(30); +/// A weight, and every item's weight times its quantity plus the heaviest tare, fit an `i64`, +/// which is how the search adds a container's payload (R19-01). +const MAX_WEIGHT_TICKS: u64 = i64::MAX as u64; /// The item fields the request schema types `boolean`, in schema order. const ITEM_BOOLEANS: [&str; 3] = ["keep_upright", "stackable", "must_be_on_floor"]; const AXES: [&str; 3] = ["x", "y", "z"]; @@ -106,9 +114,39 @@ pub(crate) fn check_request(data: &Value) -> Checked<&str> { check_container(raw, &join("/containers", &index.to_string()), unit)?; } require_unique_ids(containers, "containers")?; + total_weight(items, containers)?; Ok(unit) } +/// Every item's weight times its quantity, plus the heaviest tare, against `MAX_WEIGHT_TICKS`: +/// no container's gross weight can pass it. Each value was admitted above. O(items + containers). +fn total_weight(items: &[Value], containers: &[Value]) -> Checked { + let ticks = |holder: &Value, name: &str| { + present(holder.get(name)) + .and_then(|value| measure_ticks(value, "g", MeasureKind::Weight).ok()) + .unwrap_or(0) + }; + let heaviest_tare = containers + .iter() + .map(|container| ticks(container, "tare_weight")) + .max() + .unwrap_or(0); + let total = items.iter().fold(heaviest_tare, |total, item| { + let quantity = present(item.get("quantity")) + .and_then(json_integer) + .map_or(1, i128::from); + total.saturating_add(ticks(item, "weight").saturating_mul(quantity)) + }); + if total > i128::from(MAX_WEIGHT_TICKS) { + return Err(RequestError::new( + "above_maximum", + "/items", + format!("must weigh at most {MAX_WEIGHT_TICKS} ticks in all, with the heaviest tare"), + )); + } + Ok(()) +} + /// `base` extended by one RFC 6901 reference token, escaping `~` and `/` in it. pub(crate) fn join(base: &str, part: &str) -> String { format!("{base}/{}", part.replace('~', "~0").replace('/', "~1")) @@ -328,7 +366,7 @@ fn check_container(raw: &Value, at: &str, unit: &str) -> Checked { optional(container, "tag_limits", at, tag_limits)?; optional(container, "rate_table", at, rate_table)?; optional(container, "obstacles", at, |value, field| { - obstacles(value, field, unit) + obstacles(value, field, unit, inner_ticks(container, unit)) })?; optional(container, "deformable_boundary", at, |value, field| { deformable_boundary(container, value, field, at) @@ -364,7 +402,7 @@ fn made_to_measure( } for name in ["minimum", "increment", "outer_allowance"] { optional(machine, name, field, |value, at| { - dimensions(value, at, unit) + sides(value, at, unit, false) })?; } optional( @@ -493,14 +531,36 @@ fn set_beside_a_bag(name: &str, value: Option<&Value>) -> bool { } fn dimensions(raw: &Value, at: &str, unit: &str) -> Checked { + sides(raw, at, unit, true) +} + +/// A box's three sides, each a measure; a box that holds or is something has no empty side +///, while a made-to-measure step states its own rule for zero. +fn sides(raw: &Value, at: &str, unit: &str, positive: bool) -> Checked { let sides = object(raw, at)?; + let mut volume = Some(1_i128); for side in SIDES { - measure( - required(sides, side, at)?, - &join(at, side), - MeasureKind::Length, - unit, - )?; + let value = required(sides, side, at)?; + let field = join(at, side); + measure(value, &field, MeasureKind::Length, unit)?; + let ticks = measure_ticks(value, unit, MeasureKind::Length).ok(); + if positive && ticks == Some(0) { + return Err(RequestError::new( + "invalid_value", + field, + "must be positive", + )); + } + volume = volume + .zip(ticks) + .and_then(|(volume, ticks)| volume.checked_mul(ticks)); + } + if volume.is_none_or(|volume| volume > MAX_VOLUME_TICKS3) { + return Err(RequestError::new( + "above_maximum", + at, + "must enclose at most 10^30 cubic ticks", + )); } Ok(()) } @@ -532,25 +592,67 @@ fn rate_table(raw: &Value, at: &str) -> Checked { Ok(()) } -fn obstacles(raw: &Value, at: &str, unit: &str) -> Checked { +fn obstacles(raw: &Value, at: &str, unit: &str, inner: [i128; 3]) -> Checked { for (index, entry) in list(raw, at)?.iter().enumerate() { let here = join(at, &index.to_string()); let obstacle = object(entry, &here)?; - if let Some(origin) = present(obstacle.get("origin")) { - let origin_at = join(&here, "origin"); - let point = object(origin, &origin_at)?; - for axis in AXES { - optional(point, axis, &origin_at, |value, field| { - measure(value, field, MeasureKind::Length, unit) - })?; + placed_box(obstacle, &here, unit, inner)?; + if let Some(extra) = present(obstacle.get("additional_boxes")) { + let boxes = join(&here, "additional_boxes"); + for (position, part) in list(extra, &boxes)?.iter().enumerate() { + let part_at = join(&boxes, &position.to_string()); + placed_box(object(part, &part_at)?, &part_at, unit, inner)?; } } - let sides = required(obstacle, "dimensions", &here)?; - dimensions(sides, &join(&here, "dimensions"), unit)?; } Ok(()) } +/// An optional `origin` and required `dimensions`: an obstacle, or one more box of it +///, whose measures are read in the request's unit like every other length, and +/// which lies inside the container. +fn placed_box(entry: &Map, here: &str, unit: &str, inner: [i128; 3]) -> Checked { + let origin = present(entry.get("origin")); + if let Some(origin) = origin { + let origin_at = join(here, "origin"); + let point = object(origin, &origin_at)?; + for axis in AXES { + optional(point, axis, &origin_at, |value, field| { + measure(value, field, MeasureKind::Length, unit) + })?; + } + } + let sides = required(entry, "dimensions", here)?; + dimensions(sides, &join(here, "dimensions"), unit)?; + let ticks = |value: Option<&Value>| { + value.map_or(0, |value| { + measure_ticks(value, unit, MeasureKind::Length).unwrap_or(0) + }) + }; + for (index, axis) in AXES.iter().enumerate() { + let start = ticks(origin.and_then(|origin| present(origin.get(*axis)))); + if start + ticks(sides.get(SIDES[index])) > inner[index] { + return Err(RequestError::new( + "invalid_value", + here, + "lies outside inner_dimensions", + )); + } + } + Ok(()) +} + +/// A container's inner sides in ticks, already checked by the time its obstacles are. +fn inner_ticks(container: &Map, unit: &str) -> [i128; 3] { + SIDES.map(|side| { + container + .get("inner_dimensions") + .and_then(|sides| sides.get(side)) + .and_then(|value| measure_ticks(value, unit, MeasureKind::Length).ok()) + .unwrap_or(0) + }) +} + /// Checked once every entry is well formed, so the later of two equal ids is the one named. fn require_unique_ids(entries: &[Value], key: &str) -> Checked { let mut seen = BTreeSet::new(); @@ -656,28 +758,102 @@ fn access_directions(raw: &Value, at: &str) -> Checked { each_one_of(raw, at, &ACCESS_DIRECTIONS) } -/// A measure is an integer, a string or `{value, unit}`, in a known unit, and never negative. +/// A measure is an integer, a string or `{value, unit}`, in a known unit, and never negative; +/// a length is at most `MAX_LENGTH_TICKS` and a weight at most `MAX_WEIGHT_TICKS`. fn measure(value: &Value, field: &str, kind: MeasureKind, unit: &str) -> Checked { + let length = kind == MeasureKind::Length; match value { // A fraction in binary floating point is not the decimal the caller wrote. - Value::Number(number) if number.is_f64() && json_integer(value).is_none() => { + Value::Number(number) + if number.is_f64() + && json_integer(value).is_none() + && whole_beyond_exact(value).is_none() => + { return Err(wrong_type(field, "must be a measure")); } Value::Number(_) | Value::String(_) => {} Value::Object(map) => require_measure_unit(map, field, kind, unit)?, _ => return Err(wrong_type(field, "must be a measure")), } + let amount = value.get("value").unwrap_or(value); + // Past 2^53 - 1 a JSON number is the same whole number to every engine however its parser + // stored it, and its ticks are past the ceiling in every unit. + if length && let Some(negative) = whole_beyond_exact(amount) { + return Err(if negative { + negative_measure(field) + } else { + too_long(field) + }); + } + // Past 2^53 - 1 JavaScript has already rounded a JSON number before it reads it, so a + // weight that large is written as a string, which every engine reads exactly. + if !length && let Some(negative) = whole_beyond_exact(amount) { + return Err(if negative { + negative_measure(field) + } else { + RequestError::new( + "invalid_value", + field, + format!("must be written as a string past {MAX_EXACT_MAGNITUDE}"), + ) + }); + } + let ceiling = if length { + MAX_LENGTH_TICKS + } else { + MAX_WEIGHT_TICKS + }; match measure_ticks(value, unit, kind) { - Ok(ticks) if ticks < 0 => Err(RequestError::new( - "negative_measure", - field, - "cannot be negative", - )), + Ok(ticks) if ticks < 0 => Err(negative_measure(field)), + Ok(ticks) if ticks > i128::from(ceiling) => Err(beyond(field, kind)), Ok(_) => Ok(()), - Err(_) => Err(wrong_type(field, "must be a measure")), + Err(_) => match overflowed_measure(value, unit, kind, ceiling) { + Overflowed::Negative => Err(negative_measure(field)), + Overflowed::Beyond => Err(beyond(field, kind)), + Overflowed::Unreadable => Err(wrong_type(field, "must be a measure")), + }, } } +fn beyond(field: &str, kind: MeasureKind) -> RequestError { + match kind { + MeasureKind::Length => too_long(field), + MeasureKind::Weight => RequestError::new( + "above_maximum", + field, + format!("must be at most {MAX_WEIGHT_TICKS} ticks"), + ), + } +} + +/// `Some(is negative)` for a whole JSON number past 2^53 - 1. +fn whole_beyond_exact(value: &Value) -> Option { + let Value::Number(number) = value else { + return None; + }; + let beyond = if let Some(integer) = number.as_i64() { + integer.unsigned_abs() > MAX_EXACT_MAGNITUDE + } else if let Some(integer) = number.as_u64() { + integer > MAX_EXACT_MAGNITUDE + } else { + let float = number.as_f64()?; + float.is_finite() && float.fract() == 0.0 && float.abs() > MAX_EXACT_MAGNITUDE as f64 + }; + beyond.then(|| number.as_f64().is_some_and(|float| float < 0.0)) +} + +fn negative_measure(field: &str) -> RequestError { + RequestError::new("negative_measure", field, "cannot be negative") +} + +fn too_long(field: &str) -> RequestError { + RequestError::new( + "above_maximum", + field, + format!("must be at most {MAX_LENGTH_TICKS} ticks"), + ) +} + fn require_measure_unit( map: &Map, field: &str, diff --git a/crates/packvium-core/src/result_validation/container.rs b/crates/packvium-core/src/result_validation/container.rs index f786d9c..038c4dd 100644 --- a/crates/packvium-core/src/result_validation/container.rs +++ b/crates/packvium-core/src/result_validation/container.rs @@ -8,8 +8,8 @@ use super::pyfmt::{int_tuple, list, py_repr, py_str, str_repr, tuple}; use super::spec::{ContainerSpec, ItemSpec, rotation_axes}; use super::stacking::{ Entry, Envelopes, SQUARE_METRE_TICKS, check_crush, check_route_removal_order, - check_stack_density, check_support_and_load, entries, occupied_volume, placed_hull, - propagate_load, support_graph, valid_nesting, + check_stack_density, check_stack_top_load, check_support_and_load, entries, occupied_volume, + placed_hull, propagate_load, support_graph, valid_nesting, }; use super::{Issue, Label, MalformedResult}; @@ -395,6 +395,7 @@ pub(crate) fn check_container( let graph = support_graph(&envelopes)?; check_support_and_load(&envelopes, &graph, global_support, issues)?; let loads = propagate_load(&envelopes, &graph)?; + check_stack_top_load(&envelopes, &loads, issues); if let Some(max_density) = spec.max_stack_density { check_stack_density(&packed_id, &envelopes, &loads, max_density, issues)?; } @@ -410,7 +411,7 @@ pub(crate) fn check_container( check_limits(packed, &packed_id, placements, spec, items, payload, issues)?; check_volumes( - packed, &packed_id, placements, spec, items, &envelopes, &loads, issues, + packed, &packed_id, placements, spec, items, &envelopes, &loads, clearance, issues, )?; let total_weight = payload_of(packed, items)?; check_centre_of_mass( @@ -583,6 +584,7 @@ fn check_volumes( items: &Ordered, envelopes: &Envelopes<'_>, loads: &[i128], + clearance: i128, issues: &mut Vec, ) -> Res<()> { let list = entries(envelopes); @@ -603,11 +605,18 @@ fn check_volumes( for (first, (_, left)) in list.iter().enumerate() { for (_, right) in &list[first + 1..] { if valid_nesting(left, right)? { + // The envelopes sink by the nesting height; the items themselves overlap by + // twice the clearance less, over their own footprint. let nesting = left.spec.and_then(|spec| spec.nesting_height).unwrap_or(0); - used = sub( - used, - mul(mul(nesting, left.envelope.length)?, left.envelope.width)?, - )?; + let margin = mul(2, clearance)?; + let overlap = sub(nesting, margin)?; + if overlap > 0 { + let footprint = mul( + sub(left.envelope.length, margin)?, + sub(left.envelope.width, margin)?, + )?; + used = sub(used, mul(overlap, footprint)?)?; + } } } } diff --git a/crates/packvium-core/src/result_validation/lattice.rs b/crates/packvium-core/src/result_validation/lattice.rs index 2ac9beb..8ae1a7c 100644 --- a/crates/packvium-core/src/result_validation/lattice.rs +++ b/crates/packvium-core/src/result_validation/lattice.rs @@ -212,7 +212,7 @@ fn problems( ("layer_step", &fields.layer_step), ("count", &fields.count), ] { - if !value.strict_int().is_some_and(|number| number >= 1) { + if value.strict_int().is_none_or(|number| number < 1) { problems.push(format!( "{name} must be a positive integer, got {}", py_repr(value) diff --git a/crates/packvium-core/src/result_validation/stacking.rs b/crates/packvium-core/src/result_validation/stacking.rs index a27e251..7e76972 100644 --- a/crates/packvium-core/src/result_validation/stacking.rs +++ b/crates/packvium-core/src/result_validation/stacking.rs @@ -175,6 +175,16 @@ pub(crate) fn check_support_and_load( fixed6(required.to_f64()) ), )); + } else if mul(area, 2)? <= envelope.base_area + && !centroid_supported( + envelope, + supporting.iter().map(|(lower, _)| &list[*lower].1.envelope), + )? + { + issues.push(Issue::new( + "centre_of_gravity_unsupported", + format!("{item_id}: centroid outside its support hull"), + )); } } for (lower, _) in supporting { @@ -196,17 +206,6 @@ pub(crate) fn check_support_and_load( format!("{item_id} rests on {lower_id}"), )); } - if let Some(limit) = lower_spec.max_top_load - && spec.weight > limit - { - issues.push(Issue::new( - "top_load_exceeded", - format!( - "{item_id} ({} ticks) on {lower_id} (limit {limit})", - spec.weight - ), - )); - } } } @@ -235,6 +234,63 @@ pub(crate) fn check_support_and_load( Ok(()) } +type Point2 = (i128, i128); + +/// Whether the base centroid lies in the convex hull of the contact areas, the rule +/// the searches apply once a support ratio is enforced; reached only at or below half the +/// base, where it can refuse. Coordinates are doubled so the centroid is an integer +/// for odd extents; every product is checked. The corners come four to a positive-area +/// overlap, so the hull is empty or has at least three vertices. `O(s log s)` time and `O(s)` +/// space for `s` supporters. +fn centroid_supported<'c>( + envelope: &Cuboid, + surfaces: impl Iterator, +) -> Res { + let mut points: Vec = Vec::new(); + for surface in surfaces { + for x in [envelope.x.max(surface.x), envelope.x2.min(surface.x2)] { + for y in [envelope.y.max(surface.y), envelope.y2.min(surface.y2)] { + points.push((mul(x, 2)?, mul(y, 2)?)); + } + } + } + points.sort_unstable(); + points.dedup(); + let mut hull = half_hull(points.iter().copied())?; + hull.extend(half_hull(points.iter().rev().copied())?); + let centroid = (add(envelope.x, envelope.x2)?, add(envelope.y, envelope.y2)?); + if hull.is_empty() { + return Ok(false); + } + for index in 0..hull.len() { + if cross(hull[index], hull[(index + 1) % hull.len()], centroid)? < 0 { + return Ok(false); + } + } + Ok(true) +} + +/// One half of Andrew's monotone chain, its last point dropped for the other half to close. +fn half_hull(order: impl Iterator) -> Res> { + let mut chain: Vec = Vec::new(); + for point in order { + while chain.len() >= 2 && cross(chain[chain.len() - 2], chain[chain.len() - 1], point)? <= 0 + { + chain.pop(); + } + chain.push(point); + } + chain.pop(); + Ok(chain) +} + +fn cross(o: Point2, a: Point2, b: Point2) -> Res { + sub( + mul(sub(a.0, o.0)?, sub(b.1, o.1)?)?, + mul(sub(a.1, o.1)?, sub(b.0, o.0)?)?, + ) +} + fn check_ground_contact( item_id: &str, envelope: &Cuboid, @@ -330,6 +386,31 @@ fn pressure(load: i128, base_area: i128) -> Res { .mul(Ratio::new(1, base_area)?) } +/// `max_top_load` against the whole stack an item bears, as every engine checks it. +/// The only top-load rule since 1.9.0: an item resting on several bearers shares its +/// weight among them by contact area. `O(n)` over the loads `propagate_load` built. +pub(crate) fn check_stack_top_load( + envelopes: &Envelopes<'_>, + loads: &[i128], + issues: &mut Vec, +) { + for (index, (item_id, entry)) in entries(envelopes).iter().enumerate() { + let Some(limit) = entry.spec.and_then(|spec| spec.max_top_load) else { + continue; + }; + if loads[index] > limit { + issues.push(Issue::new( + "top_load_exceeded", + format!( + "{} bears {} ticks (limit {limit})", + py_str(item_id), + loads[index] + ), + )); + } + } +} + /// No `compressible` item may carry more pressure than it declared. pub(crate) fn check_crush( packed_id: &Label, @@ -344,7 +425,8 @@ pub(crate) fn check_crush( else { continue; }; - let pressure = pressure(loads[index], entry.envelope.base_area)?; + let [length, width, _] = physical_sides(entry.placement)?; + let pressure = pressure(loads[index], mul(length, width)?)?; if pressure.compare_int(limit)? == Ordering::Greater { issues.push(Issue::new( "crush_violation", @@ -359,11 +441,29 @@ pub(crate) fn check_crush( Ok(()) } +/// The placed item's own sides, without the clearance its envelope adds. +fn physical_sides(placement: &Json) -> Res<[i128; 3]> { + let dimensions = placement.at("dimensions")?; + let side = |name: &str| -> Res { + dimensions + .at(name)? + .at("ticks")? + .int("a placement dimension") + }; + Ok([side("length")?, side("width")?, side("height")?]) +} + /// Occupied height under load, rounded up, never below one tick. A crushed item keeps its -/// height: `check_crush` already reports it. -pub(crate) fn compressed_height(envelope: &Cuboid, spec: &ItemSpec, load: i128) -> Res { +/// height: `check_crush` already reports it. The load presses on the item itself, so the +/// footprint and the height are its own, not its envelope's. +pub(crate) fn compressed_height( + height: i128, + footprint: i128, + spec: &ItemSpec, + load: i128, +) -> Res { let Some(limit) = spec.max_compression_pressure_kpa else { - return Ok(envelope.height); + return Ok(height); }; // The reference asserts the pair: a pressure limit without a ratio is not a request it reads. let ratio_ppm = spec.compression_ratio_ppm.ok_or_else(|| { @@ -372,13 +472,13 @@ pub(crate) fn compressed_height(envelope: &Cuboid, spec: &ItemSpec, load: i128) spec.id )) })?; - let pressure = pressure(load, envelope.base_area)?; + let pressure = pressure(load, footprint)?; if pressure.compare_int(limit)? == Ordering::Greater || limit == 0 { - return Ok(envelope.height); + return Ok(height); } let divisor = mul(mul(limit, 1_000_000)?, pressure.denominator)?; let retained = sub(divisor, mul(ratio_ppm, pressure.numerator)?)?; - Ok(ceil_div(mul(envelope.height, retained)?, divisor)?.max(1)) + Ok(ceil_div(mul(height, retained)?, divisor)?.max(1)) } /// Weight per square metre of an item's own base, at every level of the stack. @@ -563,10 +663,9 @@ pub(crate) fn occupied_volume( ) -> Res { if let Some(spec) = spec { if spec.max_compression_pressure_kpa.is_some() { - return mul( - entry_envelope.base_area, - compressed_height(entry_envelope, spec, load)?, - ); + let [length, width, height] = physical_sides(placement)?; + let footprint = mul(length, width)?; + return mul(footprint, compressed_height(height, footprint, spec, load)?); } if spec.is_convex_hull() && let Some(vertices) = &spec.hull_vertices @@ -577,14 +676,8 @@ pub(crate) fn occupied_volume( } let solid = placed_hull(entry_envelope, placement, spec)?; if solid == entry_envelope.vertices() { - let dimensions = placement.at("dimensions")?; - let side = |name: &str| -> Res { - dimensions - .at(name)? - .at("ticks")? - .int("a placement dimension") - }; - return mul(mul(side("length")?, side("width")?)?, side("height")?); + let [length, width, height] = physical_sides(placement)?; + return mul(mul(length, width)?, height); } hull_volume(&solid) } diff --git a/crates/packvium-core/src/sequence.rs b/crates/packvium-core/src/sequence.rs index 8e055bf..a35dd9b 100644 --- a/crates/packvium-core/src/sequence.rs +++ b/crates/packvium-core/src/sequence.rs @@ -522,8 +522,10 @@ pub fn replay_loading_order( /// Independently reuse the exact constraint calculations already proven for /// a finished scene (`validation::validate_top_loads_with_graph`, /// `validate_stack_counts_with_graph`, `ground_contact_valid_with_graph`) against every -/// loading *prefix*, not only the final state. Each prefix builds its contact graph once -/// and the three checks share it. +/// loading *prefix*, not only the final state. A prefix whose new box is a floor box with +/// nothing nested yet and no placed box resting on its top plane adds no contact edge, so +/// it leaves every earlier load unchanged and only its own density can fail; any other +/// prefix builds its contact graph once and the three checks share it. /// Additive to `replay_loading_order` above rather than a change to it or to any of /// the bare-geometry functions in this module, so every existing caller keeps working /// unmodified. @@ -552,6 +554,28 @@ pub fn verify_loading_prefix_business_rules( reason: "order is not a permutation of every placement index exactly once", }); } + if placements.is_empty() { + return Ok(()); + } + let has_load_rules = container.max_stack_density.is_some() + || placements.iter().any(|placement| { + let item = &placement.instance.item; + !item.stackable + || !item.accepts_stacking_groups.is_empty() + || item.max_top_load.is_some() + || item.max_stacked_items.is_some() + || item.max_compression_pressure_kpa.is_some() + }); + let has_ground_rules = placements.iter().any(|placement| { + placement.envelope_origin.z != 0 + && !matches!( + placement.instance.item.ground_contact_rule.as_deref(), + None | Some("free") + ) + }); + if !has_load_rules && !has_ground_rules { + return Ok(()); + } let mut scratch = PackedContainer { container: container.clone(), sequence: 0, @@ -559,17 +583,50 @@ pub fn verify_loading_prefix_business_rules( lattice_summary: None, lattice_items: Vec::new(), }; + let mut elevated_bases = BTreeSet::new(); + let mut any_nesting = false; for (step, index) in order.iter().copied().enumerate() { - scratch.placements.push(placements[index].clone()); + let candidate = &placements[index]; + scratch.placements.push(candidate.clone()); + let candidate_box = candidate.envelope_box(); + if candidate_box.origin.z != 0 { + elevated_bases.insert(candidate_box.origin.z); + } + if candidate.instance.item.nesting_height.is_some() { + any_nesting = true; + } + let isolated_floor_step = candidate_box.origin.z == 0 + && !any_nesting + && !elevated_bases.contains(&candidate_box.z2()); + if isolated_floor_step { + if let Some(maximum) = container.max_stack_density { + const SQUARE_METRE_TICKS: i128 = 16_000_000_i128 * 16_000_000_i128; + let total = candidate.instance.item.weight.0 as i128; + if total.saturating_mul(SQUARE_METRE_TICKS) + > (maximum.0 as i128).saturating_mul(candidate.envelope_dimensions.base_area()) + { + return Err(SequenceError::Replay { + index: index as isize, + step: step as isize, + reason: "stack_density_exceeded", + }); + } + } + continue; + } let graph = crate::contact_graph::ContactGraph::from_placements(&scratch.placements); let mut issues = Vec::new(); - crate::validation::validate_top_loads_with_graph(&scratch, &graph, &mut issues); - crate::validation::validate_stack_counts_with_graph(&scratch, &graph, &mut issues); - if !crate::validation::ground_contact_valid_with_graph( - &scratch, - scratch.placements.len() - 1, - &graph, - ) { + if has_load_rules { + crate::validation::validate_top_loads_with_graph(&scratch, &graph, &mut issues); + crate::validation::validate_stack_counts_with_graph(&scratch, &graph, &mut issues); + } + if has_ground_rules + && !crate::validation::ground_contact_valid_with_graph( + &scratch, + scratch.placements.len() - 1, + &graph, + ) + { issues.push(crate::validation::ValidationIssue { code: "ground_contact_violation".into(), message: scratch diff --git a/crates/packvium-core/src/solvers/blocks.rs b/crates/packvium-core/src/solvers/blocks.rs index 8a50586..7671bbb 100644 --- a/crates/packvium-core/src/solvers/blocks.rs +++ b/crates/packvium-core/src/solvers/blocks.rs @@ -315,7 +315,7 @@ fn supports(request: &PackingRequest, constraints: &[Arc f64 { +fn member_support(supporters: &[Aabb], origin: Point, envelope: Dimensions) -> f64 { if origin.z == 0 { return 1.0; } @@ -323,10 +323,8 @@ fn member_support(placements: &[Placement], origin: Point, envelope: Dimensions) origin, dimensions: envelope, }; - let area = placements + let area = supporters .iter() - .map(Placement::envelope_box) - .filter(|below| below.z2() == origin.z) .map(|below| below.overlap_area_xy(base)) .sum::(); (area as f64 / envelope.base_area() as f64).min(1.0) @@ -886,6 +884,26 @@ fn place_members( .expect("candidate item exists"); let chosen = available.drain(..members).collect::>(); let clearance = request.config.clearance.0; + let base_z = block.space.0.origin.z; + let supporters = if base_z > 0 && members > 0 { + let block_footprint = Aabb { + origin: block.space.0.origin, + dimensions: Dimensions { + length: Length(block.nx * block.envelope.length.0), + width: Length(block.ny * block.envelope.width.0), + height: block.envelope.height, + }, + }; + round + .packed + .placements + .iter() + .map(Placement::envelope_box) + .filter(|below| below.z2() == base_z && below.overlap_area_xy(block_footprint) > 0) + .collect::>() + } else { + Vec::new() + }; let mut index = 0; for z in 0..block.nz { for y in 0..block.ny { @@ -899,7 +917,7 @@ fn place_members( z: block.space.0.origin.z + z * block.envelope.height.0, }; let support_ratio = if z == 0 { - member_support(&round.packed.placements, origin, block.envelope) + member_support(&supporters, origin, block.envelope) } else { 1.0 }; diff --git a/crates/packvium-core/src/solvers/exact.rs b/crates/packvium-core/src/solvers/exact.rs index 62d0a2f..f300e0b 100644 --- a/crates/packvium-core/src/solvers/exact.rs +++ b/crates/packvium-core/src/solvers/exact.rs @@ -46,9 +46,33 @@ pub fn pack_exact_one( let mut searched_all_containers = true; let mut metrics = SolverMetrics::default(); + let mut type_ids = BTreeMap::::new(); + let mut equiv_ids = BTreeMap::<(String, i64, i64, i64, i64, Vec), u32>::new(); let profiled = items .iter() - .map(|item| (item.clone(), exact_item_profile(item, &request.config))) + .map(|item| { + let next_type = type_ids.len() as u32; + let type_id = *type_ids.entry(item.item.id.clone()).or_insert(next_type); + let next_equiv = equiv_ids.len() as u32; + let equiv_id = *equiv_ids + .entry(( + item.item.id.clone(), + item.item.dimensions.length.0, + item.item.dimensions.width.0, + item.item.dimensions.height.0, + item.item.weight.0, + item.item + .allowed_rotations + .iter() + .map(|r| *r as u8) + .collect(), + )) + .or_insert(next_equiv); + ( + item.clone(), + exact_item_profile(item, &request.config, type_id, equiv_id), + ) + }) .collect::>(); let mut containers = request.containers.clone(); containers.sort_by_key(|container| container_order_key(container, &request.config)); @@ -109,20 +133,27 @@ pub fn pack_exact_one( ), seen: BTreeSet::new(), }; - search( - can_fit, - &cannot_fit, - request, - constraints, - scorers, - deadline, - &initial, - &mut best_state, - &mut best_state_score, - &complete_lower_bound, - &mut metrics, - &mut visited, - ); + let initial_key = visited.keys.of(&initial); + if !deadline.expired() + && visited.seen.insert(initial_key.clone()) + && !deadline.effort_stops(request, &metrics) + { + search( + can_fit, + &cannot_fit, + request, + constraints, + scorers, + deadline, + &initial, + initial_key, + &mut best_state, + &mut best_state_score, + &complete_lower_bound, + &mut metrics, + &mut visited, + ); + } let placed = best_state .packed @@ -260,9 +291,16 @@ struct ExactItemProfile { occupied_volume: i128, minimum_height: i64, weight: i64, + type_id: u32, + equiv_id: u32, } -fn exact_item_profile(item: &ItemInstance, config: &PackingConfig) -> ExactItemProfile { +fn exact_item_profile( + item: &ItemInstance, + config: &PackingConfig, + type_id: u32, + equiv_id: u32, +) -> ExactItemProfile { let minimum_height = item .item .dimensions @@ -282,6 +320,8 @@ fn exact_item_profile(item: &ItemInstance, config: &PackingConfig) -> ExactItemP occupied_volume: occupied_item_volume(&item.item), minimum_height, weight: item.item.weight.0, + type_id, + equiv_id, } } @@ -426,16 +466,17 @@ fn optimistic_completion_score( // item cap bounds it outright. Without these a weight-capped container searched // every ordering of items it could never take -- a million placement attempts to // prove three light boxes fit where the volume bound said all six might. + let mut weights = remaining + .iter() + .map(|(_, profile)| profile.weight) + .collect::>(); + weights.sort_unstable(); if let Some(maximum) = container.max_payload { let free_payload = i128::from(maximum.0) - i128::from(state.payload); - let mut weights = remaining - .iter() - .map(|(_, profile)| i128::from(profile.weight)) - .collect::>(); - weights.sort_unstable(); let mut admitted = 0; let mut lightest_sum = 0_i128; for weight in &weights { + let weight = i128::from(*weight); if lightest_sum + weight > free_payload { break; } @@ -498,11 +539,6 @@ fn optimistic_completion_score( 0 }; let cost = container.cost_minor as i128; - let mut weights = remaining - .iter() - .map(|(_, profile)| profile.weight) - .collect::>(); - weights.sort_unstable(); let gross_weight = weights .iter() .take(placeable) @@ -637,6 +673,32 @@ impl StateKeys { } key } + + fn extend( + &self, + parent: &StateKey, + type_id: u32, + candidate: &super::extreme::Candidate, + ) -> StateKey { + let entry = ( + type_id, + candidate.envelope_origin.x, + candidate.envelope_origin.y, + candidate.envelope_origin.z, + candidate.rotation as u8, + ); + let mut key = Vec::with_capacity(parent.len() + 1); + if self.canonicalize_order { + let pos = parent.partition_point(|existing| *existing <= entry); + key.extend_from_slice(&parent[..pos]); + key.push(entry); + key.extend_from_slice(&parent[pos..]); + } else { + key.extend_from_slice(parent); + key.push(entry); + } + key + } } // Each parameter is independently-varying recursive DFS state (the remaining work, @@ -653,27 +715,13 @@ fn search( scorers: &[Arc], deadline: &Deadline, state: &ContainerState, + state_key: StateKey, best: &mut ContainerState, best_score: &mut Vec, complete_lower_bound: &[i128], metrics: &mut SolverMetrics, visited: &mut VisitedStates, ) { - if deadline.expired() { - return; - } - // In an order-insensitive scene, two item orders that seat the same boxes at the same - // places reach the same state and the first visit already explored its subtree. In a - // load-sensitive or extension-bearing scene StateKeys preserves insertion order, so - // the same check only folds states whose order-dependent future is also the same. - if !visited.seen.insert(visited.keys.of(state)) { - return; - } - // Asked after the fold: a state already explored is no work refused. A stop ends the - // whole search, so the state it leaves recorded is never visited again. - if deadline.effort_stops(request, metrics) { - return; - } metrics.search_nodes_expanded = metrics.search_nodes_expanded.saturating_add(1); // This node's own score leads with `remaining.len() + unfit.len()` unpacked, so it can only // beat the incumbent when that count does not already lose the first element; @@ -710,19 +758,19 @@ fn search( return; } - let mut equivalent = BTreeSet::new(); + // Keep configurable large exact searches logarithmic in overflow classes. + let mut seen_equiv_mask = 0_u64; + let mut seen_equiv_overflow = BTreeSet::::new(); for index in 0..remaining.len() { - let item = &remaining[index].0; - let signature = format!( - "{}:{}:{}:{}:{}:{:?}", - item.item.id, - item.item.dimensions.length.0, - item.item.dimensions.width.0, - item.item.dimensions.height.0, - item.item.weight.0, - item.item.allowed_rotations, - ); - if !equivalent.insert(signature) { + let (item, profile) = &remaining[index]; + let equiv_id = profile.equiv_id; + if equiv_id < 64 { + let bit = 1_u64 << equiv_id; + if (seen_equiv_mask & bit) != 0 { + continue; + } + seen_equiv_mask |= bit; + } else if !seen_equiv_overflow.insert(equiv_id) { continue; } let candidates = find_candidates( @@ -737,6 +785,17 @@ fn search( metrics, ); for candidate in candidates { + if deadline.expired() { + continue; + } + let next_key = visited.keys.extend(&state_key, profile.type_id, &candidate); + if visited.seen.contains(&next_key) { + continue; + } + visited.seen.insert(next_key.clone()); + if deadline.effort_stops(request, metrics) { + continue; + } let mut next_state = state.clone(); apply_candidate(&mut next_state, item.clone(), &candidate); let mut next_remaining = remaining.clone(); @@ -749,6 +808,7 @@ fn search( scorers, deadline, &next_state, + next_key, best, best_score, complete_lower_bound, @@ -764,6 +824,7 @@ fn search( #[cfg(test)] mod tests { + use super::*; use crate::api::pack_json; fn open_height_request(max_search_nodes: u64) -> String { @@ -1071,4 +1132,193 @@ mod tests { assert_eq!(result["complete"], true); assert_eq!(result["score"], serde_json::json!([0, 1, 0, 0, 1000000])); } + + fn profiled_instances(items: serde_json::Value) -> Vec<(ItemInstance, ExactItemProfile)> { + let request = crate::api::request_from_json(&serde_json::json!({ + "units": {"length": "mm"}, + "items": items, + "containers": [{"id": "crate", + "inner_dimensions": {"length": "100", "width": "100", "height": "100"}}] + })) + .expect("request"); + let config = request.config.clone(); + request + .items + .iter() + .flat_map(|item| (0..item.quantity).map(move |_| item.clone())) + .enumerate() + .map(|(sequence, item)| { + let instance = ItemInstance { item, sequence }; + let profile = exact_item_profile(&instance, &config, 0, 0); + (instance, profile) + }) + .collect() + } + + #[test] + fn a_child_key_extended_from_its_parent_equals_the_key_rebuilt_from_the_child() { + // The search extends each child's visited key from its parent's instead + // of rebuilding it from every placement; the fold is only sound if the two agree, + // in insertion order and canonicalized, whatever order the placements arrive in. + let profiled = profiled_instances(serde_json::json!([ + {"id": "b", "quantity": 2, "dimensions": {"length": "10", "width": "10", "height": "10"}}, + {"id": "a", "quantity": 1, "dimensions": {"length": "10", "width": "20", "height": "10"}}, + ])); + let request = crate::api::request_from_json(&serde_json::json!({ + "units": {"length": "mm"}, + "items": [{"id": "a", "quantity": 1, "dimensions": {"length": "1", "width": "1", "height": "1"}}], + "containers": [{"id": "crate", + "inner_dimensions": {"length": "100", "width": "100", "height": "100"}}] + })) + .expect("request"); + let origins = [(40, 0, 0), (0, 0, 0), (0, 30, 0), (0, 0, 10)]; + for canonicalize_order in [false, true] { + let keys = StateKeys::new(&profiled, canonicalize_order); + let mut state = ContainerState::new(request.containers[0].clone(), 1); + let mut key = keys.of(&state); + for (index, (x, y, z)) in origins.iter().copied().enumerate() { + let (instance, _) = &profiled[index % profiled.len()]; + let origin = crate::geometry::Point { x, y, z }; + let candidate = super::super::extreme::Candidate { + envelope_origin: origin, + position: origin, + rotation: crate::geometry::Rotation::Lwh, + dimensions: instance.item.dimensions, + envelope_dimensions: instance.item.dimensions, + support_ratio: 1.0, + score: 0, + }; + key = keys.extend(&key, keys.types[&instance.item.id], &candidate); + apply_candidate(&mut state, instance.clone(), &candidate); + assert_eq!( + key, + keys.of(&state), + "canonicalize_order={canonicalize_order}, step {index}" + ); + } + } + } + + #[test] + fn equivalent_items_past_the_sixty_fourth_class_still_branch_once() { + // Equivalence classes below 64 are folded through a bitmask and the rest + // through an ordered set. A duplicate in the 65th class must still add no branch: the root + // considers exactly the orientations it would with that duplicate absent. + let items = |copies: u32| { + let mut items = (0..64) + .map(|index| { + serde_json::json!({"id": format!("t{index:02}"), "quantity": 1, + "allowed_rotations": ["LWH"], + "dimensions": {"length": "1", "width": "1", "height": (index + 1).to_string()}}) + }) + .collect::>(); + items.push( + serde_json::json!({"id": "t64", "quantity": copies, "allowed_rotations": ["LWH"], + "dimensions": {"length": "1", "width": "1", "height": "99"}}), + ); + items + }; + let root_work = |copies: u32| { + let request = serde_json::json!({ + "units": {"length": "mm"}, + "configuration": {"solvers": ["exact_small"], "solver_profile": "exact_small", + "exact_item_limit": 80, "max_containers": 1, "time_limit_ms": 300000, + "effort_budget": {"max_candidates_evaluated": 1000000, + "max_placement_attempts": 1000000, "max_search_nodes": 1}}, + "items": items(copies), + "containers": [{"id": "crate", "quantity": 1, + "inner_dimensions": {"length": "100", "width": "100", "height": "100"}}] + }); + let output = pack_json(&request.to_string()).expect("a 65-class exact request"); + let result: serde_json::Value = serde_json::from_str(&output).unwrap(); + assert_eq!(result["algorithm"]["metrics"]["search_nodes_expanded"], 1); + result["algorithm"]["metrics"]["orientations_considered"].clone() + }; + assert_eq!(root_work(2), root_work(1)); + } + + /// One millisecond per reading, so a test can say on which check the deadline passes. + struct SteppingClock(std::sync::atomic::AtomicU64); + + impl crate::deadline::Clock for SteppingClock { + fn now_ns(&self) -> u64 { + self.0 + .fetch_add(1_000_000, std::sync::atomic::Ordering::SeqCst) + } + } + + fn stepping(limit_ms: u64) -> crate::deadline::Deadline { + crate::deadline::Deadline::with_clock( + limit_ms, + std::sync::Arc::new(SteppingClock(std::sync::atomic::AtomicU64::new(0))), + ) + } + + fn cubes(quantity: usize, containers: serde_json::Value) -> crate::model::PackingRequest { + crate::api::request_from_json(&serde_json::json!({ + "units": {"length": "mm"}, + "configuration": {"solvers": ["exact_small"], "solver_profile": "exact_small", + "time_limit_ms": 300000}, + "items": [{"id": "cube", "quantity": quantity, "allowed_rotations": ["LWH"], + "dimensions": {"length": "10", "width": "10", "height": "10"}}], + "containers": containers + })) + .expect("a valid request") + } + + fn exact( + request: &crate::model::PackingRequest, + deadline: &crate::deadline::Deadline, + ) -> Option { + super::pack_exact_one(request, &request.instances(), &[], &[], deadline) + } + + fn crate_of(id: &str, length: &str) -> serde_json::Value { + serde_json::json!({"id": id, "quantity": 1, + "inner_dimensions": {"length": length, "width": "10", "height": "10"}}) + } + + #[test] + fn a_deadline_passed_before_the_first_container_answers_nothing() { + let request = cubes(2, serde_json::json!([crate_of("box", "20")])); + assert!(exact(&request, &stepping(1)).is_none()); + } + + #[test] + fn a_deadline_passed_mid_search_keeps_the_incumbent_and_names_the_limit() { + // Two containers, neither of which holds all four cubes: the first search runs out + // of clock partway, so the answer is the partial incumbent, flagged as cut off. + let request = cubes( + 4, + serde_json::json!([crate_of("short", "20"), crate_of("long", "30")]), + ); + let result = exact(&request, &stepping(12)).expect("an incumbent"); + assert!(result.algorithm.time_limit_reached); + assert_eq!(result.status, crate::model::PackingStatus::TimeLimit); + assert!(!result.unpacked.is_empty()); + assert!( + result + .unpacked + .iter() + .all(|item| item.reason == "time_limit") + ); + } + + #[test] + fn a_container_that_takes_no_item_leaves_every_item_unpacked() { + let mut request = cubes(2, serde_json::json!([crate_of("box", "20")])); + request.containers[0].max_items = Some(0); + let result = exact(&request, &stepping(60_000)).expect("an answer"); + assert!(result.containers.is_empty()); + assert_eq!(result.unpacked.len(), 2); + } + + #[test] + fn a_container_item_limit_caps_the_floor_and_the_answer() { + let mut request = cubes(3, serde_json::json!([crate_of("box", "30")])); + request.containers[0].max_items = Some(1); + let result = exact(&request, &stepping(60_000)).expect("an answer"); + assert_eq!(result.containers[0].placements.len(), 1); + assert_eq!(result.unpacked.len(), 2); + } } diff --git a/crates/packvium-core/src/solvers/extreme.rs b/crates/packvium-core/src/solvers/extreme.rs index 1afa97e..ea7baaf 100644 --- a/crates/packvium-core/src/solvers/extreme.rs +++ b/crates/packvium-core/src/solvers/extreme.rs @@ -8,6 +8,7 @@ use crate::made_to_measure::sides_of; use crate::model::*; use crate::solver::{CandidateScorer, PlacementConstraint, SolverContext}; use crate::spatial_index::SpatialIndex; +use crate::support_polygon::centre_of_gravity_supported; use crate::units::{Length, Weight}; use std::cmp::{Ordering, Reverse}; use std::collections::{BTreeMap, BTreeSet, BinaryHeap}; @@ -153,6 +154,8 @@ pub struct ContainerState { /// Candidate origins ordered by (z, y, x), matching the reference engines. points: BTreeSet<(i64, i64, i64)>, spatial_index: SpatialIndex, + placements_by_top: BTreeMap>, + placements_by_bottom: BTreeMap>, } struct ContainerTrial { @@ -191,6 +194,8 @@ impl ContainerState { extent: [0, 0, 0], points: BTreeSet::new(), spatial_index, + placements_by_top: BTreeMap::new(), + placements_by_bottom: BTreeMap::new(), }; absorb_point(&mut state, Point::ZERO); for box_ in obstacle_boxes { @@ -709,12 +714,22 @@ pub fn find_candidates_at_points( ) { continue; } + // Area alone is not stability. At or below half the base the + // centroid can still fall outside the contact hull, which Python and PHP refuse + // as centre_of_gravity_unsupported; above half it cannot. + if point.z != 0 + && required_support > 0.0 + && support_area * 2 <= envelope.base_area() + && !centre_of_gravity_carried(state, nested_support.as_ref(), envelope_box) + { + continue; + } let ground_contact_allowed = nested_support.as_ref().map_or_else( || { - ground_contact_allowed( + ground_contact_allowed_in_state( item.item.ground_contact_rule.as_deref(), envelope_box, - &state.packed.placements, + state, ) }, |support| { @@ -729,11 +744,7 @@ pub fn find_candidates_at_points( continue; } if (state.route_sensitive || item.item.stop_index.is_some()) - && !route_contact_allowed( - item.item.stop_index, - envelope_box, - &state.packed.placements, - ) + && !route_contact_allowed_in_state(item.item.stop_index, envelope_box, state) { continue; } @@ -1232,8 +1243,17 @@ fn pack_container_plans( let mut beam = vec![initial]; let mut plan_nodes = 0_usize; let maximum = request.config.max_containers.unwrap_or(usize::MAX); + // A beam wider than its node budget used to stop after trying the first + // container in static order, so the order chose it, not the objective. The budget is at + // least one trial per container type for every plan the beam keeps. + let node_limit = request.config.container_plan_node_limit.max( + request + .config + .container_plan_beam_width + .saturating_mul(request.containers.len()), + ); - while !beam.is_empty() && plan_nodes < request.config.container_plan_node_limit { + while !beam.is_empty() && plan_nodes < node_limit { let mut expansions = Vec::new(); let mut exhausted = false; for plan in &beam { @@ -1246,7 +1266,7 @@ fn pack_container_plans( continue; } for container in eligible_containers(request, &plan.remaining, &plan.inventory) { - if plan_nodes >= request.config.container_plan_node_limit { + if plan_nodes >= node_limit { break; } if deadline.expired() || deadline.effort_stops(request, metrics) { @@ -1400,9 +1420,17 @@ fn commit_placement(state: &mut ContainerState, placement: Placement) { .item .nesting_height .is_none() - && !state.packed.placements[..placement_index] - .iter() - .any(|existing| existing.envelope_origin.z == envelope_box.z2()); + && !state.placements_by_bottom.contains_key(&envelope_box.z2()); + state + .placements_by_top + .entry(envelope_box.z2()) + .or_default() + .push(placement_index); + state + .placements_by_bottom + .entry(envelope_box.origin.z) + .or_default() + .push(placement_index); if !isolated_on_floor && let Some(loads) = calculate_top_loads(&state.packed.placements) { for (placement, load) in state.packed.placements.iter_mut().zip(loads) { placement.top_load = Weight(load.clamp(0, i64::MAX as i128) as i64); @@ -1585,15 +1613,51 @@ fn solid_boxes(state: &ContainerState) -> impl Iterator + '_ { ) } +/// The supporters are the ones whose area `support_area_sufficient` just counted: the +/// nested view's graph when the candidate nests, else every placed top face on its base. +fn centre_of_gravity_carried( + state: &ContainerState, + nested: Option<&CandidateSupportView>, + box_: Aabb, +) -> bool { + match nested { + Some(view) => { + let candidate = view.placements.len() - 1; + centre_of_gravity_supported( + box_, + view.graph + .supporters(candidate) + .iter() + .map(|edge| view.placements[edge.index].envelope_box()), + ) + } + None => centre_of_gravity_supported( + box_, + state + .placements_by_top + .get(&box_.origin.z) + .into_iter() + .flatten() + .map(|&index| state.packed.placements[index].envelope_box()), + ), + } +} + /// Square ticks of placed top faces directly under `box_`'s base plane. fn supporting_area(state: &ContainerState, box_: Aabb) -> i128 { state - .packed - .placements - .iter() - .filter(|placement| placement.envelope_box().z2() == box_.origin.z) - .map(|placement| placement.envelope_box().overlap_area_xy(box_)) - .sum::() + .placements_by_top + .get(&box_.origin.z) + .map_or(0, |indices| { + indices + .iter() + .map(|&index| { + state.packed.placements[index] + .envelope_box() + .overlap_area_xy(box_) + }) + .sum() + }) } /// The reported fraction, for the placement record only: the feasibility decision reads @@ -1672,7 +1736,11 @@ fn candidate_respects_loads( // needs the placements themselves -- the two are required to agree exactly, which is // what `contact_graph`'s append property test holds them to. if let Some(sweep) = sweep { - return sweep.allows(LoadBody::of(&item.item, candidate_box)); + return sweep.allows(LoadBody::of( + &item.item, + candidate_box, + candidate.dimensions.base_area(), + )); } let mut placements = state.packed.placements.clone(); placements.push(Placement { @@ -1714,6 +1782,9 @@ pub(crate) trait LoadSubject { fn max_top_load_ticks(&self) -> Option; fn max_stacked_items(&self) -> Option; fn max_compression_pressure_kpa(&self) -> Option; + /// The item's own footprint, which a load presses on; the envelope is grown by the + /// clearance and carries the support graph. + fn footprint(&self) -> i128; fn stacking_group(&self) -> Option<&str>; /// The code refusing an item of `upper_group` resting directly on this box. fn stacking_refusal(&self, upper_group: Option<&str>) -> Option<&'static str>; @@ -1723,6 +1794,9 @@ impl LoadSubject for Placement { fn envelope(&self) -> Aabb { self.envelope_box() } + fn footprint(&self) -> i128 { + self.dimensions.base_area() + } fn weight_ticks(&self) -> i64 { self.instance.item.weight.0 } @@ -1748,6 +1822,7 @@ impl LoadSubject for Placement { #[derive(Clone, Copy, Debug)] struct LoadBody<'a> { envelope: Aabb, + footprint: i128, weight: i64, stackable: bool, max_top_load: Option, @@ -1758,9 +1833,10 @@ struct LoadBody<'a> { } impl<'a> LoadBody<'a> { - fn of(item: &'a Item, envelope: Aabb) -> Self { + fn of(item: &'a Item, envelope: Aabb, footprint: i128) -> Self { Self { envelope, + footprint, weight: item.weight.0, stackable: item.stackable, max_top_load: item.max_top_load.map(|weight| weight.0), @@ -1781,6 +1857,9 @@ impl LoadSubject for LoadBody<'_> { fn envelope(&self) -> Aabb { self.envelope } + fn footprint(&self) -> i128 { + self.footprint + } fn weight_ticks(&self) -> i64 { self.weight } @@ -1832,7 +1911,13 @@ impl<'a> LoadSweep<'a> { .packed .placements .iter() - .map(|placement| LoadBody::of(&placement.instance.item, placement.envelope_box())) + .map(|placement| { + LoadBody::of( + &placement.instance.item, + placement.envelope_box(), + placement.dimensions.base_area(), + ) + }) .collect::>(); let boxes = bodies.iter().map(|body| body.envelope).collect::>(); let graph = ContactGraph::with_cell_hint(&boxes, widest_footprint); @@ -1937,7 +2022,7 @@ impl<'a> LoadSweep<'a> { let body = scene.body(*index); let footprint_area = body.envelope.dimensions.base_area(); if let Some(limit) = body.max_compression_pressure_kpa - && crush_exceeded(limit, *load, footprint_area) + && crush_exceeded(limit, *load, body.footprint) { return false; } @@ -2117,14 +2202,21 @@ fn density_within(weight: i64, load: i128, maximum: Weight, footprint_area: i128 total.saturating_mul(SQUARE_METRE_TICKS) <= i128::from(maximum.0).saturating_mul(footprint_area) } -fn ground_contact_allowed(rule: Option<&str>, candidate: Aabb, placements: &[Placement]) -> bool { +fn ground_contact_allowed_in_state( + rule: Option<&str>, + candidate: Aabb, + state: &ContainerState, +) -> bool { if candidate.origin.z == 0 || matches!(rule, None | Some("free")) { return true; } - let supporters = placements - .iter() - .map(Placement::envelope_box) - .filter(|other| other.z2() == candidate.origin.z && other.overlap_area_xy(candidate) > 0) + let supporters = state + .placements_by_top + .get(&candidate.origin.z) + .into_iter() + .flatten() + .map(|&index| state.packed.placements[index].envelope_box()) + .filter(|other| other.overlap_area_xy(candidate) > 0) .collect::>(); match rule { Some("single") => supporters.len() == 1, @@ -2353,6 +2445,52 @@ fn stop_accessible( }) } +fn route_contact_allowed_in_state( + candidate_stop: Option, + candidate: Aabb, + state: &ContainerState, +) -> bool { + let candidate_stop = candidate_stop.unwrap_or(RIDES_THE_WHOLE_ROUTE); + let below_ok = state + .placements_by_top + .get(&candidate.origin.z) + .into_iter() + .flatten() + .all(|&index| { + let other = &state.packed.placements[index]; + let other_stop = other + .instance + .item + .stop_index + .unwrap_or(RIDES_THE_WHOLE_ROUTE); + if candidate_stop == RIDES_THE_WHOLE_ROUTE && other_stop == RIDES_THE_WHOLE_ROUTE { + return true; + } + other.envelope_box().overlap_area_xy(candidate) == 0 || candidate_stop <= other_stop + }); + if !below_ok { + return false; + } + state + .placements_by_bottom + .get(&candidate.z2()) + .into_iter() + .flatten() + .all(|&index| { + let other = &state.packed.placements[index]; + let other_stop = other + .instance + .item + .stop_index + .unwrap_or(RIDES_THE_WHOLE_ROUTE); + if candidate_stop == RIDES_THE_WHOLE_ROUTE && other_stop == RIDES_THE_WHOLE_ROUTE { + return true; + } + other.envelope_box().overlap_area_xy(candidate) == 0 || candidate_stop >= other_stop + }) +} + +#[cfg(test)] fn route_contact_allowed( candidate_stop: Option, candidate: Aabb, @@ -2457,13 +2595,12 @@ fn placement_stack_sensitive(item: &Item) -> bool { /// volume for every candidate orientation. fn used_volume_delta(placements: &[Placement], placement: &Placement) -> i128 { let mut delta = occupied_volume(placement); - let Some(depth) = placement.instance.item.nesting_height else { + if placement.instance.item.nesting_height.is_none() { return delta; - }; - let overlap = (depth.0 as i128).saturating_mul(placement.envelope_dimensions.base_area()); + } for existing in placements { if valid_nesting(existing, placement) { - delta = delta.saturating_sub(overlap); + delta = delta.saturating_sub(nested_overlap(existing, placement)); } } delta @@ -2509,9 +2646,8 @@ fn stack_density_valid_with_loads( /// `crushed` without the offender's name, over any bearing subject. fn crush_free(bodies: &[T], loads: &[i128]) -> bool { bodies.iter().zip(loads).all(|(body, load)| { - body.max_compression_pressure_kpa().is_none_or(|limit| { - !crush_exceeded(limit, *load, body.envelope().dimensions.base_area()) - }) + body.max_compression_pressure_kpa() + .is_none_or(|limit| !crush_exceeded(limit, *load, body.footprint())) }) } @@ -4739,6 +4875,7 @@ mod tests { origin, dimensions: dimensions(side, side, 10 + lcg.next(2) as i64 * 10), }, + footprint: i128::from(side * side), weight: lcg.next(5) as i64 * 1_000, stackable: lcg.next(6) != 0, max_top_load: (lcg.next(3) == 0).then(|| lcg.next(4) as i64 * 1_500), diff --git a/crates/packvium-core/src/solvers/grid.rs b/crates/packvium-core/src/solvers/grid.rs index f9938fe..97a484d 100644 --- a/crates/packvium-core/src/solvers/grid.rs +++ b/crates/packvium-core/src/solvers/grid.rs @@ -54,7 +54,7 @@ fn grid_selection_key( let top = if layers == 0 { 0 } else { - envelope.height.0 + (layers as i64 - 1) * (envelope.height.0 - nesting) + column_layer_z(layers as i64 - 1, envelope.height.0, nesting) + envelope.height.0 }; let unused_ppm = if volume > 0 { (volume - used) * SCORE_SCALE / volume @@ -168,12 +168,11 @@ pub fn try_grid(request: &PackingRequest, deadline: &Deadline) -> Option Option Option, +) -> bool { + let hull = convex_hull(contact_points(candidate, supporters)); + point_in_hull(doubled_centroid(candidate), &hull) +} + +fn contact_points(candidate: Aabb, supporters: impl IntoIterator) -> Vec { + let mut points = Vec::new(); + for other in supporters { + let x1 = candidate.origin.x.max(other.origin.x); + let y1 = candidate.origin.y.max(other.origin.y); + let x2 = candidate.x2().min(other.x2()); + let y2 = candidate.y2().min(other.y2()); + if x2 > x1 && y2 > y1 { + for x in [x1, x2] { + for y in [y1, y2] { + points.push((2 * i128::from(x), 2 * i128::from(y))); + } + } + } + } + points +} + +fn doubled_centroid(box_: Aabb) -> Point2 { + ( + i128::from(box_.origin.x) + i128::from(box_.x2()), + i128::from(box_.origin.y) + i128::from(box_.y2()), + ) +} + +fn cross(o: Point2, a: Point2, b: Point2) -> i128 { + (a.0 - o.0) * (b.1 - o.1) - (a.1 - o.1) * (b.0 - o.0) +} + +/// Andrew's monotone chain, counter-clockwise with duplicates collapsed. The points come four +/// to an overlap rectangle of positive area, so the hull is empty or has at least three +/// vertices: `support_polygon.py`'s degenerate one- and two-point cases cannot arise here. +fn convex_hull(mut points: Vec) -> Vec { + points.sort_unstable(); + points.dedup(); + let mut hull = half_chain(points.iter().copied()); + hull.extend(half_chain(points.iter().rev().copied())); + hull +} + +fn half_chain(order: impl Iterator) -> Vec { + let mut out: Vec = Vec::new(); + for point in order { + while out.len() >= 2 && cross(out[out.len() - 2], out[out.len() - 1], point) <= 0 { + out.pop(); + } + out.push(point); + } + out.pop(); + out +} + +fn point_in_hull(point: Point2, hull: &[Point2]) -> bool { + !hull.is_empty() + && (0..hull.len()) + .all(|index| cross(hull[index], hull[(index + 1) % hull.len()], point) >= 0) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::geometry::{Dimensions, Point}; + use crate::units::Length; + + fn aabb(x: i64, y: i64, length: i64, width: i64) -> Aabb { + Aabb { + origin: Point { x, y, z: 0 }, + dimensions: Dimensions { + length: Length(length), + width: Length(width), + height: Length(10), + }, + } + } + + #[test] + fn a_centroid_beyond_a_single_end_support_is_unsupported() { + assert!(!centre_of_gravity_supported( + aabb(0, 0, 100, 10), + [aabb(0, 0, 30, 10)] + )); + } + + #[test] + fn supports_at_both_ends_carry_the_centroid() { + let ends = [aabb(0, 0, 20, 10), aabb(80, 0, 20, 10)]; + assert!(centre_of_gravity_supported(aabb(0, 0, 100, 10), ends)); + } + + #[test] + fn an_odd_extent_keeps_the_centroid_exact() { + // Centroid x is 50.5; a support ending at 51 still carries it. + assert!(centre_of_gravity_supported( + aabb(0, 0, 101, 10), + [aabb(0, 0, 51, 10)] + )); + assert!(!centre_of_gravity_supported( + aabb(0, 0, 101, 10), + [aabb(0, 0, 50, 10)] + )); + } + + #[test] + fn duplicate_corners_from_adjacent_supporters_collapse() { + let halves = [aabb(0, 0, 10, 10), aabb(10, 0, 10, 10)]; + assert!(centre_of_gravity_supported(aabb(0, 0, 20, 10), halves)); + } + + #[test] + fn a_box_that_only_touches_an_edge_carries_nothing() { + assert!(!centre_of_gravity_supported( + aabb(0, 0, 10, 10), + [aabb(10, 0, 10, 10)] + )); + } + + #[test] + fn no_support_is_unsupported() { + assert!(!centre_of_gravity_supported(aabb(0, 0, 10, 10), [])); + } + + #[test] + fn a_one_tick_knife_edge_under_the_centroid_carries_the_box() { + assert!(centre_of_gravity_supported( + aabb(0, 0, 10, 10), + [aabb(5, 0, 1, 10)] + )); + assert!(!centre_of_gravity_supported( + aabb(0, 0, 10, 10), + [aabb(6, 0, 1, 10)] + )); + } + + #[test] + fn coordinates_at_the_edge_of_i64_stay_exact() { + let far = i64::MAX - 1_000; + let candidate = aabb(far, far, 101, 10); + assert!(centre_of_gravity_supported( + candidate, + [aabb(far, far, 51, 10)] + )); + assert!(!centre_of_gravity_supported( + candidate, + [aabb(far, far, 50, 10)] + )); + } + + #[test] + fn a_supporter_wider_than_the_footprint_is_clipped_to_it() { + assert!(centre_of_gravity_supported( + aabb(10, 10, 10, 10), + [aabb(0, 0, 100, 100)] + )); + } + + #[test] + fn a_corner_square_whose_inner_corner_is_the_centroid_carries_it() { + assert!(centre_of_gravity_supported( + aabb(0, 0, 40, 40), + [aabb(0, 0, 20, 20)] + )); + assert!(!centre_of_gravity_supported( + aabb(0, 0, 40, 40), + [aabb(0, 0, 20, 19)] + )); + } + + fn legs_on_a_circle(keep: impl Fn(f64) -> bool) -> Vec { + (0..360) + .map(|degree| f64::from(degree).to_radians()) + .filter(|angle| keep(*angle)) + .map(|angle| { + // Rounding to whole ticks only moves a leg, never the centroid. + #[allow(clippy::cast_possible_truncation)] + let at = |trig: f64| (500.0 + 400.0 * trig).round() as i64; + aabb(at(angle.cos()), at(angle.sin()), 1, 1) + }) + .collect() + } + + #[test] + fn three_hundred_and_sixty_legs_on_a_circle_carry_the_centroid() { + let legs = legs_on_a_circle(|_| true); + assert!(centre_of_gravity_supported(aabb(0, 0, 1000, 1000), legs)); + } + + #[test] + fn legs_on_half_a_circle_leave_the_centroid_hanging() { + let legs = legs_on_a_circle(|angle| angle.sin() > 0.1); + assert!(!centre_of_gravity_supported(aabb(0, 0, 1000, 1000), legs)); + } + + #[test] + fn repeated_and_reordered_supporters_give_the_same_answer() { + let legs = [aabb(0, 0, 5, 5), aabb(35, 0, 5, 5), aabb(0, 35, 5, 5)]; + let candidate = aabb(0, 0, 40, 40); + let reversed = legs.iter().rev().copied(); + let doubled = legs.iter().chain(legs.iter()).copied(); + assert!(centre_of_gravity_supported(candidate, legs)); + assert!(centre_of_gravity_supported(candidate, reversed)); + assert!(centre_of_gravity_supported(candidate, doubled)); + } +} diff --git a/crates/packvium-core/src/units.rs b/crates/packvium-core/src/units.rs index 3fa0402..0028589 100644 --- a/crates/packvium-core/src/units.rs +++ b/crates/packvium-core/src/units.rs @@ -147,6 +147,132 @@ pub(crate) fn measure_ticks( unbounded_ticks(value, default_unit, kind).map(|(_, ticks)| ticks) } +/// What a measure `measure_ticks` overflowed on is, read exactly. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(crate) enum Overflowed { + Negative, + /// Its ticks are past the ceiling the caller named. + Beyond, + /// Unreadable here too, or a vanishing fraction with a vast denominator. + Unreadable, +} + +/// Reads over decimal digits a measure `i128` could not hold, to say whether it is negative or +/// past `ceiling` ticks. Ticks round to nearest, so they pass an odd `ceiling` once +/// `2 n m >= (2 ceiling + 1) d`; the tie itself rounds up to even. O(digits^2). +pub(crate) fn overflowed_measure( + value: &Value, + default_unit: &str, + kind: MeasureKind, + ceiling: u64, +) -> Overflowed { + let Ok((raw, unit)) = scalar_and_unit(value, default_unit) else { + return Overflowed::Unreadable; + }; + let (Some(multiplier), Some((negative, numerator, denominator))) = + (kind.multiplier(&unit), exact_fraction(&raw)) + else { + return Overflowed::Unreadable; + }; + if numerator.is_empty() { + return Overflowed::Unreadable; + } + if negative { + return Overflowed::Negative; + } + let doubled = digits_mul(&numerator, &digits_of(2 * multiplier as u128)); + let threshold = digits_mul(&denominator, &digits_of(2 * u128::from(ceiling) + 1)); + if digits_cmp(&doubled, &threshold) == Ordering::Less { + Overflowed::Unreadable + } else { + Overflowed::Beyond + } +} + +/// `parse_rational` over little-endian decimal digits, without leading zeros: the sign, +/// numerator and denominator, or `None` for any other text. +fn exact_fraction(text: &str) -> Option<(bool, Vec, Vec)> { + let text = text.trim().replace('\u{00a0}', " "); + let negative = text.starts_with('-'); + let signed = |part: &str| digits(part.strip_prefix(['+', '-']).unwrap_or(part)); + let (numerator, denominator) = if let Some((whole, fraction)) = text.split_once(' ') + && let Some((numerator, denominator)) = fraction.split_once('/') + { + let denominator = digits(denominator.trim())?; + let whole = digits_mul(&signed(whole)?, &denominator); + (digits_add(&whole, &digits(numerator.trim())?), denominator) + } else if let Some((numerator, denominator)) = text.split_once('/') { + (signed(numerator.trim())?, digits(denominator.trim())?) + } else if let Some((whole, fraction)) = text.split_once('.') { + let shifted = format!("{}{fraction}", whole.trim_start_matches(['+', '-'])); + ( + digits(&shifted)?, + digits(&format!("1{}", "0".repeat(fraction.len())))?, + ) + } else { + (signed(&text)?, vec![1]) + }; + if denominator.is_empty() { + return None; + } + Some((negative && !numerator.is_empty(), numerator, denominator)) +} + +fn digits(text: &str) -> Option> { + if text.is_empty() || !text.bytes().all(|byte| byte.is_ascii_digit()) { + return None; + } + let mut digits: Vec = text.bytes().rev().map(|byte| byte - b'0').collect(); + while digits.last() == Some(&0) { + digits.pop(); + } + Some(digits) +} + +fn digits_of(value: u128) -> Vec { + digits(&value.to_string()).unwrap_or_default() +} + +fn digits_add(a: &[u8], b: &[u8]) -> Vec { + let mut sum = Vec::with_capacity(a.len().max(b.len()) + 1); + let mut carry = 0; + for index in 0..a.len().max(b.len()) { + let digit = a.get(index).unwrap_or(&0) + b.get(index).unwrap_or(&0) + carry; + sum.push(digit % 10); + carry = digit / 10; + } + if carry > 0 { + sum.push(carry); + } + sum +} + +fn digits_mul(a: &[u8], b: &[u8]) -> Vec { + let mut product = vec![0_u32; a.len() + b.len()]; + for (i, &left) in a.iter().enumerate() { + for (j, &right) in b.iter().enumerate() { + product[i + j] += u32::from(left) * u32::from(right); + } + } + let mut carry = 0; + for digit in &mut product { + *digit += carry; + carry = *digit / 10; + *digit %= 10; + } + let mut product: Vec = product.into_iter().map(|digit| digit as u8).collect(); + while product.last() == Some(&0) { + product.pop(); + } + product +} + +fn digits_cmp(a: &[u8], b: &[u8]) -> Ordering { + a.len() + .cmp(&b.len()) + .then_with(|| a.iter().rev().cmp(b.iter().rev())) +} + fn scalar_and_unit(value: &Value, default_unit: &str) -> PackResult<(String, String)> { match value { Value::Object(map) => { @@ -329,6 +455,112 @@ fn decimal_string(numerator: i128, denominator: i128, places: usize) -> String { mod tests { use super::*; + const VAST: &str = "10000000000000000000000000000000000000000"; + const CEILING: u64 = (1 << 53) - 1; + + fn overflowed(text: &str) -> Overflowed { + overflowed_measure( + &Value::String(text.into()), + "mm", + MeasureKind::Length, + CEILING, + ) + } + + #[test] + fn every_spelling_of_a_vast_length_is_past_the_ceiling() { + for text in [ + VAST.to_owned(), + format!("{VAST}.5"), + format!("{VAST}/3"), + format!("{VAST} 1/2"), + format!("{VAST} cm"), + format!("+{VAST}"), + ] { + assert_eq!(overflowed(&text), Overflowed::Beyond, "{text}"); + } + let object = serde_json::json!({"value": VAST, "unit": "ticks"}); + assert_eq!( + overflowed_measure(&object, "mm", MeasureKind::Length, CEILING), + Overflowed::Beyond + ); + } + + #[test] + fn a_vast_negative_measure_is_negative() { + assert_eq!(overflowed(&format!("-{VAST}")), Overflowed::Negative); + assert_eq!(overflowed(&format!("-{VAST} 1/2")), Overflowed::Negative); + } + + #[test] + fn a_vanishing_or_unreadable_measure_is_neither() { + for text in [ + format!("1/{VAST}"), + format!("0/{VAST}"), + format!("{VAST}/0"), + format!("{VAST}x"), + "-0".to_owned(), + ] { + assert_eq!(overflowed(&text), Overflowed::Unreadable, "{text}"); + } + assert_eq!( + overflowed_measure(&Value::Bool(true), "mm", MeasureKind::Length, CEILING), + Overflowed::Unreadable + ); + let furlongs = serde_json::json!({"value": VAST, "unit": "furlong"}); + assert_eq!( + overflowed_measure(&furlongs, "mm", MeasureKind::Length, CEILING), + Overflowed::Unreadable + ); + } + + #[test] + fn the_ceiling_itself_rounds_to_nearest_with_the_tie_to_even() { + // MAX + 1/2 ticks rounds to MAX + 1, past the ceiling; MAX + 1/2 - 1/10 does not. + let doubled = 2 * u128::from(CEILING) + 1; + let tie = format!("{doubled}/2"); + let ticks = |text: &str| { + overflowed_measure( + &Value::String(text.into()), + "ticks", + MeasureKind::Length, + CEILING, + ) + }; + assert_eq!(ticks(&tie), Overflowed::Beyond); + assert_eq!( + ticks(&format!("{}/20", doubled * 10 - 2)), + Overflowed::Unreadable + ); + assert_eq!(digits_add(&[9, 9], &[1]), vec![0, 0, 1]); + } + + #[test] + fn each_unit_is_worth_its_definition_in_ticks() { + // 1 in = 25.4 mm, 1 ft = 12 in, 1 lb = 453.59237 g, 1 oz = 1/16 lb. + let one = |unit: &str| serde_json::json!({"value": "1", "unit": unit}); + for (unit, ticks) in [ + ("mm", 16_000), + ("cm", 160_000), + ("m", 16_000_000), + ("in", 406_400), + ("ft", 4_876_800), + ("ticks", 1), + ] { + assert_eq!(Length::parse(&one(unit), "mm").unwrap().0, ticks, "{unit}"); + } + for (unit, ticks) in [ + ("mg", 8_000), + ("g", 8_000_000), + ("kg", 8_000_000_000), + ("oz", 226_796_185), + ("lb", 3_628_738_960), + ("ticks", 1), + ] { + assert_eq!(Weight::parse(&one(unit), "g").unwrap().0, ticks, "{unit}"); + } + } + #[test] fn fractional_inches_are_exact() { assert_eq!( diff --git a/crates/packvium-core/src/validation.rs b/crates/packvium-core/src/validation.rs index 065574d..f5299ab 100644 --- a/crates/packvium-core/src/validation.rs +++ b/crates/packvium-core/src/validation.rs @@ -84,6 +84,7 @@ impl IndependentValidator { dimensions: packed.container.inner_dimensions, }; let support_graph = ContactGraph::from_placements(&packed.placements); + let collisions = collision_pairs(&packed.placements); let mut payload = 0_i64; let mut tag_counts = BTreeMap::::new(); // Without a tag in the container no pair can be incompatible, so the common case @@ -136,14 +137,16 @@ impl IndependentValidator { { issue(&mut issues, "obstacle_collision", &id); } - for other in packed.placements.iter().skip(index + 1) { - if placements_collide(placement, other) && !valid_nesting(placement, other) { - issue( - &mut issues, - "collision", - &format!("{} with {}", id, other.instance.id()), - ); - } + for &other_index in collisions + .range((index, 0)..=(index, usize::MAX)) + .map(|(_, right)| right) + { + let other = &packed.placements[other_index]; + issue( + &mut issues, + "collision", + &format!("{} with {}", id, other.instance.id()), + ); } if compatibility_sensitive && let Some(other) = first_incompatible(&packed.placements, index) @@ -165,13 +168,27 @@ impl IndependentValidator { .item .minimum_support_ratio .max(request.config.minimum_support_ratio); + let support_area = support_graph.support_area(index); + let base_area = placement.envelope_dimensions.base_area(); if !support_area_sufficient( placement.envelope_origin.z, - support_graph.support_area(index), - placement.envelope_dimensions.base_area(), + support_area, + base_area, required, ) { issue(&mut issues, "support", &id); + } else if placement.envelope_origin.z != 0 + && required > 0.0 + && support_area * 2 <= base_area + && !crate::support_polygon::centre_of_gravity_supported( + placement.envelope_box(), + support_graph + .supporters(index) + .iter() + .map(|edge| packed.placements[edge.index].envelope_box()), + ) + { + issue(&mut issues, "centre_of_gravity_unsupported", &id); } if !ground_contact_valid_with_graph(packed, index, &support_graph) { issue(&mut issues, "ground_contact_violation", &id); @@ -223,6 +240,60 @@ impl IndependentValidator { } } +/// Intersecting placement pairs `(left, right)` with `left < right`, found via a z-bucketed +/// sweep along x (near-linear on spread-out scenes, `O(n^2)` when many boxes share an x +/// range without touching), matching Python's `_collision_pairs` and PHP's +/// `collisionPairs`. +fn collision_pairs(placements: &[Placement]) -> BTreeSet<(usize, usize)> { + let mut pairs = BTreeSet::new(); + if placements.len() < 2 { + return pairs; + } + let cell = placements + .iter() + .map(|placement| { + let box_ = placement.envelope_box(); + box_.z2() - box_.origin.z + }) + .max() + .unwrap_or(1) + .max(1); + let mut buckets = BTreeMap::>::new(); + for (index, placement) in placements.iter().enumerate() { + let box_ = placement.envelope_box(); + let z0 = box_.origin.z.div_euclid(cell); + let z1 = (box_.z2() - 1).div_euclid(cell); + buckets.entry(z0).or_default().push(index); + if z1 != z0 { + buckets.entry(z1).or_default().push(index); + } + } + let mut active = Vec::<(i64, usize)>::new(); + for indices in buckets.into_values() { + let mut ordered = indices + .into_iter() + .map(|index| { + let box_ = placements[index].envelope_box(); + (box_.origin.x, box_.x2(), index) + }) + .collect::>(); + ordered.sort_unstable(); + active.clear(); + for (x1, x2, index) in ordered { + active.retain(|(right, _)| *right > x1); + for &(_, other) in &active { + if placements_collide(&placements[index], &placements[other]) + && !valid_nesting(&placements[index], &placements[other]) + { + pairs.insert((index.min(other), index.max(other))); + } + } + active.push((x2, index)); + } + } + pairs +} + /// The first other item in the container, in placement order, that the item at `index` /// may not share it with: either one's `incompatible_tags` names a tag the other carries. fn first_incompatible(placements: &[Placement], index: usize) -> Option<&Item> { @@ -713,4 +784,78 @@ mod tests { .any(|issue| issue.code == "non_stackable") ); } + + #[test] + fn validator_rejects_overhanging_centre_of_gravity_when_area_ratio_is_met() { + let mut packed = nested_container(2, None, None); + for placement in &mut packed.placements { + placement.instance.item.nesting_height = None; + placement.instance.item.minimum_support_ratio = 0.25; + } + packed.container.inner_dimensions.length = Length(100); + packed.placements[0].dimensions.length = Length(30); + packed.placements[0].envelope_dimensions.length = Length(30); + packed.placements[1].position.z = 10; + packed.placements[1].envelope_origin.z = 10; + packed.placements[1].dimensions.length = Length(100); + packed.placements[1].envelope_dimensions.length = Length(100); + + let report = validate_nested(packed); + + assert!(!report.valid); + assert!( + report + .issues + .iter() + .any(|issue| issue.code == "centre_of_gravity_unsupported"), + "{:?}", + report.issues + ); + } + + #[test] + fn z_bucketed_collision_sweep_matches_all_pairs_scan() { + let mut seed = 0x9e37_79b9_7f4a_7c15_u64; + let base = nested_container(1, None, None); + let mut template = base.placements[0].clone(); + template.instance.item.nesting_height = None; + + for count in [0, 1, 2, 16, 48] { + let mut placements = Vec::with_capacity(count); + for index in 0..count { + let mut next = || { + seed = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1); + (seed >> 33) as i64 + }; + let dims = Dimensions { + length: Length(1 + next().rem_euclid(15)), + width: Length(1 + next().rem_euclid(15)), + height: Length(1 + next().rem_euclid(20)), + }; + let origin = Point { + x: next().rem_euclid(30), + y: next().rem_euclid(30), + z: next().rem_euclid(40), + }; + let mut p = template.clone(); + p.instance.sequence = index + 1; + p.position = origin; + p.envelope_origin = origin; + p.dimensions = dims; + p.envelope_dimensions = dims; + placements.push(p); + } + let mut expected = BTreeSet::new(); + for left in 0..placements.len() { + for right in (left + 1)..placements.len() { + if placements_collide(&placements[left], &placements[right]) + && !valid_nesting(&placements[left], &placements[right]) + { + expected.insert((left, right)); + } + } + } + assert_eq!(collision_pairs(&placements), expected); + } + } } diff --git a/docs/GUARANTEES.md b/docs/GUARANTEES.md index 8cdcba6..0d40bf9 100644 --- a/docs/GUARANTEES.md +++ b/docs/GUARANTEES.md @@ -61,7 +61,7 @@ silently — if you need them, they belong in your own layer above this library. ## Status of this release -Version `1.8.0` freezes the public API. Field names, status codes, the objective +Version `1.9.0` freezes the public API. Field names, status codes, the objective vector, the numeric policy and the validation rules do not change without a major version, so any `1.x` is a safe upgrade from any earlier `1.x`. A caret or tilde constraint on `1.0` is enough; an exact pin is no longer required. diff --git a/docs/PUBLIC-API.md b/docs/PUBLIC-API.md index 0f4fa85..7d8faa3 100644 --- a/docs/PUBLIC-API.md +++ b/docs/PUBLIC-API.md @@ -239,6 +239,9 @@ All counters are non-negative integers. A zero means the selected solver did not that phase; it does not mean the metric is unsupported. Compatibility fields `algorithm.placements_attempted` and `algorithm.candidates_evaluated` remain and must equal `metrics.orientations_considered` and `metrics.feasible_candidates`. +For a multi-start portfolio these counters belong to the selected start; the complete +list of starts is recorded separately in `termination.starts`. Counters are not summed +across starts. Metrics are diagnostics: they never participate in feasibility, ranking or the objective vector. @@ -469,9 +472,9 @@ bounds its work by counting must get the same answer on any machine, and a start own share of the clock would lose quietly, with no flag saying the answer depended on the machine's speed. When the clock does fire, the portfolio-wide deadline is reached and `time_limit_reached` is true. Rust and the JavaScript fallback always run their starts against -the one portfolio deadline. Each start keeps its own counters against the whole budget in -Python, PHP and Rust; the JavaScript fallback hands each later start what the earlier ones -left of one budget, so the same number buys less search there. +the one portfolio deadline. Each start keeps its own counters against the whole budget, in all +four engines; until 1.9.0 the JavaScript fallback handed each later start what the earlier ones +left of one budget, so the same number bought less search there. **Read `any_start_truncated` when the answer must not depend on the budget.** The selected start can finish while another start, one that might have won, was stopped by the budget; the diff --git a/docs/UNITS-AND-NUMERICS.md b/docs/UNITS-AND-NUMERICS.md index fd1e6e6..c09c8e8 100644 --- a/docs/UNITS-AND-NUMERICS.md +++ b/docs/UNITS-AND-NUMERICS.md @@ -59,6 +59,42 @@ a caller would get a number from one and a refusal from another for the same inp carries the guarded sums in a representation that holds `10^30` exactly: Python's `int`, PHP's `BigInt` decimal strings, JavaScript's `BigInt`, Rust's `i128`. +Areas follow the same rule in the search itself (1.9.0). Two lengths below +`PHP_INT_MAX` ticks multiply past a native `int` -- a 10 mm wide item longer than about +3,600 km already does -- and Python and Rust hold that product exactly. PHP forms every such +product (base and contact areas, their sums and the load shared by them, the centre-of-gravity +hull, lattice slot counts, the candidate score's room-left term) through +`Packvium\Support\ExactInteger` and `ExactGeometry`: the native `int` while it fits, an exact +decimal string past it, so an ordinary request pays one `is_int` check. The public +`Dimensions::baseAreaTicks()` and `AxisAlignedBox::overlapAreaXY()` keep their `int` contract. +`support_ratio` and `volume_utilization` are Python's correctly rounded `int / int`, not a +quotient of two doubles. + +**The admission ceiling (1.9.0).** Every engine refuses, before any model is built, a +JSON request with a length past `2^53 - 1` ticks (about 563,000 km) or a box -- an item, a +container's inner or outer dimensions, an obstacle, a made-to-measure step -- enclosing more than +`10^30` cubic ticks (about 244 million cubic metres). Both are `invalid_request` with reason +`above_maximum` at the offending pointer (ERRORS.md). The first is the largest tick +count JavaScript's `Number` holds exactly; the second is the bound path's own ceiling, which keeps +`volume x 10^6` inside Rust's `i128`. Until 1.9.0 each engine failed past its own native limit: Rust +and PHP refused a length past `2^63 - 1` ticks with different errors, Python and JavaScript answered, +Python died with `decimal.InvalidOperation` at `10^20` mm, and Rust overflowed `i128` on a container +past about `1.7 x 10^32` cubic ticks. A whole JSON number past `2^53 - 1` is refused the +same way however a parser stored it, and a value past a native integer is read exactly to tell +which way it is out of range. + +**Weights (1.9.0).** A weight is at most `2^63 - 1` ticks (about 1.15 million +tonnes), and so is every item's weight times its quantity plus the heaviest container tare, so +no container's payload or gross weight can pass a signed 64-bit integer, which is how Rust and +PHP add them. Past either, the request is `invalid_request` / `above_maximum`, at the weight or at +`/items`. A weight written as a JSON number past `2^53 - 1` is `invalid_value`: JavaScript has +rounded such a number before any engine code reads it, so a weight that large is written as a +string. Inside the ceiling every engine is exact: Python's `int`, PHP's `int` and `BigInt`, +Rust's `i64` with `i128` products, and in JavaScript a `BigInt` for every weight sum. A +JavaScript result carries a weight's `ticks`, and a `shipping_cost` score position, as a `Number` +while it is exact and as a `BigInt` past `2^53 - 1`; `stringifyExact` and `parseExact` move such +a result through JSON text without rounding it, and `pack` uses them on both backends. + That intermediate ceiling is deliberately not the result ceiling. The five bound keys can cross JSON and are returned as JavaScript `Number` values, so every engine also refuses a final key above **`2^53 - 1` (`9,007,199,254,740,991`)**. This is the largest integer all four