From 3523328f534f6fbdaf63eb4e0cbe34ea78ffcde1 Mon Sep 17 00:00:00 2001 From: Anton Date: Tue, 24 Nov 2026 08:15:36 -0500 Subject: [PATCH] chore(release): 1.12.0 --- .github/DISCUSSION_TEMPLATE/q-a.yml | 2 +- .github/DISCUSSION_TEMPLATE/show-and-tell.yml | 2 +- .github/ISSUE_TEMPLATE/bug_report.yml | 4 +- .github/ISSUE_TEMPLATE/feature_request.yml | 2 +- CHANGELOG.md | 21 +++ CITATION.cff | 2 +- README.md | 6 +- codemeta.json | 2 +- docs/COMMERCE-API.md | 16 +- docs/GUARANTEES.md | 2 +- docs/PUBLIC-API.md | 6 +- pyproject.toml | 2 +- src/packvium/artifacts.py | 2 +- src/packvium/commerce/api.py | 3 +- src/packvium/commerce/document.py | 6 +- src/packvium/hull.py | 63 ++++++- src/packvium/packer.py | 11 +- src/packvium/packing_sequence.py | 116 ++++++++++--- src/packvium/request_errors.py | 63 ++++++- src/packvium/request_objects.py | 15 +- src/packvium/result_validation.py | 62 ++++--- src/packvium/units.py | 28 ++- tests/test_axle_load.py | 6 +- tests/test_commerce_edge_cases.py | 13 +- tests/test_irregular_items.py | 71 ++++++++ tests/test_layer_direction.py | 163 ++++++++++++++++++ tests/test_made_to_measure.py | 2 + tests/test_optimality_bounds.py | 18 +- tests/test_packing_sequence.py | 105 +++++++++++ tests/test_request_objects_corpus.py | 4 +- tests/test_result_validation.py | 17 ++ 31 files changed, 722 insertions(+), 113 deletions(-) create mode 100644 tests/test_layer_direction.py diff --git a/.github/DISCUSSION_TEMPLATE/q-a.yml b/.github/DISCUSSION_TEMPLATE/q-a.yml index ee0cb51..7822a95 100644 --- a/.github/DISCUSSION_TEMPLATE/q-a.yml +++ b/.github/DISCUSSION_TEMPLATE/q-a.yml @@ -10,7 +10,7 @@ body: id: package-version attributes: label: Package and version - placeholder: "packvium 1.11.0 (Python)" + placeholder: "packvium 1.12.0 (Python)" validations: required: true - type: textarea diff --git a/.github/DISCUSSION_TEMPLATE/show-and-tell.yml b/.github/DISCUSSION_TEMPLATE/show-and-tell.yml index 26cb55f..01cd58a 100644 --- a/.github/DISCUSSION_TEMPLATE/show-and-tell.yml +++ b/.github/DISCUSSION_TEMPLATE/show-and-tell.yml @@ -16,7 +16,7 @@ body: id: package-version attributes: label: Package and version - placeholder: "packvium 1.11.0 (Python)" + placeholder: "packvium 1.12.0 (Python)" validations: required: false - type: textarea diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml index e177e5f..f3032c7 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.11.0. - placeholder: "1.11.0" + description: The exact version installed, for example 1.12.0. + placeholder: "1.12.0" validations: required: true - type: input diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml index ecd0ecc..79f3ddc 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.11.0" + placeholder: "1.12.0" validations: required: true - type: textarea diff --git a/CHANGELOG.md b/CHANGELOG.md index 3717ea9..0ff8207 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,27 @@ What changed in `packvium` on PyPI, release by release. The format follows [Keep a Changelog](https://keepachangelog.com/1.1.0/) and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [1.12.0] + +The money ceiling covers sums, one order for unplaced items, and faster hull and unloading +checks. + +### Changed + +- **A request whose dearest openable containers cost more than 9007199254740991 minor units in + all,** or whose landed top brackets bill more than that in all, is `invalid_request` / + `above_maximum` at `/containers`. +- **A commerce input integer outside ±(2^53 − 1)** is refused at its path with `expected an + exact integer`. 1.11 computed with it exactly. +- **`unpacked_items` is listed in request order, then by instance number,** in the answer and + in every alternative, as in the other engines. + +### Performance + +- **Hull collision checks reuse each shape pair's separating axes and projections:** 0.211 s → + 0.078 s CPU on the quality-beam wedge fixture. +- **`safe_removal_order`, route removal and their validation run in O(n² · d).** + ## [1.11.0] Bottom gussets and standing pouches, a certified bound for the shipping objectives, one money diff --git a/CITATION.cff b/CITATION.cff index e0a615f..26347c4 100644 --- a/CITATION.cff +++ b/CITATION.cff @@ -5,7 +5,7 @@ type: software authors: - name: "Packvium contributors" website: "https://packvium.com" -version: "1.11.0" +version: "1.12.0" license: MIT url: "https://packvium.com" repository-code: "https://github.com/packvium/packvium-python" diff --git a/README.md b/README.md index c22e697..01d0158 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ Use it to pick the smallest carton for an order, build a pallet, load a shipping or load a truck within its axle ratings and delivery-stop order. Every answer comes back as coordinates and rotations for each item, with a reason for anything that did not fit. -> **Version 1.11.0 — the public API is frozen.** Field names, status codes and the +> **Version 1.12.0 — the public API is frozen.** Field names, status codes and the > objective vector do not change without a major version, so any `1.x` is a safe upgrade > from any earlier `1.x`. > Read [docs/GUARANTEES.md](https://github.com/packvium/packvium-python/blob/main/docs/GUARANTEES.md) before relying on a result. @@ -333,7 +333,7 @@ Pick the package for your stack; mixing them in one system is safe. | --- | --- | --- | | Python — [`packvium`](https://pypi.org/project/packvium/) | `pip install packvium` | [packvium-python](https://github.com/packvium/packvium-python) | | PHP — [`packvium/packvium`](https://packagist.org/packages/packvium/packvium) | `composer require packvium/packvium` | [packvium-php](https://github.com/packvium/packvium-php) | -| Rust — [`packvium`](https://crates.io/crates/packvium) | `packvium = "1.11"` | [packvium-rust](https://github.com/packvium/packvium-rust) | +| Rust — [`packvium`](https://crates.io/crates/packvium) | `packvium = "1.12"` | [packvium-rust](https://github.com/packvium/packvium-rust) | | Node.js — [`@packvium/engine`](https://www.npmjs.com/package/@packvium/engine) | `npm install @packvium/engine` | [packvium-node](https://github.com/packvium/packvium-node) | | Browser / WebAssembly — [`@packvium/browser`](https://www.npmjs.com/package/@packvium/browser) | `npm install @packvium/browser` | [packvium-wasm](https://github.com/packvium/packvium-wasm) | | PHP FFI bridge — [`packvium/native-bridge`](https://packagist.org/packages/packvium/native-bridge) | `composer require packvium/native-bridge` | [packvium-php-bridge](https://github.com/packvium/packvium-php-bridge) | @@ -355,7 +355,7 @@ CodeMeta form. @software{packvium_python, author = {{Packvium contributors}}, title = {Packvium for Python}, - version = {1.11.0}, + version = {1.12.0}, license = {MIT}, url = {https://packvium.com} } diff --git a/codemeta.json b/codemeta.json index 15a8837..93f6e9c 100644 --- a/codemeta.json +++ b/codemeta.json @@ -3,7 +3,7 @@ "@type": "SoftwareSourceCode", "name": "Packvium for Python", "description": "Deterministic 3D bin-packing and cartonization engine for pallets, containers, trucks and shipping cartons. Exact integer geometry, reproducible results.", - "version": "1.11.0", + "version": "1.12.0", "license": "https://spdx.org/licenses/MIT", "author": [ { diff --git a/docs/COMMERCE-API.md b/docs/COMMERCE-API.md index 44a835e..e6dfe79 100644 --- a/docs/COMMERCE-API.md +++ b/docs/COMMERCE-API.md @@ -257,9 +257,8 @@ 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. +field matches neither binary operator, including its negated form. A rule priority is an +exact integer within `±(2^53 − 1)`, like every commerce integer. ### `catalog_version_info` @@ -428,8 +427,9 @@ existing rule-pool storage. Until 1.11 only JavaScript refused; Python answered without a ceiling, and Rust and PHP answered up to `2^63 - 1`. The bound is far above any real tariff — nine quadrillion minor currency units. -- JavaScript refuses an input integer above `2^53 - 1` with `expected an exact integer`: - `JSON.parse` has already rounded it, so no exact arithmetic after that can recover the - value the caller sent. Python computes from such an input exactly and PHP and Rust read it - up to `2^63 - 1`, so an engine may answer a quote JavaScript refuses; callers should not - send one. No fixture does. +- Every engine refuses an input integer outside `±(2^53 - 1)` at its path with + `expected an exact integer`: `JSON.parse` has already rounded it, so no exact arithmetic + after that can recover the value the caller sent, and the other engines hold the same + line so that none answers a quote JavaScript refuses. Until 1.12 Python + computed from such an input exactly and PHP and Rust read it up to `2^63 - 1`. Pinned by + `conformance/commerce/fixtures/input-integer-above-safe-ceiling.json`. diff --git a/docs/GUARANTEES.md b/docs/GUARANTEES.md index 929e28f..74f5c32 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.11.0` freezes the public API. Field names, status codes, the objective +Version `1.12.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 c0f98e6..25ae9b0 100644 --- a/docs/PUBLIC-API.md +++ b/docs/PUBLIC-API.md @@ -556,6 +556,10 @@ is true exactly when `winning_start_truncated || global_deadline_reached`, and ## Rejection proof +`unpacked_items` lists the items in the order the request lists them, each item's instances +by number, in every engine and every alternative. Which of several interchangeable +instances a search leaves out is not part of the contract. + Every entry in `unpacked_items` carries the same evidence shape in Python, PHP, Rust and JavaScript: @@ -583,7 +587,7 @@ The four levels have deliberately different meanings: | Level | Meaning | | --- | --- | | `proven` | A request-level bound proves rejection without relying on search completeness. Currently `no_compatible_container_dimensions`, `payload_exceeded`, `rotation_restricted` and `no_eligible_container` — each a pure geometry or tag check across every container, none dependent on how far the search got. | -| `observed` | The engine exhausted or rejected the candidates it actually examined; this is not a global impossibility proof. Currently `no_feasible_placement`, `search_exhausted`, `exact_search_incomplete` and `insufficient_support` — the last when replaying the finished layout finds a place the item fits once the support rules are set aside, and none with them, in every engine. | +| `observed` | The engine exhausted or rejected the candidates it actually examined; this is not a global impossibility proof. Currently `no_feasible_placement` and `insufficient_support` — the last when replaying the finished layout finds a place the item fits once the support rules are set aside, and none with them, in every engine. Every engine names an item no finer diagnosis explains `no_feasible_placement`; `search_exhausted` and `exact_search_incomplete` remain valid codes a result may carry, at the same level, and a validator still reads them. | | `inferred` | The reason follows from solver state or a compound rule but has no complete certificate. | | `unknown_due_to_limit` | A deadline stopped the search, so no negative conclusion is claimed. | diff --git a/pyproject.toml b/pyproject.toml index 3a79ec1..91ddbc3 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "packvium" -version = "1.11.0" +version = "1.12.0" description = "Deterministic 3D bin-packing and cartonization engine for pallets, containers, trucks and shipping cartons. Exact integer geometry, reproducible results." readme = "README.md" requires-python = ">=3.9" diff --git a/src/packvium/artifacts.py b/src/packvium/artifacts.py index d523369..ab66c64 100644 --- a/src/packvium/artifacts.py +++ b/src/packvium/artifacts.py @@ -33,7 +33,7 @@ #: The suite version of this builder, the same string in all four engines of one release. #: The engine's own name is deliberately not recorded: four correct builders naming themselves #: would emit four different documents. `make version-set` rewrites this line. -SUITE_VERSION = "1.11.0" +SUITE_VERSION = "1.12.0" #: The deterministic part of `result.algorithm`. `duration_ms` is wall-clock time and never #: enters an artifact. diff --git a/src/packvium/commerce/api.py b/src/packvium/commerce/api.py index a3c64a0..8500d5f 100644 --- a/src/packvium/commerce/api.py +++ b/src/packvium/commerce/api.py @@ -18,6 +18,7 @@ import json from typing import Any, Dict, List, Mapping, Optional, Sequence, Tuple +from .._canonical_json import MAX_EXACT_MAGNITUDE from .catalog import ( AmbiguousCatalogReferenceError, CatalogVersionNotFoundError, @@ -67,7 +68,7 @@ def _request(value: Any) -> Mapping[str, Any]: def _integer(value: Any, path: str) -> int: - if isinstance(value, bool) or not isinstance(value, int): + if isinstance(value, bool) or not isinstance(value, int) or abs(value) > MAX_EXACT_MAGNITUDE: _fail(path, "expected an exact integer") return value diff --git a/src/packvium/commerce/document.py b/src/packvium/commerce/document.py index 4fe4d6a..887b023 100644 --- a/src/packvium/commerce/document.py +++ b/src/packvium/commerce/document.py @@ -19,6 +19,7 @@ from typing import Any, Dict, Iterable, List, Mapping, Optional, Sequence, Tuple +from .._canonical_json import MAX_EXACT_MAGNITUDE from .._compat import dataclass from .catalog import ( CartonMaster, @@ -63,8 +64,9 @@ def _sequence(value: Any, path: str) -> Sequence[Any]: def _integer(value: Any, path: str) -> int: # `bool` is a subclass of `int`; a boolean where an exact integer belongs is a - # caller mistake, not a zero or a one. - if isinstance(value, bool) or not isinstance(value, int): + # caller mistake, not a zero or a one. Past 2^53 - 1 JavaScript has already rounded + # the JSON number, so every implementation holds commerce integers to the safe ceiling. + if isinstance(value, bool) or not isinstance(value, int) or abs(value) > MAX_EXACT_MAGNITUDE: _fail(path, "expected an exact integer") return value diff --git a/src/packvium/hull.py b/src/packvium/hull.py index 553f144..ec0cd78 100644 --- a/src/packvium/hull.py +++ b/src/packvium/hull.py @@ -45,6 +45,7 @@ from functools import lru_cache from itertools import combinations from math import gcd +from threading import Lock from typing import Iterable, Sequence, Tuple from ._compat import dataclass @@ -366,6 +367,61 @@ def separating_axes(left: HullShape, right: HullShape) -> Tuple[Axis, ...]: return tuple(sorted(axes)) +#: Ceilings on the pair memo below, in entries and in axes held across all entries. A request +#: meets at most (distinct hull items x orientations + distinct box sizes) squared ordered +#: pairs, and a pair of 32-vertex hulls carries at most a few thousand axes, so either bound is +#: generous for one request; what they stop is a long-lived process accumulating pairs forever. +#: The same two numbers as the JavaScript fallback's `PAIR_PLAN_ENTRIES` / `PAIR_PLAN_AXES`. +PAIR_PLAN_ENTRIES = 256 +PAIR_PLAN_AXES = 60_000 + +#: An ordered pair's separating axes with each shape's projection interval on every one. +PairPlan = Tuple[Tuple[Axis, ...], Tuple[Tuple[int, int], ...], Tuple[Tuple[int, int], ...]] + +_PAIR_PLANS: "dict[Tuple[HullShape, HullShape], PairPlan]" = {} +_PAIR_PLAN_LOCK = Lock() +_pair_plan_axes = 0 + + +def pair_plan(left: HullShape, right: HullShape) -> PairPlan: + """Memoise the ordered pair's axes and local projection intervals. + + All three depend on the two rotated shapes and never on where they stand: a placement + only adds `origin . axis` to an interval. Rebuilding them per test made every collision + check pay the `O(e_a * e_b)` axis product plus `O(axes * (a + b))` projections -- 6636 + builds on the quality-beam wedge fixture where 90 distinct pairs exist. + + Keyed by the shapes themselves, whose equality is the whole of what determines the + plan, so a box rebuilt per call still hits. Emptied whole when either ceiling would be + passed, so the contents depend only on the call sequence; and a hit returns exactly what + a rebuild would, so no output can depend on whether it hit. + """ + global _pair_plan_axes + key = (left, right) + found = _PAIR_PLANS.get(key) + if found is not None: + return found + axes = separating_axes(left, right) + plan = ( + axes, + tuple(left.projection(axis) for axis in axes), + tuple(right.projection(axis) for axis in axes), + ) + # Build outside the lock. A concurrent miss may already have published this pair. + with _PAIR_PLAN_LOCK: + found = _PAIR_PLANS.get(key) + if found is not None: + return found + if len(axes) > PAIR_PLAN_AXES: + return plan + if len(_PAIR_PLANS) >= PAIR_PLAN_ENTRIES or _pair_plan_axes + len(axes) > PAIR_PLAN_AXES: + _PAIR_PLANS.clear() + _pair_plan_axes = 0 + _PAIR_PLANS[key] = plan + _pair_plan_axes += len(axes) + return plan + + def collide(left: HullShape, left_origin: Vertex, right: HullShape, right_origin: Vertex) -> bool: """Do two placed hulls overlap with positive volume? @@ -373,9 +429,10 @@ def collide(left: HullShape, left_origin: Vertex, right: HullShape, right_origin with the half-open convention `AxisAlignedBox.intersects` already uses for cuboids, so a hull resting exactly on a box is supported rather than colliding with it. """ - for axis in separating_axes(left, right): - left_low, left_high = left.projection(axis) - right_low, right_high = right.projection(axis) + axes, left_spans, right_spans = pair_plan(left, right) + for axis, (left_low, left_high), (right_low, right_high) in zip( + axes, left_spans, right_spans + ): left_shift = _dot(left_origin, axis) right_shift = _dot(right_origin, axis) if (left_high + left_shift <= right_low + right_shift diff --git a/src/packvium/packer.py b/src/packvium/packer.py index 4b6be27..3f6164c 100644 --- a/src/packvium/packer.py +++ b/src/packvium/packer.py @@ -109,6 +109,7 @@ def _pack_checked(self, items: tuple, containers: tuple, fixed_placements: tuple portfolio = orchestrator.solve(fixed.free, request.containers, self.config, deadline, fixed.containers) raw_solutions = portfolio.solutions + request_order = {item.id: index for index, item in enumerate(items)} ranked = [] validator = IndependentSolutionValidator() scorer = self.solution_scorer or resolve_objective_scorer(self.config.objective, self.config) @@ -170,7 +171,7 @@ def _pack_checked(self, items: tuple, containers: tuple, fixed_placements: tuple ranked.append(PackingResult( status, raw.containers, - raw.unpacked, + in_request_order(raw.unpacked, request_order), AlgorithmReport( self.config.profile.value, raw.solver_name, @@ -235,6 +236,14 @@ def _pack_checked(self, items: tuple, containers: tuple, fixed_placements: tuple ) +def in_request_order(unpacked: tuple, request_order: dict[str, int]) -> tuple: + """`unpacked` in the order the request listed the items, each item's instances by number +. Every engine reports this order, whichever search left the items out and in + whichever order it gave up on them. O(u log u) for u unpacked instances.""" + return tuple(sorted(unpacked, key=lambda entry: (request_order[entry.instance.item.id], + entry.instance.sequence))) + + def _stated_optimality( status: PackingStatus, score: "tuple[int, ...]", diff --git a/src/packvium/packing_sequence.py b/src/packvium/packing_sequence.py index f3636e0..dcdd4ff 100644 --- a/src/packvium/packing_sequence.py +++ b/src/packvium/packing_sequence.py @@ -35,7 +35,7 @@ from __future__ import annotations from ._compat import dataclass -from typing import Sequence +from typing import Iterable, Sequence from .constraints import (SQUARE_METRE_TICKS, LoadSupportGraph, LoadUnit, _touches_corners, direct_support_view, load_units, non_stackable_failure, overloaded, @@ -214,26 +214,96 @@ def safe_removal_order(boxes: Sequence[AxisAlignedBox], container: Dimensions, `InvalidDirectionError` if `directions` names anything outside the six-value vocabulary.""" _validated(directions) - graph = UnloadingDependencyGraph.build(boxes) - present = frozenset(range(len(boxes))) + search = _RemovalSearch(boxes, container, directions) order: list[int] = [] - while present: - chosen = None - for index in range(len(boxes)): - if (index in present and not (graph.depends_on[index] & present) - and _clear_direction(index, boxes[index], boxes, present, container, directions) is not None): - chosen = index - break - if chosen is None: - raise SequenceError(present) + while search.present: # Deterministic: the lowest index among this step's candidates, not # arbitrary set iteration order. + chosen = search.next_removable(range(len(boxes))) + if chosen is None: + raise SequenceError(frozenset(search.present)) order.append(chosen) - present = present - {chosen} + search.remove(chosen) replay_removal_order(boxes, container, order, directions) return order +#: What the removal search knows about one box's way out, as Rust's `Exits`: never tested, +#: found blocked once, or counted (each direction's sweep with its present blockers). A box +#: found removable is removed at once, so no state records that. +_UNTESTED, _BLOCKED = "untested", "blocked" + + +class _RemovalSearch: + """The lowest-index-first removal search (A-08), as Rust's `RemovalSearch`. + + It answers exactly what a rescan from index 0 after every removal would. A box found + blocked by the early-exit scan is only marked; blocked a second time it gets per-direction + blocker counts that each removal lowers, so it is never tested against the whole scene + again. A scene whose first box is usually removable never pays for counts at all. + + Worst case `O(n^2 * d)`: each box is scanned once with early exit, counted once in + `O(n * d)`, then costs `O(d)` per removal -- where rescanning cost `O(n^3 * d)`. + """ + + def __init__(self, boxes: Sequence[AxisAlignedBox], container: Dimensions, + directions: Sequence[str]): + self._boxes = boxes + self._container = container + self._directions = directions + self.present: set[int] = set(range(len(boxes))) + graph = UnloadingDependencyGraph.build(boxes) + #: Present boxes still resting on each box, and the boxes each one rests on. + self._resting_on_top = [len(riders) for riders in graph.depends_on] + self._supporters: list[list[int]] = [[] for _ in boxes] + for lower, riders in enumerate(graph.depends_on): + for rider in riders: + self._supporters[rider].append(lower) + self._exits: list = [_UNTESTED] * len(boxes) + + def next_removable(self, candidates: Iterable[int]) -> int | None: + """The first of `candidates`, in their order, that is present and removable now.""" + for index in candidates: + if index in self.present and self._removable(index): + return index + return None + + def remove(self, removed: int) -> None: + self.present.discard(removed) + box = self._boxes[removed] + for exits in self._exits: + if isinstance(exits, list): + for exit_ in exits: + if sweep_intersects(exit_[0], box): + exit_[1] -= 1 + for lower in self._supporters[removed]: + self._resting_on_top[lower] -= 1 + self._supporters[removed] = [] + + def _removable(self, index: int) -> bool: + if self._resting_on_top[index]: + return False + exits = self._exits[index] + if exits == _UNTESTED: + self._exits[index] = _BLOCKED + return _clear_direction(index, self._boxes[index], self._boxes, self.present, + self._container, self._directions) is not None + if exits == _BLOCKED: + exits = self._count_blockers(index) + self._exits[index] = exits + return any(blockers == 0 for _, blockers in exits) + + def _count_blockers(self, index: int) -> list[list]: + box = self._boxes[index] + counted = [] + for direction in self._directions: + sweep = swept_volume(box, self._container, direction) + blockers = sum(1 for other in self.present + if other != index and sweep_intersects(sweep, self._boxes[other])) + counted.append([sweep, blockers]) + return counted + + def safe_route_removal_order(boxes: Sequence[AxisAlignedBox], stops: Sequence[int | None], container: Dimensions, directions: Sequence[str] = ALL_DIRECTIONS) -> list[int]: @@ -256,25 +326,19 @@ def safe_route_removal_order(boxes: Sequence[AxisAlignedBox], stops: Sequence[in `directions` names anything outside the six-value vocabulary. """ _validated(directions) - graph = UnloadingDependencyGraph.build(boxes) - remaining = frozenset(range(len(boxes))) + search = _RemovalSearch(boxes, container, directions) order: list[int] = [] for stop in sorted({stop for stop in stops if stop is not None}): - due = frozenset(index for index in remaining if stops[index] == stop) + due = [index for index in range(len(boxes)) if stops[index] == stop and index in search.present] while due: - chosen = None - for index in range(len(boxes)): - if (index in due and not (graph.depends_on[index] & remaining) - and _clear_direction(index, boxes[index], boxes, remaining, container, directions) is not None): - chosen = index - break - if chosen is None: - raise RouteSequenceError(stop, due) # Deterministic: the lowest index among this step's candidates, not # arbitrary set iteration order. + chosen = search.next_removable(due) + if chosen is None: + raise RouteSequenceError(stop, frozenset(due)) order.append(chosen) - remaining = remaining - {chosen} - due = due - {chosen} + search.remove(chosen) + due.remove(chosen) return order diff --git a/src/packvium/request_errors.py b/src/packvium/request_errors.py index c2fbcce..f6e25f8 100644 --- a/src/packvium/request_errors.py +++ b/src/packvium/request_errors.py @@ -24,7 +24,7 @@ from ._canonical_json import MAX_EXACT_MAGNITUDE, json_integer, json_spelling from ._request_error import InvalidRequestError from .flat_bag import BAG_ORIENTATIONS, DEFORMABLE_BOUNDARY_KINDS, GUSSETED_BAG, STANDING -from .units import LENGTH_UNIT_CODES, WEIGHT_UNIT_CODES, Length, ParsedMeasures, Weight +from .units import LENGTH_UNIT_CODES, WEIGHT_UNIT_CODES, Length, ParsedMeasures, Weight, _unit_key from .made_to_measure import box_cost_minor_for from .orientations import CODES, UPRIGHT_CODES, SIGNED_CODE_NEEDS_A_HULL, refusal_reason, vocabulary from .bounds import MAX_BOUND_SUM @@ -134,7 +134,7 @@ def _measure(value: Any, field: str, kind: Type[Length] | Type[Weight], unit: st if "value" not in value: raise InvalidRequestError("wrong_type", field, "must be a measure") stated = value.get("unit", unit) - if not isinstance(stated, str) or stated.lower().strip() not in kind._MULTIPLIERS: + if _unit_key(stated) not in kind._MULTIPLIERS: raise InvalidRequestError("invalid_unit", field, f"has an unknown unit {json_spelling(stated)}") amount = value["value"] if isinstance(value, Mapping) else value if kind is Length and _whole_beyond_exact(amount): @@ -210,6 +210,7 @@ def check_request(data: Any) -> ParsedMeasures: _check_container(raw, pointer("containers", index), unit, measures, currency) _require_unique_ids(containers, "containers") _total_weight(items, containers, measures) + _total_money(items, containers, unit, measures) return measures @@ -222,7 +223,7 @@ def _check_units(raw: Any) -> str: length = units.get("length") if length is None: return "mm" - if not isinstance(length, str) or length.lower().strip() not in Length._MULTIPLIERS: + if _unit_key(length) not in Length._MULTIPLIERS: raise InvalidRequestError("invalid_unit", "/units/length", f"has an unknown unit {json_spelling(length)}") return length @@ -558,6 +559,24 @@ def ticks(holder: Mapping[str, Any], name: str) -> int: (ticks(container, "tare_weight") for container in containers)) +def _total_money(items: list, containers: list, unit: str, measures: ParsedMeasures) -> None: + def money(container: Mapping[str, Any]) -> Tuple[Optional[int], int, int]: + fee = json_integer(container.get("cost_minor") or 0) + machine = container.get("made_to_measure") + cost = fee if machine is None else box_cost_minor_for( + json_integer(machine.get("cost_per_square_metre_minor") or 0), fee, + _ticks(container["inner_dimensions"], unit, measures)) + table = container.get("rate_table") or {} + landed = top_bracket_landed_minor( + [json_integer(price) for price in table.get("prices_minor") or ()], + json_integer(table.get("minimum_charge_minor") or 0), + json_integer(table.get("fuel_surcharge_permille") or 0)) + quantity = container.get("quantity") + return (None if quantity is None else json_integer(quantity), cost, landed) + total_money_minor(sum(json_integer(item.get("quantity", 1)) for item in items), + (money(container) for container in containers)) + + def _enclosure(sides: Tuple[int, int, int], where: str) -> None: length, width, height = sides if length * width * height > MAX_VOLUME_TICKS3: @@ -606,15 +625,45 @@ def top_bracket_landed(prices: Sequence[int], minimum_charge: int, surcharge_per `MAX_EXACT_MAGNITUDE`. The same arithmetic as `RateTable.charge_minor_or_none`, so no bracket the table can bill passes it. A table with no prices is left to the other rules. Shared with `request_objects`. O(prices).""" - if not prices: - return - base = max(max(prices), minimum_charge) - if base + -(-base * surcharge_permille // 1000) > MAX_EXACT_MAGNITUDE: + if top_bracket_landed_minor(prices, minimum_charge, surcharge_permille) > MAX_EXACT_MAGNITUDE: raise InvalidRequestError( "above_maximum", where, f"must price its top bracket at most {MAX_EXACT_MAGNITUDE} minor units with the fuel surcharge") +def top_bracket_landed_minor(prices: Sequence[int], minimum_charge: int, surcharge_permille: int) -> int: + """The most one container on this table can be billed, fuel surcharge included; 0 for a + table with no prices. O(prices).""" + if not prices: + return 0 + base = max(max(prices), minimum_charge) + return base + -(-base * surcharge_permille // 1000) + + +def total_money_minor(item_count: int, containers: Iterable[Tuple[Optional[int], int, int]]) -> None: + """M3: the most money the containers `item_count` items can open could sum to in a + packing score, against `MAX_EXACT_MAGNITUDE` -- container cost first, then the landed + charge. Each container is `(quantity or None, dearest cost_minor, dearest landed + charge)`. An opened container holds at least one item, so at most `item_count` open; + the dearest types fill that count first, up to their quantity. The bound reads only the + request, so whether a request is refused never depends on which packing an engine found. + Shared with `request_objects`. O(c log c) for c containers.""" + stock = list(containers) + for position, message in ((1, "must cost"), (2, "must bill")): + remaining, total = item_count, 0 + for quantity, *money in sorted(stock, key=lambda container: -container[position]): + if remaining == 0: + break + opened = remaining if quantity is None else min(quantity, remaining) + total += opened * money[position - 1] + remaining -= opened + if total > MAX_EXACT_MAGNITUDE: + raise InvalidRequestError( + "above_maximum", "/containers", + f"{message} at most {MAX_EXACT_MAGNITUDE} minor units in all across the containers " + f"the items can open") + + def currency_code(value: Any, field: str) -> None: """An ISO 4217 shape, `^[A-Z]{3}$`, with no code list: the engines never convert, so a code they do not know is still one they can echo (docs/SERIALIZATION.md). ASCII letters diff --git a/src/packvium/request_objects.py b/src/packvium/request_objects.py index 75506c4..0665634 100644 --- a/src/packvium/request_objects.py +++ b/src/packvium/request_objects.py @@ -26,7 +26,8 @@ from .request_errors import (BAG_EXCLUSIONS, InvalidRequestError, _integer, _one_of, _ratio, _set_beside_a_bag, _stacking_group_name, box_ticks, currency_code, length_ticks, pallet_frame, pointer, pointer_join, - rate_table_currency, top_bracket_landed, total_weight_ticks, weight_ticks) + rate_table_currency, top_bracket_landed, top_bracket_landed_minor, + total_money_minor, total_weight_ticks, weight_ticks) #: (JSON name, PackingConfig attribute, floor), in `check_request`'s order. _CONFIGURATION_INTEGERS = (("time_limit_ms", "time_limit_ms", 1), ("alternatives", "top_k", 1), @@ -57,12 +58,24 @@ def check_objects(items: Sequence[Item], containers: Sequence[Container], config _check_routes_beside_pallets(items, containers) total_weight_ticks(((item.weight.ticks, item.quantity) for item in items), (container.tare_weight.ticks for container in containers)) + total_money_minor(sum(item.quantity for item in items), + (_container_money(container) for container in containers)) hull_types = frozenset(item.id for item in items if item.shape_type is ShapeType.CONVEX_HULL) for index, placement in enumerate(fixed_placements): _check_fixed_placement(placement, f"fixed_placements[{index}]", pointer("fixed_placements", index), hull_types) +def _container_money(container: Container) -> tuple[Optional[int], int, int]: + cost = (container.cost_minor if container.made_to_measure is None + else box_cost_minor_for(container.made_to_measure.cost_per_square_metre_minor, + container.cost_minor, as_triple(container.inner_dimensions))) + table = container.rate_table + landed = 0 if table is None else top_bracket_landed_minor( + table.prices_minor, table.minimum_charge_minor, table.fuel_surcharge_permille) + return (container.quantity, cost, landed) + + def _check_routes_beside_pallets(items: Sequence[Item], containers: Sequence[Container]) -> None: """A routed item beside a pallet that allows overhang: the JSON path refuses it as `container.pallet_overhang_limit+item.stop_index`, this one at the first routed item.""" diff --git a/src/packvium/result_validation.py b/src/packvium/result_validation.py index a070d33..633e558 100644 --- a/src/packvium/result_validation.py +++ b/src/packvium/result_validation.py @@ -1971,27 +1971,6 @@ def _swept_region(envelope: Box, container: tuple[int, int, int], direction: str return Box(x1, y1, z1, x2 - x1, y2 - y1, z2 - z1) -def _has_clear_exit( - item_id: str, - envelopes: dict[str, tuple[Box, dict, ItemSpec | None]], - present: set[str], - container: tuple[int, int, int], - directions: Sequence[str] = _EXIT_DIRECTIONS, -) -> bool: - """Can `item_id` be slid straight out through some container wall without - passing through any other currently-present placement?""" - envelope = envelopes[item_id][0] - for direction in directions: - region = _swept_region(envelope, container, direction) - if not any( - other_id != item_id and region.intersects(envelopes[other_id][0]) - for other_id in present - ): - return True - return False - - - def corridor_replay_succeeds( boxes: dict[str, Box], stops: dict[str, float], @@ -2061,14 +2040,14 @@ def _check_route_removal_order( if not stops: return present = set(envelopes) + directions = doors or _EXIT_DIRECTIONS for stop in sorted(set(stops.values())): due = {item_id for item_id, value in stops.items() if value == stop and item_id in present} + exits = _ExitBlockers(due, envelopes, present, container, directions) while due: removable = [ item_id for item_id in due - if not (direct_above[item_id] & present) - and _has_clear_exit(item_id, envelopes, present, container, - doors or _EXIT_DIRECTIONS) + if not (direct_above[item_id] & present) and exits.has_clear_exit(item_id) ] if not removable: issues.append(Issue( @@ -2080,6 +2059,41 @@ def _check_route_removal_order( chosen = min(removable) present.discard(chosen) due.discard(chosen) + exits.remove(chosen, due, envelopes) + + +class _ExitBlockers: + """How many present items stand in each exit of every item due at the current stop + (A-08), as Rust's `ExitBlockers`. Taking an item out lowers the counts it was + part of instead of re-testing every due item against every present one; an exit that + is clear stays clear, so each verdict is the one a fresh sweep of every present item would give. + `O(|due| * n * d)` once per stop, then `O(|due| * d)` per removal: `O(n^2 * d)` over a + route, where re-testing cost `O(n^3 * d)`.""" + + def __init__(self, due: set[str], envelopes: dict[str, tuple[Box, dict, ItemSpec | None]], + present: set[str], container: tuple[int, int, int], directions: Sequence[str]): + self._exits: dict[str, list[list]] = {} + for item_id in due: + envelope = envelopes[item_id][0] + item_exits = [] + for direction in directions: + region = _swept_region(envelope, container, direction) + blockers = sum(1 for other_id in present + if other_id != item_id and region.intersects(envelopes[other_id][0])) + item_exits.append([region, blockers]) + self._exits[item_id] = item_exits + + def has_clear_exit(self, item_id: str) -> bool: + return any(blockers == 0 for _, blockers in self._exits[item_id]) + + def remove(self, removed: str, due: set[str], + envelopes: dict[str, tuple[Box, dict, ItemSpec | None]]) -> None: + """`removed` leaves the container: every exit of `due` it stood in is one blocker lighter.""" + envelope = envelopes[removed][0] + for item_id in due: + for exit_ in self._exits[item_id]: + if exit_[0].intersects(envelope): + exit_[1] -= 1 def validate(request: dict, result: dict) -> list[Issue]: diff --git a/src/packvium/units.py b/src/packvium/units.py index 94c8ae3..56ee130 100644 --- a/src/packvium/units.py +++ b/src/packvium/units.py @@ -9,6 +9,20 @@ from typing import Any, Optional, Tuple, Type, TypeVar +#: The whitespace of `\s` over ASCII text (space, tab, newline, return, form feed, vertical tab). +_ASCII_SPACE = " \t\n\r\f\v" +_LENGTH_SUFFIX_RE = re.compile( + r"(.+?)\s*(mm|cm|m|in|inch|inches|ft|ticks?)", re.IGNORECASE | re.ASCII +) +_WEIGHT_SUFFIX_RE = re.compile( + r"(.+?)\s*(mg|kg|g|oz|lbs?|ticks?)", re.IGNORECASE | re.ASCII +) + + +def _strip_ascii(text: str) -> str: + return text.strip(_ASCII_SPACE) + + class Rounding(str, Enum): FLOOR = "floor" CEIL = "ceil" @@ -29,7 +43,7 @@ def _fraction(value: int | str | Decimal | Fraction) -> Fraction: return Fraction(value, 1) if isinstance(value, Decimal): return Fraction(value) - text = str(value).strip().replace("\u00a0", " ") + text = _strip_ascii(str(value)).replace("\u00a0", " ") negative = text.startswith("-") mixed = re.fullmatch(r"[+-]?([0-9]+)\s+([0-9]+)\s*/\s*([0-9]+)", text, re.ASCII) if mixed: @@ -79,7 +93,7 @@ def _digits(text: str) -> int: def _unit_key(unit: object) -> str | None: """A unit code as the tables key it, or None for a value that is no code at all: `None` or a number is an unknown unit, as the JSON path refuses it, not an AttributeError.""" - return unit.lower().strip() if isinstance(unit, str) else None + return _strip_ascii(unit).lower() if isinstance(unit, str) else None def _non_negative(ticks: int, kind: str) -> int: @@ -167,9 +181,9 @@ def parse(cls, value: Any, default_unit: str = "mm", rounding: Rounding = Roundi raise refused_type("float length input is intentionally rejected; use a decimal string") value = int(value) if isinstance(value, str): - match = re.fullmatch(r"(.+?)\s*(mm|cm|m|in|inch|inches|ft|ticks?)", value.strip(), re.I) + match = _LENGTH_SUFFIX_RE.fullmatch(_strip_ascii(value)) if match: - return cls.of(match.group(1).strip(), match.group(2), rounding) + return cls.of(_strip_ascii(match.group(1)), match.group(2), rounding) return cls.of(value, default_unit, rounding) def as_fraction(self, unit: str = "mm") -> Fraction: @@ -231,9 +245,9 @@ def parse(cls, value: Any, default_unit: str = "g", rounding: Rounding = Roundin raise refused_type("float weight input is intentionally rejected; use a decimal string") value = int(value) if isinstance(value, str): - match = re.fullmatch(r"(.+?)\s*(mg|kg|g|oz|lbs?|ticks?)", value.strip(), re.I) + match = _WEIGHT_SUFFIX_RE.fullmatch(_strip_ascii(value)) if match: - return cls.of(match.group(1).strip(), match.group(2), rounding) + return cls.of(_strip_ascii(match.group(1)), match.group(2), rounding) return cls.of(value, default_unit, rounding) def decimal(self, unit: str = "g", places: int = 8) -> str: @@ -305,5 +319,5 @@ def output_length_unit(request_unit: str) -> str: The request's own `units.length`, spelt as the schema's output code: case and surrounding space are ignored and a spelt-out name folds to its code (`"Inches"` is `in`). A unit no output code names -- the internal `tick` -- gives `mm`, the default of both blocks.""" - multiplier = Length._MULTIPLIERS.get(request_unit.lower().strip()) + multiplier = Length._MULTIPLIERS.get(_unit_key(request_unit)) return next((code for code in LENGTH_UNIT_CODES if Length._MULTIPLIERS[code] == multiplier), "mm") diff --git a/tests/test_axle_load.py b/tests/test_axle_load.py index 5d9b8ce..921d4dc 100644 --- a/tests/test_axle_load.py +++ b/tests/test_axle_load.py @@ -142,7 +142,11 @@ def test_an_axle_balanced_point_seats_the_envelope_under_a_clearance(): for profile in ("fast", "balanced", "quality"): result = pack_from_dict({ "units": {"length": "mm"}, - "configuration": {"solver_profile": profile, "clearance": "10"}, + # Counted work, not the default clock: a loaded host once cut the search short. + "configuration": {"solver_profile": profile, "clearance": "10", "time_limit_ms": 60000, + "effort_budget": {"max_candidates_evaluated": 1000000, + "max_placement_attempts": 1000000, + "max_search_nodes": 1000000}}, "items": [{"id": "drum", "allowed_rotations": ["LWH"], "weight": {"value": "1000", "unit": "g"}, "dimensions": {"length": "200", "width": "100", "height": "100"}}], diff --git a/tests/test_commerce_edge_cases.py b/tests/test_commerce_edge_cases.py index 466a280..ce34b48 100644 --- a/tests/test_commerce_edge_cases.py +++ b/tests/test_commerce_edge_cases.py @@ -555,11 +555,12 @@ def test_a_total_exactly_at_the_ceiling_is_answered_exactly(self): assert result["quote"]["base_charge_minor"] == CEILING assert result["quote"]["total_minor"] == CEILING - def test_a_base_charge_one_above_the_ceiling_is_refused(self): + def test_a_rate_one_above_the_ceiling_is_refused_at_its_path(self): + # An input past 2^53 - 1 is refused where it is written, as every engine does. with pytest.raises(CommerceInputError) as caught: ceiling_quote(rate_per_kg=CEILING + 1) assert str(caught.value) == ( - f"quote amount {CEILING + 1} is above {CEILING} and cannot be represented exactly") + "document.tariffs[0].versions[0].cost_per_dimensional_kg_minor['zone-a']: expected an exact integer") def test_a_fuel_surcharge_above_the_ceiling_is_refused_with_its_own_value(self): with pytest.raises(CommerceInputError) as caught: @@ -567,12 +568,12 @@ def test_a_fuel_surcharge_above_the_ceiling_is_refused_with_its_own_value(self): assert str(caught.value) == ( f"quote amount {18 * 10**15} is above {CEILING} and cannot be represented exactly") - def test_an_accessorial_above_the_ceiling_is_refused_with_its_own_value(self): + def test_an_accessorial_above_the_ceiling_is_refused_at_its_path(self): with pytest.raises(CommerceInputError) as caught: ceiling_quote(accessorials=[{"accessorial_id": "liftgate", "flat_charge_minor": CEILING + 1}], requested=["liftgate"]) assert str(caught.value) == ( - f"quote amount {CEILING + 1} is above {CEILING} and cannot be represented exactly") + "document.tariffs[0].versions[0].accessorials[0].flat_charge_minor: expected an exact integer") def test_an_accessorial_exactly_at_the_ceiling_is_answered(self): result = ceiling_quote(rate_per_kg=0, accessorials=[ @@ -585,7 +586,7 @@ def test_a_total_above_the_ceiling_is_refused_when_every_component_is_inside(sel assert str(caught.value) == ( f"quote amount {10**16} is above {CEILING} and cannot be represented exactly") - def test_the_dimensional_weight_is_checked_before_the_charges(self): + def test_the_document_is_checked_before_the_request(self): with pytest.raises(CommerceInputError) as caught: ceiling_quote(rate_per_kg=CEILING + 1, volume_mm3=(CEILING + 1) * 5000) - assert str(caught.value).startswith(f"quote amount {CEILING + 1} is above") + assert str(caught.value).startswith("document.tariffs[0].versions[0].cost_per_dimensional_kg_minor") diff --git a/tests/test_irregular_items.py b/tests/test_irregular_items.py index 9991955..0edd416 100644 --- a/tests/test_irregular_items.py +++ b/tests/test_irregular_items.py @@ -91,6 +91,77 @@ def test_a_tetrahedron_misses_a_cube_that_its_bounding_box_overlaps(): assert collide(tetra, (0, 0, 0), unit, (7, 7, 7)) is False +def test_a_shape_pair_builds_its_axes_once_however_often_it_is_tested(monkeypatch): + """The axes and local intervals depend on the two shapes, never on where they + stand, so every origin after the first reuses them -- and answers what a rebuild would.""" + import packvium.hull as hull + + builds = [] + real = hull.separating_axes + monkeypatch.setattr(hull, "separating_axes", lambda a, b: builds.append(1) or real(a, b)) + monkeypatch.setattr(hull, "_PAIR_PLANS", {}) + tetra, unit = HullShape.of(TETRAHEDRON), cube(4) + origins = [(x, y, z) for x in range(0, 12, 3) for y in range(0, 12, 3) for z in range(0, 12, 3)] + memoised = [collide(tetra, (0, 0, 0), unit, origin) for origin in origins] + assert len(builds) == 1 + monkeypatch.setattr(hull, "_PAIR_PLANS", {}) + rebuilt = [] + for origin in origins: + hull._PAIR_PLANS.clear() + rebuilt.append(collide(tetra, (0, 0, 0), unit, origin)) + assert memoised == rebuilt and True in memoised and False in memoised + + +def test_the_pair_memo_empties_whole_at_its_ceiling(monkeypatch): + import packvium.hull as hull + + monkeypatch.setattr(hull, "_PAIR_PLANS", {}) + monkeypatch.setattr(hull, "_pair_plan_axes", 0) + monkeypatch.setattr(hull, "PAIR_PLAN_ENTRIES", 2) + shapes = [cube(side) for side in (2, 3, 4)] + for shape in shapes: + hull.pair_plan(shapes[0], shape) + assert list(hull._PAIR_PLANS) == [(shapes[0], shapes[2])] + + +def test_a_plan_larger_than_the_axis_budget_is_not_cached(monkeypatch): + import packvium.hull as hull + + monkeypatch.setattr(hull, "_PAIR_PLANS", {}) + monkeypatch.setattr(hull, "_pair_plan_axes", 0) + monkeypatch.setattr(hull, "PAIR_PLAN_AXES", 2) + shape = cube(4) + plan = hull.pair_plan(shape, shape) + assert len(plan[0]) == 3 + assert not hull._PAIR_PLANS + assert hull._pair_plan_axes == 0 + + +def test_parallel_pair_memo_misses_only_charge_for_one_entry(monkeypatch): + from concurrent.futures import ThreadPoolExecutor + from threading import Barrier + + import packvium.hull as hull + + misses = Barrier(2, timeout=10) + separating_axes = hull.separating_axes + + def synchronized_axes(left, right): + misses.wait() + return separating_axes(left, right) + + monkeypatch.setattr(hull, "_PAIR_PLANS", {}) + monkeypatch.setattr(hull, "_pair_plan_axes", 0) + monkeypatch.setattr(hull, "separating_axes", synchronized_axes) + left, right = HullShape.of(TETRAHEDRON), cube(4) + with ThreadPoolExecutor(max_workers=2) as pool: + first = pool.submit(hull.pair_plan, left, right) + second = pool.submit(hull.pair_plan, left, right) + plan = first.result() + assert second.result() == plan + assert hull._pair_plan_axes == len(plan[0]) + + def test_collision_does_not_depend_on_argument_order(): tetra = HullShape.of(TETRAHEDRON) unit = cube(6) diff --git a/tests/test_layer_direction.py b/tests/test_layer_direction.py new file mode 100644 index 0000000..f276aba --- /dev/null +++ b/tests/test_layer_direction.py @@ -0,0 +1,163 @@ +"""Every module of `packvium` imports only its own layer or a lower one (R-03). + +The tiers are docs/ARCHITECTURE.md's chain, `Units <- Domain <- Constraints/Algorithms/ +Validation <- Packer <- Serialization/Nested <- Application adapters`, with commerce as a second +root that only the adapters may join. The source is parsed, never imported, so the test sees +lazy imports inside functions too: those are dependencies all the same. Imports under +`if TYPE_CHECKING:` are skipped, because they never execute and so cannot make a lower layer +need a higher one at run time. + +A new module fails until it is placed in a tier, a new upward import fails until it is removed +or listed in `ALLOWED_UPWARD` with its reason, and a listed import that no longer exists fails +too, so the list cannot outlive what it excuses. PHP holds the same rule in LayerDirectionTest. +""" +from __future__ import annotations + +import ast +from pathlib import Path +from typing import Iterator + +SOURCE = Path(__file__).resolve().parents[1] / "src" / "packvium" + +#: Helpers every layer may use: no packing concept lives in them. +INFRASTRUCTURE = 0 +UNITS = 1 +DOMAIN = 2 +#: Constraints, algorithms, objectives, validation and extensions share one tier, as the +#: architecture's chain puts them side by side; request admission lives here too, since +#: fixed placements and the packer both call it. +ALGORITHMS = 3 +PACKER = 4 +SERIALIZATION = 5 +#: The Python-only intelligence surface: where the packing chain and commerce may meet. +ADAPTERS = 6 +FACADE = 7 +#: Commerce is its own root; see `COMMERCE_MAY_IMPORT`. +COMMERCE = -1 + +TIERS: dict[str, int] = { + **dict.fromkeys(("_compat", "_canonical_json", "_request_error", "orientations", "trace", + "spatial_index"), INFRASTRUCTURE), + "units": UNITS, + **dict.fromkeys(("geometry", "compression", "flat_bag", "hull", "models", "centre_of_mass", + "lattice_summary", "made_to_measure", "nesting", "pallet_overhang", "loads", + "axle_load", "ratios", "result", "contact", "support_polygon", "explain", + "config", "effort", + # The outcome ledger's value objects: revisions and the intelligence surface + # both record into it, and it imports nothing of the chain. + "outcomes"), DOMAIN), + **dict.fromkeys(("constraints", "bounds", "packing_sequence", "solvers", "extensions", + "validation", "result_validation", "fixed_placements", "policy", "rebalance", + "request_errors", "request_objects"), ALGORITHMS), + "packer": PACKER, + **dict.fromkeys(("serialization", "nested", "locks", "__main__", "artifacts", "execution", + "artifact_exports", "revisions", "revision_outcomes"), SERIALIZATION), + **dict.fromkeys(("recommendations", "simulation", "holdout", "pareto"), ADAPTERS), + "__init__": FACADE, + "commerce": COMMERCE, +} + +#: What commerce may read outside itself: two layer-free helpers, never a packing layer. +COMMERCE_MAY_IMPORT = {"_compat", "_canonical_json"} + +#: Upward imports that exist today, each with why it stays. Empty is the goal. +ALLOWED_UPWARD: dict[tuple[str, str], str] = {} + + +def _module_name(path: Path) -> str: + relative = path.relative_to(SOURCE).with_suffix("") + return relative.parts[0] if relative.parts[0] == "commerce" else ".".join(relative.parts) + + +def _type_checking_lines(tree: ast.Module) -> set[int]: + lines: set[int] = set() + for node in ast.walk(tree): + if isinstance(node, ast.If) and isinstance(node.test, ast.Name) and node.test.id == "TYPE_CHECKING": + for child in node.body: + lines.update(range(child.lineno, (child.end_lineno or child.lineno) + 1)) + return lines + + +def _imported_modules(path: Path) -> Iterator[str]: + """The top-level `packvium` module each import reaches, relative or absolute.""" + tree = ast.parse(path.read_text(encoding="utf-8")) + skipped = _type_checking_lines(tree) + package = list(path.relative_to(SOURCE).parent.parts) + for node in ast.walk(tree): + if getattr(node, "lineno", None) in skipped: + continue + if isinstance(node, ast.ImportFrom) and node.level: + base = package[:len(package) - node.level + 1] + names = [node.module] if node.module else [alias.name for alias in node.names] + for name in names: + parts = base + name.split(".") + target = parts[0] + yield "__init__" if not base and not node.module and target not in TIERS else target + elif isinstance(node, ast.ImportFrom) and node.module and node.module.split(".")[0] == "packvium": + parts = node.module.split(".")[1:] + if parts: + yield parts[0] + else: + for alias in node.names: + yield alias.name if alias.name in TIERS else "__init__" + elif isinstance(node, ast.Import): + for alias in node.names: + parts = alias.name.split(".") + if parts[0] == "packvium": + yield parts[1] if len(parts) > 1 else "__init__" + + +def _modules() -> dict[str, list[Path]]: + modules: dict[str, list[Path]] = {} + for path in sorted(SOURCE.rglob("*.py")): + modules.setdefault(_module_name(path), []).append(path) + return modules + + +def _upward_imports() -> set[tuple[str, str]]: + found: set[tuple[str, str]] = set() + for module, paths in _modules().items(): + tier = TIERS[module] + for path in paths: + for imported in _imported_modules(path): + if imported == module: + continue + target = TIERS[imported] + if tier == COMMERCE: + upward = imported not in COMMERCE_MAY_IMPORT + elif target == COMMERCE: + upward = tier < ADAPTERS + else: + upward = target > tier + if upward: + found.add((module, imported)) + return found + + +def test_every_module_is_placed_in_a_tier(): + unplaced = sorted(set(_modules()) - set(TIERS)) + assert not unplaced, f"place these modules in TIERS: {unplaced}" + + +def test_no_tier_names_a_module_that_does_not_exist(): + assert not sorted(set(TIERS) - set(_modules())) + + +def test_no_module_imports_a_higher_layer(): + unexplained = sorted(_upward_imports() - set(ALLOWED_UPWARD)) + assert not unexplained, f"upward imports (importer, imported): {unexplained}" + + +def test_every_allowed_upward_import_still_exists(): + stale = sorted(set(ALLOWED_UPWARD) - _upward_imports()) + assert not stale, f"remove these from ALLOWED_UPWARD: {stale}" + + +def test_absolute_import_checks_every_name_and_the_package_facade(tmp_path, monkeypatch): + monkeypatch.setitem(globals(), "SOURCE", tmp_path) + module = tmp_path / "units.py" + module.write_text( + "from packvium import models, solvers\nimport packvium\nfrom packvium import validate\n", + encoding="utf-8", + ) + assert list(_imported_modules(module)) == ["models", "solvers", "__init__", "__init__"] diff --git a/tests/test_made_to_measure.py b/tests/test_made_to_measure.py index 3930266..f26ee03 100644 --- a/tests/test_made_to_measure.py +++ b/tests/test_made_to_measure.py @@ -368,6 +368,8 @@ def test_each_request_error_names_its_rule(edit, reason, field, detail): def test_the_price_ceiling_admits_the_largest_box_exactly_at_the_limit(): data = request(inner_dimensions=mm(1000, 1000, 1000), cost_minor=0, made_to_measure={"minimum": mm(1000, 1000, 1000), "increment": mm(1, 1, 1)}) + # One cube opens one box, so only the per-box ceiling applies, not the summed one. + data["items"][0]["quantity"] = 1 # Six square metres: the largest price whose box stays within 2^53 - 1. data["containers"][0]["made_to_measure"]["cost_per_square_metre_minor"] = MAX_EXACT_INTEGER // 6 pack_from_dict(copy.deepcopy(data)) diff --git a/tests/test_optimality_bounds.py b/tests/test_optimality_bounds.py index 0cba954..16c6527 100644 --- a/tests/test_optimality_bounds.py +++ b/tests/test_optimality_bounds.py @@ -549,7 +549,10 @@ def test_a_score_below_its_bound_withholds_the_statement_rather_than_publishing_ @pytest.mark.parametrize('cheap_cost', [0, 1]) -def test_a_gap_past_the_portable_ceiling_withholds_only_the_statement(cheap_cost): +def test_a_cost_sum_past_the_portable_ceiling_is_refused_before_any_gap_is_stated(cheap_cost): + """A score past 2^53 - 1 used to reach the gap statement and have only the gap withheld. + refuses the worst-case summed cost at admission, so no admitted request has a gap + past the ceiling; the inclusive ceiling itself is pinned on `bounds.statement` below.""" request = { 'items': [{'id': 'i', 'quantity': 2, 'dimensions': dict.fromkeys(('length', 'width', 'height'), '10')}], 'containers': [ @@ -559,16 +562,9 @@ def test_a_gap_past_the_portable_ceiling_withholds_only_the_statement(cheap_cost 'cost_minor': bounds.MAX_BOUND_VALUE, 'max_items': 1}, ], } - result = packvium.pack_from_dict(request) - assert result['score'][2] == 2 * bounds.MAX_BOUND_VALUE - assert result['optimality'] == {'code': 'not_proven'} - assert packvium.validate(request, result) == [] - result['optimality'].update(lower_bound=[0, 2, 2 * cheap_cost], gap_key=2, - absolute_gap=result['score'][2] - 2 * cheap_cost) - if cheap_cost: - result['optimality']['relative_gap'] = { - 'numerator': result['optimality']['absolute_gap'], 'denominator': 2 * cheap_cost} - assert 'optimality_gap_mismatch' in [issue.code for issue in packvium.validate(request, result)] + with pytest.raises(packvium.InvalidRequestError) as caught: + packvium.pack_from_dict(request) + assert (caught.value.reason, caught.value.field) == ('above_maximum', '/containers') @pytest.mark.parametrize('least', [0, 1]) diff --git a/tests/test_packing_sequence.py b/tests/test_packing_sequence.py index 80bbb14..9b2fa2e 100644 --- a/tests/test_packing_sequence.py +++ b/tests/test_packing_sequence.py @@ -34,6 +34,7 @@ from packvium import (AxisAlignedBox, Container, Dimensions, Item, Length, Placement, Point, Rotation) +from packvium.geometry import ALL_DIRECTIONS from packvium.packing_sequence import ( InvalidDirectionError, LoadingDependencyGraph, @@ -945,3 +946,107 @@ def test_isolated_floor_step_among_many_floor_boxes_catches_exact_density_offend assert excinfo.value.step == 27 assert "stack_density_exceeded" in excinfo.value.reason + + +# -------------------------------------------------- removal search counts blockers + + +def _rescanning_removal_order(boxes, container, directions): + """The search before: restart at index 0 after every removal and test each box + again. Kept as the oracle the counted search must equal, as Rust keeps its own.""" + from packvium.packing_sequence import _clear_direction + + graph = UnloadingDependencyGraph.build(boxes) + present = frozenset(range(len(boxes))) + order = [] + while present: + chosen = next((index for index in range(len(boxes)) + if index in present and not (graph.depends_on[index] & present) + and _clear_direction(index, boxes[index], boxes, present, container, + directions) is not None), None) + if chosen is None: + raise SequenceError(present) + order.append(chosen) + present = present - {chosen} + replay_removal_order(boxes, container, order, directions) + return order + + +def _outcome(search, *args): + try: + return search(*args) + except SequenceError as error: + return ("stuck", sorted(error.stuck)) + except SequenceReplayError as error: + return ("replay", str(error)) + + +def test_the_counted_removal_search_answers_what_rescanning_would_on_mixed_scenes(): + rng = random.Random(0x2545F491) + direction_sets = [("+x",), ("+x", "+y"), ("-z", "+x"), ALL_DIRECTIONS, ()] + container = Dimensions.mm(60, 50, 40) + for round_ in range(400): + boxes = [box(rng.randrange(5) * 10, rng.randrange(4) * 10, rng.randrange(3) * 10, + 10 * (1 + rng.randrange(2)), 10 * (1 + rng.randrange(2)), 10) + for _ in range(1 + rng.randrange(14))] + directions = direction_sets[round_ % len(direction_sets)] + assert (_outcome(safe_removal_order, boxes, container, directions) + == _outcome(_rescanning_removal_order, boxes, container, directions)), round_ + + +def test_a_row_blocked_all_the_way_back_costs_quadratic_sweeps(monkeypatch): + """Sixty boxes in a row with one door: each removal unblocks only its neighbour. The + rescanning search tested every remaining box against the whole row on every step, + O(n^3); counted, each pair is swept a bounded number of times.""" + import packvium.packing_sequence as sequence + + tests = [0] + real = sequence.sweep_intersects + + def counting(sweep, other): + tests[0] += 1 + return real(sweep, other) + + monkeypatch.setattr(sequence, "sweep_intersects", counting) + boxes = [box(i * 10, 0, 0, 10, 10, 10) for i in range(60)] + order = safe_removal_order(boxes, Dimensions.mm(600, 10, 10), ("+x",)) + assert order == list(range(59, -1, -1)) + assert tests[0] <= 6 * 60 * 60 + + +def _rescanning_route_removal_order(boxes, stops, container, directions): + """`safe_route_removal_order` before, the oracle for the counted search.""" + from packvium.packing_sequence import _clear_direction + + graph = UnloadingDependencyGraph.build(boxes) + remaining = frozenset(range(len(boxes))) + order = [] + for stop in sorted({stop for stop in stops if stop is not None}): + due = frozenset(index for index in remaining if stops[index] == stop) + while due: + chosen = next((index for index in range(len(boxes)) + if index in due and not (graph.depends_on[index] & remaining) + and _clear_direction(index, boxes[index], boxes, remaining, container, + directions) is not None), None) + if chosen is None: + raise RouteSequenceError(stop, due) + order.append(chosen) + remaining, due = remaining - {chosen}, due - {chosen} + return order + + +def test_the_counted_route_search_answers_what_rescanning_would(): + rng = random.Random(0x1442695) + container = Dimensions.mm(60, 50, 40) + for round_ in range(300): + boxes = [box(rng.randrange(5) * 10, rng.randrange(4) * 10, rng.randrange(3) * 10, 10, 10, 10) + for _ in range(1 + rng.randrange(12))] + stops = [rng.choice((None, 0, 1, 2)) for _ in boxes] + directions = (("+x",), ("+x", "-y"), ALL_DIRECTIONS)[round_ % 3] + outcomes = [] + for search in (safe_route_removal_order, _rescanning_route_removal_order): + try: + outcomes.append(search(boxes, stops, container, directions)) + except RouteSequenceError as error: + outcomes.append((error.stop, sorted(error.stuck))) + assert outcomes[0] == outcomes[1], round_ diff --git a/tests/test_request_objects_corpus.py b/tests/test_request_objects_corpus.py index 89cd5d9..4250689 100644 --- a/tests/test_request_objects_corpus.py +++ b/tests/test_request_objects_corpus.py @@ -157,10 +157,12 @@ "holds the exact integer") for name in ( "item.weight", "item.max_top_load", "container.tare_weight", "container.max_payload", "container.max_stack_density", "container.made_to_measure.tare_per_square_metre")}, + "item-weight-json-number-beyond-i64": ("a JSON number past 2^53 - 1 is a rule of the JSON text; an object " + "holds the exact integer"), } #: Pinned, so the skip set cannot grow without this line changing too. -SKIPPED = 108 +SKIPPED = 109 @dataclass(frozen=True) diff --git a/tests/test_result_validation.py b/tests/test_result_validation.py index 2c948f0..e0610ef 100644 --- a/tests/test_result_validation.py +++ b/tests/test_result_validation.py @@ -488,3 +488,20 @@ def test_a_container_without_volume_counts_but_adds_no_unused_or_height_share() "container_type": "flat", "placements": [], "used_volume_ticks3": "0"}) assert [str(issue) for issue in validate(request, result) if issue.code == "score_mismatch"] == [ "score_mismatch: reported [0, 1, 0, 0, 1000000], recomputed [0, 2, 0, 0, 1000000]"] + + +def test_a_row_toward_one_door_unloads_nearest_first_and_validates(): + """Three crates due at one stop, in a row toward the only door. Each comes out + only once the one nearer the door has, which is the blocker count each removal lowers.""" + crate = {"quantity": 1, "stop_index": 0, "allowed_rotations": ["LWH"], + "dimensions": {"length": "100", "width": "100", "height": "100"}} + request = { + "configuration": {"solver_profile": "fast", "effort_budget": { + "max_candidates_evaluated": 100000, "max_placement_attempts": 100000, "max_search_nodes": 100000}}, + "items": [{"id": name, **crate} for name in ("a", "b", "c")], + "containers": [{"id": "van", "access_directions": ["+x"], + "inner_dimensions": {"length": "300", "width": "100", "height": "100"}}], + } + result = pack_from_dict(request) + assert len(result["containers"][0]["placements"]) == 3 + assert validate(request, result) == []