From 5b91ac5bccc35f35cebbfdbb0f5148d314f004d4 Mon Sep 17 00:00:00 2001 From: Anton Date: Mon, 26 Oct 2026 15:34:30 -0400 Subject: [PATCH] chore(release): 1.8.0 --- .github/DISCUSSION_TEMPLATE/ideas.yml | 28 + .github/DISCUSSION_TEMPLATE/q-a.yml | 30 + .github/DISCUSSION_TEMPLATE/show-and-tell.yml | 33 + .github/ISSUE_TEMPLATE/bug_report.yml | 105 +++ .github/ISSUE_TEMPLATE/config.yml | 11 + .github/ISSUE_TEMPLATE/feature_request.yml | 62 ++ .github/workflows/rc.yml | 60 ++ .github/workflows/release.yml | 4 +- CHANGELOG.md | 34 + CITATION.cff | 4 +- CONTRIBUTING.md | 21 + Cargo.toml | 4 +- README.md | 16 +- codemeta.json | 6 +- docs/GUARANTEES.md | 21 +- docs/PUBLIC-API.md | 56 +- src/api.rs | 40 + src/bounds.rs | 677 ++++++++----- src/contact_graph.rs | 18 +- src/deadline.rs | 34 + src/model.rs | 90 ++ src/rebalance.rs | 11 +- src/request_errors.rs | 18 +- src/result_validation/bound.rs | 888 ++++++++++++++++++ src/result_validation/json.rs | 13 + src/result_validation/lattice.rs | 15 +- src/result_validation/mod.rs | 39 +- src/result_validation/objective.rs | 5 +- src/result_validation/spec.rs | 19 +- src/result_validation/units.rs | 45 + src/sequence.rs | 42 +- src/solvers/blocks.rs | 155 ++- src/solvers/exact.rs | 31 +- src/solvers/extreme.rs | 106 ++- src/solvers/grid.rs | 22 +- src/solvers/maximal.rs | 5 +- src/solvers/portfolio.rs | 18 +- src/validation.rs | 35 +- tests/effort_stop.rs | 223 +++++ tests/request_errors.rs | 29 + 40 files changed, 2666 insertions(+), 407 deletions(-) create mode 100644 .github/DISCUSSION_TEMPLATE/ideas.yml create mode 100644 .github/DISCUSSION_TEMPLATE/q-a.yml create mode 100644 .github/DISCUSSION_TEMPLATE/show-and-tell.yml create mode 100644 .github/ISSUE_TEMPLATE/bug_report.yml create mode 100644 .github/ISSUE_TEMPLATE/config.yml create mode 100644 .github/ISSUE_TEMPLATE/feature_request.yml create mode 100644 .github/workflows/rc.yml create mode 100644 src/result_validation/bound.rs create mode 100644 tests/effort_stop.rs diff --git a/.github/DISCUSSION_TEMPLATE/ideas.yml b/.github/DISCUSSION_TEMPLATE/ideas.yml new file mode 100644 index 0000000..5520470 --- /dev/null +++ b/.github/DISCUSSION_TEMPLATE/ideas.yml @@ -0,0 +1,28 @@ +title: "[Idea] " +labels: ["idea"] +body: + - type: markdown + attributes: + value: | + Ideas for new packing rules, outputs or integrations. An idea the maintainers take on + is moved to an issue and linked back here, so you can follow it. + - type: textarea + id: problem + attributes: + label: The problem behind the idea + description: What real shipment or load does today's library not handle? + validations: + required: true + - type: textarea + id: idea + attributes: + label: The idea + validations: + required: true + - type: input + id: package + attributes: + label: Package(s) you use + placeholder: "packvium" + validations: + required: false diff --git a/.github/DISCUSSION_TEMPLATE/q-a.yml b/.github/DISCUSSION_TEMPLATE/q-a.yml new file mode 100644 index 0000000..67d3fa4 --- /dev/null +++ b/.github/DISCUSSION_TEMPLATE/q-a.yml @@ -0,0 +1,30 @@ +title: "[Q&A] " +labels: ["question"] +body: + - type: markdown + attributes: + value: | + Ask anything about using the library. If you have found a wrong result or an error, + a bug report is the better place. + - type: input + id: package-version + attributes: + label: Package and version + placeholder: "packvium 1.8.0 (Rust)" + validations: + required: true + - type: textarea + id: question + attributes: + label: Your question + description: What you are trying to pack, and what you tried. + validations: + required: true + - type: textarea + id: request + attributes: + label: Request (optional) + description: The JSON request or code, if it helps. + render: json + validations: + required: false diff --git a/.github/DISCUSSION_TEMPLATE/show-and-tell.yml b/.github/DISCUSSION_TEMPLATE/show-and-tell.yml new file mode 100644 index 0000000..0b34d0e --- /dev/null +++ b/.github/DISCUSSION_TEMPLATE/show-and-tell.yml @@ -0,0 +1,33 @@ +title: "[Show and tell] " +labels: ["show-and-tell"] +body: + - type: markdown + attributes: + value: | + Using the library in a shop, a warehouse tool or a load planner? Tell us how. Leave out + anything confidential about your business. + - type: textarea + id: what + attributes: + label: What you built + validations: + required: true + - type: input + id: package-version + attributes: + label: Package and version + placeholder: "packvium 1.8.0 (Rust)" + validations: + required: false + - type: textarea + id: lessons + attributes: + label: What worked, and what got in the way + validations: + required: false + - type: input + id: link + attributes: + label: Link (optional) + validations: + required: false diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml new file mode 100644 index 0000000..69b09d3 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -0,0 +1,105 @@ +name: Bug report +description: A result that is wrong, an error you did not expect, or a crash. +title: "[Bug]: " +labels: ["bug", "needs-triage"] +body: + - type: markdown + attributes: + value: | + Thanks for reporting. A report we can run is a report we can fix, so the most useful + thing below is the smallest request that shows the problem. + + **Security problems do not belong here.** Use **Report a vulnerability** under the + Security tab instead; it opens a private advisory. + - type: dropdown + id: package + attributes: + label: Package + description: Which package did you call? + options: + - "packvium (PyPI) — Packvium for Python" + - "packvium-native (PyPI) — Packvium native backend selector for Python" + - "packvium/packvium (Packagist) — Packvium for PHP" + - "packvium/native-bridge (Packagist) — Packvium native bridge for PHP" + - "@packvium/engine (npm) — Packvium for Node.js" + - "@packvium/browser (npm) — Packvium for browsers" + - "packvium (crates.io) — Packvium for Rust" + - "packvium-native-rust (PyPI) — Packvium native engines: Python wheels, Node addons and the C library" + - Not sure + default: 6 + validations: + required: true + - type: input + id: version + attributes: + label: Package version + description: The exact version installed, for example 1.8.0. + placeholder: "1.8.0" + validations: + required: true + - type: input + id: runtime + attributes: + label: Runtime and operating system + description: Language runtime version and OS, for example "Python 3.12, Ubuntu 24.04" or "PHP 8.3, macOS 15". + validations: + required: true + - type: dropdown + id: profile + attributes: + label: Search profile + options: + - fast + - balanced + - quality + - exact_small + - Not set / default + - Not sure + validations: + required: false + - type: textarea + id: request + attributes: + label: Request that reproduces it + description: | + The JSON request, or the code that builds it, cut down as far as it still shows the + problem. Remove anything confidential; renamed item ids are fine. + render: json + validations: + required: true + - type: textarea + id: actual + attributes: + label: What happened + description: The result (or its relevant part), or the full error message and stack trace. + render: text + validations: + required: true + - type: textarea + id: expected + attributes: + label: What you expected + description: What the result should have been, and why. If another of the packages gives a different answer for the same request, say which. + validations: + required: true + - type: dropdown + id: stopped-by + attributes: + label: How was the search limited? + description: A search stopped by a time limit can differ between runs by design; one stopped by an effort budget cannot. + options: + - effort_budget + - time_limit_ms + - Both + - Neither / not sure + validations: + required: false + - type: checkboxes + id: checks + attributes: + label: Before submitting + options: + - label: I searched the existing issues and did not find this one. + required: true + - label: I read [docs/GUARANTEES.md](https://github.com/toxakara/packvium-rust/blob/HEAD/docs/GUARANTEES.md) and this is not something it says the library does not guarantee. + required: false diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 0000000..f210780 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,11 @@ +blank_issues_enabled: false +contact_links: + - name: Question or help with a request + url: https://github.com/toxakara/packvium-rust/discussions/categories/q-a + about: Ask in Discussions → Q&A. Answers there help the next person too. + - name: Report a security vulnerability + url: https://github.com/toxakara/packvium-rust/security/advisories/new + about: Report privately. Do not open a public issue for a security problem. + - name: Documentation + url: https://packvium.com/docs + about: Guides, the request contract and the constraint reference. diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml new file mode 100644 index 0000000..a7a36ae --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.yml @@ -0,0 +1,62 @@ +name: Feature request +description: A packing rule, constraint, output or integration the library does not support yet. +title: "[Feature]: " +labels: ["enhancement", "needs-triage"] +body: + - type: markdown + attributes: + value: | + Open-ended ideas are welcome in **Discussions → Ideas** first. Use this form when you can + describe a concrete problem the library does not solve today. + - type: dropdown + id: package + attributes: + label: Package you use + options: + - "packvium (PyPI) — Packvium for Python" + - "packvium-native (PyPI) — Packvium native backend selector for Python" + - "packvium/packvium (Packagist) — Packvium for PHP" + - "packvium/native-bridge (Packagist) — Packvium native bridge for PHP" + - "@packvium/engine (npm) — Packvium for Node.js" + - "@packvium/browser (npm) — Packvium for browsers" + - "packvium (crates.io) — Packvium for Rust" + - "packvium-native-rust (PyPI) — Packvium native engines: Python wheels, Node addons and the C library" + - More than one + default: 6 + validations: + required: true + - type: input + id: version + attributes: + label: Package version + placeholder: "1.8.0" + validations: + required: true + - type: textarea + id: problem + attributes: + label: The problem + description: What are you packing, into what, and what rule or output is missing? A real (anonymised) example helps more than a general description. + validations: + required: true + - type: textarea + id: proposal + attributes: + label: What you would like + description: The behaviour or field you have in mind, if you have one. + validations: + required: false + - type: textarea + id: workaround + attributes: + label: What you do today + description: Any workaround you use, and what it costs you. + validations: + required: false + - type: markdown + attributes: + value: | + Every package implements one shared contract, so a new rule or result field lands in all + of them together, and a change to the request or result format waits for a release that + is allowed to change it. A request that is accepted may therefore take more than one + release to ship. diff --git a/.github/workflows/rc.yml b/.github/workflows/rc.yml new file mode 100644 index 0000000..8efbc50 --- /dev/null +++ b/.github/workflows/rc.yml @@ -0,0 +1,60 @@ +name: rc + +# A pre-release tag (`v1.9.0-rc.1`) builds and tests exactly as `release.yml` does and then +# runs `cargo publish --dry-run`. Nothing is uploaded: crates.io has no test registry, and a +# version published there "can never be overwritten, and the code cannot be deleted". A +# consumer tries the RC as a git dependency on the tag: +# packvium = { git = "https://github.com/toxakara/packvium-rust", tag = "v" } +# Publishing real `-rc` versions to crates.io would be the owner's decision; it needs no new +# account, but every one stays on the crate page for good. There is no GitHub Release. + +on: + push: + tags: ["v*-*"] + +permissions: + contents: read + +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + - uses: dtolnay/rust-toolchain@46511b1c83438f0dd37c02d843619ece5a4abb5b # 1.97.1 + - uses: Swatinem/rust-cache@e18b497796c12c097a38f9edb9d0641fb99eee32 # v2 + + # The tag and the 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. + - name: The tag must match the version in Cargo.toml + run: | + tagged="${GITHUB_REF_NAME#v}" + built=$(grep -m1 '^version = ' Cargo.toml | sed -E 's/version = "(.*)"/\1/') + if [ "$tagged" != "$built" ]; then + echo "tag $GITHUB_REF_NAME does not match Cargo.toml version $built" >&2 + exit 1 + fi + + - name: The tag must have a changelog entry + run: | + tagged="${GITHUB_REF_NAME#v}" + if ! grep -q "^## \[${tagged}\]" CHANGELOG.md; then + echo "CHANGELOG.md has no '## [${tagged}]' section for tag $GITHUB_REF_NAME" >&2 + exit 1 + fi + + - run: cargo test + - run: cargo package --locked + + - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 + with: + name: crate + path: target/package/*.crate + + publish-dry-run: + needs: build + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + - uses: dtolnay/rust-toolchain@46511b1c83438f0dd37c02d843619ece5a4abb5b # 1.97.1 + - run: cargo publish --dry-run --locked diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index ffed1fa..c614390 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -11,9 +11,11 @@ name: release # as CARGO_REGISTRY_TOKEN in a GitHub environment named `crates-io` with whatever # reviewers the project wants. +# A pre-release tag (`v1.9.0-rc.1`) never reaches the production registries: the negated +# pattern must follow the positive one, and `rc.yml` takes those tags instead. on: push: - tags: ["v*"] + tags: ["v*", "!v*-*"] permissions: contents: read diff --git a/CHANGELOG.md b/CHANGELOG.md index f41ff03..a918291 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,40 @@ What changed in `packvium` on crates.io, release by release. 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.8.0] + +Results now say how far they can be from the best possible answer, `Optimal` means a proof, +and a mistyped flag is refused instead of defaulted. + +### Added + +- **`optimality.lower_bound` and the gap** under the `default` and `lowest_cost` objectives, + with `bounds::for_request`, `from_items`, `statement` and `Statement`; `validate_json` + checks them. + +### Changed + +- **Only attaining the bound sets `Optimal`;** a registry solver's `Optimal` is demoted to + `Feasible` first. +- **An effort budget names a stop:** a run that ends on exactly its budget is `complete`. +- **A non-boolean `keep_upright`, `stackable`, `must_be_on_floor` or + `require_placement_coordinates` is `invalid_request` / `wrong_type`**; it was read as the + field's default. + `validate_json` returns `MalformedResult` (`contract`) for such a request, and reads `null` as + the default. +- **Faster with identical answers:** loading-order checks about 3x, `exact_small` about 2x on + larger requests (the preflight answer is reused instead of solved twice), axle-limited solves + up to 25%, `rebalance_weight` about 18%. + +### Fixed + +- **`homogeneous_blocks` named alone packs under `fast` and `balanced`**; it stopped before + its first block and placed nothing. +- **`validate` reads `units: null` and `units.length: null` as millimetres**, as the engines do, + and refuses a `units` that is not an object, or an unknown `units.length`, as a `contract` + `MalformedResult` naming the field. `units.weight` is not a field and is ignored: put the unit + on each weight. + ## [1.7.0] The reference validator ships in the crate, `quality` looks ahead in its block solver and diff --git a/CITATION.cff b/CITATION.cff index e2c0937..493550e 100644 --- a/CITATION.cff +++ b/CITATION.cff @@ -5,7 +5,7 @@ type: software authors: - name: "Packvium contributors" website: "https://packvium.com" -version: "1.7.0" +version: "1.8.0" license: MIT url: "https://packvium.com" repository-code: "https://github.com/toxakara/packvium-rust" @@ -23,3 +23,5 @@ keywords: - packing-algorithm - logistics - deterministic + - box-packing + - load-planning diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index e0c49a3..8c9ec2f 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -70,3 +70,24 @@ exact input. For anything with security implications, follow [SECURITY.md](SECURITY.md) rather than opening a public issue. + +## How your feedback is handled + +Every issue and discussion is read by a maintainer. This is what happens next: + +1. **New issues are labelled `needs-triage`.** A maintainer answers with one of: a question + back to you, a confirmation, or a reason it will not be taken on. +2. **A confirmed bug** gets the `bug` label and is reproduced from your request. A wrong result + in one package is checked against the others, because all of them implement the same + contract and must agree. +3. **An accepted feature request or idea** is added to the project's backlog, and the issue is + labelled `accepted` with a comment saying so. An idea from Discussions is first turned into + an issue and linked back to the discussion. +4. **When the change ships**, the issue is closed with the release it shipped in. A change to + the request or result format can only ship in a release that is allowed to change it, so + it may take more than one release. +5. **Declined** requests are closed with the reason, so you are never left waiting on a + silent issue. + +Questions go to **Discussions → Q&A**; security problems go to **Report a vulnerability** +under the Security tab, never to a public issue. diff --git a/Cargo.toml b/Cargo.toml index 99ea093..c0d239d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "packvium" -version = "1.7.0" +version = "1.8.0" edition = "2024" rust-version = "1.88" license = "MIT" @@ -10,7 +10,7 @@ repository = "https://github.com/toxakara/packvium-rust" homepage = "https://packvium.com" documentation = "https://packvium.com/docs" keywords = ["3d-bin-packing", "bin-packing", "3d-packing", "cartonization", "container-loading"] -categories = ["algorithms", "mathematics", "data-structures"] +categories = ["algorithms", "mathematics", "science"] authors = ["Packvium contributors"] # The published package name is `packvium`, matching the Python and PHP packages. diff --git a/README.md b/README.md index 7ceae83..8d0f38d 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@ coordinates and rotations for each item, with a reason for anything that did not Full documentation, the constraint reference and benchmarks live at [packvium.com](https://packvium.com). -> **Version 1.7.0 — the public API is frozen.** Field names, status codes and the +> **Version 1.8.0 — the public API is frozen.** Field names, status codes and the > objective vector do not change without a major version, so any `1.x` is a safe upgrade > from any earlier `1.x`. > Read [docs/GUARANTEES.md](https://github.com/toxakara/packvium-rust/blob/main/docs/GUARANTEES.md) @@ -25,7 +25,7 @@ or, in `Cargo.toml`: ```toml [dependencies] -packvium = "1.7" +packvium = "1.8" ``` ## Quick start @@ -167,6 +167,10 @@ as a fuse against a genuine hang. A search stopped by the budget says `effort_li an operational artifact built from it records its replay as `not_guaranteed`. `seed` is part of the request, so a different seed is a different, equally reproducible request. +`effort_limit` means the budget stopped work the search still had: a search that finishes on +exactly its budget reads `complete`, and `termination.any_start_truncated` says whether the +budget cut a start that might have won. + ## What it does - **Exact arithmetic.** Length is measured in ticks of 1/16000 mm and weight in 1/8 µg. @@ -182,6 +186,10 @@ of the request, so a different seed is a different, equally reproducible request maximal-space and bounded exact search, selected by problem shape and profile. - **Answers you can check.** Every solution is re-validated by logic independent of the search. Unplaced items come back with a reason code, not silently missing. +- **A proof, or the distance to one.** Under the `default` and `lowest_cost` objectives every + result states `optimality.lower_bound`. A complete result that attains it reports `optimal`, + which proves no packing obeying the request's rules scores better; any other carries the gap + to the bound (`gap_key`, `absolute_gap`, `relative_gap`). - **Multi-container and nested.** A request splits across as many containers as it needs; `pack_nested` solves caller-defined levels — cartons, then pallets — in order; a level with no items of its own packs the previous level's containers, and the chain stops at the first level @@ -231,7 +239,7 @@ Documentation, the constraint reference and the benchmarks are at | --- | --- | --- | | Python — [`packvium`](https://pypi.org/project/packvium/) | `pip install packvium` | [packvium-python](https://github.com/toxakara/packvium-python) | | PHP — [`packvium/packvium`](https://packagist.org/packages/packvium/packvium) | `composer require packvium/packvium` | [packvium-php](https://github.com/toxakara/packvium-php) | -| Rust — [`packvium`](https://crates.io/crates/packvium) | `packvium = "1.7"` | [packvium-rust](https://github.com/toxakara/packvium-rust) | +| Rust — [`packvium`](https://crates.io/crates/packvium) | `packvium = "1.8"` | [packvium-rust](https://github.com/toxakara/packvium-rust) | | Node.js — [`@packvium/engine`](https://www.npmjs.com/package/@packvium/engine) | `npm install @packvium/engine` | [packvium-node](https://github.com/toxakara/packvium-node) | | Browser / WebAssembly — [`@packvium/browser`](https://www.npmjs.com/package/@packvium/browser) | `npm install @packvium/browser` | [packvium-wasm](https://github.com/toxakara/packvium-wasm) | | PHP FFI bridge — [`packvium/native-bridge`](https://packagist.org/packages/packvium/native-bridge) | `composer require packvium/native-bridge` | [packvium-php-bridge](https://github.com/toxakara/packvium-php-bridge) | @@ -254,7 +262,7 @@ CodeMeta form. @software{packvium_rust, author = {{Packvium contributors}}, title = {Packvium for Rust}, - version = {1.7.0}, + version = {1.8.0}, license = {MIT}, url = {https://packvium.com} } diff --git a/codemeta.json b/codemeta.json index 56a802a..1d1653e 100644 --- a/codemeta.json +++ b/codemeta.json @@ -3,7 +3,7 @@ "@type": "SoftwareSourceCode", "name": "Packvium for Rust", "description": "Deterministic 3D bin-packing and cartonization engine for pallets, containers, trucks and shipping cartons. Exact integer geometry, reproducible results.", - "version": "1.7.0", + "version": "1.8.0", "license": "https://spdx.org/licenses/MIT", "author": [ { @@ -26,6 +26,8 @@ "truck-loading", "packing-algorithm", "logistics", - "deterministic" + "deterministic", + "box-packing", + "load-planning" ] } diff --git a/docs/GUARANTEES.md b/docs/GUARANTEES.md index e0949d9..8cdcba6 100644 --- a/docs/GUARANTEES.md +++ b/docs/GUARANTEES.md @@ -14,8 +14,11 @@ After a result reports `feasible` or `optimal` and passes independent validation - **exact arithmetic** — all geometry is integer, in units of 1/16000 mm for length and 1/8 µg for weight. No coordinate is ever a binary floating-point number, so no placement decision depends on rounding; -- **determinism** — identical input and identical seed produce an identical result, on - any platform, when the search completes or stops on `configuration.effort_budget`. A +- **determinism** — for a fixed backend and version, identical input and seed produce + identical packing and deterministic diagnostics on supported platforms when the search + completes or stops on `configuration.effort_budget`. Wall-clock timing diagnostics, + such as `duration_ms` and `elapsed_ms`, are excluded. This does not promise identical + solutions between backends; their documented native quality differences remain. A search stopped by `time_limit_ms` stops where the host's speed let it, so it may differ between runs; the result says which limit stopped it; - **complete accounting** — every requested item instance appears exactly once, either @@ -24,9 +27,15 @@ After a result reports `feasible` or `optimal` and passes independent validation ## It does not guarantee - **A globally optimal packing.** The `fast`, `balanced` and `quality` profiles are - heuristic. Only `exact_small`, within its item limit, searches exhaustively — and even - then optimality is not certified in the result. A returned solution is a good solution, - not a proven best one. + heuristic, and `exact_small` searches exhaustively only within its item limit. A returned + solution is a good solution, not a proven best one, unless the result proves it: under the + `default` and `lowest_cost` objectives a result states `optimality.lower_bound`, and a + complete result whose score attains that bound reports `optimal` / `proven_optimal`. That + proves no packing obeying the request's rules scores better on that objective; it says + nothing about a rule the request cannot express. Any other stated result carries the gap + to the bound, an upper limit on what a longer search could still gain. The statement is + withheld if its gap exceeds the portable integer ceiling of `2^53 - 1`, even when the + request's bound fits. Where geometry makes a request hard, expect a gap. - **Physical safety in transit.** Nothing here models vibration, shock, acceleration, tipping, strapping or load shifting. A geometrically valid packing can still be an unsafe shipment. @@ -52,7 +61,7 @@ silently — if you need them, they belong in your own layer above this library. ## Status of this release -Version `1.7.0` freezes the public API. Field names, status codes, the objective +Version `1.8.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 a784f42..d737e88 100644 --- a/docs/PUBLIC-API.md +++ b/docs/PUBLIC-API.md @@ -155,10 +155,16 @@ request field. - `termination.code`: `complete`, `time_limit`, `effort_limit`, or `error`; - `optimality.code`: `proven_optimal`, `proven_infeasible`, `best_found`, or `not_proven`. The 1.1.0 freeze reserved and typed `gap_key`, `absolute_gap` and `relative_gap` - alongside it. The pre-1.1.0 extension point remains open: closing the object would - make a previously valid producer fail a 1.1.0 validator, which is a breaking change - and therefore not legal in this minor release. No engine emits the reserved fields - yet, so `code` is still the only key any Packvium result carries; + alongside it, and the 1.8.0 freeze added `lower_bound`: the lower bound on + `score`, in the result's own score order, through the first position the result misses + -- or all of it when none is missed, which proves the result optimal for its objective + under the rules this library models. `gap_key` requires `lower_bound`, and absence of + `lower_bound` makes no statement at all; it is never "attained". The pre-1.1.0 + extension point remains open: closing the object would make a previously valid + producer fail a validator, which is a breaking change. Every engine emits these fields + since, on the primary result and on each alternative, for the `default` and + `lowest_cost` objectives; a complete result that attains its bound reports `status: + optimal` and `code: proven_optimal`, and nothing else does; - legacy `status`: `optimal`, `feasible`, `best_found`, `time_limit`, `infeasible`, or `invalid_result`; - packed containers with exact coordinates, dimensions, rotations, and a `centre_of_mass_offset_ppm` — the weighted centre of mass's exact-integer Chebyshev @@ -238,7 +244,10 @@ objective vector. `algorithm.time_limit_reached` and `algorithm.effort_limit_reached` identify distinct, mutually exclusive causes. The former is only a wall-clock deadline. The latter means -one of the request's counted-work boundaries was reached. An unpacked `time_limit` or +the selected start was stopped by one of the request's counted-work boundaries: the search +had more work to do and the budget refused it. A start that finished having used exactly its +budget was not stopped, and reports neither flag. No counter in `algorithm.metrics` ends +above its limit: each counted step is checked before it is taken. An unpacked `time_limit` or `effort_limit` reason must match the corresponding flag. ## Loading and unloading sequences @@ -401,8 +410,9 @@ deadline: Each fact is an open object with a required string `code`. Consumers must preserve an unknown code and any additional fields, allowing future effort/node/cancellation limits without turning a minor release into a parsing break. `status` remains for one -compatibility cycle and is checked against the three facts. The alpha release emits no -`proven_optimal` claim without a future proof/certificate. +compatibility cycle and is checked against the three facts. `proven_optimal` is emitted only +on a complete result whose score attains its stated `optimality.lower_bound`: a proof that no +packing obeying the request's rules scores better on the result's own objective. `status: infeasible`, with `feasibility: infeasible` and `optimality: proven_infeasible`, is emitted only when the portfolio ranks no result at all. A request whose every item is proven @@ -452,6 +462,23 @@ The fields answer separate questions: | `winning_start_truncated` | The selected packing itself came from an interrupted start. | | `global_deadline_reached` | The portfolio-wide deadline expired, independently of individual start slices. | +**Under an `effort_budget` the clock is the request's fuse, and fires only as a whole.** +Without one, Python and PHP give each start an even share of the time left, so one slow start +cannot starve the rest. With one, every start may use all the time left: a request that +bounds its work by counting must get the same answer on any machine, and a start cut by its +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. + +**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 +top-level flags then read `complete`, because they describe the selected start. +`any_start_truncated` is the only field that says a larger budget could change the answer. A +checkout that caches a quote refuses one on it (ECOMMERCE-CHECKOUT-INTEGRATIONS.md D3). + The aggregate fields are derived only from `starts`. Exactly one record is selected. `completed` and `truncated` are mutually exclusive and both require `started`. `termination.code` is `time_limit` when the selected start or portfolio hit the wall @@ -526,9 +553,10 @@ valid. A result without the documented shape is refused as `MalformedResult`, wh same as one JSON document for a binding. - PyO3 (`packvium_native_rust`): `validate_json(request, result)` over JSON text, a list of `{"code", "detail"}` dicts, `MalformedResult` (a `ValueError`) with `kind`. -- `@packvium/engine`: `validate(request, result)`, `MalformedResult`, and - `ValidatorUnavailableError` (`code: 'validator_unavailable'`) when the compiled addon is - absent, until the JavaScript fallback's port. +- `@packvium/engine`: `validate(request, result)` and `MalformedResult`; the compiled addon + answers when it is loaded and the package's JavaScript port otherwise (1.8.0). + `ValidatorUnavailableError` (`code: 'validator_unavailable'`) is still exported but + deprecated: nothing throws it since 1.8.0. - `@packvium/browser`: `validate(request, result)`, a promise, `MalformedResult`. - PHP: `Packvium\Validation\validate(array $request, array $result)`, a `list` @@ -727,3 +755,11 @@ depend on the exact shape. Python, PHP, Rust and the JavaScript fallback accept the same top-level keys: `units`, `configuration`, `items`, `containers`, `catalog_versions_used`, `policy`, `output` and `fixed_placements`. + +`units` holds one key, `length`: the unit of every length written without one, millimetres when +`units`, or `units.length`, is absent or `null`. There is no request-wide weight unit. A weight +takes its unit from the measure itself (`"2.5 kg"`, `{"value": "2.5", "unit": "kg"}`), and a +bare number is grams. `units.weight` is not a field: today every engine ignores it without an +error, so `{"length": "cm", "weight": "kg"}` still reads a bare weight `2` as 2 g. Write the unit +on each weight instead. A future release that changes the request schema will refuse unknown +keys in `units`, as it already refuses them in `configuration`. diff --git a/src/api.rs b/src/api.rs index 89b5809..474760e 100644 --- a/src/api.rs +++ b/src/api.rs @@ -1,3 +1,4 @@ +use crate::bounds; use crate::canonical_json::json_integer; use crate::error::{PackError, PackResult, RequestError}; use crate::fixed; @@ -411,6 +412,10 @@ pub fn pack_request_with_policy( policy: &PolicyRuleSet, ) -> PackResult { validate_request(request)?; + // Once per pack, from the request alone and before the first solver runs, so computing + // the bound never depends on which solver won or how much of the deadline was left + // (OPTIMALITY-GAP.md F3). + let objective_bound = bounds::for_request(request); // Registering the constraint is what makes an illegal candidate be rejected *during* // search rather than filtered out of a chosen answer -- and it is also what makes the // uniform-lattice and homogeneous-block fast paths stand down, since both gate on @@ -473,9 +478,44 @@ pub fn pack_request_with_policy( crate::solvers::unpriceable_container(&alternative.containers, &request.config).is_none() }); warn_unsupported_placements(&mut result, request.config.minimum_support_ratio); + state_optimality(&mut result, objective_bound.as_deref()); Ok(result) } +/// States the request's bound on a result and, by the same rule, on each alternative +/// (OPTIMALITY-GAP.md § 1.3). +/// +/// Attainment is the only route to `optimal`: a complete result whose score meets the bound +/// on every position is proven, and nothing else is, so a status a registry-provided solver +/// set without that proof is not carried through. A result the bound does not speak for +/// (§ 1.5) keeps the fact derived from its status alone. `O(1)` per result. +fn state_optimality(result: &mut PackingResult, bound: Option<&[i128]>) { + for alternative in &mut result.alternatives { + state_optimality(alternative, bound); + } + if result.status == PackingStatus::Optimal { + result.status = PackingStatus::Feasible; + } + if matches!( + result.status, + PackingStatus::Infeasible | PackingStatus::InvalidResult + ) { + return; + } + let Some(statement) = bound.and_then(|bound| bounds::statement(&result.score, bound)) else { + return; + }; + let complete = result.complete(); + if complete && statement.attained() { + result.status = PackingStatus::Optimal; + } + let code = derive_result_facts(result.status, complete, false).2.code; + result.optimality = Some(ResultFact { + code, + attributes: statement.attributes(), + }); +} + /// Appends the warning to a result and, by the same rule, to each alternative. /// /// The default `minimum_support_ratio` of 0 is kept so that no packing answer changes; a diff --git a/src/bounds.rs b/src/bounds.rs index 24935d3..e0450d1 100644 --- a/src/bounds.rs +++ b/src/bounds.rs @@ -1,33 +1,38 @@ -//! Lower bounds on the objective vector. +//! Lower bounds on the objective vector, and what a result states against them +//!. //! //! The mathematics is fixed by `docs/OPTIMALITY-CERTIFICATES.md`. This is an independent //! implementation written from that document, not a transcription of the Python or PHP -//! ports, and `conformance/scene/objective-bounds.json` holds all three to the same vectors -//! on 380 cases drawn from the golden corpus. +//! ports, and `conformance/scene/objective-bounds.json` holds all of them to the same vectors +//! on the cases drawn from the golden corpus and on the edges of the one refusal predicate. //! -//! asks only for soundness here -- the bound must never exceed the achieved -//! objective -- because Rust and JavaScript are not held to placement equality. That -//! distinction does not apply to a bound: it is a function of the *request*, so there is no -//! room for a legitimately different answer, and this port is held to equality because -//! equality is both achievable and strictly stronger. +//! A bound is a function of the *request*, so there is no room for a legitimately different +//! answer between engines, even though Rust and JavaScript are not held to placement +//! equality: this port is held to equality because equality is both achievable and strictly +//! stronger than soundness. //! //! ## Arithmetic //! //! `i128` throughout, and it is not close. A one-metre cube is 4.1e21 cubic ticks, a full //! container load a few orders above that, and the widest intermediate here multiplies a -//! summed volume by 1e6 -- call it 1e28 against an `i128` ceiling of 1.7e38. PHP needs -//! decimal strings for the same quantities and JavaScript needs `BigInt`; this port needs -//! neither, so there is no second arithmetic path to keep in step. +//! summed volume by 1e6 -- at most 1e36 once the declared ceiling has admitted the sums, +//! against an `i128` ceiling of 1.7e38. PHP needs decimal strings for the same quantities +//! and JavaScript needs `BigInt`; this port needs neither. //! //! ## Complexity //! -//! `O(n log n + c log c)` time and `O(n + c)` space for `n` quantity-expanded instances and -//! `c` container types: one sort of the volumes, one of the weights, one of the per-unit -//! costs. No geometry is touched and no candidate position is generated, which is why this -//! can be computed at the root of a search rather than inside it. +//! Volumes and weights are carried as runs -- each distinct value with how many instances +//! carry it -- formed per item type, so a quantity of a million costs one entry rather than a +//! million cloned instances. `O(t log t + c log c)` time and `O(t + c)` space for `t` item +//! types and `c` container types: one sort of the volume runs, one of the weight runs, one of +//! the container types by cost. With every quantity 1 that is the document's +//! `O(n log n + c log c)`. No geometry is touched and no candidate position is generated, +//! which is why it is computed once per pack, before any solver runs. use crate::geometry::ShapeType; -use crate::model::{Container, Item, ItemInstance}; +use crate::model::{Container, Item, ItemInstance, PackingRequest}; +use serde_json::Value; +use std::collections::BTreeMap; /// Parts per million, the scale keys 3 and 4 of the objective are carried at. pub const PPM: i128 = 1_000_000; @@ -61,24 +66,8 @@ impl std::fmt::Display for BoundOverflow { } } -/// Sum a slice, refusing past the ceiling instead of carrying it further. -/// -/// `checked_add` as well as the ceiling: a sum large enough to wrap `i128` is far past the -/// ceiling anyway, so both roads lead to the same refusal, and neither leads to a wrong -/// number. -fn checked_sum(values: &[i128], quantity: &str) -> Result { - let mut total: i128 = 0; - for value in values { - total = total - .checked_add(*value) - .ok_or_else(|| BoundOverflow(format!("{quantity} overflows the exact range")))?; - if total > MAX_BOUND_SUM { - return Err(BoundOverflow(format!( - "{quantity} sums past the {MAX_BOUND_SUM} ceiling the bound path declares" - ))); - } - } - Ok(total) +fn wrapped(quantity: &str) -> BoundOverflow { + BoundOverflow(format!("{quantity} overflows the exact range")) } fn guard(total: i128, quantity: &str) -> Result { @@ -147,6 +136,31 @@ pub struct ContainerType { pub cost_minor: i128, } +impl ContainerType { + fn of(container: &Container) -> Self { + let inner = container.inner_dimensions.volume(); + Self { + usable: inner - inner * container.void_fill_reserve_ppm / PPM, + inner, + base_area: container.inner_dimensions.base_area(), + height: i128::from(container.inner_dimensions.height.0), + payload: container.max_payload.map(|weight| i128::from(weight.0)), + max_items: container.max_items.map(|count| count as i128), + quantity: container.quantity.map(|count| count as i128), + cost_minor: i128::from(container.cost_minor), + } + } +} + +/// Values sorted ascending, each with how many instances carry it. +type Runs = Vec<(i128, i128)>; + +fn runs(pairs: impl Iterator) -> Runs { + let mut runs: Runs = pairs.filter(|&(_, count)| count > 0).collect(); + runs.sort_unstable(); + runs +} + /// Can this item take up less room than its declared dimensions? /// /// Three ways, and each breaks the same argument -- that nominal volumes sum to something a @@ -165,7 +179,56 @@ pub fn occupies_less_than_its_box(item: &Item) -> bool { ) } -/// Every bound for one request, from the engine's own objects. +/// Where each covered objective reads the five bounds: the position in the default-order +/// vector of each of the objective's own score keys. Any other objective has no bound. +fn objective_order(objective: &str) -> Option<[usize; 5]> { + match objective { + "default" => Some([0, 1, 2, 3, 4]), + "lowest_cost" => Some([0, 2, 1, 3, 4]), + _ => None, + } +} + +/// The request's bound in its objective's own score order, or `None` where none is stated. +/// +/// Over every instance the request declares, fixed placements included (they are part of +/// their item's quantity), and every container type. `None` for an objective with no bound, +/// for a request with a `made_to_measure` container (D13: the unused-volume key would +/// be taken from the machine maximum while the score uses the fabricated box), and for a +/// request past a declared ceiling, which withholds the bound and nothing else +/// (OPTIMALITY-GAP.md § 1.5). Computed from the request alone, independently of the solver +/// and deadline; emission also checks the result's score and the portable gap ceiling. +pub fn for_request(request: &PackingRequest) -> Option> { + let order = objective_order(&request.config.objective)?; + if request + .containers + .iter() + .any(|container| container.made_to_measure.is_some()) + { + return None; + } + let vector = from_items(&request.items, &request.containers) + .ok()? + .as_vector(); + Some(order.iter().map(|&position| vector[position]).collect()) +} + +/// Every bound for one request, from its item types and container types. +pub fn from_items(items: &[Item], containers: &[Container]) -> Result { + let counted = || { + items + .iter() + .map(|item| (item, item.quantity as i128)) + .filter(|&(_, count)| count > 0) + }; + let volumes = runs(counted().map(|(item, count)| (item.dimensions.volume(), count))); + let weights = runs(counted().map(|(item, count)| (i128::from(item.weight.0), count))); + let shrinks = counted().any(|(item, _)| occupies_less_than_its_box(item)); + let types: Vec = containers.iter().map(ContainerType::of).collect(); + from_runs(&volumes, &weights, shrinks, &types) +} + +/// Every bound for one request, from the engine's own instances. pub fn compute( instances: &[ItemInstance], containers: &[Container], @@ -178,22 +241,7 @@ pub fn compute( shrinks: occupies_less_than_its_box(&instance.item), }) .collect(); - let types: Vec = containers - .iter() - .map(|container| { - let inner = container.inner_dimensions.volume(); - ContainerType { - usable: inner - inner * container.void_fill_reserve_ppm / PPM, - inner, - base_area: container.inner_dimensions.base_area(), - height: i128::from(container.inner_dimensions.height.0), - payload: container.max_payload.map(|weight| i128::from(weight.0)), - max_items: container.max_items.map(|count| count as i128), - quantity: container.quantity.map(|count| count as i128), - cost_minor: i128::from(container.cost_minor), - } - }) - .collect(); + let types: Vec = containers.iter().map(ContainerType::of).collect(); from_reduced(&reduced, &types) } @@ -208,31 +256,46 @@ pub fn from_reduced( instances: &[Instance], containers: &[ContainerType], ) -> Result { - let mut volumes: Vec = instances.iter().map(|i| i.volume).collect(); - let mut weights: Vec = instances.iter().map(|i| i.weight).collect(); - volumes.sort_unstable(); - weights.sort_unstable(); - let shrinks = instances.iter().any(|i| i.shrinks); - let count = instances.len() as i128; - - // The a-priori check, once, on the way in. Every later product is bounded by these totals - // times `PPM`, so guarding them here is what makes the rest of the arithmetic safe by - // derivation rather than by hoping each step stays small. - checked_sum(&volumes, "instance volume")?; - checked_sum(&weights, "instance weight")?; - for container in containers { - guard(container.usable, "container capacity")?; - guard(container.cost_minor, "opening cost")?; - } + let volumes = runs(instances.iter().map(|instance| (instance.volume, 1))); + let weights = runs(instances.iter().map(|instance| (instance.weight, 1))); + let shrinks = instances.iter().any(|instance| instance.shrinks); + from_runs(&volumes, &weights, shrinks, containers) +} + +/// The one refusal predicate of docs/OPTIMALITY-CERTIFICATES.md, then the five formulas. +/// +/// Refused exactly where a sum the formulas form passes `MAX_BOUND_SUM` -- the instance +/// volumes, the instance weights, and each *finite* capacity total -- or a bound passes +/// `MAX_BOUND_VALUE`. An unbounded capacity total is never formed, so it is never guarded, +/// and nothing the formulas never compute (a single type's capacity, a cost no selection +/// reaches) is refused (finding F4). Every later product is bounded by the guarded totals +/// times `PPM`, which is what makes the rest of the arithmetic safe by derivation. +fn from_runs( + volumes: &[(i128, i128)], + weights: &[(i128, i128)], + shrinks: bool, + containers: &[ContainerType], +) -> Result { + guard(run_total(volumes, "instance volume")?, "instance volume")?; + guard(run_total(weights, "instance weight")?, "instance weight")?; + let volume_capacity = capacity_total(containers, |c| Some(c.usable))?; + let payload_capacity = capacity_total(containers, |c| c.payload)?; + let slot_capacity = capacity_total(containers, |c| c.max_items)?; + let count: i128 = volumes.iter().map(|&(_, run)| run).sum(); - let unpacked = unpacked_bound(&volumes, &weights, shrinks, count, containers)?; - let placed = count - unpacked; - let opened = container_bound(&volumes, &weights, shrinks, placed, containers); + let mut placeable = count; + if !shrinks { + placeable = placeable.min(fit(volumes, volume_capacity)); + } + placeable = placeable.min(fit(weights, payload_capacity)); + if let Some(slots) = slot_capacity { + placeable = placeable.min(slots); + } + let unpacked = count - placeable; + let opened = container_bound(volumes, weights, shrinks, placeable, containers); let cost = cost_bound(containers, opened)?; - let unused = unused_volume_bound(&volumes, shrinks, placed, containers, opened); - let height = stack_height_bound(&volumes, shrinks, placed, containers, opened); - guard(unused, "unused volume")?; - guard(height, "stack height")?; + let unused = unused_volume_bound(volumes, shrinks, placeable, containers, opened); + let height = stack_height_bound(volumes, shrinks, placeable, containers, opened); Ok(Bounds { unpacked_count: guard_output(unpacked, "unpacked count")?, container_count: guard_output(opened, "container count")?, @@ -242,35 +305,50 @@ pub fn from_reduced( }) } -/// `L0`: remove the geometry entirely and ask what the declared resources alone forbid. -/// -/// With two resources the minimum over each separately is a genuine relaxation and can fall -/// below the true two-resource optimum; it remains a bound, which is all that is claimed. -fn unpacked_bound( - volumes: &[i128], - weights: &[i128], - shrinks: bool, - count: i128, +/// `Σ value · count` over the runs, refusing a product or sum that would wrap `i128`; a sum +/// that large is far past the ceiling anyway, so both roads lead to the same refusal. +fn run_total(runs: &[(i128, i128)], quantity: &str) -> Result { + runs.iter().try_fold(0i128, |total, &(value, count)| { + value + .checked_mul(count) + .and_then(|product| total.checked_add(product)) + .ok_or_else(|| wrapped(quantity)) + }) +} + +/// `Σc limit · quantity`, guarded, or `None` when the total is unbounded: some type declares +/// no limit, or an unlimited quantity of a type whose limit is positive. A type that holds +/// nothing adds nothing however many of it there are. Unboundedness is decided before +/// anything is summed, so whether a request is refused never depends on type order. +fn capacity_total( containers: &[ContainerType], -) -> Result { - let mut placeable = count; - if !shrinks { - let capacity = volume_capacity(containers)?; - placeable = placeable.min(fit(volumes, capacity)); + limit: fn(&ContainerType) -> Option, +) -> Result, BoundOverflow> { + let unbounded = containers.iter().any(|container| match limit(container) { + None => true, + Some(value) => container.quantity.is_none() && value > 0, + }); + if unbounded { + return Ok(None); } - let payload = native_capacity(containers, |c| c.payload)?; - placeable = placeable.min(fit(weights, payload)); - if let Some(slots) = native_capacity(containers, |c| c.max_items)? { - placeable = placeable.min(slots); + let mut total: i128 = 0; + for container in containers { + let (Some(value), Some(quantity)) = (limit(container), container.quantity) else { + continue; + }; + total = value + .checked_mul(quantity) + .and_then(|product| total.checked_add(product)) + .ok_or_else(|| wrapped("container capacity"))?; } - Ok(count - placeable) + guard(total, "container capacity").map(Some) } /// `L1`: grant every container the largest capacity available, which can only understate how /// many are needed. fn container_bound( - volumes: &[i128], - weights: &[i128], + volumes: &[(i128, i128)], + weights: &[(i128, i128)], shrinks: bool, placed: i128, containers: &[ContainerType], @@ -278,18 +356,17 @@ fn container_bound( if placed <= 0 || containers.is_empty() { return 0; } - let taken = placed as usize; let mut bound: i128 = 1; if !shrinks { let largest = containers.iter().map(|c| c.usable).max().unwrap_or(0); if largest > 0 { - bound = bound.max(ceil_div(volumes[..taken].iter().sum::(), largest)); + bound = bound.max(ceil_div(smallest(volumes, placed), largest)); } } if let Some(largest) = finite_max(containers, |c| c.payload) && largest > 0 { - bound = bound.max(ceil_div(weights[..taken].iter().sum::(), largest)); + bound = bound.max(ceil_div(smallest(weights, placed), largest)); } if let Some(largest) = finite_max(containers, |c| c.max_items) && largest > 0 @@ -302,25 +379,30 @@ fn container_bound( /// `L2`: at least `L1` containers open, each costing at least the cheapest the inventory /// still holds. /// -/// Inventory is respected rather than assumed unlimited. Charging the cheapest type `L1` -/// times would also be a bound, and a weaker one whenever that type is nearly exhausted; the -/// difference costs one sort. +/// The types are sorted by cost once and taken greedily, `min(quantity, still needed)` of +/// each, which is the sum of the `L1` cheapest entries of the per-unit multiset without +/// building it: `O(c log c)` rather than the `O(c · L1 log(c · L1))` of materialising up to +/// `L1` copies of every type and sorting those (finding F6). fn cost_bound(containers: &[ContainerType], opened: i128) -> Result { - if opened <= 0 { - return Ok(0); - } - let mut available: Vec = Vec::new(); - for container in containers { - let repeat = container.quantity.unwrap_or(opened).min(opened); - for _ in 0..repeat.max(0) { - available.push(container.cost_minor); + let mut by_cost: Vec<&ContainerType> = containers.iter().collect(); + by_cost.sort_unstable_by_key(|container| container.cost_minor); + let mut needed = opened; + let mut total: i128 = 0; + for container in by_cost { + if needed <= 0 { + break; } + let taken = container + .quantity + .map_or(needed, |quantity| quantity.min(needed)); + total = container + .cost_minor + .checked_mul(taken) + .and_then(|product| total.checked_add(product)) + .ok_or_else(|| wrapped("opening cost"))?; + needed -= taken; } - available.sort_unstable(); - checked_sum( - &available[..(opened as usize).min(available.len())], - "opening cost", - ) + guard(total, "opening cost") } /// `L3`: the fill is largest when every container is the smallest available and holds the @@ -330,7 +412,7 @@ fn cost_bound(containers: &[ContainerType], opened: i128) -> Result 0 { - volumes[volumes.len() - placed as usize..] - .iter() - .sum::() - } else { - 0 - }; - (opened * PPM - ceil_div(largest_placed * PPM, smallest) - (opened - 1)).max(0) + let filled = ceil_div(largest(volumes, placed) * PPM, smallest_inner); + (opened * PPM - filled - (opened - 1)).max(0) } /// `L4`: the volume that must be placed has to stand at least as tall as itself spread across @@ -360,7 +436,7 @@ fn unused_volume_bound( /// floor of a sum, not a cautionary fudge: the objective floors each container's ratio before /// summing. fn stack_height_bound( - volumes: &[i128], + volumes: &[(i128, i128)], shrinks: bool, placed: i128, containers: &[ContainerType], @@ -374,65 +450,10 @@ fn stack_height_bound( if widest <= 0 || tallest <= 0 { return 0; } - let required = if placed > 0 { - ceil_div(volumes[..placed as usize].iter().sum::(), widest) - } else { - 0 - }; + let required = ceil_div(smallest(volumes, placed), widest); (required * PPM / tallest - (opened - 1)).max(0) } -/// `Sum of usable * quantity`, or `None` for an unbounded total. -/// -/// A container with no usable volume adds nothing however many of it there are, which is why -/// an unlimited quantity only unbounds the total when the type actually holds something. -fn volume_capacity(containers: &[ContainerType]) -> Result, BoundOverflow> { - let mut total = 0; - for container in containers { - match container.quantity { - None => { - if container.usable > 0 { - return Ok(None); - } - } - Some(quantity) => { - let contribution = container.usable.checked_mul(quantity).ok_or_else(|| { - BoundOverflow("container capacity overflows the exact range".into()) - })?; - total = checked_sum(&[total, contribution], "container capacity")?; - } - } - } - Ok(Some(total)) -} - -/// `Sum of limit * quantity`, or `None` when any limit or inventory is undeclared. -fn native_capacity( - containers: &[ContainerType], - limit: fn(&ContainerType) -> Option, -) -> Result, BoundOverflow> { - let mut total = 0; - for container in containers { - let Some(value) = limit(container) else { - return Ok(None); - }; - match container.quantity { - None => { - if value > 0 { - return Ok(None); - } - } - Some(quantity) => { - let contribution = value.checked_mul(quantity).ok_or_else(|| { - BoundOverflow("container capacity overflows the exact range".into()) - })?; - total = checked_sum(&[total, contribution], "container capacity")?; - } - } - } - Ok(Some(total)) -} - /// The largest declared limit, or `None` if any type declares none. /// /// One unlimited type makes the maximum unbounded and every term conditioned on it vacuous, @@ -449,33 +470,130 @@ fn finite_max( best } -/// The largest `n` such that the `n` smallest values sum to at most `capacity`. +/// The largest `n` such that the `n` smallest values sum to at most `capacity`; all of them +/// when the capacity is unbounded. /// /// Smallest first, and that is the whole soundness argument: taking the cheapest units /// maximises how many fit under one capacity, so this over-estimates what any real packing /// achieves. Geometry, support ratios, stacking rules, incompatible tags and route order can /// each make the real answer worse and none of them can make it better. -/// -/// The caller passes an already-ascending slice; sorting again here would double the only -/// superlinear work this module does. -fn fit(ascending: &[i128], capacity: Option) -> i128 { +fn fit(ascending: &[(i128, i128)], capacity: Option) -> i128 { + let total: i128 = ascending.iter().map(|&(_, count)| count).sum(); let Some(capacity) = capacity else { - return ascending.len() as i128; + return total; }; - let mut used = 0; - for (taken, value) in ascending.iter().enumerate() { - used += value; - if used > capacity { - return taken as i128; + let (mut taken, mut used) = (0i128, 0i128); + for &(value, count) in ascending { + let room = if value == 0 { + count + } else { + count.min((capacity - used).max(0) / value) + }; + taken += room; + used += value * room; + if room < count { + break; } } - ascending.len() as i128 + taken +} + +/// The sum of the `count` smallest values. +fn smallest(ascending: &[(i128, i128)], count: i128) -> i128 { + take(ascending.iter(), count) +} + +/// The sum of the `count` largest values. +fn largest(ascending: &[(i128, i128)], count: i128) -> i128 { + take(ascending.iter().rev(), count) +} + +fn take<'a>(runs: impl Iterator, mut count: i128) -> i128 { + let mut total = 0; + for &(value, available) in runs { + if count <= 0 { + break; + } + let taken = available.min(count); + total += value * taken; + count -= taken; + } + total } fn ceil_div(numerator: i128, denominator: i128) -> i128 { (numerator + denominator - 1) / denominator } +/// What one result states against its request's bound (OPTIMALITY-GAP.md § 1.1). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Statement { + /// The bound through the first missed position, or all of it when nothing is missed. + pub lower_bound: Vec, + /// The first missed position and `score[k] - bound[k]` there; `None` when attained. + pub gap: Option<(usize, i128)>, +} + +impl Statement { + /// Every position attained: with nothing unpacked, a proof of optimality. + pub fn attained(&self) -> bool { + self.gap.is_none() + } + + /// The result's `optimality` attributes, beside its `code`. `relative_gap` is unreduced, + /// so the pair reads as `(score - bound, bound)` by eye, and absent when the bound on the + /// missed position is zero. + pub fn attributes(&self) -> BTreeMap { + let mut attributes = BTreeMap::new(); + attributes.insert( + "lower_bound".into(), + Value::Array(self.lower_bound.iter().map(|&value| exact(value)).collect()), + ); + if let Some((key, absolute)) = self.gap { + attributes.insert("gap_key".into(), Value::from(key)); + attributes.insert("absolute_gap".into(), exact(absolute)); + let least = self.lower_bound[key]; + if least > 0 { + attributes.insert( + "relative_gap".into(), + serde_json::json!({"numerator": exact(absolute), "denominator": exact(least)}), + ); + } + } + attributes + } +} + +/// A bound value as a JSON integer. Every one is inside `MAX_BOUND_VALUE` by the output +/// guard, and every gap is at most its score component. +fn exact(value: i128) -> Value { + Value::from(i64::try_from(value).unwrap_or(i64::MAX)) +} + +/// The statement one score makes against `bound`, both in the result's own score order, or +/// `None` where a score below its bound shows the bound wrong: an engine must not publish a +/// claim it has just refuted (OPTIMALITY-GAP.md § 1.5). At most five comparisons, `O(1)`. +pub fn statement(score: &[i128], bound: &[i128]) -> Option { + for (index, (&achieved, &least)) in score.iter().zip(bound).enumerate() { + if achieved < least { + return None; + } + if achieved > least { + if achieved - least > MAX_BOUND_VALUE { + return None; + } + return Some(Statement { + lower_bound: bound[..=index].to_vec(), + gap: Some((index, achieved - least)), + }); + } + } + Some(Statement { + lower_bound: bound.to_vec(), + gap: None, + }) +} + #[cfg(test)] mod tests { use super::*; @@ -507,43 +625,7 @@ mod tests { ); for case in cases { - let instances: Vec = case["instances"] - .as_array() - .expect("instances") - .iter() - .map(|raw| Instance { - volume: raw["volume"] - .as_str() - .expect("decimal volume") - .parse() - .unwrap(), - weight: raw["weight"].as_i64().expect("weight ticks").into(), - shrinks: raw["shrinks"].as_bool().expect("shrink flag"), - }) - .collect(); - let containers: Vec = case["containers"] - .as_array() - .expect("containers") - .iter() - .map(|raw| ContainerType { - usable: raw["usable"] - .as_str() - .expect("decimal usable") - .parse() - .unwrap(), - inner: raw["inner"] - .as_str() - .expect("decimal inner") - .parse() - .unwrap(), - base_area: raw["base_area"].as_i64().expect("base area").into(), - height: raw["height"].as_i64().expect("height").into(), - payload: raw["payload"].as_i64().map(i128::from), - max_items: raw["max_items"].as_i64().map(i128::from), - quantity: raw["quantity"].as_i64().map(i128::from), - cost_minor: raw["cost_minor"].as_i64().expect("cost").into(), - }) - .collect(); + let (instances, containers) = scene_inputs(case); let expected: Vec = case["bounds"] .as_array() .expect("bounds") @@ -560,6 +642,130 @@ mod tests { case["fixture"] ); } + + // The edges are written from the oracle: the fixed-placement rule and every edge of + // the one refusal predicate, where `null` means this port must refuse too (F4). + let edges = document["edges"].as_array().expect("scene edges"); + assert!( + !edges.is_empty(), + "the refusal predicate's edges are not optional" + ); + for edge in edges { + let (instances, containers) = scene_inputs(edge); + let computed = from_reduced(&instances, &containers).map(|b| b.as_vector().to_vec()); + let expected = edge["bounds"].as_array().map(|values| { + values + .iter() + .map(|value| i128::from(value.as_i64().expect("integer bound"))) + .collect::>() + }); + assert_eq!(computed.ok(), expected, "edge {:?}", edge["name"]); + } + } + + fn decimal(value: &serde_json::Value) -> i128 { + value + .as_str() + .expect("a decimal string") + .parse() + .expect("an integer") + } + + fn scene_inputs(case: &serde_json::Value) -> (Vec, Vec) { + let instances = case["instances"] + .as_array() + .expect("instances") + .iter() + .map(|raw| Instance { + volume: decimal(&raw["volume"]), + weight: raw["weight"].as_i64().expect("weight ticks").into(), + shrinks: raw["shrinks"].as_bool().expect("shrink flag"), + }) + .collect(); + let containers = case["containers"] + .as_array() + .expect("containers") + .iter() + .map(|raw| ContainerType { + usable: decimal(&raw["usable"]), + inner: decimal(&raw["inner"]), + base_area: raw["base_area"].as_i64().expect("base area").into(), + height: raw["height"].as_i64().expect("height").into(), + payload: raw["payload"].as_i64().map(i128::from), + max_items: raw["max_items"].as_i64().map(i128::from), + quantity: raw["quantity"].as_i64().map(i128::from), + cost_minor: raw["cost_minor"].as_i64().expect("cost").into(), + }) + .collect(); + (instances, containers) + } + + /// The statement a result makes: a prefix through the first miss, an unreduced relative + /// gap that is absent on a zero bound, and nothing at all for a score below its bound. + #[test] + fn a_statement_stops_at_the_first_missed_position() { + let bound = [0, 2, 10, 500, 7]; + let attained = statement(&bound, &bound).expect("attained"); + assert!(attained.attained()); + assert_eq!( + attained.attributes().keys().collect::>(), + ["lower_bound"] + ); + + let missed = statement(&[0, 2, 14, 0, 0], &bound).expect("missed on key 2"); + assert_eq!(missed.lower_bound, vec![0, 2, 10]); + assert_eq!(missed.gap, Some((2, 4))); + assert_eq!( + missed.attributes()["relative_gap"], + serde_json::json!({"numerator": 4, "denominator": 10}) + ); + + let from_zero = statement(&[1, 0, 0, 0, 0], &bound).expect("missed on key 0"); + assert_eq!(from_zero.gap, Some((0, 1))); + assert!(!from_zero.attributes().contains_key("relative_gap")); + + assert_eq!(statement(&[0, 1, 99, 0, 0], &bound), None); + } + + /// The request-level entry point: `lowest_cost` reads the permuted vector, an uncovered + /// objective and a made-to-measure container read none. + #[test] + fn a_request_states_its_bound_in_its_objective_order() { + use crate::geometry::Dimensions; + use crate::units::Length; + let item = Item::new( + "a", + Dimensions { + length: Length(10), + width: Length(10), + height: Length(5), + }, + crate::units::Weight(0), + 1, + ); + let mut request = PackingRequest { + items: vec![item], + containers: vec![Container::new( + "box", + Dimensions { + length: Length(10), + width: Length(10), + height: Length(10), + }, + )], + config: Default::default(), + output_length_unit: "mm".into(), + output_weight_unit: "g".into(), + catalog_versions_used: Vec::new(), + fixed_placements: Vec::new(), + fixed_containers: Vec::new(), + }; + request.containers[0].cost_minor = 3; + assert_eq!(for_request(&request), Some(vec![0, 1, 3, 500_000, 500_000])); + request.config.objective = "lowest_cost".into(); + assert_eq!(for_request(&request), Some(vec![0, 3, 1, 500_000, 500_000])); + request.config.objective = "maximum_value".into(); + assert_eq!(for_request(&request), None); } /// The five cases the document works by hand. @@ -857,4 +1063,13 @@ mod tests { item.nesting_height = Some(Length(1)); assert!(occupies_less_than_its_box(&item)); } + #[test] + fn gap_ceiling_is_inclusive() { + for least in [0, 1] { + let bound = [0, 1, least, 0, 0]; + let statement = statement(&[0, 1, least + MAX_BOUND_VALUE, 0, 0], &bound).unwrap(); + assert_eq!(statement.gap, Some((2, MAX_BOUND_VALUE))); + assert!(super::statement(&[0, 1, least + MAX_BOUND_VALUE + 1, 0, 0], &bound).is_none()); + } + } } diff --git a/src/contact_graph.rs b/src/contact_graph.rs index 9ff5ec9..4fc1896 100644 --- a/src/contact_graph.rs +++ b/src/contact_graph.rs @@ -404,12 +404,26 @@ impl ContactGraph { } } -fn cells(box_: Aabb, cell: i64) -> BTreeSet<(i64, i64)> { +fn cells(box_: Aabb, cell: i64) -> impl Iterator { let x1 = box_.origin.x.div_euclid(cell); let y1 = box_.origin.y.div_euclid(cell); let x2 = box_.x2().saturating_sub(1).div_euclid(cell); let y2 = box_.y2().saturating_sub(1).div_euclid(cell); - BTreeSet::from([(x1, y1), (x2, y1), (x1, y2), (x2, y2)]) + let mut out = [(x1, y1); 4]; + let mut len = 1; + if x2 != x1 { + out[len] = (x2, y1); + len += 1; + } + if y2 != y1 { + out[len] = (x1, y2); + len += 1; + if x2 != x1 { + out[len] = (x2, y2); + len += 1; + } + } + out.into_iter().take(len) } #[cfg(test)] diff --git a/src/deadline.rs b/src/deadline.rs index 35a339e..5a37d57 100644 --- a/src/deadline.rs +++ b/src/deadline.rs @@ -1,4 +1,6 @@ +use crate::model::{PackingRequest, SolverMetrics, effort_exhausted}; use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; use web_time::Instant; /// Monotonic time source used by [`Deadline`]. @@ -29,11 +31,17 @@ impl Clock for SystemClock { } /// Monotonic search budget with an injectable clock. +/// +/// It also carries one start's effort-stop latch: a guard that finds the effort budget spent +/// while work remains refuses that work and records it, so the effort flag says the budget +/// stopped the search rather than that a counter equals its limit afterwards. Clones +/// share the latch; [`Deadline::for_start`] gives a start its own. #[derive(Clone)] pub struct Deadline { clock: Arc, started_ns: u64, limit_ns: u64, + effort_stop: Arc, } impl std::fmt::Debug for Deadline { @@ -57,9 +65,35 @@ impl Deadline { clock, started_ns, limit_ns: limit_ms.saturating_mul(1_000_000), + effort_stop: Arc::default(), + } + } + + /// The same clock and limit with a latch of its own, for one search start: parallel + /// starts share the clock but never each other's effort stop. + pub(crate) fn for_start(&self) -> Self { + Self { + effort_stop: Arc::default(), + ..self.clone() } } + /// Whether the effort budget stops the search here, recording that it did. Only a guard + /// about to do more counted work asks: asking is refusing that work. O(1); the latch is + /// written only when the guard fires, so the per-orientation check costs what it did. + pub(crate) fn effort_stops(&self, request: &PackingRequest, metrics: &SolverMetrics) -> bool { + if !effort_exhausted(request, metrics) { + return false; + } + self.effort_stop.store(true, Ordering::Relaxed); + true + } + + /// Whether a guard found the effort budget spent and stopped this start there. + pub(crate) fn effort_stopped(&self) -> bool { + self.effort_stop.load(Ordering::Relaxed) + } + pub fn expired(&self) -> bool { self.elapsed_ns() >= self.limit_ns } diff --git a/src/model.rs b/src/model.rs index 51a5311..f5087b6 100644 --- a/src/model.rs +++ b/src/model.rs @@ -1172,6 +1172,68 @@ pub fn axle_reactions( Some((denominator, front_numerator, rear_numerator)) } +#[derive(Clone, Copy)] +pub struct AxleBase { + total_weight: i128, + doubled_weighted_x: i128, + front_pos: i128, + rear_pos: i128, + front_max: Option, + rear_max: Option, +} + +impl AxleBase { + pub fn new(container: &Container, placements: &[Placement]) -> Option { + let [front, rear] = container.axles?; + let mut total_weight = container.tare_weight.0 as i128; + let mut doubled_weighted_x = (container.tare_weight.0 as i128) + .saturating_mul(container.inner_dimensions.length.0 as i128); + for placement in placements { + let weight = placement.instance.item.weight.0 as i128; + total_weight = total_weight.saturating_add(weight); + let centre = 2_i128 + .saturating_mul(placement.position.x as i128) + .saturating_add(placement.dimensions.length.0 as i128); + doubled_weighted_x = doubled_weighted_x.saturating_add(weight.saturating_mul(centre)); + } + let denominator = 2_i128.saturating_mul((rear.position.0 - front.position.0) as i128); + Some(Self { + total_weight, + doubled_weighted_x, + front_pos: front.position.0 as i128, + rear_pos: rear.position.0 as i128, + front_max: front + .max_load + .map(|limit| (limit.0 as i128).saturating_mul(denominator)), + rear_max: rear + .max_load + .map(|limit| (limit.0 as i128).saturating_mul(denominator)), + }) + } + + pub fn overloaded(&self, weight: Weight, box_: Aabb) -> bool { + let weight = weight.0 as i128; + let total_weight = self.total_weight.saturating_add(weight); + let centre = 2_i128 + .saturating_mul(box_.origin.x as i128) + .saturating_add(box_.dimensions.length.0 as i128); + let doubled_weighted_x = self + .doubled_weighted_x + .saturating_add(weight.saturating_mul(centre)); + let front_numerator = 2_i128 + .saturating_mul(total_weight) + .saturating_mul(self.rear_pos) + .saturating_sub(doubled_weighted_x); + let rear_numerator = doubled_weighted_x.saturating_sub( + 2_i128 + .saturating_mul(total_weight) + .saturating_mul(self.front_pos), + ); + self.front_max.is_some_and(|limit| front_numerator > limit) + || self.rear_max.is_some_and(|limit| rear_numerator > limit) + } +} + pub fn axle_overloaded( container: &Container, placements: &[Placement], @@ -1552,6 +1614,34 @@ pub fn effort_exhausted(request: &PackingRequest, metrics: &SolverMetrics) -> bo .unwrap_or(false) } +/// How many more placements, each one counted placement attempt and one feasible candidate, +/// the effort budget has room for: what a solver that counts a run of placements at once +/// may add without either counter passing its limit. O(1). +pub(crate) fn placement_room(request: &PackingRequest, metrics: &SolverMetrics) -> u64 { + let Some(budget) = request.config.effort_budget else { + return u64::MAX; + }; + headroom( + budget.max_placement_attempts, + metrics.orientations_considered, + ) + .min(headroom( + budget.max_candidates_evaluated, + metrics.feasible_candidates, + )) +} + +/// How many more search nodes the effort budget has room for. O(1). +pub(crate) fn node_room(request: &PackingRequest, metrics: &SolverMetrics) -> u64 { + request.config.effort_budget.map_or(u64::MAX, |budget| { + headroom(budget.max_search_nodes, metrics.search_nodes_expanded) + }) +} + +fn headroom(limit: Option, used: u64) -> u64 { + limit.map_or(u64::MAX, |limit| limit.saturating_sub(used)) +} + #[derive(Clone, Debug, Default)] pub struct AlgorithmReport { pub profile: String, diff --git a/src/rebalance.rs b/src/rebalance.rs index 949518c..d3c92c0 100644 --- a/src/rebalance.rs +++ b/src/rebalance.rs @@ -111,6 +111,9 @@ fn attempt_move( z: moving.position.z - moving.envelope_origin.z, }; + let mut source_placements = source.placements.clone(); + source_placements.remove(placement_index); + let refreshed_source = refreshed_top_loads(source_placements); for point in candidate_points(destination) { let mut relocated = moving.clone(); relocated.envelope_origin = point; @@ -123,17 +126,15 @@ fn attempt_move( relocated.top_load = Weight(0); let mut trial = containers.to_vec(); - let mut source_placements = source.placements.clone(); - source_placements.remove(placement_index); - trial[source_index].placements = refreshed_top_loads(source_placements); + trial[source_index].placements = refreshed_source.clone(); let mut destination_placements = destination.placements.clone(); destination_placements.push(relocated); trial[destination_index].placements = refreshed_top_loads(destination_placements); let mut trial_result = original.clone(); - trial_result.containers = trial.clone(); + trial_result.containers = trial; if IndependentValidator.validate(request, &trial_result).valid { - return Some(trial); + return Some(trial_result.containers); } } None diff --git a/src/request_errors.rs b/src/request_errors.rs index a6780c5..f7964d4 100644 --- a/src/request_errors.rs +++ b/src/request_errors.rs @@ -84,6 +84,8 @@ const CONFIGURATION_FIELDS: [&str; 20] = [ "time_limit_ms", ]; const SIDES: [&str; 3] = ["length", "width", "height"]; +/// 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"]; /// Refuse the request with its first violation, or return the request's length unit. @@ -182,6 +184,7 @@ fn check_configuration(raw: Option<&Value>, unit: &str) -> Checked { optional(configuration, "clearance", at, |value, field| { measure(value, field, MeasureKind::Length, unit) })?; + optional(configuration, "require_placement_coordinates", at, boolean)?; let Some(effort) = present(configuration.get("effort_budget")) else { return Ok(()); }; @@ -245,7 +248,20 @@ fn check_item(raw: &Value, at: &str, unit: &str) -> Checked { })?; optional(item, "shape_type", at, |value, field| { one_of(value, field, &SHAPE_TYPES) - }) + })?; + for name in ITEM_BOOLEANS { + optional(item, name, at, boolean)?; + } + Ok(()) +} + +/// Only JSON `true`/`false`: reading anything else as its default would pack `"no"` as if +/// the field were absent. O(1). +fn boolean(value: &Value, field: &str) -> Checked { + if value.is_boolean() { + return Ok(()); + } + Err(wrong_type(field, "must be a boolean")) } /// A nested copy sinks by less than its own height, or it would vanish into the one below diff --git a/src/result_validation/bound.rs b/src/result_validation/bound.rs new file mode 100644 index 0000000..ae8f90a --- /dev/null +++ b/src/result_validation/bound.rs @@ -0,0 +1,888 @@ +//! The optimality bound and gap of docs/OPTIMALITY-GAP.md § 6.2, recomputed from the request +//!: `optimality.lower_bound` is the recomputed prefix, the gap agrees with it and the +//! score, no score falls below it, and `optimal` / `proven_optimal` are claimed only by +//! attainment. +//! +//! The reference's own copy of docs/OPTIMALITY-CERTIFICATES.md's formulas and its one refusal +//! predicate, sharing nothing with [`crate::bounds`], which is what it checks. The guarded sums +//! saturate rather than overflow, so a request past `i128` is refused exactly as the reference +//! refuses one past `10^30`; below the ceilings every product stays under `10^36`. O(t log t + +//! c log c) for `t` item types and `c` container types, O(t + c) memory, once per result. + +use super::Issue; +use super::container::{SCORE_SCALE, ratio_ppm}; +use super::json::{Json, Ordered, Res}; +use super::num::{add, ceil_div, floor_div, mul, py_mod, sub}; +use super::pyfmt::{int_list, py_repr}; +use super::spec::{ContainerSpec, ItemSpec}; + +const MAX_BOUND_SUM: i128 = 1_000_000_000_000_000_000_000_000_000_000; +const MAX_BOUND_VALUE: i128 = 9_007_199_254_740_991; +const GAP_FIELDS: [&str; 3] = ["gap_key", "absolute_gap", "relative_gap"]; + +/// `(value, count)` pairs sorted by value: one per item type, however large its quantity. +pub(crate) type Runs = Vec<(i128, i128)>; + +/// One container type as the bound reads it, `None` wherever the request sets no limit. +#[derive(Clone, Debug)] +pub(crate) struct BoundContainer { + pub(crate) inner_volume: i128, + pub(crate) base_area: i128, + pub(crate) height: i128, + pub(crate) usable: i128, + pub(crate) cost_minor: i128, + pub(crate) payload: Option, + pub(crate) max_items: Option, + pub(crate) quantity: Option, +} + +/// Where each covered objective reads `(L0, L1, L2, L3, L4)` in its own score order. +fn order_of(objective: &Json) -> Option<[usize; 5]> { + match objective { + Json::Str(name) if name == "default" => Some([0, 1, 2, 3, 4]), + Json::Str(name) if name == "lowest_cost" => Some([0, 2, 1, 3, 4]), + _ => None, + } +} + +fn run_count(runs: &[(i128, i128)]) -> i128 { + runs.iter() + .fold(0, |total, (_, count)| total.saturating_add(*count)) +} + +fn run_sum(runs: &[(i128, i128)]) -> i128 { + runs.iter().fold(0, |total, (value, count)| { + total.saturating_add(value.saturating_mul(*count)) + }) +} + +/// `Σ value × quantity`, or `None` when unbounded; a type that holds nothing adds 0. Saturates. +fn capacity_total(values: &[Option], quantities: &[Option]) -> Option { + let mut total: i128 = 0; + for (value, quantity) in values.iter().zip(quantities) { + let value = (*value)?; + match quantity { + None if value > 0 => return None, + None => {} + Some(quantity) => total = total.saturating_add(value.saturating_mul(*quantity)), + } + } + Some(total) +} + +/// How many of the smallest values sum to at most `capacity`; all of them when unlimited. +fn fit(runs: &[(i128, i128)], capacity: Option) -> Res { + let Some(capacity) = capacity else { + return Ok(run_count(runs)); + }; + if capacity < 0 { + return Ok(0); + } + let (mut taken, mut used) = (0, 0); + for &(value, count) in runs { + let room = if value == 0 { + count + } else { + count.min(floor_div(sub(capacity, used)?, value)?) + }; + taken = add(taken, room)?; + used = add(used, mul(value, room)?)?; + if room < count { + break; + } + } + Ok(taken) +} + +/// The sum of the `count` smallest values of `runs`, walked in the order given. +fn smallest<'a, I: IntoIterator>(runs: I, mut count: i128) -> Res { + let mut total = 0; + for &(value, available) in runs { + if count <= 0 { + break; + } + let taken = available.min(count); + total = add(total, mul(value, taken)?)?; + count -= taken; + } + Ok(total) +} + +/// `L1`, given `L0`. +fn container_bound( + volumes: &[(i128, i128)], + weights: &[(i128, i128)], + shrinks: bool, + placed: i128, + containers: &[BoundContainer], +) -> Res { + if placed <= 0 || containers.is_empty() { + return Ok(0); + } + let mut bound = 1; + let largest_volume = containers.iter().map(|c| c.usable).max().unwrap_or(0); + if !shrinks && largest_volume > 0 { + bound = bound.max(ceil_div(smallest(volumes, placed)?, largest_volume)?); + } + let payloads: Option> = containers.iter().map(|c| c.payload).collect(); + if let Some(largest_payload) = payloads.and_then(|values| values.into_iter().max()) + && largest_payload > 0 + { + bound = bound.max(ceil_div(smallest(weights, placed)?, largest_payload)?); + } + let slots: Option> = containers.iter().map(|c| c.max_items).collect(); + if let Some(largest_slots) = slots.and_then(|values| values.into_iter().max()) + && largest_slots > 0 + { + bound = bound.max(ceil_div(placed, largest_slots)?); + } + Ok(bound) +} + +/// `L2`: the `opened` cheapest containers the inventory holds, greedily by cost. Saturates, so +/// a total past `i128` is past the result ceiling, as the reference finds it. +fn cost_bound(containers: &[BoundContainer], mut opened: i128) -> i128 { + let mut by_cost: Vec<&BoundContainer> = containers.iter().collect(); + by_cost.sort_by_key(|container| container.cost_minor); + let mut total: i128 = 0; + for container in by_cost { + if opened <= 0 { + break; + } + let taken = container + .quantity + .map_or(opened, |quantity| quantity.min(opened)); + total = total.saturating_add(container.cost_minor.saturating_mul(taken)); + opened -= taken; + } + total +} + +/// `L3`. +fn unused_bound( + volumes: &[(i128, i128)], + shrinks: bool, + placed: i128, + containers: &[BoundContainer], + opened: i128, +) -> Res { + let smallest_inner = containers + .iter() + .map(|c| c.inner_volume) + .filter(|volume| *volume > 0) + .min(); + let Some(smallest_inner) = smallest_inner else { + return Ok(0); + }; + if opened <= 0 || shrinks { + return Ok(0); + } + let largest = smallest(volumes.iter().rev(), placed)?; + let filled = ceil_div(mul(largest, SCORE_SCALE)?, smallest_inner)?; + Ok(sub(sub(mul(opened, SCORE_SCALE)?, filled)?, opened - 1)?.max(0)) +} + +/// `L4`. +fn height_bound( + volumes: &[(i128, i128)], + shrinks: bool, + placed: i128, + containers: &[BoundContainer], + opened: i128, +) -> Res { + let widest = containers + .iter() + .map(|c| c.base_area) + .filter(|a| *a > 0) + .max(); + let tallest = containers.iter().map(|c| c.height).filter(|h| *h > 0).max(); + let (Some(widest), Some(tallest)) = (widest, tallest) else { + return Ok(0); + }; + if opened <= 0 || shrinks { + return Ok(0); + } + let required = ceil_div(smallest(volumes, placed)?, widest)?; + Ok(sub(floor_div(mul(required, SCORE_SCALE)?, tallest)?, opened - 1)?.max(0)) +} + +/// `[L0, L1, L2, L3, L4]` of docs/OPTIMALITY-CERTIFICATES.md, or `None` where its one refusal +/// predicate withholds the bound. `volumes` and `weights` are runs sorted by value. +pub(crate) fn lower_bound( + volumes: &[(i128, i128)], + weights: &[(i128, i128)], + shrinks: bool, + containers: &[BoundContainer], +) -> Res> { + let quantities: Vec> = containers.iter().map(|c| c.quantity).collect(); + let column = |read: fn(&BoundContainer) -> Option| -> Vec> { + containers.iter().map(read).collect() + }; + let usable = capacity_total(&column(|c| Some(c.usable)), &quantities); + let payload = capacity_total(&column(|c| c.payload), &quantities); + let slots = capacity_total(&column(|c| c.max_items), &quantities); + let guarded = [ + Some(run_sum(volumes)), + Some(run_sum(weights)), + usable, + payload, + slots, + ]; + if guarded.iter().flatten().any(|total| *total > MAX_BOUND_SUM) { + return Ok(None); + } + let count = run_count(volumes); + let mut placeable = 0; + if !containers.is_empty() { + placeable = count; + if !shrinks { + placeable = placeable.min(fit(volumes, usable)?); + } + placeable = placeable.min(fit(weights, payload)?); + if let Some(slots) = slots { + placeable = placeable.min(slots); + } + } + let opened = container_bound(volumes, weights, shrinks, placeable, containers)?; + let bound = [ + count - placeable, + opened, + cost_bound(containers, opened), + unused_bound(volumes, shrinks, placeable, containers, opened)?, + height_bound(volumes, shrinks, placeable, containers, opened)?, + ]; + Ok(if bound.iter().any(|value| *value > MAX_BOUND_VALUE) { + None + } else { + Some(bound) + }) +} + +/// The bound's inputs: every instance, fixed ones included, and every declared container type. +type Inputs = (Runs, Runs, bool, Vec); + +fn inputs(items: &Ordered, containers: &Ordered) -> Res { + let mut volumes = Vec::new(); + let mut weights = Vec::new(); + let mut shrinks = false; + for spec in items.values() { + let quantity = spec.quantity.int("quantity")?; + let [length, width, height] = spec.dimensions; + volumes.push((mul(mul(length, width)?, height)?, quantity)); + weights.push((spec.weight, quantity)); + shrinks = shrinks + || (quantity > 0 + && (spec.nesting_height.is_some() + || spec.shape_type.is_str("convex_hull") + || spec.shape_type.is_str("compressible"))); + } + volumes.sort_by_key(|run| run.0); + weights.sort_by_key(|run| run.0); + let mut types = Vec::new(); + for spec in containers.values() { + let volume = spec.volume()?; + let scaled = ratio_ppm(spec.void_fill_reserve_ratio); + let reserved = add( + mul(floor_div(volume, SCORE_SCALE)?, scaled)?, + floor_div(mul(py_mod(volume, SCORE_SCALE)?, scaled)?, SCORE_SCALE)?, + )?; + types.push(BoundContainer { + inner_volume: volume, + base_area: mul(spec.inner[0], spec.inner[1])?, + height: spec.inner[2], + usable: sub(volume, reserved)?, + cost_minor: spec.cost_minor, + payload: spec.max_payload, + max_items: spec.max_items, + quantity: spec.quantity, + }); + } + Ok((volumes, weights, shrinks, types)) +} + +/// The bound in the objective's score order, or `None` with the reason none is stated (§ 1.5). +fn stated( + request: &Json, + status: &Json, + items: &Ordered, + containers: &Ordered, +) -> Res<(Option>, String)> { + let empty = Json::Dict(Vec::new()); + let default = Json::str_of("default"); + let name = request + .get_or("configuration", &empty)? + .get_or("objective", &default)?; + let Some(order) = order_of(name) else { + return Ok((None, format!("objective {} has no bound", py_repr(name)))); + }; + if containers + .values() + .any(|spec| spec.made_to_measure.is_some()) + { + return Ok((None, "a container is made to measure".to_owned())); + } + for withheld in ["infeasible", "invalid_result"] { + if status.is_str(withheld) { + return Ok((None, format!("status is '{withheld}'"))); + } + } + let (volumes, weights, shrinks, types) = inputs(items, containers)?; + Ok(match lower_bound(&volumes, &weights, shrinks, &types)? { + None => (None, "the request is past a declared ceiling".to_owned()), + Some(bound) => ( + Some(order.iter().map(|position| bound[*position]).collect()), + String::new(), + ), + }) +} + +/// The first position where `score` leaves `bound`, and whether it is above it. +fn departure(score: &[i128], bound: &[i128]) -> Option<(usize, bool)> { + score + .iter() + .zip(bound) + .position(|(achieved, floor)| achieved != floor) + .map(|index| (index, score[index] > bound[index])) +} + +/// `lower_bound` as counts when it is a list of 1 to 5 non-negative integers. +fn well_formed(emitted: &Json) -> Option> { + let Json::List(values) = emitted else { + return None; + }; + if values.is_empty() || values.len() > 5 { + return None; + } + values + .iter() + .map(|value| value.strict_int().filter(|count| *count >= 0)) + .collect() +} + +/// The three gap fields a correct result carries (§ 1.1), with the prefix length. +struct ExpectedGap { + length: usize, + gap_key: Option, + absolute_gap: Option, + relative_gap: Option<(i128, i128)>, +} + +fn expected_gap(score: &[i128], bound: &[i128], departure: Option<(usize, bool)>) -> ExpectedGap { + let Some((key, _)) = departure else { + return ExpectedGap { + length: bound.len(), + gap_key: None, + absolute_gap: None, + relative_gap: None, + }; + }; + let absolute = score[key] - bound[key]; + ExpectedGap { + length: key + 1, + gap_key: Some(key as i128), + absolute_gap: Some(absolute), + relative_gap: (bound[key] != 0).then_some((absolute, bound[key])), + } +} + +fn int_field_matches(actual: &Json, expected: Option) -> bool { + match expected { + None => actual.is_null(), + Some(value) => actual.strict_int() == Some(value), + } +} + +fn relative_matches(actual: &Json, expected: Option<(i128, i128)>) -> Res { + let Some((numerator, denominator)) = expected else { + return Ok(actual.is_null()); + }; + let Some(pairs) = actual.as_dict() else { + return Ok(false); + }; + Ok(pairs.len() == 2 + && actual.get_null("numerator")?.strict_int() == Some(numerator) + && actual.get_null("denominator")?.strict_int() == Some(denominator)) +} + +fn gap_text(expected: Option) -> String { + expected.map_or_else(|| "absent".to_owned(), |value| value.to_string()) +} + +fn check_reported( + emitted: &[i128], + score: &[i128], + bound: &[i128], + departure: Option<(usize, bool)>, + fact: &Json, + issues: &mut Vec, +) -> Res<()> { + let prefix = &bound[..emitted.len().min(bound.len())]; + if emitted != prefix { + issues.push(Issue::new( + "optimality_bound_mismatch", + format!( + "reported {}, recomputed {}", + int_list(emitted), + int_list(prefix) + ), + )); + } + let expected = expected_gap(score, bound, departure); + if emitted.len() != expected.length { + issues.push(Issue::new( + "optimality_gap_mismatch", + format!( + "lower_bound has {} entries, expected {}", + emitted.len(), + expected.length + ), + )); + } + let mut mismatch = |name: &str, text: String| { + issues.push(Issue::new( + "optimality_gap_mismatch", + format!("{name} should be {text}"), + )); + }; + if !int_field_matches(fact.get_null("gap_key")?, expected.gap_key) { + mismatch("gap_key", gap_text(expected.gap_key)); + } + if !int_field_matches(fact.get_null("absolute_gap")?, expected.absolute_gap) { + mismatch("absolute_gap", gap_text(expected.absolute_gap)); + } + if !relative_matches(fact.get_null("relative_gap")?, expected.relative_gap)? { + let text = expected.relative_gap.map_or_else( + || "absent".to_owned(), + |(numerator, denominator)| format!("{numerator}/{denominator}"), + ); + mismatch("relative_gap", text); + } + Ok(()) +} + +fn check_claims( + result: &Json, + fact: &Json, + attained: bool, + claims_attainment: bool, + issues: &mut Vec, +) -> Res<()> { + let status = result.at("status")?; + let complete = result.at("complete")?.truthy(); + if status.is_str("optimal") && !(complete && attained) { + issues.push(Issue::new( + "result_fact_mismatch", + "status 'optimal' requires a complete result that attains the recomputed lower bound" + .to_owned(), + )); + } + if status.is_str("feasible") && complete && claims_attainment { + issues.push(Issue::new( + "result_fact_mismatch", + "status is 'feasible', but the result attains its lower_bound; expected 'optimal'" + .to_owned(), + )); + } + if fact.get_null("code")?.is_str("proven_optimal") && !claims_attainment { + issues.push(Issue::new( + "unproven_optimality_claim", + "optimality.code is 'proven_optimal' without an attained lower_bound".to_owned(), + )); + } + Ok(()) +} + +/// The reference's `_check_optimality_bound`. Absence of the field is never an issue. +pub(crate) fn check_optimality_bound( + request: &Json, + result: &Json, + items: &Ordered, + containers: &Ordered, + score: &[i128], + issues: &mut Vec, +) -> Res<()> { + let fact = result.at("optimality")?; + let (bound, withheld) = stated(request, result.at("status")?, items, containers)?; + let departure = bound.as_deref().and_then(|bound| departure(score, bound)); + let below = matches!(departure, Some((_, false))); + if let (Some(bound), Some((key, false))) = (&bound, departure) { + issues.push(Issue::new( + "score_below_bound", + format!( + "score[{key}] is {}, below its lower bound {}", + score[key], bound[key] + ), + )); + } + let emitted = fact.get_null("lower_bound")?; + if !emitted.is_null() + && let (Some(bound), Some((key, _))) = (&bound, departure) + && score[key] - bound[key] > MAX_BOUND_VALUE + { + issues.push(Issue::new( + "optimality_gap_mismatch", + "the gap exceeds the portable result ceiling".to_owned(), + )); + } + let counts = well_formed(emitted); + if emitted.is_null() { + let mut reports_gap = false; + for name in GAP_FIELDS { + reports_gap = reports_gap || !fact.get_null(name)?.is_null(); + } + if reports_gap { + issues.push(Issue::new( + "optimality_gap_mismatch", + "a gap is reported without lower_bound".to_owned(), + )); + } + } else if let Some(counts) = &counts { + match &bound { + None => issues.push(Issue::new( + "optimality_bound_mismatch", + format!("lower_bound is reported where no bound is stated: {withheld}"), + )), + Some(_) if below => issues.push(Issue::new( + "optimality_bound_mismatch", + "lower_bound is reported for a score below the recomputed bound".to_owned(), + )), + Some(bound) => check_reported(counts, score, bound, departure, fact, issues)?, + } + } else { + issues.push(Issue::new( + "optimality_bound_mismatch", + "lower_bound must be a list of 1 to 5 non-negative integers".to_owned(), + )); + } + let attained = bound.is_some() && departure.is_none(); + let claims_attainment = counts.is_some_and(|counts| counts.as_slice() == score); + check_claims(result, fact, attained, claims_attainment, issues) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The cross-language scene kept one level above this crate; a published copy does not + /// carry it. + fn scene() -> Option { + let path = concat!( + env!("CARGO_MANIFEST_DIR"), + "/../../../../../conformance/scene/objective-bounds.json" + ); + let Ok(text) = std::fs::read_to_string(path) else { + eprintln!( + "skipping: the shared cross-language scene fixture is not part of this package" + ); + return None; + }; + Some(serde_json::from_str(&text).expect("the scene is JSON")) + } + + fn integer(value: &serde_json::Value) -> i128 { + match value { + serde_json::Value::String(text) => text.parse().expect("a decimal string"), + other => i128::from(other.as_i64().expect("an integer")), + } + } + + fn optional(value: &serde_json::Value) -> Option { + (!value.is_null()).then(|| integer(value)) + } + + fn runs(instances: &[serde_json::Value], field: &str) -> Runs { + let mut runs: Runs = instances.iter().map(|i| (integer(&i[field]), 1)).collect(); + runs.sort_by_key(|run| run.0); + runs + } + + /// The validator's copy agrees with the oracle on every case and edge of the shared scene, + /// refusals included. + #[test] + fn the_validator_bound_matches_the_scene() { + let Some(scene) = scene() else { + return; + }; + let mut compared = 0; + for case in ["cases", "edges"] + .iter() + .flat_map(|key| scene[*key].as_array().expect("an array")) + { + let instances = case["instances"].as_array().expect("instances"); + let containers: Vec = case["containers"] + .as_array() + .expect("containers") + .iter() + .map(|c| BoundContainer { + inner_volume: integer(&c["inner"]), + base_area: integer(&c["base_area"]), + height: integer(&c["height"]), + usable: integer(&c["usable"]), + cost_minor: integer(&c["cost_minor"]), + payload: optional(&c["payload"]), + max_items: optional(&c["max_items"]), + quantity: optional(&c["quantity"]), + }) + .collect(); + let shrinks = instances.iter().any(|i| i["shrinks"] == true); + let computed = lower_bound( + &runs(instances, "volume"), + &runs(instances, "weight"), + shrinks, + &containers, + ) + .expect("no overflow"); + let expected: Option> = case["bounds"] + .as_array() + .map(|values| values.iter().map(integer).collect()); + assert_eq!(computed.map(|bound| bound.to_vec()), expected, "{case}"); + compared += 1; + } + assert!(compared > 400); + } + + #[test] + fn a_saturated_capacity_is_past_the_ceiling() { + let container = BoundContainer { + inner_volume: 1, + base_area: 1, + height: 1, + usable: i128::MAX, + cost_minor: 0, + payload: None, + max_items: None, + quantity: Some(2), + }; + assert_eq!( + lower_bound(&[(1, 1)], &[(0, 1)], false, &[container]).unwrap(), + None + ); + } + + #[test] + fn a_negative_or_unlimited_capacity_and_no_containers_are_read_as_the_reference_reads_them() { + let mut container = BoundContainer { + inner_volume: 1000, + base_area: 100, + height: 10, + usable: -1, + cost_minor: 3, + payload: Some(5), + max_items: None, + quantity: Some(1), + }; + let bound = |containers: &[BoundContainer]| { + lower_bound(&[(0, 2)], &[(1, 2)], false, containers).unwrap() + }; + assert_eq!( + bound(std::slice::from_ref(&container)), + Some([2, 0, 0, 0, 0]) + ); + container.quantity = None; + assert_eq!(bound(&[container]), Some([0, 1, 3, 1_000_000, 0])); + assert_eq!( + lower_bound(&[(1, 1)], &[(0, 1)], false, &[]).unwrap(), + Some([1, 0, 0, 0, 0]) + ); + } + + /// One cube in a box for two: every position but the height is attained. + const REQUEST: &str = r#"{ + "items": [{"id": "cube", "quantity": 1, "dimensions": {"length": "10", "width": "10", "height": "10"}}], + "containers": [{"id": "box", "inner_dimensions": {"length": "20", "width": "10", "height": "10"}}] + }"#; + + fn gap() -> serde_json::Value { + serde_json::json!({ + "code": "not_proven", + "lower_bound": [0, 1, 0, 500000, 500000], + "gap_key": 4, + "absolute_gap": 500000, + "relative_gap": {"numerator": 500000, "denominator": 500000}, + }) + } + + fn packed(request: &str) -> serde_json::Value { + serde_json::from_str(&crate::pack_json(request).expect("packs")).expect("JSON") + } + + fn issues(request: &str, result: &serde_json::Value) -> Vec { + crate::validate_json(request, &result.to_string()).expect("judged") + } + + fn codes_after( + optimality: serde_json::Value, + change: impl FnOnce(&mut serde_json::Value), + ) -> Vec { + let mut result = packed(REQUEST); + result["optimality"] = optimality; + change(&mut result); + issues(REQUEST, &result) + .into_iter() + .map(|issue| issue.code) + .collect() + } + + fn codes(optimality: serde_json::Value) -> Vec { + codes_after(optimality, |_| {}) + } + + fn details(request: &str, optimality: serde_json::Value) -> Vec { + let mut result = packed(REQUEST); + result["optimality"] = optimality; + issues(request, &result) + .into_iter() + .map(|issue| issue.detail) + .collect() + } + + #[test] + fn a_stated_gap_and_its_absence_are_both_valid() { + assert_eq!(codes(gap()), Vec::::new()); + assert_eq!( + codes(serde_json::json!({"code": "not_proven"})), + Vec::::new() + ); + } + + #[test] + fn a_bound_where_none_is_stated_or_of_the_wrong_shape_is_a_mismatch() { + assert_eq!( + details( + REQUEST, + serde_json::json!({"code": "not_proven", "lower_bound": []}) + ), + ["lower_bound must be a list of 1 to 5 non-negative integers"] + ); + + // Payload capacity 8e24 weight ticks times a million boxes passes the 10^30 ceiling; + // the same packing answers it, only the inventory changed. + let mut huge: serde_json::Value = serde_json::from_str(REQUEST).expect("JSON"); + huge["containers"][0]["max_payload"] = + serde_json::json!({"value": "1000000000000000", "unit": "kg"}); + huge["containers"][0]["quantity"] = serde_json::json!(1_000_000); + assert_eq!( + details( + &huge.to_string(), + serde_json::json!({"code": "not_proven", "lower_bound": [0]}) + ), + [ + "lower_bound is reported where no bound is stated: the request is past a declared ceiling" + ] + ); + + let mut invalid = packed(REQUEST); + invalid["status"] = serde_json::json!("invalid_result"); + invalid["optimality"] = serde_json::json!({"code": "not_proven", "lower_bound": [0]}); + let invalid: Vec = issues(REQUEST, &invalid) + .into_iter() + .map(|issue| issue.detail) + .collect(); + assert!( + invalid.contains( + &"lower_bound is reported where no bound is stated: status is 'invalid_result'" + .to_owned() + ) + ); + } + + #[test] + fn each_check_fires_on_its_own_mutation() { + let mut wrong_bound = gap(); + wrong_bound["lower_bound"][1] = serde_json::json!(2); + assert_eq!(codes(wrong_bound), ["optimality_bound_mismatch"]); + + let mut wrong_gap = gap(); + wrong_gap["absolute_gap"] = serde_json::json!(1); + assert_eq!( + details(REQUEST, wrong_gap), + ["absolute_gap should be 500000"] + ); + + let mut wrong_relative = gap(); + wrong_relative["relative_gap"] = serde_json::json!(1); + assert_eq!( + details(REQUEST, wrong_relative), + ["relative_gap should be 500000/500000"] + ); + + assert_eq!( + codes_after(gap(), |result| result["score"][3] = serde_json::json!(0)), + [ + "score_mismatch", + "score_below_bound", + "optimality_bound_mismatch" + ] + ); + + let mut claimed = gap(); + claimed["code"] = serde_json::json!("proven_optimal"); + assert_eq!( + codes_after(claimed, |result| result["status"] = + serde_json::json!("optimal")), + ["result_fact_mismatch", "unproven_optimality_claim"] + ); + } + + /// Two cubes fill the box, so every position is attained and no gap may be stated. + #[test] + fn an_attained_bound_is_valid_and_states_no_gap() { + let attained = r#"{ + "items": [{"id": "cube", "quantity": 2, "dimensions": {"length": "10", "width": "10", "height": "10"}}], + "containers": [{"id": "box", "inner_dimensions": {"length": "20", "width": "10", "height": "10"}}] + }"#; + let mut result = packed(attained); + result["status"] = serde_json::json!("optimal"); + result["optimality"] = serde_json::json!({ + "code": "proven_optimal", + "lower_bound": [0, 1, 0, 0, 1000000], + }); + assert_eq!(issues(attained, &result), Vec::::new()); + + result["optimality"]["gap_key"] = serde_json::json!(0); + result["optimality"]["absolute_gap"] = serde_json::json!(0); + result["optimality"]["relative_gap"] = + serde_json::json!({"numerator": 0, "denominator": 1}); + let details: Vec = issues(attained, &result) + .into_iter() + .map(|issue| issue.detail) + .collect(); + assert_eq!( + details, + [ + "gap_key should be absent", + "absolute_gap should be absent", + "relative_gap should be absent" + ] + ); + } + #[test] + fn unrepresentable_gaps_are_withheld_and_rejected_when_forged() { + for cheap_cost in [0i64, 1] { + let request = serde_json::json!({ + "items": [{"id": "i", "quantity": 2, "dimensions": {"length":"10", "width":"10", "height":"10"}}], + "containers": [ + {"id":"cheap", "inner_dimensions":{"length":"1", "width":"1", "height":"1"}, "cost_minor":cheap_cost, "max_items":1}, + {"id":"big", "inner_dimensions":{"length":"10", "width":"10", "height":"10"}, "cost_minor":9007199254740991i64, "max_items":1} + ] + }).to_string(); + let mut result = packed(&request); + assert_eq!( + result["optimality"], + serde_json::json!({"code":"not_proven"}) + ); + assert!(issues(&request, &result).is_empty()); + let absolute = 18014398509481982i64 - 2 * cheap_cost; + result["optimality"] = serde_json::json!({"code":"not_proven", "lower_bound":[0,2,2*cheap_cost], "gap_key":2, "absolute_gap":absolute}); + if cheap_cost != 0 { + result["optimality"]["relative_gap"] = + serde_json::json!({"numerator":absolute,"denominator":2*cheap_cost}); + } + assert!( + issues(&request, &result) + .iter() + .any(|issue| issue.code == "optimality_gap_mismatch") + ); + } + } +} diff --git a/src/result_validation/json.rs b/src/result_validation/json.rs index 19b906e..4d699c8 100644 --- a/src/result_validation/json.rs +++ b/src/result_validation/json.rs @@ -175,6 +175,19 @@ impl Json { } } + /// A field the request schema types boolean: absent or null is its default, and any other + /// non-boolean is refused, as every engine refuses it, rather than read by + /// truthiness. + pub(crate) fn flag(&self, key: &str, default: bool, owner: &str) -> Res { + match self.get_null(key)? { + Json::Null => Ok(default), + Json::Bool(flag) => Ok(*flag), + _ => Err(MalformedResult::contract(format!( + "{owner}.{key} must be a boolean" + ))), + } + } + /// Python truthiness. pub(crate) fn truthy(&self) -> bool { match self { diff --git a/src/result_validation/lattice.rs b/src/result_validation/lattice.rs index 720e005..2ac9beb 100644 --- a/src/result_validation/lattice.rs +++ b/src/result_validation/lattice.rs @@ -13,7 +13,7 @@ use super::{Issue, MalformedResult}; const SIDES: [&str; 3] = ["length", "width", "height"]; pub(crate) fn materialize( - request: &Json, + coordinates_required: bool, result: &Json, items: &Ordered, containers: &Ordered, @@ -27,20 +27,13 @@ pub(crate) fn materialize( { return Ok(result.clone()); } - let empty = Json::Dict(Vec::new()); - let coordinates_optional = matches!( - request - .get_or("configuration", &empty)? - .get("require_placement_coordinates")?, - Some(Json::Bool(false)) - ); let mut expanded = result.clone(); let mut rewritten = Vec::with_capacity(packed_containers.len()); for packed in packed_containers { let mut packed = packed.clone(); if let Some(placements) = expand( &packed, - coordinates_optional, + coordinates_required, items, containers, clearance, @@ -57,7 +50,7 @@ pub(crate) fn materialize( /// The placements to write into one container: `None` leaves it untouched. fn expand( packed: &Json, - coordinates_optional: bool, + coordinates_required: bool, items: &Ordered, containers: &Ordered, clearance: i128, @@ -68,7 +61,7 @@ fn expand( Some(summary) => summary, }; let container_id = py_str(packed.get_or("id", &Json::str_of("?"))?); - if !coordinates_optional { + if coordinates_required { issues.push(Issue::new( "unexpected_lattice_summary", format!("{container_id}: request requires explicit placement coordinates"), diff --git a/src/result_validation/mod.rs b/src/result_validation/mod.rs index 8f0de60..ae2b7fe 100644 --- a/src/result_validation/mod.rs +++ b/src/result_validation/mod.rs @@ -13,6 +13,7 @@ //! value too large to compute exactly in `i128`. Both are [`MalformedResult`]s. mod accounting; +mod bound; mod container; mod facts; mod geometry; @@ -32,7 +33,7 @@ use std::fmt; use serde::Serialize; use json::{Json, Ordered, Res}; -use units::{LENGTH, ratio_of, to_ticks}; +use units::{LENGTH, length_unit, ratio_of, to_ticks}; /// One way a result fails to be a sound answer to its request. #[derive(Clone, Debug, PartialEq, Eq, Serialize)] @@ -188,24 +189,28 @@ fn validate(request: &Json, result: &Json) -> Res> { } } let empty = Json::Dict(Vec::new()); - let unit = request - .get_or("units", &empty)? - .get_or("length", &Json::str_of("mm"))? - .text("units.length")? - .to_owned(); + let unit = length_unit(request)?; let configuration = request.get_or("configuration", &empty)?; + let coordinates_required = + configuration.flag("require_placement_coordinates", true, "configuration")?; let clearance = to_ticks( configuration.get_or("clearance", &Json::Int(0))?, - &unit, + unit, LENGTH, )?; let global_support = ratio_of(configuration.get_or("minimum_support_ratio", &Json::Int(0))?)?; - let items = spec::parse_items(request, &unit)?; - let containers = spec::parse_containers(request, &unit)?; + let items = spec::parse_items(request, unit)?; + let containers = spec::parse_containers(request, unit)?; let mut issues = Vec::new(); - let validated = - lattice::materialize(request, result, &items, &containers, clearance, &mut issues)?; + let validated = lattice::materialize( + coordinates_required, + result, + &items, + &containers, + clearance, + &mut issues, + )?; accounting::check_structure(&validated, &mut issues)?; facts::check_algorithm_metrics(&validated, &mut issues)?; facts::check_effort_budget(request, &validated, &mut issues)?; @@ -231,7 +236,7 @@ fn validate(request: &Json, result: &Json) -> Res> { )?; check_container_counts(&validated, configuration, &containers, &mut issues)?; - objective::check_fixed_placements(request, &validated, &unit, &mut issues)?; + objective::check_fixed_placements(request, &validated, unit, &mut issues)?; objective::check_groups(request, &validated, &mut issues)?; objective::check_solver_selection(request, &validated, &mut issues)?; let inputs = objective::Inputs { @@ -240,7 +245,15 @@ fn validate(request: &Json, result: &Json) -> Res> { fabricated: &fabricated, clearance, }; - objective::check_objective(request, &validated, &inputs, &mut issues)?; + let score = objective::check_objective(request, &validated, &inputs, &mut issues)?; + bound::check_optimality_bound( + request, + &validated, + &items, + &containers, + &score, + &mut issues, + )?; Ok(issues) } diff --git a/src/result_validation/objective.rs b/src/result_validation/objective.rs index 7b62662..ea3ee06 100644 --- a/src/result_validation/objective.rs +++ b/src/result_validation/objective.rs @@ -241,12 +241,13 @@ fn objective( }) } +/// Checks the reported score against the recomputed one, and returns the reported score. pub(crate) fn check_objective( request: &Json, result: &Json, inputs: &Inputs<'_>, issues: &mut Vec, -) -> Res<()> { +) -> Res> { let empty = Json::Dict(Vec::new()); let configuration = request.get_or("configuration", &empty)?; let default_objective = Json::str_of("default"); @@ -288,7 +289,7 @@ pub(crate) fn check_objective( ), )); } - Ok(()) + Ok(reported) } pub(crate) fn check_solver_selection( diff --git a/src/result_validation/spec.rs b/src/result_validation/spec.rs index 71b10d6..51e8d7c 100644 --- a/src/result_validation/spec.rs +++ b/src/result_validation/spec.rs @@ -141,11 +141,18 @@ fn optional(raw: &Json, key: &str, read: impl FnOnce(&Json) -> Res) -> Res pub(crate) fn parse_items(request: &Json, unit: &str) -> Res> { let mut items = Ordered::default(); - for raw in request.at("items")?.list("request.items")? { + for (index, raw) in request + .at("items")? + .list("request.items")? + .iter() + .enumerate() + { + let owner = format!("items[{index}]"); + let keep_upright = raw.flag("keep_upright", false, &owner)?; + let stackable = raw.flag("stackable", true, &owner)?; + let must_be_on_floor = raw.flag("must_be_on_floor", false, &owner)?; let rotations = match raw.get_null("allowed_rotations")? { - Json::Null if raw.get_null("keep_upright")?.truthy() => { - UPRIGHT_ROTATIONS.map(Json::str_of).to_vec() - } + Json::Null if keep_upright => UPRIGHT_ROTATIONS.map(Json::str_of).to_vec(), Json::Null => ROTATIONS .iter() .map(|(code, _)| Json::str_of(code)) @@ -159,8 +166,8 @@ pub(crate) fn parse_items(request: &Json, unit: &str) -> Res> weight: to_ticks(raw.get_or("weight", &Json::Int(0))?, "g", WEIGHT)?, quantity: raw.get_or("quantity", &Json::Int(1))?.clone(), allowed_rotations: rotations, - stackable: raw.get_or("stackable", &Json::Bool(true))?.truthy(), - must_be_on_floor: raw.get_null("must_be_on_floor")?.truthy(), + stackable, + must_be_on_floor, max_top_load: optional(raw, "max_top_load", |value| to_ticks(value, "g", WEIGHT))?, minimum_support_ratio: ratio_of(raw.get_or("minimum_support_ratio", &Json::Int(0))?)?, tags: tag_set(raw.get_or("tags", &EMPTY_LIST)?, "tags")?, diff --git a/src/result_validation/units.rs b/src/result_validation/units.rs index 1de71c7..9392cdd 100644 --- a/src/result_validation/units.rs +++ b/src/result_validation/units.rs @@ -33,6 +33,51 @@ pub(crate) const WEIGHT: Table = &[ ("ticks", 1), ]; +/// Every name the engines read in `units.length`, after stripping ASCII whitespace and lowering +/// ASCII case, to the [`LENGTH`] key it means. +const REQUEST_LENGTH_UNITS: &[(&str, &str)] = &[ + ("mm", "mm"), + ("cm", "cm"), + ("m", "m"), + ("in", "in"), + ("inch", "inch"), + ("inches", "inches"), + ("ft", "ft"), + ("tick", "tick"), + ("ticks", "ticks"), + ("millimeter", "mm"), + ("millimeters", "mm"), +]; + +/// `units.length` as every engine reads it: `units` or `units.length` absent or null +/// is millimetres; `units` that is not an object, or a length unit the engines do not know, is +/// refused naming the field. +pub(crate) fn length_unit(request: &Json) -> Res<&'static str> { + let units = request.get_null("units")?; + if units.is_null() { + return Ok("mm"); + } + if !matches!(units, Json::Dict(_)) { + return Err(MalformedResult::contract( + "units must be an object".to_owned(), + )); + } + let key = match units.get_null("length")? { + Json::Null => return Ok("mm"), + Json::Str(text) => text + .trim_matches(|c: char| matches!(c, ' ' | '\t' | '\n' | '\r' | '\x0b' | '\x0c')) + .to_ascii_lowercase(), + _ => String::new(), + }; + REQUEST_LENGTH_UNITS + .iter() + .find(|(name, _)| *name == key) + .map(|(_, unit)| *unit) + .ok_or_else(|| { + MalformedResult::contract("units.length must be one of mm, cm, m, in, ft".to_owned()) + }) +} + pub(crate) const TICKS_PER_MM: i128 = 16_000; pub(crate) const TICKS_PER_GRAM: i128 = 8_000_000; pub(crate) const TICKS_PER_KG: i128 = 8_000_000_000; diff --git a/src/sequence.rs b/src/sequence.rs index fc961e4..8e055bf 100644 --- a/src/sequence.rs +++ b/src/sequence.rs @@ -7,7 +7,6 @@ use crate::geometry::{self, Aabb, Dimensions}; use crate::model::{Container, PackedContainer, Placement}; -use crate::validation::{ground_contact_valid, validate_stack_counts, validate_top_loads}; use std::collections::BTreeSet; use thiserror::Error; @@ -521,8 +520,10 @@ pub fn replay_loading_order( } /// Independently reuse the exact constraint calculations already proven for -/// a finished scene (`validation::validate_top_loads`, `validate_stack_counts`, -/// `ground_contact_valid`) against every loading *prefix*, not only the final state. +/// 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. /// 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. @@ -551,23 +552,32 @@ pub fn verify_loading_prefix_business_rules( reason: "order is not a permutation of every placement index exactly once", }); } - let mut present: Vec = Vec::new(); + let mut scratch = PackedContainer { + container: container.clone(), + sequence: 0, + placements: Vec::with_capacity(placements.len()), + lattice_summary: None, + lattice_items: Vec::new(), + }; for (step, index) in order.iter().copied().enumerate() { - present.push(placements[index].clone()); - let scratch = PackedContainer { - container: container.clone(), - sequence: 0, - placements: present.clone(), - lattice_summary: None, - lattice_items: Vec::new(), - }; + scratch.placements.push(placements[index].clone()); + let graph = crate::contact_graph::ContactGraph::from_placements(&scratch.placements); let mut issues = Vec::new(); - validate_top_loads(&scratch, &mut issues); - validate_stack_counts(&scratch, &mut issues); - if !ground_contact_valid(&scratch, present.len() - 1) { + 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, + ) { issues.push(crate::validation::ValidationIssue { code: "ground_contact_violation".into(), - message: present.last().expect("just pushed").instance.id(), + message: scratch + .placements + .last() + .expect("just pushed") + .instance + .id(), }); } if let Some(problem) = issues.first() { diff --git a/src/solvers/blocks.rs b/src/solvers/blocks.rs index d5aae1a..8a50586 100644 --- a/src/solvers/blocks.rs +++ b/src/solvers/blocks.rs @@ -5,6 +5,7 @@ use crate::geometry::{Aabb, Dimensions, Point, Rotation, ShapeType}; use crate::model::*; use crate::solver::PlacementConstraint; use crate::units::{Length, Weight}; +use std::borrow::Cow; use std::collections::BTreeMap; use std::sync::Arc; @@ -34,8 +35,8 @@ struct Block { ), } -/// Lattice nodes the block start added to `fast` and `balanced` may enumerate per mode -- -/// the bound `quality` gives the same solver through `container_plan_node_limit`. +/// Lattice nodes the block search may enumerate per mode under every profile but `quality` +/// -- the bound `quality` gives the same solver through `container_plan_node_limit`. const BLOCK_START_NODE_LIMIT: usize = 100_000; /// Leading blocks the `quality` block lookahead completes in each round. @@ -60,8 +61,26 @@ pub(crate) fn pack_homogeneous_blocks( constraints: &[Arc], deadline: &Deadline, ) -> Option { - supports(request, constraints) - .then(|| pack_blocks(request, items, &[COUNT_FIRST, VOLUME_FIRST], deadline)) + supports(request, constraints).then(|| { + pack_blocks( + &with_block_node_limit(request), + items, + &[COUNT_FIRST, VOLUME_FIRST], + deadline, + ) + }) +} + +/// The request the block search runs. Every profile but `quality` leaves +/// `container_plan_node_limit` at one, which would stop the enumeration before its first +/// block, so under them the search carries its own bound. O(n) for the copy. +fn with_block_node_limit(request: &PackingRequest) -> Cow<'_, PackingRequest> { + if request.config.profile == SolverProfile::Quality { + return Cow::Borrowed(request); + } + let mut bounded = request.clone(); + bounded.config.container_plan_node_limit = BLOCK_START_NODE_LIMIT; + Cow::Owned(bounded) } /// Whether the lattice can express the whole request as the one block start `fast` and @@ -83,20 +102,17 @@ pub(crate) fn supports_block_start( /// The block start `fast` and `balanced` add to their own; the caller has already /// established [`supports_block_start`]. /// -/// Those profiles leave `container_plan_node_limit` at one, which would stop the -/// enumeration before its first block, so the start carries its own bound. `fast` is -/// latency-bound and enumerates one mode, the one its objective ranks by; `balanced` -/// enumerates both, as `quality` does. Same O(B*S*T*R*X*Y) time and O(S+n) space as +/// Those profiles leave `container_plan_node_limit` at one, so the start carries its own +/// bound ([`with_block_node_limit`]). `fast` is latency-bound and enumerates one mode, +/// the one its objective ranks by; `balanced` enumerates both, as `quality` does. Same O(B*S*T*R*X*Y) time and O(S+n) space as /// [`pack_homogeneous_blocks`], with X*Y capped at `BLOCK_START_NODE_LIMIT` per mode. pub(crate) fn pack_block_start( request: &PackingRequest, items: &[ItemInstance], deadline: &Deadline, ) -> PackingResult { - let mut bounded = request.clone(); - bounded.config.container_plan_node_limit = BLOCK_START_NODE_LIMIT; pack_blocks( - &bounded, + &with_block_node_limit(request), items, block_start_modes(&request.config), deadline, @@ -120,6 +136,7 @@ fn pack_blocks( modes: &[bool], deadline: &Deadline, ) -> PackingResult { + let deadline = &deadline.for_start(); let started = deadline.now_ns(); let mut remaining = items.to_vec(); let mut packed = Vec::new(); @@ -228,7 +245,7 @@ fn pack_blocks( }) .collect::>(); let score = score_solution(&packed, &unpacked, &request.config); - let effort_limited = effort_exhausted(request, &metrics); + let effort_limited = deadline.effort_stopped(); PackingResult { status: if unpacked.is_empty() { PackingStatus::Feasible @@ -470,7 +487,8 @@ fn group_winner( let mut largest = 0; for nx in 1..=maximum_x.min(capacity) { for ny in 1..=maximum_y.min(capacity / nx) { - if *nodes >= node_limit || deadline.expired() || effort_exhausted(request, metrics) { + if *nodes >= node_limit || deadline.expired() || deadline.effort_stops(request, metrics) + { return Group::Stopped; } *nodes += 1; @@ -582,7 +600,10 @@ fn complete( if reached { break; } - commit(&mut round, block, request, metrics); + if !commit(&mut round, block, request, deadline, metrics) { + reached = true; + break; + } } round.finish(reached) } @@ -619,6 +640,7 @@ fn lookahead( let mut known = (!greedy.2).then(|| greedy.clone()); let mut best = greedy; let mut nodes = 0_usize; + let mut cut = false; while round.open() { let (leading, mut reached) = leading_blocks( &round, @@ -643,7 +665,10 @@ fn lookahead( let first = usize::from(chosen.is_some()); for (index, block) in leading.iter().enumerate().skip(first) { let mut trial = round.clone(); - commit(&mut trial, block, request, metrics); + if !commit(&mut trial, block, request, deadline, metrics) { + reached = true; + break; + } let solution = complete( trial, request, @@ -669,10 +694,13 @@ fn lookahead( best_key = key; best = solution.clone(); } - commit(&mut round, &leading[index], request, metrics); + if !commit(&mut round, &leading[index], request, deadline, metrics) { + cut = true; + break; + } known = Some(solution); } - let stopped = best.2 || deadline.expired(); + let stopped = cut || best.2 || deadline.expired(); (best.0, best.1, stopped) } @@ -812,17 +840,59 @@ fn leading_blocks( } /// Place every member of `block`, bottom layer first, and carve it from the free spaces. -fn commit(round: &mut Round, block: &Block, request: &PackingRequest, metrics: &mut SolverMetrics) { +/// +/// Each member is one counted candidate and placement attempt. When the effort budget has +/// room for fewer than the whole block, only the members it has room for are placed, the +/// stop is recorded and `false` says the search ends here: no counter passes its limit +///. Members go x fastest, then y, then z, so a member above the bottom layer always +/// rests on the member beneath it. O(count * p) time for the bottom layer's support. +fn commit( + round: &mut Round, + block: &Block, + request: &PackingRequest, + deadline: &Deadline, + metrics: &mut SolverMetrics, +) -> bool { + let room = placement_room(request, metrics); + let members = usize::try_from(room).map_or(block.count, |room| block.count.min(room)); + place_members(round, block, members, request, metrics); + if members < block.count { + deadline.effort_stops(request, metrics); + return false; + } + let occupied = 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: Length(block.nz * block.envelope.height.0), + }, + }; + round.spaces = subtract_all(std::mem::take(&mut round.spaces), occupied, metrics); + true +} + +/// The block's first `members` members, x fastest, then y, then z. +fn place_members( + round: &mut Round, + block: &Block, + members: usize, + request: &PackingRequest, + metrics: &mut SolverMetrics, +) { let available = round .remaining .get_mut(&block.item_id) .expect("candidate item exists"); - let chosen = available.drain(..block.count).collect::>(); + let chosen = available.drain(..members).collect::>(); let clearance = request.config.clearance.0; let mut index = 0; for z in 0..block.nz { for y in 0..block.ny { for x in 0..block.nx { + if index == members { + return; + } let origin = Point { x: block.space.0.origin.x + x * block.envelope.length.0, y: block.space.0.origin.y + y * block.envelope.width.0, @@ -856,15 +926,6 @@ fn commit(round: &mut Round, block: &Block, request: &PackingRequest, metrics: & } } } - let occupied = 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: Length(block.nz * block.envelope.height.0), - }, - }; - round.spaces = subtract_all(std::mem::take(&mut round.spaces), occupied, metrics); } #[cfg(test)] @@ -1001,6 +1062,44 @@ mod tests { }).to_string() } + /// The cartons of [`request`] under `profile`, at that profile's own node limit unless + /// one is given. + fn named_blocks(profile: &str, node_limit: Option) -> serde_json::Value { + let mut request: serde_json::Value = serde_json::from_str(&request(1, true)).unwrap(); + let configuration = &mut request["configuration"]; + configuration["solver_profile"] = profile.into(); + configuration["container_plan_beam_width"] = 1.into(); + match node_limit { + Some(limit) => configuration["container_plan_node_limit"] = limit.into(), + None => { + configuration + .as_object_mut() + .unwrap() + .remove("container_plan_node_limit"); + } + } + serde_json::from_str(&pack_json(&request.to_string()).expect("solve")).unwrap() + } + + #[test] + fn a_named_block_solver_outside_quality_reaches_its_first_block() { + // Both profiles leave `container_plan_node_limit` at one, short of the first block + //. + for profile in ["fast", "balanced"] { + let result = named_blocks(profile, None); + assert_eq!(result["summary"]["packed_item_count"], 28, "{profile}"); + assert_eq!(result["termination"]["code"], "complete", "{profile}"); + } + } + + #[test] + fn a_node_limit_stop_is_the_search_answer_not_a_time_limit() { + let result = named_blocks("quality", Some(1)); + assert_eq!(result["summary"]["packed_item_count"], 0); + assert_eq!(result["algorithm"]["time_limit_reached"], false); + assert_eq!(result["termination"]["code"], "complete"); + } + /// One 60x60x40 base and three 40x60x50 tops in a 100 mm crate. The greedy block pass, /// which `balanced` runs, ends the base on two tops so that it overhangs them; /// `quality`'s lookahead finds a layout with nothing overhanging. diff --git a/src/solvers/exact.rs b/src/solvers/exact.rs index 6a5f2c7..62d0a2f 100644 --- a/src/solvers/exact.rs +++ b/src/solvers/exact.rs @@ -40,6 +40,7 @@ pub fn pack_exact_one( return None; } + let deadline = &deadline.for_start(); let started = deadline.now_ns(); let mut best_result: Option = None; let mut searched_all_containers = true; @@ -77,7 +78,7 @@ pub fn pack_exact_one( let mut best_position = usize::MAX; for (root_floor, position, initial, can_fit, cannot_fit) in planned { - if deadline.expired() || effort_exhausted(request, &metrics) { + if deadline.expired() { searched_all_containers = false; break; } @@ -86,6 +87,11 @@ pub fn pack_exact_one( { continue; } + // Asked after the floor skip: a container proven unable to win is no work refused. + if deadline.effort_stops(request, &metrics) { + searched_all_containers = false; + break; + } let mut best_state = initial.clone(); let mut best_state_score = score_state(&best_state, &can_fit, &cannot_fit, &request.config); @@ -125,7 +131,7 @@ pub fn pack_exact_one( .map(|placement| placement.instance.id()) .collect::>(); let timed_out = deadline.expired(); - let effort_limited = effort_exhausted(request, &metrics); + let effort_limited = deadline.effort_stopped(); let unpacked = items .iter() .filter(|item| !placed.contains(&item.id())) @@ -211,7 +217,7 @@ pub fn pack_exact_one( if let Some(result) = best_result.as_mut() { let timed_out = deadline.expired(); - let effort_limited = effort_exhausted(request, &metrics); + let effort_limited = deadline.effort_stopped(); result.algorithm.duration_ms = deadline.elapsed_ms_since(started); result.algorithm.time_limit_reached = timed_out; result.algorithm.effort_limit_reached = effort_limited; @@ -653,7 +659,7 @@ fn search( metrics: &mut SolverMetrics, visited: &mut VisitedStates, ) { - if deadline.expired() || effort_exhausted(request, metrics) { + if deadline.expired() { return; } // In an order-insensitive scene, two item orders that seat the same boxes at the same @@ -663,6 +669,11 @@ fn search( 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; @@ -810,14 +821,24 @@ mod tests { // Root plus four placements exactly consumes this counted prefix. Containers are // searched best root floor first, so `b-flat` -- the one the objective prefers -- // has already produced a complete incumbent when the global exact search budget - // binds, and the remaining container must not erase that result. + // is spent, and the remaining container must not erase that result. Its floor + // cannot beat the incumbent, so it is skipped as proven: the budget refused no + // work and the search finished on exactly its budget, not stopped by it. let output = pack_json(&open_height_request(5)).expect("budgeted exact-small request"); let result: serde_json::Value = serde_json::from_str(&output).unwrap(); assert_eq!(result["complete"], true); assert_eq!(result["containers"][0]["container_type"], "b-flat"); assert_eq!(result["algorithm"]["metrics"]["search_nodes_expanded"], 5); + assert_eq!(result["algorithm"]["effort_limit_reached"], false); + assert_eq!(result["termination"]["code"], "complete"); + + // One node short, `b-flat` is cut before its last placement and the stop is reported. + let output = pack_json(&open_height_request(4)).expect("budgeted exact-small request"); + let result: serde_json::Value = serde_json::from_str(&output).unwrap(); + assert_eq!(result["algorithm"]["metrics"]["search_nodes_expanded"], 4); assert_eq!(result["algorithm"]["effort_limit_reached"], true); + assert_eq!(result["termination"]["code"], "effort_limit"); } #[test] diff --git a/src/solvers/extreme.rs b/src/solvers/extreme.rs index cd2f779..1afa97e 100644 --- a/src/solvers/extreme.rs +++ b/src/solvers/extreme.rs @@ -478,7 +478,7 @@ pub fn find_candidates_at_points( if points.is_empty() { return Vec::new(); } - if deadline.expired() || effort_exhausted(request, metrics) { + if deadline.expired() || deadline.effort_stops(request, metrics) { return Vec::new(); } let boundary = Aabb { @@ -574,15 +574,18 @@ pub fn find_candidates_at_points( ) }); let flat_bag = state.packed.container.is_flat_bag(); + let axle_base = AxleBase::new(&state.packed.container, &state.packed.placements); let mut candidates = CandidateAccumulator::new(limit); for (point_index, point) in points.into_iter().enumerate() { - if point_index > 0 && (deadline.expired() || effort_exhausted(request, metrics)) { + if point_index > 0 && (deadline.expired() || deadline.effort_stops(request, metrics)) { break; } metrics.candidate_points_considered = metrics.candidate_points_considered.saturating_add(1); for (rotation, physical, envelope, shape) in &rotations { let (rotation, physical, envelope) = (*rotation, *physical, *envelope); - if effort_exhausted(request, metrics) { + // Checked before each counted rotation, so neither `orientations_considered` nor + // `feasible_candidates` (at most one per rotation) passes its limit. + if deadline.effort_stops(request, metrics) { break; } metrics.orientations_considered = metrics.orientations_considered.saturating_add(1); @@ -670,11 +673,10 @@ pub fn find_candidates_at_points( if maximum_items_reached { continue; } - if axle_overloaded( - &state.packed.container, - &state.packed.placements, - Some((item.item.weight, envelope_box)), - ) { + if axle_base + .as_ref() + .is_some_and(|base| base.overloaded(item.item.weight, envelope_box)) + { continue; } if item.item.must_be_on_floor && point.z != 0 { @@ -689,6 +691,7 @@ pub fn find_candidates_at_points( .map(|placement| placement_support_view(&state.packed.placements, placement)); let (support_area, support_ratio) = match nested_support.as_ref() { Some(support) => (support.area, support.ratio), + None if point.z == 0 => (envelope.base_area(), 1.0), None => { let area = supporting_area(state, envelope_box); (area, support_ratio_of(area, envelope_box)) @@ -798,6 +801,7 @@ pub fn pack_order( solver_name: &str, deadline: &Deadline, ) -> PackingResult { + let deadline = &deadline.for_start(); let started = deadline.now_ns(); let mut metrics = SolverMetrics::default(); let opened = open_fixed_containers( @@ -844,7 +848,6 @@ pub fn pack_order( .map(|maximum| packed.len() < maximum) .unwrap_or(true) && !deadline.expired() - && !effort_exhausted(request, &metrics) { // Evaluate every eligible container type against the same // `remaining` items and commit to whichever placed the most, rather than @@ -854,8 +857,13 @@ pub fn pack_order( // bound Python's `_across_containers`/PHP's `acrossContainers` already // implement (docs/ALGORITHMS-AND-COMPLEXITY.md) -- this was a Rust-specific // gap, not a new cost class. + // A round with no container to try is the search ending, not the budget stopping it. + let eligible = eligible_containers(request, &remaining, &inventory); + if eligible.is_empty() || deadline.effort_stops(request, &metrics) { + break; + } let mut best: Option = None; - for container in eligible_containers(request, &remaining, &inventory) { + for container in eligible { if deadline.expired() { break; } @@ -914,7 +922,7 @@ pub fn pack_order( } let timed_out = deadline.expired(); - let effort_limited = effort_exhausted(request, &metrics); + let effort_limited = deadline.effort_stopped(); let unpacked = remaining .into_iter() .map(|instance| { @@ -1011,6 +1019,11 @@ where let mut last = None; let mut trials = 0; for rung in rungs { + // Polled before every rung after the first, so the last rung finishing on its + // budget is not a stop: no rung was refused. + if trials > 0 && (deadline.expired() || deadline.effort_stops(request, metrics)) { + break; + } let (state, next) = fill(container.with_envelope(rung), sequence, remaining, metrics); trials += 1; if state.packed.placements.is_empty() { @@ -1029,9 +1042,6 @@ where }); } } - if deadline.expired() || effort_exhausted(request, metrics) { - break; - } } match best { Some(best) => (best.state, best.remaining, trials), @@ -1100,7 +1110,13 @@ where for fixed in &request.fixed_containers { let mut seeded = fixed.container.clone(); seeded.preloaded = fixed.placements.clone(); - let (state, remaining) = if deadline.expired() || effort_exhausted(request, metrics) { + // With nothing left to place a fill is no counted work, so the budget refuses none. + let stops = if opened.remaining.is_empty() { + effort_exhausted(request, metrics) + } else { + deadline.effort_stops(request, metrics) + }; + let (state, remaining) = if deadline.expired() || stops { ( ContainerState::new(seeded, fixed.sequence), opened.remaining.clone(), @@ -1233,7 +1249,7 @@ fn pack_container_plans( if plan_nodes >= request.config.container_plan_node_limit { break; } - if deadline.expired() || effort_exhausted(request, metrics) { + if deadline.expired() || deadline.effort_stops(request, metrics) { exhausted = true; break; } @@ -1378,7 +1394,16 @@ fn commit_placement(state: &mut ContainerState, placement: Placement) { for point in exposed_points(state, envelope_box) { absorb_point(state, point); } - if let Some(loads) = calculate_top_loads(&state.packed.placements) { + let isolated_on_floor = envelope_box.origin.z == 0 + && state.packed.placements[placement_index] + .instance + .item + .nesting_height + .is_none() + && !state.packed.placements[..placement_index] + .iter() + .any(|existing| existing.envelope_origin.z == envelope_box.z2()); + 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); } @@ -1992,11 +2017,38 @@ impl CandidateScene<'_> { /// `upper`'s share of `downward` onto `lower`: proportional by contact area, with /// the last supporter taking the rounding remainder, exactly as the settled loads. fn share(&self, upper: usize, lower: usize, downward: i128) -> i128 { - let supporters = self.supporters(upper); - let total_area = supporters.iter().map(|edge| edge.area).sum::(); + if upper == self.candidate_index() { + let supporters = self.below; + let total_area = supporters.iter().map(|edge| edge.area).sum::(); + let mut distributed = 0_i128; + for (position, edge) in supporters.iter().enumerate() { + let share = if position + 1 == supporters.len() { + downward.saturating_sub(distributed) + } else { + downward.saturating_mul(edge.area) / total_area + }; + if edge.index == lower { + return share; + } + distributed = distributed.saturating_add(share); + } + return 0; + } + let base_supporters = self.sweep.graph.supporters(upper); + let extra = self + .above + .iter() + .find(|edge| edge.index == upper) + .map(|edge| ContactEdge { + index: self.candidate_index(), + area: edge.area, + }); + let total_len = base_supporters.len() + usize::from(extra.is_some()); + let total_area = base_supporters.iter().map(|edge| edge.area).sum::() + + extra.map_or(0, |edge| edge.area); let mut distributed = 0_i128; - for (position, edge) in supporters.iter().enumerate() { - let share = if position + 1 == supporters.len() { + for (position, edge) in base_supporters.iter().chain(extra.as_ref()).enumerate() { + let share = if position + 1 == total_len { downward.saturating_sub(distributed) } else { downward.saturating_mul(edge.area) / total_area @@ -2631,7 +2683,12 @@ fn try_pack_into_greedy( let mut groups = group_member_indices(current); for cursor in 0..current.len() { - if effort_exhausted(request, metrics) { + // A member placed with its group is no work left, so it is skipped before the + // budget is asked: only an unplaced item can be refused. + if processed[cursor] { + continue; + } + if deadline.effort_stops(request, metrics) { next.extend( current .iter() @@ -2641,9 +2698,6 @@ fn try_pack_into_greedy( ); break; } - if processed[cursor] { - continue; - } metrics.search_nodes_expanded = metrics.search_nodes_expanded.saturating_add(1); let batch_indices = if let Some(group) = current[cursor].item.group.as_deref() { groups @@ -3039,7 +3093,7 @@ fn try_pack_into_beam( for node in &beam { if nodes >= request.config.container_plan_node_limit || deadline.expired() - || effort_exhausted(request, metrics) + || deadline.effort_stops(request, metrics) { exhausted = true; break; diff --git a/src/solvers/grid.rs b/src/solvers/grid.rs index 9b4fd69..f9938fe 100644 --- a/src/solvers/grid.rs +++ b/src/solvers/grid.rs @@ -138,6 +138,7 @@ pub fn try_grid(request: &PackingRequest, deadline: &Deadline) -> Option Option 0 && !deadline.expired() && !effort_exhausted(request, &metrics) { + while remaining > 0 && !deadline.expired() { // Rank by what the objective rewards, not by raw capacity. Leading // with capacity reads as "the biggest box wins" -- it minimises container count // and then stops caring, so under `lowest_cost` a box holding one more item beat @@ -247,6 +248,11 @@ pub fn try_grid(request: &PackingRequest, deadline: &Deadline) -> Option Option 0 && !request.config.require_placement_coordinates && nesting == 0 { + // The fast path counts the whole lattice in one step, so it is taken only when the + // budget has room for all of it; otherwise the per-item loop below lays the same + // lattice one counted item at a time and stops on the limit, never past it. + if total > 0 + && !request.config.require_placement_coordinates + && nesting == 0 + && placement_room(request, &metrics) >= total as u64 + && node_room(request, &metrics) >= 1 + { // Quantity-compression fast path: the lattice parameters // above already fully determine every coordinate in `O(r)`; skip the // `O(n)` loop that would otherwise build one `Placement` per instance @@ -315,7 +329,7 @@ pub fn try_grid(request: &PackingRequest, deadline: &Deadline) -> Option= capacity || remaining == 0 || deadline.expired() - || effort_exhausted(request, &metrics) + || deadline.effort_stops(request, &metrics) { break 'outer; } @@ -379,7 +393,7 @@ pub fn try_grid(request: &PackingRequest, deadline: &Deadline) -> Option], deadline: &Deadline, ) -> PackingResult { + let deadline = &deadline.for_start(); let started = deadline.now_ns(); let mut metrics = SolverMetrics::default(); let fill = |container: Container, @@ -106,7 +107,7 @@ pub fn pack_maximal_order( }) .collect::>(); let score = score_solution(&packed, &unpacked, &request.config); - let effort_limited = effort_exhausted(request, &metrics); + let effort_limited = deadline.effort_stopped(); PackingResult { status: if unpacked.is_empty() { PackingStatus::Feasible @@ -180,7 +181,7 @@ fn fill_container( let mut sorted_points: Option> = None; for item in remaining.iter().cloned() { - if deadline.expired() || effort_exhausted(request, metrics) { + if deadline.expired() || deadline.effort_stops(request, metrics) { next.push(item); continue; } diff --git a/src/solvers/portfolio.rs b/src/solvers/portfolio.rs index 770c90f..253b513 100644 --- a/src/solvers/portfolio.rs +++ b/src/solvers/portfolio.rs @@ -94,13 +94,18 @@ pub(crate) fn solve_portfolio_with_deadline( { return Ok(finalize_single_start(grid.clone(), deadline.expired())); } - if enabled("exact_small") + let exact_preflight = if enabled("exact_small") && request.config.profile == SolverProfile::ExactSmall && instances.len() <= request.config.exact_item_limit - && let Some(result) = pack_exact_one(request, &instances, constraints, scorers, deadline) + { + pack_exact_one(request, &instances, constraints, scorers, deadline) + } else { + None + }; + if let Some(result) = exact_preflight.as_ref() && result.complete() { - return Ok(finalize_single_start(result, deadline.expired())); + return Ok(finalize_single_start(result.clone(), deadline.expired())); } let target = match request.config.profile { @@ -280,7 +285,12 @@ pub(crate) fn solve_portfolio_with_deadline( && !deadline.expired() && results.len() < restart_limit { - if let Some(result) = pack_exact_one(request, &instances, constraints, scorers, deadline) { + let exact_result = if let Some(preflight) = exact_preflight { + Some(preflight) + } else { + pack_exact_one(request, &instances, constraints, scorers, deadline) + }; + if let Some(result) = exact_result { results.push(result); } else if explicit_selection && request.config.solvers.len() == 1 diff --git a/src/validation.rs b/src/validation.rs index bb2b09b..065574d 100644 --- a/src/validation.rs +++ b/src/validation.rs @@ -309,14 +309,10 @@ fn validate_fixed_placements( // `pub(crate)`, not private: `sequence.rs`'s `verify_loading_prefix_business_rules` // reuses these exact calculations against every loading prefix, not only -// the finished scene -- crate-visible so that reuse doesn't need to duplicate the -// arithmetic, without widening this module's public API surface. -pub(crate) fn validate_top_loads(container: &PackedContainer, issues: &mut Vec) { - let graph = ContactGraph::from_placements(&container.placements); - validate_top_loads_with_graph(container, &graph, issues); -} - -fn validate_top_loads_with_graph( +// the finished scene, with one contact graph per prefix shared by all three checks -- +// crate-visible so that reuse doesn't need to duplicate the arithmetic, without +// widening this module's public API surface. +pub(crate) fn validate_top_loads_with_graph( container: &PackedContainer, graph: &ContactGraph, issues: &mut Vec, @@ -379,12 +375,7 @@ fn validate_top_loads_with_graph( } } -pub(crate) fn ground_contact_valid(container: &PackedContainer, index: usize) -> bool { - let graph = ContactGraph::from_placements(&container.placements); - ground_contact_valid_with_graph(container, index, &graph) -} - -fn ground_contact_valid_with_graph( +pub(crate) fn ground_contact_valid_with_graph( container: &PackedContainer, index: usize, graph: &ContactGraph, @@ -407,15 +398,7 @@ fn ground_contact_valid_with_graph( } } -pub(crate) fn validate_stack_counts( - container: &PackedContainer, - issues: &mut Vec, -) { - let graph = ContactGraph::from_placements(&container.placements); - validate_stack_counts_with_graph(container, &graph, issues); -} - -fn validate_stack_counts_with_graph( +pub(crate) fn validate_stack_counts_with_graph( container: &PackedContainer, graph: &ContactGraph, issues: &mut Vec, @@ -651,7 +634,8 @@ mod tests { Some(Weight(Weight::TICKS_PER_KG * 3 / 4)); let mut issues = Vec::new(); - validate_top_loads(&packed, &mut issues); + let graph = ContactGraph::from_placements(&packed.placements); + validate_top_loads_with_graph(&packed, &graph, &mut issues); assert_eq!( issues @@ -667,7 +651,8 @@ mod tests { let packed = nested_container(3, None, Some(1)); let mut issues = Vec::new(); - validate_stack_counts(&packed, &mut issues); + let graph = ContactGraph::from_placements(&packed.placements); + validate_stack_counts_with_graph(&packed, &graph, &mut issues); assert!( issues diff --git a/tests/effort_stop.rs b/tests/effort_stop.rs new file mode 100644 index 0000000..5f37b53 --- /dev/null +++ b/tests/effort_stop.rs @@ -0,0 +1,223 @@ +//! The effort flag means a guard stopped the search, and no counter passes its limit. +//! +//! A start that finishes having used exactly its budget was not stopped: it reports +//! `effort_limit_reached: false` and terminates `complete`. A budget one short stops it, and +//! every counted metric stays at or below its limit -- including the lattice and block paths, +//! which count a whole run of placements at once. +//! +//! "Exactly its budget" is the three limits set alike to the largest counter used, as a caller +//! sets them. Every guard reads all three counters, so a node or candidate limit equal to its +//! own use can still refuse the rotations that follow the last count -- a real stop, which is +//! why the per-counter cases below only claim the stop and the limits. + +use packvium_core::{ExecutionOptions, pack_json, pack_json_with, validate_json}; +use serde_json::{Value, json}; + +const GENEROUS: u64 = 1_000_000; + +fn request(solver: &str, profile: &str, items: Value, container: [u32; 3]) -> Value { + let [length, width, height] = container; + json!({ + "configuration": { + "solver_profile": profile, + "solvers": [solver], + "time_limit_ms": 60_000, + }, + "items": items, + "containers": [{ + "id": "box", + "inner_dimensions": { + "length": length.to_string(), + "width": width.to_string(), + "height": height.to_string(), + }, + }], + }) +} + +fn cube(id: &str, quantity: u32, side: u32) -> Value { + json!({ + "id": id, + "quantity": quantity, + "dimensions": { + "length": side.to_string(), + "width": side.to_string(), + "height": side.to_string(), + }, + }) +} + +fn mixed_cart() -> Value { + request( + "extreme_points", + "fast", + json!([ + cube("large", 3, 30), + cube("medium", 5, 20), + {"id": "slab", "quantity": 4, "dimensions": {"length": "40", "width": "20", "height": "10"}}, + ]), + [80, 60, 50], + ) +} + +/// `request` with the three counted limits set to `(candidates, placements, nodes)`, packed, +/// and checked by the reference validator. +fn pack_with(request: &Value, (candidates, placements, nodes): (u64, u64, u64)) -> Value { + let mut budgeted = request.clone(); + budgeted["configuration"]["effort_budget"] = json!({ + "max_candidates_evaluated": candidates, + "max_placement_attempts": placements, + "max_search_nodes": nodes, + }); + let text = budgeted.to_string(); + let result = pack_json(&text).expect("a valid request packs"); + let issues = validate_json(&text, &result).expect("the result has the documented shape"); + assert!(issues.is_empty(), "{issues:?}"); + serde_json::from_str(&result).expect("result JSON") +} + +fn counters(result: &Value) -> (u64, u64, u64) { + let metrics = &result["algorithm"]["metrics"]; + let read = |name: &str| metrics[name].as_u64().expect("counted metric"); + ( + read("feasible_candidates"), + read("orientations_considered"), + read("search_nodes_expanded"), + ) +} + +fn assert_within(result: &Value, (candidates, placements, nodes): (u64, u64, u64)) { + let used = counters(result); + assert!( + used.0 <= candidates && used.1 <= placements && used.2 <= nodes, + "used {used:?} past limits {:?}", + (candidates, placements, nodes) + ); +} + +fn assert_unstopped_answer(result: &Value, unlimited: &Value) { + assert_eq!(result["algorithm"]["effort_limit_reached"], false); + assert_eq!(result["termination"]["code"], "complete"); + assert_eq!(result["termination"]["any_start_truncated"], false); + assert_eq!(result["score"], unlimited["score"]); + assert_eq!(result["containers"], unlimited["containers"]); +} + +fn assert_stopped(result: &Value, limits: (u64, u64, u64)) { + assert_eq!(result["algorithm"]["effort_limit_reached"], true); + assert_eq!(result["termination"]["code"], "effort_limit"); + assert_within(result, limits); +} + +/// Runs `request` unlimited, then with every limit at exactly the largest counter it used, +/// then one short of that, then one short on each counter alone. +fn assert_exact_boundary(request: &Value) { + let unlimited = pack_with(request, (GENEROUS, GENEROUS, GENEROUS)); + assert_eq!(unlimited["termination"]["code"], "complete"); + let used = counters(&unlimited); + let most = used.0.max(used.1).max(used.2); + + assert_unstopped_answer(&pack_with(request, (most, most, most)), &unlimited); + let short = most - 1; + assert_stopped( + &pack_with(request, (short, short, short)), + (short, short, short), + ); + let (candidates, placements, nodes) = used; + for alone in [ + (candidates - 1, GENEROUS, GENEROUS), + (GENEROUS, placements - 1, GENEROUS), + (GENEROUS, GENEROUS, nodes - 1), + ] { + assert_stopped(&pack_with(request, alone), alone); + } +} + +#[test] +fn a_search_that_uses_exactly_its_budget_finishes_and_one_short_stops_it() { + assert_exact_boundary(&mixed_cart()); +} + +#[test] +fn a_block_start_meets_the_same_boundary() { + assert_exact_boundary(&request( + "homogeneous_blocks", + "quality", + json!([cube("a", 27, 10), cube("b", 8, 20)]), + [60, 30, 30], + )); +} + +#[test] +fn a_block_commit_places_only_the_members_the_budget_has_room_for() { + // One 3x3x3 block of 27: the commit counts every member at once. + let request = request( + "homogeneous_blocks", + "quality", + json!([cube("a", 27, 10)]), + [30, 30, 30], + ); + for placements in [1, 10, 26] { + let limits = (GENEROUS, placements, GENEROUS); + let result = pack_with(&request, limits); + assert_stopped(&result, limits); + assert_eq!(counters(&result).1, placements); + } +} + +#[test] +fn a_lattice_counted_at_once_is_taken_only_when_the_budget_covers_it() { + let mut request = request("grid", "fast", json!([cube("a", 20, 10)]), [100, 100, 100]); + // The closed form is the compact lattice, laid out only when coordinates may be left out. + request["configuration"]["require_placement_coordinates"] = json!(false); + let unlimited = pack_with(&request, (GENEROUS, GENEROUS, GENEROUS)); + assert_eq!(counters(&unlimited), (20, 20, 1)); + assert_unstopped_answer(&pack_with(&request, (20, 20, 1)), &unlimited); + + // Too small for the closed form: the per-item lattice stops exactly on the limit. + for limits in [ + (GENEROUS, 7, GENEROUS), + (7, GENEROUS, GENEROUS), + (19, 19, GENEROUS), + ] { + let result = pack_with(&request, limits); + assert_stopped(&result, limits); + } +} + +#[test] +fn parallel_starts_each_report_their_own_stop() { + // Several `balanced` starts on threads: each start's flag comes from its own guards, so + // the start records match the sequential run whatever the budget. + let mut request = mixed_cart(); + request["configuration"]["solver_profile"] = json!("balanced"); + request["configuration"]["solvers"] = json!(["extreme_points", "maximal_spaces"]); + for limit in [60, 200, 400, GENEROUS] { + let mut budgeted = request.clone(); + budgeted["configuration"]["effort_budget"] = json!({ + "max_candidates_evaluated": limit, + "max_placement_attempts": limit, + "max_search_nodes": limit, + }); + let text = budgeted.to_string(); + let run = |parallel| { + let output = pack_json_with(&text, ExecutionOptions { parallel }).expect("packs"); + let mut result: Value = serde_json::from_str(&output).expect("result JSON"); + without_durations(&mut result); + result + }; + assert_eq!(run(true), run(false), "limit {limit}"); + } +} + +/// Clears every `duration_ms`, the one field a wall clock writes. +fn without_durations(value: &mut Value) { + match value { + Value::Object(fields) => { + fields.remove("duration_ms"); + fields.values_mut().for_each(without_durations); + } + Value::Array(values) => values.iter_mut().for_each(without_durations), + _ => {} + } +} diff --git a/tests/request_errors.rs b/tests/request_errors.rs index 29fc008..fe6b795 100644 --- a/tests/request_errors.rs +++ b/tests/request_errors.rs @@ -557,3 +557,32 @@ fn billing_units_and_a_negative_board_price_are_refused_as_the_reference_refuses ); } } + +/// `"no"` used to be read as the field's default, so a typo packed as `stackable`. +#[test] +fn a_schema_boolean_refuses_anything_but_a_boolean() { + for (field, pointer) in [ + ("keep_upright", "/items/0/keep_upright"), + ("stackable", "/items/0/stackable"), + ("must_be_on_floor", "/items/0/must_be_on_floor"), + ] { + for value in [json!("no"), json!(0), json!(1), json!([])] { + let mut request = base(); + request["items"][0][field] = value; + let error = refused(&request); + assert_eq!( + (error.reason(), error.field(), error.detail()), + ("wrong_type", pointer, "must be a boolean") + ); + } + let mut request = base(); + request["items"][0][field] = Value::Null; + pack_json(&request.to_string()).expect("null is the default"); + } + let mut request = base(); + request["configuration"]["require_placement_coordinates"] = json!("false"); + assert_eq!( + refused(&request).field(), + "/configuration/require_placement_coordinates" + ); +}