From 1559b2c61bb2c7d1d07dfc2426dfdc9c955b88c4 Mon Sep 17 00:00:00 2001 From: Anton Date: Mon, 16 Nov 2026 11:54:47 -0500 Subject: [PATCH] chore(release): 1.11.0 --- .github/DISCUSSION_TEMPLATE/q-a.yml | 2 +- .github/DISCUSSION_TEMPLATE/show-and-tell.yml | 2 +- .github/ISSUE_TEMPLATE/bug_report.yml | 6 +- .github/ISSUE_TEMPLATE/config.yml | 4 +- .github/ISSUE_TEMPLATE/feature_request.yml | 2 +- .github/workflows/rc.yml | 2 +- CHANGELOG.md | 40 + CITATION.cff | 4 +- Cargo.toml | 4 +- README.md | 225 ++--- codemeta.json | 6 +- docs/COMMERCE-API.md | 22 +- docs/GUARANTEES.md | 2 +- docs/UNITS-AND-NUMERICS.md | 2 + examples/checkout.rs | 251 ++++++ examples/fulfilment.rs | 322 +++++++ src/api.rs | 277 ++++-- src/billing.rs | 56 ++ src/bounds.rs | 820 +++++++++++++++++- src/commerce/document.rs | 9 +- src/commerce/mod.rs | 26 +- src/commerce/rating.rs | 87 +- src/contact_graph.rs | 127 ++- src/fixed.rs | 2 +- src/hull.rs | 7 + src/lib.rs | 6 +- src/loads.rs | 111 +++ src/model.rs | 238 ++++- src/pallet_overhang.rs | 34 +- src/rebalance.rs | 3 +- src/request_errors.rs | 137 ++- src/result_validation/accounting.rs | 7 +- src/result_validation/bound.rs | 467 +++++++++- src/result_validation/container.rs | 56 +- src/result_validation/json.rs | 74 +- src/result_validation/num.rs | 20 +- src/result_validation/objective.rs | 19 +- src/result_validation/spec.rs | 32 +- src/result_validation/stacking.rs | 107 ++- src/revisions.rs | 14 +- src/sequence.rs | 287 +++++- src/solvers/blocks.rs | 2 +- src/solvers/exact.rs | 52 +- src/solvers/extreme.rs | 226 +---- src/solvers/grid.rs | 22 +- src/solvers/mod.rs | 2 +- src/units.rs | 305 +++++-- src/validation.rs | 1 + tests/bottom_gusset.rs | 326 +++++++ tests/commerce_document.rs | 19 + tests/commerce_guards.rs | 162 +++- tests/fixed_placements.rs | 1 + tests/flat_bag.rs | 1 + tests/gusseted_bag.rs | 8 +- tests/measure_parsing.rs | 67 ++ tests/rate_table_ceiling.rs | 115 +++ tests/registry_and_nested.rs | 1 + tests/request_errors.rs | 91 ++ tests/result_validation_edges.rs | 53 ++ tests/route_removal_order.rs | 66 ++ tests/stock_cut_index.rs | 28 + tests/support/mod.rs | 1 + 62 files changed, 4687 insertions(+), 781 deletions(-) create mode 100644 examples/checkout.rs create mode 100644 examples/fulfilment.rs create mode 100644 src/billing.rs create mode 100644 src/loads.rs create mode 100644 tests/bottom_gusset.rs create mode 100644 tests/rate_table_ceiling.rs create mode 100644 tests/route_removal_order.rs diff --git a/.github/DISCUSSION_TEMPLATE/q-a.yml b/.github/DISCUSSION_TEMPLATE/q-a.yml index c370b93..ec822e9 100644 --- a/.github/DISCUSSION_TEMPLATE/q-a.yml +++ b/.github/DISCUSSION_TEMPLATE/q-a.yml @@ -10,7 +10,7 @@ body: id: package-version attributes: label: Package and version - placeholder: "packvium 1.10.0 (Rust)" + placeholder: "packvium 1.11.0 (Rust)" validations: required: true - type: textarea diff --git a/.github/DISCUSSION_TEMPLATE/show-and-tell.yml b/.github/DISCUSSION_TEMPLATE/show-and-tell.yml index 36db3d7..2614169 100644 --- a/.github/DISCUSSION_TEMPLATE/show-and-tell.yml +++ b/.github/DISCUSSION_TEMPLATE/show-and-tell.yml @@ -16,7 +16,7 @@ body: id: package-version attributes: label: Package and version - placeholder: "packvium 1.10.0 (Rust)" + placeholder: "packvium 1.11.0 (Rust)" validations: required: false - type: textarea diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml index a3cf01d..881abe5 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.yml +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -33,8 +33,8 @@ body: id: version attributes: label: Package version - description: The exact version installed, for example 1.10.0. - placeholder: "1.10.0" + description: The exact version installed, for example 1.11.0. + placeholder: "1.11.0" validations: required: true - type: input @@ -101,5 +101,5 @@ body: 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. + - label: I read [docs/GUARANTEES.md](https://github.com/packvium/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 index f210780..90b9930 100644 --- a/.github/ISSUE_TEMPLATE/config.yml +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -1,10 +1,10 @@ blank_issues_enabled: false contact_links: - name: Question or help with a request - url: https://github.com/toxakara/packvium-rust/discussions/categories/q-a + url: https://github.com/packvium/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 + url: https://github.com/packvium/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 diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml index caffb54..80bc85c 100644 --- a/.github/ISSUE_TEMPLATE/feature_request.yml +++ b/.github/ISSUE_TEMPLATE/feature_request.yml @@ -29,7 +29,7 @@ body: id: version attributes: label: Package version - placeholder: "1.10.0" + placeholder: "1.11.0" validations: required: true - type: textarea diff --git a/.github/workflows/rc.yml b/.github/workflows/rc.yml index 3177216..b11a876 100644 --- a/.github/workflows/rc.yml +++ b/.github/workflows/rc.yml @@ -4,7 +4,7 @@ name: rc # 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" } +# packvium = { git = "https://github.com/packvium/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. diff --git a/CHANGELOG.md b/CHANGELOG.md index 4f1bcaa..1e129c4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,46 @@ 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.11.0] + +Bottom gussets and standing pouches, a certified bound for the shipping objectives, one money +ceiling, and one measure grammar. + +### Added + +- **`bottom_gusset_depth` and `orientation`** on `DeformableBoundary::GussetedBag`, with the new + `BagOrientation { Flat, Standing }`. `Container` gains `upright_frame`. A struct literal or a + full pattern must name the new fields. +- **`optimality.lower_bound` and the gap under `shipping_cost` and `lowest_landed_cost`** + (`bounds.rs`); the validator checks them. +- **`examples/checkout.rs` and `examples/fulfilment.rs`.** + +### Changed + +- **One money ceiling, 2^53 − 1:** a `rate_table` priced above it at its top bracket is refused + at admission, and a quote refuses an amount above it where it used to answer up to `i64::MAX` + and wrap past it. `RatingRejection::AmountOutOfRange` became `AmountAboveCeiling(i128)`. +- **Measures follow the shared grammar:** upper-case units (`"1 G"`) are read; `"100 millimeters"` + and `"1 -1/2"` are refused; `"-0 1/2"` is minus a half, not plus. `hull_vertices` holds at most + 32 points. +- **`effort_budget` limits and `tag_limits` written as `1000.0`** are the integers they equal. + +### Fixed + +- **A billed weight past `i64` wrapped into the cheapest bracket,** and an overflowing landed cost + was reported as a weight past the last bracket. +- **On wasm32, a JSON count of 2^32 truncated to 0** (`max_restarts`, `tag_limits`). It now + saturates. +- **The result validator could panic** sorting a crafted result with mixed-type values. + +### Performance + +- **The contact graph no longer buckets every box with the largest:** 961,792 candidate checks + fall to 10,672 with one pallet-wide box among 4,000. +- **The safe-removal search is no longer cubic.** +- **The plan beam scores each plan 1.4–2.2 times less often.** +- **The exact search's visited set is capped at 262,144 states.** + ## [1.10.0] Pallets may overhang their deck, mailers may have gussets, a hull turns 24 ways, every diff --git a/CITATION.cff b/CITATION.cff index 8a43300..e14e286 100644 --- a/CITATION.cff +++ b/CITATION.cff @@ -5,10 +5,10 @@ type: software authors: - name: "Packvium contributors" website: "https://packvium.com" -version: "1.10.0" +version: "1.11.0" license: MIT url: "https://packvium.com" -repository-code: "https://github.com/toxakara/packvium-rust" +repository-code: "https://github.com/packvium/packvium-rust" repository-artifact: "https://crates.io/crates/packvium" abstract: >- Deterministic 3D bin-packing and cartonization engine for pallets, containers, trucks and shipping cartons. Exact integer geometry, reproducible results. diff --git a/Cargo.toml b/Cargo.toml index 91347d5..65367ea 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,12 +1,12 @@ [package] name = "packvium" -version = "1.10.0" +version = "1.11.0" edition = "2024" rust-version = "1.88" license = "MIT" description = "Deterministic 3D bin-packing and cartonization engine for pallets, containers, trucks and shipping cartons. Exact integer geometry, reproducible results." readme = "README.md" -repository = "https://github.com/toxakara/packvium-rust" +repository = "https://github.com/packvium/packvium-rust" homepage = "https://packvium.com" documentation = "https://packvium.com/docs" keywords = ["3d-bin-packing", "bin-packing", "3d-packing", "cartonization", "container-loading"] diff --git a/README.md b/README.md index b12e083..5adc114 100644 --- a/README.md +++ b/README.md @@ -1,22 +1,21 @@ # Packvium for Rust -Deterministic 3D cartonization and rectangular bin packing with exact integer geometry. -No `unsafe` code. Five runtime dependencies: `serde`, `serde_json`, `sha2` (the digests that -chain plan revisions), `thiserror` and `web-time` (a clock that also works in WebAssembly). +Deterministic 3D bin packing and cartonization with exact integer geometry. No `unsafe` +code, and five runtime dependencies: `serde`, `serde_json`, `sha2` (the digests that chain +plan revisions), `thiserror` and `web-time` (a clock that also works in WebAssembly). Use it to pick the smallest carton for an order, build a pallet, load a shipping container, or load a truck within its axle ratings and delivery-stop order. Every answer comes back as coordinates and rotations for each item, with a reason for anything that did not fit. -Full documentation, the constraint reference and benchmarks live at -[packvium.com](https://packvium.com). - -> **Version 1.10.0 — the public API is frozen.** Field names, status codes and the +> **Version 1.11.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) +> Read [docs/GUARANTEES.md](https://github.com/packvium/packvium-rust/blob/main/docs/GUARANTEES.md) > before relying on a result. +## Install + ```sh cargo add packvium ``` @@ -25,13 +24,16 @@ or, in `Cargo.toml`: ```toml [dependencies] -packvium = "1.10" +packvium = "1.11" ``` +The package is `packvium` in `Cargo.toml` and the library is `packvium_core` in code. That +is the crate's own name, kept stable across releases. Rust 1.88 or newer (edition 2024). + ## Quick start -The crate speaks a JSON contract — one request in, one result out — the same contract every -Packvium package speaks, so a request built here packs the same way in Python, PHP or Node.js: +The crate speaks a JSON contract, one request in and one result out. It is the same contract +every Packvium package speaks, so a request built here packs the same way in Python, PHP or Node.js: ```rust fn main() -> Result<(), Box> { @@ -56,42 +58,34 @@ fn main() -> Result<(), Box> { } ``` -The package is `packvium` in `Cargo.toml`, and the library is `packvium_core` in code — the -crate's own name, kept stable across releases. - The result is JSON text. Read it with `serde_json` into your own `#[derive(Deserialize)]` -structs, naming only the fields you use; [`basic.rs`](https://github.com/toxakara/packvium-rust/blob/main/examples/basic.rs) +structs, naming only the fields you use; [`basic.rs`](https://github.com/packvium/packvium-rust/blob/main/examples/basic.rs) does exactly that. Every length and weight comes back as exact integer `ticks` beside a rendered decimal `value`: compute with the ticks, print the value. -Support is not required by default: `minimum_support_ratio` is 0, so an item may rest on -nothing above the container floor, and the result then says so in `warnings` -(`unsupported_placements: N placement(s) rest on nothing above the container floor; ...`). -To require support, set it above 0 — `"configuration": {"minimum_support_ratio": 0.75}` for three quarters of the base. +## Using it in your project -## Examples - -Runnable, each a single file you can read top to bottom: +Two examples are written the way application code is written, with your own product and +order types on one side and the library call in the middle. Start from the one closer to +what you are building. -```bash -cargo run --example basic -``` - -| File | What it shows | -| --- | --- | -| [`basic.rs`](https://github.com/toxakara/packvium-rust/blob/main/examples/basic.rs) | An order into a carton, read back into typed structs; an item that cannot fit, and why. | -| [`constraints.rs`](https://github.com/toxakara/packvium-rust/blob/main/examples/constraints.rs) | Rotations and keep-upright, stacking limits and top load, support ratio and incompatible tags — each shown with and without the rule — and a crate that fits a pallet only by overhanging its deck. | -| [`objectives.rs`](https://github.com/toxakara/packvium-rust/blob/main/examples/objectives.rs) | All seven objectives, the scenes where two of them pick different containers, the lower bound each result states, and a rate card priced in a declared currency. | -| [`units.rs`](https://github.com/toxakara/packvium-rust/blob/main/examples/units.rs) | What you can type (fractions, inches, pounds), why nothing is a float, and exact fits. | -| [`errors.rs`](https://github.com/toxakara/packvium-rust/blob/main/examples/errors.rs) | Branching on a refused request with `code()`, `reason()` and `field()`, and why an item that does not fit is not an error. | -| [`trucking.rs`](https://github.com/toxakara/packvium-rust/blob/main/examples/trucking.rs) | A delivery van: stops unloaded in route order through a named door, and axle loads kept inside their ratings. | -| [`nested.rs`](https://github.com/toxakara/packvium-rust/blob/main/examples/nested.rs) | Mugs and plates into cartons, cartons onto a pallet, with the typed `PackingRequest` API and `pack_nested`; then `pack_nested_with`, whose wider beam finds the carton set the pallet can take. | -| [`execution.rs`](https://github.com/toxakara/packvium-rust/blob/main/examples/execution.rs) | A result turned into a numbered work order, with a safe loading order computed from the placed geometry. | -| [`reproducibility.rs`](https://github.com/toxakara/packvium-rust/blob/main/examples/reproducibility.rs) | `effort_budget` against `time_limit_ms`: the same answer on every run and every machine. | -| [`shapes.rs`](https://github.com/toxakara/packvium-rust/blob/main/examples/shapes.rs) | Items that are not their box: complementary wedges sharing one crate as `convex_hull`, two copies of one wedge paired by a signed rotation (`-L-W+H`), a cushion that compresses under load until the crush limit refuses it, and a mailer that takes more books once it has side gussets. | -| [`commerce.rs`](https://github.com/toxakara/packvium-rust/blob/main/examples/commerce.rs) | Rate a shipment, apply an eligibility rule, and pin a catalog version. | -| [`artifacts.rs`](https://github.com/toxakara/packvium-rust/blob/main/examples/artifacts.rs) | Hand a result to a system with no engine: one document with the plan, geometry and the request that produced it, exported as CSV and a printable HTML work order — byte-identical to the other three engines. | -| [`revisions.rs`](https://github.com/toxakara/packvium-rust/blob/main/examples/revisions.rs) | Replan a half-loaded job: a missing item and a placement locked by its `placement_id`, recorded against the approved plan, a replan that keeps the locked item in place, and a hash-chained record that notices an edit — the same revision bytes as the other three engines; then a box cut to measure with a void-fill reserve, stocked at its cut size by the next revision. | +| You are building | Start from | What it does | +| --- | --- | --- | +| A checkout or cart service | [`checkout.rs`](https://github.com/packvium/packvium-rust/blob/main/examples/checkout.rs) | Maps a cart onto a request, picks the cheapest cartons, and reads the parcels back into a struct a handler can return. Two functions hold everything Packvium-specific. | +| A warehouse or fulfilment job | [`fulfilment.rs`](https://github.com/packvium/packvium-rust/blob/main/examples/fulfilment.rs) | Runs an order from paid to labelled: a shipping rule picks the carrier service, the order is packed under its constraints, `validate_json` checks the plan, and every parcel is priced from a pinned tariff. | +| An HTTP endpoint that packs | [`errors.rs`](https://github.com/packvium/packvium-rust/blob/main/examples/errors.rs) | Branches on a refused request by `code()`, `reason()` and `field()`. | +| A dock or driver screen | [`execution.rs`](https://github.com/packvium/packvium-rust/blob/main/examples/execution.rs), [`trucking.rs`](https://github.com/packvium/packvium-rust/blob/main/examples/trucking.rs) | Turns a result into a numbered work order, and loads a van by stop and axle rating. | + +Rules that most projects need on day one: + +- An item that does not fit is not an error. The result lists it in `unpacked_items` with a + reason, and everything else is still packed. +- Support is not required by default: `minimum_support_ratio` is 0, so an item may rest on + nothing above the container floor, and the result then says so in `warnings` + (`unsupported_placements: N placement(s) rest on nothing above the container floor; ...`). + To require support, set it above 0: `"configuration": {"minimum_support_ratio": 0.75}` for three quarters of the base. +- Set an `effort_budget` for any answer you store or show twice. See + [Getting the same answer every time](#getting-the-same-answer-every-time). ## Errors @@ -153,7 +147,7 @@ for issue in &issues { It shares no code with the solvers, so it judges any engine's result, not only this crate's. A result without the documented shape is `Err(MalformedResult { kind, message })`. -## Determinism +## Getting the same answer every time The same request gives the same placements: the only randomness is seeded from the request's `seed`, and no result depends on hash-map order. The one way to lose that is the wall clock: `time_limit_ms` stops the search when a @@ -171,71 +165,97 @@ of the request, so a different seed is a different, equally reproducible request exactly its budget reads `complete`, and `termination.any_start_truncated` says whether the budget cut a start that might have won. -## What it does +## Examples + +Runnable, each a single file you can read top to bottom: + +```bash +cargo run --example basic +``` -- **Exact arithmetic.** Length is measured in ticks of 1/16000 mm and weight in 1/8 µg. - No coordinate is ever a float, so no placement decision depends on rounding. -- **Real constraints.** Weight and payload limits, permitted rotations, keep-upright, - floor-only, non-stackable, stack-count and top-load limits, minimum support ratio, tag +| File | What it shows | +| --- | --- | +| [`checkout.rs`](https://github.com/packvium/packvium-rust/blob/main/examples/checkout.rs) | A shop's checkout: a cart mapped onto a request and the parcels read back into typed structs, with the cheapest cartons chosen. | +| [`fulfilment.rs`](https://github.com/packvium/packvium-rust/blob/main/examples/fulfilment.rs) | An order from paid to labelled: a policy rule picks the service, the order is packed under its constraints, `validate_json` checks the plan, and each parcel is priced from a pinned tariff. | +| [`basic.rs`](https://github.com/packvium/packvium-rust/blob/main/examples/basic.rs) | An order into a carton, read back into typed structs; an item that cannot fit, and why. | +| [`constraints.rs`](https://github.com/packvium/packvium-rust/blob/main/examples/constraints.rs) | Rotations and keep-upright, stacking limits and top load, support ratio and incompatible tags, each shown with and without the rule, and a crate that fits a pallet only by overhanging its deck. | +| [`objectives.rs`](https://github.com/packvium/packvium-rust/blob/main/examples/objectives.rs) | All seven objectives, the scenes where two of them pick different containers, the lower bound each result states, and a rate card priced in a declared currency. | +| [`units.rs`](https://github.com/packvium/packvium-rust/blob/main/examples/units.rs) | What you can type (fractions, inches, pounds), why nothing is a float, and exact fits. | +| [`errors.rs`](https://github.com/packvium/packvium-rust/blob/main/examples/errors.rs) | Branching on a refused request with `code()`, `reason()` and `field()`, and why an item that does not fit is not an error. | +| [`trucking.rs`](https://github.com/packvium/packvium-rust/blob/main/examples/trucking.rs) | A delivery van: stops unloaded in route order through a named door, and axle loads kept inside their ratings. | +| [`nested.rs`](https://github.com/packvium/packvium-rust/blob/main/examples/nested.rs) | Mugs and plates into cartons, cartons onto a pallet, with the typed `PackingRequest` API and `pack_nested`; then `pack_nested_with`, whose wider beam finds the carton set the pallet can take. | +| [`execution.rs`](https://github.com/packvium/packvium-rust/blob/main/examples/execution.rs) | A result turned into a numbered work order, with a safe loading order computed from the placed geometry. | +| [`reproducibility.rs`](https://github.com/packvium/packvium-rust/blob/main/examples/reproducibility.rs) | `effort_budget` against `time_limit_ms`: the same answer on every run and every machine. | +| [`shapes.rs`](https://github.com/packvium/packvium-rust/blob/main/examples/shapes.rs) | Items that are not their box: complementary wedges sharing one crate as `convex_hull`, two copies of one wedge paired by a signed rotation (`-L-W+H`), a cushion that compresses under load until the crush limit refuses it, and a mailer that takes more books once it has side gussets. | +| [`commerce.rs`](https://github.com/packvium/packvium-rust/blob/main/examples/commerce.rs) | Rate a shipment, apply an eligibility rule, and pin a catalog version. | +| [`artifacts.rs`](https://github.com/packvium/packvium-rust/blob/main/examples/artifacts.rs) | Hand a result to a system with no engine: one document with the plan, geometry and the request that produced it, exported as CSV and a printable HTML work order. Byte-identical to the other three engines. | +| [`revisions.rs`](https://github.com/packvium/packvium-rust/blob/main/examples/revisions.rs) | Replan a half-loaded job: a missing item and a placement locked by its `placement_id`, recorded against the approved plan, a replan that keeps the locked item in place, and a hash-chained record that notices an edit (the same revision bytes as the other three engines); then a box cut to measure with a void-fill reserve, stocked at its cut size by the next revision. | + +## What it covers + +- Exact arithmetic. Length is measured in ticks of 1/16000 mm and weight in 1/8 µg, so no + coordinate is a float and no placement depends on rounding. +- Constraints: weight and payload limits, permitted rotations, keep-upright, floor-only, + non-stackable, stack-count and top-load limits, minimum support ratio, tag incompatibility, clearance and rectangular obstacles; a pallet load that may overhang its deck by `pallet_overhang_limit`; flat and gusseted mailer bags; and for vehicles, route order by `stop_index`, unloading doors by `access_directions`, and two-axle load limits. -- **Items that are not boxes.** A `convex_hull` item packs by its vertices and turns any of - the 24 proper rotations, so a chiral part can pair with its own half turn; a compressible +- Items that are not boxes. A `convex_hull` item packs by its vertices and turns any of the + 24 proper rotations, so a chiral part can pair with its own half turn; a compressible item yields under load until its crush limit. -- **Seven objectives.** Fewest containers, packaging cost, carrier-billable weight, carrier - rate cards, open-dimension height, value kept and volume loaded — each a vector of exact - integers. -- **A solver portfolio, not one algorithm.** Regular-grid, layer, extreme-point, - 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 every objective but `shipping_cost` and +- Seven objectives: fewest containers, packaging cost, carrier-billable weight, carrier + rate cards, open-dimension height, value kept and volume loaded. Each is a vector of + exact integers. +- Several solvers, chosen by problem shape and profile: regular-grid, layer, extreme-point, + maximal-space and bounded exact search. +- Every solution is re-validated by logic independent of the search. Unplaced items come + back with a reason code. +- A proof, or the distance to one. Under every objective but `shipping_cost` and `lowest_landed_cost`, a result states `optimality.lower_bound` (not for a made-to-measure container, nor for a bound past `2^53 - 1`). 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 - that cannot pack everything. `pack_nested_with(&request, k)` carries the `k` best chains - from level to level, so the outermost level decides between carton sets. -- **In-process extension points.** `SolverRegistry` accepts your own `PlacementConstraint`, - `CandidateScorer`, `ItemOrderStrategy` or `Solver` for a typed `PackingRequest`. They live in - your process only: nothing about them travels in the JSON contract, so a rule every caller - must honour belongs in the request as data instead. -- **Every placement has an id.** `placement_id` is the canonical JSON of its container, +- Multi-container and nested packing. 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 that cannot pack everything. `pack_nested_with(&request, k)` carries + the `k` best chains from level to level, so the outermost level decides between carton + sets. +- In-process extension points. `SolverRegistry` accepts your own `PlacementConstraint`, + `CandidateScorer`, `ItemOrderStrategy` or `Solver` for a typed `PackingRequest`. They + live in your process only: nothing about them travels in the JSON contract, so a rule + every caller must honour belongs in the request as data instead. +- Every placement has an id. `placement_id` is the canonical JSON of its container, position, item type and orientation, so a fixed placement or a revision's lock can name exactly the box it means. -- **Money in a declared currency.** A request may carry `currency`, and each rate card its - own `rate_table.currency`, which must agree; the result echoes it. It never enters the - score. -- **Work orders and portable artifacts.** `execution::build_plan_json` turns a result into - an operator's step list, with the loading order from `safe_loading_order`. +- Money in a declared currency. A request may carry `currency`, and each rate card its own + `rate_table.currency`, which must agree; the result echoes it. It never enters the score. +- Work orders and portable artifacts. `execution::build_plan_json` turns a result into an + operator's step list, with the loading order from `safe_loading_order`. `artifacts::build_artifact_json` wraps that plan with geometry, display values and the request that produced it, and `artifact_exports` writes it as canonical JSON, CSV or a - self-contained HTML work order, byte for byte what the Python, PHP and JavaScript packages - write. -- **Items already in place, and replanning around them.** A request's `fixed_placements` pins - items to known positions before the solve: they keep their place, carry weight and support, - and come back marked `fixed: true`. `revisions` records what changed on the dock — a missing - item, a substituted container, a lock, a verification — as an append-only chain linked by - SHA-256, and derives the request the next plan solves; a box already cut to measure comes - back as a stock container at its cut size, so the replan does not cut it again. -- **`#![forbid(unsafe_code)]`.** The engine itself contains no `unsafe`. + self-contained HTML work order, byte for byte what the Python, PHP and JavaScript + packages write. +- Items already in place, and replanning around them. A request's `fixed_placements` pins + items to known positions before the solve: they keep their place, carry weight and + support, and come back marked `fixed: true`. `revisions` records what changed on the dock + (a missing item, a substituted container, a lock, a verification) as an append-only chain + linked by SHA-256, and derives the request the next plan solves; a box already cut to + measure comes back as a stock container at its cut size, so the replan does not cut it + again. +- Carrier quotes, shipping rules and catalog versions through `packvium_core::commerce`. +- `#![forbid(unsafe_code)]`. The engine itself contains no `unsafe`. ## Documentation | Document | Covers | | --- | --- | -| [docs/GUARANTEES.md](https://github.com/toxakara/packvium-rust/blob/main/docs/GUARANTEES.md) | What is promised and what is not. Start here. | -| [docs/PUBLIC-API.md](https://github.com/toxakara/packvium-rust/blob/main/docs/PUBLIC-API.md) | Inputs, outputs and status semantics. | -| [docs/UNITS-AND-NUMERICS.md](https://github.com/toxakara/packvium-rust/blob/main/docs/UNITS-AND-NUMERICS.md) | Units, accepted input forms, rounding policy. | -| [docs/COMMERCE-API.md](https://github.com/toxakara/packvium-rust/blob/main/docs/COMMERCE-API.md) | Carrier rating, eligibility rules and catalog versions. | - -## Requirements +| [docs/GUARANTEES.md](https://github.com/packvium/packvium-rust/blob/main/docs/GUARANTEES.md) | What is promised and what is not. Start here. | +| [docs/PUBLIC-API.md](https://github.com/packvium/packvium-rust/blob/main/docs/PUBLIC-API.md) | Inputs, outputs and status semantics. | +| [docs/UNITS-AND-NUMERICS.md](https://github.com/packvium/packvium-rust/blob/main/docs/UNITS-AND-NUMERICS.md) | Units, accepted input forms, rounding policy. | +| [docs/COMMERCE-API.md](https://github.com/packvium/packvium-rust/blob/main/docs/COMMERCE-API.md) | Carrier rating, eligibility rules and catalog versions. | -Rust 1.88 or newer (edition 2024). +The constraint reference and the benchmarks are at [packvium.com](https://packvium.com). ## The Packvium family @@ -245,37 +265,34 @@ engine's answer is independently validated, and none may score below the agreed a fixture. Engines may return different, equally valid arrangements for the same request. Pick the package for your stack; mixing them in one system is safe. -Documentation, the constraint reference and the benchmarks are at -[packvium.com](https://packvium.com). - | Package | Install | Source | | --- | --- | --- | -| 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.10"` | [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) | -| Python native selector — `packvium-native` | from source until the native wheels ship | [packvium-python-adapter](https://github.com/toxakara/packvium-python-adapter) | +| Python — [`packvium`](https://pypi.org/project/packvium/) | `pip install packvium` | [packvium-python](https://github.com/packvium/packvium-python) | +| PHP — [`packvium/packvium`](https://packagist.org/packages/packvium/packvium) | `composer require packvium/packvium` | [packvium-php](https://github.com/packvium/packvium-php) | +| Rust — [`packvium`](https://crates.io/crates/packvium) | `packvium = "1.11"` | [packvium-rust](https://github.com/packvium/packvium-rust) | +| Node.js — [`@packvium/engine`](https://www.npmjs.com/package/@packvium/engine) | `npm install @packvium/engine` | [packvium-node](https://github.com/packvium/packvium-node) | +| Browser / WebAssembly — [`@packvium/browser`](https://www.npmjs.com/package/@packvium/browser) | `npm install @packvium/browser` | [packvium-wasm](https://github.com/packvium/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/packvium/packvium-php-bridge) | +| Python native selector — `packvium-native` | from source until the native wheels ship | [packvium-python-adapter](https://github.com/packvium/packvium-python-adapter) | ## Contributing -See [CONTRIBUTING.md](https://github.com/toxakara/packvium-rust/blob/main/CONTRIBUTING.md). +See [CONTRIBUTING.md](https://github.com/packvium/packvium-rust/blob/main/CONTRIBUTING.md). Security reports go through the process in -[SECURITY.md](https://github.com/toxakara/packvium-rust/blob/main/SECURITY.md), not public issues. +[SECURITY.md](https://github.com/packvium/packvium-rust/blob/main/SECURITY.md), not public issues. ## Citation If Packvium supports your research, cite it as software. GitHub's **Cite this repository** -button reads [`CITATION.cff`](https://github.com/toxakara/packvium-rust/blob/main/CITATION.cff), and -[`codemeta.json`](https://github.com/toxakara/packvium-rust/blob/main/codemeta.json) carries the same record in +button reads [`CITATION.cff`](https://github.com/packvium/packvium-rust/blob/main/CITATION.cff), and +[`codemeta.json`](https://github.com/packvium/packvium-rust/blob/main/codemeta.json) carries the same record in CodeMeta form. ```bibtex @software{packvium_rust, author = {{Packvium contributors}}, title = {Packvium for Rust}, - version = {1.10.0}, + version = {1.11.0}, license = {MIT}, url = {https://packvium.com} } @@ -283,4 +300,4 @@ CodeMeta form. ## License -MIT. See [LICENSE](https://github.com/toxakara/packvium-rust/blob/main/LICENSE). +MIT. See [LICENSE](https://github.com/packvium/packvium-rust/blob/main/LICENSE). diff --git a/codemeta.json b/codemeta.json index 880ef78..4dc950f 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.10.0", + "version": "1.11.0", "license": "https://spdx.org/licenses/MIT", "author": [ { @@ -13,8 +13,8 @@ } ], "url": "https://packvium.com", - "codeRepository": "https://github.com/toxakara/packvium-rust", - "issueTracker": "https://github.com/toxakara/packvium-rust/issues", + "codeRepository": "https://github.com/packvium/packvium-rust", + "issueTracker": "https://github.com/packvium/packvium-rust/issues", "programmingLanguage": "Rust", "keywords": [ "3d-bin-packing", diff --git a/docs/COMMERCE-API.md b/docs/COMMERCE-API.md index 6f4e4b7..44a835e 100644 --- a/docs/COMMERCE-API.md +++ b/docs/COMMERCE-API.md @@ -417,9 +417,19 @@ existing rule-pool storage. difference — `JSON.parse` gives the same `Number` for `1` and `1.0` — so this is the one shape where the four implementations cannot be made to agree, and the contract resolves it by requiring callers not to emit it. No fixture uses one. -- JavaScript refuses, rather than rounds, a quote whose components exceed - `Number.MAX_SAFE_INTEGER`. The arithmetic itself runs in `BigInt`, so nothing drifts - through a double; what cannot be done is *reporting* a value a JSON number cannot hold - exactly. Python has no such ceiling, Rust takes every product in `i128`, and PHP falls - back to decimal-string arithmetic. The bound is far above any real tariff — nine - quadrillion minor currency units. +- Every engine refuses, rather than rounds, a quote that reports an amount above + `2^53 - 1` (`9007199254740991`): `dimensional_weight_g`, `billed_weight_g`, + `base_charge_minor`, `fuel_surcharge_minor`, any accessorial charge, or `total_minor`, + checked in that order. The arithmetic itself is exact in all four -- unbounded integers + in Python, `BigInt` in JavaScript, `i128` in Rust, decimal strings in PHP -- so nothing + drifts or wraps on the way; what cannot be done is *reporting* a value a JSON number + cannot hold exactly. The refusal is the input error of the language, with the message + `quote amount {value} is above 9007199254740991 and cannot be represented exactly`. + Until 1.11 only JavaScript refused; Python answered without a ceiling, and Rust and PHP + answered up to `2^63 - 1`. The bound is far above any real tariff — nine quadrillion + minor currency units. +- JavaScript refuses an input integer above `2^53 - 1` with `expected an exact integer`: + `JSON.parse` has already rounded it, so no exact arithmetic after that can recover the + value the caller sent. Python computes from such an input exactly and PHP and Rust read it + up to `2^63 - 1`, so an engine may answer a quote JavaScript refuses; callers should not + send one. No fixture does. diff --git a/docs/GUARANTEES.md b/docs/GUARANTEES.md index f0b05e9..929e28f 100644 --- a/docs/GUARANTEES.md +++ b/docs/GUARANTEES.md @@ -61,7 +61,7 @@ silently — if you need them, they belong in your own layer above this library. ## Status of this release -Version `1.10.0` freezes the public API. Field names, status codes, the objective +Version `1.11.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/UNITS-AND-NUMERICS.md b/docs/UNITS-AND-NUMERICS.md index c09c8e8..624c9d0 100644 --- a/docs/UNITS-AND-NUMERICS.md +++ b/docs/UNITS-AND-NUMERICS.md @@ -10,6 +10,8 @@ One internal length tick is `1/16000 mm`. Accepted inputs include integers, decimal strings, fractions (`3/16`) and mixed fractions (`12 3/8`), with `mm`, `cm`, `m`, `in`, `ft`, and ticks. A binary float with a fractional part is intentionally rejected by the Python API, by `Length` and `Weight` alike (`TypeError`); an integral float such as `100.0` is exact, and is what JavaScript sends for `100`, so it is accepted as that integer. PHP type declarations accept only integer/string/structured values. +The written grammar is one and the same in all four engines (1.11): an optional sign, ASCII digits, and an optional fraction part with at least one digit on each side of the point and at most 18 after it; or a fraction `n/d`; or a mixed fraction `w n/d`. A unit suffix is matched ignoring ASCII case (`100 MM`, `1 KG`). Nothing else is a measure -- not `100.`, `.5`, `0x64`, `1e2`, `1_0`, nor digits outside ASCII -- and each is refused as `wrong_type`, `must be a measure`. Until 1.11 each language's own number parser decided the edge cases, and they disagreed. + ## Weight One weight tick is `1/8 microgram`, allowing exact common metric units and exact international avoirdupois conversions used by the package. diff --git a/examples/checkout.rs b/examples/checkout.rs new file mode 100644 index 0000000..0bae9f4 --- /dev/null +++ b/examples/checkout.rs @@ -0,0 +1,251 @@ +//! A shop's checkout: turn a cart into parcels. +//! +//! cargo run --example checkout +//! +//! This is the shape most projects start from. You already have product records and cart +//! lines as your own types; the engine wants a JSON request. So there are two small +//! functions between them: `to_request` maps your types onto the request, and `parcels` +//! reads the result back into a struct your handler can return. Everything +//! Packvium-specific lives in those two functions, and the rest of the service never sees +//! a tick or a placement. +//! +//! `pack_json` is a plain synchronous function over text, so it sits behind an axum or +//! actix handler, or inside a queue worker, without any setup. + +use std::collections::BTreeMap; + +use packvium_core::pack_json; +use serde::Deserialize; +use serde_json::{Value, json}; + +/// A row of your product table. Sizes in centimetres and weights in grams, as a shop +/// usually has them. +struct Product { + sku: &'static str, + size_cm: [u32; 3], + weight_g: u32, + this_side_up: bool, +} + +/// A carton on your packing bench, with what it costs you in cents. +struct Carton { + id: &'static str, + inner_cm: [u32; 3], + max_kg: u32, + cost_cents: u64, +} + +const PRODUCTS: [Product; 4] = [ + Product { + sku: "kettle", + size_cm: [24, 22, 26], + weight_g: 1300, + this_side_up: true, + }, + Product { + sku: "mug", + size_cm: [12, 9, 10], + weight_g: 350, + this_side_up: false, + }, + Product { + sku: "cookbook", + size_cm: [28, 22, 3], + weight_g: 900, + this_side_up: false, + }, + Product { + sku: "floor-lamp", + size_cm: [150, 30, 30], + weight_g: 4200, + this_side_up: false, + }, +]; + +const CARTONS: [Carton; 3] = [ + Carton { + id: "small", + inner_cm: [30, 25, 15], + max_kg: 5, + cost_cents: 45, + }, + Carton { + id: "medium", + inner_cm: [40, 30, 30], + max_kg: 12, + cost_cents: 80, + }, + Carton { + id: "large", + inner_cm: [60, 40, 40], + max_kg: 20, + cost_cents: 140, + }, +]; + +/// The part of a result this program reads. Unknown fields are ignored, so a result that +/// gains a field in a later release still deserializes. +#[derive(Deserialize)] +struct Outcome { + containers: Vec, + unpacked_items: Vec, +} + +#[derive(Deserialize)] +struct Packed { + container_type: String, + gross_weight: Measure, + placements: Vec, +} + +#[derive(Deserialize)] +struct Placement { + item_type: String, +} + +#[derive(Deserialize)] +struct Measure { + value: String, + unit: String, +} + +#[derive(Deserialize)] +struct Unpacked { + item_type: String, +} + +/// What the checkout page needs: one entry per parcel, and what fits no carton. +struct Parcel { + carton: String, + weight: String, + contents: BTreeMap, +} + +fn measures(edges: [u32; 3]) -> Value { + json!({ + "length": edges[0].to_string(), + "width": edges[1].to_string(), + "height": edges[2].to_string(), + }) +} + +fn product(sku: &str) -> &'static Product { + PRODUCTS + .iter() + .find(|product| product.sku == sku) + .expect("the cart names a known SKU") +} + +/// Your cart (SKU and quantity pairs) as a Packvium request. +fn to_request(cart: &[(&str, u32)]) -> Value { + let items: Vec = cart + .iter() + .map(|&(sku, quantity)| { + let product = product(sku); + json!({ + "id": sku, + "quantity": quantity, + "weight": format!("{} g", product.weight_g), + "keep_upright": product.this_side_up, + "dimensions": measures(product.size_cm), + }) + }) + .collect(); + let containers: Vec = CARTONS + .iter() + .map(|carton| { + json!({ + "id": carton.id, + "max_payload": format!("{} kg", carton.max_kg), + "cost_minor": carton.cost_cents, + "inner_dimensions": measures(carton.inner_cm), + }) + }) + .collect(); + json!({ + "units": { "length": "cm" }, + "configuration": { + // Pay as little as possible for cartons, after packing everything that fits. + "objective": "lowest_cost", + // Counted work decides where the search stops, so the same cart always gets the + // same parcels. The time limit is a fuse against a hang, not a search limit. + "effort_budget": { "max_candidates_evaluated": 200000 }, + "time_limit_ms": 60000 + }, + "items": items, + "containers": containers + }) +} + +/// The parcels to ship, and the SKUs that fit no carton you stock. +fn parcels(cart: &[(&str, u32)]) -> Result<(Vec, Vec), Box> { + let outcome: Outcome = serde_json::from_str(&pack_json(&to_request(cart).to_string())?)?; + let shipped = outcome + .containers + .into_iter() + .map(|packed| { + let mut contents = BTreeMap::new(); + for placement in packed.placements { + *contents.entry(placement.item_type).or_insert(0) += 1; + } + Parcel { + carton: packed.container_type, + // `value` is the exact weight rendered in `unit`; here that is whole grams. + weight: format!("{} {}", packed.gross_weight.value, packed.gross_weight.unit), + contents, + } + }) + .collect(); + // An item that fits nowhere is not an error. It comes back with a reason, and the rest + // of the cart is still packed. + let mut left_out: Vec = outcome + .unpacked_items + .into_iter() + .map(|unpacked| unpacked.item_type) + .collect(); + left_out.sort(); + left_out.dedup(); + Ok((shipped, left_out)) +} + +fn show(title: &str, cart: &[(&str, u32)]) -> Result<(), Box> { + let (shipped, left_out) = parcels(cart)?; + println!("\n{title}"); + let mut carton_cost = 0; + for (index, parcel) in shipped.iter().enumerate() { + let contents: Vec = parcel + .contents + .iter() + .map(|(sku, count)| format!("{count} x {sku}")) + .collect(); + println!( + " parcel {}: {:<6} {:>7} {}", + index + 1, + parcel.carton, + parcel.weight, + contents.join(", ") + ); + carton_cost += CARTONS + .iter() + .find(|carton| carton.id == parcel.carton) + .map_or(0, |carton| carton.cost_cents); + } + println!(" cartons cost {carton_cost} cents"); + for sku in left_out { + println!(" {sku} fits none of our cartons: ship it in its own packaging"); + } + Ok(()) +} + +fn main() -> Result<(), Box> { + show("a small order", &[("mug", 2), ("cookbook", 1)])?; + show( + "a bigger order", + &[("kettle", 4), ("mug", 6), ("cookbook", 4)], + )?; + show( + "an order with something oversized", + &[("floor-lamp", 1), ("mug", 4)], + )?; + Ok(()) +} diff --git a/examples/fulfilment.rs b/examples/fulfilment.rs new file mode 100644 index 0000000..35dcae0 --- /dev/null +++ b/examples/fulfilment.rs @@ -0,0 +1,322 @@ +//! From a paid order to labelled parcels: eligibility, packing, a second opinion, a price. +//! +//! cargo run --example fulfilment +//! +//! The checkout example maps a cart onto a request and reads the parcels back. A warehouse +//! needs more around that call, and this example wires the pieces in the order a fulfilment +//! job runs them: +//! +//! 1. `commerce::evaluate_policy_json` decides which carrier service the order may use. +//! 2. `pack_json` packs it, under the rules the goods come with. +//! 3. `validate_json` checks the plan against the request with code that shares nothing +//! with the solvers, so a parcel is never labelled on the solver's word alone. +//! 4. `commerce::quote_json` prices every parcel from the tariff version you pinned. +//! +//! Two kinds of trouble are kept apart on purpose. A request that is wrong (a quantity of +//! zero from a bad import) is `PackError::InvalidRequest`, and the job puts the order on +//! hold. An item that fits no carton is not an error: the rest of the order ships and the +//! item is handed to freight. + +use std::collections::BTreeMap; +use std::error::Error; + +use packvium_core::commerce::{evaluate_policy_json, quote_json}; +use packvium_core::{PackError, pack_json, validate_json}; +use serde_json::{Value, json}; + +/// Results carry exact integers: 16 000 length ticks to the millimetre, 8 000 000 weight +/// ticks to the gram. A carrier bills whole millimetres and grams, rounded up. +const TICKS_PER_MM: u64 = 16_000; +const TICKS_PER_GRAM: u64 = 8_000_000; + +struct Order { + id: &'static str, + zone: &'static str, + service: &'static str, + lines: &'static [(&'static str, u32)], +} + +/// What you publish: one tariff per carrier service, and the rules that say what may ship +/// how. You would load this from your own storage; a version's number is its position in +/// the list, so `tariff_version: 1` below always means the same prices. +fn commerce_document() -> Value { + json!({ + "tariffs": [ + { + "carrier_id": "postway", "service_id": "air", + "versions": [{ + "effective_at": 0, + "dimensional_weight_divisor": 5000, + "cost_per_dimensional_kg_minor": {"domestic": 520, "eu": 890}, + "minimum_charge_minor": 950, + "fuel_surcharge_permille": 140, + "accessorials": [] + }] + }, + { + "carrier_id": "postway", "service_id": "ground", + "versions": [{ + "effective_at": 0, + "dimensional_weight_divisor": 6000, + "cost_per_dimensional_kg_minor": {"domestic": 210, "eu": 380}, + "minimum_charge_minor": 590, + "fuel_surcharge_permille": 90, + "accessorials": [] + }] + } + ], + "policy_rules": [{ + "rule_id": "lithium-stays-on-the-ground", + "versions": [{ + "scope": "service", "action": "reject", "priority": 10, "effective_at": 0, + "reason": "lithium batteries do not fly with this carrier", + "predicates": [ + {"scope": "service", "field": "service", "operator": "equals", "value": "air"}, + {"scope": "service", "field": "battery", "operator": "equals", "value": "lithium"} + ] + }] + }], + "catalogs": [] + }) +} + +/// Your product table, already in request form: the rules a product has are the fields it +/// carries, and an absent field means "no rule". `battery` is yours, not the engine's. +fn products() -> Value { + json!({ + "laptop": {"mm": [360, 250, 30], "g": 2100, "battery": "lithium"}, + "monitor": {"mm": [680, 430, 140], "g": 5400, "rules": {"keep_upright": true, "stackable": false}}, + "bleach": {"mm": [90, 90, 280], "g": 1100, + "rules": {"keep_upright": true, "tags": ["chemical"], "incompatible_tags": ["food"]}}, + "coffee": {"mm": [120, 80, 220], "g": 1000, "rules": {"tags": ["food"]}}, + "desk": {"mm": [1600, 800, 60], "g": 28000} + }) +} + +fn cartons() -> Value { + json!([ + {"id": "S", "mm": [300, 200, 300], "tare_g": 180, "max_kg": 8, "cost_minor": 50}, + {"id": "M", "mm": [400, 300, 300], "tare_g": 260, "max_kg": 15, "cost_minor": 85}, + {"id": "L", "mm": [700, 450, 450], "tare_g": 520, "max_kg": 25, "cost_minor": 160} + ]) +} + +fn measures(edges: &Value) -> Value { + json!({ + "length": edges[0].to_string(), + "width": edges[1].to_string(), + "height": edges[2].to_string(), + }) +} + +/// A commerce call takes the document and the request in one envelope. +fn commerce_call(request: Value) -> String { + json!({"document": commerce_document(), "request": request}).to_string() +} + +/// The service the customer chose, or ground when a rule forbids it, and why. +fn allowed_service(order: &Order) -> Result<(&'static str, Option), Box> { + let products = products(); + for (sku, _) in order.lines { + let battery = products[sku]["battery"].as_str().unwrap_or("none"); + let answer: Value = serde_json::from_str(&evaluate_policy_json(&commerce_call(json!({ + "scope": "service", + "context": {"service": order.service, "battery": battery}, + "as_of": 0 + })))?)?; + let decision = &answer["decision"]; + if decision["allowed"] == false { + let reason = decision["citation"]["reason"].as_str().unwrap_or_default(); + return Ok(("ground", Some(format!("{sku}: {reason}")))); + } + } + Ok((order.service, None)) +} + +fn packing_request(order: &Order) -> Value { + let products = products(); + let items: Vec = order + .lines + .iter() + .map(|(sku, quantity)| { + let product = &products[sku]; + let mut item = json!({ + "id": sku, + "quantity": quantity, + "weight": format!("{} g", product["g"]), + "dimensions": measures(&product["mm"]), + }); + if let (Some(item), Some(rules)) = (item.as_object_mut(), product["rules"].as_object()) + { + item.extend(rules.clone()); + } + item + }) + .collect(); + let containers: Vec = cartons() + .as_array() + .into_iter() + .flatten() + .map(|carton| { + json!({ + "id": carton["id"], + "inner_dimensions": measures(&carton["mm"]), + "cost_minor": carton["cost_minor"], + "tare_weight": format!("{} g", carton["tare_g"]), + "max_payload": format!("{} kg", carton["max_kg"]), + }) + }) + .collect(); + json!({ + "units": {"length": "mm"}, + "configuration": { + "objective": "lowest_cost", + // Nothing may hang in the air: three quarters of every base must rest on something. + "minimum_support_ratio": 0.75, + "effort_budget": {"max_candidates_evaluated": 200000}, + "time_limit_ms": 60000 + }, + "items": items, + "containers": containers + }) +} + +/// One parcel through the pinned tariff. Whole grams and millimetres, rounded up. The answer +/// is either a quote or a rejection with a code: a zone the tariff does not price is never a +/// zero. +fn price(container: &Value, service: &str, zone: &str) -> Result> { + let ticks = |measure: &Value| measure["ticks"].as_u64().unwrap_or(0); + let grams = ticks(&container["gross_weight"]).div_ceil(TICKS_PER_GRAM); + let volume: u64 = ["length", "width", "height"] + .iter() + .map(|edge| ticks(&container["outer_dimensions"][edge]).div_ceil(TICKS_PER_MM)) + .product(); + Ok(serde_json::from_str("e_json(&commerce_call(json!({ + "carrier_id": "postway", "service_id": service, "tariff_version": 1, + "zone": zone, "actual_weight_g": grams, "volume_mm3": volume + })))?)?) +} + +fn fulfil(order: &Order) -> Result<(), Box> { + println!( + "\norder {} to zone {}, customer chose {}", + order.id, order.zone, order.service + ); + let (service, why) = allowed_service(order)?; + if let Some(why) = why { + println!(" moved to {service}: {why}"); + } + + let request = packing_request(order).to_string(); + let text = match pack_json(&request) { + Ok(text) => text, + // `field` is a JSON Pointer into the request, `reason` one of a closed set. + Err(PackError::InvalidRequest(error)) => { + println!( + " on hold: {} at {} ({})", + error.reason(), + error.field(), + error.detail() + ); + return Ok(()); + } + Err(other) => return Err(other.into()), + }; + + let issues = validate_json(&request, &text)?; + if !issues.is_empty() { + let found: Vec = issues + .iter() + .map(|issue| format!("{}: {}", issue.code, issue.detail)) + .collect(); + println!(" on hold: the plan failed its check: {}", found.join("; ")); + return Ok(()); + } + let result: Value = serde_json::from_str(&text)?; + let containers = result["containers"] + .as_array() + .map_or(&[][..], Vec::as_slice); + println!(" plan checked: {} parcel(s), no issues", containers.len()); + + let mut answers = Vec::with_capacity(containers.len()); + for container in containers { + let answer = price(container, service, order.zone)?; + if answer["status"] != "ok" { + println!( + " on hold: no {service} price for zone {} ({})", + order.zone, + answer["error"]["code"].as_str().unwrap_or_default() + ); + return Ok(()); + } + answers.push(answer); + } + + let mut total = 0; + for (container, answer) in containers.iter().zip(&answers) { + let mut contents: BTreeMap<&str, u32> = BTreeMap::new(); + for placement in container["placements"].as_array().into_iter().flatten() { + *contents + .entry(placement["item_type"].as_str().unwrap_or_default()) + .or_insert(0) += 1; + } + let listing: Vec = contents + .iter() + .map(|(sku, count)| format!("{count} x {sku}")) + .collect(); + let quoted = &answer["quote"]; + total += quoted["total_minor"].as_u64().unwrap_or(0); + println!( + " {:<4} {}", + container["id"].as_str().unwrap_or_default(), + listing.join(", ") + ); + println!( + " {} g on the scale, billed as {} g, {} minor units", + quoted["actual_weight_g"], quoted["billed_weight_g"], quoted["total_minor"] + ); + } + println!(" shipping by {service}: {total} minor units"); + + for entry in result["unpacked_items"].as_array().into_iter().flatten() { + println!( + " {} goes to freight: {}", + entry["item_id"].as_str().unwrap_or_default(), + entry["reason"].as_str().unwrap_or_default() + ); + } + Ok(()) +} + +fn main() -> Result<(), Box> { + let orders = [ + Order { + id: "A-1001", + zone: "domestic", + service: "air", + lines: &[("coffee", 6), ("bleach", 2)], + }, + Order { + id: "A-1002", + zone: "eu", + service: "air", + lines: &[("laptop", 1), ("monitor", 1), ("desk", 1)], + }, + Order { + id: "A-1003", + zone: "domestic", + service: "ground", + lines: &[("coffee", 0)], + }, + Order { + id: "A-1004", + zone: "overseas", + service: "ground", + lines: &[("coffee", 1)], + }, + ]; + for order in &orders { + fulfil(order)?; + } + Ok(()) +} diff --git a/src/api.rs b/src/api.rs index cae8e01..1d11fe7 100644 --- a/src/api.rs +++ b/src/api.rs @@ -6,7 +6,7 @@ use crate::geometry::{ALL_DIRECTIONS, Aabb, Dimensions, Point, Rotation, ShapeTy use crate::hull::{self, Vertex}; use crate::made_to_measure::{MAX_EXACT_INTEGER, MadeToMeasure, sides_of}; use crate::model::*; -use crate::pallet_overhang::{OverhangLimit, solving_frame}; +use crate::pallet_overhang::{OverhangLimit, needs_solving_frame, solving_frame}; use crate::policy::{PolicyConstraint, PolicyRuleSet}; use crate::rebalance::rebalance_weight; use crate::request_errors; @@ -64,7 +64,8 @@ pub fn rebalance_json( let request_value: Value = serde_json::from_str(request_input)?; let request = request_from_json(&request_value)?; validate_request(&request)?; - // A result's coordinates are in each pallet's solving frame. + // A result's coordinates are in each pallet's and standing bag's solving frame (, + //). let request = with_solving_frames(&request); let result_value: Value = serde_json::from_str(result_input)?; let original = parse_rebalance_result(&request, &result_value)?; @@ -73,7 +74,7 @@ pub fn rebalance_json( // back a shipment with no published price under the caller's own objective ( // review). Objective-gated inside the helper. if let Some((container_id, grams, bound)) = - crate::solvers::unpriceable_container(&original.containers, &request.config) + crate::billing::unpriceable_container(&original.containers, &request.config) { return Err(PackError::InvalidInput(format!( "container {container_id:?} bills at {grams} g, above its rate table's last \ @@ -417,11 +418,7 @@ pub fn pack_request_with_policy( ) -> PackResult { validate_request(request)?; let framed; - let request = if request - .containers - .iter() - .any(|container| container.pallet_overhang_limit.is_some()) - { + let request = if request.containers.iter().any(needs_solving_frame) { framed = with_solving_frames(request); &framed } else { @@ -479,7 +476,7 @@ pub fn pack_request_with_policy( // the last bracket has no published price, and quoting one anyway is the failure this // objective exists to prevent. if let Some((container_id, grams, bound)) = - crate::solvers::unpriceable_container(&result.containers, &request.config) + crate::billing::unpriceable_container(&result.containers, &request.config) { return Err(PackError::InvalidInput(format!( "container {container_id:?} bills at {grams} g, above its rate table's last \ @@ -491,7 +488,7 @@ pub fn pack_request_with_policy( // ones that never passed through it, and an alternative quoting the sentinel is the // leak by another door. result.alternatives.retain(|alternative| { - crate::solvers::unpriceable_container(&alternative.containers, &request.config).is_none() + crate::billing::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()); @@ -1405,8 +1402,10 @@ fn parse_effort_budget(value: Option<&Value>) -> PackResult let field = |name: &str| -> PackResult> { match map.get(name) { None => Ok(None), - Some(value) => value - .as_u64() + // By value, as admission reads it: `1000.0` is the integer 1000 (JavaScript + // cannot tell the two apart), and `as_u64` alone would refuse it. + Some(value) => crate::canonical_json::json_integer(value) + .and_then(|value| u64::try_from(value).ok()) .filter(|value| *value > 0) .map(Some) .ok_or_else(|| { @@ -1418,7 +1417,7 @@ fn parse_effort_budget(value: Option<&Value>) -> PackResult max_candidates_evaluated: field("max_candidates_evaluated")?, max_placement_attempts: field("max_placement_attempts")?, max_search_nodes: field("max_search_nodes")?, - max_restarts: field("max_restarts")?.map(|value| value as usize), + max_restarts: field("max_restarts")?.map(to_usize), })) } @@ -1695,10 +1694,10 @@ fn parse_container(value: &Value, unit: &str) -> PackResult { Some(Value::Object(limits)) => limits .iter() .map(|(tag, value)| { - value - .as_u64() + crate::canonical_json::json_integer(value) + .and_then(|limit| u64::try_from(limit).ok()) .filter(|limit| *limit > 0) - .map(|limit| (tag.clone(), limit as usize)) + .map(|limit| (tag.clone(), to_usize(limit))) .ok_or_else(|| { PackError::InvalidInput(format!( "container.tag_limits.{tag} must be positive" @@ -1723,6 +1722,7 @@ fn parse_container(value: &Value, unit: &str) -> PackResult { made_to_measure: parse_made_to_measure(map.get("made_to_measure"), unit)?, pallet_overhang_limit: parse_pallet_overhang_limit(map.get("pallet_overhang_limit"), unit)?, deck: None, + upright_frame: false, }) } @@ -1771,8 +1771,8 @@ fn parse_made_to_measure(value: Option<&Value>, unit: &str) -> PackResult