From 8ca5923cea98a091a44f9e09bf501273dbe4da9c Mon Sep 17 00:00:00 2001 From: Anton Date: Mon, 16 Nov 2026 11:54:46 -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 +- CHANGELOG.md | 40 ++ CITATION.cff | 4 +- README.md | 255 +++++------ artifacts.js | 2 +- codemeta.json | 6 +- commerce-model.js | 2 +- commerce.js | 13 +- docs/COMMERCE-API.md | 22 +- docs/GUARANTEES.md | 2 +- docs/UNITS-AND-NUMERICS.md | 2 + examples/checkout.mjs | 107 +++++ examples/fulfilment.mjs | 208 +++++++++ fallback.js | 397 ++++++++++++++---- index.js | 2 +- package.json | 6 +- policy.js | 12 +- request-errors.js | 64 ++- result-validation/accounting.js | 6 +- result-validation/bound.js | 141 ++++++- result-validation/container.js | 12 +- result-validation/json.js | 3 +- result-validation/objective.js | 2 +- result-validation/spec.js | 40 +- revisions.js | 11 +- test/bottom-gusset.test.mjs | 135 ++++++ test/commerce-edge-cases.test.mjs | 58 ++- test/fallback.test.mjs | 203 ++++++++- test/fixed-placements.test.mjs | 13 + ...o-measure-dimensional-weight-on-outer.json | 60 +++ ...e-deck-shares-its-weight-across-piers.json | 64 +++ test/plan-bound-hulls.test.mjs | 48 ++- test/policy.test.mjs | 19 + test/request-errors.test.mjs | 77 ++++ test/result-validation-bound.test.mjs | 75 ++++ test/result-validation-port.test.mjs | 4 + test/result-writer.test.mjs | 34 ++ test/stock-cut-errors.test.mjs | 17 + test/support-diagnosis-clock.test.mjs | 43 ++ test/validate.mjs | 27 +- 44 files changed, 1964 insertions(+), 288 deletions(-) create mode 100644 examples/checkout.mjs create mode 100644 examples/fulfilment.mjs create mode 100644 test/bottom-gusset.test.mjs create mode 100644 test/fixtures/feature-made-to-measure-dimensional-weight-on-outer.json create mode 100644 test/fixtures/regression-kilometre-scale-deck-shares-its-weight-across-piers.json create mode 100644 test/support-diagnosis-clock.test.mjs diff --git a/.github/DISCUSSION_TEMPLATE/q-a.yml b/.github/DISCUSSION_TEMPLATE/q-a.yml index 4ad2731..adcaa1e 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/engine 1.10.0 (JavaScript)" + placeholder: "@packvium/engine 1.11.0 (JavaScript)" validations: required: true - type: textarea diff --git a/.github/DISCUSSION_TEMPLATE/show-and-tell.yml b/.github/DISCUSSION_TEMPLATE/show-and-tell.yml index 4a20f0a..a07c6a5 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/engine 1.10.0 (JavaScript)" + placeholder: "@packvium/engine 1.11.0 (JavaScript)" validations: required: false - type: textarea diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml index d75e278..1572dfa 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-node/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-node/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 439456a..d24126a 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-node/discussions/categories/q-a + url: https://github.com/packvium/packvium-node/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-node/security/advisories/new + url: https://github.com/packvium/packvium-node/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 70c818c..d17f41f 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/CHANGELOG.md b/CHANGELOG.md index 063c34b..0af33cf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,46 @@ What changed in `@packvium/engine` on npm, release by release. The format follow [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 + +- **`deformable_boundary: { kind: 'gusseted_bag', bottom_gusset_depth, orientation }`**: a bottom + gusset lengthens the girth along the bag, and `orientation: 'standing'` packs a stand-up pouch + upright. +- **`optimality.lower_bound` and the gap under `shipping_cost` and `lowest_landed_cost`**; + `validate` checks them. +- **`examples/checkout.mjs` and `examples/fulfilment.mjs`.** + +### Changed + +- **A `rate_table` priced above 9007199254740991 minor units** at its top bracket, surcharge + included, is `invalid_request` / `above_maximum`. The fallback's packing `score` no longer + carries a rounded double past 2^53. Commerce refuses an input integer above 2^53 − 1 with + `expected an exact integer`, since `JSON.parse` has already rounded it. +- **Measures follow the shared grammar:** `100.`, `.5`, `0x64` and `100 millimeters` are + `wrong_type`, and `"5 /2"` is five halves, not 5. `hull_vertices` holds at most 32 points. +- **Two equally ranked container types open in code-point order of their ids,** not request + order, as in every other engine. Item types in the block solver, policy citations and + validation text follow code-point order, not UTF-16 order. +- **`volume_utilization` and `support_ratio` print six places of the correctly rounded double,** + as the other engines do. +- **The "why unpacked" reason no longer reads the search deadline.** + +### Fixed + +- **`quality` crashed with two payload-limited container types** ("Cannot convert a BigInt value + to a number"). This is also in 1.10.0. +- **A `single` ground contact was checked in `O(n + kn)` per candidate;** it is now `O(b)` for the + placements on one plane, with the same answers. +- **A rate table of 125,000 brackets overflowed the stack.** +- **`rebalanceWeight` deep-copied the scene for every trial move:** 120 items with 4 moves take + 0.4 s instead of 21.8 s. +- **The validator threw on `1e999`.** + ## [1.10.0] Nested packing, overhanging pallets, gusseted bags, 24 rotations for a hull, a declared currency diff --git a/CITATION.cff b/CITATION.cff index 90efd6f..b8507d4 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-node" +repository-code: "https://github.com/packvium/packvium-node" repository-artifact: "https://www.npmjs.com/package/@packvium/engine" abstract: >- Deterministic 3D bin-packing and cartonization engine for pallets, containers, trucks and shipping cartons. Exact integer geometry, reproducible results. diff --git a/README.md b/README.md index b160307..5a19a7d 100644 --- a/README.md +++ b/README.md @@ -1,15 +1,13 @@ # @packvium/engine -Deterministic 3D cartonization for Node.js. It uses the optional native engine when -available and automatically falls back to the bundled JavaScript implementation. +Deterministic 3D bin packing and cartonization for Node.js, with TypeScript declarations +and no dependencies. It runs a bundled JavaScript engine, and a compiled native engine +instead when one is built beside it. 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). - ## Install ```bash @@ -28,7 +26,7 @@ const result = pack({ units: { length: 'mm' }, configuration: { // Stop by counted work, not by the clock, so the answer is the same on any machine. - // The time limit is only a safety fuse; see "Deterministic results" below. + // The time limit is only a safety fuse; see "Getting the same answer every time" below. effort_budget: { max_candidates_evaluated: 1000000 }, time_limit_ms: 60000, }, @@ -63,60 +61,33 @@ console.log(quote.quote.total_minor); Lengths and weights are strings on purpose: they are parsed into exact integers, so `'0.1'` is a tenth of a millimetre and never `0.09999999999999999`. Every measurement in the result -comes back as `{ ticks, value, unit }` -- `ticks` is the exact integer the engine reasoned +comes back as `{ ticks, value, unit }`: `ticks` is the exact integer the engine reasoned with, `value` the same number written for a person. -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. - -## Two backends - -`pack()` uses a compiled native addon when one is built beside `index.js` and loads, -and the bundled JavaScript engine otherwise. The published package ships no binary, so an -`npm install` runs the JavaScript engine. `backend()` says which one answered. - -- **Packing:** both return a valid packing that honours every rule in the request, and each is - deterministic on its own. They are independent searches, so for the same request they may - choose a different arrangement, a different container, or a differently worded reason for an - item left out. Do not compare results across backends byte for byte. -- **Commerce:** the two are held to the same answer: a quote's price is one exact integer - and both compute the same one, and an unanswerable request is rejected by both with the same - code and fields. - -## Deterministic results - -A solve stops when it finishes or when a limit stops it, and which limit matters: +## Using it in your project -- `configuration.time_limit_ms` is a wall clock. How far a search gets in it depends on the - machine and its load, so an answer the clock cut short can differ on the next run. The - JavaScript engine uses **1000 ms** when you set nothing. -- `configuration.effort_budget` counts work -- `max_candidates_evaluated`, - `max_placement_attempts`, `max_search_nodes`, `max_restarts` -- and stops at the same point - on every machine, so even a partial answer repeats exactly. - -For anything you store, compare or audit, set an `effort_budget` and a `time_limit_ms` far above -what that work takes, as a fuse rather than a limit. The result says which one stopped it: - -```js -const result = pack({ ...request, configuration: { - effort_budget: { max_candidates_evaluated: 200000 }, - time_limit_ms: 60000, -} }); - -result.termination.code; // "complete", "effort_limit" or "time_limit" -result.algorithm.effort_limit_reached; // true: partial, but a rerun gives the same answer -result.algorithm.time_limit_reached; // true: the clock decided -- do not cache it as the answer -``` - -Items the search never reached are listed in `unpacked_items` with reason `effort_limit` or -`time_limit`, not as items that do not fit. [`examples/reproducibility.mjs`](examples/reproducibility.mjs) -shows both. +Two examples are written the way application code is written, with your own product and +order records on one side and the library call in the middle. `pack` is synchronous and +takes a plain object, so both drop into an Express handler, a Next.js server action or a +queue worker. Start from the one closer to what you are building. -`effort_limit` means the budget stopped work the search still had: a search that finishes on -exactly its budget reads `complete`, and `termination.any_start_truncated` says whether the -budget cut a start that might have won. +| You are building | Start from | What it does | +| --- | --- | --- | +| A checkout or cart endpoint | [`checkout.mjs`](examples/checkout.mjs) | Maps a cart onto a request, picks the cheapest cartons, and reads the parcels back for the page. Two functions hold everything Packvium-specific. | +| A warehouse or fulfilment job | [`fulfilment.mjs`](examples/fulfilment.mjs) | Runs an order from paid to labelled: a shipping rule picks the carrier service, the order is packed under its constraints, `validate` checks the plan, and every parcel is priced from a pinned tariff. | +| An HTTP endpoint that packs | [`errors.mjs`](examples/errors.mjs) | Shows what each kind of refused request throws, and which fields to branch on. | +| A dock or driver screen | [`execution.mjs`](examples/execution.mjs), [`trucking.mjs`](examples/trucking.mjs) | Turns a result into numbered loading steps, 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 +124,7 @@ every Packvium engine. Branch on `reason` and `field`; show the message to a per `container.pallet_overhang_limit+axles`. It is refused rather than silently ignored. - Numbers are judged by value, as the other engines judge them: `2.0` is the integer `2`, `2.5` and `'2'` are not integers, and an integer above `Number.MAX_SAFE_INTEGER` (2^53 - 1) is - `above_maximum` -- also when it arrives as JSON text, which `JSON.parse` would otherwise round. + `above_maximum`, also when it arrives as JSON text, which `JSON.parse` would otherwise round. - Text that is not JSON makes `packJson()` throw the `SyntaxError` from `JSON.parse`. A request that is valid but does not fit completely is not an error: the result lists what was @@ -182,9 +153,56 @@ const issues = validate(request, pack(request)); // [] -- valid It judges any engine's result, not only this package's. A result without the documented shape throws `MalformedResult`, whose `kind` is `contract` or `shape`. +## Getting the same answer every time + +A solve stops when it finishes or when a limit stops it, and which limit matters: + +- `configuration.time_limit_ms` is a wall clock. How far a search gets in it depends on the + machine and its load, so an answer the clock cut short can differ on the next run. The + JavaScript engine uses **1000 ms** when you set nothing. +- `configuration.effort_budget` counts work (`max_candidates_evaluated`, + `max_placement_attempts`, `max_search_nodes`, `max_restarts`) and stops at the same point + on every machine, so even a partial answer repeats exactly. + +For anything you store, compare or audit, set an `effort_budget` and a `time_limit_ms` far above +what that work takes, as a fuse rather than a limit. The result says which one stopped it: + +```js +const result = pack({ ...request, configuration: { + effort_budget: { max_candidates_evaluated: 200000 }, + time_limit_ms: 60000, +} }); + +result.termination.code; // "complete", "effort_limit" or "time_limit" +result.algorithm.effort_limit_reached; // true: partial, but a rerun gives the same answer +result.algorithm.time_limit_reached; // true: the clock decided -- do not cache it as the answer +``` + +Items the search never reached are listed in `unpacked_items` with reason `effort_limit` or +`time_limit`, not as items that do not fit. [`examples/reproducibility.mjs`](examples/reproducibility.mjs) +shows both. + +`effort_limit` means the budget stopped work the search still had: a search that finishes on +exactly its budget reads `complete`, and `termination.any_start_truncated` says whether the +budget cut a start that might have won. + +## Two backends + +`pack()` uses a compiled native addon when one is built beside `index.js` and loads, +and the bundled JavaScript engine otherwise. The published package ships no binary, so an +`npm install` runs the JavaScript engine. `backend()` says which one answered. + +- **Packing:** both return a valid packing that honours every rule in the request, and each is + deterministic on its own. They are independent searches, so for the same request they may + choose a different arrangement, a different container, or a differently worded reason for an + item left out. Do not compare results across backends byte for byte. +- **Commerce:** the two are held to the same answer: a quote's price is one exact integer + and both compute the same one, and an unanswerable request is rejected by both with the same + code and fields. + ## Quotes, policy and catalog versions -`commerce` has three functions, all deterministic and all over one document you supply — +`commerce` has three functions, all deterministic and all over one document you supply: no clock, no network, no hidden state. A history is a list and a version's number is its position in that list starting at 1, so `tariff_version: 2` always means "the second entry under this carrier and service". @@ -217,15 +235,39 @@ commerce.canonicalJson(result); Two kinds of failure, and they are not interchangeable: - a **malformed** document or request is your bug and throws `CommerceInputError`; -- a request the model simply **cannot answer** — no tariff effective at that instant, no - rate for that zone — is a successful call returning `"status": "rejected"` with a code +- a request the model **cannot answer** (no tariff effective at that instant, no + rate for that zone) is a successful call returning `"status": "rejected"` with a code from a closed set and structured fields naming what was missing. `commerce.backend()` reports whether the native addon or the JavaScript implementation answered; both give the same price and the same rejection for the same input. A runnable walk-through of all three functions is in [examples/commerce.mjs](examples/commerce.mjs), and -the full contract — document format, every result shape, all ten rejection codes, complexity -and limitations — is [COMMERCE-API.md](https://github.com/toxakara/packvium-node/blob/main/docs/COMMERCE-API.md). +the full contract (document format, every result shape, all ten rejection codes, complexity +and limitations) is [COMMERCE-API.md](https://github.com/packvium/packvium-node/blob/main/docs/COMMERCE-API.md). + +## Subpath modules + +The main entry point has packing, sequencing, explanations, rebalancing and `commerce`. Five +more modules are separate imports, so an application that only packs never loads them: + +```js +import { buildExecutionPlan, canonicalPlanJson } from '@packvium/engine/execution.js'; +import { buildOperationalArtifact, canonicalArtifactJson } from '@packvium/engine/artifacts.js'; +import { exportCsv, exportJson, exportWorkOrderHtml } from '@packvium/engine/artifact-exports.js'; +import { deriveRevision, rootRevision, verifyRevisionChain } from '@packvium/engine/revisions.js'; +import { artifactToScene, resultToScenes, sceneItemId } from '@packvium/engine/scene.js'; +``` + +`execution.js` turns a result into numbered work-order steps. It never computes a loading order +itself: pass one from `safeLoadingOrder()` as `loadingOrders`, or the plan says its order is +`unavailable` rather than guessing. `artifacts.js` and `artifact-exports.js` package a result for a +system with no engine; `revisions.js` records changes against an approved plan. +`scene.js` turns a result into one drawable scene per container +(`packvium-visualization-scene/v1`): every length an exact tick string beside a display-only `mm` +value, items already rotated, each id spelled from the placement's type, position and orientation. `resultToScenes(request, result)` +returns them all; `artifactToScene(artifact, index)` reads one from an operational artifact, with a +loading sequence when the artifact's plan carries one. `sceneItemId(reference)` spells a plan +step's placement the way its scene item is named, to match one to the other. ## Examples @@ -234,16 +276,18 @@ and execute without a project around it, and each prints what it teaches. | File | What it shows | | --- | --- | +| [`checkout.mjs`](examples/checkout.mjs) | A shop's checkout: a cart mapped onto a request and the parcels read back, with the cheapest cartons chosen. | +| [`fulfilment.mjs`](examples/fulfilment.mjs) | An order from paid to labelled: a policy rule picks the service, the order is packed under its constraints, `validate` checks the plan, and each parcel is priced from a pinned tariff. | | [`basic.mjs`](examples/basic.mjs) | Pack an order, read placements, and see why an item was refused. | -| [`objectives.mjs`](examples/objectives.mjs) | Six of the seven objectives (all but `maximum_volume`) on scenes where they genuinely disagree about which container to open, a declared `currency` echoed on the answer, and the `optimality.lower_bound` five of them state. | -| [`constraints.mjs`](examples/constraints.mjs) | Rotations and `keep_upright`, support ratio, top load, stacking caps, incompatible tags and atomic groups — each with and without the rule — and `explainUnpackedItem` turning a refusal into a sentence. | +| [`objectives.mjs`](examples/objectives.mjs) | Six of the seven objectives (all but `maximum_volume`) on scenes where they disagree about which container to open, a declared `currency` echoed on the answer, and the `optimality.lower_bound` five of them state. | +| [`constraints.mjs`](examples/constraints.mjs) | Rotations and `keep_upright`, support ratio, top load, stacking caps, incompatible tags and atomic groups, each with and without the rule, and `explainUnpackedItem` turning a refusal into a sentence. | | [`limits.mjs`](examples/limits.mjs) | Wheel arches as `obstacles` with `additional_boxes`, `max_items` and `tag_limits` per container, what happens when container stock or `max_containers` runs out, a crate overhanging its pallet under `pallet_overhang_limit`, and a flat bag against a gusseted one. | | [`trucking.mjs`](examples/trucking.mjs) | A multi-drop van: `stop_index` and a rear door in `access_directions`, two `axles` with load limits, and a safe loading order fed into `buildExecutionPlan`. | | [`shapes.mjs`](examples/shapes.mjs) | Items that are not their box: complementary wedges sharing one crate as `convex_hull`, two identical wedges that need one of the 18 signed rotations to share it, and a cushion that compresses under load until the crush limit refuses it. | | [`units.mjs`](examples/units.mjs) | Why lengths travel as strings: fractional inches kept exact, one tick deciding a fit, and the point where a JavaScript number stops being exact and a quote is refused rather than rounded. | | [`serialization.mjs`](examples/serialization.mjs) | `packJson` with JSON text in and out, runners-up through `alternatives`, and exactly which mistakes are refused and which are ignored. | | [`reproducibility.mjs`](examples/reproducibility.mjs) | `effort_budget` against `time_limit_ms`: a budget that never binds, one that cuts the search short and still repeats exactly, and how to tell from the result which one stopped it. | -| [`errors.mjs`](examples/errors.mjs) | `InvalidRequestError`'s `code`, `reason`, `field` and message for each kind of bad request, JavaScript's integer range, `FixedPlacementError` and `UnsupportedFeatureError` — and a valid request that simply does not fit. | +| [`errors.mjs`](examples/errors.mjs) | `InvalidRequestError`'s `code`, `reason`, `field` and message for each kind of bad request, JavaScript's integer range, `FixedPlacementError` and `UnsupportedFeatureError`, and a valid request that does not fit. | | [`fixed_placements.mjs`](examples/fixed_placements.mjs) | Pack around items already loaded, lock half of an earlier plan by quoting its placements and their `placement_id`, a fixed set that cannot hold, and an id that names another placement. | | [`rebalancing.mjs`](examples/rebalancing.mjs) | `rebalanceWeight` evening out payload between packed crates, the moves it made, and `maxMoves`. | | [`commerce.mjs`](examples/commerce.mjs) | Rate a shipment, apply an eligibility rule, and pin a catalog version. | @@ -256,31 +300,7 @@ and execute without a project around it, and each prints what it teaches. node examples/basic.mjs ``` -## Subpath modules - -The main entry point has packing, sequencing, explanations, rebalancing and `commerce`. Five -more modules are separate imports, so an application that only packs never loads them: - -```js -import { buildExecutionPlan, canonicalPlanJson } from '@packvium/engine/execution.js'; -import { buildOperationalArtifact, canonicalArtifactJson } from '@packvium/engine/artifacts.js'; -import { exportCsv, exportJson, exportWorkOrderHtml } from '@packvium/engine/artifact-exports.js'; -import { deriveRevision, rootRevision, verifyRevisionChain } from '@packvium/engine/revisions.js'; -import { artifactToScene, resultToScenes, sceneItemId } from '@packvium/engine/scene.js'; -``` - -`execution.js` turns a result into numbered work-order steps. It never computes a loading order -itself: pass one from `safeLoadingOrder()` as `loadingOrders`, or the plan says its order is -`unavailable` rather than guessing. `artifacts.js` and `artifact-exports.js` package a result for a -system with no engine; `revisions.js` records changes against an approved plan. -`scene.js` turns a result into one drawable scene per container -(`packvium-visualization-scene/v1`): every length an exact tick string beside a display-only `mm` -value, items already rotated, each id spelled from the placement's type, position and orientation. `resultToScenes(request, result)` -returns them all; `artifactToScene(artifact, index)` reads one from an operational artifact, with a -loading sequence when the artifact's plan carries one. `sceneItemId(reference)` spells a plan -step's placement the way its scene item is named, to match one to the other. - -## Features +## What it covers - Exact, deterministic placement with no floating-point geometry decisions. - Rotation, payload, stackability, support, clearance, obstacle and tag constraints; a @@ -307,7 +327,7 @@ step's placement the way its scene item is named, to match one to the other. - Execution plans through `buildExecutionPlan()` / `canonicalPlanJson()`: a work-order view of a result, with solver facts separated from the text that cites them. - Portable operational artifacts through `buildOperationalArtifact()` from `artifacts.js`, exported - by `artifact-exports.js` as canonical JSON, CSV or a self-contained HTML work order — the same + by `artifact-exports.js` as canonical JSON, CSV or a self-contained HTML work order, the same bytes the Python, PHP and Rust packages write. - Fixed placements (`fixed_placements`): items already loaded stay where they are and the solve packs around them; plan revisions from `revisions.js` record exceptions against an approved @@ -318,6 +338,22 @@ step's placement the way its scene item is named, to match one to the other. The native addon is optional. `npm install` works on unsupported platforms too; call `backend()` if your application needs to know which implementation handled a request. +## Documentation + +TypeScript declarations are included. See the package's `index.d.ts` for the complete +request and result types. The documentation is in the source repository, not in the npm +package: + +- [GUARANTEES.md](https://github.com/packvium/packvium-node/blob/main/docs/GUARANTEES.md): what is promised and what is not; +- [PUBLIC-API.md](https://github.com/packvium/packvium-node/blob/main/docs/PUBLIC-API.md): every request field, result shape and status; +- [UNITS-AND-NUMERICS.md](https://github.com/packvium/packvium-node/blob/main/docs/UNITS-AND-NUMERICS.md): units, accepted input forms, exact + arithmetic and the 2^53 ceiling; +- [COMMERCE-API.md](https://github.com/packvium/packvium-node/blob/main/docs/COMMERCE-API.md): the commercial/control-plane contract. + +Report security issues through [SECURITY.md](SECURITY.md). + +The constraint reference and the benchmarks are at [packvium.com](https://packvium.com). + ## The Packvium family One request and result contract, implemented independently in four engines (Rust, @@ -326,45 +362,28 @@ PHP to identical placements, Rust and JavaScript to a valid packing that scores than a per-fixture floor. 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) | - -## API and support - -TypeScript declarations are included. See the package's `index.d.ts` for the complete -request and result types. The documentation is in the source repository, not in the npm -package: - -- [GUARANTEES.md](https://github.com/toxakara/packvium-node/blob/main/docs/GUARANTEES.md) — what is promised and what is not; -- [PUBLIC-API.md](https://github.com/toxakara/packvium-node/blob/main/docs/PUBLIC-API.md) — every request field, result shape and status; -- [UNITS-AND-NUMERICS.md](https://github.com/toxakara/packvium-node/blob/main/docs/UNITS-AND-NUMERICS.md) — units, accepted input forms, exact - arithmetic and the 2^53 ceiling; -- [COMMERCE-API.md](https://github.com/toxakara/packvium-node/blob/main/docs/COMMERCE-API.md) — the commercial/control-plane contract. - -Report security issues through [SECURITY.md](SECURITY.md). +| 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) | ## Citation If Packvium supports your research, cite it as software. GitHub's **Cite this repository** -button reads [`CITATION.cff`](https://github.com/toxakara/packvium-node/blob/main/CITATION.cff), and -[`codemeta.json`](https://github.com/toxakara/packvium-node/blob/main/codemeta.json) carries the same record in +button reads [`CITATION.cff`](https://github.com/packvium/packvium-node/blob/main/CITATION.cff), and +[`codemeta.json`](https://github.com/packvium/packvium-node/blob/main/codemeta.json) carries the same record in CodeMeta form. ```bibtex @software{packvium_node, author = {{Packvium contributors}}, title = {Packvium for Node.js}, - version = {1.10.0}, + version = {1.11.0}, license = {MIT}, url = {https://packvium.com} } diff --git a/artifacts.js b/artifacts.js index a0acf46..7c16116 100644 --- a/artifacts.js +++ b/artifacts.js @@ -22,7 +22,7 @@ export const FORMAT = 'packvium-operational-artifact/v1'; * The engine's own name is deliberately not recorded: four correct builders naming themselves * would emit four different documents. */ -export const SUITE_VERSION = '1.10.0'; +export const SUITE_VERSION = '1.11.0'; /** The deterministic part of `result.algorithm`; `duration_ms` is wall-clock time. */ const SOLVER_FIELDS = ['profile', 'solver', 'seed', 'time_limit_reached', 'effort_limit_reached']; diff --git a/codemeta.json b/codemeta.json index 3322dd5..6f1f758 100644 --- a/codemeta.json +++ b/codemeta.json @@ -3,7 +3,7 @@ "@type": "SoftwareSourceCode", "name": "Packvium for Node.js", "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-node", - "issueTracker": "https://github.com/toxakara/packvium-node/issues", + "codeRepository": "https://github.com/packvium/packvium-node", + "issueTracker": "https://github.com/packvium/packvium-node/issues", "programmingLanguage": "JavaScript", "keywords": [ "3d-bin-packing", diff --git a/commerce-model.js b/commerce-model.js index b52e3d2..def9152 100644 --- a/commerce-model.js +++ b/commerce-model.js @@ -34,7 +34,7 @@ export function exact(value) { const number = Number(value); if (!Number.isSafeInteger(number)) { throw new CommerceInputError( - `${value} is outside JavaScript's exact integer range; this quote cannot be represented`, + `quote amount ${value} is above ${Number.MAX_SAFE_INTEGER} and cannot be represented exactly`, ); } return number; diff --git a/commerce.js b/commerce.js index 8877a43..55627b0 100644 --- a/commerce.js +++ b/commerce.js @@ -68,8 +68,10 @@ function asList(value, path) { } function asInteger(value, path) { - // A JSON boolean where an exact integer belongs is a caller mistake, not a 0 or a 1. - if (typeof value !== 'number' || !Number.isInteger(value)) { + // A JSON boolean where an exact integer belongs is a caller mistake, not a 0 or a 1. Past + // 2^53 - 1 the parsed Number is already rounded, so the exact arithmetic after it would + // start from a value the caller never sent. + if (typeof value !== 'number' || !Number.isSafeInteger(value)) { fail(path, 'expected an exact integer'); } return value; @@ -81,11 +83,11 @@ function asText(value, path) { } function checkKeys(value, path, required, optionalKeys = []) { - const missing = required.filter((key) => !Object.hasOwn(value, key)).sort(); + const missing = required.filter((key) => !Object.hasOwn(value, key)).sort(compareCodePoints); if (missing.length > 0) fail(path, `missing required key(s) ${JSON.stringify(missing)}`); const unknown = Object.keys(value) .filter((key) => !required.includes(key) && !optionalKeys.includes(key)) - .sort(); + .sort(compareCodePoints); if (unknown.length > 0) fail(path, `unrecognised key(s) ${JSON.stringify(unknown)}`); } @@ -182,7 +184,8 @@ function parseTariff(value, path, [carrierId, serviceId], number) { const zonesPath = `${path}.cost_per_dimensional_kg_minor`; const costPerDimensionalKgMinor = Object.create(null); const zones = asObject(fields.cost_per_dimensional_kg_minor, zonesPath); - for (const [zone, cost] of Object.entries(zones)) { + // K2: ascending code-point order, so the first error never depends on where a language puts integer-like keys. + for (const [zone, cost] of Object.entries(zones).sort(([left], [right]) => compareCodePoints(left, right))) { costPerDimensionalKgMinor[zone] = nonNegative( asInteger(cost, `${zonesPath}[${zone}]`), zonesPath, 'cost_per_dimensional_kg_minor entries cannot be negative', 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.mjs b/examples/checkout.mjs new file mode 100644 index 0000000..7891ca6 --- /dev/null +++ b/examples/checkout.mjs @@ -0,0 +1,107 @@ +/** + * A shop's checkout: turn a cart into parcels. + * + * Run it: + * + * node examples/checkout.mjs + * + * This is the shape most projects start from. You already have product rows and cart + * lines in your own format; the library wants a request. So there are two small functions + * between them: `toRequest` maps your records onto the request, and `parcels` reads the + * result back into something your checkout page can render. Everything Packvium-specific + * lives in those two functions, and the rest of the shop never sees a tick or a placement. + * + * `pack` is synchronous and takes a plain object, so it drops into an Express handler, a + * Next.js server action or a queue worker as it is. In your project the import reads + * `from '@packvium/engine'`; here it points at the package this file ships in. + */ + +import { pack } from '../index.js'; + +// Your product table. Sizes in centimetres and weights in grams, as a shop usually has them. +const PRODUCTS = { + kettle: { sizeCm: [24, 22, 26], weightG: 1300, thisSideUp: true }, + mug: { sizeCm: [12, 9, 10], weightG: 350, thisSideUp: false }, + cookbook: { sizeCm: [28, 22, 3], weightG: 900, thisSideUp: false }, + 'floor-lamp': { sizeCm: [150, 30, 30], weightG: 4200, thisSideUp: false }, +}; + +// The cartons on your packing bench, with what each one costs you in cents. +const BOXES = { + small: { innerCm: [30, 25, 15], maxKg: 5, costCents: 45 }, + medium: { innerCm: [40, 30, 30], maxKg: 12, costCents: 80 }, + large: { innerCm: [60, 40, 40], maxKg: 20, costCents: 140 }, +}; + +const measures = ([length, width, height]) => ({ + length: String(length), width: String(width), height: String(height), +}); + +/** Your cart (`{ sku: quantity }`) as a Packvium request. */ +function toRequest(cart) { + return { + 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: Object.entries(cart).map(([sku, quantity]) => ({ + id: sku, + quantity, + weight: `${PRODUCTS[sku].weightG} g`, + keep_upright: PRODUCTS[sku].thisSideUp, + dimensions: measures(PRODUCTS[sku].sizeCm), + })), + containers: Object.entries(BOXES).map(([id, box]) => ({ + id, + max_payload: `${box.maxKg} kg`, + cost_minor: box.costCents, + inner_dimensions: measures(box.innerCm), + })), + }; +} + +/** The parcels to ship, and the SKUs that fit no carton you stock. */ +function parcels(cart) { + const result = pack(toRequest(cart)); + const shipped = result.containers.map((container) => { + const contents = {}; + for (const placement of container.placements) { + contents[placement.item_type] = (contents[placement.item_type] ?? 0) + 1; + } + return { + box: container.container_type, + contents, + // `value` is the exact weight rendered in `unit`; here that is whole grams. + weight: `${container.gross_weight.value} ${container.gross_weight.unit}`, + }; + }); + // An item that fits nowhere is not an error. It comes back with a reason, and the rest + // of the cart is still packed. + const leftOut = [...new Set(result.unpacked_items.map((entry) => entry.item_type))].sort(); + return { shipped, leftOut }; +} + +function show(title, cart) { + const { shipped, leftOut } = parcels(cart); + console.log(`\n${title}`); + let boxCost = 0; + for (const [index, parcel] of shipped.entries()) { + const contents = Object.keys(parcel.contents).sort() + .map((sku) => `${parcel.contents[sku]} x ${sku}`).join(', '); + console.log(` parcel ${index + 1}: ${parcel.box.padEnd(6)} ${parcel.weight.padStart(7)} ${contents}`); + boxCost += BOXES[parcel.box].costCents; + } + console.log(` cartons cost ${boxCost} cents`); + for (const sku of leftOut) { + console.log(` ${sku} fits none of our cartons: ship it in its own packaging`); + } +} + +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 }); diff --git a/examples/fulfilment.mjs b/examples/fulfilment.mjs new file mode 100644 index 0000000..8b9c70e --- /dev/null +++ b/examples/fulfilment.mjs @@ -0,0 +1,208 @@ +/** + * From a paid order to labelled parcels: eligibility, packing, a second opinion, a price. + * + * Run it: + * + * node examples/fulfilment.mjs + * + * checkout.mjs 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.evaluatePolicy` decides which carrier service the order may use at all. + * 2. `pack` packs it, under the rules the goods come with. + * 3. `validate` checks the plan against the request with code that shares nothing with + * the solver, so a parcel is never labelled on the solver's word alone. + * 4. `commerce.quote` 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) throws `InvalidRequestError`, 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. + */ + +import { InvalidRequestError, commerce, pack, validate } from '../index.js'; + +// 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 = 16000; +const TICKS_PER_GRAM = 8000000; + +// 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. +const COMMERCE = { + 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: [], +}; + +const PRODUCTS = { + laptop: { mm: [360, 250, 30], g: 2100, battery: 'lithium' }, + monitor: { mm: [680, 430, 140], g: 5400, keep_upright: true, stackable: false }, + bleach: { mm: [90, 90, 280], g: 1100, keep_upright: true, tags: ['chemical'], incompatible_tags: ['food'] }, + coffee: { mm: [120, 80, 220], g: 1000, tags: ['food'] }, + desk: { mm: [1600, 800, 60], g: 28000 }, +}; + +const BOXES = [ + { id: 'S', mm: [300, 200, 300], tareG: 180, maxKg: 8, costMinor: 50 }, + { id: 'M', mm: [400, 300, 300], tareG: 260, maxKg: 15, costMinor: 85 }, + { id: 'L', mm: [700, 450, 450], tareG: 520, maxKg: 25, costMinor: 160 }, +]; + +const measures = ([length, width, height]) => ({ + length: String(length), width: String(width), height: String(height), +}); + +/** The service the customer chose, or ground when a rule forbids it, and why. */ +function allowedService(order) { + for (const sku of Object.keys(order.lines)) { + const { decision } = commerce.evaluatePolicy(COMMERCE, { + scope: 'service', + context: { service: order.service, battery: PRODUCTS[sku].battery ?? 'none' }, + as_of: 0, + }); + if (!decision.allowed) { + return { service: 'ground', why: `${sku}: ${decision.citation.reason}` }; + } + } + return { service: order.service, why: null }; +} + +function packingRequest(order) { + const items = Object.entries(order.lines).map(([sku, quantity]) => { + const product = PRODUCTS[sku]; + const item = { id: sku, quantity, weight: `${product.g} g`, dimensions: measures(product.mm) }; + // Only the rules a product actually has are sent; an absent field means "no rule". + for (const rule of ['keep_upright', 'stackable', 'tags', 'incompatible_tags']) { + if (rule in product) item[rule] = product[rule]; + } + return item; + }); + return { + 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, + containers: BOXES.map((box) => ({ + id: box.id, + inner_dimensions: measures(box.mm), + cost_minor: box.costMinor, + tare_weight: `${box.tareG} g`, + max_payload: `${box.maxKg} kg`, + })), + }; +} + +/** + * 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. + */ +function price(container, service, zone) { + const grams = Math.ceil(container.gross_weight.ticks / TICKS_PER_GRAM); + let volume = 1; + for (const edge of ['length', 'width', 'height']) { + volume *= Math.ceil(container.outer_dimensions[edge].ticks / TICKS_PER_MM); + } + return commerce.quote(COMMERCE, { + carrier_id: 'postway', service_id: service, tariff_version: 1, + zone, actual_weight_g: grams, volume_mm3: volume, + }); +} + +/** An order that cannot ship as it is stops here, with the reason for whoever picks it up. */ +const hold = (why) => console.log(` on hold: ${why}`); + +function fulfil(order) { + console.log(`\norder ${order.id} to zone ${order.zone}, customer chose ${order.service}`); + const { service, why } = allowedService(order); + if (why) console.log(` moved to ${service}: ${why}`); + + const request = packingRequest(order); + let result; + try { + result = pack(request); + } catch (error) { + if (!(error instanceof InvalidRequestError)) throw error; + // `field` is a JSON Pointer into the request, `reason` one of a closed set. + return hold(`${error.reason} at ${error.field} (${error.detail})`); + } + + const issues = validate(request, result); + const found = issues.map((issue) => `${issue.code}: ${issue.detail}`).join('; '); + if (found) return hold(`the plan failed its check: ${found}`); + console.log(` plan checked: ${result.containers.length} parcel(s), no issues`); + + const answers = result.containers.map((container) => price(container, service, order.zone)); + const refused = answers.find((answer) => answer.status !== 'ok'); + if (refused) return hold(`no ${service} price for zone ${order.zone} (${refused.error.code})`); + + let total = 0; + for (const [index, container] of result.containers.entries()) { + const contents = {}; + for (const placement of container.placements) { + contents[placement.item_type] = (contents[placement.item_type] ?? 0) + 1; + } + const listing = Object.keys(contents).sort().map((sku) => `${contents[sku]} x ${sku}`).join(', '); + const quoted = answers[index].quote; + total += quoted.total_minor; + console.log(` ${container.id.padEnd(4)} ${listing}`); + console.log(` ${quoted.actual_weight_g} g on the scale, billed as ` + + `${quoted.billed_weight_g} g, ${quoted.total_minor} minor units`); + } + console.log(` shipping by ${service}: ${total} minor units`); + + for (const entry of result.unpacked_items) { + console.log(` ${entry.item_id} goes to freight: ${entry.reason}`); + } +} + +fulfil({ id: 'A-1001', zone: 'domestic', service: 'air', lines: { coffee: 6, bleach: 2 } }); +fulfil({ id: 'A-1002', zone: 'eu', service: 'air', lines: { laptop: 1, monitor: 1, desk: 1 } }); +fulfil({ id: 'A-1003', zone: 'domestic', service: 'ground', lines: { coffee: 0 } }); +fulfil({ id: 'A-1004', zone: 'overseas', service: 'ground', lines: { coffee: 1 } }); diff --git a/fallback.js b/fallback.js index 266e48d..2e261be 100644 --- a/fallback.js +++ b/fallback.js @@ -25,17 +25,6 @@ const supportPpm=(ratio)=>ratio>0?Math.max(1,scaledRatio(ratio)):0; const MIN_CANDIDATE_POINTS=16; const hasOwn=(value,key)=>Object.prototype.hasOwnProperty.call(value,key); const isObject=value=>value!==null&&typeof value==='object'&&!Array.isArray(value); -function cloneValue(value){ - if(Array.isArray(value))return value.map(cloneValue); - // An item's accepted stacking groups are a Set of strings; copied, not flattened. - if(value instanceof Set)return new Set(value); - if(value!==null&&typeof value==='object'){ - const copy={}; - for(const [key,entry] of Object.entries(value))copy[key]=cloneValue(entry); - return copy - } - return value -} const UNSUPPORTED={ // Top-level scope: a block describing the whole request rather than one item or // container, which none of the per-entry loops below would ever see. @@ -106,7 +95,8 @@ const billedGrams=ticks=>Number((BigInt(ticks)+BigInt(WT.g)-1n)/BigInt(WT.g)); function chargeMinor(table,grams){ for(let index=0;indexnew RangeError(`container ${JSON.stringify(id)} bills at ${grams} g, above its rate table's last bracket (${bound} g); the shipment has no published price`); +// An unpriceable total is still reported as the largest safe integer, as every engine does. +const reportedLanded=total=>total===UNPRICEABLE?Number.MAX_SAFE_INTEGER:total; const addLanded=(total,template,billedTicks)=>{ if(total===UNPRICEABLE)return total; const charge=template.rate==null?null:chargeMinor(template.rate,billedGrams(billedTicks)); @@ -350,8 +343,26 @@ function fixedSetIssue(groups,req,clear){ function bagExtent(placements){let a=0,b=0,c=0; for(const p of placements){a=Math.max(a,p.x+p.ed[0]);b=Math.max(b,p.y+p.ed[1]);c=Math.max(c,p.z+p.ed[2])} return [a,b,c]} -// 1.10: a gusseted bag's side gusset G widens the width girth to b + c <= W + G; G = 0 is the flat bag. -function bagAdmits(tmpl,placements){const [a,b,c]=bagExtent(placements);return a+c<=tmpl.d[0]&&b+c<=tmpl.d[1]+tmpl.gusset} +// A bag's two loops of film round its package (1.10 side gusset G, bottom +// gusset K, 0 where none is declared): lying flat on `L x W`, 2(a + c) <= 2L + K along and +// b + c <= W + G across; standing in its `W x H x L` frame, 2(b + c) <= 2L + K and a + b <= W + G. +// Each loop is held as the axis its side bounds (`a <= L` lying flat, `c <= L` standing, by the +// rigid check that always runs first), the axis added to it, and that side. Null for a rigid +// container. O(1). +function bagGirth(boundary,declared,length){if(boundary==null)return null; + const standing=boundary.orientation==='standing'; + return Object.freeze({standing,length:declared[0],width:declared[1], + side:boundary.side_gusset_depth==null?0:length(boundary.side_gusset_depth), + bottom:boundary.bottom_gusset_depth==null?0:length(boundary.bottom_gusset_depth), + along:standing?[2,1]:[0,2],across:standing?[0,1]:[1,2]})} +// The `W x H x L` frame a bag declared `L x W x H` stands in, and back. +const standingFrame=declared=>[declared[1],declared[2],declared[0]]; +const declaredFrame=tmpl=>tmpl.girth?.standing?[tmpl.d[2],tmpl.d[0],tmpl.d[1]]:declaredInner(tmpl.d,tmpl.deck); +// Differences from the bounded side, not plain sums: every term stays a safe integer however +// long the sides, so 2(a + c) <= 2L + K reads exactly as 2((a - L) + c) <= K. +function girthAdmits(girth,extent){const [i,j]=girth.along,[p,q]=girth.across; + return 2*((extent[i]-girth.length)+extent[j])<=girth.bottom&&(extent[p]-girth.width)+extent[q]<=girth.side} +function bagAdmits(tmpl,placements){return girthAdmits(tmpl.girth,bagExtent(placements))} function compatibilityIssue(item,others,tmpl){ if(item.tags.length||item.incompatible.length)for(const other of others) if(item.incompatible.some(tag=>other.item.tags.includes(tag))||other.item.incompatible.some(tag=>item.tags.includes(tag))) @@ -411,9 +422,20 @@ function routeStuck(placements,tmpl,clear){ const chosen=Math.min(...removable);present.delete(chosen);due=due.filter(k=>k!==chosen)}} return null } -function rat(s){s=String(s).trim();if(s.includes(' ')){const [w,f]=s.split(/\s+/,2),[n,d]=f.split('/').map(BigInt),wb=BigInt(w),sg=s.startsWith('-')?-1n:1n,mag=(wb<0n?-wb:wb)*d+n;return [sg*mag,d]}if(s.includes('/')){const[n,d]=s.split('/').map(BigInt);return[n,d]}if(s.includes('.')){const neg=s.startsWith('-'),[a,b]=s.replace(/^[-+]/,'').split('.');const d=10n**BigInt(b.length),n=BigInt(a)*d+BigInt(b);return[neg?-n:n,d]}return[BigInt(s),1n]} +// K1: the measure grammar of Python's `_fraction`, the reference: an optional sign and ASCII digits, a `.` with digits on both sides (at most 18 after it), `n/d`, or a mixed `w n/d`; nothing else. +// The classes spell Python's whitespace by hand, because JavaScript's `\s` and `trim` differ from it. +const PY_SPACE='\\t\\n\\v\\f\\r\\x1c-\\x1f \\x85\\xa0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000',ASCII_SPACE='[ \\t\\n\\r\\f\\v]'; +const MIXED_MEASURE=new RegExp(`^([+-]?[0-9]+)${ASCII_SPACE}+([0-9]+)${ASCII_SPACE}*/${ASCII_SPACE}*([0-9]+)$`),FRACTION_MEASURE=new RegExp(`^([+-]?[0-9]+)${ASCII_SPACE}*/${ASCII_SPACE}*([0-9]+)$`),DECIMAL_MEASURE=/^([+-]?)([0-9]+)(?:\.([0-9]+))?$/; +const MEASURE_SUFFIX=new RegExp(`^([^\\n]+?)[${PY_SPACE}]*(inches|ticks|inch|lbs|tick|mm|cm|ft|in|mg|kg|oz|lb|g|m)$`,'i'),PY_TRIM=new RegExp(`^[${PY_SPACE}]+|[${PY_SPACE}]+$`,'g'); +function rat(s){if(typeof s==='number'&&!Number.isInteger(s))throw new RangeError('a fractional number is not a measure'); + const text=String(s).replace(PY_TRIM,'').replace(/ /g,' '),mixed=MIXED_MEASURE.exec(text); + if(mixed){const d=BigInt(mixed[3]),whole=BigInt(mixed[1]),magnitude=(whole<0n?-whole:whole)*d+BigInt(mixed[2]);return [text.startsWith('-')?-magnitude:magnitude,d]} + const simple=FRACTION_MEASURE.exec(text);if(simple)return [BigInt(simple[1]),BigInt(simple[2])]; + const decimal=DECIMAL_MEASURE.exec(text);if(decimal===null)throw new RangeError(`invalid decimal or fraction: ${text}`); + const places=decimal[3]??'';if(places.length>18)throw new RangeError('decimal has more fractional digits than a tick can distinguish'); + const scale=10n**BigInt(places.length),magnitude=BigInt(decimal[2])*scale+BigInt(places===''?'0':places);return [decimal[1]==='-'?-magnitude:magnitude,scale]} function round(n,d){const sg=n<0n?-1n:1n,a=n<0n?-n:n,q=a/d,r=a%d;const z=r*2nd?q+1n:q%2n===0n?q:q+1n;return sg*z} -function scalar(v,def,table){let raw=v,unit=def;if(v&&typeof v==='object'){raw=v.value;unit=v.unit??def}else if(typeof v==='string'){const m=v.trim().match(/^(.+?)\s*(millimeters|millimeter|inches|ticks|inch|lbs|tick|mm|cm|ft|in|mg|kg|oz|lb|g|m)$/i);if(m){raw=m[1];unit=m[2]}}const[n,d]=rat(raw),exact=round(n*BigInt(table[unit.trim().toLowerCase()]),d),ticks=table===WT?exact:Number(exact);if(ticks<0)throw new RangeError(`${table===WT?'weight':'length'} cannot be negative`);return ticks} +function scalar(v,def,table){let raw=v,unit=def;if(v&&typeof v==='object'){raw=v.value;unit=v.unit??def}else if(typeof v==='string'){const m=MEASURE_SUFFIX.exec(v.replace(PY_TRIM,''));if(m){raw=m[1];unit=m[2]}}const[n,d]=rat(raw),exact=round(n*BigInt(table[unit.trim().toLowerCase()]),d),ticks=table===WT?exact:Number(exact);if(ticks<0)throw new RangeError(`${table===WT?'weight':'length'} cannot be negative`);return ticks} // With no `output.length_unit`, the request's own `units.length` spelt as the schema's // output code ("Inches" is `in`); a unit no output code names, the internal tick, gives `mm`. /** A length measure in `unit`, and a weight measure in grams, as exact ticks: the request @@ -678,6 +700,11 @@ export class BoundOverflowError extends Error{ this.name='BoundOverflowError'; } } +/** A billed objective's inventory cannot carry, at any price it lists, a packing that attains + * `L0`; no answer is compared against a bound then, so none is stated. */ +class BoundWithheld extends Error{ + constructor(reason){super(reason);this.name='BoundWithheld'} +} function boundGuard(total,quantity){ if(total>MAX_BOUND_SUM)throw new BoundOverflowError(quantity); return total; @@ -838,7 +865,11 @@ function objectiveBounds(instances,containers){ * ranks by. Any other objective has no bound. */ const BOUND_ORDERS=new Map([['default',[0,1,2,3,4]],['lowest_cost',[0,2,1,3,4]], ['maximum_value',[0,'value_forgone',1,2,3]],['open_dimension_height',[0,'achieved_height',1,2,3]], - ['maximum_volume',['unpacked_volume_ppm',0,1,2,3]]]); + ['maximum_volume',['unpacked_volume_ppm',0,1,2,3]], + ['shipping_cost',[0,'billed_weight',1,3,4]],['lowest_landed_cost',[0,'landed_charge',1,3,4]]]); +/** The objectives whose own key is what a carrier bills, which needs the configuration's + * dimensional-weight divisor and units as well as the request. */ +const BILLED_OBJECTIVES=new Set(['shipping_cost','lowest_landed_cost']); /** The sum of the `count` smallest values of unsorted `[value, count]` runs, without sorting * them: a max-heap holds only the runs the `count` smallest can still reach, and the run on * top contributes just the part of it they need. The bound already paid for its only sorts @@ -867,11 +898,14 @@ function runSmallestUnsorted(pairs,count){ * drops both volume terms. No term sorts: the volume runs are the ones the five bounds sorted, * and the values are selected, so the bound stays `O(t log t + c log c)`; `BigInt` until * `boundOutput`. */ -function objectiveTerm(name,volumes,values,shrinks,containers,unpacked){ +function objectiveTerm(name,volumes,weights,values,shrinks,containers,[unpacked,opened]){ if(name==='value_forgone')return runSmallestUnsorted(values,unpacked); + const placed=runCount(volumes)-unpacked; + if(name==='billed_weight')return billedWeightBound(weights,containers,placed,opened); + if(name==='landed_charge')return landedChargeBound(weights,volumes,shrinks,containers,placed,opened); if(shrinks)return 0n; if(name==='achieved_height'){ - const placed=runCount(volumes)-unpacked,widest=bigMax(containers.map(c=>c.baseArea)); + const widest=bigMax(containers.map(c=>c.baseArea)); return placed>0n&&widest>0n?boundCeilDiv(runSmallest(volumes,placed),widest):0n; } const requested=volumes.reduce((total,[value,count])=>total+value*count,0n),capacity=boundCapacity(containers,c=>c.usable); @@ -884,17 +918,144 @@ function objectiveTerm(name,volumes,values,shrinks,containers,unpacked){ function objectiveVector(order,volumes,weights,values,shrinks,containers){ const vector=objectiveBoundsFromRuns(volumes,weights,shrinks,containers); return order.map(position=>typeof position==='number'?vector[position] - :boundOutput(objectiveTerm(position,volumes,values,shrinks,containers,BigInt(vector[0])),position)); + :boundOutput(objectiveTerm(position,volumes,weights,values,shrinks,containers,[BigInt(vector[0]),BigInt(vector[1])]),position)); +} +/** What a carrier bills an opened container of this type at the least, `max(tare, dimensional)` + * in weight ticks: it is billed `max(tare + payload, dimensional)` whatever it carries. */ +const billingFloor=c=>c.tare>c.dimensional?c.tare:c.dimensional; +/** The sum of the `count` smallest of `{value repeated quantity}` from `[value, quantity]` + * pairs, or null when the inventory holds fewer. Sorting the types and taking + * `min(quantity, still needed)` of each is `L2`'s rule, `O(c log c)`, without the multiset. */ +function smallestFromInventory(pairs,count){ + let total=0n,needed=count; + for(const [value,quantity] of [...pairs].sort((a,b)=>bigAscending(a[0],b[0]))){ + if(needed<=0n)break; + const taken=quantity===null||quantity>needed?needed:quantity; + total+=value*taken;needed-=taken; + } + return needed>0n?null:total; +} +/** `shipping_cost`'s second key, summed billed weight in ticks. + * + * A packing that leaves exactly `L0` behind opens at least `opened` containers and carries at + * least the `placed` lightest instances. Each opened container is billed at least its floor + * and at least its tare plus what it carries, and a sum of maxima is at least either sum on + * its own, so the two are taken over different types. Every term is non-negative, so opening + * more only adds. `O(t + c log c)`. */ +function billedWeightBound(weights,containers,placed,opened){ + if(opened===0n)return 0n; + const floors=smallestFromInventory(containers.map(c=>[billingFloor(c),c.quantity]),opened); + const tares=smallestFromInventory(containers.map(c=>[c.tare,c.quantity]),opened); + if(floors===null||tares===null)throw new BoundWithheld('the inventory holds fewer containers than must be opened'); + const carried=tares+runSmallest(weights,placed); + return floors>carried?floors:carried; +} +/** `lowest_landed_cost`'s second key, the summed carrier charge in minor units. + * + * Every opened container is billed in exactly one bracket and pays its charge. A container in + * bracket `[bound, charge]` weighs at most `bound`, so it is reachable only when its floor is + * within it, carries at most `bound - tare` of payload (and its `max_payload`), and at most as + * many instances as the lightest-first count under that payload, its usable volume and + * `max_items`. Three relaxations of that assignment hold and the largest is the bound: the + * cheapest reachable charge per container over `opened` containers; the least cost covering + * the placed weight; the least cost covering the placed count. Prices need not rise with + * weight, which is why a bracket is chosen rather than read off the floor. A type no bracket + * prices offers nothing: a packing that opens one is refused, never returned. + * `O(t + c b log t + c b log(c b))` for `t` runs and `b` brackets per type. */ +function landedChargeBound(weights,volumes,shrinks,containers,placed,opened){ + if(opened===0n||placed===0n)return 0n; + const payloadPrefix=runPrefix(weights),volumePrefix=shrinks?null:runPrefix(volumes); + const cheapest=[],offers=[]; + for(const c of containers){ + const floor=billingFloor(c),reachable=c.brackets.filter(([bound,charge])=>charge!==null&&floor<=bound); + if(!reachable.length)continue; + cheapest.push([reachable.reduce((least,[,charge])=>charge[charge,carried,quantity]),runSmallest(weights,placed)); + const byItems=fractionalCover(offers.map(([charge,,count,quantity])=>[charge,count,quantity]),placed); + if(byCount===null||byWeight===null||byItems===null)throw new BoundWithheld('no priceable inventory carries a packing that attains L0'); + return bigMax([byCount,byWeight,byItems]); +} +/** Each ascending run with the instance count and total reached at its end, so a fit is a + * binary search: `O(t)` once, `O(log t)` per question. */ +function runPrefix(runs){ + let count=0n,total=0n; + return runs.map(([value,taken])=>{count+=taken;total+=value*taken;return [value,count,total]}); +} +/** `boundFit` over a `runPrefix`: how many of the lightest instances sum to at most `capacity`. + * The first run whose total passes it has a positive value, so it is taken in part. */ +function prefixFit(prefix,capacity){ + if(capacity<0n)return 0n; + let low=0,high=prefix.length; + while(low>1;if(prefix[middle][2]>capacity)high=middle;else low=middle+1} + const [,count,total]=low===0?[0n,0n,0n]:prefix[low-1]; + return low===prefix.length?count:count+(capacity-total)/prefix[low][0]; +} +/** The least cost covering `need` units from `[cost, capacity, quantity]` offers, taken + * fractionally and rounded up, or null when the offers cannot cover it. + * + * A fractional covering problem with one constraint is solved exactly by taking offers in + * order of cost per unit, compared by cross-multiplication so no fraction is formed. Only the + * last offer is taken in part, so the cost is an integer plus one ceiling. Offers of equal cost + * per unit give the same total in either order, so the order needs no tie-break. Each offer is + * limited by its type's whole inventory, which only weakens the bound. `O(k log k)`. */ +function fractionalCover(offers,need){ + if(need<=0n)return 0n; + const ranked=offers.filter(([,capacity])=>capacity>0n).sort((a,b)=>bigAscending(a[0]*b[1],b[0]*a[1])); + let total=0n,remaining=need; + for(const [cost,capacity,quantity] of ranked){ + if(quantity===null||quantity*capacity>=remaining)return total+boundCeilDiv(cost*remaining,capacity); + total+=cost*quantity;remaining-=capacity*quantity; + } + return null; +} +/** `floor(volume * weight ticks per unit / (length ticks per unit ^ 3 * divisor))`, in ticks. */ +const dimensionalTicks=(d,divisor,lengthUnit,weightUnit)=>volume(d)*BigInt(WT[weightUnit])/(BigInt(LEN[lengthUnit])**3n*BigInt(divisor)); +/** The rate table as `[bound in weight ticks, charge]`: the charge at a bracket's bound is that + * bracket's, `max(price, minimum)` then the surcharge rounded up, exact in `BigInt`. */ +function boundBrackets(table){ + if(table==null)return []; + const brackets=table.weight_brackets_g??[],prices=table.prices_minor??[]; + const minimum=BigInt(table.minimum_charge_minor??0),fuel=BigInt(table.fuel_surcharge_permille??0); + return brackets.slice(0,prices.length).map((grams,index)=>{ + const price=BigInt(prices[index]),base=price>minimum?price:minimum; + return [BigInt(grams)*BigInt(WT.g),base+boundCeilDiv(base*fuel,1000n)]; + }); +} +/** What a carrier can bill one container of a type, at the least. A rigid container + * is billed on its declared outer size, else its declared inner one: a pallet whose load + * overhangs is billed larger per side, never smaller, and dimensional weight only grows with + * each side. A bag is billed on the package its contents make, which can be smaller than + * declared, so its floor is 0. Null without the divisor the billed key needs. */ +function requestBilling(req,unit,measures){ + const configuration=req.configuration??{},divisor=configuration.dimensional_weight_divisor; + if(divisor==null)return null; + const lengthUnit=configuration.dimensional_weight_length_unit??'in',weightUnit=configuration.dimensional_weight_weight_unit??'lb'; + const landed=configuration.objective==='lowest_landed_cost'; + return raw=>({tare:BigInt(measures.weight(raw.tare_weight??0)), + dimensional:raw.deformable_boundary!=null?0n:dimensionalTicks(measures.sides(raw.outer_dimensions??raw.inner_dimensions,unit),divisor,lengthUnit,weightUnit), + brackets:landed?boundBrackets(raw.rate_table):[]}); } /** The request's bound in its objective's own score order, or null where none is stated. * * Read from the request itself, as every engine reads it: every item type with its whole * quantity (fixed placements are part of it), every container type, lengths in * ticks and volumes formed in `BigInt` from them, never as a `Number` product converted - * afterwards (F3). Null for an objective with no bound, for a request with a made-to-measure - * container (D13), and for a request past a declared ceiling, which withholds the - * bound and nothing else (OPTIMALITY-GAP.md § 1.5). `O(t log t + c log c)` for `t` item - * types and `c` container types. */ + * afterwards (F3). Null for an objective with no bound, for a billed objective without its + * divisor or whose inventory cannot carry a packing that attains `L0` at a price, + * for a request with a made-to-measure container (D13), and for a request past a + * declared ceiling, which withholds the bound and nothing else (OPTIMALITY-GAP.md § 1.5). + * `O(t log t + c log c)` for `t` item types and `c` container types, and + * `O(c b log t + c b log(c b))` more for `lowest_landed_cost`'s `b` brackets per type. */ /** The inner size every solver packs: a pallet's widened frame, else the declared one. */ function solvingDimensions(raw,unit,measures){const declared=measures.sides(raw.inner_dimensions,unit),limit=raw.pallet_overhang_limit; return limit==null?declared:solvingFrame(declared,measures.length(limit.length,unit),measures.length(limit.width,unit)).d} @@ -904,6 +1065,8 @@ function requestBound(req,measures){ const rawContainers=req.containers??[]; if(rawContainers.some(c=>c.made_to_measure!=null))return null; const unit=req.units?.length??'mm'; + const billing=BILLED_OBJECTIVES.has(req.configuration?.objective)?requestBilling(req,unit,measures):()=>({}); + if(billing===null)return null; const items=(req.items??[]).map(raw=>({raw,count:BigInt(raw.quantity??1)})).filter(item=>item.count>0n); const volumes=boundRuns(items.map(({raw,count})=>[volume(measures.sides(raw.dimensions,unit)),count])); const weights=boundRuns(items.map(({raw,count})=>[BigInt(measures.weight(raw.weight??0)),count])); @@ -915,10 +1078,10 @@ function requestBound(req,measures){ baseArea:BigInt(d[0])*BigInt(d[1]),height:BigInt(d[2]), payload:raw.max_payload==null?null:BigInt(measures.weight(raw.max_payload)), maxItems:raw.max_items==null?null:BigInt(raw.max_items), - quantity:raw.quantity==null?null:BigInt(raw.quantity),costMinor:BigInt(raw.cost_minor??0)}; + quantity:raw.quantity==null?null:BigInt(raw.quantity),costMinor:BigInt(raw.cost_minor??0),...billing(raw)}; }); try{return objectiveVector(order,volumes,weights,values,shrinks,containers)} - catch(error){if(error instanceof BoundOverflowError)return null;throw error} + catch(error){if(error instanceof BoundOverflowError||error instanceof BoundWithheld)return null;throw error} } /** What one score states against `bound`, both in the result's own score order * (OPTIMALITY-GAP.md § 1.1): the bound through the first missed position with the gap @@ -959,10 +1122,20 @@ export function __runSmallestUnsortedForTests(pairs,count){return runSmallestUns export function __objectiveVectorForTests(instances,containers,objective){ const runs=field=>boundRuns(instances.map(i=>[i[field],1n])); try{return objectiveVector(BOUND_ORDERS.get(objective),runs('volume'),runs('weight'),instances.map(i=>[i.value,1n]),instances.some(i=>i.shrinks),containers)} - catch(error){if(error instanceof BoundOverflowError)return null;throw error} + catch(error){if(error instanceof BoundOverflowError||error instanceof BoundWithheld)return null;throw error} } +export function __fractionalCoverForTests(offers,need){return fractionalCover(offers,need);} +export function __billedWeightBoundForTests(weights,containers,placed,opened){return billedWeightBound(weights,containers,placed,opened);} export function __requestBoundForTests(req){return requestBound(req,requestMeasures().close());} export function __occupiesLessThanItsBoxForTests(item){return occupiesLessThanItsBox(item);} +const BOX_SHAPE_ENTRIES=1024,boxShapes=new Map(); +/** One shared shape per box size, so a pair of shapes has a stable identity to be keyed by. */ +function boxShapeFor(dx,dy,dz){ + const key=dx+','+dy+','+dz,found=boxShapes.get(key); + if(found!==undefined)return found; + if(boxShapes.size>=BOX_SHAPE_ENTRIES)boxShapes.clear(); + const shape=boxShape(dx,dy,dz);boxShapes.set(key,shape);return shape; +} function boxShape(dx,dy,dz){ const v=[]; for(const x of [0n,BigInt(dx)])for(const y of [0n,BigInt(dy)])for(const z of [0n,BigInt(dz)])v.push([x,y,z]); @@ -989,17 +1162,34 @@ function separatingAxes(left,right){ } return [...axes.values()]; } +/** The separating axes of an ordered pair of shapes and each shape's projection interval on + * every one: all of it depends on the two shapes and not on where they sit, so a collision + * only adds the origins' dot products. Keyed by the shapes' identities, which is sound because + * `shapeFor` and `boxShapeFor` hand out one object per shape and nothing mutates a shape. + * Bounded twice, by entries and by total axes, and emptied whole when either is passed, so the + * contents depend only on the call sequence. */ +const PAIR_PLAN_ENTRIES=256,PAIR_PLAN_AXES=60000; +const pairPlans=new Map(),shapeIds=new WeakMap();let pairPlanAxes=0,shapesIdentified=0; +const shapeId=shape=>{let id=shapeIds.get(shape);if(id===undefined){id=++shapesIdentified;shapeIds.set(shape,id)}return id}; +const projectOnto=(shape,axis)=>{let low=null,high=null; + for(const v of shape.v){const value=dot3(v,axis); + if(low===null||valuehigh)high=value} + return [low,high]}; +function pairPlan(left,right){ + const key=shapeId(left)+','+shapeId(right),found=pairPlans.get(key); + if(found!==undefined)return found; + const axes=separatingAxes(left,right),plan={axes,left:axes.map(axis=>projectOnto(left,axis)),right:axes.map(axis=>projectOnto(right,axis))}; + if(pairPlans.size>=PAIR_PLAN_ENTRIES||pairPlanAxes+axes.length>PAIR_PLAN_AXES){pairPlans.clear();pairPlanAxes=0} + pairPlans.set(key,plan);pairPlanAxes+=axes.length; + return plan; +} /** Do two placed hulls overlap with positive volume? Touching is contact, not collision: the * comparison is `<=`, matching the half-open convention cuboids already use. */ function hullsCollide(left,leftOrigin,right,rightOrigin){ - const lo=big3(leftOrigin),ro=big3(rightOrigin); - for(const axis of separatingAxes(left,right)){ - const project=shape=>{let low=null,high=null; - for(const v of shape.v){const value=dot3(v,axis); - if(low===null||valuehigh)high=value} - return [low,high]}; - const [ll,lh]=project(left),[rl,rh]=project(right); - const ls=dot3(lo,axis),rs=dot3(ro,axis); + const lo=big3(leftOrigin),ro=big3(rightOrigin),{axes,left:leftSpans,right:rightSpans}=pairPlan(left,right); + for(let i=0;iplan.inventory.get(t.id)>0);if(!plan.remaining.length||!available.length)return 0;let lower=0; if(!plan.remaining.some(item=>item.nesting!=null)){const capacity=available.reduce((best,t)=>volume(t.d)>best?volume(t.d):best,0n),required=plan.remaining.reduce((sum,item)=>sum+itemOccupiedVolume(item),0n);if(capacity>0n)lower=Math.max(lower,Number((required+capacity-1n)/capacity))} - if(available.every(t=>t.max!=null)){const capacity=Math.max(...available.map(t=>t.max)),required=plan.remaining.reduce((sum,item)=>sum+item.w,0n);if(capacity>0)lower=Math.max(lower,Math.ceil(required/capacity))}return lower} + if(available.every(t=>t.max!=null)){const capacity=available.reduce((best,t)=>t.max>best?t.max:best,0n),required=plan.remaining.reduce((sum,item)=>sum+item.w,0n);if(capacity>0n)lower=Math.max(lower,Number((required+capacity-1n)/capacity))}return lower} export function __additionalContainerBoundForTests(plan,templates){return additionalContainerBound(plan,templates)} /** First compressible box carrying more pressure than it declared it can take. * @@ -1339,7 +1529,7 @@ function axleBalancedPoints(container,placements,points,item,clearance){ const {front,rear}=axleBalancedOrigins(container,load,item.w,length),last=BigInt(container.d[0]-length); for(const origin of [front,rear])if(origin!=null&&origin>=0n&&origin<=last)for(const y of floorYs)out.push([Number(origin),y,0])} return out} -function fitsTemplateAlone(c,d){return d.every((edge,k)=>edge<=c.d[k])&&(!c.bag||(d[0]+d[2]<=c.d[0]&&d[1]+d[2]<=c.d[1]+c.gusset))} +function fitsTemplateAlone(c,d){return d.every((edge,k)=>edge<=c.d[k])&&(!c.bag||girthAdmits(c.girth,d))} // The container limit that left an item out, for the search_exhausted // fallback, or null when none explains it. The same rule, in the same order, as every // engine: an axle that refuses the item alone in every container otherwise admitting it, @@ -1441,6 +1631,24 @@ function doubleFraction(value){ const mantissa=exponent===0?fraction:fraction|(1n<<52n),shift=(exponent===0?1:exponent)-1075; return shift>=0?[mantissa<=0?n<=0?d:d<>extra; + if(tail>half||(tail===half&&(inexact||mantissa%2n===1n)))mantissa+=1n; + return Number(mantissa)*2**(Number(extra)-shift); +} +// A reported ratio: six places of that double, as Python's `f"{a / b:.6f}"` writes it. An exact +// decimal half therefore follows the double it lands on (50/20000000 -> 0.000003), not the even digit. +const ratioPlaces=(numerator,denominator)=>sixPlaces(...doubleFraction(ratioDouble(numerator,denominator))); // `decimalString` for a safe-integer tick count, in Number arithmetic. Every intermediate is an // integer below 10 * divisor or below |v|, so each `%` and each exact quotient is exact and the // digits, the rounding and the text are the BigInt path's own; a result writes six of these per @@ -1595,6 +1803,14 @@ function compareFarCorner(a,b){const ae=a.ed,be=b.ed; return (a.z+ae[2])-(b.z+be[2])||(a.y+ae[1])-(b.y+be[1])||(a.x+ae[0])-(b.x+be[0]) ||a.z-b.z||a.y-b.y||a.x-b.x ||(a.item.shapeType==='convex_hull'?ROT_INDEX[a.r]-ROT_INDEX[b.r]:0)} +// S-08: the order each solver alias ranks candidates by, field by field. These were weighted sums +// (`z*1e12+y*1e6+x` and the like) that pass 2^53 at realistic sizes, so sub-ulp steps collapsed to +// ties and a term outweighed the next one. Each is the lexicographic reading of the sum it replaces. +const compareOriginFirst=(a,b)=>a.z-b.z||a.y-b.y||a.x-b.x; +const compareLayered=(a,b)=>(a.z+a.ed[2])-(b.z+b.ed[2])||a.z-b.z||a.y-b.y||a.x-b.x; +const compareMaximalSpaces=(a,b)=>(a.z+a.ed[2])-(b.z+b.ed[2])||(a.x+a.ed[0]+a.y+a.ed[1])-(b.x+b.ed[0]+b.y+b.ed[1]); +// A multi-drop sweep ranks x first, so what leaves last stands deepest. +const compareRouteFirst=(a,b)=>(a.x+a.ed[0])-(b.x+b.ed[0])||(a.y+a.ed[1])-(b.y+b.ed[1])||(a.z+a.ed[2])-(b.z+b.ed[2]); // Keep only the requested prefix: the root is the worst score, latest tie first. // Ordinals make heap eviction preserve the stable full-sort order exactly. function compareRetained(a,b,tieBreak=noTieBreak){return a.score-b.score||tieBreak(a.candidate,b.candidate)||a.ordinal-b.ordinal} @@ -1672,11 +1888,22 @@ function groundContactAllowed(candidate,placed,supports=null){const rule=candida if(rule==='covered'){const corners=[[box.x,box.y],[box.x+box.d[0],box.y],[box.x,box.y+box.d[1]],[box.x+box.d[0],box.y+box.d[1]]];return corners.every(([x,y])=>supporters.some(({placement})=>{const d=placementDimensions(placement);return placement.x<=x&&x<=placement.x+d[0]&&placement.y<=y&&y<=placement.y+d[1]}))}return true} /**: a candidate may not become the second supporter of an item already resting on exactly * one, as `ground_contact_rule: single` requires; the item's own check ran before the candidate - * existed. Only items whose base the candidate's top face reaches are counted again. O(n). */ -function singleSupportsKept(candidate,placed){ - const top=candidate.z+placementDimensions(candidate)[2];let scene=null; - for(const other of placed){ - if(other.item.groundRule!=='single'||other.z!==top)continue; + * existed. Only items whose base is the candidate's top plane can gain it, and only through + * footprint overlap: a nested predecessor shares its column's footprint. A searched, + * non-nesting item there already rests on exactly one supporter -- its own check, kept since + * by this one -- so touching it makes two and is refused without a recount. Fixed and nesting + * items entered without that guarantee or can shadow a face contact, so they are recounted + * exactly. O(b) per candidate for the b placements on that plane, plus O(n) for each fixed or + * nesting single-rule item there. */ +function singleSupportsKept(candidate,placed,sweep){ + const dimensions=placementDimensions(candidate),level=sweep.bottomPlane().get(candidate.z+dimensions[2]); + if(level===undefined)return true; + let scene=null; + for(let index=0;index0)return false; + continue} if(scene===null)scene=[...placed,candidate]; if(directSupporters(other,scene).length!==1)return false; } @@ -1913,7 +2140,7 @@ function allowed(candidate,placed,container,globalSupportPpm,metrics,loadBase=nu const needsLoads=container.maxStackDensity!=null||candidate.item.maxTop!=null||scene.placedMaxTop ||candidate.item.maxCompressionKpa!=null||scene.placedCompressible; const needsGraph=needsLoads||candidate.item.maxStacked!=null||scene.placedMaxStacked; - if(!groundContactAllowed(candidate,placed,supports)||!singleSupportsKept(candidate,placed)||!routeContactAllowed(candidate,placed,supports,scene))return false; + if(!groundContactAllowed(candidate,placed,supports)||!singleSupportsKept(candidate,placed,scene)||!routeContactAllowed(candidate,placed,supports,scene))return false; if(!needsGraph)return accessBase===null||accessBase.inert||accessibleAgainst(accessBase,corridorBox(candidate)); // With a base for this sweep, both the box list and the graph come from it by // appending one box, rather than each candidate rebuilding both from every placement. @@ -2196,8 +2423,8 @@ function compactGridResult(req,{measures,u,ou,ow,clear,objective,dimensionalWeig // `shipping_cost`, whose proxy it is; re-enabling compact for landed cost would // resurrect the MAX_SAFE_INTEGER leak, since this return path has no refusal. templates.sort((a,b)=>objective==='shipping_cost'||objective==='lowest_landed_cost' - ?compareWeights(dimensionalWeight(a.outerD),dimensionalWeight(b.outerD))||(a.cost_minor??0)-(b.cost_minor??0)||Number(volume(a.d)-volume(b.d)) - :(a.cost_minor??0)-(b.cost_minor??0)||Number(volume(a.d)-volume(b.d))); + ?compareWeights(dimensionalWeight(a.outerD),dimensionalWeight(b.outerD))||(a.cost_minor??0)-(b.cost_minor??0)||Number(volume(a.d)-volume(b.d))||compareCodePoints(a.id,b.id) + :(a.cost_minor??0)-(b.cost_minor??0)||Number(volume(a.d)-volume(b.d))||compareCodePoints(a.id,b.id)); let remaining=quantity,scoreCost=0,scoreUnused=0,scoreHeight=0,scoreBillable=0n,scoreLanded=0,scoreAchievedHeight=0; const containers=[],maxContainers=req.configuration?.max_containers??Infinity; // Per-unit capacity depends only on (item, template), both fixed for the @@ -2323,7 +2550,7 @@ function compactGridResult(req,{measures,u,ou,ow,clear,objective,dimensionalWeig id:`${template.id}#${plan.opened}`,container_type:template.id,inner_dimensions:outDims(template.d,ou), outer_dimensions:outDims(template.outerD,ou),payload_weight:outWeight(payload,ow), gross_weight:outWeight(payload+template.tare,ow),used_volume_ticks3:used.toString(), - volume_utilization:sixPlaces(used,volume(template.d)), + volume_utilization:ratioPlaces(used,volume(template.d)), centre_of_mass_offset_ppm:latticeCentreOfMassOffsetPpm(summary,template.d), void_fill_reserve_ticks3:'0', placements:wantCoordinates?latticePlacements({best,count,firstIndex,raw,weight,clear,ou,ow,containerId:`${template.id}#${plan.opened}`}):[], @@ -2397,7 +2624,7 @@ function compactGridResult(req,{measures,u,ou,ow,clear,objective,dimensionalWeig const defaultScore=[remaining,containers.length,scoreCost,scoreUnused,scoreHeight]; const score=objective==='lowest_cost'?[defaultScore[0],defaultScore[2],defaultScore[1],defaultScore[3],defaultScore[4]] :objective==='shipping_cost'?[defaultScore[0],exactTicks(scoreBillable),defaultScore[1],defaultScore[3],defaultScore[4]] - :objective==='lowest_landed_cost'?[defaultScore[0],scoreLanded,defaultScore[1],defaultScore[3],defaultScore[4]] + :objective==='lowest_landed_cost'?[defaultScore[0],reportedLanded(scoreLanded),defaultScore[1],defaultScore[3],defaultScore[4]] :objective==='open_dimension_height'?[defaultScore[0],scoreAchievedHeight,defaultScore[1],defaultScore[2],defaultScore[3]] :objective==='maximum_value'?[defaultScore[0],remaining*(raw.value??0),defaultScore[1],defaultScore[2],defaultScore[3]] // One item type, so the most pieces is also the most volume and the lattice needs @@ -2601,14 +2828,14 @@ function subtractBlock(spaces,box,metrics){metrics.space_partitions+=spaces.leng // In this order a space that contains another sorts before it: its origin is no greater // on every axis, and at an equal origin its volume is larger (no two spaces here are equal), // so a slab is tested only against the spaces ahead of it. - const kept=out.sort((a,b)=>a.z-b.z||a.y-b.y||a.x-b.x||(a.volume>b.volume?-1:1)); + const kept=out.sort((a,b)=>a.z-b.z||a.y-b.y||a.x-b.x||(a.volume>b.volume?-1:a.volume!fresh.has(space)||!containedByEarlier(kept,index)); if(result.length>256)result=result.sort((a,b)=>a.volume>b.volume?-1:a.volumea.z-b.z||a.y-b.y||a.x-b.x); return result} // The result writer's shortcuts, held to the code paths they bypass by // `test/result-writer.test.mjs`. export const __resultWriterForTests=Object.freeze({decimalString,usedVolume,validNesting,occupiedVolume}); -export const __ratiosForTests=Object.freeze({scaledRatio,supportPpm,sixPlaces,doubleFraction}); +export const __ratiosForTests=Object.freeze({scaledRatio,supportPpm,sixPlaces,doubleFraction,ratioDouble,ratioPlaces}); export const __planBeamForTests=Object.freeze({compareIdLists,planSignature}); export const __blockGroupForTests=Object.freeze({nodes:blockGroupNodes,stop:blockStopNode,best:blockGroupBest,typeTally:blockTypeTally, space:blockSpace,subtract:subtractBlock}); @@ -2937,6 +3164,8 @@ let timeLimitReached=false; // Python, PHP and Rust read it every 64th node: a counted limit is still checked at each // one, and only where a wall-clock stop lands can move. let candidateClockTick=0; +// True only while the support diagnosis replays a finished layout: that verdict is a function of the request and the layout, so it must not read the clock. +let replayingSupport=false; const metrics={candidate_points_considered:0,orientations_considered:0,feasible_candidates:0,collision_checks:0,support_checks:0,space_partitions:0,search_nodes_expanded:0}; // The value of each budgeted counter at which the effort budget stops this frame's search; // Infinity for a limit the request leaves out. `let`: the support replay lifts them, as @@ -3058,8 +3287,11 @@ if(startOrder?.seen!=null){const typeOf=new Map(req.items.map((raw,index)=>[raw, for(let at=0;at+1{const declared=measures.sides(c.inner_dimensions,u),limit=c.pallet_overhang_limit; - const frame=limit==null?null:solvingFrame(declared,measures.length(limit.length,u),measures.length(limit.width,u)),d=frame===null?declared:frame.d,axleSpec=c.axles==null?null:c.axles.map(a=>({position:measures.length(a.position,u),max:a.max_load==null?null:measures.weight(a.max_load)})); + const girth=bagGirth(c.deformable_boundary,declared,value=>measures.length(value,u)); + const frame=limit==null?null:solvingFrame(declared,measures.length(limit.length,u),measures.length(limit.width,u)),d=frame!==null?frame.d:girth?.standing?standingFrame(declared):declared,axleSpec=c.axles==null?null:c.axles.map(a=>({position:measures.length(a.position,u),max:a.max_load==null?null:measures.weight(a.max_load)})); if(axleSpec&&(axleSpec.length!==2||axleSpec[0].position>=axleSpec[1].position||axleSpec[0].position<0||axleSpec[1].position>d[0]))throw new RangeError('axles must be [front, rear] inside the container'); const reservePpm=scaledRatio(c.void_fill_reserve_ratio??0); if(c.tag_limits!=null&&(typeof c.tag_limits!=='object'||Array.isArray(c.tag_limits)||Object.values(c.tag_limits).some(limit=>!Number.isSafeInteger(limit)||limit<1)))throw new RangeError('tag_limits must map strings to positive safe integers'); @@ -3074,10 +3306,10 @@ const templates=req.containers.map(c=>{const declared=measures.sides(c.inner_dim // Python, PHP and Rust decoders apply, and the reason all four agree on the answer. validateDirections(c.access_directions??[]); const doors=Object.freeze(ALL_DIRECTIONS.filter(d=>(c.access_directions??[]).includes(d))); - return {...c,d,outerD,deck:frame===null?null:frame.deck,doors,bag:c.deformable_boundary!=null,gusset:c.deformable_boundary?.side_gusset_depth==null?0:measures.length(c.deformable_boundary.side_gusset_depth,u),machine:parseMachine(c.made_to_measure,u,measures),max:c.max_payload==null?null:measures.weight(c.max_payload),tare:measures.weight(c.tare_weight??0),axleSpec,reservePpm, + return {...c,d,outerD,deck:frame===null?null:frame.deck,doors,bag:girth!==null,girth,machine:parseMachine(c.made_to_measure,u,measures),max:c.max_payload==null?null:measures.weight(c.max_payload),tare:measures.weight(c.tare_weight??0),axleSpec,reservePpm, innerVolume:volume(d),reserve:volume(d)*BigInt(reservePpm)/BigInt(SUPPORT_SCALE), rate:parseRateTable(c.rate_table),tagLimits:c.tag_limits??{},maxStackDensity, - obs:(c.obstacles??[]).flatMap(o=>[o,...(o.additional_boxes??[])]).map(o=>({x:measures.length(o.origin?.x??0,u),y:measures.length(o.origin?.y??0,u),z:measures.length(o.origin?.z??0,u),d:measures.sides(o.dimensions,u)}))}}).sort((a,b)=>objective==='shipping_cost'||objective==='lowest_landed_cost'?(compareWeights(dimensionalWeight(a.outerD),dimensionalWeight(b.outerD))||(a.cost_minor??0)-(b.cost_minor??0)||Number(volume(a.d)-volume(b.d))):((a.cost_minor??0)-(b.cost_minor??0)||Number(volume(a.d)-volume(b.d)))); + obs:(c.obstacles??[]).flatMap(o=>[o,...(o.additional_boxes??[])]).map(o=>({x:measures.length(o.origin?.x??0,u),y:measures.length(o.origin?.y??0,u),z:measures.length(o.origin?.z??0,u),d:measures.sides(o.dimensions,u)}))}}).sort((a,b)=>objective==='shipping_cost'||objective==='lowest_landed_cost'?(compareWeights(dimensionalWeight(a.outerD),dimensionalWeight(b.outerD))||(a.cost_minor??0)-(b.cost_minor??0)||Number(volume(a.d)-volume(b.d))||compareCodePoints(a.id,b.id)):((a.cost_minor??0)-(b.cost_minor??0)||Number(volume(a.d)-volume(b.d))||compareCodePoints(a.id,b.id))); // Admission of fixed placements, before any search: the containers they name, each holding // only its fixed items, in opening order. Their instances leave the free list. const fixedGroups=admitFixedPlacements(req,{items,templates,u,clear}); @@ -3162,7 +3394,7 @@ const sweepCandidates=(tmpl,item,state,candidates,index,used,width,supportRatioP // With no doors the base is inert and admits every candidate, so the sweep skips building it. const accessBase=tmpl.doors.length?stopAccessibilityBase(item.stopIndex,state.placements,tmpl,tmpl.doors):null; const compressionSensitive=item.shapeType==='compressible'||anyCompressiblePlaced(state.placements); - const found=[];let bestScore=0; + const found=[]; // Fixed for the sweep: neither the doors nor any placed stop change inside it. const routeSensitive=tmpl.doors.length>0&&(item.stopIndex!=null||state.placements.some(p=>p.item.stopIndex!=null)); // JavaScript registers no candidate scorers, so the extreme-point score is Rust's empty @@ -3170,7 +3402,7 @@ const sweepCandidates=(tmpl,item,state,candidates,index,used,width,supportRatioP // The grid stands down for a pallet as the reference's does, to the extreme-point order. const alias=solverAlias==='grid'&&tmpl.deck!=null?'extreme_points':solverAlias; const farCornerRanked=alias!=='grid'&&alias!=='layer'&&alias!=='maximal_spaces'&&!routeSensitive; - const tieBreak=farCornerRanked?compareFarCorner:noTieBreak; + const tieBreak=farCornerRanked?compareFarCorner:alias==='grid'?compareOriginFirst:alias==='layer'?compareLayered:alias==='maximal_spaces'?compareMaximalSpaces:compareRouteFirst; // Everything that is a function of (item, rotation) alone -- the rotated envelope, the // volume it occupies, its hull -- is computed once per sweep here rather than once per // point, the class of waste docs/PERFORMANCE-PRACTICE.md ranks first. The volume gate is @@ -3192,18 +3424,20 @@ const sweepCandidates=(tmpl,item,state,candidates,index,used,width,supportRatioP orientations.push({r,pd,ed,shape:exactHull?shapeFor(item.hullVertices,r):null, volumeBlocked:boxVolumeBlocked??(volumeGated&&occupiedVolume({pd,r,item})>volumeRoom)})} const [innerX,innerY,innerZ]=tmpl.d,obstacles=tmpl.obs; - // A bag also needs a + c <= L and b + c <= W + G over the extents grown by the candidate - // (G is a gusseted bag's side gusset, 0 for a flat one): O(p) once per sweep, + // A bag also needs both loops of film round the extents grown by the candidate (`bagGirth`: + //, 1.10 side gussets, bottom gussets and standing): O(p) once per sweep, // O(1) per candidate, and a verdict never flips later. // Read as scalars, not destructured, so a rigid container pays nothing for the rule. const bag=Boolean(tmpl.bag),bagExtents=bag?bagExtent(placements):null,bagX=bag?bagExtents[0]:0,bagY=bag?bagExtents[1]:0,bagZ=bag?bagExtents[2]:0; - const girthY=innerY+(bag?tmpl.gusset:0); + const standing=bag&&tmpl.girth.standing,bottomGusset=bag?tmpl.girth.bottom:0,sideGusset=bag?tmpl.girth.side:0; const baseAxle=tmpl.axleSpec==null?null:axleLoad(tmpl,placements); candidatePoints:for(let pointIndex=0;pointIndex=attemptCeiling){effortStopped=true;break}metrics.candidate_points_considered++;const x=pt[0],y=pt[1],z=pt[2]; - for(let orientationIndex=0;orientationIndex=attemptCeiling){effortStopped=true;break candidatePoints}metrics.orientations_considered++;if((candidateClockTick++&63)===0&&deadline.expired()){timeLimitReached=true;break candidatePoints} + for(let orientationIndex=0;orientationIndex=attemptCeiling){effortStopped=true;break candidatePoints}metrics.orientations_considered++;if((candidateClockTick++&63)===0&&!replayingSupport&&deadline.expired()){timeLimitReached=true;break candidatePoints} const {r,pd,ed}=orientation,x2=x+ed[0],y2=y+ed[1],z2=z+ed[2]; if(x2>innerX||y2>innerY||z2>innerZ)continue; - if(bag&&(Math.max(x2,bagX)+Math.max(z2,bagZ)>innerX||Math.max(y2,bagY)+Math.max(z2,bagZ)>girthY))continue; + // The frame's own sides are the loops' bounded sides: L is innerX lying flat and innerZ standing. + if(bag&&(standing?2*((Math.max(z2,bagZ)-innerZ)+Math.max(y2,bagY))>bottomGusset||(Math.max(x2,bagX)-innerX)+Math.max(y2,bagY)>sideGusset + :2*((Math.max(x2,bagX)-innerX)+Math.max(z2,bagZ))>bottomGusset||(Math.max(y2,bagY)-innerY)+Math.max(z2,bagZ)>sideGusset))continue; if(payloadBlocked||countBlocked||orientation.volumeBlocked)continue; let candidate=nests?{x,y,z,pd,ed,r,item}:null,box=null; if(nests&&!compressionSensitive&&usedVolumeDelta(placements,candidate)>volumeRoom)continue; @@ -3255,14 +3489,8 @@ const sweepCandidates=(tmpl,item,state,candidates,index,used,width,supportRatioP // not the attempts before it that find nothing feasible. if(metrics.feasible_candidates>=candidateCeiling){effortStopped=true;break candidatePoints} metrics.feasible_candidates++; - const score=farCornerRanked?0:alias==='grid' - ?z*1e12+y*1e6+x - :alias==='layer' - ?z2*1e12+z*1e8+y*1e4+x - :alias==='maximal_spaces' - ?x2+y2+z2*1e6 - :x2*1e9+y2*1e4+z2; - if(width===1){if(!found.length||(score-bestScore||tieBreak(candidate,found[0]))<0){found[0]=candidate;bestScore=score}continue} + const score=0; + if(width===1){if(!found.length||tieBreak(candidate,found[0])<0)found[0]=candidate;continue} if(width!=null){retainCandidate(found,width,score,metrics.feasible_candidates,candidate,tieBreak);continue} found.push({score,candidate})}} // A returned candidate is the box itself, without its score: it becomes a placement, and a @@ -3282,7 +3510,7 @@ const sweepCandidates=(tmpl,item,state,candidates,index,used,width,supportRatioP // already run. const candidatesFor=(tmpl,item,state,points,index,used,width,supportRatioPpm)=>{ const found=sweepCandidates(tmpl,item,state,points.length>maxCandidatePoints?points.slice(0,maxCandidatePoints):points,index,used,width,supportRatioPpm); - if(tmpl.axleSpec==null||item.w<=0||found.length||timeLimitReached)return found; + if(tmpl.axleSpec==null||item.w<=0||found.length||(timeLimitReached&&!replayingSupport))return found; return sweepCandidates(tmpl,item,state,axleBalancedPoints(tmpl,state.placements,points,item,clear),index,used,width,supportRatioPpm)}; const tryPackIntoTemplate=(tmpl,itemsRemaining)=>{const seeded=seedState(tmpl),state=seeded.state;const next=[]; // Running `usedVolume` of `state.placements`, maintained incrementally rather than @@ -3600,7 +3828,7 @@ const blockLattices=prototype=>{const seen=new Set(),lattices=[]; // of the space and a capacity alone, and a lattice of the type alone. const blockStart=(tmpl,itemsRemaining)=>{const byType=new Map(); for(const item of itemsRemaining){const values=byType.get(item.raw.id)??[];values.push(item);byType.set(item.raw.id,values)} - return {state:{tmpl,placements:[],payload:0n},spaces:[blockSpace(0,0,0,tmpl.d.slice())],byType,itemIds:[...byType.keys()].sort(),lattices:new Map()}}; + return {state:{tmpl,placements:[],payload:0n},spaces:[blockSpace(0,0,0,tmpl.d.slice())],byType,itemIds:[...byType.keys()].sort(compareCodePoints),lattices:new Map()}}; const blockOpen=round=>round.spaces.length>0&&[...round.byType.values()].some(values=>values.length); const blockCopy=round=>({state:{tmpl:round.state.tmpl,placements:round.state.placements.slice(),payload:round.state.payload}, spaces:round.spaces,byType:new Map([...round.byType].map(([key,values])=>[key,values.slice()])),itemIds:round.itemIds,lattices:round.lattices}); @@ -3860,7 +4088,7 @@ if(containerPlanBeamWidth>1&&solverAlias!=='exact_small'){ for(const c of packed){const n=(counts.get(c.tmpl.id)??0)+1;counts.set(c.tmpl.id,n);c.seq=n}} const containers=packed.map(c=>{const loads=topLoads(c.placements.map(constraintBox)),used=usedVolume(c.placements),topPlane=bucketByPlane(c.placements,p=>p.z+placementDimensions(p)[2]); const reaction=axleReactions(c.tmpl,c.placements); - return {id:`${c.tmpl.id}#${c.seq}`,container_type:c.tmpl.id,inner_dimensions:outDims(declaredInner(c.tmpl.d,c.tmpl.deck),ou),outer_dimensions:outDims(c.tmpl.machine?c.tmpl.outerD:c.tmpl.outer_dimensions?dims(c.tmpl.outer_dimensions,u):declaredInner(c.tmpl.d,c.tmpl.deck),ou),...(c.tmpl.deck!=null?{achieved_dimensions:outDims(achievedDimensions(c.tmpl.deck,c.placements),ou)}:c.tmpl.bag||c.tmpl.machine?{achieved_dimensions:outDims(bagExtent(c.placements),ou)}:{}),...(c.tmpl.machine?{made_to_measure:{cost_minor:c.tmpl.cost_minor,tare_weight:outWeight(c.tmpl.tare,ow)}}:{}),payload_weight:outWeight(c.payload,ow),gross_weight:outWeight(c.payload+c.tmpl.tare,ow),used_volume_ticks3:used.toString(),volume_utilization:sixPlaces(used,volume(c.tmpl.d)),centre_of_mass_offset_ppm:centreOfMassOffsetPpm(c.tmpl,c.placements,clear),...(reaction==null?{}:{axle_reactions:{basis:'gross',denominator:reaction.denominator.toString(),front_numerator:reaction.front.toString(),rear_numerator:reaction.rear.toString()}}),void_fill_reserve_ticks3:(volume(c.tmpl.d)*BigInt(c.tmpl.reservePpm)/BigInt(SUPPORT_SCALE)).toString(),placements:c.placements.map((p,i)=>({placement_id:placementId(`${c.tmpl.id}#${c.seq}`,[p.x+clear,p.y+clear,p.z+clear],p.item.raw.id,p.r),item_id:p.item.id,item_type:p.item.raw.id,position:outPoint({x:p.x+clear,y:p.y+clear,z:p.z+clear},ou),dimensions:outDims(p.pd,ou),orientation:p.r,support_ratio:sixPlaces(...(p.fixed?p.fixedSupport:supportFraction(p,c.placements,topPlane,c.tmpl.deck))),top_load:outWeight(loads[i],ow),...(p.fixed?{fixed:true}:{})}))}}); + return {id:`${c.tmpl.id}#${c.seq}`,container_type:c.tmpl.id,inner_dimensions:outDims(declaredFrame(c.tmpl),ou),outer_dimensions:outDims(c.tmpl.machine?c.tmpl.outerD:c.tmpl.outer_dimensions?dims(c.tmpl.outer_dimensions,u):declaredFrame(c.tmpl),ou),...(c.tmpl.deck!=null?{achieved_dimensions:outDims(achievedDimensions(c.tmpl.deck,c.placements),ou)}:c.tmpl.bag||c.tmpl.machine?{achieved_dimensions:outDims(bagExtent(c.placements),ou)}:{}),...(c.tmpl.machine?{made_to_measure:{cost_minor:c.tmpl.cost_minor,tare_weight:outWeight(c.tmpl.tare,ow)}}:{}),payload_weight:outWeight(c.payload,ow),gross_weight:outWeight(c.payload+c.tmpl.tare,ow),used_volume_ticks3:used.toString(),volume_utilization:ratioPlaces(used,volume(c.tmpl.d)),centre_of_mass_offset_ppm:centreOfMassOffsetPpm(c.tmpl,c.placements,clear),...(reaction==null?{}:{axle_reactions:{basis:'gross',denominator:reaction.denominator.toString(),front_numerator:reaction.front.toString(),rear_numerator:reaction.rear.toString()}}),void_fill_reserve_ticks3:(volume(c.tmpl.d)*BigInt(c.tmpl.reservePpm)/BigInt(SUPPORT_SCALE)).toString(),placements:c.placements.map((p,i)=>({placement_id:placementId(`${c.tmpl.id}#${c.seq}`,[p.x+clear,p.y+clear,p.z+clear],p.item.raw.id,p.r),item_id:p.item.id,item_type:p.item.raw.id,position:outPoint({x:p.x+clear,y:p.y+clear,z:p.z+clear},ou),dimensions:outDims(p.pd,ou),orientation:p.r,support_ratio:ratioPlaces(...(p.fixed?p.fixedSupport:supportFraction(p,c.placements,topPlane,c.tmpl.deck))),top_load:outWeight(loads[i],ow),...(p.fixed?{fixed:true}:{})}))}}); const fitsWithRotations=(i,rots)=>templates.some(c=>rots.some(r=>fitsTemplateAlone(c,rotate(i.d,r).map(x=>x+2*clear)))); const openedByType=new Map();for(const c of packed)openedByType.set(c.tmpl.id,(openedByType.get(c.tmpl.id)??0)+1); // Python's and PHP's `support_is_the_blocker`. Each packed container's final scene is @@ -3877,10 +4105,10 @@ const supportIsTheBlocker=i=>{ const unsupported={...i,supportPpm:0,groundRule:null},counters={...metrics},reached=timeLimitReached,tick=candidateClockTick; // The replay diagnoses a finished search, so the effort budget neither bounds it nor can be // stopped by it: a verdict must not depend on how close the search came to its limit. - const ceilings=[attemptCeiling,candidateCeiling,nodeCeiling];attemptCeiling=candidateCeiling=nodeCeiling=Infinity; + const ceilings=[attemptCeiling,candidateCeiling,nodeCeiling];attemptCeiling=candidateCeiling=nodeCeiling=Infinity;replayingSupport=true; const fits=(scene,item,ratio)=>candidatesFor(scene.tmpl,item,scene.state,scene.points,scene.index,scene.used,1,ratio).length>0; const blocked=finishedScenes.some(scene=>fits(scene,unsupported,0)&&!fits(scene,i,globalSupportPpm)); - [attemptCeiling,candidateCeiling,nodeCeiling]=ceilings; + [attemptCeiling,candidateCeiling,nodeCeiling]=ceilings;replayingSupport=false; Object.assign(metrics,counters);timeLimitReached=reached;candidateClockTick=tick; supportVerdicts.set(i.raw.id,blocked);return blocked}; const unpacked=remaining.map(i=>{ @@ -3933,7 +4161,7 @@ const status=unpacked.length?(timeLimitReached?'time_limit':'best_found'):'feasi const solverName=solverAlias?`${solverAlias}:javascript_fallback`:'javascript_fallback'; const starts=[{id:solverName,started:true,completed:!timeLimitReached&&!effortLimitReached,truncated:timeLimitReached||effortLimitReached,selected:true,global_deadline_reached:timeLimitReached}],termination=aggregateTermination(starts);if(effortLimitReached&&!timeLimitReached)termination.code='effort_limit'; const scoreValueForgone=remaining.reduce((sum,i)=>sum+(i.value??0),0); -const defaultScore=[unpacked.length,containers.length,scoreCost,scoreUnused,scoreHeight],score=objective==='lowest_cost'?[defaultScore[0],defaultScore[2],defaultScore[1],defaultScore[3],defaultScore[4]]:objective==='shipping_cost'?[defaultScore[0],exactTicks(scoreBillable),defaultScore[1],defaultScore[3],defaultScore[4]]:objective==='lowest_landed_cost'?[defaultScore[0],scoreLanded,defaultScore[1],defaultScore[3],defaultScore[4]]:objective==='open_dimension_height'?[defaultScore[0],scoreAchievedHeight,defaultScore[1],defaultScore[2],defaultScore[3]]:objective==='maximum_value'?[defaultScore[0],scoreValueForgone,defaultScore[1],defaultScore[2],defaultScore[3]]:byVolume?[unpackedVolumePpm(nominalVolume(remaining),requestedVolume),defaultScore[0],defaultScore[1],defaultScore[2],defaultScore[3]]:defaultScore; +const defaultScore=[unpacked.length,containers.length,scoreCost,scoreUnused,scoreHeight],score=objective==='lowest_cost'?[defaultScore[0],defaultScore[2],defaultScore[1],defaultScore[3],defaultScore[4]]:objective==='shipping_cost'?[defaultScore[0],exactTicks(scoreBillable),defaultScore[1],defaultScore[3],defaultScore[4]]:objective==='lowest_landed_cost'?[defaultScore[0],reportedLanded(scoreLanded),defaultScore[1],defaultScore[3],defaultScore[4]]:objective==='open_dimension_height'?[defaultScore[0],scoreAchievedHeight,defaultScore[1],defaultScore[2],defaultScore[3]]:objective==='maximum_value'?[defaultScore[0],scoreValueForgone,defaultScore[1],defaultScore[2],defaultScore[3]]:byVolume?[unpackedVolumePpm(nominalVolume(remaining),requestedVolume),defaultScore[0],defaultScore[1],defaultScore[2],defaultScore[3]]:defaultScore; const result={status,feasibility:{code:complete?'feasible':'unknown'},termination,optimality:{code:complete?'not_proven':'best_found'},complete,objective,algorithm:{profile:req.configuration?.solver_profile??'balanced',solver:solverName,duration_ms:0,seed:req.configuration?.seed??42,time_limit_reached:timeLimitReached,effort_limit_reached:effortLimitReached,candidates_evaluated:metrics.feasible_candidates,placements_attempted:metrics.orientations_considered,metrics},summary:{container_count:containers.length,packed_item_count:items.length-unpacked.length,unpacked_item_count:unpacked.length},score,containers,unpacked_items:unpacked,catalog_versions_used:catalogVersionsUsed(req.catalog_versions_used),warnings:['JavaScript fallback is active; build the Rust addon for the native portfolio'],alternatives:[]}; if(unpriceableDetail!=null)Object.defineProperty(result,'unpriceableDetail',{value:unpriceableDetail,enumerable:false,writable:false,configurable:true}); return finalizeOutermost(result)} @@ -3966,13 +4194,13 @@ function rebalanceContext(req,result){ } const templates=new Map((req.containers??[]).map(raw=>{ const declared=dims(raw.inner_dimensions,unit),limit=raw.pallet_overhang_limit; - const frame=limit==null?null:solvingFrame(declared,scalar(limit.length,unit,LEN),scalar(limit.width,unit,LEN)),d=frame===null?declared:frame.d; + const girth=bagGirth(raw.deformable_boundary,declared,value=>scalar(value,unit,LEN)); + const frame=limit==null?null:solvingFrame(declared,scalar(limit.length,unit,LEN),scalar(limit.width,unit,LEN)),d=frame!==null?frame.d:girth?.standing?standingFrame(declared):declared; const axleSpec=raw.axles==null?null:raw.axles.map(axle=>({ position:scalar(axle.position,unit,LEN), max:axle.max_load==null?null:scalar(axle.max_load,'g',WT), })); - const template={...raw,d,outerD:raw.outer_dimensions?dims(raw.outer_dimensions,unit):declared,deck:frame===null?null:frame.deck,bag:raw.deformable_boundary!=null, - gusset:raw.deformable_boundary?.side_gusset_depth==null?0:scalar(raw.deformable_boundary.side_gusset_depth,unit,LEN), + const template={...raw,d,outerD:raw.outer_dimensions?dims(raw.outer_dimensions,unit):declared,deck:frame===null?null:frame.deck,bag:girth!==null,girth, max:raw.max_payload==null?null:scalar(raw.max_payload,'g',WT), tare:scalar(raw.tare_weight??0,'g',WT),axleSpec, reservePpm:scaledRatio(raw.void_fill_reserve_ratio??0), @@ -4072,14 +4300,14 @@ function publicRebalancedContainers(req,context){ const used=usedVolume(state.placements),reaction=axleReactions(state.tmpl,state.placements); const container={...state.publicContainer,payload_weight:outWeight(payload,outputWeight), gross_weight:outWeight(payload+state.tmpl.tare,outputWeight),used_volume_ticks3:used.toString(), - volume_utilization:sixPlaces(used,volume(state.tmpl.d)), + volume_utilization:ratioPlaces(used,volume(state.tmpl.d)), centre_of_mass_offset_ppm:centreOfMassOffsetPpm(state.tmpl,state.placements,context.clear), placements:state.placements.map((placement,index)=>({...placement.publicPlacement, // A moved item's id names where it now is, in the container it now sits in (1.10). placement_id:placementId(state.publicContainer.id,[placement.x+context.clear,placement.y+context.clear,placement.z+context.clear],placement.item.raw.id,placement.r), position:outPoint({x:placement.x+context.clear,y:placement.y+context.clear,z:placement.z+context.clear},outputLength), dimensions:outDims(placement.pd,outputLength),orientation:placement.r, - support_ratio:sixPlaces(...supportFraction(placement,state.placements,null,state.tmpl.deck)), + support_ratio:ratioPlaces(...supportFraction(placement,state.placements,null,state.tmpl.deck)), top_load:outWeight(loads[index],outputWeight), })), }; @@ -4150,9 +4378,10 @@ export function rebalanceWeight(req,result,{maxMoves=64}={}){ const projected=[...weights];projected[sourceIndex]-=weight;projected[destinationIndex]+=weight; if(projected.reduce(heavier)-projected.reduce(lighter)>=spread)continue; for(const [x,y,z] of rebalanceCandidatePoints(context.states[destinationIndex])){ - const trial=cloneValue(context.states); - const [relocated]=trial[sourceIndex].placements.splice(placementIndex,1); - relocated.x=x;relocated.y=y;relocated.z=z;trial[destinationIndex].placements.push(relocated); + // Only the two states' placement lists and the moved placement change; everything else is read-only here. + const trial=context.states.map((state,index)=>index===sourceIndex||index===destinationIndex?{...state,placements:[...state.placements]}:state); + const [original]=trial[sourceIndex].placements.splice(placementIndex,1); + trial[destinationIndex].placements.push({...original,x,y,z}); const originalStates=context.states;context.states=trial; if(rebalanceValid(context,result)&&(statesPriceable==null||statesPriceable())){ committed={item_id:moving.item.id,from_container_id:originalStates[sourceIndex].publicContainer.id,to_container_id:originalStates[destinationIndex].publicContainer.id}; diff --git a/index.js b/index.js index 73ef773..535b2b7 100644 --- a/index.js +++ b/index.js @@ -162,7 +162,7 @@ export function rebalanceWeightWith(binding, request, result, { maxMoves = 64 } return rebalanceFallback(request, result, { maxMoves }); } -export const version = () => native?.version?.() ?? '1.10.0-js-fallback'; +export const version = () => native?.version?.() ?? '1.11.0-js-fallback'; /** * The result is not a document the reference validator can judge (docs/VALIDATION-CONTRACT.md): diff --git a/package.json b/package.json index eb5432f..729bca0 100644 --- a/package.json +++ b/package.json @@ -1,12 +1,12 @@ { "name":"@packvium/engine", - "version":"1.10.0", + "version":"1.11.0", "description":"Deterministic 3D bin-packing and cartonization engine for pallets, containers, trucks and shipping cartons. Exact integer geometry, reproducible results.", "author":{"name":"Packvium contributors","url":"https://packvium.com"}, "keywords":["3d-bin-packing","bin-packing","3d-packing","cartonization","container-loading","pallet-packing","truck-loading","packing-algorithm","logistics","deterministic","box-packing","load-planning"], "homepage":"https://packvium.com", - "repository":{"type":"git","url":"git+https://github.com/toxakara/packvium-node.git"}, - "bugs":{"url":"https://github.com/toxakara/packvium-node/issues"}, + "repository":{"type":"git","url":"git+https://github.com/packvium/packvium-node.git"}, + "bugs":{"url":"https://github.com/packvium/packvium-node/issues"}, "type":"module", "main":"index.js", "types":"index.d.ts", diff --git a/policy.js b/policy.js index 703453d..7c9047b 100644 --- a/policy.js +++ b/policy.js @@ -17,6 +17,8 @@ // The shipment-scoped facts a rule may select on. Properties of the shipment rather // than of any item or container, which is why the request had nowhere to put them. +import { compareCodePoints } from './commerce-model.js'; + const SHIPMENT_FACTS = ['facility', 'customer', 'carrier', 'service']; // Wire name -> the keys the form requires, in the order they are read. Exactly one may @@ -67,7 +69,7 @@ function shipmentContext(raw, where) { for (const fact of SHIPMENT_FACTS) context[fact] = null; if (raw == null) return context; if (!isPlainObject(raw)) throw new PolicyError(`${where} must be an object`); - const unknown = Object.keys(raw).filter(key => !SHIPMENT_FACTS.includes(key)).sort(); + const unknown = Object.keys(raw).filter(key => !SHIPMENT_FACTS.includes(key)).sort(compareCodePoints); if (unknown.length) throw new PolicyError(`${where} names unknown shipment facts: ${unknown.join(', ')}`); for (const [name, value] of Object.entries(raw)) { if (typeof value !== 'string' || !value) throw new PolicyError(`${where}.${name} must be a non-empty string`); @@ -83,7 +85,7 @@ const satisfiedBy = (selector, shipment) => function parseForm(name, raw, where) { if (!isPlainObject(raw)) throw new PolicyError(`${where} must be an object`); const keys = FORMS[name]; - const unknown = Object.keys(raw).filter(key => !keys.includes(key)).sort(); + const unknown = Object.keys(raw).filter(key => !keys.includes(key)).sort(compareCodePoints); if (unknown.length) throw new PolicyError(`${where} has unknown keys: ${unknown.join(', ')}`); const missing = keys.filter(key => !hasOwn(raw, key)); if (missing.length) throw new PolicyError(`${where} is missing ${missing.join(', ')}`); @@ -102,7 +104,7 @@ function parseRule(raw, index) { const named = Object.keys(FORMS).filter(name => hasOwn(raw, name)); if (named.length !== 1) { throw new PolicyError( - `${where} must name exactly one rule form (${Object.keys(FORMS).sort().join(', ')}), not ${named.length}`); + `${where} must name exactly one rule form (${Object.keys(FORMS).sort(compareCodePoints).join(', ')}), not ${named.length}`); } if (typeof raw.id !== 'string' || !raw.id) throw new PolicyError(`${where}.id must be a non-empty string`); const version = integer(raw.version, `${where}.version`, 1); @@ -140,14 +142,14 @@ function resolve(rules, asOf, shipment) { // one cited, so sorting here is what makes the citation deterministic. Ties go to the // lexicographically smallest id -- never to insertion order, which would make the // citation depend on the order the caller happened to write. - return [...latest.values()].sort((a, b) => b.priority - a.priority || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0)); + return [...latest.values()].sort((a, b) => b.priority - a.priority || compareCodePoints(a.id, b.id)); } /** The rules that participate in one request, already resolved and ordered. */ export function parsePolicy(raw) { if (raw == null) return []; if (!isPlainObject(raw)) throw new PolicyError('policy must be an object'); - const unknown = Object.keys(raw).filter(key => !['as_of', 'shipment', 'rules'].includes(key)).sort(); + const unknown = Object.keys(raw).filter(key => !['as_of', 'shipment', 'rules'].includes(key)).sort(compareCodePoints); if (unknown.length) throw new PolicyError(`policy has unknown keys: ${unknown.join(', ')}`); const declared = raw.rules ?? []; if (!Array.isArray(declared)) throw new PolicyError('policy.rules must be an array'); diff --git a/request-errors.js b/request-errors.js index 9fe824e..36b9c32 100644 --- a/request-errors.js +++ b/request-errors.js @@ -154,6 +154,8 @@ const MAX_VOLUME_TICKS3 = 10n ** 30n; * 64-bit integer, which is how Rust and PHP add a container's payload (R19-01). */ const MAX_WEIGHT_TICKS = 2n ** 63n - 1n; +/** K3: the most points a convex hull item may list; the shape build is O(v^4), so the cap is checked at admission. */ +const MAXIMUM_HULL_VERTICES = 32; const hasOwn = (value, key) => Object.prototype.hasOwnProperty.call(value, key); const isObject = (value) => value !== null && typeof value === 'object' && !Array.isArray(value); @@ -398,6 +400,7 @@ function checkItem(raw, where, length, weight, lengthTicks) { optional(item, 'allowed_rotations', where, (value, field) => allowedRotations(value, field, item)); optional(item, 'ground_contact_rule', where, oneOf(GROUND_CONTACT_RULES)); optional(item, 'shape_type', where, oneOf(SHAPE_TYPES)); + optional(item, 'hull_vertices', where, hullVertexCount); for (const name of ITEM_BOOLEANS) optional(item, name, where, requireBoolean); const listed = item.allowed_rotations; if (listed != null && !listed.some((code) => !item.keep_upright || UPRIGHT_ORIENTATIONS.includes(code))) { @@ -406,6 +409,13 @@ function checkItem(raw, where, length, weight, lengthTicks) { } } +/** K3: only the count, so no per-vertex work runs on an oversized hull. A non-list reports its own type error first. O(1). */ +function hullVertexCount(raw, field) { + if (requireList(raw, field).length > MAXIMUM_HULL_VERTICES) { + throw new InvalidRequestError('above_maximum', field, `must have at most ${MAXIMUM_HULL_VERTICES} vertices`); + } +} + /** * Each code from the item's vocabulary (1.10): all 24 for a hull, the six legacy codes for * anything else, where a signed code is a rule broken rather than an unknown word. The shape is @@ -522,19 +532,22 @@ export const DEFORMABLE_BOUNDARY_KINDS = Object.freeze(['flat_bag', 'gusseted_ba const BAG_EXCLUSIONS = Object.freeze(['obstacles', 'axles', 'access_directions', 'max_stack_density', 'outer_dimensions', 'void_fill_reserve_ratio', 'made_to_measure', 'pallet_overhang_limit']); +/**: the frames a gusseted bag may be packed in. */ +const BAG_ORIENTATIONS = Object.freeze(['flat', 'standing']); +/** The keys a gusseted bag's boundary may carry (1.10 side gusset; 1.11 bottom gusset and orientation). */ +const GUSSETED_BAG_FIELDS = Object.freeze(['bottom_gusset_depth', 'kind', 'orientation', 'side_gusset_depth']); + /** - * The boundary object top to bottom -- kind, unknown keys, the gusset (1.10) -- then the - * container fields a bag refuses. O(1). + * The boundary object top to bottom -- kind, unknown keys, the gussets, the orientation -- + * then the container fields a bag refuses. O(1). */ function deformableBoundary(container, raw, field, where, length, inner) { const boundary = requireObject(raw, field); const kind = required(boundary, 'kind', field); requireOneOf(kind, field + pointer('kind'), DEFORMABLE_BOUNDARY_KINDS); const gusseted = kind === 'gusseted_bag'; - requireKnownFields(boundary, field, gusseted ? ['kind', 'side_gusset_depth'] : ['kind']); - if (gusseted) { - sideGussetDepth(required(boundary, 'side_gusset_depth', field), field + pointer('side_gusset_depth'), length, inner); - } + requireKnownFields(boundary, field, gusseted ? GUSSETED_BAG_FIELDS : ['kind']); + if (gusseted) gussetedBag(boundary, field, length, inner); for (const name of BAG_EXCLUSIONS) { if (setBesideABag(name, hasOwn(container, name) ? container[name] : null)) { throw new InvalidRequestError('not_allowed', where + pointer(name), 'cannot be combined with deformable_boundary'); @@ -542,11 +555,30 @@ function deformableBoundary(container, raw, field, where, length, inner) { } } -/** A length, positive once read in ticks, and no deeper than the bag's inner width. */ -function sideGussetDepth(value, field, length, inner) { +/** + * The side gusset, then the bottom one, each a positive length within its fold; with neither, + * the side gusset is reported missing as in 1.10. Then the orientation, and a standing bag's + * bottom gusset. O(1). + */ +function gussetedBag(boundary, field, length, inner) { + const side = hasOwn(boundary, 'side_gusset_depth') ? boundary.side_gusset_depth : null; + const bottom = hasOwn(boundary, 'bottom_gusset_depth') ? boundary.bottom_gusset_depth : null; + if (side == null && bottom == null) required(boundary, 'side_gusset_depth', field); + if (side != null) gussetDepth(side, field + pointer('side_gusset_depth'), length, inner[1], 'exceeds inner_dimensions width'); + if (bottom != null) gussetDepth(bottom, field + pointer('bottom_gusset_depth'), length, 2 * inner[0], 'exceeds twice inner_dimensions length'); + const orientation = hasOwn(boundary, 'orientation') ? boundary.orientation : null; + if (orientation == null) return; + requireOneOf(orientation, field + pointer('orientation'), BAG_ORIENTATIONS); + if (orientation === 'standing' && bottom == null) { + throw new InvalidRequestError('missing_field', field + pointer('bottom_gusset_depth'), 'is required when orientation is standing'); + } +} + +/** A length, positive once read in ticks, and no deeper than its fold allows. */ +function gussetDepth(value, field, length, deepest, tooDeep) { const depth = length(value, field); if (depth === 0) throw new InvalidRequestError('invalid_value', field, 'must be positive'); - if (depth > inner[1]) throw new InvalidRequestError('invalid_value', field, 'exceeds inner_dimensions width'); + if (depth > deepest) throw new InvalidRequestError('invalid_value', field, tooDeep); } // An empty obstacle list and a zero reserve change nothing, so only they are let through. @@ -591,6 +623,20 @@ function rateTable(raw, where, currency) { optional(table, 'minimum_charge_minor', where, atLeast(0)); optional(table, 'fuel_surcharge_permille', where, atLeast(0)); optional(table, 'currency', where, (v, f) => rateTableCurrency(v, f, currency)); + if (landedTopBracket(table) > BigInt(MAX_EXACT_MAGNITUDE)) { + throw new InvalidRequestError('above_maximum', where, + `must price its top bracket at most ${MAX_EXACT_MAGNITUDE} minor units with the fuel surcharge`); + } +} + +/** The dearest charge a table can bill, surcharge included, in `BigInt` (two values near 2^53 multiply past a `Number`); 0n for a table with no prices. O(prices). */ +function landedTopBracket(table) { + if (!Array.isArray(table.prices_minor) || table.prices_minor.length === 0) return 0n; + // A loop, not a spread: a long table would overflow the call stack as arguments. + let top = table.minimum_charge_minor ?? 0; + for (const price of table.prices_minor) if (price > top) top = price; + const base = BigInt(top); + return base + (base * BigInt(table.fuel_surcharge_permille ?? 0) + 999n) / 1000n; } /** diff --git a/result-validation/accounting.js b/result-validation/accounting.js index ae0fcdd..fd99fe6 100644 --- a/result-validation/accounting.js +++ b/result-validation/accounting.js @@ -6,7 +6,7 @@ import { } from './json.js'; import { issue, shape } from './outcome.js'; import { pyRepr, pyStr, strRepr } from './pyfmt.js'; -import { holds, intersectsTags, rotationAxes } from './spec.js'; +import { girthBreach, holds, intersectsTags, rotationAxes } from './spec.js'; export function checkStructure(result, issues) { const summary = at(result, 'summary'); @@ -112,12 +112,12 @@ export function checkAccounting(result, context, issues) { } /** - * Whether one envelope of this size fits the empty container: its frame and, for a flat bag, + * Whether one envelope of this size fits the empty container: its frame and, for a bag, * both girth sums with the envelope alone at the origin. */ export function fitsEmpty(container, size) { if (size.some((side, axis) => side > container.inner[axis])) return false; - return !container.flatBag || (size[0] + size[2] <= container.inner[0] && size[1] + size[2] <= container.inner[1] + container.sideGusset); + return !container.flatBag || girthBreach(container, ...size) === null; } /** diff --git a/result-validation/bound.js b/result-validation/bound.js index a4be7fc..c56dad8 100644 --- a/result-validation/bound.js +++ b/result-validation/bound.js @@ -11,12 +11,14 @@ */ import { - at, getNull, getOr, int, isDict, strictInt, truthy, + at, getNull, getOr, int, isDict, list, pyInt, strictInt, text, truthy, } from './json.js'; import { ceilDiv, floorDiv, max, min, pyMod, ratioPpm } from './num.js'; +import { dimensionalWeight } from './objective.js'; import { issue } from './outcome.js'; import { intList, pyRepr } from './pyfmt.js'; import { SCORE_SCALE } from './stacking.js'; +import { TICKS_PER_GRAM } from './units.js'; /** * Where each covered objective reads `(L0, L1, L2, L3, L4)` in its own score order, a name @@ -28,8 +30,15 @@ const BOUND_ORDERS = new Map([ ['maximum_value', [0, 'value_forgone', 1, 2, 3]], ['open_dimension_height', [0, 'achieved_height', 1, 2, 3]], ['maximum_volume', ['unpacked_volume_ppm', 0, 1, 2, 3]], + ['shipping_cost', [0, 'billed_weight', 1, 3, 4]], + ['lowest_landed_cost', [0, 'landed_charge', 1, 3, 4]], ]); +/** The objectives whose own key is what a carrier bills. */ +const BILLED_BOUND_OBJECTIVES = ['shipping_cost', 'lowest_landed_cost']; +const BILLED_KEYS = ['billed_weight', 'landed_charge']; +const UNPRICEABLE = 'no priceable inventory carries a packing that attains the count bound'; + const MAX_BOUND_SUM = 10n ** 30n; const MAX_BOUND_VALUE = 2n ** 53n - 1n; const GAP_FIELDS = ['gap_key', 'absolute_gap', 'relative_gap']; @@ -280,17 +289,106 @@ function objectiveTerm(name, values, volumes, shrinks, containers, unpacked) { return ceilDiv(max(0n, requested - capacity) * SCORE_SCALE, requested); } +/** The `count` smallest of `{value repeated quantity}` from `[value, quantity]` pairs, summed; `null` if fewer exist. */ +function leastOfInventory(pairs, count) { + let total = 0n; + let remaining = count; + for (const [value, quantity] of pairs.slice().sort(ascending)) { + if (remaining <= 0n) break; + const taken = quantity === null ? remaining : min(quantity, remaining); + total += value * taken; + remaining -= taken; + } + return remaining > 0n ? null : total; +} + +/** + * Least cost covering `need` from `[cost, capacity, quantity]` offers taken fractionally, rounded + * up; greedy by cost per unit is optimal for one covering constraint. Whole offers add whole + * costs, so the one fraction is the last offer's share, `cost × remaining / capacity`. + */ +function fractionalCover(offers, need) { + if (need <= 0n) return 0n; + const perUnit = (left, right) => { + const [lower, upper] = [left[0] * right[1], right[0] * left[1]]; + return lower < upper ? -1 : lower > upper ? 1 : 0; + }; + let remaining = need; + let whole = 0n; + for (const [cost, capacity, quantity] of offers.filter((offer) => offer[1] > 0n).sort(perUnit)) { + if (quantity === null || remaining <= capacity * quantity) return ceilDiv(whole * capacity + cost * remaining, capacity); + whole += cost * quantity; + remaining -= capacity * quantity; + } + return null; +} + +/** `shipping_cost`'s key: the floors and the tares plus the placed weight, each over `L1` containers. */ +function billedWeightTerm(weights, containers, placed, opened) { + if (opened === 0n) return 0n; + const byFloor = leastOfInventory(containers.map((container) => [container.floor, container.quantity]), opened); + const byTare = leastOfInventory(containers.map((container) => [container.tare, container.quantity]), opened); + if (byFloor === null || byTare === null) return null; + return max(byFloor, byTare + smallest(weights, placed)); +} + +/** `lowest_landed_cost`'s key: the cheapest reachable charge over `L1`, and the cheapest covers of the placed weight and count. */ +function landedChargeTerm(volumes, weights, shrinks, containers, placed, opened) { + if (opened === 0n || placed === 0n) return 0n; + const cheapest = []; + const byWeight = []; + const byItems = []; + for (const container of containers) { + const reachable = container.brackets.filter(([limit, charge]) => charge !== null && container.floor <= limit); + for (const [limit, charge] of reachable) { + const carried = container.payload === null ? limit - container.tare : min(limit - container.tare, container.payload); + let count = fit(weights, carried); + if (!shrinks) count = min(count, fit(volumes, container.usable)); + if (container.maxItems !== null) count = min(count, container.maxItems); + byWeight.push([charge, carried, container.quantity]); + byItems.push([charge, count, container.quantity]); + } + if (reachable.length > 0) cheapest.push([reachable.map(([, charge]) => charge).reduce(min), container.quantity]); + } + const terms = [leastOfInventory(cheapest, opened), fractionalCover(byWeight, smallest(weights, placed)), + fractionalCover(byItems, placed)]; + return terms.some((term) => term === null) ? null : terms.reduce(max); +} + +/** + * The billed key of `shipping_cost` or `lowest_landed_cost`, or `null` when no priceable + * inventory carries a packing that leaves exactly `L0` behind. Each opened container bills at + * least its `floor`, `max(tare, dimensional)`, and at least its tare plus what it carries. A + * rate-table bracket is reachable from a floor within it; there a container carries at most the + * bracket's bound less its tare (and its `max_payload`), so at most the lightest-first count under + * that, its usable volume and `max_items`. The cheapest reachable charge over the `L1` containers + * and the cheapest covers of the placed weight and of the placed count each bound the charge; the + * largest is stated. O(c b t + c b log(c b)) for `t` runs and `b` brackets per type. + */ +function billedTerm(name, volumes, weights, shrinks, containers, bound) { + const [unpacked, opened] = bound; + const placed = runCount(volumes) - unpacked; + if (name === 'billed_weight') return billedWeightTerm(weights, containers, placed, opened); + return landedChargeTerm(volumes, weights, shrinks, containers, placed, opened); +} + /** * A covered objective's bound in its own score order, or `null` with the reason a ceiling * withholds it: the one refusal predicate's, or the objective's own term's, which withholds * that objective alone. `values` yields the value runs, read only by `maximum_value`, so no - * other objective parses `Item.value`. Exported so the shared scene can hold it to the oracle. + * other objective parses `Item.value`. A billed objective reads each type's `tare`, `floor` and + * `brackets` as well, and `priced` is false where the configuration has no divisor to bill by. + * Exported so the shared scene can hold it to the oracle. */ -export function objectiveLowerBound(name, values, volumes, weights, shrinks, containers) { +export function objectiveLowerBound(name, values, volumes, weights, shrinks, containers, priced = true) { const bound = lowerBound(volumes, weights, shrinks, containers); if (bound === null) return { bound: null, withheld: 'the request is past a declared ceiling' }; - const stated = BOUND_ORDERS.get(name).map((position) => (typeof position === 'number' - ? bound[position] : objectiveTerm(position, values, volumes, shrinks, containers, bound[0]))); + const order = BOUND_ORDERS.get(name); + const billedKey = order.find((position) => BILLED_KEYS.includes(position)); + const billed = billedKey === undefined || !priced ? null : billedTerm(billedKey, volumes, weights, shrinks, containers, bound); + if (billedKey !== undefined && billed === null) return { bound: null, withheld: UNPRICEABLE }; + const stated = order.map((position) => (typeof position === 'number' ? bound[position] + : position === billedKey ? billed : objectiveTerm(position, values, volumes, shrinks, containers, bound[0]))); if (stated.some((value) => value > MAX_BOUND_VALUE)) { return { bound: null, withheld: `the ${name} key is past the portable ceiling` }; } @@ -308,7 +406,38 @@ function statedBound(request, status, items, containers) { if (status === 'infeasible') return { bound: null, withheld: "status is 'infeasible'" }; if (status === 'invalid_result') return { bound: null, withheld: "status is 'invalid_result'" }; const [volumes, weights, shrinks, types] = boundInputs(items, containers); - return objectiveLowerBound(name, () => valueRuns(items), volumes, weights, shrinks, types); + const configuration = getOr(request, 'configuration', {}); + const priced = !BILLED_BOUND_OBJECTIVES.includes(name) || getNull(configuration, 'dimensional_weight_divisor') !== null; + const billed = BILLED_BOUND_OBJECTIVES.includes(name) && priced + ? containers.values().map((spec, index) => ({ ...types[index], ...billingOf(spec, configuration, name) })) + : types; + return objectiveLowerBound(name, () => valueRuns(items), volumes, weights, shrinks, billed, priced); +} + +/** + * One type's billing floor, tare and priced brackets, recomputed from the request. The + * floor is the dimensional weight of the declared outer size, else of a pallet's deck at the + * declared height, else of the inner size, and 0 for a bag, whose billed package can be smaller; + * a bracket's charge is `max(price, minimum)` with the surcharge rounded up. + */ +function billingOf(spec, configuration, name) { + const size = spec.outer ?? (spec.deck === null ? spec.inner : [spec.deck[2], spec.deck[3], spec.inner[2]]); + const dimensional = spec.flatBag ? 0n : dimensionalWeight(size, int(at(configuration, 'dimensional_weight_divisor'), 'dimensional_weight_divisor'), + text(getOr(configuration, 'dimensional_weight_length_unit', 'in'), 'dimensional_weight_length_unit'), + text(getOr(configuration, 'dimensional_weight_weight_unit', 'lb'), 'dimensional_weight_weight_unit')); + const table = name === 'lowest_landed_cost' ? spec.rateTable : null; + const brackets = []; + if (table !== null) { + const bounds = list(at(table, 'weight_brackets_g'), 'weight_brackets_g').map((grams) => pyInt(grams, 'bracket')); + const prices = list(at(table, 'prices_minor'), 'prices_minor').map((price) => pyInt(price, 'price')); + const minimum = pyInt(getOr(table, 'minimum_charge_minor', 0), 'minimum_charge_minor'); + const permille = pyInt(getOr(table, 'fuel_surcharge_permille', 0), 'fuel_surcharge_permille'); + for (let index = 0; index < Math.min(bounds.length, prices.length); index += 1) { + const base = max(prices[index], minimum); + brackets.push([bounds[index] * TICKS_PER_GRAM, base + ceilDiv(base * permille, 1000n)]); + } + } + return { tare: spec.tareWeight, floor: max(spec.tareWeight, dimensional), brackets }; } /** The first position where `score` leaves `bound`, and whether it is above (1) or below (-1). */ diff --git a/result-validation/container.js b/result-validation/container.js index 161f4b4..b80b176 100644 --- a/result-validation/container.js +++ b/result-validation/container.js @@ -10,7 +10,7 @@ import { import { Refusal, contract, issue, shape } from './outcome.js'; import { Ratio, abs, ceilDiv, floorDiv, max, min, pyMod, ratioPpm } from './num.js'; import { intTuple, list as listRepr, pyRepr, pyStr, strRepr, valueTuple } from './pyfmt.js'; -import { allows, intersectsTags, isRotation, rotated, sortedTags, volumeOf } from './spec.js'; +import { allows, girthBreach, intersectsTags, isRotation, rotated, sortedTags, volumeOf } from './spec.js'; import { SCORE_SCALE, SQUARE_METRE_TICKS, checkCrush, checkDeckSupport, checkRouteRemovalOrder, checkStackDensity, checkStackTopLoad, checkSupportAndLoad, occupiedVolume, placedHull, propagateLoad, supportGraph, validNesting, @@ -97,7 +97,8 @@ const optionalTuple = (values) => (values === null ? 'None' : valueTuple(values) /** * `achieved_dimensions` is present exactly when the container declares a soft size, and equals - * the tight extent; a bag's extent must pass the girth rule, widened by a side gusset (1.10). + * the tight extent; a bag's extent must pass the girth rule, widened by a side gusset (1.10) + * and lengthened by a bottom one, flat or standing. */ export function checkAchievedExtent(packed, spec, clearance, issues) { const reported = getNull(packed, 'achieved_dimensions'); @@ -113,11 +114,8 @@ export function checkAchievedExtent(packed, spec, clearance, issues) { if (!matchesInts(stated, [a, b, c])) { issues.push(issue('achieved_dimensions_mismatch', `${packedId}: reported ${optionalTuple(stated)}, computed ${intTuple([a, b, c])}`)); } - if (spec.flatBag && (a + c > spec.inner[0] || b + c > spec.inner[1] + spec.sideGusset)) { - const gusset = spec.sideGusset > 0n ? `, side gusset ${spec.sideGusset}` : ''; - issues.push(issue('bag_girth_exceeded', - `${packedId}: a + c = ${a + c}, b + c = ${b + c}, flat size ${spec.inner[0]} x ${spec.inner[1]}${gusset}`)); - } + const breach = spec.flatBag ? girthBreach(spec, a, b, c) : null; + if (breach !== null) issues.push(issue('bag_girth_exceeded', `${packedId}: ${breach}`)); packedId.verify(); } diff --git a/result-validation/json.js b/result-validation/json.js index 99a4147..5613b35 100644 --- a/result-validation/json.js +++ b/result-validation/json.js @@ -159,8 +159,9 @@ function numberOf(value) { const sign = (difference) => (difference < 0n ? -1 : difference > 0n ? 1 : 0); -/** An integer against a finite float, exactly, as Python compares `int` with `float`. */ +/** An integer against a float, exactly, as Python compares `int` with `float`. */ function compareIntegerToFloat(integer, float) { + if (!Number.isFinite(float)) return float > 0 ? -1 : float < 0 ? 1 : 0; if (Number.isInteger(float)) return sign(integer - BigInt(float)); return integer <= BigInt(Math.floor(float)) ? -1 : 1; } diff --git a/result-validation/objective.js b/result-validation/objective.js index 45b95ae..c3fa263 100644 --- a/result-validation/objective.js +++ b/result-validation/objective.js @@ -15,7 +15,7 @@ import { SCORE_SCALE } from './stacking.js'; import { LENGTH, TICKS_PER_GRAM, WEIGHT, perUnit, toTicks } from './units.js'; /** `floor(volume * weight ticks per unit / (length ticks per unit ^ 3 * divisor))`. */ -function dimensionalWeight(size, divisor, lengthUnit, weightUnit) { +export function dimensionalWeight(size, divisor, lengthUnit, weightUnit) { const length = perUnit(LENGTH, lengthUnit); const weight = perUnit(WEIGHT, weightUnit); return floorDiv(size[0] * size[1] * size[2] * weight, length ** 3n * divisor); diff --git a/result-validation/spec.js b/result-validation/spec.js index a58bb42..e99c94f 100644 --- a/result-validation/spec.js +++ b/result-validation/spec.js @@ -190,15 +190,38 @@ function frameAndDeck(declared, limit, unit) { Object.freeze([overhangX, overhangY, declared[0], declared[1]])]; } -/** A gusseted bag's side gusset depth in ticks, else 0n. */ -function sideGusset(boundary, unit) { +/** A gusseted bag's side or bottom gusset depth in ticks, else 0n. */ +function gusset(boundary, name, unit) { if (boundary === null) return 0n; - const depth = getNull(boundary, 'side_gusset_depth'); + const depth = getNull(boundary, name); return depth === null ? 0n : toTicks(depth, unit, LENGTH); } +/** + * How a bag's package of extents `(a, b, c)` breaks a loop of film, or null. + * + * Lying flat on an `L x W` bag: `2(a + c) <= 2L + K` and `b + c <= W + G`. Standing in its + * `W x H x L` frame: `2(b + c) <= 2L + K` and `a + b <= W + G` (1.10). `G` + * and `K` are the side and bottom gussets, 0n where none is declared. + */ +export function girthBreach(spec, a, b, c) { + const [length, width] = spec.standing ? [spec.inner[2], spec.inner[0]] : [spec.inner[0], spec.inner[1]]; + const [along, across] = spec.standing ? [b + c, a + b] : [a + c, b + c]; + if (2n * along <= 2n * length + spec.bottomGusset && across <= width + spec.sideGusset) return null; + const sums = spec.standing + ? `b + c = ${b + c}, a + b = ${a + b}, standing, length ${length}, width ${width}` + : `a + c = ${a + c}, b + c = ${b + c}, flat size ${length} x ${width}`; + return sums + (spec.sideGusset ? `, side gusset ${spec.sideGusset}` : '') + + (spec.bottomGusset ? `, bottom gusset ${spec.bottomGusset}` : ''); +} + function parseContainer(raw, unit) { - const [inner, deck] = frameAndDeck(dimensions(at(raw, 'inner_dimensions'), unit), getNull(raw, 'pallet_overhang_limit'), unit); + const boundary = getNull(raw, 'deformable_boundary'); + const standing = boundary !== null && getNull(boundary, 'orientation') === 'standing'; + const declared = dimensions(at(raw, 'inner_dimensions'), unit); + // A standing bag's placements are in its `W x H x L` frame, which `inner` then is. + const [inner, deck] = frameAndDeck(standing ? [declared[1], declared[2], declared[0]] : declared, + getNull(raw, 'pallet_overhang_limit'), unit); return Object.freeze({ id: at(raw, 'id'), inner, @@ -216,10 +239,15 @@ function parseContainer(raw, unit) { axles: optional(raw, 'axles', (value) => axles(value, unit)), maxStackDensity: optional(raw, 'max_stack_density', weightTicks), rateTable: getNull(raw, 'rate_table'), - flatBag: getNull(raw, 'deformable_boundary') !== null, + flatBag: boundary !== null, // 1.10: a gusseted bag's side gusset depth G in ticks, widening the width girth to // b + c <= W + G; 0n for a flat bag and every rigid container. - sideGusset: sideGusset(getNull(raw, 'deformable_boundary'), unit), + sideGusset: gusset(boundary, 'side_gusset_depth', unit), + // Its bottom gusset depth K, lengthening the length girth to 2(a + c) <= 2L + K; + // 0n where none is declared. + bottomGusset: gusset(boundary, 'bottom_gusset_depth', unit), + // A bag standing on its bottom gusset, whose `inner` is then `W x H x L`. + standing, reportsAchievedExtent: getNull(raw, 'deformable_boundary') !== null || getNull(raw, 'made_to_measure') !== null || deck !== null, madeToMeasure: optional(raw, 'made_to_measure', (machine) => parseMachine(machine, unit)), diff --git a/revisions.js b/revisions.js index 7802c88..2fff2be 100644 --- a/revisions.js +++ b/revisions.js @@ -238,12 +238,21 @@ function stockBox(request, machine, stockId, inner) { quantity: 1, inner_dimensions: tickBox(inner), outer_dimensions: tickBox(outer), - cost_minor: Number(BigInt(stockInteger(get(machine, 'cost_minor'), 'cost_minor')) + perSquareMetre(price, area)), + cost_minor: safeCost(BigInt(stockInteger(get(machine, 'cost_minor'), 'cost_minor')) + perSquareMetre(price, area)), tare_weight: { value: String(BigInt(declaredTare) + perSquareMetre(tareRate, area)), unit: 'ticks' }, }); return box; } +/** C-13: the exact cost as a `Number`, or a refusal in the wording of the admission rule; a cut box larger than its machine's own declared size can pass 2^53 - 1, and rounding would price it wrongly. */ +function safeCost(cost) { + if (cost > BigInt(Number.MAX_SAFE_INTEGER)) { + throw new PlanRevisionError('invalid_revision', + `a made-to-measure container's cost_per_square_metre_minor prices the largest box above ${Number.MAX_SAFE_INTEGER}`); + } + return Number(cost); +} + function stockObject(value, name, optional = false) { if (value === null && optional) return {}; if (!isMapping(value)) throw new PlanRevisionError('invalid_revision', `a made-to-measure container's ${name} is not an object`); diff --git a/test/bottom-gusset.test.mjs b/test/bottom-gusset.test.mjs new file mode 100644 index 0000000..a9a1ddb --- /dev/null +++ b/test/bottom-gusset.test.mjs @@ -0,0 +1,135 @@ +/** + * 1.11: bottom gussets, lying flat or standing, admitted by the two loops of film. + * + * Mirrors `packvium-python/tests/test_bottom_gusset.py`; the request error and validator texts + * are asserted whole because they are compared across engines. + */ + +import assert from 'node:assert/strict'; +import test from 'node:test'; + +import { FixedPlacementError, InvalidRequestError, packFallback, rebalanceWeight } from '../fallback.js'; +import { validateDocuments } from '../result-validation/index.js'; +import { girthBreach } from '../result-validation/spec.js'; +import { validate } from './validate.mjs'; + +const MM = 16000; + +const ROD = { id: 'rod', allowed_rotations: ['LWH'], dimensions: { length: '300', width: '100', height: '20' } }; +const BOTTLE = { id: 'bottle', allowed_rotations: ['LWH'], dimensions: { length: '50', width: '50', height: '150' } }; +const STANDING = { kind: 'gusseted_bag', bottom_gusset_depth: '60', orientation: 'standing' }; + +const pouch = (boundary, width = '150') => ({ + id: 'pouch', quantity: 1, deformable_boundary: boundary, inner_dimensions: { length: '300', width, height: '100' }, +}); +const request = (boundary, item, quantity, width = '150') => ({ + items: [{ ...item, quantity, weight: '300 g' }], + containers: [pouch(boundary, width)], + configuration: { solver_profile: 'fast', time_limit_ms: 60000, effort_budget: { max_search_nodes: 100000 } }, +}); +const sidesMm = (dimensions) => ['length', 'width', 'height'].map((side) => dimensions[side].ticks / MM); + +function refusal(boundary) { + try { + packFallback(request(boundary, BOTTLE, 1)); + } catch (error) { + return error; + } + return assert.fail('the request was accepted'); +} + +test('a bottom gusset admits a rod the flat length refuses, and equality fits', () => { + // a + c = 320 > L = 300 lying flat; K = 40 makes 2L + K = 640 = 2(a + c). + const flat = packFallback(request({ kind: 'gusseted_bag', side_gusset_depth: '10' }, ROD, 1)); + assert.equal(flat.unpacked_items[0].reason, 'no_compatible_container_dimensions'); + const block = packFallback(request({ kind: 'gusseted_bag', bottom_gusset_depth: '40' }, ROD, 1)); + assert.deepEqual(block.unpacked_items, []); + const past = packFallback(request({ kind: 'gusseted_bag', bottom_gusset_depth: { value: String(40 * MM - 1), unit: 'ticks' } }, ROD, 1)); + assert.equal(past.unpacked_items[0].reason, 'no_compatible_container_dimensions'); +}); + +test('a standing pouch packs in its turned frame and reports the bag as declared', () => { + // The 300 x 150 x 100 pouch stands as a 150 x 100 x 300 frame: two bottles side by side + // make a + b = 150 = W, a third breaks that loop and one on top 2(b + c) = 700 > 660. + const req = request(STANDING, BOTTLE, 3); + const result = packFallback(req); + const [packed] = result.containers; + assert.equal(packed.placements.length, 2); + assert.equal(result.unpacked_items.length, 1); + assert.deepEqual(sidesMm(packed.inner_dimensions), [300, 150, 100]); + const [a, b, c] = sidesMm(packed.achieved_dimensions); + assert.deepEqual([a * b, c, a + b], [5000, 150, 150]); + assert.deepEqual(validate(req, result), []); + assert.deepEqual(validateDocuments(req, result).issues, []); +}); + +test('the validator refuses a standing package past its loop, with its text', () => { + const result = packFallback(request(STANDING, BOTTLE, 2)); + const narrower = request(STANDING, BOTTLE, 2, '149'); + const [a, b] = sidesMm(result.containers[0].achieved_dimensions); + const issues = validateDocuments(narrower, result).issues.filter((issue) => issue.code === 'bag_girth_exceeded'); + assert.deepEqual(issues.map((issue) => issue.detail), [ + `pouch#1: b + c = ${(b + 150) * MM}, a + b = ${(a + b) * MM}, standing, length ${300 * MM}, width ${149 * MM}, bottom gusset ${60 * MM}`, + ]); +}); + +test('the validator states both gussets of a flat bag it refuses', () => { + const spec = { standing: false, inner: [300n, 150n, 100n], sideGusset: 10n, bottomGusset: 40n }; + assert.equal(girthBreach(spec, 300n, 100n, 20n), null); + assert.equal(girthBreach(spec, 300n, 100n, 21n), + 'a + c = 321, b + c = 121, flat size 300 x 150, side gusset 10, bottom gusset 40'); +}); + +test('the validator loops agree with the plain sums over every small package', () => { + for (const standing of [false, true]) { + const spec = { standing, inner: standing ? [7n, 5n, 9n] : [9n, 7n, 5n], sideGusset: 2n, bottomGusset: 3n }; + for (let a = 0n; a <= spec.inner[0]; a++) for (let b = 0n; b <= spec.inner[1]; b++) for (let c = 0n; c <= spec.inner[2]; c++) { + const fits = standing ? 2n * (b + c) <= 21n && a + b <= 9n : 2n * (a + c) <= 21n && b + c <= 9n; + assert.equal(girthBreach(spec, a, b, c) === null, fits, `${[a, b, c]} standing=${standing}`); + } + } +}); + +test('a fixed set in the standing frame past its loop cannot hold', () => { + const fixed = ['0', '50'].map((y) => ({ item_type: 'bottle', container_type: 'pouch', orientation: 'LWH', position: { x: '0', y, z: '0' } })); + assert.throws(() => packFallback({ ...request(STANDING, BOTTLE, 2, '149'), fixed_placements: fixed }), (error) => { + assert.ok(error instanceof FixedPlacementError); + assert.equal(error.message, 'invalid_fixed_placement: bag_girth_exceeded: pouch#1'); + return true; + }); + const held = packFallback({ ...request(STANDING, BOTTLE, 2), fixed_placements: fixed }); + assert.deepEqual(sidesMm(held.containers[0].achieved_dimensions), [50, 100, 150]); +}); + +test('a weight rebalance keeps a standing pouch inside both loops', () => { + const req = request(STANDING, BOTTLE, 3); + const balanced = rebalanceWeight(req, packFallback(req)); + for (const container of balanced.containers) { + const [a, b, c] = sidesMm(container.achieved_dimensions); + assert.ok(a + b <= 150 && 2 * (b + c) <= 660, JSON.stringify(container.achieved_dimensions)); + } +}); + +test('a malformed gusseted bag is refused with its pointer, reason and text', () => { + const field = '/containers/0/deformable_boundary'; + const cases = [ + [{ kind: 'gusseted_bag' }, '/side_gusset_depth', 'missing_field', 'is required'], + [{ kind: 'gusseted_bag', bottom_gusset_depth: { value: String(600 * MM + 1), unit: 'ticks' } }, '/bottom_gusset_depth', 'invalid_value', + 'exceeds twice inner_dimensions length'], + [{ kind: 'gusseted_bag', bottom_gusset_depth: '0' }, '/bottom_gusset_depth', 'invalid_value', 'must be positive'], + [{ kind: 'gusseted_bag', side_gusset_depth: '151', bottom_gusset_depth: '0' }, '/side_gusset_depth', 'invalid_value', + 'exceeds inner_dimensions width'], + [{ kind: 'gusseted_bag', side_gusset_depth: '10', orientation: 'standing' }, '/bottom_gusset_depth', 'missing_field', + 'is required when orientation is standing'], + [{ kind: 'gusseted_bag', bottom_gusset_depth: '10', orientation: 'upright' }, '/orientation', 'not_allowed', + 'must be one of ["flat","standing"]'], + [{ kind: 'flat_bag', orientation: 'flat' }, '/orientation', 'not_allowed', 'is not a known field'], + ]; + for (const [boundary, pointer, reason, detail] of cases) { + const error = refusal(boundary); + assert.ok(error instanceof InvalidRequestError, error.message); + assert.deepEqual([error.field, error.reason, error.detail], [field + pointer, reason, detail]); + } + const deepest = packFallback(request({ kind: 'gusseted_bag', bottom_gusset_depth: '600', orientation: 'flat' }, ROD, 1)); + assert.deepEqual(deepest.unpacked_items, []); +}); diff --git a/test/commerce-edge-cases.test.mjs b/test/commerce-edge-cases.test.mjs index 72d2079..9f0e9b3 100644 --- a/test/commerce-edge-cases.test.mjs +++ b/test/commerce-edge-cases.test.mjs @@ -97,7 +97,7 @@ test('an integer beyond the exact range is refused, never silently rounded', () // 10^15 grams at 10^6 minor units per kilogram is 10^18, well past 2^53. refuses( () => quote(document, shipment({ actual_weight_g: 0, volume_mm3: 10 ** 15 })), - /outside JavaScript's exact integer range/, + /^quote amount 1000000000000000000 is above 9007199254740991 and cannot be represented exactly$/, ); }); @@ -116,6 +116,45 @@ test('the largest exactly representable quote is still answered', () => { assert.ok(Number.isSafeInteger(result.quote.total_minor)); }); +// M2: one ceiling, 2^53 - 1, and the first quote amount past it (in report order) is the one named. +const ABOVE_CEILING = (value) => new RegExp(`^quote amount ${value} is above 9007199254740991 and cannot be represented exactly$`); + +function grams(overrides, volume) { + const document = tariffDocument({ + dimensional_weight_divisor: 1, + cost_per_dimensional_kg_minor: { 'zone-a': 1000 }, + minimum_charge_minor: 0, + fuel_surcharge_permille: 0, + accessorials: [{ accessorial_id: 'extra', permille_of_base: 1000 }], + ...overrides, + }); + return () => quote(document, shipment({ actual_weight_g: 0, volume_mm3: volume, requested_accessorials: document.tariffs[0].versions[0].accessorials.map((entry) => entry.accessorial_id) })); +} + +test('an input integer JSON.parse has already rounded is refused, not quoted from the rounded value', () => { + const document = tariffDocument(); + for (const weight of [9007199254740992, 9007199254740993, 1e17 + 1]) { + refuses(() => quote(document, shipment({ actual_weight_g: weight })), /expected an exact integer/); + } +}); + +test('a quote amount is refused past the ceiling, named in report order', () => { + // dimensional and billed weight sit at 2^52 and the base charge is 2^53. + refuses(grams({ cost_per_dimensional_kg_minor: { 'zone-a': 2000 } }, 4503599627370496), ABOVE_CEILING('9007199254740992')); + // the base charge is exactly 2^53 - 1, the fuel surcharge is twice that. + refuses(grams({ fuel_surcharge_permille: 2000 }, 9007199254740991), ABOVE_CEILING('18014398509481982')); + // the base and fuel charge are inside; the accessorial at 2000 permille of the base is not. + refuses(grams({ accessorials: [{ accessorial_id: 'extra', permille_of_base: 2000 }] }, 4503599627370496), + ABOVE_CEILING('9007199254740992')); + // every component is inside and only their sum is above. + refuses(grams({}, 4503599627370496 * 1 + 1), ABOVE_CEILING('9007199254740994')); +}); + +test('a quote total exactly at the ceiling is answered', () => { + const result = grams({ accessorials: [] }, 9007199254740991)(); + assert.equal(result.quote.total_minor, 9007199254740991); +}); + // --------------------------------------------------------------------------- code points test('code-point ordering matches the other implementations, not UTF-16 order', () => { @@ -131,6 +170,13 @@ test('code-point ordering falls back to length for a shared prefix', () => { assert.equal(compareCodePoints('abc', 'ab'), 1); }); +test('unrecognised key names are listed in code-point order (S-04)', () => { + assert.throws( + () => loadDocument({ '\u{1F600}': 1, 'A': 1 }), + (error) => error instanceof CommerceInputError && error.message.endsWith('["A","\u{1F600}"]'), + ); +}); + test('catalog id lists come back in code-point order', () => { const entry = (id) => ({ id, dimensions_mm: [1, 1, 1], weight_g: 1 }); const document = catalogDocument({ @@ -340,3 +386,13 @@ test('catalog pinned lookups preserve boundaries and rollback across a long hist assert.equal(catalogVersionInfo(document, {catalog_id: 'c', as_of: 6, resolved_at: 100}).catalog.version, 65); assert.equal(catalogVersionInfo(document, {catalog_id: 'c', as_of: 0, resolved_at: 100}).catalog.version, 63); }); + +test('tariff zones are validated in ascending code-point order of the zone key, whatever the insertion order (K2)', () => { + for (const zones of ['{"b":"x","2":"y"}', '{"2":"y","b":"x"}']) { + refuses(() => loadDocument(tariffDocument({ cost_per_dimensional_kg_minor: JSON.parse(zones) })), /\[2\]/); + } + for (const zones of ['{"b":-1,"2":-1}', '{"2":-1,"b":-1}']) { + refuses(() => loadDocument(tariffDocument({ cost_per_dimensional_kg_minor: JSON.parse(zones) })), /entries cannot be negative/); + } + refuses(() => loadDocument(tariffDocument({ cost_per_dimensional_kg_minor: { b: -1, a: 'x' } })), /\[a\]/); +}); diff --git a/test/fallback.test.mjs b/test/fallback.test.mjs index a99ee4d..f8a2fe6 100644 --- a/test/fallback.test.mjs +++ b/test/fallback.test.mjs @@ -5,7 +5,8 @@ import test from 'node:test'; import { Deadline, SequenceReplayError, UNSUPPORTED_FIELDS, UnsupportedFeatureError, BoundOverflowError, __spatialIndexForTests, __inspectHullShapeForTests, __objectiveBoundsForTests, - __objectiveVectorForTests, __requestBoundForTests, __runSmallestUnsortedForTests, + __objectiveVectorForTests, __requestBoundForTests, __runSmallestUnsortedForTests, __fractionalCoverForTests, + __billedWeightBoundForTests, __occupiesLessThanItsBoxForTests, __candidatePrefixForTests, __groupBatchesForTests, aggregateTermination, InvalidRequestError, explainUnpackedItem, explanationForUnpackedItem, packFallback, rebalanceWeight, verifyLoadingPrefixBusinessRules, __ratiosForTests, __planBeamForTests, @@ -1570,6 +1571,16 @@ test('a weight the tariff does not price is never reported as an answer', () => ); }); +test('a container landing exactly at 9007199254740991 is priced, not mistaken for unpriceable', () => { + const result = packFallback(landed({ weight_brackets_g: [5000], prices_minor: [9007199254740991] }, '200 g')); + assert.equal(result.score[1], 9007199254740991); + assert.equal(result.status, 'feasible'); + assert.throws( + () => packFallback(landed({ weight_brackets_g: [500], prices_minor: [9007199254740991] }, '200 g')), + /above its rate table's last bracket \(500 g\); the shipment has no published price/, + ); +}); + test('an unpriceable container loses to a priceable one in the general greedy path', () => { // Eight units is past the single-item shape the compact path takes, and `try_grid` // stands down for this objective anyway, so this lands in the general per-round key. @@ -2189,6 +2200,19 @@ test('the objective lower bound matches Python on every corpus case', (t) => { } assertObjectives(edge, instances, containers, edge.name); } + // The billed objectives need each type's tare, dimensional floor and priced + // brackets as well, so they are recorded apart, with `null` where the bound is withheld. + assert.ok(scene.billed.length > 0, 'a billed section that quietly emptied itself would be vacuous'); + for (const one of scene.billed) { + const containers = containersOf(one).map((container, index) => ({ + ...container, tare: BigInt(one.containers[index].tare), dimensional: BigInt(one.containers[index].dimensional), + brackets: one.containers[index].brackets.map(([bound, charge]) => [BigInt(bound), charge === null ? null : BigInt(charge)]), + })); + const name = one.fixture ?? one.name; + assert.deepEqual(__objectiveBoundsForTests(instancesOf(one), containers), one.bounds, `bounds diverge on ${name}`); + assert.deepEqual(__objectiveVectorForTests(instancesOf(one), containers, one.objective), one.vector, + `${one.objective} diverges from Python on ${name}`); + } }); test('the request bound is read from the request itself, in the objective\'s own order', () => { @@ -2217,9 +2241,114 @@ test('a result states its bound, and attainment is the only route to optimal', ( assert.equal(missed.optimality.absolute_gap, missed.score[missed.optimality.gap_key] - missed.optimality.lower_bound[missed.optimality.gap_key]); - const uncovered = packFallback(request([cube('c', 100)], [box('b', 300, 100, 100)], - { configuration: { objective: 'shipping_cost', dimensional_weight_divisor: 5000 } })); - assert.deepEqual(uncovered.optimality, { code: 'not_proven' }); + // Every built-in objective is covered since, so the withheld case is a + // made-to-measure container (D13). + // A copy of the conformance fixture, so the test runs where the shared corpus is absent. + const madeToMeasure = new URL('./fixtures/feature-made-to-measure-dimensional-weight-on-outer.json', import.meta.url); + assert.deepEqual(packFallback(JSON.parse(readFileSync(madeToMeasure))).optimality, { code: 'not_proven' }); +}); + +const GRAM = 8_000_000; +const brick = (quantity, grams) => cube('brick', 100, { quantity, weight: `${grams} g` }); +const billed = (objective, containers, items) => request(items, containers, { configuration: { + objective, dimensional_weight_divisor: 5000, dimensional_weight_length_unit: 'cm', + dimensional_weight_weight_unit: 'kg', solver_profile: 'exact_small' } }); + +test('a billed objective without its divisor gets no bound', () => { + // The billed key needs the configuration's divisor; the solver refuses such a + // request, and the bound path says nothing rather than inventing a divisor. + const pair = request([cube('i', 10, { quantity: 2 })], [box('box', 30, 30, 30)]); + for (const objective of ['shipping_cost', 'lowest_landed_cost']) { + assert.equal(__requestBoundForTests({ ...pair, configuration: { objective } }), null, objective); + } +}); + +test('shipping_cost bills at least the floor and at least tare plus payload', () => { + // A 200 x 100 x 100 mm box is 0.4 kg dimensional at 5000 cm/kg; two 1 kg bricks and a + // 300 g tare bill 2.3 kg actual, so the bound is the actual weight, and it is attained. + const result = packFallback(billed('shipping_cost', [box('box', 200, 100, 100, { tare_weight: '300 g' })], [brick(2, 1000)])); + assert.deepEqual(result.optimality.lower_bound.slice(0, 2), [0, 2300 * GRAM]); + assert.equal(result.status, 'optimal'); + // A 400 mm cube is 12.8 kg dimensional, above one light brick. + const bulky = __requestBoundForTests(billed('shipping_cost', [box('bulky', 400, 400, 400)], [brick(1, 100)])); + assert.equal(bulky[1], 12_800 * GRAM); + // A bag is billed on the package its load makes, so its floor is the tare and payload alone. + const bag = __requestBoundForTests(billed('shipping_cost', + [box('bag', 400, 400, 400, { deformable_boundary: { kind: 'flat_bag' } })], [brick(1, 100)])); + assert.equal(bag[1], 100 * GRAM); +}); + +test('lowest_landed_cost sees that two bricks cannot share a bracket', () => { + // Two 1000 g bricks cannot share a 1500 g bracket, so two containers pay it twice: the item + // cover says 200, which the weight cover alone (134) and the count term (100) miss. + const result = packFallback(billed('lowest_landed_cost', [ + box('snug-dear', 200, 100, 100, { rate_table: { weight_brackets_g: [20000], prices_minor: [5000] } }), + box('unit-cheap', 100, 100, 100, { rate_table: { weight_brackets_g: [1500], prices_minor: [100] } }), + ], [brick(2, 1000)])); + assert.deepEqual(result.optimality.lower_bound.slice(0, 2), [0, 200]); + assert.equal(result.score[1], 200); +}); + +test('lowest_landed_cost reads the cheapest bracket a floor can reach, priced as the rate table prices it', () => { + const g = 8_000_000n; + const one = [{ volume: 1n, weight: 1000n * g, shrinks: false, value: 0n }]; + const type = (brackets, rest = {}) => ({ usable: 10n, inner: 10n, baseArea: 1n, height: 10n, payload: null, + maxItems: null, quantity: null, costMinor: 0n, tare: 0n, dimensional: 0n, brackets, ...rest }); + // A promotional dip: the 2 kg bracket is dearer than the 5 kg one, and prices need not rise + // with weight, so a load billable in either is bounded by the cheaper. + assert.equal(__objectiveVectorForTests(one, [type([[2000n * g, 700n], [5000n * g, 400n]])], 'lowest_landed_cost')[1], 400); + // A floor above every bracket cannot be priced, and with nothing else to open no + // statement is made; an unpriced bracket offers nothing either. + assert.equal(__objectiveVectorForTests(one, [type([[5n, 100n]], { dimensional: 10n })], 'lowest_landed_cost'), null); + assert.equal(__objectiveVectorForTests(one, [type([[5000n * g, null]])], 'lowest_landed_cost'), null); + // `max(price, minimum)` then the surcharge rounded up: 300 + 26 and 900 + 77. + const priced = (prices) => __requestBoundForTests(billed('lowest_landed_cost', [box('c', 100, 100, 100, { rate_table: { + weight_brackets_g: [1000, 2000], prices_minor: prices, minimum_charge_minor: 300, fuel_surcharge_permille: 85 } })], + [brick(1, 1000)]))[1]; + assert.equal(priced([100, 900]), 326); + assert.equal(priced([2000, 900]), 977); +}); + +test('the landed bound caps each bracket by payload, volume and max_items, and only counts placed instances', () => { + const g = 8_000_000n; + const three = [1n, 2n, 3n].map((grams) => ({ volume: 4n, weight: grams * 1000n * g, shrinks: false, value: 0n })); + const type = (rest) => ({ usable: 100n, inner: 100n, baseArea: 10n, height: 10n, payload: null, maxItems: null, + quantity: null, costMinor: 0n, tare: 0n, dimensional: 0n, brackets: [[10000n * g, 100n]], ...rest }); + // Uncapped, one container carries all three: the count term, 100. + assert.equal(__objectiveVectorForTests(three, [type({})], 'lowest_landed_cost')[1], 100); + // One item per container: three are opened and the item cover pays three charges. + assert.equal(__objectiveVectorForTests(three, [type({ maxItems: 1n })], 'lowest_landed_cost')[1], 300); + // A 3 kg payload carries the two lightest, so the 6 kg placed weight needs two charges. + assert.equal(__objectiveVectorForTests(three, [type({ payload: 3000n * g })], 'lowest_landed_cost')[1], 200); + // Room for one 4-unit instance: three are needed. + assert.equal(__objectiveVectorForTests(three, [type({ usable: 4n })], 'lowest_landed_cost')[1], 300); + // An instance smaller than its box gives the volume no say. + const nested = three.map((instance) => ({ ...instance, shrinks: true })); + assert.equal(__objectiveVectorForTests(nested, [type({ usable: 4n })], 'lowest_landed_cost')[1], 100); + // The one cheap single-item container is taken whole, then the dear one covers the other + // two at two thirds of its charge: 10 + ceil(2 x 90 / 3). + const capped = type({ brackets: [[10000n * g, 10n]], quantity: 1n, maxItems: 1n }); + assert.equal(__objectiveVectorForTests(three, [capped, type({ brackets: [[10000n * g, 90n]] })], 'lowest_landed_cost')[1], 70); + // Nothing placed costs nothing. + assert.deepEqual(__objectiveVectorForTests(three, [type({ quantity: 0n })], 'lowest_landed_cost').slice(0, 2), [3, 0]); +}); + +test('the fractional cover takes cost-per-unit order and rounds only once', () => { + // Greedy by cost per unit is exact for one covering constraint; inventory caps an offer. + assert.equal(__fractionalCoverForTests([[10n, 3n, null], [4n, 1n, null]], 7n), 24n); + assert.equal(__fractionalCoverForTests([[10n, 3n, 1n], [4n, 1n, null]], 7n), 26n); + assert.equal(__fractionalCoverForTests([[10n, 3n, 1n]], 7n), null); + assert.equal(__fractionalCoverForTests([[0n, 5n, null]], 7n), 0n); + assert.equal(__fractionalCoverForTests([[5n, 0n, null]], 0n), 0n); +}); + +test('the shipping bound is withheld without enough inventory to open', () => { + // `L0` keeps `L1` inside the inventory, so this is reached only directly, as Python tests it. + const one = { tare: 0n, dimensional: 5n, quantity: 1n }; + assert.throws(() => __billedWeightBoundForTests([[1n, 2n]], [one], 2n, 2n), { name: 'BoundWithheld' }); + // One opened container bills its floor, 5, above the two ticks it carries. + assert.equal(__billedWeightBoundForTests([[1n, 2n]], [one], 2n, 1n), 5n); + assert.equal(__billedWeightBoundForTests([[1n, 2n]], [one], 0n, 0n), 0n); }); test('maximum_value, open_dimension_height and maximum_volume each bound their own key', () => { @@ -3390,3 +3519,69 @@ test('multilayer quality beam search with diamond top_load and compressible item assert.deepEqual(validate(payload, result), []); }); + +test('the block solver orders item types by code point, not UTF-16 unit (S-03)', () => { + // "A" (U+FF21) sorts before an astral id by code point and after it by UTF-16 unit, so the + // renamed request ("a" < "b") must pack exactly like the one that uses the real ids. + const request = (first, second) => ({ + units: { length: 'mm' }, + configuration: { + solver_profile: 'quality', time_limit_ms: 300_000, + effort_budget: { max_candidates_evaluated: 1_000_000, max_placement_attempts: 1_000_000, max_search_nodes: 1_000_000 }, + }, + items: [ + { id: first, quantity: 3, dimensions: { length: '40', width: '60', height: '50' } }, + { id: second, quantity: 3, dimensions: { length: '40', width: '60', height: '50' } }, + ], + containers: [{ id: 'c', quantity: 2, inner_dimensions: { length: '80', width: '80', height: '80' } }], + }); + const outcome = (first, second) => { + const result = packFallback(request(first, second)); + return [result.containers.flatMap(({ placements }) => placements.map((placement) => placement.item_id)), + result.unpacked_items.map((item) => item.item_id)]; + }; + const renamed = JSON.stringify(outcome('b', 'a')).replaceAll('b#', '\u{1F600}#').replaceAll('a#', '\uFF21#'); + assert.equal(JSON.stringify(outcome('\u{1F600}', '\uFF21')), renamed); +}); + +test('two identical container types are opened in code-point order of their ids, as in the other engines', () => { + for (const profile of ['fast', 'quality']) { + for (const [listed, opened] of [[['9', '10'], '10'], [['1e1', '10'], '10'], [['\u{1F600}', '\uFF21'], '\uFF21']]) { + const result = packFallback({ + configuration: { solver_profile: profile }, + items: [{ id: 'cube', quantity: 1, dimensions: { length: '10', width: '10', height: '10' } }], + containers: listed.map((id) => ({ id, quantity: 1, inner_dimensions: { length: '20', width: '20', height: '20' } })), + }); + assert.equal(result.containers[0].container_type, opened, `${profile}: ${listed.join(', ')}`); + } + } +}); + +test('rebalanceWeight trials leave the request and the packing it was given untouched (A-02)', () => { + const payload = request( + [ + cube('heavy', 10, { weight: '500', priority: 2 }), + cube('light', 10, { weight: '100', priority: 1 }), + cube('alone', 10, { weight: '100' }), + ], + [box('box', 30, 10, 10, { quantity: 2, max_items: 2 })], + ); + const original = packSound(payload); + const requestBefore = JSON.stringify(payload); + const resultBefore = JSON.stringify(original); + const first = rebalanceWeight(payload, original); + assert.equal(first.improved, true); + assert.equal(JSON.stringify(payload), requestBefore); + assert.equal(JSON.stringify(original), resultBefore); + assert.deepEqual(rebalanceWeight(payload, original), first); +}); + +test('the maximal-spaces ranking compares candidates field by field, not as a sum past 2^53 (S-08)', async () => { + const { readFile } = await import('node:fs/promises'); + const name = 'regression-kilometre-scale-deck-shares-its-weight-across-piers.json'; + const request = JSON.parse(await readFile(new URL(`./fixtures/${name}`, import.meta.url), 'utf8')); + request.configuration = { ...request.configuration, solvers: ['maximal_spaces'] }; + const result = packFallback(request); + assert.equal(result.containers.length, 1); + assert.equal(result.unpacked_items.length, 0); +}); diff --git a/test/fixed-placements.test.mjs b/test/fixed-placements.test.mjs index 0a23f5e..6c37fd3 100644 --- a/test/fixed-placements.test.mjs +++ b/test/fixed-placements.test.mjs @@ -337,6 +337,19 @@ for (const [name, items, container, placements] of LAWFUL) { }); } +// A fixed single-rule item is recounted exactly rather than trusted, so a searched +// item is kept out from under its overhang just as under a searched one. +test('a searched item never becomes the second supporter of a fixed single-contact item', () => { + const data = { items: [item('a', { quantity: 2, must_be_on_floor: true }), item('b', { quantity: 1, ground_contact_rule: 'single', dimensions: wide })], + containers: [room({ quantity: 1 })], fixed_placements: [at('a'), at('b', '0', '100')] }; + const result = packFallback(data); + // Without the recount the floor slot under the overhang, x = 100, is the first one taken. + const underOverhang = result.containers.flatMap((container) => container.placements) + .filter((placement) => !placement.fixed && placement.position.x.value === '100' && placement.position.z.value === '0'); + assert.deepEqual(underOverhang, []); + assert.deepEqual(validate(data, result), []); +}); + test('the validator catches a moved fixed item', () => { const packed = packFallback(request()); const moved = request({ placements: [fixed('0')] }); diff --git a/test/fixtures/feature-made-to-measure-dimensional-weight-on-outer.json b/test/fixtures/feature-made-to-measure-dimensional-weight-on-outer.json new file mode 100644 index 0000000..8a42fc7 --- /dev/null +++ b/test/fixtures/feature-made-to-measure-dimensional-weight-on-outer.json @@ -0,0 +1,60 @@ +{ + "units": { + "length": "mm" + }, + "configuration": { + "solver_profile": "balanced", + "time_limit_ms": 300000, + "minimum_support_ratio": 1, + "effort_budget": { + "max_candidates_evaluated": 1000000, + "max_placement_attempts": 1000000, + "max_search_nodes": 1000000 + }, + "objective": "shipping_cost", + "dimensional_weight_divisor": 5000, + "dimensional_weight_length_unit": "cm", + "dimensional_weight_weight_unit": "kg" + }, + "items": [ + { + "id": "cube", + "quantity": 8, + "weight": "1", + "dimensions": { + "length": "100", + "width": "100", + "height": "100" + } + } + ], + "containers": [ + { + "id": "machine", + "cost_minor": 40, + "inner_dimensions": { + "length": "1510", + "width": "1510", + "height": "1510" + }, + "made_to_measure": { + "minimum": { + "length": "60", + "width": "60", + "height": "60" + }, + "increment": { + "length": "25", + "width": "25", + "height": "25" + }, + "cost_per_square_metre_minor": 1000, + "outer_allowance": { + "length": "3", + "width": "3", + "height": "3" + } + } + } + ] +} diff --git a/test/fixtures/regression-kilometre-scale-deck-shares-its-weight-across-piers.json b/test/fixtures/regression-kilometre-scale-deck-shares-its-weight-across-piers.json new file mode 100644 index 0000000..c19c6be --- /dev/null +++ b/test/fixtures/regression-kilometre-scale-deck-shares-its-weight-across-piers.json @@ -0,0 +1,64 @@ +{ + "configuration": { + "solver_profile": "balanced", + "time_limit_ms": 300000, + "minimum_support_ratio": 0.5, + "effort_budget": { + "max_candidates_evaluated": 1000000, + "max_placement_attempts": 1000000, + "max_search_nodes": 1000000 + } + }, + "items": [ + { + "id": "deck", + "quantity": 1, + "dimensions": { + "length": "6000000000", + "width": "10", + "height": "10" + }, + "weight": { + "value": "2999", + "unit": "g" + }, + "allowed_rotations": [ + "LWH" + ], + "max_top_load": { + "value": "0", + "unit": "g" + } + }, + { + "id": "pier", + "quantity": 3, + "dimensions": { + "length": "2000000000", + "width": "10", + "height": "10" + }, + "weight": { + "value": "1", + "unit": "kg" + }, + "max_top_load": { + "value": "1000", + "unit": "g" + }, + "allowed_rotations": [ + "LWH" + ] + } + ], + "containers": [ + { + "id": "valley", + "inner_dimensions": { + "length": "6000000000", + "width": "10", + "height": "20" + } + } + ] +} diff --git a/test/plan-bound-hulls.test.mjs b/test/plan-bound-hulls.test.mjs index 8c26c99..7259959 100644 --- a/test/plan-bound-hulls.test.mjs +++ b/test/plan-bound-hulls.test.mjs @@ -1,7 +1,7 @@ import assert from 'node:assert/strict'; import test from 'node:test'; -import { __additionalContainerBoundForTests as additionalContainerBound } from '../fallback.js'; +import { __additionalContainerBoundForTests as additionalContainerBound, packFallback } from '../fallback.js'; /** * The container-plan bound against `convex_hull` items. @@ -29,3 +29,49 @@ test('a cuboid still counts its whole box', () => { const plan = { remaining: [cube, cube], inventory: new Map([['crate', 2]]) }; assert.equal(additionalContainerBound(plan, [crate]), 2); }); + +/** + * The payload half of the same bound. Weights and payloads are BigInt ticks, and the half + * mixed them with `Math.max` and `Math.ceil`, so a `quality` solve over two container types + * that both carry `max_payload` threw a TypeError instead of answering. + */ +const brick = (w) => ({ d: [10, 10, 10], w, nesting: null, rots: ['LWH'], shapeType: 'box' }); + +test('payload decides when volume does not: seven kilograms need two five-kilogram crates', () => { + const light = { id: 'light', d: [100, 100, 100], max: 3n }; + const heavy = { id: 'heavy', d: [100, 100, 100], max: 5n }; + const plan = { + remaining: [brick(3n), brick(4n)], + inventory: new Map([['light', 2], ['heavy', 2]]), + }; + assert.equal(additionalContainerBound(plan, [light, heavy]), 2); +}); + +test('an exact multiple of the payload is not rounded up', () => { + const heavy = { id: 'heavy', d: [100, 100, 100], max: 5n }; + const plan = { remaining: [brick(5n), brick(5n)], inventory: new Map([['heavy', 3]]) }; + assert.equal(additionalContainerBound(plan, [heavy]), 2); +}); + +test('one container type without a payload limit switches the payload half off', () => { + const heavy = { id: 'heavy', d: [100, 100, 100], max: 5n }; + const open = { id: 'open', d: [100, 100, 100], max: null }; + const plan = { remaining: [brick(9n)], inventory: new Map([['heavy', 1], ['open', 1]]) }; + assert.equal(additionalContainerBound(plan, [heavy, open]), 1); +}); + +test('a quality solve over two payload-limited container types answers', () => { + const result = packFallback({ + configuration: { + solver_profile: 'quality', time_limit_ms: 60000, + effort_budget: { max_candidates_evaluated: 200000 }, + }, + items: [{ id: 'a', quantity: 6, weight: '1 kg', dimensions: { length: '100', width: '100', height: '100' } }], + containers: [ + { id: 's', cost_minor: 5, max_payload: '5 kg', inner_dimensions: { length: '150', width: '150', height: '150' } }, + { id: 'm', cost_minor: 8, max_payload: '9 kg', inner_dimensions: { length: '250', width: '250', height: '150' } }, + ], + }); + assert.equal(result.unpacked_items.length, 0); + assert.equal(result.summary.packed_item_count, 6); +}); diff --git a/test/policy.test.mjs b/test/policy.test.mjs index 7164aee..9e765ee 100644 --- a/test/policy.test.mjs +++ b/test/policy.test.mjs @@ -138,6 +138,25 @@ test('resolution orders rules by priority then id, never by declaration order', assert.match(unpackedByPolicy(withRules(prioritised)).details[0], /^zebra-routing@1: /); }); +test('the id tie-break compares code points, not UTF-16 units (S-02)', () => { + // "\uFF21" is below an astral id by code point and above it by UTF-16 unit; Python and Rust + // cite the fullwidth rule. + const rules = ['\u{1F600}', '\uFF21'].map((id, index) => ({ + id, version: 1, effective_at: AS_OF, priority: 10, + require_container_tag: { item_tag: 'food', container_tag: ['reefer', 'dock'][index] }, + })); + for (const declared of [rules, [...rules].reverse()]) { + assert.match(unpackedByPolicy(withRules(declared)).details[0], /^\uFF21@1: /); + } +}); + +test('unknown key names in a refusal are listed in code-point order (S-04)', () => { + assert.throws( + () => parsePolicy({ as_of: 0, '\u{1F600}': 1, '\uFF21': 1 }), + (error) => error instanceof PolicyError && error.message.endsWith('\uFF21, \u{1F600}'), + ); +}); + test('an undeclared shipment fact is absent rather than matching anything', () => { const rule = { id: 'r', version: 1, effective_at: 0, priority: 0, diff --git a/test/request-errors.test.mjs b/test/request-errors.test.mjs index eaecd29..8c811cc 100644 --- a/test/request-errors.test.mjs +++ b/test/request-errors.test.mjs @@ -367,3 +367,80 @@ test('every item weight times its quantity and the heaviest tare fit the ceiling assert.equal(result.containers.reduce((total, container) => total + BigInt(container.payload_weight.ticks), 0n), 2n ** 63n - 2n); }); + +test('a rate table prices its top bracket at most 9007199254740991 with the fuel surcharge (M1)', () => { + const message = 'must price its top bracket at most 9007199254740991 minor units with the fuel surcharge'; + const table = (edit) => (request) => { + request.containers[0].rate_table = { weight_brackets_g: [1000, 5000], prices_minor: [100, 200] }; + edit(request.containers[0].rate_table); + }; + const refused = (edit) => assertRefused(table(edit), 'above_maximum', '/containers/0/rate_table', message); + refused((t) => { t.prices_minor = [100, 9007199254740991]; t.fuel_surcharge_permille = 1; }); + refused((t) => { t.minimum_charge_minor = 9007199254740991; t.fuel_surcharge_permille = 1; }); + refused((t) => { t.prices_minor = [9007199254740990, 9007199254740991]; t.fuel_surcharge_permille = 9007199254740991; }); + // base 9e15 is inside; with 1000 permille the landed charge is not. + refused((t) => { t.prices_minor = [100, 9000000000000000]; t.fuel_surcharge_permille = 1000; }); + // A wrong-typed price still reports its own error first. + assertRefused(table((t) => { t.prices_minor = [100, '9007199254740991']; t.fuel_surcharge_permille = 1000; }), + 'wrong_type', '/containers/0/rate_table/prices_minor/1', 'must be an integer'); + // Landed at or inside the ceiling is answered, including a base x permille product that passes 2^53. + for (const [price, permille] of [[9007199254740991, 0], [9007199254740991, null], [4503599627370495, 1000], [9000000000000000, 0], [10000000000000, 1000]]) { + const request = base(); + table((t) => { t.prices_minor = [100, price]; if (permille !== null) t.fuel_surcharge_permille = permille; })(request); + assert.ok(packFallback(request).containers.length > 0); + } +}); + +test('the top-bracket ceiling reads a rate table of any length without overflowing the stack (M1)', () => { + const brackets = (price) => (request) => { + request.containers[0].rate_table = { weight_brackets_g: Array.from({ length: 300_000 }, (_, index) => index + 1), + prices_minor: Array.from({ length: 300_000 }, () => price), fuel_surcharge_permille: 1 }; + }; + const request = base(); + brackets(5)(request); + assert.ok(packFallback(request).containers.length > 0); + assertRefused(brackets(9007199254740991), 'above_maximum', '/containers/0/rate_table', + 'must price its top bracket at most 9007199254740991 minor units with the fuel surcharge'); +}); + +test('a measure is a sign, ASCII digits and a decimal point with digits on both sides, or a fraction, as in Python (K1)', () => { + const side = (spelling) => (request) => { request.items[0].dimensions.length = spelling; }; + const refusedSpellings = ['100 millimeters', '100.', '.5', '+.5', '-.5', '0x64', '1e2', '1_0', '1/2/3', '1.5.2', '1 /2 3', '0.1111111111111111111', '1']; + for (const spelling of refusedSpellings) { + assertRefused(side(spelling), 'wrong_type', '/items/0/dimensions/length', 'must be a measure'); + } + assertRefused(side('-5'), 'negative_measure', '/items/0/dimensions/length', 'cannot be negative'); + assertRefused((request) => { request.items[0].weight = '.5 g'; }, 'wrong_type', '/items/0/weight', 'must be a measure'); + assertRefused((request) => { request.items[0].weight = '1 mm'; }, 'wrong_type', '/items/0/weight', 'must be a measure'); + for (const spelling of ['100', '100.0', '0.5', '+5', '1/2', '1 1/2', '5 /2', '100 MM', '0.111111111111111111']) { + const request = base(); + side(spelling)(request); + assert.ok(packFallback(request).containers.length >= 0, spelling); + } + for (const weight of ['1 g', '1 G', '1 kg', '1 KG', '1 lb', '1 LBS']) { + const request = base(); + request.items[0].weight = weight; + assert.ok(packFallback(request).containers.length >= 0, weight); + } +}); + +test('a hull lists at most 32 vertices, refused before any hull is built (K3)', () => { + const ring = (count) => Array.from({ length: count }, (_, index) => { + const angle = (2 * Math.PI * index) / count; + return { x: (50 + 40 * Math.cos(angle)).toFixed(3), y: (50 + 40 * Math.sin(angle)).toFixed(3), z: index % 2 === 0 ? '0' : '100' }; + }); + const hull = (vertices) => (request) => { + Object.assign(request.items[0], { shape_type: 'convex_hull', hull_vertices: vertices }); + }; + assertRefused(hull(ring(33)), 'above_maximum', '/items/0/hull_vertices', 'must have at most 32 vertices'); + // The cap comes before the per-vertex rules, and a non-list reports its own type error first. + assertRefused(hull([...ring(32), 'not a vertex']), 'above_maximum', '/items/0/hull_vertices', 'must have at most 32 vertices'); + assertRefused(hull('many'), 'wrong_type', '/items/0/hull_vertices', 'must be a list'); + const request = base(); + hull(ring(32))(request); + try { + packFallback(request); + } catch (error) { + assert.ok(!/at most 32 vertices/.test(error.message), error.message); + } +}); diff --git a/test/result-validation-bound.test.mjs b/test/result-validation-bound.test.mjs index cee95f9..ff5ea88 100644 --- a/test/result-validation-bound.test.mjs +++ b/test/result-validation-bound.test.mjs @@ -69,8 +69,83 @@ if (!fs.existsSync(SCENE)) { .map((scenario) => scenario.name || scenario.fixture); assert.deepEqual(disagreements, []); }); + + test('the billed objectives\' vectors match the shared scene', () => { + const scene = JSON.parse(fs.readFileSync(SCENE, 'utf8')); + assert.ok(scene.billed.length > 0); + const disagreements = scene.billed.filter((scenario) => { + const [volumes, weights, shrinks, containers] = sceneInputs(scenario); + const billed = containers.map((container, index) => { + const { tare, dimensional, brackets } = scenario.containers[index]; + const floor = integer(tare) > integer(dimensional) ? integer(tare) : integer(dimensional); + return { ...container, tare: integer(tare), floor, brackets: brackets.map(([limit, charge]) => [integer(limit), optional(charge)]) }; + }); + const { bound } = objectiveLowerBound(scenario.objective, () => [], volumes, weights, shrinks, billed); + return JSON.stringify(bound && bound.map(Number)) !== JSON.stringify(scenario.vector); + }).map((scenario) => scenario.fixture || scenario.name); + assert.deepEqual(disagreements, []); + }); + + test('a bound where none is stated is an optimality_bound_mismatch', async () => { + // Every built-in objective is covered since; a made-to-measure container (D13) is + // where no bound is stated. + const { packFallback } = await import('../fallback.js'); + const fixture = new URL('./fixtures/feature-made-to-measure-dimensional-weight-on-outer.json', import.meta.url); + const request = JSON.parse(fs.readFileSync(fixture, 'utf8')); + const packed = packFallback(request); + packed.optimality.lower_bound = [0]; + assert.deepEqual(validateWith(null, request, packed).map(({ code, detail }) => [code, detail]), [[ + 'optimality_bound_mismatch', 'lower_bound is reported where no bound is stated: a container is made to measure', + ]]); + }); } +test('a billed objective states the bound the validator recomputes, and one moved by one is caught', async () => { + const { packFallback } = await import('../fallback.js'); + for (const configuration of [ + { objective: 'shipping_cost', dimensional_weight_divisor: 5000, dimensional_weight_length_unit: 'cm', dimensional_weight_weight_unit: 'kg' }, + { objective: 'lowest_landed_cost', dimensional_weight_divisor: 5000, dimensional_weight_length_unit: 'cm', dimensional_weight_weight_unit: 'kg' }, + ]) { + const priced = { weight_brackets_g: [1, 5000], prices_minor: [900, 400], minimum_charge_minor: 450, fuel_surcharge_permille: 85 }; + const request = { + items: [{ id: 'cube', quantity: 2, weight: '300 g', dimensions: { length: '100', width: '100', height: '100' } }], + containers: [ + { id: 'box', tare_weight: '50 g', inner_dimensions: { length: '200', width: '100', height: '100' }, rate_table: priced }, + { id: 'bag', inner_dimensions: { length: '300', width: '100', height: '100' }, deformable_boundary: { kind: 'flat_bag' }, rate_table: priced }, + { id: 'walled', inner_dimensions: { length: '200', width: '100', height: '100' }, outer_dimensions: { length: '210', width: '110', height: '120' }, + rate_table: { weight_brackets_g: [100], prices_minor: [1] } }, + ], + configuration, + }; + const packed = packFallback(request); + assert.ok(Array.isArray(packed.optimality.lower_bound), configuration.objective); + assert.deepEqual(validateWith(null, request, packed), [], configuration.objective); + packed.optimality.lower_bound[1] -= 1; + assert.ok(validateWith(null, request, packed).some((found) => found.code === 'optimality_bound_mismatch'), configuration.objective); + } +}); + +test('a billed key is withheld where nothing can price it or no divisor bills it', () => { + const box = { + innerVolume: 1000n, baseArea: 100n, height: 10n, usable: 1000n, costMinor: 0n, payload: null, maxItems: 1n, quantity: null, + tare: 0n, floor: 10n, brackets: [[5n, 100n]], + }; + const unpriceable = 'no priceable inventory carries a packing that attains the count bound'; + const landed = (containers, priced = true) => objectiveLowerBound('lowest_landed_cost', () => [], [[1n, 2n]], [[1n, 2n]], false, containers, priced); + assert.deepEqual(landed([box]), { bound: null, withheld: unpriceable }); + // One item per container opens two, each paying the one charge it can reach. + assert.deepEqual(landed([{ ...box, floor: 0n }]).bound.slice(0, 2), [0n, 200n]); + assert.deepEqual(landed([{ ...box, floor: 0n }], false), { bound: null, withheld: unpriceable }); + // The one cheap single-item container is taken whole, then the dear one covers the other + // item at half its charge: 10 + ceil(100 / 2). + const capped = { ...box, floor: 0n, brackets: [[5n, 10n]], quantity: 1n }; + const unlimited = { ...box, floor: 0n, brackets: [[5n, 100n]], maxItems: null }; + assert.deepEqual(landed([capped, unlimited]).bound.slice(0, 2), [0n, 60n]); + // Shrinking instances drop the volume terms; one opened container still bills its floor. + const shipping = (containers) => objectiveLowerBound('shipping_cost', () => [], [[1n, 2n]], [[1n, 2n]], true, containers); + assert.deepEqual(shipping([{ ...box, maxItems: null, quantity: 1n }]).bound.slice(0, 2), [0n, 10n]); +}); + test('an unlimited capacity, a negative one and zero-volume instances are read as the reference reads them', () => { const container = { innerVolume: 1000n, baseArea: 100n, height: 10n, usable: -1n, costMinor: 3n, payload: 5n, maxItems: null, quantity: 1n, diff --git a/test/result-validation-port.test.mjs b/test/result-validation-port.test.mjs index df67be8..16f80c6 100644 --- a/test/result-validation-port.test.mjs +++ b/test/result-validation-port.test.mjs @@ -129,6 +129,10 @@ test('values compare, hash and convert as Python\'s do', () => { assert.equal(pyCmp(2.5, 1.5), 1); assert.equal(pyCmp(1.5, 1.5), 0); assert.equal(pyCmp(1e21, 10n ** 21n), 0); + assert.equal(pyCmp(1, JSON.parse('1e999')), -1); + assert.equal(pyCmp(1, JSON.parse('-1e999')), 1); + assert.equal(pyCmp(JSON.parse('1e999'), 10n ** 400n), 1); + assert.equal(pyCmp(JSON.parse('-1e999'), -(10n ** 400n)), -1); assert.equal(pyCmp(-1.5, -1), -1); assert.ok(pyEq([1, [2], null], [true, [2n], null])); assert.ok(!pyEq([1, 2], [1, 3])); diff --git a/test/result-writer.test.mjs b/test/result-writer.test.mjs index d705d6e..46c9362 100644 --- a/test/result-writer.test.mjs +++ b/test/result-writer.test.mjs @@ -123,6 +123,40 @@ test('six-place ratios round an exact half to even, from the exact fraction (S13 assert.ok(equals(doubleFraction(Number.MIN_VALUE), [1n, 2n ** 1074n])); }); +test('a reported ratio is six places of the correctly rounded double, as the other engines write it', async () => { + const { packFallback, __ratiosForTests: { ratioDouble, ratioPlaces } } = await import('../fallback.js'); + // [numerator, denominator, Python's `n / d`, Python's f"{n / d:.6f}"]. The first is 5x5x2 mm in + // 400x250x200 mm, in cubic ticks: an exact 0.0000025 whose double lies above the half. + const reference = [ + [204800000000000n, 81920000000000000000n, 2.5e-06, '0.000003'], + [384307168202282325n, 1152921504606846976n, 0.3333333333333333, '0.333333'], + [1208925819614629174706177n, 2417851639229258349412352n, 0.5, '0.500000'], + [9007199254740993n, 18014398509481984n, 0.5, '0.500000'], + [100000000000000000000000000007n, 300000000000000000000000000000n, 0.3333333333333333, '0.333333'], + [1n, 1000000000000000000000000000000n, 1e-30, '0.000000'], + [123456789012345678901n, 987654321098765432109n, 0.1249999988609375, '0.125000'], + ]; + for (const [numerator, denominator, quotient, text] of reference) { + assert.equal(ratioDouble(numerator, denominator), quotient); + assert.equal(ratioPlaces(numerator, denominator), text); + } + // Below 2^53 the division of two Numbers is already the correctly rounded one. + let state = 12345; + const next = () => { state = (state * 1103515245 + 12345) % 2147483648; return state % 1000000 + 1; }; + for (let i = 0; i < 20000; i++) { + const numerator = next(), denominator = next(); + assert.equal(ratioDouble(BigInt(numerator), BigInt(denominator)), numerator / denominator); + } + assert.equal(ratioPlaces(1, 128), '0.007812'); // the double is the half itself: to even + assert.equal(ratioPlaces(0, 7), '0.000000'); + const result = packFallback({ + configuration: {}, + items: [{ id: 'a', dimensions: { length: 5, width: 5, height: 2 }, weight: 1, quantity: 1 }], + containers: [{ id: 'c', inner_dimensions: { length: 400, width: 250, height: 200 }, max_weight: 1000, quantity: 1 }], + }); + assert.equal(result.containers[0].volume_utilization, '0.000003'); +}); + test('support_ratio and volume_utilization are written half to even (S13)', async () => { const { packFallback } = await import('../fallback.js'); const mm = (side) => ({ length: side, width: side, height: side }); diff --git a/test/stock-cut-errors.test.mjs b/test/stock-cut-errors.test.mjs index 361f6c9..2ed385b 100644 --- a/test/stock-cut-errors.test.mjs +++ b/test/stock-cut-errors.test.mjs @@ -38,3 +38,20 @@ test('replacement and lock refuse unreadable stock fields through the revision e assert.equal(stockCutBoxes(fixed, artifact, 1).containers[1].cost_minor, cost ?? 0); } }); + +test('a cut box priced past 2^53 - 1 is refused, not rounded (C-13)', () => { + const sides = { length: '10', width: '10', height: '10' }; + const request = { items: [{ id: 'cube', dimensions: sides }], containers: [ + { id: 'machine', inner_dimensions: sides, made_to_measure: { minimum: sides, increment: sides, cost_per_square_metre_minor: 9007199254740991 } }, + ] }; + const artifact = buildOperationalArtifact(request, packFallback(request)); + request.fixed_placements = [{ container_type: 'machine' }]; + // 10 mm cube: 600 mm^2 of surface is far below a square metre, so the price stays inside the ceiling. + assert.ok(Number.isSafeInteger(stockCutBoxes(request, artifact, 1).containers[1].cost_minor)); + // The same rate on a cut box of 2000 mm per side is 24 m^2 and passes it. + const cut = JSON.parse(JSON.stringify(artifact)); + for (const axis of ['length', 'width', 'height']) cut.geometry.containers[0].inner_dimensions[axis] = String(2000 * 16000); + assert.throws(() => stockCutBoxes(request, cut, 1), + (error) => error instanceof PlanRevisionError && error.code === 'invalid_revision' + && error.message === "a made-to-measure container's cost_per_square_metre_minor prices the largest box above 9007199254740991"); +}); diff --git a/test/support-diagnosis-clock.test.mjs b/test/support-diagnosis-clock.test.mjs new file mode 100644 index 0000000..2fe9563 --- /dev/null +++ b/test/support-diagnosis-clock.test.mjs @@ -0,0 +1,43 @@ +/** + * C-02: the "why unpacked" support verdict is a function of the request and the final layout. + * The replay of a finished layout must not read the deadline clock, so a deadline that passes + * only after the search ended cannot turn `insufficient_support` into another reason. + */ + +import assert from 'node:assert/strict'; +import test from 'node:test'; + +import { packFallback } from '../fallback.js'; + +const cuboid = (id, quantity, length, width, height) => ({ + id, quantity, allowed_rotations: ['LWH'], + dimensions: { length: String(length), width: String(width), height: String(height) }, +}); +// The support-is-the-only-blocker scene plus enough one-millimetre pebbles that the replay's +// candidate sweeps pass a clock-read boundary (the clock is read on every 64th orientation). +const request = () => ({ + units: { length: 'mm' }, + configuration: { solver_profile: 'fast', time_limit_ms: 300000, minimum_support_ratio: 0.75, + effort_budget: { max_candidates_evaluated: 1000000, max_placement_attempts: 1000000, max_search_nodes: 1000000 } }, + items: [cuboid('post', 1, 50, 100, 100), cuboid('plank', 1, 100, 100, 40), cuboid('pebble', 40, 1, 1, 1)], + containers: [{ id: 'box', quantity: 1, inner_dimensions: { length: '100', width: '100', height: '140' } }], + fixed_placements: [{ item_type: 'post', container_type: 'box', orientation: 'LWH', position: { x: '0', y: '0', z: '0' } }], +}); +const reasons = (result) => result.unpacked_items.map((item) => [item.item_type, item.reason]); + +test('a deadline that passes after the search does not change the support verdict', () => { + let reads = 0; + const reference = packFallback(request(), () => { reads++; return 0; }); + const verdict = reasons(reference).find(([, reason]) => reason === 'insufficient_support'); + assert.ok(verdict); + + // Whichever clock read the deadline passes at, a run whose search finished (nothing is + // reported as time_limit) must still give the verdict: a diagnosis that read the clock + // itself would lose it when the deadline passes during the replay. + for (let passesAt = 0; passesAt <= reads; passesAt++) { + let seen = 0; + const found = reasons(packFallback(request(), () => (seen++ < passesAt ? 0 : 1e9))); + if (found.some(([, reason]) => reason === 'time_limit')) continue; + assert.deepEqual(found.find(([item]) => item === verdict[0]), verdict, `deadline passes at read ${passesAt}`); + } +}); diff --git a/test/validate.mjs b/test/validate.mjs index d93e727..b4a9102 100644 --- a/test/validate.mjs +++ b/test/validate.mjs @@ -287,12 +287,14 @@ function placementIdIssues(result) { } /** - * A pallet's solving frame: the reported inner size is the declared deck, the load - * may pass it by the limit at each end and side, and coordinates start at the corner of the - * overhang zone. Without a limit the frame is the reported inner size and there is no deck. + * The frame the solver packed. A pallet's: the reported inner size is the declared + * deck, the load may pass it by the limit at each end and side, and coordinates start at the + * corner of the overhang zone. A standing bag's: the declared `L x W x H` turned to + * `W x H x L`. Otherwise the frame is the reported inner size and there is no deck. */ -function palletFrame(template, container, lengthUnit) { +function packedFrame(template, container, lengthUnit) { const inner = size(container.inner_dimensions); + if (template?.deformable_boundary?.orientation === 'standing') return { frame: [inner[1], inner[2], inner[0]], deck: null }; const limit = template?.pallet_overhang_limit; if (limit == null) return { frame: inner, deck: null }; const x = requestLengthTicks(limit.length, lengthUnit); @@ -320,7 +322,9 @@ function palletIssues(container, boxes, deck) { /** * A bag reports the package its placements make, and that package passes the girth - * rule a + c <= L, b + c <= W + G, G a gusseted bag's side gusset (1.10) and 0 for a flat one. + * rule 2(a + c) <= 2L + K, b + c <= W + G lying flat, and 2(b + c) <= 2L + K, a + b <= W + G + * standing in its `W x H x L` frame; G and K are a gusseted bag's side (1.10) and bottom + * gussets, 0 where none is declared. * Measured on the physical boxes, as the score below is: meaningful only when no clearance * was configured. */ @@ -334,9 +338,12 @@ function flatBagIssues(template, container, boxes, inner, deck, lengthUnit) { const issues = []; const reported = container.achieved_dimensions == null ? null : size(container.achieved_dimensions); if (reported == null || reported[0] !== a || reported[1] !== b || reported[2] !== c) issues.push('achieved_dimensions_mismatch'); - const depth = template.deformable_boundary.side_gusset_depth; - const gusset = depth == null ? 0 : requestLengthTicks(depth, lengthUnit); - if (a + c > inner[0] || b + c > inner[1] + gusset) issues.push('bag_girth_exceeded'); + const boundary = template.deformable_boundary; + const depth = (name) => (boundary[name] == null ? 0 : requestLengthTicks(boundary[name], lengthUnit)); + const side = depth('side_gusset_depth'), bottom = depth('bottom_gusset_depth'); + const [along, across, length, width] = boundary.orientation === 'standing' + ? [b + c, a + b, inner[2], inner[0]] : [a + c, b + c, inner[0], inner[1]]; + if (2 * along > 2 * length + bottom || across > width + side) issues.push('bag_girth_exceeded'); return issues; } @@ -362,7 +369,7 @@ export function validate(request, result) { } inventory.set(container.container_type, (inventory.get(container.container_type) ?? 0) + 1); - const { frame: inner, deck } = palletFrame(template, container, lengthUnit); + const { frame: inner, deck } = packedFrame(template, container, lengthUnit); const boxes = boxesOf(container, latticeSequences); if (template.max_items != null && boxes.length > template.max_items) issues.push('max_items_exceeded'); @@ -529,7 +536,7 @@ export function objective(request, result) { cost += containerCost(template, size(container.inner_dimensions)); // Utilization and height are measured against the frame the solver packed. - const { frame: inner, deck } = palletFrame(template, container, lengthUnit); + const { frame: inner, deck } = packedFrame(template, container, lengthUnit); const total = volume(inner); const boxes = boxesOf(container, latticeSequences); // Occupied volume follows the shape: a hull's own volume, a compressible item's height