diff --git a/.github/DISCUSSION_TEMPLATE/q-a.yml b/.github/DISCUSSION_TEMPLATE/q-a.yml
index 753c402..8ff9dc8 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.8.0 (JavaScript)"
+ placeholder: "@packvium/engine 1.9.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 449e80a..e8258a0 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.8.0 (JavaScript)"
+ placeholder: "@packvium/engine 1.9.0 (JavaScript)"
validations:
required: false
- type: textarea
diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml
index 187c8b2..0362d36 100644
--- a/.github/ISSUE_TEMPLATE/bug_report.yml
+++ b/.github/ISSUE_TEMPLATE/bug_report.yml
@@ -33,8 +33,8 @@ body:
id: version
attributes:
label: Package version
- description: The exact version installed, for example 1.8.0.
- placeholder: "1.8.0"
+ description: The exact version installed, for example 1.9.0.
+ placeholder: "1.9.0"
validations:
required: true
- type: input
diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml
index cb4a822..6f093e0 100644
--- a/.github/ISSUE_TEMPLATE/feature_request.yml
+++ b/.github/ISSUE_TEMPLATE/feature_request.yml
@@ -29,7 +29,7 @@ body:
id: version
attributes:
label: Package version
- placeholder: "1.8.0"
+ placeholder: "1.9.0"
validations:
required: true
- type: textarea
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 4cb3df4..f3962f3 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -18,8 +18,8 @@ jobs:
os: [ubuntu-latest, macos-latest, windows-latest]
node: ["16", "18", "20", "22", "24", "26"]
steps:
- - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
- - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
+ - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
+ - uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
with:
node-version: ${{ matrix.node }}
- if: matrix.node == '16'
@@ -33,8 +33,8 @@ jobs:
# the fallback needs that never made it into the published tarball.
runs-on: ubuntu-latest
steps:
- - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
- - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
+ - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
+ - uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
with: {node-version: "22"}
- run: npm pack
- name: Install the packed tarball into a clean project and import it
@@ -63,7 +63,7 @@ jobs:
contents: read
pull-requests: write
steps:
- - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
+ - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
- uses: actions/dependency-review-action@a1d282b36b6f3519aa1f3fc636f609c47dddb294 # v5.0.0
with:
fail-on-severity: low
diff --git a/.github/workflows/rc.yml b/.github/workflows/rc.yml
index d2619cc..151969a 100644
--- a/.github/workflows/rc.yml
+++ b/.github/workflows/rc.yml
@@ -26,8 +26,8 @@ jobs:
build:
runs-on: ubuntu-latest
steps:
- - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
- - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
+ - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
+ - uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
with: {node-version: "22"}
- run: npm test
@@ -44,7 +44,7 @@ jobs:
fi
- run: npm pack
- - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
+ - uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
with:
name: tarball
path: "*.tgz"
@@ -61,12 +61,12 @@ jobs:
id-token: write # npm Trusted Publishing and the attestation
attestations: write # build provenance, so a consumer can verify where a file came from
steps:
- - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
+ - uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
with: {node-version: "22", registry-url: "https://registry.npmjs.org"}
# OIDC trusted publishing needs npm 11.5.1 or newer; Node 22 bundles npm 10 (see release.yml).
- run: npm install -g npm@^11.5.1
- run: npm --version
- - uses: actions/download-artifact@fa0a91b85d4f404e444e00e005971372dc801d16 # v4.1.8
+ - uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7.0.0
with:
name: tarball
- uses: actions/attest-build-provenance@0f67c3f4856b2e3261c31976d6725780e5e4c373 # v4.1.1
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index fb1cac5..ef8c62d 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -22,8 +22,8 @@ jobs:
build:
runs-on: ubuntu-latest
steps:
- - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
- - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
+ - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
+ - uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
with: {node-version: "22"}
- run: npm test
@@ -40,7 +40,7 @@ jobs:
fi
- run: npm pack
- - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
+ - uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
with:
name: tarball
path: "*.tgz"
@@ -53,7 +53,7 @@ jobs:
id-token: write # npm Trusted Publishing and the attestation
attestations: write # build provenance, so a consumer can verify where a file came from
steps:
- - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
+ - uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
with: {node-version: "22", registry-url: "https://registry.npmjs.org"}
# npm's OIDC trusted publishing needs npm 11.5.1 or newer; Node 22 still bundles
# npm 10, which performs no OIDC exchange at all. The publish then goes out
@@ -62,7 +62,7 @@ jobs:
# that sent 1.0.0 out by hand, permanently without provenance.
- run: npm install -g npm@^11.5.1
- run: npm --version
- - uses: actions/download-artifact@fa0a91b85d4f404e444e00e005971372dc801d16 # v4.1.8
+ - uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7.0.0
with:
name: tarball
- uses: actions/attest-build-provenance@0f67c3f4856b2e3261c31976d6725780e5e4c373 # v4.1.1
@@ -80,7 +80,7 @@ jobs:
permissions:
contents: write # the Release is the only thing this workflow writes to the repository
steps:
- - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
+ - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
- name: Create the GitHub Release from the tag
env:
GH_TOKEN: ${{ github.token }}
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 712b49f..1f13914 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,45 @@ 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.9.0]
+
+The fallback now checks what the addon checks, spends an effort budget the same way and reports
+its time.
+
+### Changed
+
+- **Under a clearance a compressible item bears its load on its own footprint**, so its crush
+ check is stricter and `validate` measures its own compressed volume.
+- **Breaking for weights past `2^53 - 1` ticks:** a weight's `ticks`, and a `shipping_cost`
+ score position, are a `BigInt` past it, so `JSON.stringify` refuses such a result; the new
+ `stringifyExact` and `parseExact` carry it through JSON exactly. Below it nothing changes.
+- **A weight is at most `2^63 - 1` ticks, and so is every item's weight times its quantity plus
+ the heaviest tare**: past it, `invalid_request` / `above_maximum`; a weight written as a JSON
+ number past `2^53 - 1` is `invalid_value` and must be a string.
+- **The centre of gravity is checked under a `minimum_support_ratio` above 0:** a placement
+ covering at most half its base with the centroid outside the contact hull is refused.
+ A request without a ratio packs as before.
+- **Agrees with the other engines where 1.8 did not:** nesting under a clearance shares the
+ items' own overlap and a deep nesting column nests in pairs; a length past `2^53 - 1` ticks or
+ a box past `10^30` cubic ticks is `invalid_request` / `above_maximum`; a side that reads as zero
+ ticks is `invalid_value` / `must be positive`; an obstacle box outside its container is
+ `invalid_value` / `lies outside inner_dimensions`, each at its own pointer.
+- **`validate` checks the centroid (`centre_of_gravity_unsupported`) and the whole stack's load
+ (`top_load_exceeded`)**, an item on several bearers shared by contact area. It no longer
+ holds that item's whole weight against every bearer, so it accepts some results 1.8 rejected
+ and names the overloaded bearer.
+- **A plan beam wider than 1 compares every container type**, whatever the node limit.
+- **The JavaScript fallback spends `effort_budget` as the other engines do**, and its `quality`
+ beam refines its best order once instead of its first two: about 1.6x faster, no score changed.
+- **`algorithm.duration_ms` reports the milliseconds the fallback took**; it was always 0.
+- **The native backend accepts null obstacle coordinates as zero**, including additional boxes,
+ consistently with request admission.
+
+### Fixed
+
+- **The fallback no longer slides an item under a `ground_contact_rule: single` item that already
+ rests on one supporter.**
+
## [1.8.0]
`validate` works after a plain `npm install`, results say how far they can be from the best
diff --git a/CITATION.cff b/CITATION.cff
index e0f2a83..2e22be0 100644
--- a/CITATION.cff
+++ b/CITATION.cff
@@ -5,7 +5,7 @@ type: software
authors:
- name: "Packvium contributors"
website: "https://packvium.com"
-version: "1.8.0"
+version: "1.9.0"
license: MIT
url: "https://packvium.com"
repository-code: "https://github.com/toxakara/packvium-node"
diff --git a/README.md b/README.md
index b213003..e59e44d 100644
--- a/README.md
+++ b/README.md
@@ -319,7 +319,7 @@ Documentation, the constraint reference and the benchmarks are at
| --- | --- | --- |
| Python — [`packvium`](https://pypi.org/project/packvium/) | `pip install packvium` | [packvium-python](https://github.com/toxakara/packvium-python) |
| PHP — [`packvium/packvium`](https://packagist.org/packages/packvium/packvium) | `composer require packvium/packvium` | [packvium-php](https://github.com/toxakara/packvium-php) |
-| Rust — [`packvium`](https://crates.io/crates/packvium) | `packvium = "1.8"` | [packvium-rust](https://github.com/toxakara/packvium-rust) |
+| Rust — [`packvium`](https://crates.io/crates/packvium) | `packvium = "1.9"` | [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) |
@@ -350,7 +350,7 @@ CodeMeta form.
@software{packvium_node,
author = {{Packvium contributors}},
title = {Packvium for Node.js},
- version = {1.8.0},
+ version = {1.9.0},
license = {MIT},
url = {https://packvium.com}
}
diff --git a/artifacts.js b/artifacts.js
index 1b2b00e..74e7738 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.8.0';
+export const SUITE_VERSION = '1.9.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 f1da7f4..e93488d 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.8.0",
+ "version": "1.9.0",
"license": "https://spdx.org/licenses/MIT",
"author": [
{
diff --git a/commerce-model.js b/commerce-model.js
index 54f4738..b52e3d2 100644
--- a/commerce-model.js
+++ b/commerce-model.js
@@ -159,7 +159,7 @@ export function isUnary(operator) {
}
/**
- * Value equality over the JSON scalar types, matching the reference implementation
+ * Structural equality over JSON values, matching the reference implementation
* exactly -- including that a boolean equals the integer it stands for, the one place a
* naive `===` would disagree and quietly change a decision.
*/
@@ -175,12 +175,20 @@ export function valuesEqual(left, right) {
if (Array.isArray(left) || Array.isArray(right)) return false;
if (left === null || right === null) return left === right;
if (typeof left !== typeof right) return false;
+ if (typeof left === 'object') {
+ const keys = Object.keys(left);
+ return keys.length === Object.keys(right).length
+ && keys.every((key) => Object.hasOwn(right, key) && valuesEqual(left[key], right[key]));
+ }
return left === right;
}
function contains(haystack, needle) {
if (Array.isArray(haystack)) return haystack.some((entry) => valuesEqual(entry, needle));
if (typeof haystack === 'string') return typeof needle === 'string' && haystack.includes(needle);
+ if (haystack !== null && typeof haystack === 'object') {
+ return typeof needle === 'string' && Object.hasOwn(haystack, needle);
+ }
return false;
}
diff --git a/commerce.js b/commerce.js
index 4ed1786..8877a43 100644
--- a/commerce.js
+++ b/commerce.js
@@ -133,7 +133,7 @@ function loadHistories(value, path, identityKeys, label, parseVersion) {
const fields = asObject(entry, entryPath);
checkKeys(fields, entryPath, [...identityKeys, 'versions']);
const identity = identityKeys.map((name) => asText(fields[name], `${entryPath}.${name}`));
- const key = identity.join('/');
+ const key = identity.length === 1 ? identity[0] : JSON.stringify(identity);
if (histories.has(key)) fail(entryPath, `duplicate ${label} history for '${key}'`);
const versions = asList(fields.versions, `${entryPath}.versions`);
if (versions.length === 0) {
@@ -180,7 +180,7 @@ function parseTariff(value, path, [carrierId, serviceId], number) {
['minimum_charge_minor', 'fuel_surcharge_permille', 'accessorials'],
);
const zonesPath = `${path}.cost_per_dimensional_kg_minor`;
- const costPerDimensionalKgMinor = {};
+ const costPerDimensionalKgMinor = Object.create(null);
const zones = asObject(fields.cost_per_dimensional_kg_minor, zonesPath);
for (const [zone, cost] of Object.entries(zones)) {
costPerDimensionalKgMinor[zone] = nonNegative(
@@ -214,7 +214,7 @@ function parseTariff(value, path, [carrierId, serviceId], number) {
}
function parseAccessorials(value, path) {
- const charges = {};
+ const charges = Object.create(null);
asList(value, path).forEach((entry, index) => {
const entryPath = `${path}[${index}]`;
const fields = asObject(entry, entryPath);
@@ -311,12 +311,18 @@ function parseRollback(fields, path, number, history) {
if (target === undefined) {
fail(path, `rollback_to names version ${toVersion}, which is not published yet`);
}
- const publishedAt = asInteger(fields.published_at, `${path}.published_at`);
+ const publishedAt = nonNegative(
+ asInteger(fields.published_at, `${path}.published_at`),
+ path, 'published_at cannot be negative',
+ );
const note = asText(optional(fields, 'note') ?? '', `${path}.note`);
return {
number,
snapshot: target.snapshot,
- effectiveAt: asInteger(optional(fields, 'effective_at') ?? publishedAt, `${path}.effective_at`),
+ effectiveAt: nonNegative(
+ asInteger(optional(fields, 'effective_at') ?? publishedAt, `${path}.effective_at`),
+ path, 'effective_at cannot be negative',
+ ),
publishedAt,
rolledBackFrom: toVersion,
note: note === '' ? `rollback to version ${toVersion}` : note,
@@ -481,7 +487,7 @@ export function quote(document, request) {
}
function resolveTariff(carriers, identity, fields, pin) {
- const history = carriers.get(`${identity.carrier_id}/${identity.service_id}`);
+ const history = carriers.get(JSON.stringify([identity.carrier_id, identity.service_id]));
if (pin === 'tariff_version') {
const version = asInteger(fields.tariff_version, 'request.tariff_version');
const tariff = history?.find((candidate) => candidate.version === version);
@@ -591,7 +597,10 @@ export function catalogVersionInfo(document, request) {
const fields = asObject(request, 'request');
checkKeys(fields, 'request', ['catalog_id', 'resolved_at'], ['version', 'as_of']);
const catalogId = asText(fields.catalog_id, 'request.catalog_id');
- const resolvedAt = asInteger(fields.resolved_at, 'request.resolved_at');
+ const resolvedAt = nonNegative(
+ asInteger(fields.resolved_at, 'request.resolved_at'),
+ 'request.resolved_at', 'resolved_at cannot be negative',
+ );
const version = optional(fields, 'version') === undefined
? undefined
: asInteger(fields.version, 'request.version');
diff --git a/docs/COMMERCE-API.md b/docs/COMMERCE-API.md
index 7fcc53d..6f4e4b7 100644
--- a/docs/COMMERCE-API.md
+++ b/docs/COMMERCE-API.md
@@ -150,6 +150,10 @@ history with a hole or a duplicated version number.
All three top-level keys are optional; a document that only needs to price a shipment
may carry only `tariffs`. Field-level rules:
+- A tariff history is identified by the ordered pair `(carrier_id, service_id)`.
+ Separators inside either string are ordinary identifier characters: for example,
+ `("a/b", "c")` and `("a", "b/c")` name different histories. Duplicate detection and
+ both pinned and effective-dated lookup use the complete pair.
- `accessorials` is an ordered **list**, not an object, so no language has to agree
about key order; each entry sets exactly one of `flat_charge_minor` or
`permille_of_base`. Duplicate `accessorial_id` values are an input error.
@@ -165,6 +169,9 @@ may carry only `tariffs`. Field-level rules:
`published_at`, `cost_minor`, `minimum_charge_minor`, `fuel_surcharge_permille`,
`flat_charge_minor`, `permille_of_base` and each zone rate in
`cost_per_dimensional_kg_minor` may be zero but not negative.
+ Rollback versions follow the same date bounds as snapshot versions, and a catalog
+ request's `resolved_at` must also be non-negative, including when its catalog or
+ version does not exist. These are input errors rather than lookup rejections.
### Input errors versus rejections
@@ -244,6 +251,16 @@ Success:
`false` `allowed` always carries a citation — the model refuses to construct a
citation-free rejection.
+`equals` and `not_equals` compare JSON values recursively: list order matters,
+object key order does not, and different key sets remain different even when values
+are `null`. Boolean/integer equality follows the reference model (`true == 1`,
+`false == 0`), including inside lists and objects. `in` and `not_in` test list
+elements, string substrings, or object keys; object values are not members. A
+non-string context value cannot be a substring or an object key. A missing context
+field matches neither binary operator, including its negated form. Rust's rule priority
+comparison handles the entire signed 64-bit range without negating its minimum;
+portable JavaScript inputs remain limited by exact `Number` representation.
+
### `catalog_version_info`
Request:
@@ -368,6 +385,16 @@ The `e log e` term is sorting the three id lists; every other bound is a linear
the relevant history. These are the bounds of the underlying models; the wrapper adds
parsing and serialization, both linear in the payload, and nothing else.
+The policy rows treat predicate values as bounded. For structured values, multiply
+their predicate work by the comparison/membership cost: recursive equality visits
+the compared values, with an additional logarithmic key lookup per object entry in
+Rust's default ordered maps. PHP and JavaScript use expected constant-time object-key
+lookup; JavaScript also allocates key arrays during object comparison. Python's
+effective-dated model evaluation streams version resolution and winner selection in
+constant auxiliary space, excluding value-comparison recursion and the loaded
+document. Each matching rule's predicates run once; the other ports retain their
+existing rule-pool storage.
+
## Limitations
- The document is supplied by the caller. Nothing here fetches, scrapes or embeds any
@@ -380,6 +407,11 @@ parsing and serialization, both linear in the payload, and nothing else.
- Policy evaluation covers the closed `PolicyScope` / `PolicyOperator` vocabulary.
An unrecognised scope or operator fails document admission rather than being
silently ignored — the guarantee `domain/policy/model.py` already makes.
+- PHP's array boundary cannot recover the object/list distinction erased by an
+ associative JSON decoder: `{}` and `[]`, or an object with consecutive numeric
+ keys, can become the same PHP array. Portable object-valued predicates should use
+ nonempty objects with nonnumeric string keys. This limitation does not affect
+ list ordering or ordinary string-key object comparisons.
- A JSON number must be written without a fractional part. `1` is an integer; `1.0` and
`1e3` are not, and Python, PHP and Rust refuse them. JavaScript cannot tell the
difference — `JSON.parse` gives the same `Number` for `1` and `1.0` — so this is the
diff --git a/docs/GUARANTEES.md b/docs/GUARANTEES.md
index 8cdcba6..0d40bf9 100644
--- a/docs/GUARANTEES.md
+++ b/docs/GUARANTEES.md
@@ -61,7 +61,7 @@ silently — if you need them, they belong in your own layer above this library.
## Status of this release
-Version `1.8.0` freezes the public API. Field names, status codes, the objective
+Version `1.9.0` freezes the public API. Field names, status codes, the objective
vector, the numeric policy and the validation rules do not change without a major
version, so any `1.x` is a safe upgrade from any earlier `1.x`. A caret or tilde
constraint on `1.0` is enough; an exact pin is no longer required.
diff --git a/docs/PUBLIC-API.md b/docs/PUBLIC-API.md
index d737e88..7eb418e 100644
--- a/docs/PUBLIC-API.md
+++ b/docs/PUBLIC-API.md
@@ -239,6 +239,9 @@ All counters are non-negative integers. A zero means the selected solver did not
that phase; it does not mean the metric is unsupported. Compatibility fields
`algorithm.placements_attempted` and `algorithm.candidates_evaluated` remain and must
equal `metrics.orientations_considered` and `metrics.feasible_candidates`.
+For a multi-start portfolio these counters belong to the selected start; the complete
+list of starts is recorded separately in `termination.starts`. Counters are not summed
+across starts.
Metrics are diagnostics: they never participate in feasibility, ranking or the
objective vector.
@@ -469,9 +472,9 @@ bounds its work by counting must get the same answer on any machine, and a start
own share of the clock would lose quietly, with no flag saying the answer depended on the
machine's speed. When the clock does fire, the portfolio-wide deadline is reached and
`time_limit_reached` is true. Rust and the JavaScript fallback always run their starts against
-the one portfolio deadline. Each start keeps its own counters against the whole budget in
-Python, PHP and Rust; the JavaScript fallback hands each later start what the earlier ones
-left of one budget, so the same number buys less search there.
+the one portfolio deadline. Each start keeps its own counters against the whole budget, in all
+four engines; until 1.9.0 the JavaScript fallback handed each later start what the earlier ones
+left of one budget, so the same number bought less search there.
**Read `any_start_truncated` when the answer must not depend on the budget.** The selected
start can finish while another start, one that might have won, was stopped by the budget; the
diff --git a/docs/UNITS-AND-NUMERICS.md b/docs/UNITS-AND-NUMERICS.md
index fd1e6e6..c09c8e8 100644
--- a/docs/UNITS-AND-NUMERICS.md
+++ b/docs/UNITS-AND-NUMERICS.md
@@ -59,6 +59,42 @@ a caller would get a number from one and a refusal from another for the same inp
carries the guarded sums in a representation that holds `10^30` exactly: Python's `int`,
PHP's `BigInt` decimal strings, JavaScript's `BigInt`, Rust's `i128`.
+Areas follow the same rule in the search itself (1.9.0). Two lengths below
+`PHP_INT_MAX` ticks multiply past a native `int` -- a 10 mm wide item longer than about
+3,600 km already does -- and Python and Rust hold that product exactly. PHP forms every such
+product (base and contact areas, their sums and the load shared by them, the centre-of-gravity
+hull, lattice slot counts, the candidate score's room-left term) through
+`Packvium\Support\ExactInteger` and `ExactGeometry`: the native `int` while it fits, an exact
+decimal string past it, so an ordinary request pays one `is_int` check. The public
+`Dimensions::baseAreaTicks()` and `AxisAlignedBox::overlapAreaXY()` keep their `int` contract.
+`support_ratio` and `volume_utilization` are Python's correctly rounded `int / int`, not a
+quotient of two doubles.
+
+**The admission ceiling (1.9.0).** Every engine refuses, before any model is built, a
+JSON request with a length past `2^53 - 1` ticks (about 563,000 km) or a box -- an item, a
+container's inner or outer dimensions, an obstacle, a made-to-measure step -- enclosing more than
+`10^30` cubic ticks (about 244 million cubic metres). Both are `invalid_request` with reason
+`above_maximum` at the offending pointer (ERRORS.md). The first is the largest tick
+count JavaScript's `Number` holds exactly; the second is the bound path's own ceiling, which keeps
+`volume x 10^6` inside Rust's `i128`. Until 1.9.0 each engine failed past its own native limit: Rust
+and PHP refused a length past `2^63 - 1` ticks with different errors, Python and JavaScript answered,
+Python died with `decimal.InvalidOperation` at `10^20` mm, and Rust overflowed `i128` on a container
+past about `1.7 x 10^32` cubic ticks. A whole JSON number past `2^53 - 1` is refused the
+same way however a parser stored it, and a value past a native integer is read exactly to tell
+which way it is out of range.
+
+**Weights (1.9.0).** A weight is at most `2^63 - 1` ticks (about 1.15 million
+tonnes), and so is every item's weight times its quantity plus the heaviest container tare, so
+no container's payload or gross weight can pass a signed 64-bit integer, which is how Rust and
+PHP add them. Past either, the request is `invalid_request` / `above_maximum`, at the weight or at
+`/items`. A weight written as a JSON number past `2^53 - 1` is `invalid_value`: JavaScript has
+rounded such a number before any engine code reads it, so a weight that large is written as a
+string. Inside the ceiling every engine is exact: Python's `int`, PHP's `int` and `BigInt`,
+Rust's `i64` with `i128` products, and in JavaScript a `BigInt` for every weight sum. A
+JavaScript result carries a weight's `ticks`, and a `shipping_cost` score position, as a `Number`
+while it is exact and as a `BigInt` past `2^53 - 1`; `stringifyExact` and `parseExact` move such
+a result through JSON text without rounding it, and `pack` uses them on both backends.
+
That intermediate ceiling is deliberately not the result ceiling. The five bound keys can
cross JSON and are returned as JavaScript `Number` values, so every engine also refuses a
final key above **`2^53 - 1` (`9,007,199,254,740,991`)**. This is the largest integer all four
diff --git a/exact-json.js b/exact-json.js
new file mode 100644
index 0000000..8f58a0a
--- /dev/null
+++ b/exact-json.js
@@ -0,0 +1,61 @@
+/**
+ * JSON text for results whose integers can pass 2^53 - 1 (R19-01).
+ *
+ * A weight is admitted up to `2^63 - 1` ticks, and a `Number` holds only 2^53 - 1 exactly, so a
+ * result carries such a weight's `ticks`, and a score position that sums weights, as a `BigInt`.
+ * `JSON.stringify` refuses a `BigInt` and `JSON.parse` rounds a long integer, so this package
+ * moves results through text with these two instead: a `BigInt` is written as the integer it
+ * is, and an integer past the safe range is read back as a `BigInt`; every other value is what
+ * `JSON` would make of it. O(text).
+ */
+
+const MARK = '\u0000packvium-exact-integer:';
+const SAFE = BigInt(Number.MAX_SAFE_INTEGER);
+const MARKED = /"\\u0000packvium-exact-integer:(-?\d+)"/g;
+const LONG_INTEGER = /-?\d{16,}(?![.\deE])/y;
+
+/** An integer as this package returns it: a `Number` while exact, a `BigInt` past 2^53 - 1. */
+export function exactInteger(digits) {
+ const value = BigInt(digits);
+ return value <= SAFE && value >= -SAFE ? Number(value) : value;
+}
+
+export function stringifyExact(value) {
+ return JSON.stringify(value, (_, member) => (typeof member === 'bigint' ? MARK + member : member))
+ .replace(MARKED, '$1');
+}
+
+export function parseExact(text) {
+ return JSON.parse(markLongIntegers(text), (_, member) =>
+ typeof member === 'string' && member.startsWith(MARK) ? exactInteger(member.slice(MARK.length)) : member);
+}
+
+/**
+ * `text` with every integer literal of 16 or more digits outside a string turned into a marked
+ * string, which the reviver above reads back exactly. The mark is written escaped: JSON text may
+ * not hold a raw control character. One pass, skipping string contents and their escapes.
+ */
+function markLongIntegers(text) {
+ let marked = '';
+ let copied = 0;
+ for (let index = 0; index < text.length; index++) {
+ const character = text[index];
+ if (character === '"') {
+ for (index++; index < text.length && text[index] !== '"'; index++) {
+ if (text[index] === '\\') index++;
+ }
+ continue;
+ }
+ if (character !== '-' && (character < '0' || character > '9')) continue;
+ LONG_INTEGER.lastIndex = index;
+ const match = LONG_INTEGER.exec(text);
+ if (match === null) {
+ while (index + 1 < text.length && /[-+.\deE]/.test(text[index + 1])) index++;
+ continue;
+ }
+ marked += `${text.slice(copied, index)}"\\u0000packvium-exact-integer:${match[0]}"`;
+ copied = index + match[0].length;
+ index = copied - 1;
+ }
+ return marked + text.slice(copied);
+}
diff --git a/examples/reproducibility.mjs b/examples/reproducibility.mjs
index e785bb1..7e8c88c 100644
--- a/examples/reproducibility.mjs
+++ b/examples/reproducibility.mjs
@@ -54,11 +54,16 @@ const solve = (maxCandidates) => pack({
/**
* A fingerprint of everything the result says. `duration_ms` is the one field that is a
- * measurement of the run rather than part of the answer, so it is zeroed first; the rest
- * is written in canonical JSON (sorted keys, no whitespace) so equal results hash equally.
+ * measurement of the run rather than part of the answer, so it is zeroed first, in the answer
+ * and in each alternative; the rest is written in canonical JSON (sorted keys, no whitespace)
+ * so equal results hash equally.
*/
+const withoutDuration = (answer) => ({ ...answer, algorithm: { ...answer.algorithm, duration_ms: 0 } });
const fingerprint = (result) => createHash('sha256')
- .update(commerce.canonicalJson({ ...result, algorithm: { ...result.algorithm, duration_ms: 0 } }))
+ .update(commerce.canonicalJson({
+ ...withoutDuration(result),
+ alternatives: (result.alternatives ?? []).map(withoutDuration),
+ }))
.digest('hex')
.slice(0, 16);
diff --git a/examples/serialization.mjs b/examples/serialization.mjs
index 890af8a..a9ef730 100644
--- a/examples/serialization.mjs
+++ b/examples/serialization.mjs
@@ -51,7 +51,9 @@ const section = (title) => console.log(`\n${rule}\n${title}\n${rule}`);
section('1. JSON in, JSON out');
console.log(` request ${body.length} characters of text`);
-console.log(` result ${text.length} characters of text`);
+// `duration_ms` is the run's wall clock, so its digits are counted as one: the length below
+// is the answer's, the same on every run.
+console.log(` result ${text.replace(/"duration_ms":\s*\d+/g, '"duration_ms":0').length} characters of text`);
console.log(` status ${result.status}`);
console.log(` score [${result.score.join(', ')}] <- exact integers, compared left to right`);
console.log(` opened ${result.containers.map((container) => container.id).join(', ')}`);
diff --git a/fallback.js b/fallback.js
index 9280818..baa81bb 100644
--- a/fallback.js
+++ b/fallback.js
@@ -95,12 +95,12 @@ function parseMachine(raw,unit,measures){
if(raw==null)return null;
const sides=value=>value==null?[0,0,0]:measures.sides(value,unit);
return {minimum:sides(raw.minimum),increment:sides(raw.increment),price:raw.cost_per_square_metre_minor??0,
- tarePerSquareMetre:raw.tare_per_square_metre==null?0:measures.weight(raw.tare_per_square_metre),allowance:sides(raw.outer_allowance)}
+ tarePerSquareMetre:raw.tare_per_square_metre==null?0n:measures.weight(raw.tare_per_square_metre),allowance:sides(raw.outer_allowance)}
}
// Billed weight in whole grams, rounded up -- how a carrier reads a scale. A shipment
// fractionally over a bracket is in the next bracket; rounding down would price it
// below what the carrier charges.
-const billedGrams=ticks=>ceilDiv(ticks,WT.g);
+const billedGrams=ticks=>Number((BigInt(ticks)+BigInt(WT.g)-1n)/BigInt(WT.g));
/** The charge for a billed weight, or `null` when the tariff does not price it. */
function chargeMinor(table,grams){
for(let index=0;index
groups.find(group=>group.tmpl.id===id).tmpl;
* `code: detail`, or null. Same rules, same order: collisions, then per placement bounds,
* obstacles, floor, eligibility, compatibility, tag counts, support and stacking, then per
* container load, axles, route, payload and item count, then groups. Item accounting is
- * left out because the free items have not been placed yet. The support-polygon centroid
- * test is absent because this engine does not enforce it in search either
- * (docs/VALIDATION-CONTRACT.md).
+ * left out because the free items have not been placed yet.
*/
function fixedSetIssue(groups,req,clear){
const globalRatio=req.configuration?.minimum_support_ratio??0,globalPpm=supportPpm(globalRatio),located=new Map();
@@ -302,7 +300,7 @@ function fixedSetIssue(groups,req,clear){
if(tmpl.bag&&!bagAdmits(tmpl,placements))return `bag_girth_exceeded: ${cid}`;
if(placements.some(p=>p.item.stopIndex!=null)){const stuck=routeStuck(placements,tmpl,clear);
if(stuck!==null)return `unloading_order_violation: ${cid}: stop ${stuck.stop} cannot be fully unloaded (${stuck.indices.map(k=>placements[k].item.id).join(', ')} still blocked)`}
- if(tmpl.max!=null&&placements.reduce((total,p)=>total+p.item.w,0)>tmpl.max)return `payload_exceeded: ${cid}`;
+ if(tmpl.max!=null&&placements.reduce((total,p)=>total+p.item.w,0n)>tmpl.max)return `payload_exceeded: ${cid}`;
if(tmpl.max_items!=null&&placements.length>tmpl.max_items)return `max_items_exceeded: ${cid}`;
for(const p of placements)if(p.item.group!=null){if(!located.has(p.item.group))located.set(p.item.group,new Set());located.get(p.item.group).add(cid)}}
for(const group of [...located.keys()].sort(compareCodePoints)){const where=[...located.get(group)].sort(compareCodePoints);
@@ -334,7 +332,12 @@ function supportIssue(p,others,globalRatio,globalPpm){
if(rule==='multiple'&&count<2)return ['ground_contact_violation',`multiple: rests on ${count} item(s)`];
if(required<=0)return null;
const area=supporters.reduce((total,support)=>total+support.area,0),base=p.ed[0]*p.ed[1];
- return areabase)return null;
+ const box={x:p.x,y:p.y,z:p.z,d:p.ed},hull=contactHull(box,supporters);
+ return pointInHull([BigInt(p.ed[0]),BigInt(p.ed[1])],hull)?null
+ :['centre_of_gravity_unsupported',`${area}/${base} met but centroid outside the ${hull.length}-point support hull`]
}
// The whole-container bearing pass, each rule reporting its first offender by instance id.
function loadIssue(boxes,graph,placements,tmpl){
@@ -364,7 +367,7 @@ function routeStuck(placements,tmpl,clear){
}
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]}
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),ticks=Number(round(n*BigInt(table[unit.trim().toLowerCase()]),d));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=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}
// 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`.
function outputLengthUnit(unit){const multiplier=LEN[unit.trim().toLowerCase()];return ['mm','cm','m','in','ft'].find(code=>LEN[code]===multiplier)??'mm'}
@@ -380,7 +383,7 @@ function dims(v,u){return [scalar(v.length,u,LEN),scalar(v.width,u,LEN),scalar(v
function requestMeasures(){
const tables=new Map([[LEN,new Map()],[WT,new Map()]]);let open=true;
const read=(table,value,unit)=>{
- if(value===0)return 0;
+ if(value===0)return table===WT?0n:0;
const byUnit=tables.get(table),known=byUnit.get(unit)?.get(value);
if(known!==undefined)return known;
const ticks=scalar(value,unit,table);
@@ -1000,7 +1003,7 @@ function itemOccupiedVolume(item){
* Nominal volume is not additive under nesting, so that half stands down there. O(n + t). */
function additionalContainerBound(plan,templates){const available=templates.filter(t=>plan.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,0);if(capacity>0)lower=Math.max(lower,Math.ceil(required/capacity))}return lower}
+ 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}
export function __additionalContainerBoundForTests(plan,templates){return additionalContainerBound(plan,templates)}
/** First compressible box carrying more pressure than it declared it can take.
*
@@ -1012,8 +1015,9 @@ function crushed(boxes,loads=null){
if(loads==null)loads=topLoads(boxes);
return boxes.some((b,i)=>{
if(b.maxCompressionKpa==null)return false;
- const footprint=b.d[0]*b.d[1];
- return pressureExceeds(appliedPressure(Number(loads[i]),footprint),b.maxCompressionKpa);
+ // The load presses on the item itself, not on the clearance its envelope adds.
+ const footprint=b.footprint??BigInt(b.d[0])*BigInt(b.d[1]);
+ return pressureExceeds(appliedPressure(loads[i],footprint),b.maxCompressionKpa);
});
}
/** Parse and admit an item's shape, or refuse it with the reason.
@@ -1067,8 +1071,13 @@ function usedVolume(placements){
// placement order: O(n + k^2) for k nesting placements instead of O(n^2) for every result.
const nesting=[];for(const p of placements)if(p.item.nesting!=null)nesting.push(p);
for(let i=0;i0?BigInt(height)*BigInt(placement.pd[0])*BigInt(placement.pd[1]):0n}
// What `tentative` would add to `usedVolume(placements.concat(tentative))`, without
// recomputing it. Appending to the end only creates the pairs that include the new
// placement, so the delta is its own volume less the nesting overlap it forms against
@@ -1076,8 +1085,7 @@ function usedVolume(placements){
// per candidate orientation, which is what made the whole solve super-linear in item
// count before.
function usedVolumeDelta(placements,tentative){let delta=occupiedVolume(tentative);
- for(const placed of placements)if(validNesting(placed,tentative))
- delta-=BigInt(placed.item.nesting)*BigInt(placed.ed[0])*BigInt(placed.ed[1]);
+ for(const placed of placements)if(validNesting(placed,tentative))delta-=nestedOverlap(placed);
return delta}
// Candidate points are consumed smallest-first by (z, y, x) and only the leading
// `max_candidate_points` are ever read, so the search keeps one array in that order and
@@ -1351,7 +1359,14 @@ function outPoint(p,u){return {x:outLength(p.x,u),y:outLength(p.y,u),z:outLength
// JSON has no BigInt scalar, while the established result schema exposes `ticks` as a
// number. Keep the exact integer through every calculation and comparison, render the
// decimal value from it, and convert only the compatibility `ticks` field here.
-function outWeight(v,u){const exact=typeof v==='bigint'?v:BigInt(v);return {ticks:Number(exact),value:decimalString(exact,WT[u]),unit:u}}
+// Weights are exact `BigInt` ticks inside the engine, up to the `2^63 - 1` admission ceiling
+// (R19-01); `ticks` stays a `Number` while it is one exactly, and is a `BigInt` past 2^53 - 1.
+const MAX_SAFE_TICKS=BigInt(Number.MAX_SAFE_INTEGER);
+const heavier=(a,b)=>a>b?a:b,lighter=(a,b)=>aab?1:0;
+function outWeight(v,u){const exact=typeof v==='bigint'?v:BigInt(v);return {ticks:exactTicks(exact),value:decimalString(exact,WT[u]),unit:u}}
+function exactTicks(exact){return exact<=MAX_SAFE_TICKS&&exact>=-MAX_SAFE_TICKS?Number(exact):exact}
function proofForReason(reason,details=[]){const level=['no_compatible_container_dimensions','payload_exceeded','no_eligible_container','rotation_restricted','policy_rule'].includes(reason)?'proven':['time_limit','effort_limit'].includes(reason)?'unknown_due_to_limit':['no_feasible_placement','search_exhausted','exact_search_incomplete','insufficient_support'].includes(reason)?'observed':'inferred';return {level,observations:[{code:reason,count:1,details}]}}
function catalogVersionsUsed(raw=[]){
if(!Array.isArray(raw))throw new TypeError('catalog_versions_used must be an array');
@@ -1401,6 +1416,28 @@ export class Deadline{constructor(limitMs,clock=monotonicNow){this.clock=clock;t
// Exact floor(baseArea * ratio / 1) with the ratio held at parts per million, so support
// is decided on integers rather than a float comparison against an epsilon.
+// Area alone is not stability. A candidate can clear the ratio while its
+// centroid lies outside the convex hull of its contact areas, which Python's and PHP's
+// SupportConstraint refuse with centre_of_gravity_unsupported. Work relative to the box
+// origin before doubling: world-space 2*x+length can lose a half tick even for safe inputs.
+// The doubled local centroid is exactly the extent; BigInt keeps cross products exact.
+// O(s log s) for s supporters: the hull is over at most 4s overlap corners.
+function contactHull(box,supports){const points=[];
+ for(let index=0;indexx1&&y2>y1)for(const x of [x1,x2])for(const y of [y1,y2])points.push([BigInt(2*(x-box.x)),BigInt(2*(y-box.y))])}
+ return convexHull(points)}
+function centreOfGravitySupported(box,supports){return pointInHull([BigInt(box.d[0]),BigInt(box.d[1])],contactHull(box,supports))}
+function hullCross(o,a,b){return (a[0]-o[0])*(b[1]-o[1])-(a[1]-o[1])*(b[0]-o[0])}
+// Andrew's monotone chain, counter-clockwise with duplicates collapsed. The points come four
+// to an overlap rectangle of positive area, so the hull is empty or has at least three
+// vertices: support_polygon.py's degenerate one- and two-point cases cannot arise here.
+function convexHull(points){const sorted=points.slice().sort((a,b)=>a[0]b[0]?1:a[1]b[1]?1:0),pts=[];
+ for(const point of sorted)if(pts.length===0||pts[pts.length-1][0]!==point[0]||pts[pts.length-1][1]!==point[1])pts.push(point);
+ const chain=order=>{const out=[];for(const point of order){while(out.length>=2&&hullCross(out[out.length-2],out[out.length-1],point)<=0n)out.pop();out.push(point)}return out.slice(0,-1)};
+ return [...chain(pts),...chain(pts.slice().reverse())]}
+function pointInHull(point,hull){return hull.length>0&&hull.every((vertex,index)=>hullCross(vertex,hull[(index+1)%hull.length],point)>=0n)}
+export function __centreOfGravitySupportedForTests(box,supporters){return centreOfGravitySupported(box,supporters.map(placement=>({placement})))}
function requiredArea(baseArea,ratioPpm){const whole=Math.floor(baseArea/SUPPORT_SCALE),rest=baseArea%SUPPORT_SCALE;return whole*ratioPpm+Math.floor(rest*ratioPpm/SUPPORT_SCALE)}
// Weight borne by each box once everything above it is accounted for. Boxes are settled
@@ -1435,6 +1472,7 @@ function constraintBox(placement){return {x:placement.x,y:placement.y,z:placemen
// the numerator the pressure model needs, so the crush check rides the graph that is built
// anyway rather than a second one.
maxCompressionKpa:placement.item.maxCompressionKpa,compressionPpm:placement.item.compressionPpm,
+ ...(placement.item.maxCompressionKpa==null||placement.pd==null?{}:{footprint:BigInt(placement.pd[0])*BigInt(placement.pd[1])}),
stopIndex:placement.item.stopIndex}}
// Ties between equal scores fall to enumeration order unless a solver ranks them further.
@@ -1525,6 +1563,18 @@ function groundContactAllowed(candidate,placed,supports=null){const rule=candida
const box={x:candidate.x,y:candidate.y,z:candidate.z,d:placementDimensions(candidate)},supporters=supports??directSupporters(candidate,placed);
if(rule==='single')return supporters.length===1;if(rule==='multiple')return supporters.length>=2;
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;
+ if(scene===null)scene=[...placed,candidate];
+ if(directSupporters(other,scene).length!==1)return false;
+ }
+ return true;
+}
function routeContactAllowed(candidate,placed,supports,sweep=null){
// An item without a declared stop rides the whole route. Infinity is the shared
// PHP/Python/Rust contract. Check only the new relations, as the existing scene was
@@ -1744,6 +1794,9 @@ function allowed(candidate,placed,container,globalSupportPpm,metrics,loadBase=nu
if(box.z!==0&&ratio>0){
const area=supports.reduce((total,support)=>total+support.area,0);
if(areacompareCodePoints(left,right));
return JSON.stringify([plan.remaining.map(i=>i.id),inventory]);
}
-function compareScore(left,right){for(let i=0;ib)return 1}return 0}
function uniqueRotations(dimensions,rotations){
const seen=new Set(),choices=[];
@@ -1806,7 +1860,7 @@ function uniqueRotations(dimensions,rotations){
}
function latticeCentreOfMassOffsetPpm(summary,inner){
- if(summary.weight===0||summary.count===0)return 0;
+ if(summary.weight===0n||summary.count===0)return 0;
const perLayer=summary.nx*summary.ny,fullLayers=Math.floor(summary.count/perLayer),remainder=summary.count%perLayer;
const rows=Math.floor(remainder/summary.nx),columns=remainder%summary.nx,triangular=n=>BigInt(n)*BigInt(n-1)/2n;
const sumX=BigInt(fullLayers*summary.ny+rows)*triangular(summary.nx)+triangular(columns);
@@ -1960,9 +2014,9 @@ 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'
- ?dimensionalWeight(a.outerD)-dimensionalWeight(b.outerD)||(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))
:(a.cost_minor??0)-(b.cost_minor??0)||Number(volume(a.d)-volume(b.d)));
- let remaining=quantity,scoreCost=0,scoreUnused=0,scoreHeight=0,scoreBillable=0,scoreLanded=0,scoreAchievedHeight=0;
+ 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
// whole solve, so it is computed once per template rather than recomputed on
@@ -1992,7 +2046,7 @@ function compactGridResult(req,{measures,u,ou,ow,clear,objective,dimensionalWeig
}
let capacity=Math.min(Number.MAX_SAFE_INTEGER,nx*ny*nz);
if(template.max_items!=null)capacity=Math.min(capacity,template.max_items);
- if(template.max!=null&&weight>0)capacity=Math.min(capacity,Math.floor(template.max/weight));
+ if(template.max!=null&&weight>0n)capacity=Math.min(capacity,Number(template.max/weight));
// Among rotations that hold the same number, prefer the one that needs
// fewer layers for the items actually being placed -- a lower centre of load is
// the objective's fifth key, and ranking rotations by capacity alone left it to
@@ -2079,7 +2133,7 @@ function compactGridResult(req,{measures,u,ou,ow,clear,objective,dimensionalWeig
cut=count0;i--){const j=next()%(i+1);[ordered[i],ordered[j]]=[ordered[j],ordered[i]]}
return ordered
}
-// A portfolio's reported effort is what the whole portfolio spent, not what its winner
-// spent. Each run here is a separate `packFallback` call with its own metrics closure, so
-// without this the record understates the work by the number of runs.
-// The counters each effort limit caps, as a frame's effort ceilings read them.
-const EFFORT_COUNTERS=[['max_search_nodes','search_nodes_expanded'],['max_candidates_evaluated','feasible_candidates'],['max_placement_attempts','orientations_considered']];
-/** What the request's effort budget leaves after `runs`; a spent limit is 0.
- *
- * The budget belongs to the request, not to each start: Python, PHP and Rust share it across
- * the portfolio, so a later start gets only what the earlier ones left, and one left with
- * nothing still starts and stops at its first counted step, as in Python. Each start used to
- * get the whole budget, which went unseen while `balanced` ran one ordering. O(r). */
-function remainingEffort(effort,runs){
- const left={...effort};
- for(const [limit,counter] of EFFORT_COUNTERS)
- if(effort[limit]!=null)left[limit]=Math.max(0,effort[limit]-runs.reduce((total,run)=>total+run.algorithm.metrics[counter],0));
- return left
-}
-const withEffort=(request,effort)=>effort==null?request:{...request,configuration:{...(request.configuration??{}),effort_budget:effort}};
-function withPortfolioEffort(winner,runs){
- const metrics={};
- for(const key of Object.keys(winner.algorithm.metrics))
- metrics[key]=runs.reduce((total,run)=>total+run.algorithm.metrics[key],0);
- return {...winner.algorithm,metrics,
- candidates_evaluated:runs.reduce((total,run)=>total+run.algorithm.candidates_evaluated,0),
- placements_attempted:runs.reduce((total,run)=>total+run.algorithm.placements_attempted,0)}
-}
// What a start adds to its solver's name: nothing for the first ordering, its index for a
// later one, and the swapped position for a neighbour run in a start a repeat freed.
function startSuffix(index,swapAt=null){
@@ -2416,6 +2444,7 @@ const MEASURES=Object.freeze({length:{units:LEN,parse:(value,unit)=>scalar(value
* `code` (unsupported feature, policy, fixed placement, direction) passes through unchanged.
*/
export function packFallback(req,clock=monotonicNow,solverAlias=null,startIndex=null,sharedDeadline=null){
+ const started=clock();
if(!isObject(req))throw new InvalidRequestError('wrong_type','','must be an object');
rejectUnsupported(req);
const filling=requestMeasures();
@@ -2427,9 +2456,53 @@ export function packFallback(req,clock=monotonicNow,solverAlias=null,startIndex=
const bound=requestBound(req,measures);
const result=solveChecked(req,clock,solverAlias,startIndex,sharedDeadline,measures);
warnUnsupportedPlacements(result,req.configuration?.minimum_support_ratio??0);
+ validateResultGroups(result,req.items);
stateOptimality(result,bound);
+ reportDuration(result,Math.max(0,Math.floor(clock()-started)));
return result;
}
+// `algorithm.duration_ms` is the wall-clock milliseconds the pack took, as every engine reports
+// it, on the clock the deadline reads; it was a constant 0 here. It is the one field
+// a determinism comparison masks, so nothing the answer is judged by reads it.
+function reportDuration(result,durationMs){
+ for(const answer of [result,...(result.alternatives??[])])if(answer.algorithm!=null)answer.algorithm.duration_ms=durationMs;
+}
+// Fixed containers are filled before fresh ones. A group's free members can therefore
+// survive their anchored container's trial and be packed elsewhere, or left behind.
+// Check the returned accounting without replaying geometry or expanding quantities:
+// O(t + p) time per result, O(t + g) space for t item types, p placements and g groups.
+function validateResultGroups(result,items){
+ const byType=new Map(),expected=new Map();
+ for(const item of items){
+ if(item.group==null)continue;
+ byType.set(item.id,item.group);
+ expected.set(item.group,(expected.get(item.group)??0)+(item.quantity??1));
+ }
+ if(expected.size===0)return;
+ const check=answer=>{
+ const groups=new Map();
+ for(const container of answer.containers)for(const placement of container.placements??[]){
+ if(!byType.has(placement.item_type))continue;
+ const group=byType.get(placement.item_type);
+ let state=groups.get(group);
+ if(state===undefined){state={count:0,first:container.id,other:null};groups.set(group,state)}
+ state.count++;
+ if(state.first!==container.id&&state.other===null)state.other=container.id;
+ }
+ const warnings=[];
+ for(const [group,state] of groups)if(state.other!==null)
+ warnings.push(`group_split: ${group}: ${state.first}, ${state.other}`);
+ for(const [group,state] of groups)if(state.counttotal+(item.quanti
if(requestedSolvers.includes('exact_small')&&requestedItemCount>exactItemLimit)throw new RangeError('exact-small item limit exceeded');
const effort=req.configuration?.effort_budget??null;
// A null limit is an absent one, as in every other engine (docs/ERRORS.md).
-// Only the request's own budget is checked: a start inside the portfolio may be handed a
-// spent limit of 0 by `remainingEffort`.
+// Every start of the portfolio gets the request's whole budget with its own counters, as in
+// Python, PHP and Rust; the budget is checked once, at the outermost frame.
if(sharedDeadline===null)for(const [name,value] of Object.entries(effort??{}))if(value!=null&&(!Number.isSafeInteger(value)||value<=0))throw new RangeError(`effort_budget.${name} must be a positive safe integer`);
const requestedOrders=req.configuration?.multi_start_orders??8;
if(!Number.isSafeInteger(requestedOrders)||requestedOrders<1)throw new RangeError('multi_start_orders must be a positive safe integer');
@@ -2517,16 +2590,15 @@ const addsBlockStart=solverAlias===null&&startIndex===null&&requestedSolvers.len
&&restartLimit>multiStartOrders&&new Set((req.items??[]).map(item=>item.id)).size>1;
// The start is there to improve an answer, not to replace an equal one: a lattice knows
// nothing of the ordering the profile's own starts honour, so on a tie or worse its
-// packing is dropped and only the record that it ran, and what it spent, is kept. A start
+// packing is dropped and only the record that it ran is kept. A start
// the deadline left no time for is recorded as never started, like any other restart.
const withAddedBlockStart=own=>{
- const late=deadline.expired(),left=effort==null?null:remainingEffort(effort,[own]);
- const blocks=solveFrame(withEffort({...req,configuration:{...(req.configuration??{}),multi_start_orders:1}},left),clock,'homogeneous_blocks',null,deadline,measures,phase,true);
+ const late=deadline.expired();
+ const blocks=solveFrame({...req,configuration:{...(req.configuration??{}),multi_start_orders:1}},clock,'homogeneous_blocks',null,deadline,measures,phase,true);
if(blocks===null)return own;
const runs=late?[own]:[own,blocks],winnerIndex=!late&&compareScore(blocks.score,own.score)<0?1:0,winner=runs[winnerIndex],globalDeadlineReached=deadline.expired();
const starts=portfolioStarts(runs,winnerIndex,globalDeadlineReached);if(late)starts.push(unstartedRecord('homogeneous_blocks',0,globalDeadlineReached));
winner.termination=aggregateTermination(starts);
- winner.algorithm=withPortfolioEffort(winner,runs);
if(winner.algorithm.effort_limit_reached&&!winner.algorithm.time_limit_reached&&!globalDeadlineReached)winner.termination.code='effort_limit';
// The profile's own answer is a real alternative to a winning lattice, as a losing
// solver's is in the quality portfolio; the sentinel never is (review).
@@ -2559,8 +2631,7 @@ if(solverAlias===null&&requestedSolvers.length){
const runs=[];
for(const plan of plans){
if(runs.length&&deadline.expired())break;
- const left=effort==null?null:remainingEffort(effort,runs);
- const childRequest=withEffort({...req,configuration:{...(req.configuration??{}),solvers:[],multi_start_orders:plan.count}},left);
+ const childRequest={...req,configuration:{...(req.configuration??{}),solvers:[],multi_start_orders:plan.count}};
runs.push(solveFrame(childRequest,clock,plan.name,null,deadline,measures,phase));
}
let winnerIndex=0;for(let index=1;index1){
const stagedPlanSearch=profile==='quality'&&(req.configuration?.container_plan_beam_width??16)>1;
const child=stagedPlanSearch?{...req,configuration:{...(req.configuration??{}),max_candidates_per_item:1,container_plan_beam_width:1,container_plan_node_limit:1}}:req;
const runStart=(request,index,startOrder,label)=>{
- const left=effort==null?null:remainingEffort(effort,runs);
- const run=solveFrame(withEffort(request,left),clock,solverAlias,index,deadline,measures,phase,false,startOrder);
+ const run=solveFrame(request,clock,solverAlias,index,deadline,measures,phase,false,startOrder);
if(run!==null){runs.push(run);labels.push(label)}
return run!==null};
// Instances of one item are interchangeable, so a start whose item-type sequence an earlier
@@ -2601,8 +2670,14 @@ if(startIndex===null&&multiStartOrders>1){
ownStarts.push({index:reached,sequence:startOrder.sequence,swappable:startOrder.swappable});
}
const freed=reached-runs.length;
+ // The beam refines the best greedy answer's order, ranked as the portfolio ranks (score,
+ // then the earlier start), as Python, PHP and Rust do; starts 0 and 1 used to be
+ // refined whatever they scored, so a full-width beam could start from the weakest order.
let refined=0;
- if(stagedPlanSearch)for(;refined<2;refined++){if(deadline.expired())break;runStart(req,refined,null,{index:plannedStarts+refined,swapAt:null})}
+ if(stagedPlanSearch&&runs.length&&!deadline.expired()){
+ let best=0;for(let index=1;index1){
global_deadline_reached:run.termination.starts[0].global_deadline_reached||globalDeadlineReached,
}));
for(let index=reached;indexNumber(volume(d)*BigInt(WT[dimWeightUnit])/(BigInt(LEN[dimLengthUnit])**3n*BigInt(dimDivisor??1)));
+const dimensionalWeight=d=>volume(d)*BigInt(WT[dimWeightUnit])/(BigInt(LEN[dimLengthUnit])**3n*BigInt(dimDivisor??1));
// A flat bag is billed on the package its placements make, which only grows as items
// are added, so the current extent is also a lower bound for any completion; an empty bag has
// no parcel yet and bills nothing by volume. O(p).
const billedDimensionalWeight=(tmpl,placements)=>!tmpl.bag?dimensionalWeight(tmpl.outerD)
- :placements.length?dimensionalWeight(bagExtent(placements)):0;
+ :placements.length?dimensionalWeight(bagExtent(placements)):0n;
const globalSupportRatio=req.configuration?.minimum_support_ratio??0;
const globalSupportPpm=supportPpm(globalSupportRatio);
const maxCandidatePoints=req.configuration?.max_candidate_points??4096;
@@ -2757,7 +2831,7 @@ items.sort((a,b)=>{
// The layer start keeps its own key in every profile, as Python's and Rust's
// order-insensitive layer solvers do. Under `quality` it used to take the small-first
// ordering every other start there takes, so no start tried large items first.
- if(solverAlias==='layer')return (b.basea.base?1:0)||ascendingVolume(b,a)||(b.w-a.w)||compareId(a.id,b.id);
+ if(solverAlias==='layer')return (b.basea.base?1:0)||ascendingVolume(b,a)||compareWeights(b.w,a.w)||compareId(a.id,b.id);
if(smallFirstStart===0)return a.longest-b.longest||ascendingVolume(a,b)||compareId(a.id,b.id);
if(smallFirstStart===1)return ascendingVolume(a,b)||a.longest-b.longest||compareId(a.id,b.id);
if(solverAlias==='maximal_spaces')return (b.longest-a.longest)||ascendingVolume(b,a)||compareId(a.id,b.id);
@@ -2767,7 +2841,7 @@ items.sort((a,b)=>{
// pack everything and the bound never pruned.
// Equal volumes tie on the longest edge, then the heavier item, as Python's `volume`
// order does; an id tie-break let a name decide which item took the last floor cell.
- return ascendingVolume(b,a)||(b.longest-a.longest)||(b.w-a.w)||compareId(a.id,b.id);
+ return ascendingVolume(b,a)||(b.longest-a.longest)||compareWeights(b.w,a.w)||compareId(a.id,b.id);
});
// Start 0 is the ordering above, so a single-start request is byte-identical to what it
// produced before restarts existed; every later start re-solves a plain shuffle of it, as
@@ -2801,7 +2875,7 @@ const templates=req.containers.map(c=>{const d=measures.sides(c.inner_dimensions
return {...c,d,outerD,doors,bag:c.deformable_boundary!=null,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'?(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))):((a.cost_minor??0)-(b.cost_minor??0)||Number(volume(a.d)-volume(b.d))));
// 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});
@@ -2813,7 +2887,7 @@ const inventory=new Map(templates.map(c=>[c.id,c.quantity??Infinity])),remaining
// A fresh per-container search state: candidate points, spatial index and running volume,
// with the template's fixed items (`tmpl.fixed`, set only on a seeded copy) already placed
// exactly as search would place them, so every solver starts from them unaware they exist.
-const seedState=tmpl=>{const node={state:{tmpl,placements:[],payload:0},used:0n,
+const seedState=tmpl=>{const node={state:{tmpl,placements:[],payload:0n},used:0n,
points:[[0,0,0],...tmpl.obs.flatMap(o=>[[o.x+o.d[0],o.y,o.z],[o.x,o.y+o.d[1],o.z],[o.x,o.y,o.z+o.d[2]]])].sort(comparePoints),
index:makeIndex(tmpl.d)};
for(const placement of tmpl.fixed??[]){const placements=node.state.placements;node.state.payload+=placement.item.w;
@@ -3069,7 +3143,7 @@ const packBeamIntoTemplate=(tmpl,itemsRemaining)=>{
// declaring the whole crate both fit in it.
const lowerBound=(node,future,cumulativeVolumes=null,cumulativeWeights=null)=>{let possible=future.length;
if(!future.some(item=>item.nesting!=null))possible=Math.min(possible,maxCount(cumulativeVolumes??cumulativeCosts(future.map(itemOccupiedVolume)),volume(tmpl.d)-node.used));
- if(tmpl.max!=null)possible=Math.min(possible,maxCount(cumulativeWeights??cumulativeCosts(future.map(item=>BigInt(item.w))),BigInt(Math.max(0,tmpl.max-node.state.payload))));
+ if(tmpl.max!=null)possible=Math.min(possible,maxCount(cumulativeWeights??cumulativeCosts(future.map(item=>BigInt(item.w))),heavier(0n,tmpl.max-node.state.payload)));
return node.unplaced.length+future.length-possible};
// Compared states are complete; placement always mutates a fresh clone first.
// Weak keys let discarded branches release their cached strings with their state.
@@ -3223,8 +3297,8 @@ const packExactIntoTemplate=(tmpl,itemsRemaining)=>{
for(const itemVolume of volumes){if(work.used+smallestVolumeSum+itemVolume>containerVolume)break;smallestVolumeSum+=itemVolume;placeable++}
}
if(tmpl.max!=null){
- const weights=future.map(item=>profiles.get(item.id).weight).sort((a,b)=>a-b);
- let count=0,total=0;const capacity=Math.max(0,tmpl.max-work.state.payload);
+ const weights=future.map(item=>profiles.get(item.id).weight).sort(compareWeights);
+ let count=0,total=0n;const capacity=heavier(0n,tmpl.max-work.state.payload);
for(const weight of weights){if(total+weight>capacity)break;total+=weight;count++}
placeable=Math.min(placeable,count);
}
@@ -3247,9 +3321,9 @@ const packExactIntoTemplate=(tmpl,itemsRemaining)=>{
}
if(placeable===future.length)minimumHeight=Math.max(minimumHeight,...future.map(item=>profiles.get(item.id).minimumHeight));
const height=tmpl.d[2]>0?Math.floor(minimumHeight*1000000/tmpl.d[2]):0;
- const weights=future.map(item=>profiles.get(item.id).weight).sort((a,b)=>a-b);
+ const weights=future.map(item=>profiles.get(item.id).weight).sort(compareWeights);
const grossWeight=weights.slice(0,placeable).reduce((sum,value)=>sum+value,work.state.payload+tmpl.tare);
- const billable=objective==='shipping_cost'||objective==='lowest_landed_cost'?Math.max(grossWeight,billedDimensionalWeight(tmpl,work.state.placements)):0;
+ const billable=objective==='shipping_cost'||objective==='lowest_landed_cost'?heavier(grossWeight,billedDimensionalWeight(tmpl,work.state.placements)):0n;
// A promotional bracket may be cheaper than a lighter bracket, so pricing the
// lightest possible completion is not an admissible lower bound. Tariff charges are
// non-negative; zero is the general money floor and only loosens this exact search.
@@ -3317,7 +3391,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:0},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(),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});
@@ -3335,7 +3409,7 @@ const blockLeading=(round,volumeFirst,leaders,nodeLimit,counter)=>{if(effortStop
for(let slot=0;slot0)capacity=Math.min(capacity,Math.floor(Math.max(0,tmpl.max-state.payload)/prototype.w));
+ if(tmpl.max!=null&&prototype.w>0n)capacity=Math.min(capacity,Number(heavier(0n,tmpl.max-state.payload)/prototype.w));
if(capacity<=0)continue;
if(!lattices.has(itemId))lattices.set(itemId,blockLattices(prototype));
const typeLattices=lattices.get(itemId);let minimumX=Infinity,minimumY=Infinity;
@@ -3421,7 +3495,7 @@ const packBlocksIntoTemplate=(tmpl,itemsRemaining)=>{if(!homogeneousBlocksSuppor
if(bestKey==null)bestKey=blockModeKey(best);
const key=blockModeKey(candidate),order=compareBlockKey(key,bestKey);
if(order<0||order===0&&compareCodePoints(blockModeSignature(candidate),blockModeSignature(best))<0){best=candidate;bestKey=key}}
- return best??{state:{tmpl,placements:[],payload:0},next:itemsRemaining.slice()}}
+ return best??{state:{tmpl,placements:[],payload:0n},next:itemsRemaining.slice()}}
// The added start runs only where the lattice can express the whole request -- a start
// that fell back to the per-item search would repeat one the profile already ran -- and
// only where every item leads the ordering alike: a lattice takes whichever type fills
@@ -3432,11 +3506,11 @@ const packBlocksIntoTemplate=(tmpl,itemsRemaining)=>{if(!homogeneousBlocksSuppor
if(addedBlockStart&&!(homogeneousBlocksSupported()&&globalSupportPpm===0
&&items.every(i=>i.shapeType==='rigid_cuboid'&&i.priority===items[0].priority&&(objective!=='maximum_value'||i.value===items[0].value))))return null;
const packIntoTemplate=solverAlias==='exact_small'?packExactIntoTemplate:solverAlias==='homogeneous_blocks'?packBlocksIntoTemplate:containerPlanBeamWidth>1?packBeamIntoTemplate:tryPackIntoTemplate;
-const planScore=(plan,unpacked=plan.remaining)=>{let cost=0,unused=0,height=0,billable=0,landed=0,achieved=0;
+const planScore=(plan,unpacked=plan.remaining)=>{let cost=0,unused=0,height=0,billable=0n,landed=0,achieved=0;
for(const state of plan.packed){cost+=state.tmpl.cost_minor??0;const inner=volume(state.tmpl.d),used=usedVolume(state.placements);unused+=Number((inner-used)*1000000n/inner);
const top=state.placements.reduce((z,p)=>Math.max(z,p.z+p.ed[2]),0);height+=Number(BigInt(top)*1000000n/BigInt(state.tmpl.d[2]));achieved+=top;
if(objective==='shipping_cost'||objective==='lowest_landed_cost'){
- const billed=Math.max(state.payload+state.tmpl.tare,billedDimensionalWeight(state.tmpl,state.placements));
+ const billed=heavier(state.payload+state.tmpl.tare,billedDimensionalWeight(state.tmpl,state.placements));
if(objective==='shipping_cost')billable+=billed;else landed=addLanded(landed,state.tmpl,billed)}}
const base=[unpacked.length,plan.packed.length,cost,unused,height];
if(objective==='lowest_cost')return [base[0],base[2],base[1],base[3],base[4]];
@@ -3460,8 +3534,11 @@ const planBound=(plan)=>{const key=planScore(plan,[]),index=objective==='default
// sentinel. Otherwise the round's lead is its progress: pieces placed, or exact (BigInt) volume
// placed under `maximum_volume`; both sides of a comparison always carry the same type.
const roundScore=(trial,itemsRemaining)=>{const tmpl=trial.state.tmpl,placed=trial.state.placements.length;
+ if(objective==='shipping_cost'){
+ const billed=heavier(trial.state.payload+tmpl.tare,billedDimensionalWeight(tmpl,trial.state.placements));
+ return [-placed,billed,tmpl.id]}
if(objective==='lowest_landed_cost'){
- const billed=Math.max(trial.state.payload+tmpl.tare,billedDimensionalWeight(tmpl,trial.state.placements));
+ const billed=heavier(trial.state.payload+tmpl.tare,billedDimensionalWeight(tmpl,trial.state.placements));
return [addLanded(0,tmpl,billed),Math.ceil(itemsRemaining.length/Math.max(placed,1)),-placed,tmpl.id]}
if(solverAlias==='exact_small')return [...planScore({packed:[trial.state],remaining:trial.next}),tmpl.id];
const used=usedVolume(trial.state.placements);
@@ -3501,9 +3578,13 @@ for(const group of fixedGroups){const seeded={...group.tmpl,fixed:group.placemen
if(trial!==null)remaining.splice(0,remaining.length,...trial.next)}
if(containerPlanBeamWidth>1&&solverAlias!=='exact_small'){
const initial={packed:packed.slice(),remaining:remaining.slice(),inventory:new Map(inventory),seq};let beam=fixedReached?[]:[initial],incumbent=initial,planNodes=0;
- while(beam.length&&planNodes=maxContainers){if(compareScore(planScore(plan),planScore(incumbent))<0)incumbent=plan;continue}
- for(const tmpl of templates){if(planNodes>=containerPlanNodeLimit)break;if(deadline.expired()||effortStopped){exhausted=true;break}if(plan.inventory.get(tmpl.id)<=0)continue;
+ for(const tmpl of templates){if(planNodes>=planNodeLimit)break;if(deadline.expired()||effortStopped){exhausted=true;break}if(plan.inventory.get(tmpl.id)<=0)continue;
// Each rung is one single-container solve, so the node limit keeps bounding the work
// of a made-to-measure chain.
const {trial,trials}=trialFor(tmpl,plan.remaining);planNodes+=trials;if(!trial.state.placements.length)continue;const nextInventory=new Map(plan.inventory);nextInventory.set(tmpl.id,nextInventory.get(tmpl.id)-1);
@@ -3583,7 +3664,7 @@ const unpacked=remaining.map(i=>{
// Canonical objective vector — see docs/OBJECTIVE.md. Five lexicographic keys,
// ascending, lower is better. Ratios are floored per container in BigInt at
// parts-per-million scale so Python, PHP, Rust and this fallback agree exactly.
-const SCORE_SCALE=1000000n;let scoreCost=0,scoreUnused=0,scoreHeight=0,scoreBillable=0,scoreLanded=0,scoreAchievedHeight=0;
+const SCORE_SCALE=1000000n;let scoreCost=0,scoreUnused=0,scoreHeight=0,scoreBillable=0n,scoreLanded=0,scoreAchievedHeight=0;
for(const c of packed){scoreCost+=c.tmpl.cost_minor??0;
const inner=volume(c.tmpl.d),used=usedVolume(c.placements);
if(inner>0n)scoreUnused+=Number((inner-used)*SCORE_SCALE/inner);
@@ -3591,7 +3672,7 @@ for(const c of packed){scoreCost+=c.tmpl.cost_minor??0;
scoreAchievedHeight+=top;
if(innerHeight>0n)scoreHeight+=Number(BigInt(top)*SCORE_SCALE/innerHeight);
if(objective==='shipping_cost'||objective==='lowest_landed_cost'){
- const billed=Math.max(c.payload+c.tmpl.tare,billedDimensionalWeight(c.tmpl,c.placements));
+ const billed=heavier(c.payload+c.tmpl.tare,billedDimensionalWeight(c.tmpl,c.placements));
if(objective==='shipping_cost')scoreBillable+=billed;else scoreLanded=addLanded(scoreLanded,c.tmpl,billed);}}
// The search ranks an unpriceable packing worst so that any priceable alternative beats
// it; reaching here means none existed in this run. Returning such a packing would
@@ -3603,7 +3684,7 @@ for(const c of packed){scoreCost+=c.tmpl.cost_minor??0;
// below, a search device that never serializes.
let unpriceableDetail=null;
if(objective==='lowest_landed_cost')for(const c of packed){
- const grams=billedGrams(Math.max(c.payload+c.tmpl.tare,billedDimensionalWeight(c.tmpl,c.placements))),table=c.tmpl.rate;
+ const grams=billedGrams(heavier(c.payload+c.tmpl.tare,billedDimensionalWeight(c.tmpl,c.placements))),table=c.tmpl.rate;
if(table!=null&&chargeMinor(table,grams)!=null)continue;
// A missing table is already refused at admission, so `0` here is unreachable rather
// than a real bound -- but reading a bracket off `null` would replace the refusal
@@ -3616,7 +3697,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],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],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)}
@@ -3691,7 +3772,7 @@ function rebalanceContext(req,result){
function rebalanceValid(context,result){
const expected=new Set(context.items.keys()),seen=new Set(),groups=new Map();
for(const state of context.states){
- let payload=0;
+ let payload=0n;
const tagCounts=new Map();
for(let index=0;index(state.tmpl.tags??[]).includes(tag)))return false;
for(const tag of placement.item.tags)tagCounts.set(tag,(tagCounts.get(tag)??0)+1);
- const box={x:placement.x,y:placement.y,z:placement.z,d:placement.ed};
+ const box={x:placement.x,y:placement.y,z:placement.z,d:placement.ed},shape=placedHull(placement);
if(box.x<0||box.y<0||box.z<0||box.x+box.d[0]>state.tmpl.d[0]||box.y+box.d[1]>state.tmpl.d[1]||box.z+box.d[2]>state.tmpl.d[2])return false;
- if(state.tmpl.obs.some(obstacle=>intersects(box,obstacle)))return false;
+ if(state.tmpl.obs.some(obstacle=>intersects(box,obstacle)&&solidsOverlap(shape,box,null,obstacle)))return false;
for(const other of state.placements.slice(index+1)){
- if(intersects(box,{x:other.x,y:other.y,z:other.z,d:other.ed})&&!validNesting(placement,other))return false
+ if(intersects(box,{x:other.x,y:other.y,z:other.z,d:other.ed})&&!validNesting(placement,other)&&solidsOverlapAt(shape,box.x,box.y,box.z,box.d,other))return false
}
}
if(state.tmpl.max!=null&&payload>state.tmpl.max)return false;
@@ -3749,7 +3830,7 @@ function publicRebalancedContainers(req,context){
const outputLength=req.output?.length_unit??outputLengthUnit(req.units?.length??'mm'),outputWeight=req.output?.weight_unit??'g';
return context.states.map(state=>{
const loads=topLoads(state.placements.map(constraintBox));
- const payload=state.placements.reduce((total,placement)=>total+placement.item.w,0);
+ const payload=state.placements.reduce((total,placement)=>total+placement.item.w,0n);
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(),
@@ -3792,7 +3873,7 @@ export function rebalanceWeight(req,result,{maxMoves=64}={}){
let statesPriceable=null;
if(objective==='lowest_landed_cost'){
const lengthUnit=req.configuration?.dimensional_weight_length_unit??'in',weightUnit=req.configuration?.dimensional_weight_weight_unit??'lb';
- const dimensionalTicks=d=>Number(volume(d)*BigInt(WT[weightUnit])/(BigInt(LEN[lengthUnit])**3n*BigInt(dimDivisor)));
+ const dimensionalTicks=d=>volume(d)*BigInt(WT[weightUnit])/(BigInt(LEN[lengthUnit])**3n*BigInt(dimDivisor));
// rebalanceContext keeps the raw rate_table; parse it once per container type with
// the packer's own parser so both entry points refuse the same malformed tariffs.
const pricing=new Map();
@@ -3801,8 +3882,8 @@ export function rebalanceWeight(req,result,{maxMoves=64}={}){
if(entry===undefined){entry={rate:parseRateTable(tmpl.rate_table),dimTicks:dimensionalTicks(tmpl.outerD)};pricing.set(tmpl.id,entry)}
return entry};
const unpriceableState=state=>{
- const entry=priceEntry(state.tmpl),payload=state.placements.reduce((total,placement)=>total+placement.item.w,0);
- const grams=billedGrams(Math.max(payload+state.tmpl.tare,entry.dimTicks));
+ const entry=priceEntry(state.tmpl),payload=state.placements.reduce((total,placement)=>total+placement.item.w,0n);
+ const grams=billedGrams(heavier(payload+state.tmpl.tare,entry.dimTicks));
if(entry.rate!=null&&chargeMinor(entry.rate,grams)!=null)return null;
return {id:state.tmpl.id,grams,bound:entry.rate==null?0:entry.rate.brackets[entry.rate.brackets.length-1]}};
statesPriceable=()=>context.states.every(state=>unpriceableState(state)==null);
@@ -3810,12 +3891,12 @@ export function rebalanceWeight(req,result,{maxMoves=64}={}){
}
for(let moveNumber=0;moveNumberstate.placements.reduce((total,placement)=>total+placement.item.w,0));
- const spread=Math.max(...weights)-Math.min(...weights);if(spread<=0)break;
+ const weights=context.states.map(state=>state.placements.reduce((total,placement)=>total+placement.item.w,0n));
+ const spread=weights.reduce(heavier)-weights.reduce(lighter);if(spread<=0n)break;
const sourceIndex=weights.reduce((best,weight,index)=>weight>weights[best]?index:best,0);
const placements=context.states[sourceIndex].placements.map((_,index)=>index)
- .sort((a,b)=>context.states[sourceIndex].placements[b].item.w-context.states[sourceIndex].placements[a].item.w);
- const destinations=context.states.map((_,index)=>index).filter(index=>index!==sourceIndex).sort((a,b)=>weights[a]-weights[b]);
+ .sort((a,b)=>compareWeights(context.states[sourceIndex].placements[b].item.w,context.states[sourceIndex].placements[a].item.w)||a-b);
+ const destinations=context.states.map((_,index)=>index).filter(index=>index!==sourceIndex).sort((a,b)=>compareWeights(weights[a],weights[b])||a-b);
let committed=null;
search:for(const placementIndex of placements){
const moving=context.states[sourceIndex].placements[placementIndex],weight=moving.item.w;
@@ -3823,7 +3904,7 @@ export function rebalanceWeight(req,result,{maxMoves=64}={}){
if(moving.publicPlacement.fixed===true||weight<=0)continue;
for(const destinationIndex of destinations){
const projected=[...weights];projected[sourceIndex]-=weight;projected[destinationIndex]+=weight;
- if(Math.max(...projected)-Math.min(...projected)>=spread)continue;
+ 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);
@@ -3954,6 +4035,10 @@ export function verifyLoadingPrefixBusinessRules(placements,order,container){
// only when some item declares a list, and only on the new step's own edges, since every
// earlier edge was judged at its own step.
const grouped=placements.some(raw=>(raw.accepts_stacking_groups??[]).length>0);
+ const hasNonStackable=placements.some(raw=>raw.stackable===false);
+ const hasLoadRules=maxDensity!=null||grouped||hasNonStackable||placements.some(raw=>raw.max_top_load!=null||raw.max_stacked_items!=null);
+ const elevatedBases=new Set(),squareMetre=16000000n*16000000n;
+ let anyNesting=false;
order.forEach((index,step)=>{
const raw=placements[index],origin=raw.origin??{x:raw.x,y:raw.y,z:raw.z};
const dims=raw.dimensions??{length:raw.length,width:raw.width,height:raw.height};
@@ -3968,16 +4053,26 @@ export function verifyLoadingPrefixBusinessRules(placements,order,container){
stackable:raw.stackable??true,item:{groundRule:raw.ground_contact_rule??null},
stackingGroup:raw.stacking_group??null,accepts:acceptedStackingGroups(raw)};
present.push(box);
- const needsLoads=maxDensity!=null||present.some(candidate=>candidate.maxTop!=null),graph=contactGraph(present),loads=needsLoads?topLoads(present,graph):null;
- if(overloaded(present,loads))throw new SequenceReplayError(index,step,'top_load_exceeded');
- if(stackLimitsExceeded(present,graph))throw new SequenceReplayError(index,step,'stacked_item_limit_exceeded');
- if(maxDensity!=null&&stackDensityExceeded(present,maxDensity,loads))throw new SequenceReplayError(index,step,'stack_density_exceeded');
- const children=supportChildren(present,graph);
- if(present.some((b,i)=>b.stackable===false&&children[i].length>0))throw new SequenceReplayError(index,step,'non_stackable_item_has_load');
- if(grouped){const last=present.length-1;
- if(graph.supporters[last].some(([k])=>stackingRefusal(present[k],box)!==null)
- ||children[last].some(k=>stackingRefusal(box,present[k])!==null))
- throw new SequenceReplayError(index,step,'stacking_group_incompatible')}
+ if(box.z!==0)elevatedBases.add(box.z);
+ if(box.nesting!=null)anyNesting=true;
+ const isolatedFloorStep=box.z===0&&!anyNesting&&!elevatedBases.has(box.z+box.d[2]);
+ if(isolatedFloorStep){
+ if(maxDensity!=null&&BigInt(box.w)*squareMetre>BigInt(maxDensity)*BigInt(box.d[0])*BigInt(box.d[1]))
+ throw new SequenceReplayError(index,step,'stack_density_exceeded');
+ return;
+ }
+ if(hasLoadRules){
+ const needsLoads=maxDensity!=null||present.some(candidate=>candidate.maxTop!=null),graph=contactGraph(present),loads=needsLoads?topLoads(present,graph):null;
+ if(overloaded(present,loads))throw new SequenceReplayError(index,step,'top_load_exceeded');
+ if(stackLimitsExceeded(present,graph))throw new SequenceReplayError(index,step,'stacked_item_limit_exceeded');
+ if(maxDensity!=null&&stackDensityExceeded(present,maxDensity,loads))throw new SequenceReplayError(index,step,'stack_density_exceeded');
+ const children=(hasNonStackable||grouped)?supportChildren(present,graph):null;
+ if(hasNonStackable&&present.some((b,i)=>b.stackable===false&&children[i].length>0))throw new SequenceReplayError(index,step,'non_stackable_item_has_load');
+ if(grouped){const last=present.length-1;
+ if(graph.supporters[last].some(([k])=>stackingRefusal(present[k],box)!==null)
+ ||children[last].some(k=>stackingRefusal(box,present[k])!==null))
+ throw new SequenceReplayError(index,step,'stacking_group_incompatible')}
+ }
if(!groundContactAllowed(box,present.slice(0,-1)))throw new SequenceReplayError(index,step,'ground_contact_violation')
})
}
diff --git a/index.d.ts b/index.d.ts
index 2737f8e..5d690ca 100644
--- a/index.d.ts
+++ b/index.d.ts
@@ -58,6 +58,10 @@ export function explanationForUnpackedItem(item:UnpackedItemResult):ExplanationD
export function explainUnpackedItem(item:UnpackedItemResult):string;
export function pack(request:PackingRequest):PackingResult;
export function packJson(input:string):string;
+/** `JSON.stringify` that writes a `BigInt` (a weight's `ticks` past 2^53 - 1) as the integer it is. */
+export function stringifyExact(value:unknown):string;
+/** `JSON.parse` that reads a `ticks` past 2^53 - 1 as an exact `BigInt`. */
+export function parseExact(text:string):unknown;
export function rebalanceWeight(request:PackingRequest,result:PackingResult,options?:{maxMoves?:number}):RebalanceResult;
export function backend():"rust"|"javascript";
export function version():string;
diff --git a/index.js b/index.js
index f1511f2..cdedaff 100644
--- a/index.js
+++ b/index.js
@@ -19,8 +19,10 @@ export {
export { FixedPlacementError, InvalidRequestError, UnsupportedFeatureError };
import * as commerceFallback from './commerce.js';
export { CommerceInputError } from './commerce.js';
+export { parseExact, stringifyExact } from './exact-json.js';
import { SUITE_VERSION } from './artifacts.js';
import { validateDocuments } from './result-validation/index.js';
+import { parseExact, stringifyExact } from './exact-json.js';
const require = createRequire(import.meta.url);
/** The largest `maxMoves` the addon's `u32` parameter holds; napi wraps anything above it. */
@@ -120,11 +122,13 @@ export function packJsonWith(binding, input) {
checkRequestShape(JSON.parse(input));
return answered(() => binding.packJson(input));
}
- return JSON.stringify(packFallback(JSON.parse(input)));
+ return stringifyExact(packFallback(JSON.parse(input)));
}
+// Through `exact-json`, so a weight's `ticks` past 2^53 - 1 arrives as an exact `BigInt` from
+// either backend, and a result holding one can be passed back in (R19-01).
export function pack(request) {
- return JSON.parse(packJson(JSON.stringify(request)));
+ return parseExact(packJson(stringifyExact(request)));
}
export function rebalanceWeight(request, result, options) {
@@ -143,12 +147,12 @@ export function rebalanceWeightWith(binding, request, result, { maxMoves = 64 }
throw new RangeError('maxMoves must be an integer from 0 to 4294967295');
}
if (binding?.rebalanceJson) {
- return JSON.parse(answered(() => binding.rebalanceJson(JSON.stringify(request), JSON.stringify(result), maxMoves)));
+ return parseExact(answered(() => binding.rebalanceJson(stringifyExact(request), stringifyExact(result), maxMoves)));
}
return rebalanceFallback(request, result, { maxMoves });
}
-export const version = () => native?.version?.() ?? '1.8.0-js-fallback';
+export const version = () => native?.version?.() ?? '1.9.0-js-fallback';
/**
* The result is not a document the reference validator can judge (docs/VALIDATION-CONTRACT.md):
@@ -193,7 +197,7 @@ export function validate(request, result) {
// binding without `validateJson` (or none) is answered by the JavaScript port.
export function validateWith(binding, request, result) {
const outcome = binding?.validateJson
- ? JSON.parse(binding.validateJson(JSON.stringify(request), JSON.stringify(result)))
+ ? JSON.parse(binding.validateJson(stringifyExact(request), stringifyExact(result)))
: validateDocuments(request, result);
if (outcome.refusal) {
throw new MalformedResult(outcome.refusal.message, outcome.refusal.kind);
diff --git a/made-to-measure.js b/made-to-measure.js
index 46afddd..b288b5c 100644
--- a/made-to-measure.js
+++ b/made-to-measure.js
@@ -90,6 +90,6 @@ export function fabricate(machine, maximum, achieved, fee, tare) {
sides,
outer: sides.map((side, axis) => side + machine.allowance[axis]),
cost: Number(BigInt(fee) + perSquareMetre(machine.price, area)),
- tare: Number(BigInt(tare) + perSquareMetre(machine.tarePerSquareMetre, area)),
+ tare: BigInt(tare) + perSquareMetre(machine.tarePerSquareMetre, area),
};
}
diff --git a/package.json b/package.json
index 66deec6..316ccdf 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name":"@packvium/engine",
- "version":"1.8.0",
+ "version":"1.9.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"],
@@ -11,7 +11,7 @@
"main":"index.js",
"types":"index.d.ts",
"exports":{".":{"types":"./index.d.ts","import":"./index.js"},"./execution.js":{"types":"./execution.d.ts","import":"./execution.js"},"./artifacts.js":{"types":"./artifacts.d.ts","import":"./artifacts.js"},"./artifact-exports.js":{"types":"./artifact-exports.d.ts","import":"./artifact-exports.js"},"./revisions.js":{"types":"./revisions.d.ts","import":"./revisions.js"},"./scene.js":{"types":"./scene.d.ts","import":"./scene.js"}},
- "files":["index.js","fallback.js","contact-graph.js","policy.js","commerce.js","commerce-model.js","execution.js","canonical-json.js","artifacts.js","artifact-exports.js","revisions.js","scene.js","request-errors.js","made-to-measure.js","result-validation","examples","index.d.ts","execution.d.ts","artifacts.d.ts","artifact-exports.d.ts","revisions.d.ts","scene.d.ts","README.md","SECURITY.md"],
+ "files":["index.js","fallback.js","contact-graph.js","policy.js","commerce.js","commerce-model.js","execution.js","canonical-json.js","artifacts.js","artifact-exports.js","revisions.js","scene.js","request-errors.js","made-to-measure.js","exact-json.js","result-validation","examples","index.d.ts","execution.d.ts","artifacts.d.ts","artifact-exports.d.ts","revisions.d.ts","scene.d.ts","README.md","SECURITY.md"],
"engines":{"node":">=16"},
"scripts":{
"test":"node test/run-tests.mjs",
diff --git a/request-errors.js b/request-errors.js
index ffd9f74..81ce57a 100644
--- a/request-errors.js
+++ b/request-errors.js
@@ -62,6 +62,18 @@ export function pointer(...parts) {
// ------------------------------------------------------------------------------ primitives
const MAX_EXACT_MAGNITUDE = Number.MAX_SAFE_INTEGER;
+/**
+ * The admission ceiling every engine refuses past: a length is a tick count
+ * every engine holds exactly, this one's `Number` included, and a box encloses no more than the
+ * bound path can sum, so `volume x 10^6` stays inside Rust's `i128`.
+ */
+const MAX_LENGTH_TICKS = MAX_EXACT_MAGNITUDE;
+const MAX_VOLUME_TICKS3 = 10n ** 30n;
+/**
+ * A weight, and every item's weight times its quantity plus the heaviest tare, fit a signed
+ * 64-bit integer, which is how Rust and PHP add a container's payload (R19-01).
+ */
+const MAX_WEIGHT_TICKS = 2n ** 63n - 1n;
const hasOwn = (value, key) => Object.prototype.hasOwnProperty.call(value, key);
const isObject = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
@@ -138,7 +150,7 @@ function requireMeasure(value, field, kind, unit) {
}
if (isObject(value)) requireMeasureObject(value, field, kind, unit);
try {
- kind.parse(value, unit);
+ return kind.parse(value, unit);
} catch (error) {
if (String(error?.message).includes('cannot be negative')) {
throw new InvalidRequestError('negative_measure', field, 'cannot be negative');
@@ -155,6 +167,52 @@ function requireMeasureObject(value, field, kind, unit) {
}
}
+/**
+ * A length at most `MAX_LENGTH_TICKS`. The parser rounds its exact `BigInt` ticks to a `Number`,
+ * and every count past 2^53 - 1 rounds to at least 2^53, so the comparison stays exact.
+ */
+function requireLength(ticks, field) {
+ if (ticks > MAX_LENGTH_TICKS) {
+ throw new InvalidRequestError('above_maximum', field, `must be at most ${MAX_LENGTH_TICKS} ticks`);
+ }
+ return ticks;
+}
+
+/**
+ * A weight: a measure past 2^53 - 1 is written as a string, because a JSON number that large
+ * reached this engine already rounded; its exact ticks are at most `MAX_WEIGHT_TICKS`.
+ */
+function requireWeight(value, field, kind) {
+ const amount = isObject(value) ? value.value : value;
+ if (typeof amount === 'number' && Number.isInteger(amount) && !Number.isSafeInteger(amount)
+ && (typeof value === 'number' || (isObject(value) && knownUnit(hasOwn(value, 'unit') ? value.unit : 'g', kind)))) {
+ if (amount < 0) throw new InvalidRequestError('negative_measure', field, 'cannot be negative');
+ throw new InvalidRequestError('invalid_value', field, `must be written as a string past ${MAX_EXACT_MAGNITUDE}`);
+ }
+ const ticks = requireMeasure(value, field, kind, 'g');
+ if (ticks > MAX_WEIGHT_TICKS) {
+ throw new InvalidRequestError('above_maximum', field, `must be at most ${MAX_WEIGHT_TICKS} ticks`);
+ }
+ return ticks;
+}
+
+/**
+ * Every item's weight times its quantity, plus the heaviest tare, against `MAX_WEIGHT_TICKS`:
+ * no container's gross weight can pass it. Each value was admitted above. O(items + containers).
+ */
+function requireTotalWeight(items, containers, weights) {
+ const ticks = (holder, name) => (holder[name] == null ? 0n : BigInt(weights.parse(holder[name], 'g')));
+ const total = items.reduce((sum, item) => sum + ticks(item, 'weight') * BigInt(item.quantity ?? 1),
+ containers.reduce((heaviest, container) => {
+ const tare = ticks(container, 'tare_weight');
+ return tare > heaviest ? tare : heaviest;
+ }, 0n));
+ if (total > MAX_WEIGHT_TICKS) {
+ throw new InvalidRequestError('above_maximum', '/items',
+ `must weigh at most ${MAX_WEIGHT_TICKS} ticks in all, with the heaviest tare`);
+ }
+}
+
const knownUnit = (unit, kind) => typeof unit === 'string' && hasOwn(kind.units, unit.trim().toLowerCase());
// ------------------------------------------------------------------------------ the rules
@@ -186,8 +244,8 @@ export function checkRequest(data, measures) {
const request = requireObject(data, '');
const unit = checkUnits(request.units, measures.length);
checkOutput(request.output);
- const length = (value, field) => requireMeasure(value, field, measures.length, unit);
- const weight = (value, field) => requireMeasure(value, field, measures.weight, 'g');
+ const length = (value, field) => requireLength(requireMeasure(value, field, measures.length, unit), field);
+ const weight = (value, field) => requireWeight(value, field, measures.weight);
checkConfiguration(request.configuration, length);
const items = requiredList(request, 'items', '');
const lengthTicks = (value) => measures.length.parse(value, unit);
@@ -196,6 +254,7 @@ export function checkRequest(data, measures) {
const containers = requiredList(request, 'containers', '');
containers.forEach((raw, index) => checkContainer(raw, pointer('containers', index), length, weight, lengthTicks));
requireUniqueIds(containers, 'containers');
+ requireTotalWeight(items, containers, measures.weight);
}
function checkUnits(raw, lengths) {
@@ -289,7 +348,8 @@ function checkContainer(raw, where, length, weight, lengthTicks) {
optional(container, 'access_directions', where, accessDirections);
optional(container, 'tag_limits', where, tagLimits);
optional(container, 'rate_table', where, rateTable);
- optional(container, 'obstacles', where, (v, f) => obstacles(v, f, length));
+ const inner = SIDES.map((side) => lengthTicks(container.inner_dimensions[side]));
+ optional(container, 'obstacles', where, (v, f) => obstacles(v, f, length, inner));
optional(container, 'deformable_boundary', where, (v, f) => deformableBoundary(container, v, f, where));
optional(container, 'made_to_measure', where, (v, f) => madeToMeasure(container, v, f, where, { length, weight, lengthTicks }));
}
@@ -306,7 +366,7 @@ function madeToMeasure(container, raw, field, where, { length, weight, lengthTic
const machine = requireObject(raw, field);
requireKnownFields(machine, field, MADE_TO_MEASURE_FIELDS);
for (const name of ['minimum', 'increment']) required(machine, name, field);
- for (const name of ['minimum', 'increment', 'outer_allowance']) optional(machine, name, field, (v, f) => dimensions(v, f, length));
+ for (const name of ['minimum', 'increment', 'outer_allowance']) optional(machine, name, field, (v, f) => dimensions(v, f, length, false));
optional(machine, 'cost_per_square_metre_minor', field, atLeast(0));
optional(machine, 'tare_per_square_metre', field, weight);
if (container.outer_dimensions != null) {
@@ -356,9 +416,20 @@ function setBesideABag(name, value) {
const accessDirections = eachOneOf(ACCESS_DIRECTIONS);
-function dimensions(raw, where, length) {
+/**
+ * A box's three sides, each a measure; a box that holds or is something has no empty side
+ *, while a made-to-measure step states its own rule for zero.
+ */
+function dimensions(raw, where, length, positive = true) {
const sides = requireObject(raw, where);
- for (const side of SIDES) length(required(sides, side, where), where + pointer(side));
+ const volume = SIDES.reduce((product, side) => {
+ const field = where + pointer(side), ticks = length(required(sides, side, where), field);
+ if (positive && ticks === 0) throw new InvalidRequestError('invalid_value', field, 'must be positive');
+ return product * BigInt(ticks);
+ }, 1n);
+ if (volume > MAX_VOLUME_TICKS3) {
+ throw new InvalidRequestError('above_maximum', where, 'must enclose at most 10^30 cubic ticks');
+ }
}
// Tags in code-point order, as every engine walks them: a JavaScript object lists integer-like
@@ -379,15 +450,40 @@ function rateTable(raw, where) {
optional(table, 'fuel_surcharge_permille', where, atLeast(0));
}
-function obstacles(raw, where, length) {
+function obstacles(raw, where, length, inner) {
requireList(raw, where).forEach((entry, index) => {
const at = where + pointer(index);
const obstacle = requireObject(entry, at);
- if (obstacle.origin != null) {
- const point = requireObject(obstacle.origin, `${at}/origin`);
- for (const axis of AXES) optional(point, axis, `${at}/origin`, length);
+ placedBox(obstacle, at, length, inner);
+ if (obstacle.additional_boxes != null) {
+ const boxes = `${at}/additional_boxes`;
+ requireList(obstacle.additional_boxes, boxes).forEach((box, position) => {
+ const part = boxes + pointer(position);
+ placedBox(requireObject(box, part), part, length, inner);
+ });
+ }
+ });
+}
+
+/**
+ * An optional `origin` and required `dimensions`: an obstacle, or one more box of it,
+ * whose measures are read in the request's unit like every other length, and which lies inside
+ * the container.
+ */
+function placedBox(box, at, length, inner) {
+ const starts = [0, 0, 0];
+ if (box.origin != null) {
+ const point = requireObject(box.origin, `${at}/origin`);
+ AXES.forEach((axis, index) => {
+ if (point[axis] != null) starts[index] = length(point[axis], `${at}/origin/${axis}`);
+ });
+ }
+ const sides = required(box, 'dimensions', at);
+ dimensions(sides, `${at}/dimensions`, length);
+ SIDES.forEach((side, index) => {
+ if (starts[index] + length(sides[side], `${at}/dimensions/${side}`) > inner[index]) {
+ throw new InvalidRequestError('invalid_value', at, 'lies outside inner_dimensions');
}
- dimensions(required(obstacle, 'dimensions', at), `${at}/dimensions`, length);
});
}
diff --git a/result-validation/container.js b/result-validation/container.js
index 13451aa..eb5f5b1 100644
--- a/result-validation/container.js
+++ b/result-validation/container.js
@@ -12,7 +12,7 @@ import { abs, ceilDiv, floorDiv, max, 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 {
- SCORE_SCALE, SQUARE_METRE_TICKS, checkCrush, checkRouteRemovalOrder, checkStackDensity, checkSupportAndLoad,
+ SCORE_SCALE, SQUARE_METRE_TICKS, checkCrush, checkRouteRemovalOrder, checkStackDensity, checkStackTopLoad, checkSupportAndLoad,
occupiedVolume, placedHull, propagateLoad, supportGraph, validNesting,
} from './stacking.js';
@@ -188,11 +188,12 @@ export function checkContainer(packed, spec, items, clearance, globalSupport, is
const graph = supportGraph(entries);
checkSupportAndLoad(entries, graph, globalSupport, issues);
const loads = propagateLoad(entries, graph);
+ checkStackTopLoad(entries, loads, issues);
if (spec.maxStackDensity !== null) checkStackDensity(packedId, entries, loads, spec.maxStackDensity, issues);
checkCrush(packedId, entries, loads, issues);
checkRouteRemovalOrder(packedId, entries, graph, spec.inner, spec.accessDirections, issues);
checkLimits(packed, packedId, placements, spec, items, payload, issues);
- checkVolumes(packed, packedId, placements, spec, items, envelopes, loads, issues);
+ checkVolumes(packed, packedId, placements, spec, items, envelopes, loads, clearance, issues);
const totalWeight = payloadOf(placements, items);
checkCentreOfMass(packed, packedId, placements, spec, items, totalWeight, issues);
checkAxles(packed, packedId, placements, spec, items, totalWeight, issues);
@@ -281,7 +282,7 @@ function checkLimits(packed, packedId, placements, spec, items, payload, issues)
/** Python's `int(value) != computed` for a reported figure that is present. */
const differs = (reported, computed) => reported !== null && pyInt(reported, 'a reported volume') !== computed;
-function checkVolumes(packed, packedId, placements, spec, items, envelopes, loads, issues) {
+function checkVolumes(packed, packedId, placements, spec, items, envelopes, loads, clearance, issues) {
const entries = envelopes.items();
// Every placement counts, through the envelope its item id resolves to -- a repeated id
// resolves to its last placement, as the reference's dict does.
@@ -293,7 +294,11 @@ function checkVolumes(packed, packedId, placements, spec, items, envelopes, load
const left = entries[first][1];
if (left.spec === undefined || left.spec.nestingHeight === null) continue;
for (let second = first + 1; second < entries.length; second += 1) {
- if (validNesting(left, entries[second][1])) used -= left.spec.nestingHeight * left.envelope.length * left.envelope.width;
+ if (!validNesting(left, entries[second][1])) continue;
+ // The envelopes sink by the nesting height; the items themselves overlap by twice the
+ // clearance less, over their own footprint.
+ const margin = 2n * clearance, overlap = left.spec.nestingHeight - margin;
+ if (overlap > 0n) used -= overlap * (left.envelope.length - margin) * (left.envelope.width - margin);
}
}
const reportedVolume = getNull(packed, 'used_volume_ticks3');
diff --git a/result-validation/stacking.js b/result-validation/stacking.js
index dbf27e9..503b62f 100644
--- a/result-validation/stacking.js
+++ b/result-validation/stacking.js
@@ -9,7 +9,7 @@
import { cuboid, hullVolume, intersects, overlapAreaXY, rotateHull, vertices } from './geometry.js';
import { at, hashKey, int, pyCmp, pyEq, sortPy, text } from './json.js';
-import { Ratio, ceilDiv, fixed6, floorDiv, max, ratioPpm } from './num.js';
+import { Ratio, ceilDiv, fixed6, floorDiv, max, min, ratioPpm } from './num.js';
import { issue, shape } from './outcome.js';
import { list, pyRepr, pyStr } from './pyfmt.js';
import { EXIT_DIRECTIONS, holds, rotated, rotationAxes } from './spec.js';
@@ -98,6 +98,9 @@ export function checkSupportAndLoad(entries, graph, globalSupport, issues) {
const ratio = new Ratio(area, envelope.baseArea);
issues.push(issue('insufficient_support',
`${itemId}: ${fixed6(ratio.toDouble())} < ${fixed6(required.toDouble())}`));
+ } else if (area * 2n <= envelope.baseArea
+ && !centroidSupported(envelope, supporting.map(([lower]) => entries[lower][1].envelope))) {
+ issues.push(issue('centre_of_gravity_unsupported', `${itemId}: centroid outside its support hull`));
}
}
for (const [lower] of supporting) checkResting(itemId, spec, entries[lower], issues);
@@ -113,6 +116,39 @@ export function checkSupportAndLoad(entries, graph, globalSupport, issues) {
}
/** What one direct supporter allows to rest on it. */
+/**
+ * Whether the base centroid lies in the convex hull of the contact areas, the rule
+ * the searches apply once a support ratio is enforced; reached only at or below half the base,
+ * where it can refuse. Coordinates are doubled so the centroid is an integer for odd
+ * extents. The corners come four to a positive-area overlap, so the hull is empty or has at
+ * least three vertices. O(s log s) time and O(s) space for s supporters.
+ */
+function centroidSupported(envelope, surfaces) {
+ const unique = new Map();
+ for (const surface of surfaces) {
+ for (const x of [max(envelope.x, surface.x), min(envelope.x2, surface.x2)]) {
+ for (const y of [max(envelope.y, surface.y), min(envelope.y2, surface.y2)]) unique.set(`${x},${y}`, [2n * x, 2n * y]);
+ }
+ }
+ const points = [...unique.values()].sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : a[1] < b[1] ? -1 : a[1] > b[1] ? 1 : 0));
+ const hull = [...halfHull(points), ...halfHull([...points].reverse())];
+ const centroid = [envelope.x + envelope.x2, envelope.y + envelope.y2];
+ return hull.length > 0 && hull.every((vertex, index) => cross(vertex, hull[(index + 1) % hull.length], centroid) >= 0n);
+}
+
+/** One half of Andrew's monotone chain, its last point dropped for the other half to close. */
+function halfHull(points) {
+ const chain = [];
+ for (const point of points) {
+ while (chain.length >= 2 && cross(chain[chain.length - 2], chain[chain.length - 1], point) <= 0n) chain.pop();
+ chain.push(point);
+ }
+ chain.pop();
+ return chain;
+}
+
+const cross = (o, a, b) => (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0]);
+
function checkResting(itemId, spec, [lowerId, lowerEntry], issues) {
const lowerSpec = lowerEntry.spec;
if (lowerSpec === undefined) return;
@@ -122,9 +158,6 @@ function checkResting(itemId, spec, [lowerId, lowerEntry], issues) {
} else if (lowerSpec.acceptsStackingGroups.size > 0 && !holds(lowerSpec.acceptsStackingGroups, spec.stackingGroup)) {
issues.push(issue('stacking_group_incompatible', `${itemId} rests on ${lower}`));
}
- if (lowerSpec.maxTopLoad !== null && spec.weight > lowerSpec.maxTopLoad) {
- issues.push(issue('top_load_exceeded', `${itemId} (${spec.weight} ticks) on ${lower} (limit ${lowerSpec.maxTopLoad})`));
- }
}
/** Everything resting on an item, however indirectly. */
@@ -192,12 +225,26 @@ function pressure(load, baseArea) {
return new Ratio(load * 980665n * SQUARE_METRE_TICKS, TICKS_PER_KG * 100000n * 1000n * baseArea);
}
+/**
+ * `max_top_load` against the whole stack an item bears, as every engine checks it. The
+ * only top-load rule since 1.9.0: an item resting on several bearers shares its weight
+ * among them by contact area. O(n) over the loads `propagateLoad` built.
+ */
+export function checkStackTopLoad(entries, loads, issues) {
+ entries.forEach(([rawId, entry], index) => {
+ const limit = entry.spec === undefined ? null : entry.spec.maxTopLoad;
+ if (limit === null || loads[index] <= limit) return;
+ issues.push(issue('top_load_exceeded', `${pyStr(rawId)} bears ${loads[index]} ticks (limit ${limit})`));
+ });
+}
+
/**: no `compressible` item may carry more pressure than it declared. */
export function checkCrush(packedId, entries, loads, issues) {
entries.forEach(([rawId, entry], index) => {
const limit = entry.spec === undefined ? null : entry.spec.maxCompressionPressureKpa;
if (limit === null) return;
- const carried = pressure(loads[index], entry.envelope.baseArea);
+ const [length, width] = physicalSides(entry.placement);
+ const carried = pressure(loads[index], length * width);
if (carried.compare(Ratio.of(limit)) > 0) {
issues.push(issue('crush_violation',
`${pyStr(rawId)} in ${packedId}: ${fixed6(carried.toDouble())} kPa exceeds ${limit} kPa`));
@@ -205,16 +252,25 @@ export function checkCrush(packedId, entries, loads, issues) {
});
}
-/** Occupied height under load, rounded up, never below one tick; a crushed item keeps its height. */
-function compressedHeight(envelope, spec, load) {
+/** The placed item's own sides, without the clearance its envelope adds. */
+function physicalSides(placement) {
+ const dimensions = at(placement, 'dimensions');
+ return ['length', 'width', 'height'].map((name) => int(at(at(dimensions, name), 'ticks'), 'a placement dimension'));
+}
+
+/**
+ * Occupied height under load, rounded up, never below one tick; a crushed item keeps its height.
+ * The load presses on the item itself, so the footprint and the height are its own.
+ */
+function compressedHeight(height, footprint, spec, load) {
const limit = spec.maxCompressionPressureKpa;
// The reference asserts the pair: a pressure limit without a ratio is not a request it reads.
if (spec.compressionRatioPpm === null) throw shape(`${spec.id}: max_compression_pressure_kpa without compression_ratio`);
- const carried = pressure(load, envelope.baseArea);
- if (carried.compare(Ratio.of(limit)) > 0 || limit === 0n) return envelope.height;
+ const carried = pressure(load, footprint);
+ if (carried.compare(Ratio.of(limit)) > 0 || limit === 0n) return height;
const divisor = limit * 1000000n * carried.denominator;
const retained = divisor - spec.compressionRatioPpm * carried.numerator;
- return max(1n, ceilDiv(envelope.height * retained, divisor));
+ return max(1n, ceilDiv(height * retained, divisor));
}
/**: weight per square metre of an item's own base, at every level of the stack. */
@@ -329,14 +385,14 @@ export function placedHull(envelope, placement, spec) {
/** Space a placement actually takes: its compressed box, its hull, or its box. */
export function occupiedVolume(envelope, placement, spec, load) {
if (spec !== undefined && spec.maxCompressionPressureKpa !== null) {
- return envelope.baseArea * compressedHeight(envelope, spec, load);
+ const [length, width, height] = physicalSides(placement);
+ return length * width * compressedHeight(height, length * width, spec, load);
}
if (spec !== undefined && spec.shapeType === 'convex_hull' && spec.hullVertices !== null) {
return hullVolume(rotateHull(spec.hullVertices, orientationAxes(placement)));
}
// Only an exact hull makes `_placed_hull` differ from the envelope's corners, and a hull was
// answered above, so the reference's remaining `_hull_volume(solid)` arm is never reached.
- const dimensions = at(placement, 'dimensions');
- const side = (name) => int(at(at(dimensions, name), 'ticks'), 'a placement dimension');
- return side('length') * side('width') * side('height');
+ const [length, width, height] = physicalSides(placement);
+ return length * width * height;
}
diff --git a/test/centre-of-gravity.test.mjs b/test/centre-of-gravity.test.mjs
new file mode 100644
index 0000000..b85a023
--- /dev/null
+++ b/test/centre-of-gravity.test.mjs
@@ -0,0 +1,112 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { readFileSync } from 'node:fs';
+
+import {
+ FixedPlacementError,
+ __centreOfGravitySupportedForTests as supported,
+ packFallback,
+} from '../fallback.js';
+
+// The same centroid-in-hull rule Python's and PHP's SupportConstraint apply.
+const box = (x, y, length, width) => ({ x, y, z: 0, d: [length, width, 10] });
+
+test('a centroid beyond a single end support is unsupported', () => {
+ assert.equal(supported(box(0, 0, 100, 10), [box(0, 0, 30, 10)]), false);
+});
+
+test('supports at both ends carry the centroid', () => {
+ assert.equal(supported(box(0, 0, 100, 10), [box(0, 0, 20, 10), box(80, 0, 20, 10)]), true);
+});
+
+test('an odd extent keeps the centroid exact', () => {
+ assert.equal(supported(box(0, 0, 101, 10), [box(0, 0, 51, 10)]), true);
+ assert.equal(supported(box(0, 0, 101, 10), [box(0, 0, 50, 10)]), false);
+});
+
+test('a supporter that only touches an edge carries nothing', () => {
+ assert.equal(supported(box(0, 0, 10, 10), [box(10, 0, 10, 10)]), false);
+});
+
+test('duplicate corners from adjacent supporters collapse', () => {
+ assert.equal(supported(box(0, 0, 20, 10), [box(0, 0, 10, 10), box(10, 0, 10, 10)]), true);
+});
+
+test('a one-tick knife edge under the centroid carries the box', () => {
+ assert.equal(supported(box(0, 0, 10, 10), [box(5, 0, 1, 10)]), true);
+ assert.equal(supported(box(0, 0, 10, 10), [box(6, 0, 1, 10)]), false);
+});
+
+test('a supporter wider than the footprint is clipped to it', () => {
+ assert.equal(supported(box(10, 10, 10, 10), [box(0, 0, 100, 100)]), true);
+});
+
+test('a corner square whose inner corner is the centroid carries it', () => {
+ assert.equal(supported(box(0, 0, 40, 40), [box(0, 0, 20, 20)]), true);
+ assert.equal(supported(box(0, 0, 40, 40), [box(0, 0, 20, 19)]), false);
+});
+
+const legsOnACircle = (keep) => Array.from({ length: 360 }, (_, degree) => degree * Math.PI / 180)
+ .filter(keep)
+ .map((angle) => box(Math.round(500 + 400 * Math.cos(angle)), Math.round(500 + 400 * Math.sin(angle)), 1, 1));
+
+test('three hundred and sixty legs on a circle carry the centroid', () => {
+ assert.equal(supported(box(0, 0, 1000, 1000), legsOnACircle(() => true)), true);
+});
+
+test('legs on half a circle leave the centroid hanging', () => {
+ assert.equal(supported(box(0, 0, 1000, 1000), legsOnACircle((angle) => Math.sin(angle) > 0.1)), false);
+});
+
+test('repeated and reordered supporters give the same answer', () => {
+ const legs = [box(0, 0, 5, 5), box(35, 0, 5, 5), box(0, 35, 5, 5)];
+ for (const order of [legs, [...legs].reverse(), [...legs, ...legs]]) {
+ assert.equal(supported(box(0, 0, 40, 40), order), true);
+ }
+});
+
+test('the largest safe integers keep a half-tick centroid exact', () => {
+ const far = Number.MAX_SAFE_INTEGER - 1000;
+ assert.equal(supported(box(far, far, 101, 10), [box(far, far, 51, 10)]), true);
+ assert.equal(supported(box(far, far, 101, 10), [box(far, far, 50, 10)]), false);
+});
+
+test('safe translations preserve an exact half-tick centroid', () => {
+ const fixture = JSON.parse(readFileSync(new URL(
+ './fixtures/centre-of-gravity-safe-integer-frontier.json', import.meta.url,
+ ), 'utf8'));
+ for (const [dx, dy] of fixture.translations) {
+ for (const entry of fixture.cases) {
+ const translate = ([x, y, length, width]) => box(x + dx, y + dy, length, width);
+ const candidate = translate(entry.probe);
+ assert.ok([candidate.x, candidate.y, candidate.x + candidate.d[0],
+ candidate.y + candidate.d[1]].every(Number.isSafeInteger));
+ assert.equal(supported(candidate, entry.supporters.map(translate)), entry.supported,
+ `translation ${dx},${dy}; probe ${entry.probe}; supports ${entry.supporters}`);
+ }
+ }
+});
+
+test('fixed placement admission refuses an overhanging centre of gravity', () => {
+ const request = {
+ configuration: { minimum_support_ratio: 0.25 },
+ items: [{
+ id: 'cube',
+ quantity: 2,
+ dimensions: { length: '100', width: '100', height: '100' },
+ }],
+ containers: [{
+ id: 'box',
+ inner_dimensions: { length: '200', width: '200', height: '200' },
+ }],
+ fixed_placements: [
+ { item_type: 'cube', container_type: 'box', orientation: 'LWH', position: { x: '0', y: '0', z: '0' } },
+ { item_type: 'cube', container_type: 'box', orientation: 'LWH', position: { x: '60', y: '0', z: '100' } },
+ ],
+ };
+ assert.throws(
+ () => packFallback(request),
+ (error) => error instanceof FixedPlacementError
+ && error.message.startsWith('invalid_fixed_placement: centre_of_gravity_unsupported: cube#2:'),
+ );
+});
diff --git a/test/commerce-boundaries.test.mjs b/test/commerce-boundaries.test.mjs
new file mode 100644
index 0000000..72d0106
--- /dev/null
+++ b/test/commerce-boundaries.test.mjs
@@ -0,0 +1,108 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { catalogVersionInfo, CommerceInputError, quote } from '../commerce.js';
+
+function tariff(carrierId, serviceId, rate = 100) {
+ return { carrier_id: carrierId, service_id: serviceId, versions: [{
+ effective_at: 0, dimensional_weight_divisor: 5000,
+ cost_per_dimensional_kg_minor: { z: rate },
+ }] };
+}
+
+function quoteRequest(carrierId, serviceId, pin) {
+ return { carrier_id: carrierId, service_id: serviceId, ...pin,
+ zone: 'z', actual_weight_g: 1000, volume_mm3: 0 };
+}
+
+for (const separator of ['/', '\0']) {
+ for (const pin of [{ tariff_version: 1 }, { as_of: 0 }]) {
+ test(`tariff identity cannot alias through ${JSON.stringify(separator)} with ${Object.keys(pin)[0]}`, () => {
+ const document = { tariffs: [tariff(`a${separator}b`, 'c')] };
+ const result = quote(document, quoteRequest('a', `b${separator}c`, pin));
+ assert.deepEqual(result, { api_version: 1, status: 'rejected', error: {
+ code: 'tariff_not_found', fields: {
+ carrier_id: 'a', service_id: `b${separator}c`,
+ ...(pin.tariff_version === undefined ? {} : { tariff_version: 1 }),
+ },
+ } });
+ });
+
+ test(`distinct tariff identities containing ${JSON.stringify(separator)} retain their own rate with ${Object.keys(pin)[0]}`, () => {
+ const document = { tariffs: [tariff(`a${separator}b`, 'c', 100), tariff('a', `b${separator}c`, 250)] };
+ for (const [carrierId, serviceId, total] of [[`a${separator}b`, 'c', 100], ['a', `b${separator}c`, 250]]) {
+ const result = quote(document, quoteRequest(carrierId, serviceId, pin));
+ assert.equal(result.status, 'ok');
+ assert.equal(result.quote.carrier_id, carrierId);
+ assert.equal(result.quote.service_id, serviceId);
+ assert.equal(result.quote.total_minor, total);
+ }
+ });
+ }
+}
+
+test('an identical tariff identity is still refused as a duplicate', () => {
+ assert.throws(() => quote({ tariffs: [tariff('a/b', 'c'), tariff('a/b', 'c')] },
+ quoteRequest('a/b', 'c', { tariff_version: 1 })), CommerceInputError);
+});
+
+test('a zone named __proto__ retains its declared rate', () => {
+ const document = { tariffs: [tariff('carrier', 'service')] };
+ document.tariffs[0].versions[0].cost_per_dimensional_kg_minor = JSON.parse('{"__proto__":100}');
+ const result = quote(document, { ...quoteRequest('carrier', 'service', { tariff_version: 1 }),
+ zone: '__proto__' });
+ assert.equal(result.status, 'ok');
+ assert.equal(result.quote.total_minor, 100);
+});
+
+test('an accessorial named __proto__ is charged in request order', () => {
+ const document = { tariffs: [tariff('carrier', 'service')] };
+ document.tariffs[0].versions[0].accessorials = [
+ { accessorial_id: '__proto__', flat_charge_minor: 25 },
+ { accessorial_id: 'constructor', flat_charge_minor: 5 },
+ ];
+ const result = quote(document, { ...quoteRequest('carrier', 'service', { tariff_version: 1 }),
+ requested_accessorials: ['constructor', '__proto__'] });
+ assert.equal(result.status, 'ok');
+ assert.equal(result.quote.total_minor, 130);
+ assert.deepEqual(result.quote.accessorial_charges_minor, [['constructor', 5], ['__proto__', 25]]);
+});
+
+test('duplicate __proto__ accessorial identifiers are refused', () => {
+ const document = { tariffs: [tariff('carrier', 'service')] };
+ document.tariffs[0].versions[0].accessorials = [
+ { accessorial_id: '__proto__', flat_charge_minor: 25 },
+ { accessorial_id: '__proto__', flat_charge_minor: 50 },
+ ];
+ assert.throws(() => quote(document,
+ quoteRequest('carrier', 'service', { tariff_version: 1 })), CommerceInputError);
+});
+
+function catalog(rollback) {
+ return { catalogs: [{ catalog_id: 'catalog', versions: [
+ { effective_at: 0, published_at: 0, snapshot: {} }, rollback,
+ ] }] };
+}
+
+for (const rollback of [
+ { rollback_to: 1, published_at: -1 },
+ { rollback_to: 1, published_at: -1, effective_at: 0 },
+ { rollback_to: 1, published_at: 0, effective_at: -1 },
+]) {
+ test(`catalog rollback refuses negative dates: ${JSON.stringify(rollback)}`, () => {
+ assert.throws(() => catalogVersionInfo(catalog(rollback),
+ { catalog_id: 'catalog', version: 2, resolved_at: 0 }), CommerceInputError);
+ });
+}
+
+test('catalog resolution refuses a negative resolved_at', () => {
+ assert.throws(() => catalogVersionInfo(catalog({ rollback_to: 1, published_at: 0 }),
+ { catalog_id: 'catalog', version: 2, resolved_at: -1 }), CommerceInputError);
+});
+
+test('catalog rollback accepts zero dates and null effective_at defaults to published_at', () => {
+ const result = catalogVersionInfo(catalog({ rollback_to: 1, published_at: 0, effective_at: null }),
+ { catalog_id: 'catalog', version: 2, resolved_at: 0 });
+ assert.equal(result.catalog.effective_at, 0);
+ assert.equal(result.catalog.published_at, 0);
+ assert.equal(result.catalog.resolved_at, 0);
+});
diff --git a/test/commerce-policy-values.test.mjs b/test/commerce-policy-values.test.mjs
new file mode 100644
index 0000000..b4a6c7a
--- /dev/null
+++ b/test/commerce-policy-values.test.mjs
@@ -0,0 +1,39 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { evaluatePolicy } from '../commerce.js';
+
+function decision(operator, value, context) {
+ const document = { policy_rules: [{ rule_id: 'restriction', versions: [{
+ scope: 'facility', action: 'reject', priority: 1, effective_at: 0,
+ predicates: [{ scope: 'facility', field: 'x', operator, value }],
+ }] }] };
+ return evaluatePolicy(document, { scope: 'facility', context, as_of: 0 }).decision;
+}
+
+const cases = [
+ ['equals', { a: [1, { flag: true }], b: null }, { b: null, a: [true, { flag: 1 }] }, false],
+ ['not_equals', { a: null }, { b: null }, false],
+ ['equals', { a: null }, { b: null }, true],
+ ['equals', { a: [1, 2] }, { a: [2, 1] }, true],
+ ['in', [{ a: 1, b: true }], { b: 1, a: true }, false],
+ ['not_in', [{ a: 1 }], { a: 2 }, false],
+ ['in', { a: null }, 'a', false],
+ ['in', { a: 'b' }, 'b', true],
+ ['not_in', { a: 1 }, 'missing', false],
+ ['in', { a: 1 }, ['a'], true],
+ ['in', { a: 1 }, 'toString', true],
+];
+
+for (const [index, [operator, value, actual, allowed]] of cases.entries()) {
+ test(`structured policy value ${index}: ${operator}`, () => {
+ const result = decision(operator, value, { x: actual });
+ assert.equal(result.allowed, allowed);
+ assert.equal(result.citation === null, allowed);
+ });
+}
+
+test('missing fields never match binary operators', () => {
+ for (const operator of ['equals', 'not_equals', 'in', 'not_in']) {
+ assert.equal(decision(operator, { a: 1 }, {}).citation, null);
+ }
+});
diff --git a/test/conformance.test.mjs b/test/conformance.test.mjs
index c1c98a4..b25a80e 100644
--- a/test/conformance.test.mjs
+++ b/test/conformance.test.mjs
@@ -19,6 +19,9 @@ import { objective, validate } from './validate.mjs';
* is deliberately unsatisfiable.
*/
+/** `algorithm.duration_ms` is the wall clock, the one field a determinism check must mask. */
+const withoutDuration = (result) => JSON.parse(JSON.stringify(result, (key, value) => (key === 'duration_ms' ? 0 : value)));
+
const FIXTURES = path.resolve(
path.dirname(fileURLToPath(import.meta.url)), '../../conformance/shared/fixtures');
const FIELD_MATRIX = path.resolve(
@@ -153,6 +156,6 @@ for (const name of names) {
context.skip('wall-clock-truncated searches promise soundness, not bit identity');
return;
}
- assert.deepEqual(first, pack(request));
+ assert.deepEqual(withoutDuration(first), withoutDuration(pack(request)));
});
}
diff --git a/test/effort-boundary.test.mjs b/test/effort-boundary.test.mjs
index 1b9cd16..8e51801 100644
--- a/test/effort-boundary.test.mjs
+++ b/test/effort-boundary.test.mjs
@@ -117,16 +117,29 @@ test('a block the budget cuts short places its first members and stops', () => {
assert.ok(result.summary.packed_item_count > 0 && result.summary.packed_item_count < unlimited.summary.packed_item_count);
});
-test('a later start handed a spent budget is still started and stopped', () => {
+test('later starts get independent effort budgets after an earlier start spends its own', () => {
const portfolio = scene([box('a', 30, 20, 10, 12), box('b', 40, 40, 25, 4)], { multi_start_orders: 3 }, 1);
- const first = packFallback(withBudget(portfolio, { max_restarts: 1 }));
- const request = withBudget(portfolio, { max_search_nodes: first.algorithm.metrics.search_nodes_expanded });
+ const request = withBudget(portfolio, { max_search_nodes: 16 });
const result = packFallback(request);
assertEffortConsistent(request, result);
- const [own, ...later] = result.termination.starts;
- assert.deepEqual([own.started, own.truncated], [true, false]);
- assert.ok(later.length >= 2);
- for (const start of later) assert.deepEqual([start.started, start.truncated], [true, true]);
+ assert.equal(result.algorithm.metrics.search_nodes_expanded, 16);
+ assert.deepEqual(result.termination.starts.map((start) => [start.started, start.truncated]),
+ [[true, false], [true, false], [true, false], [true, true]]);
+ assert.equal(result.algorithm.effort_limit_reached, false);
+ assert.equal(result.termination.any_start_truncated, true);
+
+ // Each of the three item orders completes at its own ceiling. The added block
+ // start also gets sixteen nodes, then stops when it needs a seventeenth.
+ for (let index = 0; index < 3; index++) {
+ const own = packFallback(request, () => 0, null, index);
+ assertEffortConsistent(request, own);
+ assert.equal(own.algorithm.metrics.search_nodes_expanded, 16);
+ assert.equal(own.algorithm.effort_limit_reached, false);
+ }
+ const block = packFallback(request, () => 0, 'homogeneous_blocks', 0);
+ assertEffortConsistent(request, block);
+ assert.equal(block.algorithm.metrics.search_nodes_expanded, 16);
+ assert.equal(block.algorithm.effort_limit_reached, true);
});
test('a named block solver outside quality reaches its first block', () => {
diff --git a/test/exact-json.test.mjs b/test/exact-json.test.mjs
new file mode 100644
index 0000000..d020fc6
--- /dev/null
+++ b/test/exact-json.test.mjs
@@ -0,0 +1,30 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+
+import { exactInteger, parseExact, stringifyExact } from '../exact-json.js';
+
+test('a weight past the safe range round-trips exactly, and nothing else changes', () => {
+ const result = { weight: { ticks: 2n ** 63n - 1n, value: '1', unit: 'g' }, small: { ticks: 7 }, list: [1.5, null, 'x'] };
+ const text = stringifyExact(result);
+ assert.equal(text, '{"weight":{"ticks":9223372036854775807,"value":"1","unit":"g"},"small":{"ticks":7},"list":[1.5,null,"x"]}');
+ assert.deepEqual(parseExact(text), result);
+ assert.deepEqual(parseExact(JSON.stringify({ id: '"ticks":12345678901234567890' })), { id: '"ticks":12345678901234567890' });
+});
+
+test('ticks stay a Number up to 2^53 - 1 and become a BigInt past it', () => {
+ assert.equal(exactInteger(String(Number.MAX_SAFE_INTEGER)), Number.MAX_SAFE_INTEGER);
+ assert.equal(exactInteger('-9007199254740993'), -9007199254740993n);
+ assert.equal(parseExact('{"ticks": 9007199254740993}').ticks, 9007199254740993n);
+ assert.equal(parseExact('{"ticks":9007199254740991}').ticks, 9007199254740991);
+});
+
+test('any integer past the safe range is read exactly, wherever it stands, and no other number moves', () => {
+ const text = '{"score":[1,3747987187107132459,-9007199254740993],"f":12345678901234567.5,"e":1e300,"s":"12345678901234567890","n":-0.5}';
+ const parsed = parseExact(text);
+ assert.deepEqual(parsed.score, [1, 3747987187107132459n, -9007199254740993n]);
+ assert.equal(parsed.f, 12345678901234567.5);
+ assert.equal(parsed.e, 1e300);
+ assert.equal(parsed.s, '12345678901234567890');
+ assert.equal(parsed.n, -0.5);
+ assert.equal(stringifyExact(parsed), '{"score":[1,3747987187107132459,-9007199254740993],"f":12345678901234568,"e":1e+300,"s":"12345678901234567890","n":-0.5}');
+});
diff --git a/test/fallback.test.mjs b/test/fallback.test.mjs
index bb81e4c..8cc06cd 100644
--- a/test/fallback.test.mjs
+++ b/test/fallback.test.mjs
@@ -11,6 +11,7 @@ import {
verifyLoadingPrefixBusinessRules, __ratiosForTests, __planBeamForTests,
} from '../fallback.js';
import { objective as recomputeObjective, validate } from './validate.mjs';
+import { parseExact, stringifyExact } from '../exact-json.js';
/**
* The JavaScript fallback, exercised directly.
@@ -612,7 +613,7 @@ test('effort budget stops at the exact counted boundary without claiming a wall-
const result = packFallback(request(
[cube('a', 10, { quantity: 20 })],
[box('c', 100, 100, 100)],
- { configuration: { time_limit_ms: 60_000, effort_budget: { max_search_nodes: 5 } } },
+ { configuration: { time_limit_ms: 60_000, multi_start_orders: 1, effort_budget: { max_search_nodes: 5 } } },
));
assert.equal(result.summary.packed_item_count, 5);
assert.equal(result.algorithm.metrics.search_nodes_expanded, 5);
@@ -891,13 +892,16 @@ test('cumulative top load stays exact beyond the safe-number boundary', () => {
assert.equal(rejected.summary.packed_item_count, 2);
assert.deepEqual(rejected.unpacked_items.map(item => item.item_type), ['top']);
- // `ticks` remains a Number for schema compatibility, but the rendered value comes
- // from the exact BigInt at that one explicit JSON boundary.
+ // Past 2^53 - 1 a weight's `ticks` is the exact BigInt (R19-01), which `JSON.stringify`
+ // refuses; `stringifyExact` writes it as the integer it is and `parseExact` reads it back.
const reported = packFallback(payload(null));
const bottom = placements(reported).find(placement => placement.item_type === 'bottom');
- assert.equal(bottom.top_load.ticks, boundary);
+ assert.equal(bottom.top_load.ticks, BigInt(boundary) + 1n);
assert.equal(bottom.top_load.value, '1125899906842.624125');
- assert.doesNotThrow(() => JSON.stringify(reported));
+ assert.throws(() => JSON.stringify(reported), TypeError);
+ const text = stringifyExact(reported);
+ assert.match(text, /"ticks":9007199254740993,/);
+ assert.deepEqual(parseExact(text), reported);
});
test('incompatible items are separated', () => {
@@ -1166,7 +1170,7 @@ test('the same request produces the same answer', () => {
// With an adequate deadline and no randomness, reproducibility is total —
// including the search-effort counters.
const payload = request([cube('a', 40, { quantity: 6 })], [box('c', 150, 150, 150, { quantity: 2 })]);
- assert.deepEqual(packFallback(payload), packFallback(payload));
+ assert.equal(withoutDuration(packFallback(payload)), withoutDuration(packFallback(payload)));
});
test('coordinate compaction keeps a 10,000-item lattice at constant result size', () => {
@@ -1202,7 +1206,7 @@ test('coordinate compaction is opt-in and the default result shape is unchanged'
...payload,
configuration: { require_placement_coordinates: true },
});
- assert.deepEqual(implicit, explicit);
+ assert.equal(withoutDuration(implicit), withoutDuration(explicit));
assert.equal(implicit.containers[0].placements.length, 8);
assert.equal('lattice_summary' in implicit.containers[0], false);
});
@@ -1223,6 +1227,7 @@ test('compact lattice stops at the exact effort boundary', () => {
[box('c', 100, 100, 100)],
{ configuration: {
require_placement_coordinates: false,
+ multi_start_orders: 1,
effort_budget: { [field]: 5 },
} },
));
@@ -2075,7 +2080,7 @@ test('the shape memo answers a repeated pack exactly as the first one', () => {
[{ id: 'crate', inner_dimensions: { length: '100', width: '100', height: '100' } }]));
const first = build();
const second = build();
- assert.deepEqual(second, first);
+ assert.equal(withoutDuration(second), withoutDuration(first));
// Named separately from the deep compare: the volume is the number the hull geometry
// decides, so a memo handing back a stale or foreign shape shows here first.
assert.equal(second.containers[0].used_volume_ticks3, String((100 * 16000) ** 3));
@@ -2655,10 +2660,7 @@ test('every requested restart runs and is recorded', () => {
// start `balanced` adds to its own.
assert.equal(one.termination.starts.length, 2);
assert.equal(eight.termination.starts.length, 9);
- assert.ok(
- eight.algorithm.metrics.search_nodes_expanded > one.algorithm.metrics.search_nodes_expanded,
- 'eight restarts must cost more search than one',
- );
+ assert.equal(eight.termination.starts.every((start) => start.started), true);
assert.equal(eight.termination.starts.filter((start) => start.selected).length, 1);
});
@@ -2984,9 +2986,11 @@ test('the added block start replaces an answer it strictly beats', () => {
// The profile's own answer stays on offer, as a losing solver's does under `quality`.
assert.deepEqual(result.alternatives.map((alternative) => alternative.score), [own.score]);
assert.deepEqual(packFallback(cartons('balanced', { alternatives: 1 })).alternatives, []);
- // Both runs are counted: the reported effort is the portfolio's, not the winner's.
- assert.equal(result.algorithm.metrics.search_nodes_expanded > own.algorithm.metrics.search_nodes_expanded, true);
- assert.equal(result.algorithm.candidates_evaluated > own.algorithm.candidates_evaluated, true);
+ // The selected start reports its own work, as every alternative does.
+ const blocks = packFallback(payload, () => 0, 'homogeneous_blocks', 0);
+ assert.deepEqual(result.algorithm.metrics, blocks.algorithm.metrics);
+ assert.equal(result.algorithm.candidates_evaluated, blocks.algorithm.candidates_evaluated);
+ assert.equal(result.algorithm.placements_attempted, blocks.algorithm.placements_attempted);
});
test('the added block start is discarded when it only ties', () => {
@@ -3006,10 +3010,13 @@ test('the added block start is discarded when it only ties', () => {
});
test('fast enumerates one block mode where balanced enumerates both', () => {
- const spent = (profile) => packFallback(cartons(profile)).algorithm.metrics.search_nodes_expanded;
- const own = ownAnswer(cartons('fast')).algorithm.metrics.search_nodes_expanded;
- assert.equal(spent('fast') > own, true);
- assert.equal(spent('balanced') - own, 2 * (spent('fast') - own));
+ const spent = (profile) => {
+ const result = packFallback(cartons(profile));
+ assert.equal(result.algorithm.solver, blockStartId);
+ return result.algorithm.metrics.search_nodes_expanded;
+ };
+ assert.equal(spent('fast') > 0, true);
+ assert.equal(spent('balanced'), 2 * spent('fast'));
});
test('the block solver carries its own node limit outside quality, not the container plan limit', () => {
@@ -3174,6 +3181,32 @@ test('stacking groups: rebalancing never moves an item onto a lower item that re
assert.deepEqual(withBase.placements.map((p) => p.item_type), ['base']);
});
+test('rebalanceWeight accepts interlocking convex_hull placements and breaks tied source weights by first container', () => {
+ const wedgeVertices = [
+ { x: '0', y: '0', z: '0' },
+ { x: '100', y: '0', z: '0' },
+ { x: '0', y: '100', z: '0' },
+ { x: '0', y: '0', z: '100' },
+ { x: '100', y: '0', z: '100' },
+ { x: '0', y: '100', z: '100' },
+ ];
+ const payload = request(
+ [{
+ id: 'wedge',
+ quantity: 3,
+ weight: '100',
+ shape_type: 'convex_hull',
+ hull_vertices: wedgeVertices,
+ dimensions: mm(100, 100, 100),
+ }],
+ [box('crate', 100, 100, 100, { quantity: 2 })],
+ );
+ const original = packSound(payload);
+ assert.equal(original.containers.length, 2);
+ const balanced = rebalanceWeight(payload, original);
+ assert.deepEqual(validate(payload, { ...original, containers: balanced.containers }), []);
+});
+
// --------------------------------------------------------------------------------
test('every support ratio crosses into ppm by one rule (S11)', () => {
diff --git a/test/fixed-group-validation.test.mjs b/test/fixed-group-validation.test.mjs
new file mode 100644
index 0000000..702ec21
--- /dev/null
+++ b/test/fixed-group-validation.test.mjs
@@ -0,0 +1,88 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+
+import { InvalidRequestError, packFallback } from '../fallback.js';
+
+const dimensions = (length = '10') => ({ length, width: '10', height: '10' });
+const request = (configuration = {}) => ({
+ configuration: { solver_profile: 'fast', solvers: ['extreme_points'], time_limit_ms: 300000,
+ max_containers: 2, ...configuration },
+ items: [{ id: 'cube', quantity: 2, group: 'g', dimensions: dimensions() }],
+ containers: [{ id: 'box', inner_dimensions: dimensions() }],
+ fixed_placements: [{ item_type: 'cube', container_type: 'box', orientation: 'LWH' }],
+});
+
+function assertInvalid(result, complete, warning) {
+ assert.equal(result.status, 'invalid_result');
+ assert.deepEqual(result.feasibility, { code: 'unknown' });
+ assert.equal(result.termination.code, 'error');
+ assert.deepEqual(result.optimality, { code: 'not_proven' });
+ assert.equal(result.complete, complete);
+ assert.ok(result.warnings.includes(warning), JSON.stringify(result.warnings));
+}
+
+test('a group split across its fixed container and a fresh one is invalid', () => {
+ assertInvalid(packFallback(request()), true, 'group_split: g: box#1, box#2');
+});
+
+test('an anchored group with a free member left unpacked is invalid', () => {
+ assertInvalid(packFallback(request({ max_containers: 1 })), false, 'group_partial: g: 1/2 packed');
+});
+
+test('an anchored group that fits together remains a valid complete result', () => {
+ const data = request();
+ data.containers[0].inner_dimensions = dimensions('20');
+ const result = packFallback(data);
+ assert.equal(result.complete, true);
+ assert.equal(result.feasibility.code, 'feasible');
+ assert.equal(result.termination.code, 'complete');
+ assert.equal(result.containers.length, 1);
+ assert.equal(result.containers[0].placements.length, 2);
+ assert.ok(!result.warnings.some((warning) => warning.startsWith('group_')));
+});
+
+test('leaving every member of a group unpacked does not partially pack it', () => {
+ const data = request();
+ delete data.fixed_placements;
+ const result = packFallback(data);
+ assert.equal(result.complete, false);
+ assert.notEqual(result.status, 'invalid_result');
+ assert.equal(result.containers.length, 0);
+ assert.equal(result.unpacked_items.length, 2);
+ assert.ok(!result.warnings.some((warning) => warning.startsWith('group_')));
+});
+
+test('validate_result remains an unknown serialized field', () => {
+ assert.throws(() => packFallback(request({ validate_result: false })),
+ (error) => error instanceof InvalidRequestError && error.field === '/configuration/validate_result');
+});
+
+test('null groups are ungrouped and can occupy separate containers', () => {
+ const data = request();
+ data.items[0].group = null;
+ const result = packFallback(data);
+ assert.notEqual(result.status, 'invalid_result');
+ assert.equal(result.complete, true);
+ assert.equal(result.feasibility.code, 'feasible');
+});
+
+test('an empty string names a real group, as in the other ports', () => {
+ const data = request();
+ data.items[0].group = '';
+ assertInvalid(packFallback(data), true, 'group_split: : box#1, box#2');
+});
+
+test('each alternative receives its own group validation result', () => {
+ const result = packFallback(request({ solver_profile: 'balanced', solvers: ['extreme_points', 'layer'], alternatives: 3 }));
+ assert.ok(result.alternatives.length > 0);
+ for (const alternative of result.alternatives) {
+ assertInvalid(alternative, true, 'group_split: g: box#1, box#2');
+ }
+});
+
+test('group accounting combines fixed and free members of distinct item types', () => {
+ const data = request({ max_containers: 1 });
+ data.items = [{ id: 'cube', group: 'g', dimensions: dimensions() },
+ { id: 'other', quantity: 2, group: 'g', dimensions: dimensions() }];
+ assertInvalid(packFallback(data), false, 'group_partial: g: 1/3 packed');
+});
diff --git a/test/fixed-placements.test.mjs b/test/fixed-placements.test.mjs
index f0d3618..0a23f5e 100644
--- a/test/fixed-placements.test.mjs
+++ b/test/fixed-placements.test.mjs
@@ -77,7 +77,8 @@ test('a request without fixed placements answers byte for byte as before', () =>
const data = request();
delete data.fixed_placements;
const empty = { ...data, fixed_placements: [] };
- assert.equal(JSON.stringify(packFallback(empty)), JSON.stringify(packFallback(data)));
+ const withoutDuration = (result) => JSON.stringify(result, (key, value) => (key === 'duration_ms' ? 0 : value));
+ assert.equal(withoutDuration(packFallback(empty)), withoutDuration(packFallback(data)));
assert.ok(!JSON.stringify(packFallback(data)).includes('"fixed"'));
});
diff --git a/test/fixtures/centre-of-gravity-safe-integer-frontier.json b/test/fixtures/centre-of-gravity-safe-integer-frontier.json
new file mode 100644
index 0000000..31d4507
--- /dev/null
+++ b/test/fixtures/centre-of-gravity-safe-integer-frontier.json
@@ -0,0 +1,19 @@
+{
+ "translations": [
+ [0, 0],
+ [4503599627370496, 0],
+ [4503599627370497, 0],
+ [0, 4503599627370496],
+ [0, 4503599627370497],
+ [4503599627370496, 4503599627370497]
+ ],
+ "cases": [
+ {"probe": [0, 0, 7, 1], "supporters": [[4, 0, 3, 1]], "supported": false},
+ {"probe": [0, 0, 7, 1], "supporters": [[0, 0, 3, 1]], "supported": false},
+ {"probe": [0, 0, 7, 1], "supporters": [[3, 0, 4, 1]], "supported": true},
+ {"probe": [0, 0, 1, 7], "supporters": [[0, 4, 1, 3]], "supported": false},
+ {"probe": [0, 0, 1, 7], "supporters": [[0, 0, 1, 3]], "supported": false},
+ {"probe": [0, 0, 1, 7], "supporters": [[0, 3, 1, 4]], "supported": true},
+ {"probe": [0, 0, 6, 1], "supporters": [[0, 0, 3, 1]], "supported": true}
+ ]
+}
diff --git a/test/multi-start-orders.test.mjs b/test/multi-start-orders.test.mjs
index 2e834fb..cdeaa8e 100644
--- a/test/multi-start-orders.test.mjs
+++ b/test/multi-start-orders.test.mjs
@@ -2,12 +2,13 @@ import assert from 'node:assert/strict';
import test from 'node:test';
import { packFallback } from '../fallback.js';
+import { validateWith } from '../index.js';
/**
* Starts the JavaScript engine runs when the request does not say.
*
* Eight orderings outside `fast`, one under it, as Python, PHP and Rust default to; the
- * effort budget is the request's, shared by every start; and a shuffled ordering keeps the
+ * effort budget applies independently to every start; and a shuffled ordering keeps the
* lead keys, so priority survives a restart.
*/
@@ -29,14 +30,34 @@ test('balanced and quality run eight orderings by default, fast runs one', () =>
assert.equal(startCount(packFallback(scene({ multi_start_orders: 3 }))), 3);
});
-test('the effort budget is shared by every start', () => {
- const result = packFallback(scene({ effort_budget: { max_search_nodes: 5 } }));
+test('each start gets its own effort budget and reports the selected start counters', () => {
+ const configuration = { effort_budget: { max_search_nodes: 5 } };
+ const single = packFallback(scene({ ...configuration, multi_start_orders: 1 }));
+ assert.equal(single.algorithm.metrics.search_nodes_expanded, 5);
+ assert.equal(single.summary.packed_item_count, 5);
+ assert.equal(single.termination.code, 'effort_limit');
+ assert.deepEqual(single.termination.starts.map((start) => [start.started, start.truncated]), [[true, true]]);
+
+ const result = packFallback(scene(configuration));
assert.equal(result.algorithm.metrics.search_nodes_expanded, 5);
+ assert.equal(result.summary.packed_item_count, 5);
assert.equal(result.termination.code, 'effort_limit');
assert.deepEqual(result.termination.starts.map((start) => [start.started, start.truncated]),
[[true, true], ...Array.from({ length: 7 }, () => [true, true])]);
});
+test('the public validator accepts budgeted portfolio metrics and rejects a single-start overshoot', () => {
+ const request = scene({ effort_budget: { max_search_nodes: 5 } });
+ const result = packFallback(request, () => 0);
+ assert.deepEqual(validateWith(null, request, result), []);
+
+ const singleRequest = scene({ multi_start_orders: 1, effort_budget: { max_search_nodes: 5 } });
+ const single = packFallback(singleRequest, () => 0);
+ assert.deepEqual(validateWith(null, singleRequest, single), []);
+ single.algorithm.metrics.search_nodes_expanded = 6;
+ assert.deepEqual(validateWith(null, singleRequest, single).map((issue) => issue.code), ['effort_budget_exceeded']);
+});
+
test('start 0 leads with priority; shuffled starts are free shuffles', () => {
// Start 0 respects priority. Later starts re-solve a plain shuffle, allowing the portfolio
// to try low-priority items first (JS gap 2 revert).
diff --git a/test/request-errors.test.mjs b/test/request-errors.test.mjs
index ee4c036..03a7fa4 100644
--- a/test/request-errors.test.mjs
+++ b/test/request-errors.test.mjs
@@ -282,3 +282,59 @@ test('without an output block the result is in the request unit spelt as its cod
assert.equal(packFallback(request).containers[0].inner_dimensions.length.unit, code, unit);
}
});
+
+test('a length or a box past the admission ceiling is refused where it is spelled', () => {
+ const tooLong = 'must be at most 9007199254740991 ticks';
+ assertRefused((r) => { r.items[0].dimensions.length = { value: '9007199254740992', unit: 'ticks' }; },
+ 'above_maximum', '/items/0/dimensions/length', tooLong);
+ assertRefused((r) => { r.configuration.clearance = 1e20; }, 'above_maximum', '/configuration/clearance', tooLong);
+ assertRefused((r) => { r.items[0].dimensions.length = -1e20; }, 'negative_measure', '/items/0/dimensions/length',
+ 'cannot be negative');
+ const side = { value: '10000000001', unit: 'ticks' };
+ assertRefused((r) => { r.containers[0].inner_dimensions = { length: side, width: side, height: side }; },
+ 'above_maximum', '/containers/0/inner_dimensions', 'must enclose at most 10^30 cubic ticks');
+});
+
+test('a side that rounds to zero ticks is refused where it is spelled', () => {
+ assertRefused((r) => { r.items[0].dimensions.width = '0'; }, 'invalid_value', '/items/0/dimensions/width',
+ 'must be positive');
+ assertRefused((r) => { r.containers[0].inner_dimensions.length = '0.00001'; }, 'invalid_value',
+ '/containers/0/inner_dimensions/length', 'must be positive');
+});
+
+test('an obstacle and each of its boxes lie inside the container', () => {
+ const pillar = (extra) => ({ id: 'pillar', origin: { x: '150' },
+ dimensions: { length: '10', width: '10', height: '10' }, ...extra });
+ const side = { length: '10', width: '10', height: '10' };
+ assertRefused((r) => { r.containers[0].obstacles = [pillar({ origin: { x: '195' } })]; }, 'invalid_value',
+ '/containers/0/obstacles/0', 'lies outside inner_dimensions');
+ assertRefused((r) => { r.containers[0].obstacles = [pillar({ additional_boxes: [{ origin: { z: '195' }, dimensions: side }] })]; },
+ 'invalid_value', '/containers/0/obstacles/0/additional_boxes/0', 'lies outside inner_dimensions');
+ assertRefused((r) => { r.containers[0].obstacles = [pillar({ additional_boxes: [{ dimensions: { ...side, width: '0' } }] })]; },
+ 'invalid_value', '/containers/0/obstacles/0/additional_boxes/0/dimensions/width', 'must be positive');
+});
+
+test('a weight past a signed 64-bit integer, or written as an unsafe number, is refused at its pointer (R19-01)', () => {
+ const at = (weight) => (request) => { request.items[0].weight = weight; };
+ assertRefused(at({ value: '9223372036854775808', unit: 'ticks' }), 'above_maximum', '/items/0/weight',
+ 'must be at most 9223372036854775807 ticks');
+ assertRefused(at({ value: 2 ** 53 + 2, unit: 'ticks' }), 'invalid_value', '/items/0/weight',
+ 'must be written as a string past 9007199254740991');
+ assertRefused(at(2 ** 60), 'invalid_value', '/items/0/weight', 'must be written as a string past 9007199254740991');
+ assertRefused(at({ value: -(2 ** 60), unit: 'ticks' }), 'negative_measure', '/items/0/weight', 'cannot be negative');
+ assertRefused(at({ value: 2 ** 60, unit: 'stone' }), 'invalid_unit', '/items/0/weight', 'has an unknown unit "stone"');
+});
+
+test('every item weight times its quantity and the heaviest tare fit the ceiling (R19-01)', () => {
+ const heavy = (weight, tare) => (request) => {
+ request.items[0].weight = { value: String(weight), unit: 'ticks' };
+ request.containers[0].tare_weight = { value: String(tare), unit: 'ticks' };
+ };
+ assertRefused(heavy(2n ** 62n - 1n, 2n), 'above_maximum', '/items',
+ 'must weigh at most 9223372036854775807 ticks in all, with the heaviest tare');
+ const request = base();
+ heavy(2n ** 62n - 1n, 1n)(request);
+ const result = packFallback(request);
+ assert.equal(result.containers.reduce((total, container) => total + BigInt(container.payload_weight.ticks), 0n),
+ 2n ** 63n - 2n);
+});
diff --git a/test/request-measures.test.mjs b/test/request-measures.test.mjs
index db24a15..438d6d7 100644
--- a/test/request-measures.test.mjs
+++ b/test/request-measures.test.mjs
@@ -35,3 +35,21 @@ test('made-to-measure input parsing does not grow with portfolio starts',()=>{
assert.equal(counts[1],counts[0],'machine input measures must come from the request table');
delete globalThis.__requestMeasureParses;
});
+
+test('each unit is worth its definition in ticks', () => {
+ // 1 in = 25.4 mm, 1 ft = 12 in, 1 lb = 453.59237 g, 1 oz = 1/16 lb: one item of one unit
+ // a side and one unit of weight, read back from the answer in ticks.
+ const lengths = { mm: 16000, cm: 160000, m: 16000000, in: 406400, ft: 4876800 };
+ const weights = { mg: 8000, g: 8000000, kg: 8000000000, oz: 226796185, lb: 3628738960 };
+ for (const [unit, ticks] of Object.entries(lengths)) {
+ const side = { value: '1', unit };
+ const answer = packFallback({ items: [{ id: 'a', dimensions: { length: side, width: side, height: side } }],
+ containers: [{ id: 'c', inner_dimensions: { length: '2000', width: '2000', height: '2000' } }] });
+ assert.equal(answer.containers[0].placements[0].dimensions.length.ticks, ticks, unit);
+ }
+ for (const [unit, ticks] of Object.entries(weights)) {
+ const answer = packFallback({ items: [{ id: 'a', weight: { value: '1', unit }, dimensions: { length: '1', width: '1', height: '1' } }],
+ containers: [{ id: 'c', inner_dimensions: { length: '10', width: '10', height: '10' } }] });
+ assert.equal(Number(answer.containers[0].payload_weight.ticks), ticks, unit);
+ }
+});
diff --git a/test/shipping-selection.test.mjs b/test/shipping-selection.test.mjs
new file mode 100644
index 0000000..037daaf
--- /dev/null
+++ b/test/shipping-selection.test.mjs
@@ -0,0 +1,66 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+
+import { packFallback } from '../fallback.js';
+
+const mm = (length, width = length, height = length) => ({
+ length: String(length), width: String(width), height: String(height),
+});
+const request = (containers) => ({
+ units: { length: 'mm' },
+ configuration: { solver_profile: 'fast', solvers: ['extreme_points'], time_limit_ms: 300000,
+ max_containers: 1, objective: 'shipping_cost', dimensional_weight_divisor: 5000,
+ dimensional_weight_length_unit: 'cm', dimensional_weight_weight_unit: 'kg',
+ effort_budget: { max_candidates_evaluated: 1000000, max_placement_attempts: 1000000,
+ max_search_nodes: 1000000 } },
+ items: [{ id: 'cube', dimensions: mm(10) }],
+ containers,
+});
+
+test('shipping selection ranks gross billed weight before the purchase cost', () => {
+ const result = packFallback(request([
+ { id: 'heavy', inner_dimensions: mm(10), tare_weight: '1000', cost_minor: 0 },
+ { id: 'light', inner_dimensions: mm(10), tare_weight: '1', cost_minor: 100 },
+ ]));
+ assert.equal(result.containers[0].container_type, 'light');
+ assert.deepEqual(result.score, [0, 8000000, 1, 0, 1000000]);
+});
+
+test('shipping selection bills the outer dimensions of a rigid container', () => {
+ const result = packFallback(request([
+ { id: 'bulky', inner_dimensions: mm(10), outer_dimensions: mm(100), cost_minor: 0 },
+ { id: 'small', inner_dimensions: mm(10), cost_minor: 100 },
+ ]));
+ assert.equal(result.containers[0].container_type, 'small');
+ assert.deepEqual(result.score, [0, 1600000, 1, 0, 1000000]);
+});
+
+test('shipping selection bills a flat bag on its achieved dimensions', () => {
+ const result = packFallback(request([
+ { id: 'rigid', inner_dimensions: mm(20), cost_minor: 0 },
+ { id: 'bag', inner_dimensions: mm(100), deformable_boundary: { kind: 'flat_bag' }, cost_minor: 100 },
+ ]));
+ assert.equal(result.containers[0].container_type, 'bag');
+ assert.deepEqual(result.score, [0, 1600000, 1, 999000, 100000]);
+});
+
+test('shipping selection bills the fabricated box rather than its machine maximum', () => {
+ const result = packFallback(request([
+ { id: 'stock', inner_dimensions: mm(20), cost_minor: 0 },
+ { id: 'machine', inner_dimensions: mm(100), cost_minor: 100,
+ made_to_measure: { minimum: mm(10), increment: mm(10), outer_allowance: mm(1) } },
+ ]));
+ assert.equal(result.containers[0].container_type, 'machine');
+ assert.deepEqual(result.score, [0, 2129600, 1, 0, 1000000]);
+});
+
+test('shipping selection keeps placing more items ahead of a lighter incomplete trial', () => {
+ const data = request([
+ { id: 'single', inner_dimensions: mm(10), tare_weight: '1' },
+ { id: 'double', inner_dimensions: mm(20, 10, 10), tare_weight: '1000' },
+ ]);
+ data.items[0].quantity = 2;
+ const result = packFallback(data);
+ assert.equal(result.containers[0].container_type, 'double');
+ assert.equal(result.complete, true);
+});
diff --git a/test/validate.mjs b/test/validate.mjs
index 50992ea..0f7d1ff 100644
--- a/test/validate.mjs
+++ b/test/validate.mjs
@@ -37,7 +37,11 @@ function overlaps(one, other) {
start < other.at[axis] + other.size[axis] && start + one.size[axis] > other.at[axis]);
}
-function validNesting(one, other, itemsById, lengthUnit) {
+/**
+ * Whether two physical boxes are a nesting pair. The envelopes sink by `nesting_height`, so the
+ * boxes themselves sink by twice the clearance less.
+ */
+function validNesting(one, other, itemsById, lengthUnit, clearance = 0) {
if (one.type !== other.type) return false;
const nesting = itemsById.get(one.type)?.nesting_height;
if (nesting == null) return false;
@@ -46,7 +50,7 @@ function validNesting(one, other, itemsById, lengthUnit) {
|| one.at[1] + one.size[1] !== other.at[1] + other.size[1]) return false;
const [lower, upper] = one.at[2] <= other.at[2] ? [one, other] : [other, one];
return lower.at[2] !== upper.at[2]
- && lower.at[2] + lower.size[2] - upper.at[2] === requestLengthTicks(nesting, lengthUnit);
+ && lower.at[2] + lower.size[2] - upper.at[2] === requestLengthTicks(nesting, lengthUnit) - 2 * clearance;
}
function boxesOf(container, latticeSequences = new Map()) {
@@ -277,6 +281,7 @@ export function validate(request, result) {
const itemsById = new Map(request.items.map((item) => [item.id, item]));
const containersById = new Map(request.containers.map((container) => [container.id, container]));
const lengthUnit = request.units?.length ?? 'mm';
+ const clearance = request.configuration?.clearance == null ? 0 : requestLengthTicks(request.configuration.clearance, lengthUnit);
const seen = new Set();
const inventory = new Map();
@@ -309,7 +314,8 @@ export function validate(request, result) {
if (box.at.some((start, axis) => start < 0 || start + box.size[axis] > inner[axis])) {
issues.push('outside_container');
}
- if (item.must_be_on_floor && box.at[2] !== 0) issues.push('must_be_on_floor');
+ // The envelope stands on the floor; the item itself starts one clearance above it.
+ if (item.must_be_on_floor && box.at[2] !== clearance) issues.push('must_be_on_floor');
if (item.group != null) {
groupHomes.set(item.group, (groupHomes.get(item.group) ?? new Set()).add(container.id));
}
@@ -318,7 +324,7 @@ export function validate(request, result) {
// The axis-aligned test is the broad phase; the exact test refines it only when a hull
// is one of the two solids, so an ordinary box pair reaches the same verdict it always
// did.
- if (overlaps(box, other) && !validNesting(box, other, itemsById, lengthUnit)
+ if (overlaps(box, other) && !validNesting(box, other, itemsById, lengthUnit, clearance)
&& solidsOverlap(solidOf(box, item, lengthUnit),
solidOf(other, itemsById.get(other.type), lengthUnit))) {
issues.push('collision');