From a6c272bbedf29679a1322e578f0b42f4a6dc3c73 Mon Sep 17 00:00:00 2001 From: Anton Date: Sun, 18 Oct 2026 11:53:32 -0400 Subject: [PATCH] chore(release): 1.7.0 --- CHANGELOG.md | 59 ++ CITATION.cff | 2 +- Cargo.toml | 2 +- README.md | 40 +- codemeta.json | 2 +- docs/COMMERCE-API.md | 25 +- docs/GUARANTEES.md | 4 +- docs/PUBLIC-API.md | 102 ++-- docs/UNITS-AND-NUMERICS.md | 6 +- src/api.rs | 69 ++- src/fixed.rs | 5 +- src/lib.rs | 4 + src/model.rs | 15 +- src/policy.rs | 5 + src/request_errors.rs | 104 +++- src/result_validation/accounting.rs | 497 ++++++++++++++++ src/result_validation/container.rs | 803 ++++++++++++++++++++++++++ src/result_validation/facts.rs | 384 ++++++++++++ src/result_validation/geometry.rs | 308 ++++++++++ src/result_validation/json.rs | 610 +++++++++++++++++++ src/result_validation/lattice.rs | 326 +++++++++++ src/result_validation/mod.rs | 354 ++++++++++++ src/result_validation/nonprintable.rs | 725 +++++++++++++++++++++++ src/result_validation/num.rs | 433 ++++++++++++++ src/result_validation/objective.rs | 530 +++++++++++++++++ src/result_validation/pyfmt.rs | 210 +++++++ src/result_validation/spec.rs | 339 +++++++++++ src/result_validation/stacking.rs | 627 ++++++++++++++++++++ src/result_validation/units.rs | 164 ++++++ src/revisions.rs | 5 +- src/solver.rs | 9 + src/solvers/blocks.rs | 644 ++++++++++++++------- src/solvers/exact.rs | 5 +- src/solvers/extreme.rs | 361 +++++++++--- src/solvers/mod.rs | 2 + src/solvers/portfolio.rs | 430 ++++++++++++-- src/solvers/support_blocker.rs | 83 +++ src/spatial_index.rs | 100 ++++ src/units.rs | 11 + tests/constraints.rs | 132 +++++ tests/fixed_placements.rs | 2 +- tests/limit_reasons.rs | 26 + tests/registry_and_nested.rs | 185 ++++++ tests/request_errors.rs | 109 +++- tests/result_validation.rs | 300 ++++++++++ tests/result_validation_corpus.rs | 116 ++++ tests/search_scenarios.rs | 34 +- 47 files changed, 8848 insertions(+), 460 deletions(-) create mode 100644 src/result_validation/accounting.rs create mode 100644 src/result_validation/container.rs create mode 100644 src/result_validation/facts.rs create mode 100644 src/result_validation/geometry.rs create mode 100644 src/result_validation/json.rs create mode 100644 src/result_validation/lattice.rs create mode 100644 src/result_validation/mod.rs create mode 100644 src/result_validation/nonprintable.rs create mode 100644 src/result_validation/num.rs create mode 100644 src/result_validation/objective.rs create mode 100644 src/result_validation/pyfmt.rs create mode 100644 src/result_validation/spec.rs create mode 100644 src/result_validation/stacking.rs create mode 100644 src/result_validation/units.rs create mode 100644 src/solvers/support_blocker.rs create mode 100644 tests/result_validation.rs create mode 100644 tests/result_validation_corpus.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index b43d7e0..f41ff03 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,65 @@ What changed in `packvium` on crates.io, release by release. The format follows [Keep a Changelog](https://keepachangelog.com/1.1.0/) and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [1.7.0] + +The reference validator ships in the crate, `quality` looks ahead in its block solver and +finishes inside its time limit, and extreme points scan the candidate set they were meant to. +No request or result field changes. + +### Added + +- **`validate_json(request, result)` and `validate_json_outcome`**, with `ResultIssue`, + `MalformedResult { kind, message }` and `RefusalKind`: the reference validator over the JSON + text, returning the same issues, code and detail, in the same order, as every other package. + It shares no code with the solvers or `IndependentValidator`, which is unchanged. +- **`PlacementConstraint::distinguishes_instances`**, a defaulted trait method, `true` unless + overridden, so existing implementations compile and keep their behaviour. A constraint that + reads only item attributes may return `false` to let the portfolio drop a start order that + repeats another's item-type sequence. + +### Changed + +- **A `CandidateScorer` leads the extreme-point rank.** The rank is the tuple (sum of + scorer scores, far corner z, y, x, origin, rotation); before, a scorer's `score` was added to + one weighted sum of the far-corner ticks at the weight of one x tick. A scorer that returned + small nudges meant as tie-breaks now decides the rank; return 0 where it has no preference. + The trait's signature is unchanged, and no request without a custom scorer answers + differently on the measured corpora. +- **Every schema enum value is refused as `not_allowed`.** A value outside its list in + `allowed_rotations`, the output and dimensional-weight units, `shape_type`, + `ground_contact_rule` or `configuration.solvers` is `invalid_request` with reason `not_allowed` + at its JSON Pointer. An unknown output unit was copied through; **`ticks` as an output unit is + now refused**, as the schema always said. +- **`quality` looks ahead in the block solver**, completing its leading blocks greedily + and committing the best, so the answer is never worse than the greedy pass. On our benchmark + 85 of 89 answers improved and none got worse. Under a tight effort budget the block start can + now report `truncated` / `effort_limit`. +- **`quality` finishes inside its limit.** The staged beam refines the best greedy + order instead of the first two, and the spatial index stops at the first hit without + allocating. On the 22 pinned benchmark runs 1.6.0 needed more than 20 s of CPU on 10; this + release needs at most 8.1 s. +- **Extreme points scan the exposed corners and their projections**, not every + combination of placed faces. With `solvers: ["extreme_points"]` alone, over 67 benchmark + instances, `fast`/`balanced`/`quality` leave 2711/1477/1297 items out instead of + 3658/3048/2643. The full portfolio's answers did not change on the 89 benchmark requests, and + its `quality` CPU fell to 42%. +- **Portfolio starts go to distinct item orders.** A start that repeats another's + item-type sequence runs a neighbouring order instead, kept only on a strict win. A stacking + scene that took two containers now takes one. +- **`no_eligible_container` is reported `proven`, and `insufficient_support` is reported** + (`observed`) where the support rule is the only blocker. +- **A `nesting_height` not below the item's height is refused as `invalid_value`** at its + pointer, and with no `output` block the result is written in `units.length`'s schema code. + +### Fixed + +- **`incompatible_tags` is applied item against item**, not against container tags, as the + validator and every other engine apply it. +- **A panicking start fails a parallel portfolio** as it fails a sequential one; it was dropped. +- **Axle-balanced candidate points use the envelope length under clearance** and are not offered + twice. + ## [1.6.0] Boxes cut to measure, flat bags, stacking groups and a volume-first objective, and a fix for diff --git a/CITATION.cff b/CITATION.cff index cc88296..e2c0937 100644 --- a/CITATION.cff +++ b/CITATION.cff @@ -5,7 +5,7 @@ type: software authors: - name: "Packvium contributors" website: "https://packvium.com" -version: "1.6.0" +version: "1.7.0" license: MIT url: "https://packvium.com" repository-code: "https://github.com/toxakara/packvium-rust" diff --git a/Cargo.toml b/Cargo.toml index 4d78653..99ea093 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "packvium" -version = "1.6.0" +version = "1.7.0" edition = "2024" rust-version = "1.88" license = "MIT" diff --git a/README.md b/README.md index 05020e6..7ceae83 100644 --- a/README.md +++ b/README.md @@ -11,15 +11,21 @@ coordinates and rotations for each item, with a reason for anything that did not Full documentation, the constraint reference and benchmarks live at [packvium.com](https://packvium.com). -> **Version 1.6.0 — the public API is frozen.** Field names, status codes and the +> **Version 1.7.0 — the public API is frozen.** Field names, status codes and the > objective vector do not change without a major version, so any `1.x` is a safe upgrade > from any earlier `1.x`. > Read [docs/GUARANTEES.md](https://github.com/toxakara/packvium-rust/blob/main/docs/GUARANTEES.md) > before relying on a result. +```sh +cargo add packvium +``` + +or, in `Cargo.toml`: + ```toml [dependencies] -packvium = "1.5" +packvium = "1.7" ``` ## Quick start @@ -75,7 +81,7 @@ cargo run --example basic | --- | --- | | [`basic.rs`](https://github.com/toxakara/packvium-rust/blob/main/examples/basic.rs) | An order into a carton, read back into typed structs; an item that cannot fit, and why. | | [`constraints.rs`](https://github.com/toxakara/packvium-rust/blob/main/examples/constraints.rs) | Rotations and keep-upright, stacking limits and top load, support ratio and incompatible tags — each shown with and without the rule. | -| [`objectives.rs`](https://github.com/toxakara/packvium-rust/blob/main/examples/objectives.rs) | The six objectives, and the scenes where two of them pick different containers. | +| [`objectives.rs`](https://github.com/toxakara/packvium-rust/blob/main/examples/objectives.rs) | Six of the seven objectives (all but `maximum_volume`), and the scenes where two of them pick different containers. | | [`units.rs`](https://github.com/toxakara/packvium-rust/blob/main/examples/units.rs) | What you can type (fractions, inches, pounds), why nothing is a float, and exact fits. | | [`errors.rs`](https://github.com/toxakara/packvium-rust/blob/main/examples/errors.rs) | Branching on a refused request with `code()`, `reason()` and `field()`, and why an item that does not fit is not an error. | | [`trucking.rs`](https://github.com/toxakara/packvium-rust/blob/main/examples/trucking.rs) | A delivery van: stops unloaded in route order through a named door, and axle loads kept inside their ratings. | @@ -128,6 +134,25 @@ A request that is valid but does not fit completely is not an error. The result left out, and why, in `unpacked_items`, and `packvium_core::explain_reason` turns each reason code into a sentence. +## Checking a result + +*New in 1.7.0.* + +`validate_json` checks a result against the request it answers, from the JSON alone: geometry, +support and load, accounting, the result's facts and its score. It is the same reference +validator every Packvium package exports, so it returns the same issues, code and detail: + +```rust +let result = packvium_core::pack_json(request)?; +let issues = packvium_core::validate_json(request, &result)?; // empty: valid +for issue in &issues { + println!("{}: {}", issue.code, issue.detail); // e.g. collision: cube#1 with cube#2 in box#1 +} +``` + +It shares no code with the solvers, so it judges any engine's result, not only this crate's. A +result without the documented shape is `Err(MalformedResult { kind, message })`. + ## Determinism The same request gives the same placements: the only randomness is seeded from the request's @@ -150,8 +175,9 @@ of the request, so a different seed is a different, equally reproducible request floor-only, non-stackable, stack-count and top-load limits, minimum support ratio, tag incompatibility, clearance and rectangular obstacles; and for vehicles, route order by `stop_index`, unloading doors by `access_directions`, and two-axle load limits. -- **Six objectives.** Fewest containers, packaging cost, carrier-billable weight, carrier - rate cards, open-dimension height and value kept — each a vector of exact integers. +- **Seven objectives.** Fewest containers, packaging cost, carrier-billable weight, carrier + rate cards, open-dimension height, value kept and volume loaded — each a vector of exact + integers. - **A solver portfolio, not one algorithm.** Regular-grid, layer, extreme-point, maximal-space and bounded exact search, selected by problem shape and profile. - **Answers you can check.** Every solution is re-validated by logic independent of the @@ -205,7 +231,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.5"` | [packvium-rust](https://github.com/toxakara/packvium-rust) | +| Rust — [`packvium`](https://crates.io/crates/packvium) | `packvium = "1.7"` | [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) | @@ -228,7 +254,7 @@ CodeMeta form. @software{packvium_rust, author = {{Packvium contributors}}, title = {Packvium for Rust}, - version = {1.6.0}, + version = {1.7.0}, license = {MIT}, url = {https://packvium.com} } diff --git a/codemeta.json b/codemeta.json index 33e69d5..56a802a 100644 --- a/codemeta.json +++ b/codemeta.json @@ -3,7 +3,7 @@ "@type": "SoftwareSourceCode", "name": "Packvium for Rust", "description": "Deterministic 3D bin-packing and cartonization engine for pallets, containers, trucks and shipping cartons. Exact integer geometry, reproducible results.", - "version": "1.6.0", + "version": "1.7.0", "license": "https://spdx.org/licenses/MIT", "author": [ { diff --git a/docs/COMMERCE-API.md b/docs/COMMERCE-API.md index 6237164..7fcc53d 100644 --- a/docs/COMMERCE-API.md +++ b/docs/COMMERCE-API.md @@ -160,9 +160,11 @@ may carry only `tariffs`. Field-level rules: than leaving it to be inferred from which fields the payload happens to carry. - An omitted optional field and an explicit JSON `null` mean the same thing: absent. Writing `"minimum_charge_minor": null` is exactly writing nothing. -- Every integer is exact and, except where a model explicitly allows zero, positive. - The per-field bounds are the ones the models already enforce — see - CATALOG-VERSIONING.md and POLICY-RULES.md. +- Every integer is exact. Dimensions, an item's `weight_g`, `max_payload_g`, + `max_stack_height_mm` and `dimensional_weight_divisor` must be positive; `effective_at`, + `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. ### Input errors versus rejections @@ -322,13 +324,12 @@ original paths and re-export the relocated definitions, so every workspace test, against the exact same objects. There is one definition of `rate_tariff` in the Python tree, and the installed wheel contains it. `commerce/rating/objective.py` — the solver adapter — is untouched and stays a workspace module: it registers in-process scorer and -selector objects, which EXTENDING.md explains are deliberately not -cross-language features. +selector objects, which are deliberately not cross-language features: an in-process +object cannot cross the JSON boundary every other engine is driven through. ## Conformance standard -Held to the standard every other capability in this project is held to, per -TESTING-AND-RELEASE.md: +Held to the standard every other capability in this project is held to: - **Python and PHP: byte-identical.** Both are ports of one contract; canonical JSON (sorted keys, `,`/`:` separators, no trailing whitespace) of the result document must @@ -364,15 +365,15 @@ TESTING-AND-RELEASE.md: | `catalog_version_info` | `O(h + e log e)` | `O(e)` | The `e log e` term is sorting the three id lists; every other bound is a linear scan of -the relevant history. These match the bounds already published for the underlying -models in ALGORITHMS-AND-COMPLEXITY.md — the wrapper -adds parsing and serialization, both linear in the payload, and nothing else. +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. ## Limitations - The document is supplied by the caller. Nothing here fetches, scrapes or embeds any - real carrier's published rates; live rate-card ingestion is still out of scope and - still tracked in LIMITATIONS-AND-ROADMAP.md. + real carrier's published rates. Live rate-card ingestion exists, but in the carrier + connectors, not here: CARRIER-RATE-INGESTION.md builds a + table from a feed, and this API is handed the result like any other document. - `catalog_version_info` returns metadata and id lists, not the resolved master-data records. Exporting the full snapshot is a larger surface with its own wire-format question and is not part of this epic. diff --git a/docs/GUARANTEES.md b/docs/GUARANTEES.md index 1ee0c28..e0949d9 100644 --- a/docs/GUARANTEES.md +++ b/docs/GUARANTEES.md @@ -52,7 +52,7 @@ silently — if you need them, they belong in your own layer above this library. ## Status of this release -Version `1.6.0` freezes the public API. Field names, status codes, the objective +Version `1.7.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. @@ -61,7 +61,7 @@ What the freeze does not cover: which of several equally valid packings a solver returns. That is bounded by the objective vector, not by the placement list, and a minor release may return a different arrangement with the same or a better score. -The algorithm complexities documented in `ALGORITHMS-AND-COMPLEXITY.md` are asymptotic +The algorithm complexities Packvium states, in these docs and in the source, are asymptotic design bounds held by review, not per-release measurements. They are not a wall-clock performance contract either: constants, input shape and host all move the real number. Use them to choose a solver profile, not to predict a duration. diff --git a/docs/PUBLIC-API.md b/docs/PUBLIC-API.md index df8fd8c..a784f42 100644 --- a/docs/PUBLIC-API.md +++ b/docs/PUBLIC-API.md @@ -15,8 +15,7 @@ false` dominates. The engines expose the same two fields on their item type: Python `Item.stacking_group` / `Item.accepts_stacking_groups`, PHP trailing constructor parameters `$stackingGroup` / `$acceptsStackingGroups`, Rust `Item::stacking_group` / - `Item::accepts_stacking_groups`, and the TypeScript request type. See - STACKING-GROUPS.md. + `Item::accepts_stacking_groups`, and the TypeScript request type. - **Item geometry beyond the box.** `shape_type` is an enum — `rigid_cuboid` (the default), `convex_hull`, `compressible` — accompanied by `hull_vertices`, `compression_ratio` and `max_compression_pressure_kpa`. **A request that @@ -26,11 +25,12 @@ The two other values are rolling out one engine at a time, which is what the fields were reserved before the freeze for, and the rollout is finished: **all four engines implement - both**, and are held to byte-identical results on the shared fixtures. The one - recorded difference is the JavaScript fallback on a scene whose answer depends on item - ordering -- it makes a single ordering pass where the other three run a portfolio, so it can - pack validly but less densely; that is pinned in `conformance/native-quality-budget.json` - rather than left to drift. + both**. On the shared fixtures Python and PHP are held to byte-identical results, + Rust and JavaScript to valid results no worse than the native quality budget. The + JavaScript fallback runs its own, smaller portfolio (eight item orderings, one under `fast`, + and four solvers under `quality`), so on a scene whose answer depends on item ordering it can + pack validly but less densely; any such difference is pinned in + `conformance/native-quality-budget.json` rather than left to drift. Where they are implemented: a `convex_hull` item's collisions are decided by an exact integer separating-axis test rather than by its box, and its occupied volume is the hull's @@ -42,7 +42,6 @@ fast path. Hull coordinates are non-negative offsets from the corner of the item's own bounding box and are capped at 10^8 length ticks -- 6.25 m, beyond ordinary parcel sizes, and the bound that keeps the exact geometry inside a 64-bit integer everywhere it can be. - IRREGULAR-ITEMS.md is the model and states why. - `Container`: id, inner/outer dimensions, tare/payload, cost, inventory quantity, obstacles (each a union of one or more exact boxes — `additional_boxes` approximates a non-rectangular zone such as a wheel arch or tapered roof without @@ -75,7 +74,7 @@ parameter `$deformableBoundary` with `PackedContainer::achievedDimensions()` / `billedDimensions()`, Rust `Container::deformable_boundary: Option` with `PackedContainer::achieved_dimensions()` / `billed_dimensions()`, and the TypeScript request - type. See DEFORMABLE-CONTAINERS.md. + type. - **Made-to-measure containers.** `made_to_measure` (absent or `null`: a stock container) makes the container an on-demand box machine whose largest box is `inner_dimensions`: `minimum` and `increment` per axis (required; `minimum` equal to @@ -93,8 +92,7 @@ `invalid_value`. The engines expose it as Python `Container.made_to_measure` (a `packvium.MadeToMeasure`, last field), PHP the trailing constructor parameter `?MadeToMeasure $madeToMeasure` (`Packvium\Domain\MadeToMeasure`), Rust - `Container::made_to_measure: Option`, and the TypeScript request type. See - MADE-TO-MEASURE-CONTAINERS.md. + `Container::made_to_measure: Option`, and the TypeScript request type. - `PackingConfig`: solver profile, deadline, alternatives, deterministic seed, clearance, support threshold (`minimum_support_ratio`, default 0: support is not required, and an item may rest on nothing above the floor; set it above 0 to require that share of the @@ -104,7 +102,7 @@ that bounds all four stable implementations by counted work instead of wall-clock time. In code it is Python `packvium.EffortBudget`, PHP `Packvium\Config\EffortBudget` and Rust `packvium_core::EffortBudget`. `solvers` is an ordered list: every named strategy is run, stable ties prefer - the earlier name, and an unknown name is a structured error. The optional + the earlier name, and an unknown name is a structured error. The stable solver names are `grid`, `extreme_points`, `homogeneous_blocks`, `layer`, `maximal_spaces` and `exact_small`. `homogeneous_blocks` is the unrestricted solid-lattice quality strategy and safely delegates to `extreme_points` when a scene @@ -114,8 +112,7 @@ example, for multiple declared item types or a custom hard constraint); it does not silently return an empty lattice result. The optional `shipping_cost` objective accepts exact dimensional-weight divisor/unit inputs and ranks billable weight from the shipped container's outer dimensions. These fields - have identical semantics in all four implementations — see - ALGORITHMS-AND-COMPLEXITY.md. + have identical semantics in all four implementations. `require_placement_coordinates` (Python/PHP/Rust/JavaScript, default `true`) lets a caller trade per-item coordinates for speed and memory on a bulk single-item-type order: when `false` and `GridSolver`'s regular-lattice preconditions already hold (see the @@ -138,18 +135,18 @@ search with `invalid_fixed_placement`. Python `Packer.pack(items, containers, fixed_placements)` and PHP `Packer::pack($items, $containers, $fixedPlacements)` take `FixedPlacement` values; Rust takes them in `PackingRequest.fixed_placements`, and every - JSON entry point reads the field. PLAN-REVISIONS.md is the contract; - all four engines implement it. + JSON entry point reads the field; all four engines implement it. - `catalog_versions_used`: optional immutable catalog references resolved before packing. Each reference has exactly `catalog_id`, positive `version`, non-negative `published_at_epoch_ms`, and `content_digest`; catalog IDs are unique. Production packing uses a monotonic system clock. Test harnesses and deterministic simulations may inject a monotonic clock into Python `Packer(..., clock=...)`, PHP -`Packer(..., clock: ...)`, Rust `Deadline::with_clock(...)` with -`SolverRegistry::solve_with_deadline(...)`, or the JavaScript fallback's optional clock -argument. The callable returns an implementation-native monotonic value; it must never -move backwards. This is a testing seam, not a serialized request field. +`Packer(..., clock: ...)`, or Rust `Deadline::with_clock(...)` with +`SolverRegistry::solve_with_deadline(...)`. `@packvium/engine` exposes no clock: its +`pack(request)` takes the request alone. The callable returns an implementation-native +monotonic value; it must never move backwards. This is a testing seam, not a serialized +request field. ## Core output @@ -161,8 +158,7 @@ move backwards. This is a testing seam, not a serialized request field. alongside it. The pre-1.1.0 extension point remains open: closing the object would make a previously valid producer fail a 1.1.0 validator, which is a breaking change and therefore not legal in this minor release. No engine emits the reserved fields - yet, so `code` is still the only key any Packvium result carries. See - OPTIMALITY-CERTIFICATES.md; + yet, so `code` is still the only key any Packvium result carries; - legacy `status`: `optimal`, `feasible`, `best_found`, `time_limit`, `infeasible`, or `invalid_result`; - packed containers with exact coordinates, dimensions, rotations, and a `centre_of_mass_offset_ppm` — the weighted centre of mass's exact-integer Chebyshev @@ -174,7 +170,7 @@ move backwards. This is a testing seam, not a serialized request field. share the positive `denominator`; signed numerators intentionally expose a centre of mass outside the axle span instead of clipping it; - unpacked instances with reason codes, proof levels and rejection observations; -- objective score — a five-key lexicographic vector of exact integers, identical across every implementation (OBJECTIVE.md) — and solver statistics; +- objective score — a five-key lexicographic vector of exact integers, lower is better, computed by the same formula in every implementation — and solver statistics. Under the default objective the keys are `unpacked_count`, `container_count`, `total_cost_minor`, `unused_volume_ppm` (per container `floor((V - used) x 10^6 / V)` of inner volume `V`) and `stack_height_ppm` (per container `floor(top x 10^6 / H)` of inner height `H`); `configuration.objective` selects one of seven orderings (`default`, `lowest_cost`, `shipping_cost`, `lowest_landed_cost`, `open_dimension_height`, `maximum_value`, `maximum_volume`), and the result echoes it in `objective`; - the exact `catalog_versions_used` lineage from the request (an empty array when no catalog was involved), preserved by Python, PHP, Rust and JavaScript; - warnings and top-K alternatives. With `minimum_support_ratio` at its default 0, a result @@ -285,8 +281,7 @@ own `code` property): {"code": "invalid_direction", "direction": "sideways"} ``` -`conformance/scene/sequence-fixtures.json` pins this shape across all four languages; -see `docs/SERIALIZATION.md`. +A shared fixture pins this shape across all four languages. Sequence diagnostics use a separate canonical `SequenceWarning` DTO instead of putting caller-facing prose into an untyped string. Its four fields are stable in @@ -409,6 +404,12 @@ without turning a minor release into a parsing break. `status` remains for one compatibility cycle and is checked against the three facts. The alpha release emits no `proven_optimal` claim without a future proof/certificate. +`status: infeasible`, with `feasibility: infeasible` and `optimality: proven_infeasible`, is +emitted only when the portfolio ranks no result at all. A request whose every item is proven +unpackable is not that case: every engine answers `status: best_found`, `feasibility: +unknown` and `optimality: best_found`, with each item and its `proven` reason in +`unpacked_items`. Read `unpacked_items`, not `status`, to learn that nothing fits. + ## Portfolio termination `termination` describes the whole solver portfolio instead of copying one ambiguous @@ -457,8 +458,9 @@ The aggregate fields are derived only from `starts`. Exactly one record is selec clock, and `effort_limit` when the selected start stopped at a counted-work boundary. A truncated loser alone leaves the selected answer's code `complete`, while still making `all_required_starts_completed` false. The two algorithm limit flags preserve -the exact cause. -`winning_start_truncated || global_deadline_reached`. +the exact cause: one of `algorithm.time_limit_reached` and `algorithm.effort_limit_reached` +is true exactly when `winning_start_truncated || global_deadline_reached`, and +`global_deadline_reached` requires `time_limit_reached`. ## Rejection proof @@ -489,7 +491,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. | +| `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. | | `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. | @@ -510,6 +512,28 @@ load can only refuse an item a fresh container would take, so they all end there relieve the front one -- and both rank after the structural proofs, the deadline, the effort budget and `group_cannot_fit_together`. +## Result validation + +Every package can check a result against the request it answers with the same reference +validator, and gets the same issue list back: geometry, support and load, accounting, the +result's facts and its score, each issue a `code` and a `detail`, an empty list meaning +valid. A result without the documented shape is refused as `MalformedResult`, whose `kind` is +`contract` or `shape`. + +- Python: `packvium.validate(request, result)`, `packvium.MalformedResult`. +- Rust: `packvium_core::validate_json(request, result)` over JSON text, returning + `Vec` or `MalformedResult { kind, message }`; `validate_json_outcome` returns the + same as one JSON document for a binding. +- PyO3 (`packvium_native_rust`): `validate_json(request, result)` over JSON text, a list of + `{"code", "detail"}` dicts, `MalformedResult` (a `ValueError`) with `kind`. +- `@packvium/engine`: `validate(request, result)`, `MalformedResult`, and + `ValidatorUnavailableError` (`code: 'validator_unavailable'`) when the compiled addon is + absent, until the JavaScript fallback's port. +- `@packvium/browser`: `validate(request, result)`, a promise, `MalformedResult`. + +- PHP: `Packvium\Validation\validate(array $request, array $result)`, a `list` + (`code`, `detail`), `MalformedResult` with `kind`. + ## Commercial and control-plane API Three deterministic functions over one canonical JSON document -- a carrier quote, an @@ -546,8 +570,7 @@ request returns a result with a status rather than raising. A document derived from an already validated packing result: what to do first, why this carton, and what was not packed. It is a view, not a decision — it calls no solver and no -validator, and a test in each language asserts that. The contract is -EXECUTION-PLAN.md. +validator, and a test in each language asserts that. | Language | Entry point | | --- | --- | @@ -609,8 +632,7 @@ One portable document built from a validated result. It carries: of the solver record, and an honest replay level. It is exported as JSON, RFC 4180 CSV, or a self-contained printable HTML work order. Like the -plan it is a view, not a decision: no solver, validator, renderer or clock is called. The -contract is OPERATIONAL-ARTIFACTS.md. +plan it is a view, not a decision: no solver, validator, renderer or clock is called. | Language | Builder | Exports | | --- | --- | --- | @@ -645,8 +667,7 @@ An append-only, hash-chained record of what differed from an approved plan: a mi a substituted carton, an operator lock or a verified placement. Each revision derives the request the next plan solves; a replan is an ordinary solve of it, with locks and verified placements carried as `fixed_placements`. A revision is a pure function of its parent, the -approved operational artifact and its events, and calls no solver or clock. The contract is -PLAN-REVISIONS.md. +approved operational artifact and its events, and calls no solver or clock. | Language | Surface | | --- | --- | @@ -663,9 +684,8 @@ stopping at the first. Refusals use `invalid_revision`, `invalid_event`, `event_ ## Scenario and recommendation API Scenario what-if comparison and catalog/rule recommendation publication, exported as -`packvium.simulation` and `packvium.recommendations`. The full contract is -INTELLIGENCE-API.md; what belongs here is the surface and its two -limits, both of which are part of the API rather than notes about it. +`packvium.simulation` and `packvium.recommendations`. This section is the surface and its +two limits, both of which are part of the API rather than notes about it. | Language | Entry point | | --- | --- | @@ -677,7 +697,7 @@ document is proved by driving four engines as subprocesses over JSON. `run_scena an `OrderEvaluator` *callback* as its central argument, and a callback does not cross a pipe -- so the harness that proves the packing and commerce contracts cannot express a scenario at all. Whether the data-in/data-out half ever crosses runtimes is an open -question, not an omission; INTELLIGENCE-API.md scopes it. +question, not an omission. **Historical replay ships with the ledger it reads.** `evaluate_on_history` scores a recommendation against decisions held out by an explicit `split_at`, and could not be @@ -700,10 +720,10 @@ importing the submodule, which puts them outside the frozen API snapshot the pac commerce surfaces are held to. They work, they are tested, and they will not be withdrawn inside 1.x — but a parameter may be renamed or a returned value gain a field in a minor release, announced in the changelog rather than blocked by a gate. Pin the version if you -depend on the exact shape. COMPATIBILITY.md states why this one surface -is held that way and what would change it. +depend on the exact shape. ## JSON API Python, PHP, Rust and the JavaScript fallback accept the same top-level keys: `units`, -`configuration`, `items`, `containers`, `catalog_versions_used`, and `output`. +`configuration`, `items`, `containers`, `catalog_versions_used`, `policy`, `output` and +`fixed_placements`. diff --git a/docs/UNITS-AND-NUMERICS.md b/docs/UNITS-AND-NUMERICS.md index 272c4ee..fd1e6e6 100644 --- a/docs/UNITS-AND-NUMERICS.md +++ b/docs/UNITS-AND-NUMERICS.md @@ -20,7 +20,7 @@ Conversion supports floor, ceiling and ties-to-even nearest rounding. Applicatio ## Geometry versus scores -Feasibility checks are integer-only, including the support ratio: the requested fraction is converted once to parts per million and compared as `supported_area >= floor(base_area x ratio_ppm / 10^6)`, never as a float division against an epsilon. The independent validator rechecks boundaries and intersections using exact integers. +Feasibility checks are integer-only, including the support ratio: the requested fraction is converted once to parts per million, `ratio_ppm = floor(ratio x 10^6 + 0.5)` on the IEEE double the request carries (each step correctly rounded, so every language gets the same integer; on about one in a hundred seven-decimal halves it differs from rounding the exact decimal, `0.0001245` giving 124), and compared as `supported_area >= floor(base_area x ratio_ppm / 10^6)`, never as a float division against an epsilon. Every result validator applies this same rule rather than the exact rational. `void_fill_reserve_ratio` goes through the same conversion and reserves `floor(inner_volume x ratio_ppm / 10^6)` cubic ticks, which the validators recompute the same way. The independent validator rechecks boundaries and intersections using exact integers. The Rust solver and validator were the exception until 2026-09-02: both compared `area / base_area + 1e-12 < ratio` in `f64`. On a real-sized base (a square centimetre is `2.56 x 10^10` square ticks) an area one square tick short of the requirement sits well inside that epsilon, so Rust admitted a placement the shared validator refused. Both now go through `support_area_sufficient`, the rule above; the `f64` ratio survives only as the reported `support_ratio` on the placement record. @@ -33,7 +33,7 @@ Coordinates remain 64-bit integers. Values that exceed that range are handled wi | Quantity | Why it overflows | How it is handled | | --- | --- | --- | | Volume, for output and ordering | A one-metre cube is `4.096 x 10^21` cubic ticks | `BigInt::multiply`/`add`, compared as decimal integers; this includes exact-small's equal-count physical-volume tie-break | -| Objective keys 3 and 4 | Ratio of two volumes | `BigInt::subtract` / `BigInt::divide`, see OBJECTIVE.md | +| Objective keys 3 and 4 | `unused_volume_ppm`, per container `floor((V - used) x 10^6 / V)`, scales a volume by 10^6; `stack_height_ppm` is `floor(top x 10^6 / H)` | `BigInt::subtract` / `BigInt::divide` | | Load shares, `weight x area / total_area` | Eighth-microgram counts times squared ticks | `Arithmetic::mulDiv`, exact and overflow-free | | Serialized decimals | Ticks beyond `2^53` do not survive a `double` | long division on digits, rounded ties-to-even | @@ -46,7 +46,7 @@ converted back to a number only at the existing JSON boundary. ## The bound path's declared ceiling -`docs/OPTIMALITY-CERTIFICATES.md` defines lower bounds on the objective. Their arithmetic is +The engines compute lower bounds on the objective during search. Their arithmetic is integer-only, and the limit at which they refuse is **declared rather than inherited from the language**: every sum in that path must stay below `10^30`, and exceeding it is a structured refusal in all four engines rather than a number. diff --git a/src/api.rs b/src/api.rs index 1059a2f..89b5809 100644 --- a/src/api.rs +++ b/src/api.rs @@ -8,8 +8,9 @@ use crate::model::*; use crate::policy::{PolicyConstraint, PolicyRuleSet}; use crate::rebalance::rebalance_weight; use crate::request_errors; -use crate::solver::SolverRegistry; -use crate::units::{Length, Weight}; +use crate::solver::{PlacementConstraint, SolverRegistry}; +use crate::solvers::{SupportReplay, support_can_refuse}; +use crate::units::{Length, Weight, output_length_unit}; use crate::validation::IndependentValidator; use serde_json::{Map, Value}; use std::collections::{BTreeMap, BTreeSet}; @@ -423,6 +424,7 @@ pub fn pack_request_with_policy( }; let mut result = registry.solve(request)?; cite_policy_rejections(&mut result, request, policy); + cite_support_rejections(&mut result, request, ®istry.constraints); cite_limit_rejections(&mut result, request); result.catalog_versions_used = request.catalog_versions_used.clone(); // Independent validation re-derives every guarantee from per-item placements. @@ -548,6 +550,49 @@ fn cite_policy_rejections( } } +/// Names the support rules behind a `search_exhausted` or `exact_search_incomplete` item +/// when they alone refuse it a place in the finished layout, as Python and PHP do +/// before the limit diagnosis. Group members keep their reason, as for the limits. The +/// scenes are rebuilt only when an item a support rule can refuse is left out, and each item +/// type is replayed once: `O(P + T * S * K)` for P placements, T such types, S containers +/// and K one candidate scan. Alternatives too, for the reason `cite_policy_rejections` gives. +fn cite_support_rejections( + result: &mut PackingResult, + request: &PackingRequest, + constraints: &[Arc], +) { + for alternative in &mut result.alternatives { + cite_support_rejections(alternative, request, constraints); + } + let asked: Vec = (0..result.unpacked.len()) + .filter(|&index| { + let unpacked = &result.unpacked[index]; + unpacked.instance.item.group.is_none() + && matches!( + unpacked.reason.as_str(), + "search_exhausted" | "exact_search_incomplete" + ) + && support_can_refuse(&unpacked.instance.item, &request.config) + }) + .collect(); + if asked.is_empty() { + return; + } + let replay = SupportReplay::new(&result.containers, request, constraints); + let mut verdicts: BTreeMap = BTreeMap::new(); + for index in asked { + let instance = &result.unpacked[index].instance; + let blocked = *verdicts + .entry(instance.item.id.clone()) + .or_insert_with(|| replay.support_is_the_blocker(instance)); + if blocked { + let instance = instance.clone(); + result.unpacked[index] = + UnpackedItem::new(instance, "insufficient_support".into(), Vec::new()); + } + } +} + /// Names the container limit behind a `search_exhausted` or `exact_search_incomplete` /// item, with the rule and precedence every engine shares. Group /// members keep their reason, as the group check ranks first in the other engines. @@ -945,7 +990,7 @@ fn parse_request(object: &Map) -> PackResult { .and_then(Value::as_object) .and_then(|output| output.get("length_unit")) .and_then(Value::as_str) - .unwrap_or(length_unit) + .unwrap_or_else(|| output_length_unit(length_unit)) .to_owned(); let output_weight_unit = object .get("output") @@ -1139,7 +1184,7 @@ fn parse_config(value: Option<&Value>, length_unit: &str) -> PackResult usize { usize::try_from(value).unwrap_or(usize::MAX) } -fn u64_field(map: &Map, key: &str, default: u64) -> u64 { - map.get(key).and_then(Value::as_u64).unwrap_or(default) +/// The request's `seed`, negative ones included; 42 only when none is given. +/// +/// A seed past `i64::MAX` is kept as its residue modulo `SEED_MODULUS`, the only part of +/// it any engine's shuffle reads, so it still draws the orders Python and PHP draw. +fn seed_field(map: &Map) -> i64 { + let Some(seed) = map.get("seed") else { + return 42; + }; + seed.as_i64() + .or_else(|| { + seed.as_u64() + .map(|seed| (seed % SEED_MODULUS.unsigned_abs()) as i64) + }) + .unwrap_or(42) } fn string_set(value: Option<&Value>) -> BTreeSet { diff --git a/src/fixed.rs b/src/fixed.rs index 9e289b5..871b3d9 100644 --- a/src/fixed.rs +++ b/src/fixed.rs @@ -106,7 +106,10 @@ fn entry_shape_fault(entry: &Value, place: &str, field: &str, unit: &str) -> Opt .is_some_and(|orientation| ORIENTATIONS.contains(&orientation)) { return fault( - format!("{place}.orientation is one of the six codes"), + format!( + "{place}.orientation must be one of {}", + spell_names(&ORIENTATIONS) + ), &format!("{field}/orientation"), ); } diff --git a/src/lib.rs b/src/lib.rs index da60298..5de000e 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -22,6 +22,7 @@ mod nested; mod policy; mod rebalance; mod request_errors; +pub mod result_validation; pub mod revisions; mod sequence; mod solver; @@ -49,6 +50,9 @@ pub use model::{ pub use nested::{NestedLevel, NestedPackingRequest, NestedPackingResult, pack_nested}; pub use policy::{PolicyConstraint, PolicyRule, PolicyRuleSet, RuleForm, ShipmentContext}; pub use rebalance::{RebalanceResult, WeightMove, rebalance_weight}; +pub use result_validation::{ + MalformedResult, RefusalKind, ResultIssue, validate_json, validate_json_outcome, +}; pub use sequence::{ ALL_DIRECTIONS, LoadingDependencyGraph, Reachability, SequenceError, SequenceStep, SequenceWarning, UnloadingDependencyGraph, placement_reachability, replay_loading_order, diff --git a/src/model.rs b/src/model.rs index 9e5be2f..51a5311 100644 --- a/src/model.rs +++ b/src/model.rs @@ -54,12 +54,17 @@ impl EffortBudget { } } +/// The modulus Python's and PHP's `DeterministicRandom` reduce a seed by. +pub const SEED_MODULUS: i64 = 1 << 31; + #[derive(Clone, Debug)] pub struct PackingConfig { pub profile: SolverProfile, pub time_limit_ms: u64, pub top_k: usize, - pub seed: u64, + /// Any integer: only its residue modulo [`SEED_MODULUS`] steers a shuffle, as in Python + /// and PHP, so `-7` and `2_147_483_641` draw the same orders. + pub seed: i64, pub max_containers: Option, pub clearance: Length, pub minimum_support_ratio: f64, @@ -1353,6 +1358,7 @@ impl ReasonProof { reason, "no_compatible_container_dimensions" | "payload_exceeded" + | "no_eligible_container" | "rotation_restricted" | "policy_rule" ) { @@ -1361,7 +1367,10 @@ impl ReasonProof { "unknown_due_to_limit" } else if matches!( reason, - "no_feasible_placement" | "search_exhausted" | "exact_search_incomplete" + "no_feasible_placement" + | "search_exhausted" + | "exact_search_incomplete" + | "insufficient_support" ) { "observed" } else { @@ -1548,7 +1557,7 @@ pub struct AlgorithmReport { pub profile: String, pub solver: String, pub duration_ms: u64, - pub seed: u64, + pub seed: i64, pub time_limit_reached: bool, pub effort_limit_reached: bool, pub candidates_evaluated: u64, diff --git a/src/policy.rs b/src/policy.rs index c0c5eb5..99d6ec2 100644 --- a/src/policy.rs +++ b/src/policy.rs @@ -421,6 +421,11 @@ impl PlacementConstraint for PolicyConstraint { } ConstraintDecision::allow() } + + /// Every rule reads the item's tags and the container's contents, never the instance. + fn distinguishes_instances(&self) -> bool { + false + } } fn tag_counts<'a>(context: &SolverContext<'a>) -> BTreeMap<&'a str, usize> { diff --git a/src/request_errors.rs b/src/request_errors.rs index 0a5bbf7..a6780c5 100644 --- a/src/request_errors.rs +++ b/src/request_errors.rs @@ -3,11 +3,11 @@ //! A caller who sends a malformed request needs to know which value is wrong and why, in a //! form a program can branch on, and the four engines must say it identically. So the first //! violation is refused as a [`RequestError`] naming a reason from a closed set and the JSON -//! Pointer of the value, in the order every engine walks: units, configuration, items, -//! containers. The Python reference (`packvium/request_errors.py`) is the source of truth for +//! Pointer of the value, in the order every engine walks: units, output, configuration, +//! items, containers. The Python reference (`packvium/request_errors.py`) is the source of truth for //! every rule, pointer and text here; a cross-engine suite holds this engine to it. -use crate::canonical_json::{MAX_EXACT_MAGNITUDE, json_integer, json_spelling}; +use crate::canonical_json::{MAX_EXACT_MAGNITUDE, json_integer, json_spelling, spell_names}; use crate::error::RequestError; use crate::fixed::unknown_keys; use crate::made_to_measure::MadeToMeasure; @@ -28,6 +28,20 @@ const OBJECTIVES: [&str; 7] = [ "maximum_volume", ]; const ACCESS_DIRECTIONS: [&str; 6] = ["+x", "-x", "+y", "-y", "+z", "-z"]; +// The schema's closed vocabularies, each refused as `not_allowed` like the two above. +const SOLVERS: [&str; 6] = [ + "grid", + "extreme_points", + "homogeneous_blocks", + "layer", + "maximal_spaces", + "exact_small", +]; +const ROTATIONS: [&str; 6] = ["LWH", "LHW", "WLH", "WHL", "HLW", "HWL"]; +const LENGTH_UNITS: [&str; 5] = ["mm", "cm", "m", "in", "ft"]; +const WEIGHT_UNITS: [&str; 5] = ["mg", "g", "kg", "oz", "lb"]; +const GROUND_CONTACT_RULES: [&str; 4] = ["free", "covered", "single", "multiple"]; +const SHAPE_TYPES: [&str; 3] = ["rigid_cuboid", "convex_hull", "compressible"]; const CONFIGURATION_INTEGERS: [(&str, i64); 10] = [ ("time_limit_ms", 1), ("alternatives", 1), @@ -78,6 +92,7 @@ const AXES: [&str; 3] = ["x", "y", "z"]; pub(crate) fn check_request(data: &Value) -> Checked<&str> { let request = object(data, "")?; let unit = check_units(request.get("units"))?; + check_output(request.get("output"))?; check_configuration(request.get("configuration"), unit)?; let items = required_list(request, "items", "")?; for (index, raw) in items.iter().enumerate() { @@ -112,6 +127,19 @@ fn check_units(raw: Option<&Value>) -> Checked<&str> { } } +fn check_output(raw: Option<&Value>) -> Checked { + let Some(raw) = present(raw) else { + return Ok(()); + }; + let output = object(raw, "/output")?; + optional(output, "length_unit", "/output", |value, field| { + one_of(value, field, &LENGTH_UNITS) + })?; + optional(output, "weight_unit", "/output", |value, field| { + one_of(value, field, &WEIGHT_UNITS) + }) +} + fn check_configuration(raw: Option<&Value>, unit: &str) -> Checked { let Some(raw) = present(raw) else { return Ok(()); @@ -125,6 +153,21 @@ fn check_configuration(raw: Option<&Value>, unit: &str) -> Checked { optional(configuration, "objective", at, |value, field| { one_of(value, field, &OBJECTIVES) })?; + optional(configuration, "solvers", at, |value, field| { + each_one_of(value, field, &SOLVERS) + })?; + optional( + configuration, + "dimensional_weight_length_unit", + at, + |value, field| one_of(value, field, &LENGTH_UNITS), + )?; + optional( + configuration, + "dimensional_weight_weight_unit", + at, + |value, field| one_of(value, field, &WEIGHT_UNITS), + )?; for (name, minimum) in CONFIGURATION_INTEGERS { optional(configuration, name, at, |value, field| { integer(value, field, minimum) @@ -168,7 +211,8 @@ fn check_item(raw: &Value, at: &str, unit: &str) -> Checked { })?; } optional(item, "nesting_height", at, |value, field| { - measure(value, field, MeasureKind::Length, unit) + measure(value, field, MeasureKind::Length, unit)?; + nesting_below_height(value, field, item, unit) })?; for (name, minimum) in [ ("max_stacked_items", 1), @@ -192,9 +236,41 @@ fn check_item(raw: &Value, at: &str, unit: &str) -> Checked { stacking_group_name(name, &join(field, &index.to_string()))?; } Ok(()) + })?; + optional(item, "allowed_rotations", at, |value, field| { + each_one_of(value, field, &ROTATIONS) + })?; + optional(item, "ground_contact_rule", at, |value, field| { + one_of(value, field, &GROUND_CONTACT_RULES) + })?; + optional(item, "shape_type", at, |value, field| { + one_of(value, field, &SHAPE_TYPES) }) } +/// A nested copy sinks by less than its own height, or it would vanish into the one below +///. Both measures have passed their own rules already. O(1). +fn nesting_below_height( + value: &Value, + field: &str, + item: &Map, + unit: &str, +) -> Checked { + let ticks = |value: &Value| measure_ticks(value, unit, MeasureKind::Length).ok(); + let height = item + .get("dimensions") + .and_then(|sides| sides.get("height")) + .and_then(ticks); + match (ticks(value), height) { + (Some(nesting), Some(height)) if nesting >= height => Err(RequestError::new( + "invalid_value", + field, + "must be less than the item's height", + )), + _ => Ok(()), + } +} + fn stacking_group_name(value: &Value, field: &str) -> Checked { match value.as_str() { None => Err(wrong_type(field, "must be a string")), @@ -546,28 +622,24 @@ fn one_of(value: &Value, field: &str, allowed: &[&str]) -> Checked { if value.as_str().is_some_and(|item| allowed.contains(&item)) { return Ok(()); } - let allowed_values = allowed - .iter() - .map(|item| Value::String((*item).to_owned())) - .collect(); Err(RequestError::new( "not_allowed", field, - format!( - "must be one of {}", - json_spelling(&Value::Array(allowed_values)) - ), + format!("must be one of {}", spell_names(allowed)), )) } -fn access_directions(raw: &Value, at: &str) -> Checked { - let directions = list(raw, at)?; - for (index, direction) in directions.iter().enumerate() { - one_of(direction, &join(at, &index.to_string()), &ACCESS_DIRECTIONS)?; +fn each_one_of(raw: &Value, at: &str, allowed: &[&str]) -> Checked { + for (index, value) in list(raw, at)?.iter().enumerate() { + one_of(value, &join(at, &index.to_string()), allowed)?; } Ok(()) } +fn access_directions(raw: &Value, at: &str) -> Checked { + each_one_of(raw, at, &ACCESS_DIRECTIONS) +} + /// A measure is an integer, a string or `{value, unit}`, in a known unit, and never negative. fn measure(value: &Value, field: &str, kind: MeasureKind, unit: &str) -> Checked { match value { diff --git a/src/result_validation/accounting.rs b/src/result_validation/accounting.rs new file mode 100644 index 0000000..04f16f4 --- /dev/null +++ b/src/result_validation/accounting.rs @@ -0,0 +1,497 @@ +//! The summary, the item accounting, and the proof behind every unpacked reason. + +use std::cmp::Ordering; + +use super::Issue; +use super::geometry::ROTATIONS; +use super::json::{EMPTY_STR, Json, Ordered, Res}; +use super::num::{add, mul}; +use super::pyfmt::{py_repr, py_str, str_repr}; +use super::spec::{ContainerSpec, ItemSpec, rotation_axes}; + +pub(crate) fn check_structure(result: &Json, issues: &mut Vec) -> Res<()> { + let summary = result.at("summary")?; + let containers = result.at("containers")?.list("result.containers")?; + let mut packed = 0usize; + for container in containers { + packed += container.at("placements")?.list("placements")?.len(); + } + let unpacked = result + .at("unpacked_items")? + .list("result.unpacked_items")? + .len(); + for (field, actual) in [ + ("container_count", containers.len()), + ("packed_item_count", packed), + ("unpacked_item_count", unpacked), + ] { + let reported = summary.at(field)?; + if !reported.eq_int(actual as i128) { + issues.push(Issue::new( + "summary_mismatch", + format!("{field} {} != {actual}", py_str(reported)), + )); + } + } + let complete = result.at("complete")?; + if !complete.eq_int(i128::from(unpacked == 0)) { + issues.push(Issue::new( + "complete_mismatch", + format!("complete={} with {unpacked} unpacked", py_str(complete)), + )); + } + Ok(()) +} + +/// Participating `require_container_tag` rules, resolved from the request alone -- a second +/// implementation of docs/POLICY-RULES.md, so a resolution bug shared with an engine cannot +/// hide behind agreement with it. +pub(crate) fn container_tag_rules(request: &Json) -> Res> { + let policy = request.get_null("policy")?; + if !policy.is_dict() { + return Ok(Vec::new()); + } + let declared = policy.get_null("rules")?; + let Json::List(declared) = declared else { + return Ok(Vec::new()); + }; + if declared.is_empty() { + return Ok(Vec::new()); + } + let Some(as_of) = policy.get_null("as_of")?.py_int_instance() else { + return Ok(Vec::new()); + }; + let empty = Json::Dict(Vec::new()); + let shipment = policy.get_null("shipment")?; + let shipment = if shipment.truthy() { shipment } else { &empty }; + let zero = Json::Int(0); + let mut latest: Ordered = Ordered::default(); + for rule in declared { + if !rule.is_dict() || !rule.has("require_container_tag") { + continue; + } + let applies_to = rule.get_null("applies_to")?; + let applies_to = if applies_to.truthy() { + applies_to + } else { + &empty + }; + let pairs = applies_to.as_dict().ok_or_else(|| { + super::MalformedResult::shape("applies_to must be an object".to_owned()) + })?; + let mut applies = true; + for (fact, value) in pairs { + if !shipment.get_null(fact)?.py_eq(value) { + applies = false; + break; + } + } + if !applies { + continue; + } + if rule + .get_or("effective_at", &zero)? + .py_cmp(&Json::Int(as_of))? + == Ordering::Greater + { + continue; + } + let id = rule.get_null("id")?; + let newer = match latest.get(id)? { + None => true, + Some(current) => { + let mine = Json::List(vec![ + rule.get_or("effective_at", &zero)?.clone(), + rule.get_or("version", &zero)?.clone(), + ]); + let theirs = Json::List(vec![ + current.get_or("effective_at", &zero)?.clone(), + current.get_or("version", &zero)?.clone(), + ]); + mine.py_cmp(&theirs)? == Ordering::Greater + } + }; + if newer { + latest.insert(id, rule.clone())?; + } + } + Ok(latest.values().cloned().collect()) +} + +pub(crate) struct Context<'a> { + pub(crate) items: &'a Ordered, + pub(crate) containers: &'a Ordered, + pub(crate) clearance: i128, + pub(crate) rules: &'a [Json], +} + +pub(crate) fn check_accounting( + result: &Json, + context: &Context<'_>, + issues: &mut Vec, +) -> Res<()> { + let mut seen: Ordered<()> = Ordered::default(); + let mut per_type: Ordered = Ordered::default(); + let count = |per_type: &mut Ordered, item_type: &Json| -> Res<()> { + let next = per_type.get(item_type)?.copied().unwrap_or(0) + 1; + per_type.insert(item_type, next) + }; + for container in result.at("containers")?.list("result.containers")? { + for placement in container.at("placements")?.list("placements")? { + let item_id = placement.at("item_id")?; + if seen.contains(item_id)? { + issues.push(Issue::new("duplicate_item", py_str(item_id))); + } + seen.insert(item_id, ())?; + count(&mut per_type, placement.at("item_type")?)?; + } + } + let algorithm = result.at("algorithm")?; + let timed_out = algorithm.at("time_limit_reached")?.truthy(); + let effort_limited = algorithm.at("effort_limit_reached")?.truthy(); + for unpacked in result.at("unpacked_items")?.list("result.unpacked_items")? { + let item_id = unpacked.at("item_id")?; + if seen.contains(item_id)? { + issues.push(Issue::new( + "duplicate_item", + format!("{} is both packed and unpacked", py_str(item_id)), + )); + } + seen.insert(item_id, ())?; + let item_type = unpacked.at("item_type")?; + count(&mut per_type, item_type)?; + if !unpacked.get_null("reason")?.truthy() { + issues.push(Issue::new("missing_reason", py_str(item_id))); + } + let spec = context.items.get(unpacked.at("item_type")?)?; + check_reason_proof(unpacked, spec, context, timed_out, effort_limited, issues)?; + } + + for (item_type, count) in per_type.iter() { + match context.items.get(item_type)? { + None => issues.push(Issue::new("unknown_item", py_str(item_type))), + Some(spec) if !spec.quantity.eq_int(*count) => issues.push(Issue::new( + "quantity_mismatch", + format!( + "{}: {count} accounted for, {} requested", + py_str(item_type), + py_str(&spec.quantity) + ), + )), + Some(_) => {} + } + } + for (item_type, spec) in context.items.iter() { + if !per_type.contains(item_type)? { + issues.push(Issue::new( + "quantity_mismatch", + format!( + "{}: 0 accounted for, {} requested", + py_str(item_type), + py_str(&spec.quantity) + ), + )); + } + } + Ok(()) +} + +/// Whether one envelope of this size fits the empty container: its frame and, for a flat bag, +/// both girth sums with the envelope alone at the origin. +pub(crate) fn fits_empty(container: &ContainerSpec, size: [i128; 3]) -> Res { + if (0..3).any(|axis| size[axis] > container.inner[axis]) { + return Ok(false); + } + Ok(!container.flat_bag + || (add(size[0], size[2])? <= container.inner[0] + && add(size[1], size[2])? <= container.inner[1])) +} + +/// `any(_fits_empty(container, rotated envelope) for container ... for rotation ...)`, +/// stopping at the first fit as Python's generator does, so an unknown rotation is only an +/// error when the search reaches it. +fn fits_some(spec: &ItemSpec, context: &Context<'_>, rotations: &[Json]) -> Res { + let margin = mul(2, context.clearance)?; + for container in context.containers.values() { + for rotation in rotations { + let axes = rotation_axes(rotation.text("a rotation")?)?; + let size = [ + add(spec.dimensions[axes[0]], margin)?, + add(spec.dimensions[axes[1]], margin)?, + add(spec.dimensions[axes[2]], margin)?, + ]; + if fits_empty(container, size)? { + return Ok(true); + } + } + } + Ok(false) +} + +const PROVEN: [&str; 5] = [ + "no_compatible_container_dimensions", + "payload_exceeded", + "no_eligible_container", + "rotation_restricted", + "policy_rule", +]; +const LIMITED: [&str; 2] = ["time_limit", "effort_limit"]; +const OBSERVED: [&str; 4] = [ + "no_feasible_placement", + "search_exhausted", + "exact_search_incomplete", + "insufficient_support", +]; + +fn check_reason_proof( + unpacked: &Json, + spec: Option<&ItemSpec>, + context: &Context<'_>, + timed_out: bool, + effort_limited: bool, + issues: &mut Vec, +) -> Res<()> { + let item_id = py_str(unpacked.get_or("item_id", &Json::str_of("?"))?); + let reason = unpacked.get_or("reason", &EMPTY_STR)?; + let proof = unpacked.get_null("proof")?; + if !proof.is_dict() { + issues.push(Issue::new("missing_reason_proof", item_id)); + return Ok(()); + } + reason.hash_key()?; + let is = |names: &[&str]| names.iter().any(|name| reason.is_str(name)); + let expected = if is(&PROVEN) { + "proven" + } else if is(&LIMITED) { + "unknown_due_to_limit" + } else if is(&OBSERVED) { + "observed" + } else { + "inferred" + }; + let level = proof.get_null("level")?; + if !level.is_str(expected) { + issues.push(Issue::new( + "reason_proof_mismatch", + format!( + "{item_id}: {} has proof {}, expected {}", + py_repr(reason), + py_repr(level), + str_repr(expected) + ), + )); + } + if reason.is_str("time_limit") && !timed_out { + issues.push(Issue::new( + "reason_limit_mismatch", + format!("{item_id}: time_limit reason without a reached time limit"), + )); + } + if reason.is_str("effort_limit") && !effort_limited { + issues.push(Issue::new( + "reason_limit_mismatch", + format!("{item_id}: effort_limit reason without a reached effort limit"), + )); + } + if let Some(spec) = spec { + check_proven_reason(unpacked, reason, spec, context, &item_id, issues)?; + } + check_observations(proof, reason, &item_id, issues) +} + +fn check_proven_reason( + unpacked: &Json, + reason: &Json, + spec: &ItemSpec, + context: &Context<'_>, + item_id: &str, + issues: &mut Vec, +) -> Res<()> { + let own = &spec.allowed_rotations; + let every: Vec = ROTATIONS + .iter() + .map(|(code, _)| Json::str_of(code)) + .collect(); + let every = &every; + let invalid = |detail: String| Issue::new("invalid_proven_reason", detail); + + if reason.is_str("no_compatible_container_dimensions") { + if fits_some(spec, context, own)? { + issues.push(invalid(format!( + "{item_id}: at least one allowed orientation fits a container" + ))); + } + if fits_some(spec, context, every)? { + issues.push(invalid(format!( + "{item_id}: fits at least one container once every rotation is tried, not only its own allowed set -- should be rotation_restricted" + ))); + } + } + if reason.is_str("rotation_restricted") { + if fits_some(spec, context, own)? { + issues.push(invalid(format!( + "{item_id}: already fits a container within its own allowed rotations" + ))); + } + if !fits_some(spec, context, every)? { + issues.push(invalid(format!( + "{item_id}: does not fit any container even with every rotation tried -- should be no_compatible_container_dimensions" + ))); + } + } + if reason.is_str("payload_exceeded") + && context.containers.values().any(|container| { + container + .max_payload + .is_none_or(|limit| spec.weight <= limit) + }) + { + issues.push(invalid(format!( + "{item_id}: its weight is within at least one container payload limit" + ))); + } + if reason.is_str("no_eligible_container") + && context.containers.values().any(|container| { + spec.eligible_container_tags.is_empty() + || !spec.eligible_container_tags.is_disjoint(&container.tags) + }) + { + issues.push(invalid(format!( + "{item_id}: at least one container satisfies its eligible tags" + ))); + } + if reason.is_str("policy_rule") { + check_policy_citation(unpacked, spec, context, item_id, issues)?; + } + Ok(()) +} + +/// Two claims, both checked: that some rule rules this item out of every container, and that +/// the rule the result *names* is that rule. +fn check_policy_citation( + unpacked: &Json, + spec: &ItemSpec, + context: &Context<'_>, + item_id: &str, + issues: &mut Vec, +) -> Res<()> { + let mut blocking = Vec::new(); + for rule in context.rules { + let requirement = rule.at("require_container_tag")?; + let item_tag = requirement.get_null("item_tag")?; + if !holds(&spec.tags, item_tag)? { + continue; + } + let mut admitted = false; + for container in context.containers.values() { + if holds( + &container.tags, + rule.at("require_container_tag")? + .get_null("container_tag")?, + )? { + admitted = true; + break; + } + } + if !admitted { + blocking.push(rule); + } + } + if blocking.is_empty() { + issues.push(Issue::new( + "invalid_proven_reason", + format!("{item_id}: no participating policy rule rules it out of every container"), + )); + return Ok(()); + } + let details = unpacked.get_null("details")?; + let cited = if details.truthy() { + details + .list("details")? + .iter() + .map(|detail| detail.text("details").map(str::to_owned)) + .collect::>>()? + .join(" ") + } else { + String::new() + }; + let mut named = false; + for rule in blocking { + if cited.contains(&format!( + "{}@{}", + py_str(rule.at("id")?), + py_str(rule.at("version")?) + )) { + named = true; + break; + } + } + if !named { + issues.push(Issue::new( + "invalid_proven_reason", + format!( + "{item_id}: cites {}, which names no rule that actually blocks it", + str_repr(&cited) + ), + )); + } + Ok(()) +} + +/// `value in tags` for a frozenset of strings; an unhashable value is Python's `TypeError`. +pub(crate) fn holds(tags: &std::collections::BTreeSet, value: &Json) -> Res { + value.hash_key()?; + Ok(matches!(value, Json::Str(tag) if tags.contains(tag))) +} + +fn check_observations( + proof: &Json, + reason: &Json, + item_id: &str, + issues: &mut Vec, +) -> Res<()> { + let observations = match proof.get_null("observations")? { + Json::List(observations) if !observations.is_empty() => observations, + _ => { + issues.push(Issue::new( + "missing_reason_observations", + item_id.to_owned(), + )); + return Ok(()); + } + }; + let mut observed_reason = false; + for observation in observations { + if !observation.is_dict() { + issues.push(Issue::new( + "malformed_reason_observation", + item_id.to_owned(), + )); + continue; + } + let code = observation.get_null("code")?; + let well_formed = matches!(code, Json::Str(text) if !text.is_empty()) + && observation + .get_null("count")? + .py_int_instance() + .is_some_and(|count| count >= 1) + && matches!(observation.get_null("details")?, Json::List(_)); + if !well_formed { + issues.push(Issue::new( + "malformed_reason_observation", + item_id.to_owned(), + )); + continue; + } + if code.py_eq(reason) { + observed_reason = true; + } + } + if !observed_reason { + issues.push(Issue::new( + "reason_observation_mismatch", + format!("{item_id}: {}", py_str(reason)), + )); + } + Ok(()) +} diff --git a/src/result_validation/container.rs b/src/result_validation/container.rs new file mode 100644 index 0000000..f786d9c --- /dev/null +++ b/src/result_validation/container.rs @@ -0,0 +1,803 @@ +//! One packed container: its geometry, its loads, its accounting figures, and the box a +//! made-to-measure machine would have cut for it. + +use super::geometry::{Cuboid, solids_overlap}; +use super::json::{Json, Ordered, Res}; +use super::num::{Ratio, abs, add, ceil_div, floor_div, mul, mul_div, py_mod, sub, sum}; +use super::pyfmt::{int_tuple, list, py_repr, py_str, str_repr, tuple}; +use super::spec::{ContainerSpec, ItemSpec, rotation_axes}; +use super::stacking::{ + Entry, Envelopes, SQUARE_METRE_TICKS, check_crush, check_route_removal_order, + check_stack_density, check_support_and_load, entries, occupied_volume, placed_hull, + propagate_load, support_graph, valid_nesting, +}; +use super::{Issue, Label, MalformedResult}; + +/// Ratios in the objective vector and the reserve are carried as parts per million. +pub(crate) const SCORE_SCALE: i128 = 1_000_000; + +const SIDES: [&str; 3] = ["length", "width", "height"]; + +/// The physical box grown by the clearance margin. A placement without integer tick +/// coordinates is the reference's contract refusal, worded as it words it. +pub(crate) fn envelope(placement: &Json, clearance: i128) -> Res { + read_envelope(placement, clearance).map_err(|error| { + MalformedResult::contract(format!( + "placement is missing tick coordinates: {}", + error.message + )) + }) +} + +fn read_envelope(placement: &Json, clearance: i128) -> Res { + let position = placement.at("position")?; + let dimensions = placement.at("dimensions")?; + let tick = |block: &Json, key: &str| -> Res { + block.at(key)?.at("ticks")?.int("placement ticks") + }; + let margin = mul(2, clearance)?; + Cuboid::new( + sub(tick(position, "x")?, clearance)?, + sub(tick(position, "y")?, clearance)?, + sub(tick(position, "z")?, clearance)?, + add(tick(dimensions, "length")?, margin)?, + add(tick(dimensions, "width")?, margin)?, + add(tick(dimensions, "height")?, margin)?, + ) +} + +/// The largest envelope x2, y2 and z2 over a packed container's placements. +pub(crate) fn achieved_extent(packed: &Json, clearance: i128) -> Res<[i128; 3]> { + let mut extent: Option<[i128; 3]> = None; + for placement in packed.at("placements")?.list("placements")? { + let envelope = envelope(placement, clearance)?; + extent = Some(match extent { + None => [envelope.x2, envelope.y2, envelope.z2], + Some([x, y, z]) => [x.max(envelope.x2), y.max(envelope.y2), z.max(envelope.z2)], + }); + } + Ok(extent.unwrap_or([0, 0, 0])) +} + +/// `achieved_dimensions` is present exactly when the container declares a soft size, and +/// equals the tight extent; a flat bag's extent must pass the girth rule. +pub(crate) fn check_achieved_extent( + packed: &Json, + spec: &ContainerSpec, + clearance: i128, + issues: &mut Vec, +) -> Res<()> { + let reported = packed.get_null("achieved_dimensions")?; + let packed_id = Label::of(packed)?; + if !spec.reports_achieved_extent { + if !reported.is_null() { + issues.push(Issue::new( + "achieved_dimensions_mismatch", + format!("{packed_id}: reported for a container of fixed size"), + )); + } + return packed_id.verify(); + } + let [a, b, c] = achieved_extent(packed, clearance)?; + let stated: Option> = if reported.is_dict() { + let empty = Json::Dict(Vec::new()); + Some( + SIDES + .iter() + .map(|side| Ok(reported.get_or(side, &empty)?.get_null("ticks")?.clone())) + .collect::>()?, + ) + } else { + None + }; + if !matches_ints(stated.as_deref(), &[a, b, c]) { + issues.push(Issue::new( + "achieved_dimensions_mismatch", + format!( + "{packed_id}: reported {}, computed {}", + optional_tuple(stated.as_deref()), + int_tuple(&[a, b, c]) + ), + )); + } + if spec.flat_bag && (add(a, c)? > spec.inner[0] || add(b, c)? > spec.inner[1]) { + issues.push(Issue::new( + "bag_girth_exceeded", + format!( + "{packed_id}: a + c = {}, b + c = {}, flat size {} x {}", + add(a, c)?, + add(b, c)?, + spec.inner[0], + spec.inner[1], + ), + )); + } + packed_id.verify() +} + +fn matches_ints(stated: Option<&[Json]>, expected: &[i128]) -> bool { + stated.is_some_and(|values| { + values.len() == expected.len() && values.iter().zip(expected).all(|(v, e)| v.eq_int(*e)) + }) +} + +fn optional_tuple(values: Option<&[Json]>) -> String { + values.map_or_else( + || "None".to_owned(), + |values| tuple(values.iter().map(py_repr)), + ) +} + +/// The smallest size on the machine grid `minimum + k * increment` that is at least `achieved`. +fn fabricated_side(achieved: i128, minimum: i128, increment: i128) -> Res { + add( + minimum, + mul( + ceil_div(sub(achieved.max(minimum), minimum)?, increment)?, + increment, + )?, + ) +} + +/// `ceil(rate * 2(LW + LH + WH) / 1 m^2)`, the material and board rounding. +fn per_square_metre_ceiling(rate: i128, sides: [i128; 3]) -> Res { + let [length, width, height] = sides; + let area = mul( + 2, + add( + add(mul(length, width)?, mul(length, height)?)?, + mul(width, height)?, + )?, + )?; + ceil_div(mul(rate, area)?, SQUARE_METRE_TICKS) +} + +/// `(value.get(key) or {}).get("ticks")` per key, or `None` when `value` is not an object. +fn reported_ticks(value: &Json) -> Res>> { + if !value.is_dict() { + return Ok(None); + } + let mut ticks = Vec::with_capacity(3); + for side in SIDES { + let block = value.get_null(side)?; + ticks.push(if block.truthy() { + block.get_null("ticks")?.clone() + } else { + Json::Null + }); + } + Ok(Some(ticks)) +} + +/// `(block.get(key) or {}).get("ticks")`. +fn nested_ticks(block: &Json, key: &str) -> Res { + let value = block.get_null(key)?; + Ok(if value.truthy() { + value.get_null("ticks")?.clone() + } else { + Json::Null + }) +} + +/// Recompute a made-to-measure container's box from its placements alone and return the spec +/// every later check uses: the recomputed box, never the reported one. +pub(crate) fn check_made_to_measure( + packed: &Json, + compact: bool, + spec: &ContainerSpec, + items: &Ordered, + clearance: i128, + issues: &mut Vec, +) -> Res { + let container_id = py_str(packed.get_or("id", &Json::str_of("?"))?); + let reported_block = packed.get_null("made_to_measure")?; + let Some(machine) = &spec.made_to_measure else { + if !reported_block.is_null() { + issues.push(Issue::new("made_to_measure_unexpected", container_id)); + } + return Ok(spec.clone()); + }; + let empty = Json::Dict(Vec::new()); + let block = if reported_block.is_dict() { + reported_block + } else { + issues.push(Issue::new("made_to_measure_missing", container_id.clone())); + &empty + }; + if compact { + issues.push(Issue::new( + "lattice_summary_on_made_to_measure", + container_id.clone(), + )); + } + let achieved = achieved_extent(packed, clearance)?; + let mut fabricated = [0; 3]; + for axis in 0..3 { + fabricated[axis] = fabricated_side( + achieved[axis], + machine.minimum[axis], + machine.increment[axis], + )?; + } + if (0..3).any(|axis| fabricated[axis] > spec.inner[axis]) { + issues.push(Issue::new( + "fabricated_dimensions_exceed_machine", + format!( + "{container_id}: {} beyond {}", + int_tuple(&fabricated), + int_tuple(&spec.inner) + ), + )); + } + let reported_inner = reported_ticks(packed.get_null("inner_dimensions")?)?; + if !matches_ints(reported_inner.as_deref(), &fabricated) { + issues.push(Issue::new( + "fabricated_dimensions_mismatch", + format!( + "{container_id}: reported {}, computed {}", + optional_tuple(reported_inner.as_deref()), + int_tuple(&fabricated) + ), + )); + } + let outer = [ + add(fabricated[0], machine.allowance[0])?, + add(fabricated[1], machine.allowance[1])?, + add(fabricated[2], machine.allowance[2])?, + ]; + let reported_outer = reported_ticks(packed.get_null("outer_dimensions")?)?; + if !matches_ints(reported_outer.as_deref(), &outer) { + issues.push(Issue::new( + "outer_dimensions_mismatch", + format!( + "{container_id}: reported {}, computed {}", + optional_tuple(reported_outer.as_deref()), + int_tuple(&outer) + ), + )); + } + let cost = add( + spec.cost_minor, + per_square_metre_ceiling(machine.price_per_square_metre_minor, fabricated)?, + )?; + let reported_cost = block.get_null("cost_minor")?; + if !reported_cost.eq_int(cost) { + issues.push(Issue::new( + "made_to_measure_cost_mismatch", + format!( + "{container_id}: reported {}, computed {cost}", + py_str(reported_cost) + ), + )); + } + let tare = add( + spec.tare_weight, + per_square_metre_ceiling(machine.tare_per_square_metre, fabricated)?, + )?; + let reported_tare = nested_ticks(block, "tare_weight")?; + if !reported_tare.eq_int(tare) { + issues.push(Issue::new( + "made_to_measure_tare_mismatch", + format!( + "{container_id}: reported {}, computed {tare}", + py_str(&reported_tare) + ), + )); + } + let payload = payload_of(packed, items)?; + let reported_gross = nested_ticks(packed, "gross_weight")?; + let gross = add(tare, payload)?; + if !reported_gross.eq_int(gross) { + issues.push(Issue::new( + "gross_weight_mismatch", + format!( + "{container_id}: reported {}, computed {gross}", + py_str(&reported_gross) + ), + )); + } + Ok(ContainerSpec { + inner: fabricated, + outer: Some(outer), + cost_minor: cost, + tare_weight: tare, + ..spec.clone() + }) +} + +/// The summed weight of every placement whose type the request declares. +fn payload_of(packed: &Json, items: &Ordered) -> Res { + let mut payload = 0; + for placement in packed.at("placements")?.list("placements")? { + if let Some(spec) = items.get(placement.at("item_type")?)? { + payload = add(payload, spec.weight)?; + } + } + Ok(payload) +} + +pub(crate) fn check_container( + packed: &Json, + spec: &ContainerSpec, + items: &Ordered, + clearance: i128, + global_support: Ratio, + issues: &mut Vec, +) -> Res<()> { + let packed_id = Label::of(packed)?; + let placements = packed.at("placements")?.list("placements")?; + let boundary = Cuboid::new(0, 0, 0, spec.inner[0], spec.inner[1], spec.inner[2])?; + let mut envelopes: Envelopes<'_> = Ordered::default(); + let mut payload = 0; + + for placement in placements { + let item_id = placement.at("item_id")?; + let item_spec = items.get(placement.at("item_type")?)?; + let envelope = envelope(placement, clearance)?; + envelopes.insert( + item_id, + Entry { + envelope, + placement, + spec: item_spec, + }, + )?; + let item_id = py_str(item_id); + + if !boundary.contains(&envelope) { + issues.push(Issue::new( + "outside_container", + format!("{item_id} in {packed_id}"), + )); + } + for obstacle in &spec.obstacles { + if envelope.intersects(obstacle) + && solids_overlap( + &placed_hull(&envelope, placement, item_spec)?, + &obstacle.vertices(), + )? + { + issues.push(Issue::new( + "obstacle_collision", + format!("{item_id} in {packed_id}"), + )); + } + } + let Some(item_spec) = item_spec else { continue }; + payload = add(payload, item_spec.weight)?; + check_rotation(placement, item_spec, &item_id, issues)?; + if !item_spec.eligible_container_tags.is_empty() + && item_spec.eligible_container_tags.is_disjoint(&spec.tags) + { + issues.push(Issue::new( + "container_ineligible", + format!( + "{item_id}: {} has none of {}", + py_str(packed.at("container_type")?), + list( + item_spec + .eligible_container_tags + .iter() + .map(|tag| str_repr(tag)) + ), + ), + )); + } + if item_spec.must_be_on_floor && envelope.z != 0 { + issues.push(Issue::new( + "floor_violation", + format!("{item_id} at z={}", envelope.z), + )); + } + } + + check_pairs(&envelopes, &packed_id, issues)?; + let graph = support_graph(&envelopes)?; + check_support_and_load(&envelopes, &graph, global_support, issues)?; + let loads = propagate_load(&envelopes, &graph)?; + if let Some(max_density) = spec.max_stack_density { + check_stack_density(&packed_id, &envelopes, &loads, max_density, issues)?; + } + check_crush(&packed_id, &envelopes, &loads, issues)?; + check_route_removal_order( + &packed_id, + &envelopes, + &graph, + spec.inner, + &spec.access_directions, + issues, + )?; + + check_limits(packed, &packed_id, placements, spec, items, payload, issues)?; + check_volumes( + packed, &packed_id, placements, spec, items, &envelopes, &loads, issues, + )?; + let total_weight = payload_of(packed, items)?; + check_centre_of_mass( + packed, + &packed_id, + placements, + spec, + items, + total_weight, + issues, + )?; + check_axles( + packed, + &packed_id, + placements, + spec, + items, + total_weight, + issues, + )?; + packed_id.verify() +} + +fn check_rotation( + placement: &Json, + spec: &ItemSpec, + item_id: &str, + issues: &mut Vec, +) -> Res<()> { + let orientation = placement.at("orientation")?; + if !super::spec::is_rotation(orientation)? { + issues.push(Issue::new( + "unknown_orientation", + format!("{item_id}: {}", py_str(orientation)), + )); + return Ok(()); + } + let name = orientation.text("orientation")?; + if !spec.allows(orientation) { + issues.push(Issue::new( + "forbidden_rotation", + format!("{item_id}: {name}"), + )); + } + let axes = rotation_axes(name)?; + let expected = [ + spec.dimensions[axes[0]], + spec.dimensions[axes[1]], + spec.dimensions[axes[2]], + ]; + let dimensions = placement.at("dimensions")?; + let actual: Vec = SIDES + .iter() + .map(|side| Ok(dimensions.at(side)?.at("ticks")?.clone())) + .collect::>()?; + if !matches_ints(Some(&actual), &expected) { + issues.push(Issue::new( + "dimension_mismatch", + format!( + "{item_id}: {name} of {} is {}, got {}", + int_tuple(&spec.dimensions), + int_tuple(&expected), + tuple(actual.iter().map(py_repr)), + ), + )); + } + Ok(()) +} + +fn check_pairs(envelopes: &Envelopes<'_>, packed_id: &Label, issues: &mut Vec) -> Res<()> { + let list = entries(envelopes); + for (first, (left_id, left)) in list.iter().enumerate() { + for (right_id, right) in &list[first + 1..] { + if left.envelope.intersects(&right.envelope) + && solids_overlap( + &placed_hull(&left.envelope, left.placement, left.spec)?, + &placed_hull(&right.envelope, right.placement, right.spec)?, + )? + && !valid_nesting(left, right)? + { + issues.push(Issue::new( + "collision", + format!( + "{} with {} in {packed_id}", + py_str(left_id), + py_str(right_id) + ), + )); + } + if let (Some(left_spec), Some(right_spec)) = (left.spec, right.spec) + && (!left_spec.incompatible_tags.is_disjoint(&right_spec.tags) + || !right_spec.incompatible_tags.is_disjoint(&left_spec.tags)) + { + issues.push(Issue::new( + "incompatible_items", + format!( + "{} is incompatible with {} in {packed_id}", + py_str(left_id), + py_str(right_id) + ), + )); + } + } + } + Ok(()) +} + +fn check_limits( + packed: &Json, + packed_id: &Label, + placements: &[Json], + spec: &ContainerSpec, + items: &Ordered, + payload: i128, + issues: &mut Vec, +) -> Res<()> { + if let Some(limit) = spec.max_payload + && payload > limit + { + issues.push(Issue::new( + "payload_exceeded", + format!("{packed_id}: {payload} > {limit} ticks"), + )); + } + let empty = Json::Dict(Vec::new()); + let reported = packed.get_or("payload_weight", &empty)?.get_null("ticks")?; + if !reported.is_null() && !reported.eq_int(payload) { + issues.push(Issue::new( + "payload_weight_mismatch", + format!( + "{packed_id}: reported {}, computed {payload}", + py_str(reported) + ), + )); + } + if let Some(limit) = spec.max_items + && placements.len() as i128 > limit + { + issues.push(Issue::new( + "max_items_exceeded", + format!("{packed_id}: {} > {limit}", placements.len()), + )); + } + for (tag, limit) in &spec.tag_limits { + let mut count = 0; + for placement in placements { + if items + .get(placement.at("item_type")?)? + .is_some_and(|item| item.tags.contains(tag)) + { + count += 1; + } + } + if count > *limit { + issues.push(Issue::new( + "tag_count_exceeded", + format!("{packed_id}: {tag} count {count} > limit {limit}"), + )); + } + } + Ok(()) +} + +#[allow(clippy::too_many_arguments)] +fn check_volumes( + packed: &Json, + packed_id: &Label, + placements: &[Json], + spec: &ContainerSpec, + items: &Ordered, + envelopes: &Envelopes<'_>, + loads: &[i128], + issues: &mut Vec, +) -> Res<()> { + let list = entries(envelopes); + // 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. + let mut used = 0; + for placement in placements { + let item_id = placement.at("item_id")?; + let index = envelopes.position(item_id)?.ok_or_else(|| { + super::MalformedResult::shape("placement without an envelope".to_owned()) + })?; + let spec = items.get(placement.at("item_type")?)?; + used = add( + used, + occupied_volume(&list[index].1.envelope, placement, spec, loads[index])?, + )?; + } + for (first, (_, left)) in list.iter().enumerate() { + for (_, right) in &list[first + 1..] { + if valid_nesting(left, right)? { + let nesting = left.spec.and_then(|spec| spec.nesting_height).unwrap_or(0); + used = sub( + used, + mul(mul(nesting, left.envelope.length)?, left.envelope.width)?, + )?; + } + } + } + let reported_volume = packed.get_null("used_volume_ticks3")?; + if !reported_volume.is_null() && reported_volume.py_int("used_volume_ticks3")? != used { + issues.push(Issue::new( + "used_volume_mismatch", + format!( + "{packed_id}: reported {}, computed {used}", + py_str(reported_volume) + ), + )); + } + let volume = spec.volume()?; + let scaled_reserve = ratio_ppm(spec.void_fill_reserve_ratio); + let reserved = add( + mul(floor_div(volume, SCORE_SCALE)?, scaled_reserve)?, + floor_div( + mul(py_mod(volume, SCORE_SCALE)?, scaled_reserve)?, + SCORE_SCALE, + )?, + )?; + let reported_reserve = packed.get_null("void_fill_reserve_ticks3")?; + if !reported_reserve.is_null() + && reported_reserve.py_int("void_fill_reserve_ticks3")? != reserved + { + issues.push(Issue::new( + "void_fill_reserve_mismatch", + format!( + "{packed_id}: reported {}, computed {reserved}", + py_str(reported_reserve) + ), + )); + } else if reserved != 0 && reported_reserve.is_null() { + issues.push(Issue::new( + "void_fill_reserve_mismatch", + format!("{packed_id}: non-zero reserve {reserved} is not reported"), + )); + } + let usable = sub(volume, reserved)?; + if used > usable { + issues.push(Issue::new( + "void_fill_reserve_exceeded", + format!("{packed_id}: used {used} > usable {usable}"), + )); + } + Ok(()) +} + +/// A support, void-fill reserve or compression ratio in parts per million exactly as every solver converts +/// it: the IEEE double `floor(ratio * 10^6 + 0.5)` of docs/UNITS-AND-NUMERICS.md. Rounding the +/// exact rational instead disagrees on about one in a hundred seven-decimal halves and would +/// refuse placements, and reported reserves, every solver produces. +pub(crate) fn ratio_ppm(ratio: Ratio) -> i128 { + (ratio.to_f64() * SCORE_SCALE as f64 + 0.5) as i128 +} + +/// `sum(weight * (2 * position + extent))` along one axis, over declared item types. +fn doubled_moment( + placements: &[Json], + items: &Ordered, + axis: &str, + side: &str, +) -> Res { + let mut moments = Vec::new(); + for placement in placements { + let Some(spec) = items.get(placement.at("item_type")?)? else { + continue; + }; + let position = placement + .at("position")? + .at(axis)? + .at("ticks")? + .int("placement ticks")?; + let extent = placement + .at("dimensions")? + .at(side)? + .at("ticks")? + .int("placement ticks")?; + moments.push(mul(spec.weight, add(mul(2, position)?, extent)?)?); + } + sum(moments) +} + +fn check_centre_of_mass( + packed: &Json, + packed_id: &Label, + placements: &[Json], + spec: &ContainerSpec, + items: &Ordered, + total_weight: i128, + issues: &mut Vec, +) -> Res<()> { + let expected = if total_weight == 0 { + 0 + } else { + let offset = |doubled: i128, side: i128| -> Res { + let centred = mul(total_weight, side)?; + floor_div(mul(abs(sub(doubled, centred)?)?, SCORE_SCALE)?, centred) + }; + let x_ppm = offset( + doubled_moment(placements, items, "x", "length")?, + spec.inner[0], + )?; + let y_ppm = offset( + doubled_moment(placements, items, "y", "width")?, + spec.inner[1], + )?; + x_ppm.max(y_ppm) + }; + let reported = packed.get_null("centre_of_mass_offset_ppm")?; + if !reported.eq_int(expected) { + issues.push(Issue::new( + "centre_of_mass_mismatch", + format!( + "{packed_id}: reported {}, computed {expected}", + py_str(reported) + ), + )); + } + Ok(()) +} + +fn check_axles( + packed: &Json, + packed_id: &Label, + placements: &[Json], + spec: &ContainerSpec, + items: &Ordered, + total_weight: i128, + issues: &mut Vec, +) -> Res<()> { + let Some(axles) = &spec.axles else { + if packed.has("axle_reactions") { + issues.push(Issue::new( + "axle_reaction_mismatch", + format!("{packed_id}: reactions reported without configured axles"), + )); + } + return Ok(()); + }; + let [front, rear] = axles.as_slice() else { + return Err(super::MalformedResult::shape(format!( + "{packed_id}: axles must name exactly a front and a rear axle" + ))); + }; + let denominator = mul(2, sub(rear.position, front.position)?)?; + let gross = add(spec.tare_weight, total_weight)?; + let doubled_weighted_x = add( + mul(spec.tare_weight, spec.inner[0])?, + doubled_moment(placements, items, "x", "length")?, + )?; + let front_numerator = sub(mul(mul(2, gross)?, rear.position)?, doubled_weighted_x)?; + let rear_numerator = sub(doubled_weighted_x, mul(mul(2, gross)?, front.position)?)?; + let expected = Json::Dict(vec![ + ("basis".to_owned(), Json::str_of("gross")), + ("denominator".to_owned(), Json::Str(denominator.to_string())), + ( + "front_numerator".to_owned(), + Json::Str(front_numerator.to_string()), + ), + ( + "rear_numerator".to_owned(), + Json::Str(rear_numerator.to_string()), + ), + ]); + let reported = packed.get_null("axle_reactions")?; + if !reported.py_eq(&expected) { + issues.push(Issue::new( + "axle_reaction_mismatch", + format!( + "{packed_id}: reported {}, computed {}", + py_str(reported), + py_repr(&expected) + ), + )); + } + let over = |limit: Option, numerator: i128| -> Res { + Ok(match limit { + Some(limit) => numerator > mul(limit, denominator)?, + None => false, + }) + }; + if over(front.max_load, front_numerator)? || over(rear.max_load, rear_numerator)? { + issues.push(Issue::new("axle_overloaded", packed_id.to_string())); + } + Ok(()) +} + +/// `mul_div`, used by the objective for the products that outgrow `i128`. +pub(crate) fn unused_ppm(volume: i128, used: i128) -> Res { + mul_div(sub(volume, used)?, SCORE_SCALE, volume) +} diff --git a/src/result_validation/facts.rs b/src/result_validation/facts.rs new file mode 100644 index 0000000..9ef5dc1 --- /dev/null +++ b/src/result_validation/facts.rs @@ -0,0 +1,384 @@ +//! The result's own claims about the search: counters, counted-work limits, start records and +//! the feasibility, termination and optimality facts. + +use std::cmp::Ordering; + +use super::json::{EMPTY_LIST, EMPTY_STR, Json, Res}; +use super::pyfmt::{bool_repr, py_repr, py_str, str_repr}; +use super::{Issue, MalformedResult}; + +const METRICS: [&str; 7] = [ + "candidate_points_considered", + "orientations_considered", + "feasible_candidates", + "collision_checks", + "support_checks", + "space_partitions", + "search_nodes_expanded", +]; + +fn algorithm(result: &Json) -> Res<&Json> { + let algorithm = result.at("algorithm")?; + if !algorithm.is_dict() { + return Err(MalformedResult::contract( + "algorithm must be an object".to_owned(), + )); + } + Ok(algorithm) +} + +pub(crate) fn check_algorithm_metrics(result: &Json, issues: &mut Vec) -> Res<()> { + let algorithm = algorithm(result)?; + let metrics = algorithm.get_null("metrics")?; + let counters_well_formed = metrics.is_dict() + && METRICS.iter().all(|field| { + matches!(metrics.get_null(field), Ok(value) if value.strict_int().is_some_and(|count| count >= 0)) + }); + if !counters_well_formed { + issues.push(Issue::new( + "solver_metrics_mismatch", + "algorithm.metrics must contain every non-negative integer counter".to_owned(), + )); + return Ok(()); + } + let legacy_candidates = algorithm.get_null("candidates_evaluated")?.strict_int(); + let legacy_attempts = algorithm.get_null("placements_attempted")?.strict_int(); + let mirrors = legacy_candidates.is_some() + && legacy_attempts.is_some() + && legacy_candidates == metrics.at("feasible_candidates")?.strict_int() + && legacy_attempts == metrics.at("orientations_considered")?.strict_int(); + if !mirrors { + issues.push(Issue::new( + "solver_metrics_mismatch", + "legacy candidate counters must mirror algorithm.metrics".to_owned(), + )); + } + Ok(()) +} + +/// Counted-work limits are respected, and the stop flag is evidenced by one of them. +pub(crate) fn check_effort_budget( + request: &Json, + result: &Json, + issues: &mut Vec, +) -> Res<()> { + let algorithm = result.at("algorithm")?; + let effort_limited = match algorithm.get_null("effort_limit_reached")? { + Json::Bool(flag) => *flag, + _ => { + return Err(MalformedResult::contract( + "algorithm.effort_limit_reached must be a boolean".to_owned(), + )); + } + }; + let empty = Json::Dict(Vec::new()); + let budget = request + .get_or("configuration", &empty)? + .get_null("effort_budget")?; + if budget.is_null() { + if effort_limited { + issues.push(Issue::new( + "effort_budget_mismatch", + "effort_limit_reached is true but the request has no effort_budget".to_owned(), + )); + } + return Ok(()); + } + if !budget.is_dict() { + return Err(MalformedResult::contract( + "config.effort_budget must be an object".to_owned(), + )); + } + let metrics = algorithm.get_null("metrics")?; + if !metrics.is_dict() { + return Ok(()); + } + let mut reached = false; + for (budget_name, metric_name) in [ + ("max_candidates_evaluated", "feasible_candidates"), + ("max_placement_attempts", "orientations_considered"), + ("max_search_nodes", "search_nodes_expanded"), + ] { + let limit = budget.get_null(budget_name)?; + let Some(value) = metrics.get_null(metric_name)?.strict_int() else { + continue; + }; + if limit.is_null() { + continue; + } + let order = Json::Int(value).py_cmp(limit)?; + if order == Ordering::Greater { + issues.push(Issue::new( + "effort_budget_exceeded", + format!( + "{metric_name} is {value}, above {budget_name}={}", + py_str(limit) + ), + )); + } + reached = reached || order != Ordering::Less; + } + let restart_limit = budget.get_null("max_restarts")?; + let starts = result + .get_or("termination", &empty)? + .get_or("starts", &EMPTY_LIST)?; + if let (Some(limit), Json::List(starts)) = (restart_limit.py_int_instance(), starts) { + let started = starts + .iter() + .filter(|start| { + start.is_dict() && matches!(start.get_null("started"), Ok(Json::Bool(true))) + }) + .count() as i128; + if started > limit { + issues.push(Issue::new( + "effort_budget_exceeded", + format!( + "started {started} solver runs, above max_restarts={}", + py_str(restart_limit) + ), + )); + } + reached = reached || started >= limit; + } + if effort_limited && !reached { + issues.push(Issue::new( + "effort_budget_mismatch", + "effort_limit_reached is true but no configured counted-work boundary was reached" + .to_owned(), + )); + } + Ok(()) +} + +fn flag(algorithm: &Json, name: &str) -> Res { + match algorithm.get_null(name)? { + Json::Bool(value) => Ok(*value), + _ => Err(MalformedResult::contract(format!( + "algorithm.{name} must be a boolean" + ))), + } +} + +fn fact_code<'a>(result: &'a Json, name: &str) -> Res<&'a str> { + let fact = result.at(name)?; + if !fact.is_dict() { + return Err(MalformedResult::contract(format!( + "{name} must be an object" + ))); + } + match fact.get_null("code")? { + Json::Str(code) if !code.is_empty() => Ok(code), + _ => Err(MalformedResult::contract(format!( + "{name}.code must be a non-empty string" + ))), + } +} + +pub(crate) fn check_result_facts(result: &Json, issues: &mut Vec) -> Res<()> { + let algorithm = algorithm(result)?; + let timed_out = flag(algorithm, "time_limit_reached")?; + let effort_limited = flag(algorithm, "effort_limit_reached")?; + if timed_out && effort_limited { + issues.push(Issue::new( + "result_fact_mismatch", + "time_limit_reached and effort_limit_reached cannot both be true".to_owned(), + )); + } + let termination = result.at("termination")?; + if !termination.is_dict() { + return Err(MalformedResult::contract( + "termination must be an object".to_owned(), + )); + } + check_starts(termination, algorithm, timed_out, effort_limited, issues)?; + + let status = result.at("status")?; + let complete = result.at("complete")?.truthy(); + let invalid = status.is_str("invalid_result"); + let expected_feasibility = if status.is_str("infeasible") { + "infeasible" + } else if complete && !invalid { + "feasible" + } else { + "unknown" + }; + let expected_termination = if invalid { + "error" + } else if timed_out { + "time_limit" + } else if effort_limited { + "effort_limit" + } else { + "complete" + }; + let expected_optimality = if status.is_str("optimal") { + "proven_optimal" + } else if status.is_str("infeasible") { + "proven_infeasible" + } else if !complete && !invalid { + "best_found" + } else { + "not_proven" + }; + for (name, expected) in [ + ("feasibility", expected_feasibility), + ("termination", expected_termination), + ("optimality", expected_optimality), + ] { + let actual = fact_code(result, name)?; + if actual != expected { + issues.push(Issue::new( + "result_fact_mismatch", + format!( + "{name}.code is {}, expected {}", + str_repr(actual), + str_repr(expected) + ), + )); + } + } + Ok(()) +} + +fn check_starts( + termination: &Json, + algorithm: &Json, + timed_out: bool, + effort_limited: bool, + issues: &mut Vec, +) -> Res<()> { + let starts = match termination.get_null("starts")? { + Json::List(starts) if !starts.is_empty() => starts, + _ => { + issues.push(Issue::new( + "termination_aggregate_mismatch", + "termination.starts must contain at least one start".to_owned(), + )); + return Ok(()); + } + }; + let mut malformed = false; + for start in starts { + if !start.is_dict() || !matches!(start.get_null("id")?, Json::Str(_)) { + malformed = true; + continue; + } + let mut flags = [false; 5]; + let mut booleans = true; + for (slot, name) in [ + "started", + "completed", + "truncated", + "selected", + "global_deadline_reached", + ] + .iter() + .enumerate() + { + match start.get_null(name)? { + Json::Bool(value) => flags[slot] = *value, + _ => booleans = false, + } + } + if !booleans { + malformed = true; + continue; + } + let [started, completed, truncated, _, _] = flags; + if (completed && (!started || truncated)) + || (truncated && (!started || completed)) + || (!started && (completed || truncated)) + { + issues.push(Issue::new( + "start_record_mismatch", + format!("{}: inconsistent lifecycle flags", py_str(start.at("id")?)), + )); + } + } + if malformed { + issues.push(Issue::new( + "start_record_mismatch", + "a start record is missing its id or boolean lifecycle fields".to_owned(), + )); + } + let is_true = |start: &Json, name: &str| { + start.is_dict() && matches!(start.get_null(name), Ok(Json::Bool(true))) + }; + let selected: Vec<&Json> = starts + .iter() + .filter(|start| is_true(start, "selected")) + .collect(); + if selected.len() != 1 { + issues.push(Issue::new( + "termination_aggregate_mismatch", + format!("expected one selected start, found {}", selected.len()), + )); + return Ok(()); + } + if !starts.iter().all(Json::is_dict) { + return Ok(()); + } + let winner = selected[0]; + let aggregate = [ + ( + "any_start_truncated", + starts.iter().any(|start| is_true(start, "truncated")), + ), + ( + "all_required_starts_completed", + starts.iter().all(|start| is_true(start, "completed")), + ), + ("winning_start_truncated", is_true(winner, "truncated")), + ( + "global_deadline_reached", + starts + .iter() + .any(|start| is_true(start, "global_deadline_reached")), + ), + ]; + for (name, expected) in aggregate { + let reported = termination.get_null(name)?; + if !matches!(reported, Json::Bool(value) if *value == expected) { + issues.push(Issue::new( + "termination_aggregate_mismatch", + format!( + "{name} is {}, expected {}", + py_repr(reported), + bool_repr(expected) + ), + )); + } + } + let solver = algorithm.get_null("solver")?; + let selected_id = winner.get_or("id", &EMPTY_STR)?; + if let Json::Str(solver) = solver + && !(selected_id.is_str(solver) + || selected_id + .text("a start id")? + .starts_with(&format!("{solver}#"))) + { + issues.push(Issue::new( + "winning_start_mismatch", + format!( + "selected start {} does not identify solver {}", + py_repr(selected_id), + str_repr(solver) + ), + )); + } + let (_, global_deadline) = aggregate[3]; + let (_, winning_truncated) = aggregate[2]; + if global_deadline && !timed_out { + issues.push(Issue::new( + "legacy_time_limit_mismatch", + "global_deadline_reached requires time_limit_reached".to_owned(), + )); + } + if (global_deadline || winning_truncated) != (timed_out || effort_limited) { + issues.push(Issue::new( + "termination_limit_mismatch", + "selected-start truncation must identify exactly one reached limit".to_owned(), + )); + } + Ok(()) +} diff --git a/src/result_validation/geometry.rs b/src/result_validation/geometry.rs new file mode 100644 index 0000000..c5f02ac --- /dev/null +++ b/src/result_validation/geometry.rs @@ -0,0 +1,308 @@ +//! Boxes and convex hulls in ticks, written the slow, obvious way the reference writes them: +//! a validator that took the engine's shortcuts would stop being a second opinion. + +use std::collections::BTreeSet; + +use super::json::Res; +use super::num::{abs, add, mul, sub}; + +pub(crate) type Vertex = [i128; 3]; + +/// Axis permutation each orientation code applies to (length, width, height). +pub(crate) const ROTATIONS: [(&str, [usize; 3]); 6] = [ + ("LWH", [0, 1, 2]), + ("LHW", [0, 2, 1]), + ("WLH", [1, 0, 2]), + ("WHL", [1, 2, 0]), + ("HLW", [2, 0, 1]), + ("HWL", [2, 1, 0]), +]; + +/// An axis-aligned box. Its far corner and base area are computed once, checked. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct Cuboid { + pub(crate) x: i128, + pub(crate) y: i128, + pub(crate) z: i128, + pub(crate) length: i128, + pub(crate) width: i128, + pub(crate) height: i128, + pub(crate) x2: i128, + pub(crate) y2: i128, + pub(crate) z2: i128, + pub(crate) base_area: i128, +} + +impl Cuboid { + pub(crate) fn new( + x: i128, + y: i128, + z: i128, + length: i128, + width: i128, + height: i128, + ) -> Res { + Ok(Cuboid { + x, + y, + z, + length, + width, + height, + x2: add(x, length)?, + y2: add(y, width)?, + z2: add(z, height)?, + base_area: mul(length, width)?, + }) + } + + pub(crate) fn intersects(&self, other: &Cuboid) -> bool { + self.x < other.x2 + && other.x < self.x2 + && self.y < other.y2 + && other.y < self.y2 + && self.z < other.z2 + && other.z < self.z2 + } + + pub(crate) fn contains(&self, other: &Cuboid) -> bool { + self.x <= other.x + && self.y <= other.y + && self.z <= other.z + && other.x2 <= self.x2 + && other.y2 <= self.y2 + && other.z2 <= self.z2 + } + + /// Never larger than either base area, so the product cannot overflow. + pub(crate) fn overlap_area_xy(&self, other: &Cuboid) -> i128 { + let dx = (self.x2.min(other.x2) - self.x.max(other.x)).max(0); + let dy = (self.y2.min(other.y2) - self.y.max(other.y)).max(0); + dx * dy + } + + pub(crate) fn vertices(&self) -> Vec { + let mut corners = Vec::with_capacity(8); + for dx in [0, 1] { + for dy in [0, 1] { + for dz in [0, 1] { + corners.push([ + if dx == 1 { self.x2 } else { self.x }, + if dy == 1 { self.y2 } else { self.y }, + if dz == 1 { self.z2 } else { self.z }, + ]); + } + } + } + corners + } +} + +pub(crate) fn difference(left: Vertex, right: Vertex) -> Res { + Ok([ + sub(left[0], right[0])?, + sub(left[1], right[1])?, + sub(left[2], right[2])?, + ]) +} + +pub(crate) fn cross(left: Vertex, right: Vertex) -> Res { + Ok([ + sub(mul(left[1], right[2])?, mul(left[2], right[1])?)?, + sub(mul(left[2], right[0])?, mul(left[0], right[2])?)?, + sub(mul(left[0], right[1])?, mul(left[1], right[0])?)?, + ]) +} + +pub(crate) fn dot(left: Vertex, right: Vertex) -> Res { + add( + add(mul(left[0], right[0])?, mul(left[1], right[1])?)?, + mul(left[2], right[2])?, + ) +} + +fn gcd(mut left: i128, mut right: i128) -> i128 { + while right != 0 { + (left, right) = (right, left % right); + } + left +} + +/// The axis reduced by its gcd and signed so its first non-zero component is positive. +pub(crate) fn primitive_axis(axis: Vertex) -> Res { + let divisor = gcd(gcd(abs(axis[0])?, abs(axis[1])?), abs(axis[2])?); + if divisor == 0 { + return Ok([0, 0, 0]); + } + let reduced = [axis[0] / divisor, axis[1] / divisor, axis[2] / divisor]; + Ok(match reduced.iter().find(|value| **value != 0) { + Some(first) if *first < 0 => [-reduced[0], -reduced[1], -reduced[2]], + _ => reduced, + }) +} + +/// Reorient a hull the way `ROTATIONS` reorients its box, flipping one axis on an odd +/// permutation so it stays a proper rotation, then translated so its bounds start at 0. +pub(crate) fn rotate_hull(vertices: &[Vertex], axes: [usize; 3]) -> Res> { + let inversions = (0..3) + .flat_map(|first| (first + 1..3).map(move |second| (first, second))) + .filter(|&(first, second)| axes[first] > axes[second]) + .count(); + let sign = if inversions % 2 == 1 { -1 } else { 1 }; + let turned: Vec = vertices + .iter() + .map(|vertex| [sign * vertex[axes[0]], vertex[axes[1]], vertex[axes[2]]]) + .collect(); + let low: Vec = (0..3) + .map(|axis| turned.iter().map(|vertex| vertex[axis]).min().unwrap_or(0)) + .collect(); + turned + .iter() + .map(|vertex| difference(*vertex, [low[0], low[1], low[2]])) + .collect() +} + +/// Every 3-combination of `points`, in `itertools.combinations` order. +fn triples(points: &[Vertex]) -> impl Iterator + '_ { + let count = points.len(); + (0..count).flat_map(move |first| { + (first + 1..count).flat_map(move |second| { + (second + 1..count).map(move |third| (points[first], points[second], points[third])) + }) + }) +} + +fn pair_directions(points: &[Vertex]) -> Res> { + let mut directions = Vec::new(); + for first in 0..points.len() { + for second in first + 1..points.len() { + directions.push(difference(points[second], points[first])?); + } + } + Ok(directions) +} + +/// The complete separating-axis superset: every face normal of each hull and every cross +/// product of an edge direction from one with one from the other. +fn hull_axes(left: &[Vertex], right: &[Vertex]) -> Res> { + let mut axes = BTreeSet::new(); + for hull in [left, right] { + for (first, second, third) in triples(hull) { + axes.insert(primitive_axis(cross( + difference(second, first)?, + difference(third, first)?, + )?)?); + } + } + let right_directions = pair_directions(right)?; + for one in pair_directions(left)? { + for other in &right_directions { + axes.insert(primitive_axis(cross(one, *other)?)?); + } + } + axes.remove(&[0, 0, 0]); + Ok(axes) +} + +/// Whether two convex solids share interior volume. Touching is contact, not collision. +pub(crate) fn solids_overlap(left: &[Vertex], right: &[Vertex]) -> Res { + for axis in hull_axes(left, right)? { + let (left_low, left_high) = extent(left, axis)?; + let (right_low, right_high) = extent(right, axis)?; + if left_high <= right_low || right_high <= left_low { + return Ok(false); + } + } + Ok(true) +} + +fn extent(points: &[Vertex], axis: Vertex) -> Res<(i128, i128)> { + let mut low = i128::MAX; + let mut high = i128::MIN; + for point in points { + let value = dot(*point, axis)?; + low = low.min(value); + high = high.max(value); + } + Ok((low, high)) +} + +/// Exact volume of a convex hull, `6V = sum of a . (b x c)` over its outward faces. +pub(crate) fn hull_volume(vertices: &[Vertex]) -> Res { + let mut normals = BTreeSet::new(); + for (first, second, third) in triples(vertices) { + let axis = primitive_axis(cross( + difference(second, first)?, + difference(third, first)?, + )?)?; + if axis != [0, 0, 0] { + normals.insert(axis); + } + } + let mut six_volumes: i128 = 0; + for axis in normals { + for outward in [axis, [-axis[0], -axis[1], -axis[2]]] { + let (_, highest) = extent(vertices, outward)?; + let mut face = Vec::new(); + for vertex in vertices { + if dot(*vertex, outward)? == highest { + face.push(*vertex); + } + } + if face.len() < 3 { + continue; + } + let ordered = wind_face(&face, outward)?; + let apex = ordered[0]; + for pair in ordered[1..].windows(2) { + six_volumes = add(six_volumes, dot(apex, cross(pair[0], pair[1])?)?)?; + } + } + } + Ok(abs(six_volumes)? / 6) +} + +/// Corners of one planar convex face in cyclic order seen from outside, by gift-wrapping from +/// the lexicographically smallest vertex; collinear candidates resolve to the farthest. +fn wind_face(face: &[Vertex], outward: Vertex) -> Res> { + let start = *face + .iter() + .min() + .expect("a face has at least three vertices"); + let mut ordered = vec![start]; + let mut current = start; + for _ in 0..face.len() { + let mut following: Option = None; + for candidate in face { + if *candidate == current { + continue; + } + let Some(held_vertex) = following else { + following = Some(*candidate); + continue; + }; + let turn = dot( + cross( + difference(held_vertex, current)?, + difference(*candidate, current)?, + )?, + outward, + )?; + let reach_vector = difference(*candidate, current)?; + let held_vector = difference(held_vertex, current)?; + let reach = dot(reach_vector, reach_vector)?; + let held = dot(held_vector, held_vector)?; + if turn < 0 || (turn == 0 && reach > held) { + following = Some(*candidate); + } + } + match following { + Some(next) if next != start => { + ordered.push(next); + current = next; + } + _ => break, + } + } + Ok(ordered) +} diff --git a/src/result_validation/json.rs b/src/result_validation/json.rs new file mode 100644 index 0000000..19b906e --- /dev/null +++ b/src/result_validation/json.rs @@ -0,0 +1,610 @@ +//! The JSON documents the validator reads, held the way Python's `json.loads` holds them. +//! +//! The reference reads plain dicts and lists, and some of its details print one (an +//! `axle_reactions` object, a repeated value): Python keeps an object's keys in document order, +//! so this type does too, where `serde_json::Value` would sort them. A repeated key keeps its +//! first position and its last value, as a Python dict built from the pairs does. + +use std::cmp::Ordering; +use std::collections::HashMap; +use std::fmt; + +use serde::Deserialize; +use serde::de::{self, MapAccess, SeqAccess, Visitor}; + +use super::MalformedResult; + +pub(crate) type Res = Result; + +#[derive(Clone, Debug)] +pub(crate) enum Json { + Null, + Bool(bool), + Int(i128), + Float(f64), + Str(String), + List(Vec), + Dict(Vec<(String, Json)>), +} + +pub(crate) static NULL: Json = Json::Null; +pub(crate) static EMPTY_LIST: Json = Json::List(Vec::new()); +pub(crate) static EMPTY_STR: Json = Json::Str(String::new()); + +pub(crate) fn parse(text: &str, what: &str) -> Res { + serde_json::from_str(text) + .map_err(|error| MalformedResult::shape(format!("{what} is not JSON: {error}"))) +} + +impl Json { + pub(crate) fn str_of(text: &str) -> Json { + Json::Str(text.to_owned()) + } + + /// Python's `d.get(key)`: `None` when the key is absent. A non-object has no `.get`. + pub(crate) fn get(&self, key: &str) -> Res> { + match self { + Json::Dict(pairs) => Ok(pairs + .iter() + .find(|(name, _)| name == key) + .map(|(_, value)| value)), + other => Err(MalformedResult::shape(format!( + "expected an object holding {key:?}, got {}", + other.kind() + ))), + } + } + + /// Python's `d.get(key, default)`: the default only when the key is absent, so a key + /// present as `null` still reads as `null`. + pub(crate) fn get_or<'a>(&'a self, key: &str, default: &'a Json) -> Res<&'a Json> { + Ok(self.get(key)?.unwrap_or(default)) + } + + /// Python's `d.get(key)`, absent reading as `None`. + pub(crate) fn get_null(&self, key: &str) -> Res<&Json> { + self.get_or(key, &NULL) + } + + /// Python's `d[key]`. + pub(crate) fn at(&self, key: &str) -> Res<&Json> { + self.get(key)? + .ok_or_else(|| MalformedResult::shape(format!("missing {key:?}"))) + } + + /// Python's `key in value`, for an object. Anything else reads as not holding it. + pub(crate) fn has(&self, key: &str) -> bool { + matches!(self, Json::Dict(pairs) if pairs.iter().any(|(name, _)| name == key)) + } + + pub(crate) fn is_null(&self) -> bool { + matches!(self, Json::Null) + } + + pub(crate) fn as_dict(&self) -> Option<&[(String, Json)]> { + match self { + Json::Dict(pairs) => Some(pairs), + _ => None, + } + } + + pub(crate) fn is_dict(&self) -> bool { + matches!(self, Json::Dict(_)) + } + + pub(crate) fn is_str(&self, text: &str) -> bool { + matches!(self, Json::Str(value) if value == text) + } + + /// Something the reference iterates. Only a list is admitted: iterating a string or an + /// object would walk its characters or keys, which no contract means. + pub(crate) fn list(&self, what: &str) -> Res<&[Json]> { + match self { + Json::List(values) => Ok(values), + other => Err(MalformedResult::shape(format!( + "{what} must be a list, got {}", + other.kind() + ))), + } + } + + pub(crate) fn text(&self, what: &str) -> Res<&str> { + match self { + Json::Str(text) => Ok(text), + other => Err(MalformedResult::shape(format!( + "{what} must be a string, got {}", + other.kind() + ))), + } + } + + /// An integer the reference does arithmetic on. A boolean is Python's `int`, so it counts; + /// a float would carry the reference into float arithmetic this port does not follow, so + /// it is refused rather than approximated. + pub(crate) fn int(&self, what: &str) -> Res { + match self { + Json::Int(value) => Ok(*value), + Json::Bool(flag) => Ok(i128::from(*flag)), + other => Err(MalformedResult::shape(format!( + "{what} must be an integer, got {}", + other.kind() + ))), + } + } + + pub(crate) fn opt_int(&self, what: &str) -> Res> { + if self.is_null() { + Ok(None) + } else { + self.int(what).map(Some) + } + } + + /// `isinstance(value, int)`, which a boolean satisfies. + pub(crate) fn py_int_instance(&self) -> Option { + match self { + Json::Int(value) => Some(*value), + Json::Bool(flag) => Some(i128::from(*flag)), + _ => None, + } + } + + /// `isinstance(value, int) and not isinstance(value, bool)`. + pub(crate) fn strict_int(&self) -> Option { + match self { + Json::Int(value) => Some(*value), + _ => None, + } + } + + /// Python's `int(value)`: a number truncates, a string parses as a base-10 integer. + pub(crate) fn py_int(&self, what: &str) -> Res { + match self { + Json::Int(value) => Ok(*value), + Json::Bool(flag) => Ok(i128::from(*flag)), + Json::Float(value) if value.is_finite() && value.abs() < 1.0e38 => { + Ok(value.trunc() as i128) + } + Json::Str(text) => parse_int_literal(text).ok_or_else(|| { + MalformedResult::shape(format!("{what}: invalid literal for int(): {text:?}")) + }), + other => Err(MalformedResult::shape(format!( + "{what}: int() cannot convert {}", + other.kind() + ))), + } + } + + /// Python truthiness. + pub(crate) fn truthy(&self) -> bool { + match self { + Json::Null => false, + Json::Bool(flag) => *flag, + Json::Int(value) => *value != 0, + Json::Float(value) => *value != 0.0, + Json::Str(text) => !text.is_empty(), + Json::List(values) => !values.is_empty(), + Json::Dict(pairs) => !pairs.is_empty(), + } + } + + /// Python `==`: a boolean equals its integer, an integer equals the float of the same + /// value, containers compare element-wise and objects regardless of key order. + pub(crate) fn py_eq(&self, other: &Json) -> bool { + match (self.number(), other.number()) { + (Some(left), Some(right)) => return left.equals(right), + (Some(_), None) | (None, Some(_)) => return false, + (None, None) => {} + } + match (self, other) { + (Json::Null, Json::Null) => true, + (Json::Str(left), Json::Str(right)) => left == right, + (Json::List(left), Json::List(right)) => { + left.len() == right.len() && left.iter().zip(right).all(|(a, b)| a.py_eq(b)) + } + (Json::Dict(left), Json::Dict(right)) => { + left.len() == right.len() + && left.iter().all(|(key, value)| { + right + .iter() + .any(|(name, candidate)| name == key && value.py_eq(candidate)) + }) + } + _ => false, + } + } + + pub(crate) fn eq_int(&self, value: i128) -> bool { + self.number() + .is_some_and(|number| number.equals(Number::Int(value))) + } + + /// Python's `<`/`>` ordering for values the reference sorts or compares: numbers with + /// numbers, strings with strings. Anything else is Python's `TypeError`. + pub(crate) fn py_cmp(&self, other: &Json) -> Res { + if let (Some(left), Some(right)) = (self.number(), other.number()) { + return left.compare(right); + } + match (self, other) { + (Json::Str(left), Json::Str(right)) => Ok(left.cmp(right)), + (Json::List(left), Json::List(right)) => { + for (a, b) in left.iter().zip(right) { + if !a.py_eq(b) { + return a.py_cmp(b); + } + } + Ok(left.len().cmp(&right.len())) + } + _ => Err(MalformedResult::shape(format!( + "cannot order {} against {}", + self.kind(), + other.kind() + ))), + } + } + + /// The identity Python hashes a set member or dict key by, so `1`, `1.0` and `True` share + /// one. A list or an object is unhashable, as in Python. + pub(crate) fn hash_key(&self) -> Res { + if let Some(number) = self.number() { + return Ok(match number { + Number::Int(value) => format!("n{value}"), + Number::Float(value) => format!("f{value:e}"), + }); + } + match self { + Json::Null => Ok("null".to_owned()), + Json::Str(text) => Ok(format!("s{text}")), + other => Err(MalformedResult::shape(format!( + "{} is unhashable", + other.kind() + ))), + } + } + + fn number(&self) -> Option { + match self { + Json::Bool(flag) => Some(Number::Int(i128::from(*flag))), + Json::Int(value) => Some(Number::Int(*value)), + Json::Float(value) => Some(Number::from_float(*value)), + _ => None, + } + } + + pub(crate) fn kind(&self) -> &'static str { + match self { + Json::Null => "null", + Json::Bool(_) => "a boolean", + Json::Int(_) => "an integer", + Json::Float(_) => "a number", + Json::Str(_) => "a string", + Json::List(_) => "a list", + Json::Dict(_) => "an object", + } + } + + /// Replace or append `key`, keeping its position when it already exists. + pub(crate) fn set(&mut self, key: &str, value: Json) -> Res<()> { + match self { + Json::Dict(pairs) => { + match pairs.iter_mut().find(|(name, _)| name == key) { + Some(existing) => existing.1 = value, + None => pairs.push((key.to_owned(), value)), + } + Ok(()) + } + other => Err(MalformedResult::shape(format!( + "cannot set {key:?} on {}", + other.kind() + ))), + } + } +} + +/// A number compared the way Python compares `int` with `float`: exactly. +#[derive(Clone, Copy, Debug)] +enum Number { + Int(i128), + Float(f64), +} + +impl Number { + fn from_float(value: f64) -> Number { + // An integral float within range is that integer, as Python's comparison treats it. + if value.fract() == 0.0 && value.abs() < 1.0e38 { + Number::Int(value as i128) + } else { + Number::Float(value) + } + } + + fn equals(self, other: Number) -> bool { + matches!(self.compare(other), Ok(Ordering::Equal)) + } + + fn compare(self, other: Number) -> Res { + match (self, other) { + (Number::Int(left), Number::Int(right)) => Ok(left.cmp(&right)), + (left, right) => left + .as_float() + .partial_cmp(&right.as_float()) + .ok_or_else(|| MalformedResult::shape("cannot order a NaN".to_owned())), + } + } + + fn as_float(self) -> f64 { + match self { + Number::Int(value) => value as f64, + Number::Float(value) => value, + } + } +} + +/// `sorted(values)` in place, by Python's ordering; values Python cannot order are its +/// `TypeError`. +pub(crate) fn sort_py(values: &mut [&Json]) -> Res<()> { + let mut failure = None; + values.sort_by(|left, right| { + left.py_cmp(right).unwrap_or_else(|error| { + failure = Some(error); + Ordering::Equal + }) + }); + failure.map_or(Ok(()), Err) +} + +/// `int(text)` for a string: optional surrounding whitespace, an optional sign, ASCII digits +/// with single underscores between them. +fn parse_int_literal(text: &str) -> Option { + let trimmed = text.trim(); + let (negative, digits) = match trimmed.strip_prefix('-') { + Some(rest) => (true, rest), + None => (false, trimmed.strip_prefix('+').unwrap_or(trimmed)), + }; + if digits.is_empty() + || digits.starts_with('_') + || digits.ends_with('_') + || digits.contains("__") + { + return None; + } + let mut value: i128 = 0; + for character in digits.chars().filter(|character| *character != '_') { + let digit = character.to_digit(10)?; + value = value.checked_mul(10)?.checked_add(i128::from(digit))?; + } + Some(if negative { -value } else { value }) +} + +/// Insertion-ordered map keyed the way a Python dict is: assigning an existing key replaces +/// its value in place. Keys are kept as the JSON value they came from, for printing. +#[derive(Clone, Debug)] +pub(crate) struct Ordered { + entries: Vec<(Json, T)>, + index: HashMap, +} + +impl Default for Ordered { + fn default() -> Self { + Ordered { + entries: Vec::new(), + index: HashMap::new(), + } + } +} + +impl Ordered { + pub(crate) fn insert(&mut self, key: &Json, value: T) -> Res<()> { + let hashed = key.hash_key()?; + match self.index.get(&hashed) { + Some(&position) => self.entries[position].1 = value, + None => { + self.index.insert(hashed, self.entries.len()); + self.entries.push((key.clone(), value)); + } + } + Ok(()) + } + + pub(crate) fn get(&self, key: &Json) -> Res> { + Ok(self + .index + .get(&key.hash_key()?) + .map(|&position| &self.entries[position].1)) + } + + /// The entry's position in insertion order. + pub(crate) fn position(&self, key: &Json) -> Res> { + Ok(self.index.get(&key.hash_key()?).copied()) + } + + pub(crate) fn get_mut(&mut self, key: &Json) -> Res> { + let hashed = key.hash_key()?; + Ok(self + .index + .get(&hashed) + .map(|&position| &mut self.entries[position].1)) + } + + pub(crate) fn contains(&self, key: &Json) -> Res { + Ok(self.index.contains_key(&key.hash_key()?)) + } + + pub(crate) fn iter(&self) -> impl Iterator { + self.entries.iter().map(|(key, value)| (key, value)) + } + + pub(crate) fn values(&self) -> impl Iterator { + self.entries.iter().map(|(_, value)| value) + } + + pub(crate) fn len(&self) -> usize { + self.entries.len() + } + + pub(crate) fn is_empty(&self) -> bool { + self.entries.is_empty() + } +} + +impl<'de> Deserialize<'de> for Json { + fn deserialize>(deserializer: D) -> Result { + deserializer.deserialize_any(JsonVisitor) + } +} + +struct JsonVisitor; + +impl<'de> Visitor<'de> for JsonVisitor { + type Value = Json; + + fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.write_str("a JSON value") + } + + fn visit_unit(self) -> Result { + Ok(Json::Null) + } + + fn visit_bool(self, value: bool) -> Result { + Ok(Json::Bool(value)) + } + + fn visit_i64(self, value: i64) -> Result { + Ok(Json::Int(i128::from(value))) + } + + fn visit_u64(self, value: u64) -> Result { + Ok(Json::Int(i128::from(value))) + } + + fn visit_f64(self, value: f64) -> Result { + Ok(Json::Float(value)) + } + + fn visit_str(self, value: &str) -> Result { + Ok(Json::Str(value.to_owned())) + } + + fn visit_string(self, value: String) -> Result { + Ok(Json::Str(value)) + } + + fn visit_seq>(self, mut sequence: A) -> Result { + let mut values = Vec::new(); + while let Some(value) = sequence.next_element()? { + values.push(value); + } + Ok(Json::List(values)) + } + + fn visit_map>(self, mut map: A) -> Result { + let mut pairs: Vec<(String, Json)> = Vec::new(); + while let Some((key, value)) = map.next_entry::()? { + match pairs.iter_mut().find(|(name, _)| *name == key) { + Some(existing) => existing.1 = value, + None => pairs.push((key, value)), + } + } + Ok(Json::Dict(pairs)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn read(text: &str) -> Json { + parse(text, "test").unwrap() + } + + #[test] + fn values_compare_and_hash_as_python_compares_and_hashes_them() { + assert_eq!( + read("[1, 2]").py_cmp(&read("[1]")).unwrap(), + Ordering::Greater + ); + assert_eq!(read("[1]").py_cmp(&read("[1, 2]")).unwrap(), Ordering::Less); + assert_eq!(read("1.5").py_cmp(&read("2")).unwrap(), Ordering::Less); + assert!(read("[1, [2.0], null]").py_eq(&read("[true, [2], null]"))); + assert!(!read("[1, 2]").py_eq(&read("[1, 3]"))); + assert!(!read("{\"a\": 1}").py_eq(&read("{\"b\": 1}"))); + assert!(read("0.5").truthy()); + assert_eq!(read("null").hash_key().unwrap(), "null"); + assert_eq!( + read("2.0").hash_key().unwrap(), + read("2").hash_key().unwrap() + ); + assert_ne!( + read("2.5").hash_key().unwrap(), + read("2").hash_key().unwrap() + ); + let kinds: Vec<&str> = ["null", "false", "1", "1.5", "\"x\"", "[1]", "{}"] + .iter() + .map(|text| read(text).kind()) + .collect(); + assert_eq!( + kinds, + [ + "null", + "a boolean", + "an integer", + "a number", + "a string", + "a list", + "an object" + ] + ); + } + + #[test] + fn numbers_read_as_python_int_reads_them() { + assert_eq!(read("true").int("x").unwrap(), 1); + assert_eq!(read("true").py_int_instance(), Some(1)); + assert_eq!(read("false").py_int("x").unwrap(), 0); + assert_eq!(read("-2.7").py_int("x").unwrap(), -2); + assert_eq!(read("\" +1_000 \"").py_int("x").unwrap(), 1000); + assert_eq!(read("\"-12\"").py_int("x").unwrap(), -12); + } + + #[test] + fn what_the_reference_cannot_read_is_a_shape_refusal() { + let refusals = [ + read("5").get("x").map(|_| ()), + read("\"x\"").list("x").map(|_| ()), + read("1").text("x").map(|_| ()), + read("1.5").int("x").map(|_| ()), + read("[]").py_int("x").map(|_| ()), + read("\"1__0\"").py_int("x").map(|_| ()), + read("[1]").py_cmp(&read("\"a\"")).map(|_| ()), + read("[1]").hash_key().map(|_| ()), + read("5").set("x", Json::Null), + ]; + for (index, refusal) in refusals.into_iter().enumerate() { + assert_eq!( + refusal.unwrap_err().kind, + super::super::RefusalKind::Shape, + "refusal {index}" + ); + } + let mut values = [read("1"), read("\"a\"")]; + let mut references: Vec<&Json> = values.iter_mut().map(|value| &*value).collect(); + assert!(sort_py(&mut references).is_err()); + } + + #[test] + fn a_repeated_key_keeps_its_first_place_and_its_last_value() { + let mut object = read("{\"a\": 1, \"b\": 2, \"a\": 3}"); + object.set("c", Json::Str("d".to_owned())).unwrap(); + object.set("b", Json::Null).unwrap(); + let keys: Vec<&str> = object + .as_dict() + .unwrap() + .iter() + .map(|(key, _)| key.as_str()) + .collect(); + assert_eq!(keys, ["a", "b", "c"]); + assert!(object.at("a").unwrap().eq_int(3)); + assert!(object.at("b").unwrap().is_null()); + } +} diff --git a/src/result_validation/lattice.rs b/src/result_validation/lattice.rs new file mode 100644 index 0000000..720e005 --- /dev/null +++ b/src/result_validation/lattice.rs @@ -0,0 +1,326 @@ +//! Compact lattice results, expanded independently before ordinary validation. +//! +//! The wire summary is an untrusted, reconstructible representation: its lattice parameters +//! must agree with the request before they are used to synthesize placements, and every +//! synthesized placement then passes through the same checks as an explicit one. + +use super::json::{Json, Ordered, Res}; +use super::num::{add, ceil_div, floor_div, mul}; +use super::pyfmt::{py_repr, py_str, tuple}; +use super::spec::{ContainerSpec, ItemSpec, is_rotation}; +use super::{Issue, MalformedResult}; + +const SIDES: [&str; 3] = ["length", "width", "height"]; + +pub(crate) fn materialize( + request: &Json, + result: &Json, + items: &Ordered, + containers: &Ordered, + clearance: i128, + issues: &mut Vec, +) -> Res { + let packed_containers = result.at("containers")?.list("result.containers")?; + if !packed_containers + .iter() + .any(|packed| packed.has("lattice_summary")) + { + return Ok(result.clone()); + } + let empty = Json::Dict(Vec::new()); + let coordinates_optional = matches!( + request + .get_or("configuration", &empty)? + .get("require_placement_coordinates")?, + Some(Json::Bool(false)) + ); + let mut expanded = result.clone(); + let mut rewritten = Vec::with_capacity(packed_containers.len()); + for packed in packed_containers { + let mut packed = packed.clone(); + if let Some(placements) = expand( + &packed, + coordinates_optional, + items, + containers, + clearance, + issues, + )? { + packed.set("placements", Json::List(placements))?; + } + rewritten.push(packed); + } + expanded.set("containers", Json::List(rewritten))?; + Ok(expanded) +} + +/// The placements to write into one container: `None` leaves it untouched. +fn expand( + packed: &Json, + coordinates_optional: bool, + items: &Ordered, + containers: &Ordered, + clearance: i128, + issues: &mut Vec, +) -> Res>> { + let summary = match packed.get("lattice_summary")? { + None | Some(Json::Null) => return Ok(None), + Some(summary) => summary, + }; + let container_id = py_str(packed.get_or("id", &Json::str_of("?"))?); + if !coordinates_optional { + issues.push(Issue::new( + "unexpected_lattice_summary", + format!("{container_id}: request requires explicit placement coordinates"), + )); + } + if packed.get_null("placements")?.truthy() { + issues.push(Issue::new( + "lattice_placements_conflict", + format!( + "{container_id}: compact summary and explicit placements are mutually exclusive" + ), + )); + } + let item_type = summary.get_null("item_type")?; + let item = items.get(item_type)?; + let container = containers.get(packed.get_null("container_type")?)?; + let (Some(item), Some(container)) = (item, container) else { + // The ordinary accounting and container checks report the unknown reference. + return Ok(None); + }; + + let fields = Fields::read(summary, &container_id)?; + let problems = problems(&fields, item, item_type, container, clearance)?; + if !problems.is_empty() { + issues.extend(problems.into_iter().map(|problem| { + Issue::new( + "lattice_summary_mismatch", + format!("{container_id}: {problem}"), + ) + })); + return Ok(Some(Vec::new())); + } + synthesize(&fields, summary, item_type, &container_id, clearance).map(Some) +} + +struct Fields { + orientation: Json, + physical: [Json; 3], + envelope: [Json; 3], + nx: Json, + ny: Json, + layers_used: Json, + layer_step: Json, + count: Json, +} + +impl Fields { + fn read(summary: &Json, container_id: &str) -> Res { + let read = || -> Res { + let sides = |key: &str| -> Res<[Json; 3]> { + let block = summary.at(key)?; + Ok([ + block.at(SIDES[0])?.at("ticks")?.clone(), + block.at(SIDES[1])?.at("ticks")?.clone(), + block.at(SIDES[2])?.at("ticks")?.clone(), + ]) + }; + Ok(Fields { + orientation: summary.at("orientation")?.clone(), + physical: sides("physical_dimensions")?, + envelope: sides("envelope_dimensions")?, + nx: summary.at("nx")?.clone(), + ny: summary.at("ny")?.clone(), + layers_used: summary.at("layers_used")?.clone(), + layer_step: summary.at("layer_step")?.at("ticks")?.clone(), + count: summary.at("count")?.clone(), + }) + }; + // The reference reports a missing field as a contract break, naming the container. + read().map_err(|error| { + MalformedResult::contract(format!( + "{container_id}: lattice_summary is missing a canonical field: {}", + error.message + )) + }) + } +} + +fn json_tuple(values: &[Json]) -> String { + tuple(values.iter().map(py_repr)) +} + +fn problems( + fields: &Fields, + item: &ItemSpec, + item_type: &Json, + container: &ContainerSpec, + clearance: i128, +) -> Res> { + let mut problems = Vec::new(); + if !is_rotation(&fields.orientation)? { + problems.push(format!( + "unknown orientation {}", + py_repr(&fields.orientation) + )); + } else { + let orientation = fields.orientation.text("orientation")?; + let expected = item.rotated(orientation)?; + if !fields + .physical + .iter() + .zip(expected) + .all(|(reported, value)| reported.eq_int(value)) + { + problems.push(format!( + "physical dimensions {} != rotated item {}", + json_tuple(&fields.physical), + super::pyfmt::int_tuple(&expected), + )); + } + if !item.allows(&fields.orientation) { + problems.push(format!( + "orientation {orientation} is forbidden for {}", + py_str(item_type) + )); + } + } + let mut expected_envelope = Vec::with_capacity(3); + for side in &fields.physical { + expected_envelope.push(add(side.int("physical dimension")?, mul(2, clearance)?)?); + } + if !fields + .envelope + .iter() + .zip(&expected_envelope) + .all(|(reported, value)| reported.eq_int(*value)) + { + problems.push(format!( + "envelope dimensions {} != physical+clearance {}", + json_tuple(&fields.envelope), + super::pyfmt::int_tuple(&expected_envelope), + )); + } + if item.nesting_height.is_some() { + problems.push("compact lattice form is not valid for nesting items".to_owned()); + } + if !fields.layer_step.py_eq(&fields.envelope[2]) { + problems.push(format!( + "layer_step {} != envelope height {}", + py_str(&fields.layer_step), + py_str(&fields.envelope[2]), + )); + } + for (name, value) in [ + ("nx", &fields.nx), + ("ny", &fields.ny), + ("layers_used", &fields.layers_used), + ("layer_step", &fields.layer_step), + ("count", &fields.count), + ] { + if !value.strict_int().is_some_and(|number| number >= 1) { + problems.push(format!( + "{name} must be a positive integer, got {}", + py_repr(value) + )); + } + } + if problems.is_empty() { + independent_counts(fields, item, container, &mut problems)?; + } + Ok(problems) +} + +/// Only reached once every field is a positive integer and the envelope is the expected one. +fn independent_counts( + fields: &Fields, + item: &ItemSpec, + container: &ContainerSpec, + problems: &mut Vec, +) -> Res<()> { + let int = |value: &Json| value.int("lattice field"); + let (nx, ny, layers_used, layer_step, count) = ( + int(&fields.nx)?, + int(&fields.ny)?, + int(&fields.layers_used)?, + int(&fields.layer_step)?, + int(&fields.count)?, + ); + let expected_nx = floor_div(container.inner[0], int(&fields.envelope[0])?)?; + let expected_ny = floor_div(container.inner[1], int(&fields.envelope[1])?)?; + let expected_layers = ceil_div(count, mul(nx, ny)?)?; + if nx != expected_nx { + problems.push(format!("nx {nx} != independently computed {expected_nx}")); + } + if ny != expected_ny { + problems.push(format!("ny {ny} != independently computed {expected_ny}")); + } + if layers_used != expected_layers { + problems.push(format!( + "layers_used {layers_used} != independently computed {expected_layers}" + )); + } + let quantity = item.quantity.int("quantity")?; + if count > quantity { + problems.push(format!( + "count {count} exceeds requested quantity {}", + py_str(&item.quantity) + )); + } + let vertical_capacity = floor_div(container.inner[2], layer_step)?; + if layers_used > vertical_capacity { + problems.push(format!( + "layers_used {layers_used} exceeds vertical capacity {vertical_capacity}" + )); + } + Ok(()) +} + +fn synthesize( + fields: &Fields, + summary: &Json, + item_type: &Json, + container_id: &str, + clearance: i128, +) -> Res> { + let int = |value: &Json| value.int("lattice field"); + let (nx, ny, count, layer_step) = ( + int(&fields.nx)?, + int(&fields.ny)?, + int(&fields.count)?, + int(&fields.layer_step)?, + ); + let envelope = [int(&fields.envelope[0])?, int(&fields.envelope[1])?]; + let per_layer = mul(nx, ny)?; + let physical = summary.at("physical_dimensions")?.clone(); + let mut placements = Vec::new(); + for index in 0..count { + let tick = |value: i128| Json::Dict(vec![("ticks".to_owned(), Json::Int(value))]); + let x = add(mul(index % nx, envelope[0])?, clearance)?; + let y = add(mul((index / nx) % ny, envelope[1])?, clearance)?; + let z = add(mul(index / per_layer, layer_step)?, clearance)?; + placements.push(Json::Dict(vec![ + ( + "item_id".to_owned(), + Json::Str(format!( + "{}#lattice:{container_id}:{}", + py_str(item_type), + index + 1 + )), + ), + ("item_type".to_owned(), item_type.clone()), + ("orientation".to_owned(), fields.orientation.clone()), + ( + "position".to_owned(), + Json::Dict(vec![ + ("x".to_owned(), tick(x)), + ("y".to_owned(), tick(y)), + ("z".to_owned(), tick(z)), + ]), + ), + ("dimensions".to_owned(), physical.clone()), + ])); + } + Ok(placements) +} diff --git a/src/result_validation/mod.rs b/src/result_validation/mod.rs new file mode 100644 index 0000000..8f0de60 --- /dev/null +++ b/src/result_validation/mod.rs @@ -0,0 +1,354 @@ +//! `validate_json`: language-neutral validation of a packing result. +//! +//! A port of the reference validator, `packvium.validate` (packvium-python's +//! `result_validation.py`), over the JSON documents rather than this crate's model. It shares no +//! code with the solvers or with [`crate::IndependentValidator`]: units, geometry, support and load +//! are all recomputed here from the request and the reported placements, because a validator +//! built on the engine's own code would agree with the engine's bugs. Every issue code and every +//! detail string is the reference's, Python spelling included, so one result gets the same issue +//! list from every package (docs/VALIDATION-CONTRACT.md). +//! +//! Where the reference computes on a value of the wrong type (a float tick, a string quantity) +//! this port refuses the result instead of following Python's arithmetic, and it refuses any +//! value too large to compute exactly in `i128`. Both are [`MalformedResult`]s. + +mod accounting; +mod container; +mod facts; +mod geometry; +mod json; +mod lattice; +mod nonprintable; +mod num; +mod objective; +mod pyfmt; +mod spec; +mod stacking; +mod units; + +use std::cell::Cell; +use std::fmt; + +use serde::Serialize; + +use json::{Json, Ordered, Res}; +use units::{LENGTH, ratio_of, to_ticks}; + +/// One way a result fails to be a sound answer to its request. +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +pub struct ResultIssue { + pub code: String, + pub detail: String, +} + +pub(crate) type Issue = ResultIssue; + +impl ResultIssue { + pub(crate) fn new(code: &str, detail: String) -> ResultIssue { + ResultIssue { + code: code.to_owned(), + detail, + } + } +} + +impl fmt::Display for ResultIssue { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(formatter, "{}: {}", self.code, self.detail) + } +} + +/// How the reference answers the same input. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum RefusalKind { + /// The reference raises `MalformedResult` with this message. Where the reference's message + /// quotes a Python exception (a placement or lattice summary missing a field), the text + /// after that quote is this port's own account of the same failure. + Contract, + /// The reference fails on the input some other way (a missing key, a value of the wrong + /// type), or a value is beyond what this port computes exactly. The message is this port's. + Shape, +} + +/// The documents do not have the shape the contract requires: a contract break, not a packing +/// defect, so no issue list is returned. +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +pub struct MalformedResult { + pub kind: RefusalKind, + pub message: String, +} + +impl MalformedResult { + pub(crate) fn contract(message: String) -> MalformedResult { + MalformedResult { + kind: RefusalKind::Contract, + message, + } + } + + pub(crate) fn shape(message: String) -> MalformedResult { + MalformedResult { + kind: RefusalKind::Shape, + message, + } + } +} + +impl fmt::Display for MalformedResult { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.write_str(&self.message) + } +} + +impl std::error::Error for MalformedResult {} + +/// A packed container's id as an issue prints it. The reference reads `packed["id"]` only +/// while formatting an issue, so a missing id fails only once an issue needs it; `verify` +/// reports that after the check, which aborts the run exactly as the reference's `KeyError` does. +pub(crate) struct Label { + text: Option, + missing_used: Cell, +} + +impl Label { + pub(crate) fn of(packed: &Json) -> Res