From 442b30d4b2a3bdd4a2e00bb9230ca905569b0a71 Mon Sep 17 00:00:00 2001 From: Anton Date: Mon, 26 Oct 2026 15:34:31 -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 | 47 ++++++++ .github/workflows/release.yml | 4 +- CHANGELOG.md | 30 ++--- CITATION.cff | 2 + CONTRIBUTING.md | 21 ++++ bindings/python/pyproject.toml | 2 +- codemeta.json | 4 +- crates/packvium-core/src/contact_graph.rs | 18 ++- crates/packvium-core/src/model.rs | 62 +++++++++++ crates/packvium-core/src/rebalance.rs | 11 +- crates/packvium-core/src/request_errors.rs | 18 ++- .../src/result_validation/json.rs | 13 +++ .../src/result_validation/lattice.rs | 15 +-- .../src/result_validation/mod.rs | 28 +++-- .../src/result_validation/spec.rs | 19 +++- .../src/result_validation/units.rs | 45 ++++++++ crates/packvium-core/src/sequence.rs | 42 ++++--- crates/packvium-core/src/solvers/blocks.rs | 76 +++++++++++-- crates/packvium-core/src/solvers/extreme.rs | 57 ++++++++-- crates/packvium-core/src/solvers/portfolio.rs | 18 ++- crates/packvium-core/src/validation.rs | 35 ++---- docs/GUARANTEES.md | 7 +- docs/PUBLIC-API.md | 8 ++ 29 files changed, 725 insertions(+), 126 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 diff --git a/.github/DISCUSSION_TEMPLATE/ideas.yml b/.github/DISCUSSION_TEMPLATE/ideas.yml new file mode 100644 index 0000000..1bd9af9 --- /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-native-rust" + 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..6ed5d12 --- /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-native-rust 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..6aa24ba --- /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-native-rust 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..1a949f3 --- /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: 7 + 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-native/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..9a99c8f --- /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-native/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-native/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..3f11eee --- /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: 7 + 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..d39348c --- /dev/null +++ b/.github/workflows/rc.yml @@ -0,0 +1,47 @@ +name: rc + +# A pre-release tag (`v1.9.0-rc.1`) is checked against every version this repository +# declares and its changelog, exactly as `release.yml` does, and nothing is built or +# published. The native packages (`packvium-native-rust` on PyPI, `@packvium/native*` on +# npm) are not yet published to production at all; an RC channel for them is added in the +# change that gives them their production Trusted Publishers. There is no GitHub Release. + +on: + push: + tags: ["v*-*"] + +permissions: + contents: read + +jobs: + verify-tag: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + # The tag and every packaged version must agree. Without this, `git tag v0.2.0` on a + # tree that still says 0.1.0 publishes 0.1.0 under a name that claims otherwise, and the + # mistake is only visible after it is public and immutable. + - name: The tag must match every version this repository publishes + run: | + python3 - "${GITHUB_REF_NAME#v}" <<'PY' + import json, sys, tomllib + from pathlib import Path + tagged = sys.argv[1] + versions = { + "Cargo.toml": tomllib.loads(Path("Cargo.toml").read_text())["workspace"]["package"]["version"], + "bindings/python/pyproject.toml": tomllib.loads(Path("bindings/python/pyproject.toml").read_text())["project"]["version"], + } + for manifest in ["bindings/node/package.json", *map(str, sorted(Path("bindings/node/npm").glob("*/package.json")))]: + versions[manifest] = json.loads(Path(manifest).read_text())["version"] + wrong = {path: found for path, found in versions.items() if found != tagged} + for path, found in wrong.items(): + print(f"{path} declares {found}, the tag says {tagged}", file=sys.stderr) + raise SystemExit(1 if wrong else 0) + PY + - 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 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 7bda9c1..50e0d53 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -13,9 +13,11 @@ name: release # `npm publish` allowed. # GitHub: environments named `pypi` and `npm`, 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 bb3e573..8813c74 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,26 +7,20 @@ project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [1.8.0] -The first published release of the compiled engines. Each binary is built from the Rust -source in this repository at the tagged commit, run on the platform it names, and attested. -The engine inside is the 1.8.0 core. +The first release of the compiled engines. Each binary is built from the Rust source in this +repository at the tagged commit, tested on the platform it names, and attested. The engine +inside is the 1.8.0 core. ### Added -- **`packvium-native-rust` wheels**, one `abi3-py39` wheel each for Linux (manylinux_2_28, - x86_64 and aarch64), macOS (arm64 and x86_64) and Windows (x86_64). Every wheel is - installed into a clean CPython 3.9 and 3.14 and solves a request before it is published. - It is the backend the `packvium-native` selector's `native` extra installs; that selector is - not on PyPI yet. -- **`@packvium/native`** with four platform packages: `darwin-arm64`, `darwin-x64`, - `linux-x64-gnu` and `win32-x64-msvc`. npm installs the one matching the host as an - optional dependency. The loader names every binary it can load by a literal specifier and - refuses a binary from another release. - **The C library** — `libpackvium_ffi` for Linux (x86_64, aarch64) and macOS (arm64, - x86_64), `packvium_ffi.dll` for Windows (x86_64) — attached to the GitHub Release with - `packvium.h` and `SHA256SUMS.txt`. + x86_64), `packvium_ffi.dll` for Windows (x86_64) — on the GitHub Release with `packvium.h` + and `SHA256SUMS.txt`. +- **`packvium-native-rust` abi3-py39 wheels** for the same five targets, each installed into a + clean CPython 3.9 and 3.14 and run before upload. +- **`@packvium/native`** with four platform packages (`darwin-arm64`, `darwin-x64`, + `linux-x64-gnu`, `win32-x64-msvc`); its loader names every binary by a literal specifier and + refuses one from another release. -## Before 1.8.0 - -No compiled engine was published. The Python selector and `@packvium/engine` answered from -their pure implementations, which give the same results. +The wheels and npm packages reach PyPI and npm only once their Trusted Publishers exist; until +then the release carries the C library alone. diff --git a/CITATION.cff b/CITATION.cff index c412f84..9e94698 100644 --- a/CITATION.cff +++ b/CITATION.cff @@ -22,3 +22,5 @@ keywords: - packing-algorithm - logistics - deterministic + - box-packing + - load-planning diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index e461d49..d1c04ce 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -53,3 +53,24 @@ in a change that says so. Include the platform, the package and version you installed, and the request that reproduces it. 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/bindings/python/pyproject.toml b/bindings/python/pyproject.toml index 2cbee08..7bcb4b4 100644 --- a/bindings/python/pyproject.toml +++ b/bindings/python/pyproject.toml @@ -9,7 +9,7 @@ requires-python = ">=3.9" description = "Compiled Rust backend for Packvium, consumed by the packvium-native selector" readme = "README.md" license = "MIT" -keywords = ["3d-bin-packing", "bin-packing", "3d-packing", "cartonization", "container-loading", "pallet-packing", "truck-loading", "packing-algorithm", "logistics", "deterministic"] +keywords = ["3d-bin-packing", "bin-packing", "3d-packing", "cartonization", "container-loading", "pallet-packing", "truck-loading", "packing-algorithm", "logistics", "deterministic", "box-packing", "load-planning"] authors = [{name = "Packvium contributors"}] [project.urls] diff --git a/codemeta.json b/codemeta.json index 07b15b0..ad216af 100644 --- a/codemeta.json +++ b/codemeta.json @@ -26,6 +26,8 @@ "truck-loading", "packing-algorithm", "logistics", - "deterministic" + "deterministic", + "box-packing", + "load-planning" ] } diff --git a/crates/packvium-core/src/contact_graph.rs b/crates/packvium-core/src/contact_graph.rs index 9ff5ec9..4fc1896 100644 --- a/crates/packvium-core/src/contact_graph.rs +++ b/crates/packvium-core/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/crates/packvium-core/src/model.rs b/crates/packvium-core/src/model.rs index be91110..f5087b6 100644 --- a/crates/packvium-core/src/model.rs +++ b/crates/packvium-core/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], diff --git a/crates/packvium-core/src/rebalance.rs b/crates/packvium-core/src/rebalance.rs index 949518c..d3c92c0 100644 --- a/crates/packvium-core/src/rebalance.rs +++ b/crates/packvium-core/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/crates/packvium-core/src/request_errors.rs b/crates/packvium-core/src/request_errors.rs index a6780c5..f7964d4 100644 --- a/crates/packvium-core/src/request_errors.rs +++ b/crates/packvium-core/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/crates/packvium-core/src/result_validation/json.rs b/crates/packvium-core/src/result_validation/json.rs index 19b906e..4d699c8 100644 --- a/crates/packvium-core/src/result_validation/json.rs +++ b/crates/packvium-core/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/crates/packvium-core/src/result_validation/lattice.rs b/crates/packvium-core/src/result_validation/lattice.rs index 720e005..2ac9beb 100644 --- a/crates/packvium-core/src/result_validation/lattice.rs +++ b/crates/packvium-core/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/crates/packvium-core/src/result_validation/mod.rs b/crates/packvium-core/src/result_validation/mod.rs index c0af3e5..ae2b7fe 100644 --- a/crates/packvium-core/src/result_validation/mod.rs +++ b/crates/packvium-core/src/result_validation/mod.rs @@ -33,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)] @@ -189,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)?; @@ -232,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 { diff --git a/crates/packvium-core/src/result_validation/spec.rs b/crates/packvium-core/src/result_validation/spec.rs index 71b10d6..51e8d7c 100644 --- a/crates/packvium-core/src/result_validation/spec.rs +++ b/crates/packvium-core/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/crates/packvium-core/src/result_validation/units.rs b/crates/packvium-core/src/result_validation/units.rs index 1de71c7..9392cdd 100644 --- a/crates/packvium-core/src/result_validation/units.rs +++ b/crates/packvium-core/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/crates/packvium-core/src/sequence.rs b/crates/packvium-core/src/sequence.rs index fc961e4..8e055bf 100644 --- a/crates/packvium-core/src/sequence.rs +++ b/crates/packvium-core/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/crates/packvium-core/src/solvers/blocks.rs b/crates/packvium-core/src/solvers/blocks.rs index 6bd8d1e..8a50586 100644 --- a/crates/packvium-core/src/solvers/blocks.rs +++ b/crates/packvium-core/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, @@ -1046,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/crates/packvium-core/src/solvers/extreme.rs b/crates/packvium-core/src/solvers/extreme.rs index 18442e2..1afa97e 100644 --- a/crates/packvium-core/src/solvers/extreme.rs +++ b/crates/packvium-core/src/solvers/extreme.rs @@ -574,6 +574,7 @@ 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() || deadline.effort_stops(request, metrics)) { @@ -672,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 { @@ -691,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)) @@ -1393,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); } @@ -2007,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 diff --git a/crates/packvium-core/src/solvers/portfolio.rs b/crates/packvium-core/src/solvers/portfolio.rs index 770c90f..253b513 100644 --- a/crates/packvium-core/src/solvers/portfolio.rs +++ b/crates/packvium-core/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/crates/packvium-core/src/validation.rs b/crates/packvium-core/src/validation.rs index bb2b09b..065574d 100644 --- a/crates/packvium-core/src/validation.rs +++ b/crates/packvium-core/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/docs/GUARANTEES.md b/docs/GUARANTEES.md index 98526d1..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 diff --git a/docs/PUBLIC-API.md b/docs/PUBLIC-API.md index f0762e8..0f4fa85 100644 --- a/docs/PUBLIC-API.md +++ b/docs/PUBLIC-API.md @@ -755,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`.