From fbfe43bcd1f956a254ee480389b9324e3d0a06c6 Mon Sep 17 00:00:00 2001 From: Anton Date: Mon, 14 Sep 2026 09:44:16 -0400 Subject: [PATCH] chore(release): sync 1.2.0 from workspace --- .github/workflows/release.yml | 38 ++++++ CHANGELOG.md | 107 ++++++++++++++++ README.md | 3 + docs/GUARANTEES.md | 2 +- docs/PUBLIC-API.md | 134 +++++++++++++++++++ examples/basic.mjs | 4 + examples/constraints.mjs | 6 +- examples/execution.mjs | 150 ++++++++++++++++++++++ examples/objectives.mjs | 17 ++- examples/shapes.mjs | 7 +- examples/units.mjs | 7 + execution.d.ts | 54 ++++++++ execution.js | 235 ++++++++++++++++++++++++++++++++++ fallback.js | 57 +++++++-- index.js | 2 +- package.json | 6 +- test/execution.test.mjs | 229 +++++++++++++++++++++++++++++++++ test/fallback.test.mjs | 49 ++++++- test/package-exports.test.mjs | 73 +++++++++++ 19 files changed, 1157 insertions(+), 23 deletions(-) create mode 100644 examples/execution.mjs create mode 100644 execution.d.ts create mode 100644 execution.js create mode 100644 test/execution.test.mjs create mode 100644 test/package-exports.test.mjs diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 44ccf9b..b663e98 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -67,3 +67,41 @@ jobs: with: subject-path: "*.tgz" - run: npm publish ./*.tgz --provenance --access public + + # Rule 3: every tag gets a GitHub Release. A tag is a git object; a Release is what a + # human and a maintenance scorer can read, and cadence is a signal tags do not carry. + # Every mirror had every tag and zero Releases until 1.1.0, whose six were created by + # hand -- which is how the rule was being met, and therefore how it would stop being met. + github-release: + needs: publish + runs-on: ubuntu-latest + permissions: + contents: write # the Release is the only thing this workflow writes to the repository + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + - name: Create the GitHub Release from the tag + env: + GH_TOKEN: ${{ github.token }} + run: | + set -euo pipefail + version="${GITHUB_REF_NAME#v}" + if gh release view "$GITHUB_REF_NAME" >/dev/null 2>&1; then + echo "Release $GITHUB_REF_NAME already exists; nothing to do." + exit 0 + fi + # This version's entry, from its heading to the next one. A tag whose version has + # no entry would publish a Release nobody can read, so that fails the job rather + # than shipping an empty one. + awk -v want="## [$version]" ' + index($0, want) == 1 { inside = 1; next } + inside && /^## \[/ { exit } + inside { print } + ' CHANGELOG.md > release-notes.md + if [ ! -s release-notes.md ]; then + echo "CHANGELOG.md carries no entry for $version" >&2 + exit 1 + fi + gh release create "$GITHUB_REF_NAME" \ + --title "Packvium $version" \ + --notes-file release-notes.md \ + --verify-tag diff --git a/CHANGELOG.md b/CHANGELOG.md index 648baf5..1831154 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,113 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). As of `1. public API, the request and result schemas, the numeric and units policy, the validation rules and the compatibility policy are frozen: breaking any of them costs a major version. +## [1.2.0] + +An additive release. A packing result can now be turned into a document an operator can +work from, in all four languages; and, in Python, a proposed catalog change can be +compared, replayed against history and published through an approval step rather than +argued about. + +Nothing here breaks 1.1.0. Every schema change is additive, the frozen Python surface is +unchanged, and the PHP surface grows one new namespace and nothing else. + +### Added + +- **Execution plans, in all four languages.** `packvium.execution`, + `Packvium\Execution\Plan`, `packvium_core::execution` and `@packvium/engine`'s + `execution.js` derive a work order from an already validated result: what to lift, why a + carton was chosen, and what was not packed with its proof level unsoftened. The adapter + calls no solver and no validator — a test in each language asserts that — and given the + same result all four emit a byte-identical canonical form. + + Two properties are part of the format rather than notes about it. Everything the solver + or validator decided sits under `facts`; every human-readable sentence sits under + `presentation` and names the fields it came from in `cites`, so a consumer that reads + only `facts` loses nothing it may rely on. And the step order is **injected**: supply + `loading_orders` and each step is numbered, omit it and the container reports + `order: "unavailable"` with every placement still listed. There is no third behaviour, + because presenting the order the solver happened to walk its candidates in as an order + that is safe to lift boxes in would be a claim nothing supports. + +- **Operator locks, in Python.** `packvium.locks` lets an operator pin a placement and get + a *second* result beside the approved one — never an edit of it, so "what was approved" + and "what was proposed" stay two artifacts. A lock becomes an ordinary placement + constraint, so the re-solve is the same portfolio under the same independent validator: + **a lock cannot produce a placement the engine would otherwise refuse**, and the + strongest thing it can do is reserve its own slot. A lock the solve cannot honour is + reported as unpreserved and names the lock rather than raising; a lock set that + contradicts itself is refused before any solve runs. + + Python-only, deliberately: a lock has no representation in the request schema, so there + is nothing to hand another engine. + +- **Scenario comparison, recommendations and historical replay, in Python.** + `packvium.simulation` compares two pinned scenarios order by order and returns a Pareto + report per order — never a blended delta, because a single number can name a winner that + is worse on the axis a caller actually cares about. `packvium.recommendations` turns that + comparison into a proposal, or returns nothing at all when the paired cohort is too + small, and publishes only through an explicit approval step. `packvium.holdout` replays a + proposal against decisions held out of the evidence that produced it, over the append-only + ledger in `packvium.outcomes`; a packing the injected validator rejects is that arm's + failure at any cost, and realised damage, returns and repacks are reported against the + carton that actually shipped rather than credited to the one that was never tried. + + This surface is supported and **not yet signature-frozen** — a parameter may be renamed + or a returned value gain a field in a minor release, announced here rather than blocked + by a gate. Pin the version if you depend on its exact shape; `docs/PUBLIC-API.md` says + which surfaces carry the stronger promise. + +- **`pack_from_dict` accepts a keyword-only `extensions` registry (Python).** Additive: it + defaults to `None` and every existing call keeps its meaning and its answer. It exists so + a lock can enter the engine as an ordinary request-derived constraint rather than through + a second, lock-aware search path. The registry **adds to** the compiled policy rules and + does not replace them. + +- **Two new worked examples.** `execution` (Python, PHP and Node) turns a result into + numbered steps and shows what "byte-identical" does and does not promise; `intelligence` + (Python) proves a carton change is worth publishing before publishing it. + +### Changed + +- **The solvers do less repeated work, again.** Byte-identical results everywhere. Group + batching in the Rust extreme-point solver drops two quadratic scans over group members + for a single pass, and the PHP and Python grid-admission and load-ordering paths reuse a + prototype profile and a canonical order instead of rebuilding them per candidate. + +- **Every example names its own time budget.** An example that solved on the library default + could print a different answer on a busy machine. Each now sets `time_limit_ms`, far above + what its solve needs; every printed answer is unchanged. + +### Fixed + +- **The JavaScript engine could return fewer placements than it reported packed.** When the + per-container beam search stopped early — on its node limit, the deadline or the effort + budget — it chose the surviving leader without the batches it had not reached yet, so those + items were neither placed nor listed as unpacked while the result still said `feasible`. It + needs `solver_profile: "quality"` or an explicit `container_plan_beam_width` above 1, and it + shipped in `@packvium/engine` `1.0.0` and `1.1.0`. The default profiles never reach that + path, and Python, PHP and Rust were never affected. If you run the JavaScript engine on the + `quality` profile, check `packed_item_count` against the placements you actually received + from those versions. + +- **The intelligence modules would not have imported on Python 3.9**, which is the minimum + the package declares. Six modules used `dataclass(slots=True)` from the standard library; + that argument does not exist before 3.10, so importing any of them raised `TypeError` on a + supported runtime. They now route through the package's own compatibility shim, as the + rest of the package already did. + +- **`@packvium/engine` did not expose its execution plan.** The module was named in the + package manifest but not in `exports`, so `import '@packvium/engine/execution.js'` failed + with `ERR_PACKAGE_PATH_NOT_EXPORTED` and the main entry re-exported neither function. The + subpath is now declared, with TypeScript declarations beside it. + +- **A non-finite metric is refused rather than ranked as optimal.** `NaN` makes both `>` and + `<` false, so an axis carrying one was silently counted equal and a candidate whose metrics + were all `NaN` arrived on the Pareto frontier beside a clean one. It is now refused by a + named error that says which candidate and which axis. Infinities are still accepted: they + are ends of the number line, and a caller encoding "unpriceable" as an infinite cost gets + the answer they mean. + ## [1.1.0] An additive release on the 1.0.0 freeze. Route-aware unloading becomes a property of the diff --git a/README.md b/README.md index 4dd1047..1296559 100644 --- a/README.md +++ b/README.md @@ -108,6 +108,7 @@ and execute without a project around it. | [`constraints.mjs`](examples/constraints.mjs) | Stacking caps, incompatible tags and atomic groups — each shown with and without the rule, plus how to read the structured refusal. | | [`units.mjs`](examples/units.mjs) | Why lengths travel as strings: fractional inches kept exact, one tick deciding a fit, and the point where a JavaScript number stops being exact and a quote is refused rather than rounded. | | [`commerce.mjs`](examples/commerce.mjs) | Rate a shipment, apply an eligibility rule, and pin a catalog version. | +| [`execution.mjs`](examples/execution.mjs) | Turn a result into dock instructions — and the clearest place to see what "byte-identical" does and does not promise: the four adapters agree on any given result, while this engine is free to reach a different packing than Python does. | ```bash node examples/basic.mjs @@ -121,6 +122,8 @@ node examples/basic.mjs - JSON input/output through `pack()` or `packJson()`. - Optional payload rebalancing with `rebalanceWeight()`. - Loading and removal sequence helpers for already placed boxes. +- Execution plans through `buildExecutionPlan()` / `canonicalPlanJson()`: a work-order view of a + result, with solver facts separated from the text that cites them. - Deterministic carrier quotes, policy evaluation and effective-dated catalog lookup through `commerce`. diff --git a/docs/GUARANTEES.md b/docs/GUARANTEES.md index 34bed67..44a9cea 100644 --- a/docs/GUARANTEES.md +++ b/docs/GUARANTEES.md @@ -48,7 +48,7 @@ silently — if you need them, they belong in your own layer above this library. ## Status of this release -Version `1.1.0` freezes the public API. Field names, status codes, the objective +Version `1.2.0` freezes the public API. Field names, status codes, the objective vector, the numeric policy and the validation rules do not change without a major version, so any `1.x` is a safe upgrade from any earlier `1.x`. A caret or tilde constraint on `1.0` is enough; an exact pin is no longer required. diff --git a/docs/PUBLIC-API.md b/docs/PUBLIC-API.md index 9996b03..ecf9af0 100644 --- a/docs/PUBLIC-API.md +++ b/docs/PUBLIC-API.md @@ -113,6 +113,43 @@ move backwards. This is a testing seam, not a serialized request field. catalog was involved), preserved by Python, PHP, Rust and JavaScript; - warnings and top-K alternatives. +### `alternatives`, and what it is not + +Each entry in `alternatives[]` is a **complete result in its own right**, with its own score +vector, containers and unpacked items — the schema says `$ref: "#"` and means it. + +**`configuration.alternatives` counts the winner.** It is the size of the ranked set the +portfolio keeps, so the list of runners-up holds at most `alternatives - 1` entries. The +schema's own minimum, `alternatives: 1`, therefore returns an **empty** list. Ask for `2` to +receive one. + +**The list is per-engine and is not part of the cross-language contract.** Implementations +are not required to explore the same number of portfolio starts — under this engine's own +profiles a request may run one start, nine, or twenty-two — so PHP, Python, Rust and +JavaScript will not generally return the same runners-up, the same number of them, or the +same scores. Do not diff `alternatives` across implementations. Three properties *are* +required of every implementation: + +1. each entry is a complete result that satisfies the result schema on its own; +2. no alternative's score is lexicographically better than the winner's — if one were, it + would be the winner; +3. the list holds at most `configuration.alternatives - 1` entries. + +**An empty list is normal, and it does not mean "nothing else was possible".** Read +`termination.starts`, which names every portfolio start, whether it completed, and which was +selected. Four situations produce an empty list, and only the last is about the difficulty of +the request: + +| Situation | What `termination.starts` shows | +| --- | --- | +| `solver_profile: fast` runs a single solver | one start — this profile can never rank a runner-up | +| `alternatives: 1` | any number of starts, and a cap of zero runners-up | +| only one start finished within the budget | several starts, `completed: true` on one | +| the grid lattice packed everything, so the portfolio stopped | one start, `grid:volume`, selected | + +If you want alternatives, ask for a profile that explores (`balanced` or `quality`) and a +count of at least `2`. + ### Solver metrics Every result, including each alternative, contains an `algorithm.metrics` object: @@ -421,6 +458,103 @@ tariff effective at that instant, no rate for that zone -- is a successful call `"status": "rejected"` with a code from a closed set, exactly as an infeasible packing request returns a result with a status rather than raising. +## Execution plan + +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. + +| Language | Entry point | +| --- | --- | +| Python | `packvium.execution.build_execution_plan(request, result, loading_orders=...)`, `.canonical_plan_json(plan)` | +| PHP | `Packvium\Execution\Plan::build(array $request, array $result, array $loadingOrders = [])`, `::canonicalJson(array $plan)` | +| Rust | `packvium_core::execution::build_plan_json(result_json, loading_orders_json)` | +| JavaScript | `buildExecutionPlan(request, result, {loadingOrders})`, `canonicalPlanJson(plan)` from `@packvium/engine`'s `execution.js` | + +All four are held to **byte-identical** output on the canonical form, over the whole golden +corpus. That is stricter than the packing contract, which allows two engines to place items +differently and compares an objective floor: a plan is derived from a result, so there is +nothing left to differ about. The plan's own JSON Schema is closed — an extra key in one +implementation is a divergence, not a nicety. + +**The step order is injected.** The engines compute a safe loading order from geometry the +adapter never sees, so `loading_orders` is optional: supply it and each step is numbered, +omit it and the container reports `order: "unavailable"` with every placement still listed. +There is no third behaviour, because falling back to the order placements appear in would +present an artifact of how the solver walked its candidates as an order safe to lift boxes +in. + +**Facts and presentation are separate in the output.** Anything the solver or validator +decided is under `facts`; every human-readable sentence is under `presentation` and names +the authoritative fields it was built from in `cites`. A downstream system that reads only +`facts` loses nothing it is entitled to rely on, and an `unpacked_items[].proof.level` of +`observed` stays `observed` in both. + +**Operator locks re-solve; they never edit the plan.** An operator who pins a placement +gets a *new* result beside the approved one rather than an edit of it, so "what was +approved" and "what was proposed" stay two artifacts instead of two states of one. + +| Language | Entry point | +| --- | --- | +| Python | `packvium.locks.resolve_with_locks(request, locks)`, `.locks_from_plan(plan, ...)`, `.lock_registry(locks)` | +| PHP, Rust, JavaScript | **not exported** | + +Each lock becomes an ordinary placement constraint, so the re-solve is the same portfolio +under the same independent validator that any other request gets. There is no lock-aware +solver and no relaxed validation: **a lock cannot produce a placement the engine would +otherwise refuse**, and the strongest thing it can do is reserve its own slot. A lock the +solve cannot honour comes back on `LockedResolve` as unpreserved and names the lock — it is +an outcome, not an exception — while a lock set that contradicts itself, by overlapping or +by naming an item the request does not contain, is refused with `LockSetError` before any +solve runs. + +Python only, and deliberately so: a lock has no representation in the request schema, since +that field is held for the next contract freeze, so there is nothing to hand another engine. + +## 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. + +| Language | Entry point | +| --- | --- | +| Python | `packvium.simulation.run_scenario(...)`, `.compare_scenarios(...)`; `packvium.recommendations.propose_recommendation(...)`, `.approve_catalog(...)`, `.approve_policy(...)`; `packvium.holdout.evaluate_on_history(...)` over a `packvium.outcomes.OutcomeLedger` | +| PHP, Rust, JavaScript | **not exported** | + +**Python only, and held to no cross-language conformance.** Every other contract in this +document is proved by driving four engines as subprocesses over JSON. `run_scenario` takes +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. + +**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 +exported until `packvium.outcomes` was, because a function whose central argument a caller +cannot construct is worse than an unexported one. Two rules are enforced as control flow +rather than documented: a packing the injected validator rejects is that arm's failure at +any cost and its metrics never reach the comparison, and the validator is handed the +request/result pair with no score in it. Only the deterministically recomputable part of an +outcome is scored -- realised damage, returns, repacks and operator overrides happened +under the carton that actually shipped, so they are reported against the baseline and never +credited to the treatment. + +`compare_scenarios` returns a Pareto report per order and never a blended delta, and +`propose_recommendation` returns `None` rather than a low-confidence proposal when the +paired cohort is too small. Neither writes to a registry: publishing goes only through +`approve_catalog` / `approve_policy`, and a proposal is handed no registry to write to. + +**Supported, and not yet frozen.** This surface and `packvium.locks` are reached by +importing the submodule, which puts them outside the frozen API snapshot the packing and +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. + ## JSON API Python, PHP, Rust and the JavaScript fallback accept the same top-level keys: `units`, diff --git a/examples/basic.mjs b/examples/basic.mjs index 3b3f6f9..0e0b634 100644 --- a/examples/basic.mjs +++ b/examples/basic.mjs @@ -19,6 +19,10 @@ import { backend, pack, version } from '../index.js'; console.log(`engine ${version()} using the ${backend()} backend\n`); const request = { + // An example must not change answer merely because the host was busy. This solve needs + // a fraction of the budget; the generous wall-clock value is only a safety fuse, so a + // loaded machine cannot cut the multi-start portfolio short and let a different start win. + configuration: { time_limit_ms: 60000 }, items: [ // Lengths and weights are strings on purpose. They are parsed into exact integers, // so '0.1' means a tenth of a millimetre and never 0.09999999999999999. Plain diff --git a/examples/constraints.mjs b/examples/constraints.mjs index 0c35e43..8fd223d 100644 --- a/examples/constraints.mjs +++ b/examples/constraints.mjs @@ -18,6 +18,10 @@ import { pack } from '../index.js'; const MM = { units: { length: 'mm' } }; +// An example must not change answer merely because the host was busy. These solves need +// a fraction of the budget; the generous wall-clock value is only a safety fuse, so a +// loaded machine cannot cut the multi-start portfolio short and let a different start win. +const SAFETY_FUSE = { configuration: { time_limit_ms: 60000 } }; /** * Pack one variant and print what it cost. @@ -27,7 +31,7 @@ const MM = { units: { length: 'mm' } }; * you actually wanted to see coming. */ const solve = (label, items, containers) => { - const result = pack({ ...MM, items, containers }); + const result = pack({ ...MM, ...SAFETY_FUSE, items, containers }); const placed = result.containers.reduce((n, c) => n + c.placements.length, 0); console.log( ` ${label.padEnd(20)} ${result.containers.length} container(s), ` + diff --git a/examples/execution.mjs b/examples/execution.mjs new file mode 100644 index 0000000..e955563 --- /dev/null +++ b/examples/execution.mjs @@ -0,0 +1,150 @@ +/** + * Turn a packing result into instructions someone can follow on a dock. + * + * Run it: + * + * node examples/execution.mjs + * + * `pack()` answers where every box goes. That answer is not yet a work order: it does not + * say what to lift first, and it does not separate what the solver *decided* from what a + * screen should *say*. + * + * The execution plan is that second document. It is derived from an already validated + * result -- it calls no solver and no validator, and a test in each language asserts so. + * + * The scene is the same one `examples/execution.py` and `examples/execution.php` build, + * and the last section is the interesting one: this engine reaches a *different* packing + * than they do, which is allowed, and the section explains exactly which promise that + * does and does not break. + */ + +import { pack } from '../index.js'; +import { buildExecutionPlan, canonicalPlanJson } from '../execution.js'; + +/** + * One crate, a printer that must stay upright, four toner cartridges, and a pallet jack + * that was never going to fit. The last one is deliberate: an execution plan has to say + * what is *not* going on the truck as clearly as what is. + */ +const request = { + units: { length: 'mm' }, + configuration: { + objective: 'default', + profile: 'balanced', + seed: 42, + // A safety fuse, not a target -- nothing in this scene comes close to it. + time_limit_ms: 60000, + }, + items: [ + { id: 'printer', quantity: 1, weight: '9 kg', keep_upright: true, + dimensions: { length: '420', width: '340', height: '260' } }, + { id: 'toner', quantity: 4, weight: '900 g', + dimensions: { length: '180', width: '120', height: '100' } }, + { id: 'pallet-jack', quantity: 1, weight: '80 kg', + dimensions: { length: '1200', width: '550', height: '1200' } }, + ], + containers: [ + { id: 'crate', quantity: 1, max_payload: '30 kg', + inner_dimensions: { length: '600', width: '400', height: '400' } }, + ], +}; + +const result = pack(request); +const plan = buildExecutionPlan(request, result); +const container = plan.containers[0]; +const rule = '='.repeat(78); + +console.log(rule); +console.log('1. What the solver decided, kept apart from what a screen says'); +console.log(rule); +console.log(); + +console.log(` format: ${plan.format}`); +console.log(` status: ${plan.facts.status}`); +console.log(` containers used: ${plan.facts.container_count}`); +console.log(` score: [${plan.facts.score.join(', ')}]`); +console.log(` utilization: ${container.facts.volume_utilization}`); +console.log(); +console.log(" Everything above is under `facts`. It is the solver's own answer, copied and"); +console.log(' not re-derived, so a downstream system that reads only `facts` loses nothing it'); +console.log(' is entitled to rely on. The score stays a vector: collapsing five axes into one'); +console.log(' number is a judgement about your priorities that this document does not make.'); +console.log(); + +console.log(rule); +console.log('2. The step order is injected, or it is honestly absent'); +console.log(rule); +console.log(); + +console.log(` order: ${container.order}`); +for (const step of container.steps) { + const { item_type: itemType, orientation, position_ticks: ticks } = step.placement; + console.log(` ${itemType.padEnd(9)} ${orientation} at (${ticks.x}, ${ticks.y}, ${ticks.z})`); +} +console.log(); +console.log(' Every placement is listed and not one is numbered. The engines compute a safe'); +console.log(' loading order from geometry this adapter never sees, so without one it says'); +console.log(' `unavailable` rather than guessing.'); +console.log(); +console.log(' There is no third behaviour on purpose. Falling back to the order placements'); +console.log(' happen to appear in would present an artifact of how the solver walked its'); +console.log(' candidate points as an order that is safe to lift boxes in. It is not.'); +console.log(); + +const reversed = container.steps.map((_, index) => index).reverse(); +const ordered = buildExecutionPlan(request, result, { loadingOrders: { 0: reversed } }); +console.log(` order: ${ordered.containers[0].order}`); +for (const step of ordered.containers[0].steps) { + console.log(` ${step.sequence}. ${step.placement.item_type}`); +} +console.log(); +console.log(' Hand it an order and each step is numbered. The order above is reversed on'); +console.log(' purpose, to show that the sequence is the one you supplied and not one the'); +console.log(' adapter re-derived behind your back.'); +console.log(); + +console.log(rule); +console.log('3. Every sentence names the fields it was built from'); +console.log(rule); +console.log(); + +for (const entry of plan.unplaced) { + const { facts, presentation } = entry; + console.log(` facts: item_type='${facts.item_type}'`); + console.log(` reason='${facts.reason}' proof_level='${facts.proof_level}'`); + console.log(` presentation: ${presentation.summary}`); + console.log(` cites: ${presentation.cites.join(', ')}`); +} +console.log(); +console.log(' `proven` is a claim about a search, not a summary of one: no orientation of the'); +console.log(' pallet jack fits any offered crate, so nothing was tried and nothing needed to'); +console.log(' be. A reason with no citation would be a sentence nobody can check, which is'); +console.log(' why `cites` is part of the format rather than a convention.'); +console.log(); + +console.log(rule); +console.log('4. Byte-identical is a promise about the adapter, not about the search'); +console.log(rule); +console.log(); + +const canonical = canonicalPlanJson(plan); +console.log(` canonical form: ${canonical.length} bytes, first 68 of them`); +console.log(` ${canonical.slice(0, 68)}...`); +console.log(); +console.log(' Run the Python and PHP files on this same scene and you get 1877 bytes, not'); +console.log(` ${canonical.length}. Nothing is broken. The two claims are different, and this is the`); +console.log(' clearest place to see it:'); +console.log(); +console.log(' * Given the *same result*, all four adapters emit the same bytes. That is what'); +console.log(' the conformance run proves — it feeds every engine the committed golden'); +console.log(' results and compares byte for byte.'); +console.log(); +console.log(' * Given the same *request*, the engines are not required to agree. Python and'); +console.log(' PHP are held to identical placements; Rust and JavaScript are held to a valid'); +console.log(' answer at or above the objective floor. This engine found a different one.'); +console.log(); +console.log(' So a plan is a faithful projection of whatever result you hand it, and the'); +console.log(' question of which engine packed better is a separate one the plan never answers.'); +console.log(); +console.log(' Operator locks continue this story and are Python-only: a lock has no'); +console.log(' representation in the request schema, so there is nothing to hand another engine.'); diff --git a/examples/objectives.mjs b/examples/objectives.mjs index 4632bc5..27dfbd0 100644 --- a/examples/objectives.mjs +++ b/examples/objectives.mjs @@ -25,6 +25,11 @@ const widgets = [{ weight: '500 g', }]; +// An example must not change answer merely because the host was busy. These solves need +// a fraction of the budget; the generous wall-clock value is only a safety fuse, so a +// loaded machine cannot cut the multi-start portfolio short and let a different start win. +const SAFETY_FUSE_MS = 60000; + const solve = (configuration, containers) => { const result = pack({ units: { length: 'mm' }, configuration, items: widgets, containers }); const chosen = result.containers.length > 0 ? result.containers[0].container_type : 'none'; @@ -49,18 +54,18 @@ const roomy = box('roomy', '400', { cost_minor: 150 }); // `default` -- fewest containers, then tightest fit. What you want when the boxes are // interchangeable and you are simply trying not to open another one. -console.log('default ', solve({ seed: 42 }, [snug, roomy])); +console.log('default ', solve({ seed: 42, time_limit_ms: SAFETY_FUSE_MS }, [snug, roomy])); // `lowest_cost` -- the cheapest *packaging*. `cost_minor` is what the box costs you, so // this is the objective for a warehouse buying cartons, not a shipper paying a carrier. -console.log('lowest_cost ', solve({ seed: 42, objective: 'lowest_cost' }, [snug, roomy])); +console.log('lowest_cost ', solve({ seed: 42, objective: 'lowest_cost', time_limit_ms: SAFETY_FUSE_MS }, [snug, roomy])); // `shipping_cost` -- carrier-billable *weight*: the greater of actual gross weight and // dimensional weight. A big light box can bill more than a small heavy one, which is why // this is not the same objective as `lowest_cost`. It needs a divisor and refuses rather // than guessing one, because a wrong divisor silently misprices every shipment. console.log('shipping_cost ', - solve({ seed: 42, objective: 'shipping_cost', ...weightPricing }, [snug, roomy])); + solve({ seed: 42, objective: 'shipping_cost', time_limit_ms: SAFETY_FUSE_MS, ...weightPricing }, [snug, roomy])); // `lowest_landed_cost` -- carrier-billable *money*, with the rate card arriving as // request data. Weight and money do not always agree: a bracket step, or a minimum @@ -73,7 +78,7 @@ const dearPerGram = box('snug', '300', { const cheapPerGram = box('roomy', '400', { rate_table: { weight_brackets_g: [6000, 20000], prices_minor: [900, 1500] }, }); -const byMoney = { seed: 42, objective: 'lowest_landed_cost', ...weightPricing }; +const byMoney = { seed: 42, objective: 'lowest_landed_cost', time_limit_ms: SAFETY_FUSE_MS, ...weightPricing }; console.log('lowest_landed_cost ', solve(byMoney, [dearPerGram, cheapPerGram])); // A rate card that stops short of the shipment is a refusal, never a silent clamp to the @@ -90,7 +95,7 @@ try { // `open_dimension_height` -- pack into the shortest stack, for a lidless container or a // pallet that has to clear a doorway. console.log('open_dimension_height', - solve({ seed: 42, objective: 'open_dimension_height' }, [snug, roomy])); + solve({ seed: 42, objective: 'open_dimension_height', time_limit_ms: SAFETY_FUSE_MS }, [snug, roomy])); // `maximum_value` -- when not everything fits, leave the *cheap* things behind. It orders // by value; it does not solve the knapsack problem to optimality. `quantity: 1` on the @@ -98,7 +103,7 @@ console.log('open_dimension_height', // simply opens another box. const scarce = pack({ units: { length: 'mm' }, - configuration: { seed: 42, objective: 'maximum_value' }, + configuration: { seed: 42, objective: 'maximum_value', time_limit_ms: SAFETY_FUSE_MS }, items: [ { id: 'gold', quantity: 2, dimensions: { length: '100', width: '100', height: '100' }, weight: '500 g', value: 90000 }, { id: 'gravel', quantity: 2, dimensions: { length: '100', width: '100', height: '100' }, weight: '500 g', value: 10 }, diff --git a/examples/shapes.mjs b/examples/shapes.mjs index 9037d20..ec9da3f 100644 --- a/examples/shapes.mjs +++ b/examples/shapes.mjs @@ -24,13 +24,17 @@ import { pack } from '../index.js'; const MM = { units: { length: 'mm' } }; +// An example must not change answer merely because the host was busy. These solves need +// a fraction of the budget; the generous wall-clock value is only a safety fuse, so a +// loaded machine cannot cut the multi-start portfolio short and let a different start win. +const SAFETY_FUSE = { configuration: { time_limit_ms: 60000 } }; const crate = (length, width, height) => [ { id: 'crate', inner_dimensions: { length, width, height } }, ]; /** Run one request and print only what the shape changed: containers and refusals. */ const summarise = (label, request) => { - const result = pack({ ...MM, ...request }); + const result = pack({ ...MM, ...SAFETY_FUSE, ...request }); const placed = result.containers.reduce((n, c) => n + c.placements.length, 0); console.log( ` ${label.padEnd(22)} ${result.status.padEnd(10)} ` + @@ -119,6 +123,7 @@ const brick = (kilograms) => ({ const load = (label, kilograms) => { const result = pack({ ...MM, + ...SAFETY_FUSE, items: [cushion(100), brick(kilograms)], containers: crate('100', '100', '200'), }); diff --git a/examples/units.mjs b/examples/units.mjs index d79dbed..6a4dea6 100644 --- a/examples/units.mjs +++ b/examples/units.mjs @@ -18,6 +18,11 @@ import { pack, commerce, CommerceInputError } from '../index.js'; +// An example must not change answer merely because the host was busy. These solves need +// a fraction of the budget; the generous wall-clock value is only a safety fuse, so a +// loaded machine cannot cut the multi-start portfolio short and let a different start win. +const SAFETY_FUSE_MS = 60000; + // ------------------------------------------------------------- fractions survive intact // // Imperial sizes arrive as fractions far more often than as decimals, and "12 3/8" is an @@ -26,6 +31,7 @@ import { pack, commerce, CommerceInputError } from '../index.js'; const inches = pack({ units: { length: 'in' }, + configuration: { time_limit_ms: SAFETY_FUSE_MS }, items: [{ id: 'plank', quantity: 2, dimensions: { length: '12 3/8', width: '8 1/2', height: '3/4' } }], containers: [{ id: 'crate', inner_dimensions: { length: '24', width: '24', height: '24' } }], }); @@ -51,6 +57,7 @@ const TICKS_PER_MM = 16000; const fit = (containerMm) => { const result = pack({ units: { length: 'mm' }, + configuration: { time_limit_ms: SAFETY_FUSE_MS }, items: [{ id: 'rod', quantity: 1, dimensions: { length: '100', width: '10', height: '10' } }], containers: [{ id: 'tube', inner_dimensions: { length: containerMm, width: '10', height: '10' } }], }); diff --git a/execution.d.ts b/execution.d.ts new file mode 100644 index 0000000..4cb4108 --- /dev/null +++ b/execution.d.ts @@ -0,0 +1,54 @@ +// Types for `@packvium/engine/execution.js` — the execution-plan adapter. +// +// The split between `facts` and `presentation` is part of the contract rather than a +// convention, so it is spelt out here: `facts` is copied from the validated result and is +// what a downstream system may rely on; every `presentation.summary` names the fields it +// was built from in `cites`. A consumer that reads only `facts` loses nothing. +import type { PackingRequest, PackingResult, ResultFact } from './index.js'; + +export const FORMAT: 'packvium-execution-plan/v1'; +export const UNNAMED_AXIS: string; + +export class ExecutionPlanError extends Error {} + +export interface PositionTicks{x:number;y:number;z:number} + +/** How a step names a placement. Ticks are the exact integer coordinate, never a rendering. */ +export interface PlacementReference{container_index:number;item_type:string;orientation:string;position_ticks:PositionTicks} + +/** `sequence` is present only when a loading order was supplied; it is never derived. */ +export interface ExecutionStep{sequence?:number;placement:PlacementReference} + +export interface Presentation{summary:string;cites:string[]} + +export interface ContainerFacts{container_type:string|null;placement_count:number;volume_utilization:string|null} + +/** `order` is `'unavailable'` unless `loadingOrders` supplied one for this container. */ +export interface PlanContainer{container_index:number;facts:ContainerFacts;order:'loading'|'unavailable';steps:ExecutionStep[]} + +export interface UnplacedFacts{item_type:string|null;reason:string|null;proof_level:string|null;details:string[]} +export interface PlanUnplaced{facts:UnplacedFacts;presentation:Presentation} + +/** `null` when the two scores are equal on every axis. */ +export interface ScoreDifference{index:number;winner:number;alternative:number} +export interface AlternativeFacts{alternative_index:number;score:number[];status:string|null;first_difference:ScoreDifference|null} +export interface PlanAlternative{facts:AlternativeFacts;presentation:Presentation} + +export interface PlanFacts{status:string;score:number[];feasibility:ResultFact|null;optimality:ResultFact|null;container_count:number} + +export interface ExecutionPlan{format:string;objective:string|null;facts:PlanFacts;containers:PlanContainer[];alternatives:PlanAlternative[];unplaced:PlanUnplaced[]} + +/** Throws `ExecutionPlanError` if the placement lacks `item_type`, `orientation` or a tick on any axis. */ +export function placementReference(containerIndex:number,placement:unknown):PlacementReference; + +/** + * Derive the plan for one already validated result. Calls no solver and no validator. + * + * `loadingOrders` maps a container index to a permutation of that container's placement + * indices; omit it and each container reports `order: 'unavailable'` with every placement + * still listed. An order that is not a permutation throws `ExecutionPlanError`. + */ +export function buildExecutionPlan(request:PackingRequest,result:PackingResult,options?:{loadingOrders?:Record}):ExecutionPlan; + +/** The one byte-comparable spelling, with keys sorted recursively and arrays left in place. */ +export function canonicalPlanJson(plan:ExecutionPlan):string; diff --git a/execution.js b/execution.js new file mode 100644 index 0000000..12cb154 --- /dev/null +++ b/execution.js @@ -0,0 +1,235 @@ +/** + * An execution plan derived from an already validated packing result. + * + * `docs/EXECUTION-PLAN.md` is the contract. A packing result answers *what goes where*; an + * operator needs *what to do first, and why this carton*. This module turns the first into + * the second and is built so that it cannot do anything else: it imports no solver and no + * validator, holds no registry and reads no clock, so the same result yields the same plan + * forever. + * + * Held to byte-identical output with `packvium.execution`, `Packvium\Execution\Plan` and + * `packvium_core::execution`. JavaScript is the one that needs care for that: `JSON.stringify` + * emits keys in insertion order, so this module sorts them itself, and it is also this + * project's known odd one out for string order -- `sort()` compares UTF-16 code units where + * the other three compare code points. Every key sorted here is an ASCII identifier this + * module writes, so the two orders coincide; a key derived from caller data would not be + * safe to sort this way and none is. + * + * Two rules do the work, and both are about not quietly becoming a decision-maker. + * Authoritative solver facts and human text are separated in the *output*, under `facts` + * and `presentation`, and every presentation string names the fields it came from. A + * placement is referenced by container index, `item_type`, `orientation` and + * `position.*.ticks` -- never by `item_id`, which `conformance/canonical.py` drops as "an + * instance count rather than a semantic property". + */ + +/** The plan's own format tag; not the packing schema's version, and it does not move with it. */ +export const FORMAT = 'packvium-execution-plan/v1'; + +/** + * What a `score` index means is a property of the request's objective, which this adapter + * does not know. Naming an index it cannot explain would be inventing meaning. + */ +export const UNNAMED_AXIS = 'unnamed objective axis'; + +/** The adapter was handed something it cannot describe. */ +export class ExecutionPlanError extends Error { + constructor(message) { + super(message); + this.name = 'ExecutionPlanError'; + } +} + +const integers = (value) => (Array.isArray(value) ? value.map((n) => Math.trunc(Number(n))) : []); + +/** A reference two languages agree on, for one placement in one container. */ +export function placementReference(containerIndex, placement) { + for (const required of ['item_type', 'orientation']) { + if (placement == null || !(required in placement)) { + throw new ExecutionPlanError( + `placement is missing a field the reference is built from: '${required}'`); + } + } + const ticks = {}; + for (const axis of ['x', 'y', 'z']) { + const value = placement.position?.[axis]?.ticks; + if (value === undefined) { + throw new ExecutionPlanError( + `placement is missing a field the reference is built from: 'position.${axis}.ticks'`); + } + // `ticks` is the exact integer; `value`, which the same `exactScalar` also carries, is + // a rendering, and a reference built on it would depend on how a number was printed. + ticks[axis] = Math.trunc(Number(value)); + } + return { + container_index: containerIndex, + item_type: placement.item_type, + orientation: placement.orientation, + position_ticks: ticks, + }; +} + +/** + * The operator sequence for one container, or an honest absence of one. + * + * The engines compute a loading order from geometry this adapter never sees, so it is + * injected. Falling back to the order placements happen to appear in would present an + * artifact of how the solver walked its candidates as a safe order to lift boxes in. + */ +function steps(containerIndex, placements, loadingOrder) { + if (loadingOrder === undefined) { + return { + order: 'unavailable', + steps: placements.map((placement) => ({ + placement: placementReference(containerIndex, placement), + })), + }; + } + const sorted = [...loadingOrder].sort((a, b) => a - b); + const expected = placements.map((_, index) => index); + if (sorted.length !== expected.length || sorted.some((v, i) => v !== expected[i])) { + throw new ExecutionPlanError( + `loading order for container ${containerIndex} is not a permutation of its ` + + `${placements.length} placements`); + } + return { + order: 'loading', + steps: loadingOrder.map((index, step) => ({ + sequence: step + 1, + placement: placementReference(containerIndex, placements[index]), + })), + }; +} + +/** + * The first index at which two score vectors differ, and by how much. + * + * Never a blended number. The portfolio compared these lexicographically, so the first + * differing index *is* the decision; weighting the vector would replace a decision that was + * made with one that was not. + */ +function firstDifference(winner, loser) { + const shared = Math.min(winner.length, loser.length); + for (let index = 0; index < shared; index += 1) { + if (winner[index] !== loser[index]) { + return { + index, + winner: winner[index], + alternative: loser[index], + difference: loser[index] - winner[index], + }; + } + } + if (winner.length !== loser.length) { + throw new ExecutionPlanError( + 'score vectors of different length cannot be compared lexicographically'); + } + return null; +} + +function alternativeOf(index, winnerScore, alternative) { + const score = integers(alternative?.score); + const difference = firstDifference(winnerScore, score); + const summary = difference === null + ? 'This option scored identically to the chosen one on every objective axis; ' + + 'the score does not record why one was taken.' + : `This option differs first at objective axis ${difference.index} (${UNNAMED_AXIS}): ` + + `chosen ${difference.winner}, this ${difference.alternative}.`; + return { + facts: { + alternative_index: index, + score, + status: alternative?.status ?? null, + first_difference: difference, + }, + // Deliberately not "it lost because it is taller". The solver recorded a score, not a + // cause; naming a cause would be a claim nothing in the result supports. + presentation: { summary, cites: ['score', 'alternatives[].score'] }, + }; +} + +/** + * Derive the execution plan for one validated result. + * + * `loadingOrders` maps a container index to the engine-computed order its placements load + * in, and is optional for the reason `steps` gives. + */ +export function buildExecutionPlan(request, result, { loadingOrders = {} } = {}) { + if (result?.status === undefined || result.status === null) { + throw new ExecutionPlanError('a result without a status is not a validated result'); + } + const containers = result.containers ?? []; + const winnerScore = integers(result.score); + + const planContainers = containers.map((container, index) => ({ + container_index: index, + facts: { + container_type: container.container_type ?? null, + placement_count: (container.placements ?? []).length, + volume_utilization: container.volume_utilization ?? null, + }, + ...steps(index, container.placements ?? [], loadingOrders[index]), + })); + + const unplaced = (result.unpacked_items ?? []).map((item) => ({ + facts: { + item_type: item.item_type ?? null, + reason: item.reason ?? null, + // Carried through unchanged. Softening `observed` into "could not fit" would turn an + // honest limit into a false certainty. + proof_level: item.proof?.level ?? null, + details: item.details ?? [], + }, + presentation: { + summary: `Not packed: ${item.reason ?? ''} (${item.proof?.level ?? ''}).`, + cites: ['unpacked_items[].reason', 'unpacked_items[].proof.level'], + }, + })); + + const alternatives = (result.alternatives ?? []) + .map((alternative, index) => alternativeOf(index, winnerScore, alternative)); + + return { + format: FORMAT, + objective: result.objective ?? null, + facts: { + status: result.status, + score: winnerScore, + feasibility: result.feasibility ?? null, + optimality: result.optimality ?? null, + container_count: containers.length, + }, + containers: planContainers, + // Often empty, and not for one reason. Four produce an empty list: the `fast` profile + // runs a single solver, stops the start loop once the grid lattice packs + // everything, only one start completed, or `alternatives: 1` -- the cap counts the + // winner. Measured over the corpus, 165 of 399 requests do carry one, so this is not + // the rare case an earlier draft of this comment claimed. An empty list is + // well-formed and is never an error. + alternatives, + unplaced, + }; +} + +/** + * Sort object keys recursively, leaving arrays in place. + * + * A list stays a list: sorting one would reorder steps, which are ordered on purpose. + */ +function sortKeys(value) { + if (Array.isArray(value)) return value.map(sortKeys); + if (value === null || typeof value !== 'object') return value; + const sorted = {}; + for (const key of Object.keys(value).sort()) sorted[key] = sortKeys(value[key]); + return sorted; +} + +/** + * The one byte-comparable spelling of a plan. + * + * `JSON.stringify` emits insertion order, so the sort above is what makes this comparable + * with Python's `sort_keys=True`, PHP's recursive `ksort` and `serde_json`'s `BTreeMap`. + */ +export function canonicalPlanJson(plan) { + return JSON.stringify(sortKeys(plan)); +} diff --git a/fallback.js b/fallback.js index c5ef266..a9db2d7 100644 --- a/fallback.js +++ b/fallback.js @@ -912,6 +912,39 @@ function constraintBox(placement){return {x:placement.x,y:placement.y,z:placemen maxCompressionKpa:placement.item.maxCompressionKpa,compressionPpm:placement.item.compressionPpm, stopIndex:placement.item.stopIndex}} +// Keep only the requested prefix: the root is the worst score, latest tie first. +// Ordinals make heap eviction preserve the stable full-sort order exactly. +function compareRetained(a,b){return a.score-b.score||a.ordinal-b.ordinal} +function retainCandidate(heap,width,score,ordinal,candidate){ + if(heap.length===width&&score>=heap[0].score)return; + const entry={score,ordinal,candidate}; + if(heap.length0){const parent=Math.floor((at-1)/2);if(compareRetained(heap[parent],entry)>=0)break; + heap[at]=heap[parent];at=parent} + heap[at]=entry;return; + } + let at=0; + while(at*2+10)child++; + if(compareRetained(entry,heap[child])>=0)break; + heap[at]=heap[child];at=child} + heap[at]=entry; +} +function groupBatches(items){const batches=[],groups=new Map(); + for(const item of items){ + if(item.group===null){batches.push([item]);continue} + let batch=groups.get(item.group); + if(batch===undefined){batch=[];groups.set(item.group,batch);batches.push(batch)} + batch.push(item)} + return batches; +} +// Internal test probes, deliberately absent from the package's index.js exports. +export function __candidatePrefixForTests(scores,width){const heap=[]; + scores.forEach((score,ordinal)=>retainCandidate(heap,width,score,ordinal,ordinal)); + return heap.sort(compareRetained).map(entry=>entry.candidate)} +export function __groupBatchesForTests(items){return groupBatches(items)} + // The order boxes settle in: highest top first, then highest base, then index. A strict // total order, so the permutation it yields is unique -- which is what lets a candidate // sweep insert one box into the scene's settled order rather than sort per candidate. @@ -1769,12 +1802,7 @@ const maxContainers=req.configuration?.max_containers??Infinity; // template wins. // Group members travel together: one container takes all of them or none. Batching them // here is what both the greedy pass and the exact search branch over. -const batchesOf=itemsRemaining=>{const batches=[],taken=new Set(); - for(const item of itemsRemaining){if(taken.has(item))continue; - if(item.group===null){batches.push([item]);taken.add(item);continue} - const batch=itemsRemaining.filter(other=>other.group===item.group&&!taken.has(other)); - batch.forEach(o=>taken.add(o));batches.push(batch)} - return batches}; +const batchesOf=groupBatches; // Every feasible (point, rotation) for `item`, ordered by the solver's own candidate // score, best first. The greedy path asks for one and takes it; the exact search asks for // all of them and branches on each, which is the only difference between the two @@ -1883,10 +1911,12 @@ const candidatesFor=(tmpl,item,state,points,index,used,width)=>{ ?x2+y2+z2*1e6 :z2*1e9+y2*1e4+x2; if(width===1){if(!found.length||score({score,...candidate})); found.sort((a,b)=>a.score-b.score); - return width==null?found:found.slice(0,width) + return found }; const tryPackIntoTemplate=(tmpl,itemsRemaining)=>{const state={tmpl,placements:[],payload:0};const next=[]; // Running `usedVolume` of `state.placements`, maintained incrementally rather than @@ -1948,6 +1978,11 @@ const packBeamIntoTemplate=(tmpl,itemsRemaining)=>{ if(az!==bz)return az-bz;if(a.used!==b.used)return a.used>b.used?-1:1; const signature=node=>node.state.placements.map(p=>`${p.item.id}@${p.x},${p.y},${p.z}`).join('|');return compareCodePoints(signature(a),signature(b))}; const greedy=tryPackIntoTemplate(tmpl,itemsRemaining);let beam=[fresh()],incumbent=fresh();incumbent.state=greedy.state;incumbent.used=greedy.used;incumbent.unplaced=greedy.next;let nodes=0; + // The batch the loop stopped before, when it stopped early (node limit, deadline or + // effort). Surviving beam nodes have consumed only the batches before it, so completing + // one means adding every batch from here on to its unplaced list -- mirrors Rust's + // `try_pack_into_beam` `pending_from`. + let pendingFrom=null; for(let position=0;position=containerPlanNodeLimit||deadline.expired()||effortExceeded()){exhausted=true;break}nodes++;metrics.search_nodes_expanded++; @@ -1960,11 +1995,15 @@ const packBeamIntoTemplate=(tmpl,itemsRemaining)=>{ // re-enters the beam, so cloning the candidate points and spatial index for it // was pure allocation per expansion. for(const node of expansions){const complete={state:{tmpl,placements:node.state.placements.slice(),payload:node.state.payload},used:node.used,unplaced:[...node.unplaced,...future]};if(compareNode(complete,incumbent)<0)incumbent=complete} - if(!expansions.length||exhausted)break; + if(!expansions.length||exhausted){pendingFrom=position;break} const futureVolumes=future.some(item=>item.nesting!=null)?null:sortCosts(future.map(item=>volume(item.d))); const futureWeights=tmpl.max!=null?sortCosts(future.map(item=>BigInt(item.w))):null; expansions.sort((a,b)=>compareNode(a,b,future,futureVolumes,futureWeights));beam=expansions.slice(0,containerPlanBeamWidth)} - beam.sort((a,b)=>compareNode(a,b));if(beam.length&&compareNode(beam[0],incumbent)<0)incumbent=beam[0]; + // Without the unreached tail a beam leader looks better than every complete incumbent, + // and choosing it dropped those items outright: neither placed nor reported unpacked. + const pending=pendingFrom===null?[]:batches.slice(pendingFrom).flat(); + const completed=beam.map(node=>({state:node.state,used:node.used,unplaced:[...node.unplaced,...pending]})).sort((a,b)=>compareNode(a,b)); + if(completed.length&&compareNode(completed[0],incumbent)<0)incumbent=completed[0]; return {state:incumbent.state,next:incumbent.unplaced} }; // Depth-first branch and bound over the same group batches, mirroring Python's diff --git a/index.js b/index.js index 375f1d9..df0e823 100644 --- a/index.js +++ b/index.js @@ -69,7 +69,7 @@ export function rebalanceWeight(request, result, { maxMoves = 64 } = {}) { return rebalanceFallback(request, result, { maxMoves }); } -export const version = () => native?.version?.() ?? '1.1.0-js-fallback'; +export const version = () => native?.version?.() ?? '1.2.0-js-fallback'; /** * The exported commercial and control-plane API: a quote, a policy decision and catalog diff --git a/package.json b/package.json index 9155dd7..1f8d0f0 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name":"@packvium/engine", - "version":"1.1.0", + "version":"1.2.0", "description":"Native-first 3D cartonization with deterministic JS fallback", "author":{"name":"Packvium","url":"https://packvium.com"}, "keywords":["3d-bin-packing","bin-packing","cartonization","packing","container-loading","logistics","shipping","deterministic"], @@ -10,8 +10,8 @@ "type":"module", "main":"index.js", "types":"index.d.ts", - "exports":{".":{"types":"./index.d.ts","import":"./index.js"}}, - "files":["index.js","fallback.js","contact-graph.js","policy.js","commerce.js","commerce-model.js","examples","index.d.ts","README.md","SECURITY.md"], + "exports":{".":{"types":"./index.d.ts","import":"./index.js"},"./execution.js":{"types":"./execution.d.ts","import":"./execution.js"}}, + "files":["index.js","fallback.js","contact-graph.js","policy.js","commerce.js","commerce-model.js","execution.js","examples","index.d.ts","execution.d.ts","README.md","SECURITY.md"], "engines":{"node":">=16"}, "scripts":{ "test":"node test/run-tests.mjs", diff --git a/test/execution.test.mjs b/test/execution.test.mjs new file mode 100644 index 0000000..7b875ad --- /dev/null +++ b/test/execution.test.mjs @@ -0,0 +1,229 @@ +/** + * The execution-plan adapter in JavaScript. + * + * docs/EXECUTION-PLAN.md is the contract and `packvium.execution` is the reference. The + * same properties are held here as in the other three implementations, because the bar is + * byte-identical output and a property proved on one side of that proves half of it. + * + * JavaScript needs one assertion the others do not: `JSON.stringify` emits insertion order, + * so the canonical form depends on this module sorting keys itself. + */ + +import { strict as assert } from 'node:assert'; +import test from 'node:test'; + +import { + ExecutionPlanError, + FORMAT, + buildExecutionPlan, + canonicalPlanJson, + placementReference, +} from '../execution.js'; + +const scalar = (ticks) => ({ ticks, value: String(Math.trunc(ticks / 16000)), unit: 'mm' }); + +const placement = (itemType, x) => ({ + item_id: `${itemType}#${x}`, + item_type: itemType, + orientation: 'LWH', + position: { x: scalar(x), y: scalar(0), z: scalar(0) }, + dimensions: { length: scalar(1600000), width: scalar(1600000), height: scalar(1600000) }, + support_ratio: 1.0, + top_load: 0, +}); + +const result = (overrides = {}) => ({ + status: 'feasible', + objective: 'default', + score: [0, 1, 0, 0, 1000000], + feasibility: { code: 'feasible' }, + optimality: { code: 'not_proven' }, + containers: [{ + id: 'box#1', + container_type: 'box', + volume_utilization: 0.5, + placements: [placement('cube', 0), placement('cube', 1600000)], + }], + unpacked_items: [], + alternatives: [], + ...overrides, +}); + +test('without an injected order the plan says so', () => { + const container = buildExecutionPlan({}, result()).containers[0]; + assert.equal(container.order, 'unavailable'); + // Every placement is still listed; no step numbers, because array position is an + // artifact of candidate iteration. + assert.equal(container.steps.length, 2); + assert.ok(!('sequence' in container.steps[0])); +}); + +test('an injected order is used verbatim', () => { + const container = buildExecutionPlan({}, result(), { loadingOrders: { 0: [1, 0] } }) + .containers[0]; + assert.equal(container.order, 'loading'); + assert.deepEqual(container.steps.map((s) => s.sequence), [1, 2]); + // Step 1 is the placement the caller put first, not the one the result listed first. + assert.equal(container.steps[0].placement.position_ticks.x, 1600000); +}); + +test('an order that is not a permutation is refused', () => { + assert.throws( + () => buildExecutionPlan({}, result(), { loadingOrders: { 0: [0, 0] } }), + (error) => error instanceof ExecutionPlanError && /permutation/.test(error.message)); +}); + +test('the placement reference does not use item_id', () => { + // `item_id` exists and conformance/canonical.py drops it as an instance count; + // referencing it would make a plan two correct engines disagree about. + const reference = placementReference(0, placement('cube', 0)); + assert.deepEqual(Object.keys(reference).sort(), + ['container_index', 'item_type', 'orientation', 'position_ticks']); +}); + +test('the placement reference reads ticks and not the rendered value', () => { + const subject = placement('cube', 12345); + subject.position.x.value = 'wrong'; + assert.equal(placementReference(0, subject).position_ticks.x, 12345); +}); + +test('a placement it cannot reference is refused', () => { + const subject = placement('cube', 0); + delete subject.orientation; + assert.throws(() => placementReference(0, subject), + (error) => /missing a field/.test(error.message)); +}); + +test('the loss is the first differing index and never a blend', () => { + const plan = buildExecutionPlan({}, result({ + alternatives: [{ status: 'feasible', score: [0, 2, 0, 0, 900000] }], + })); + assert.deepEqual(plan.alternatives[0].facts.first_difference, + { index: 1, winner: 1, alternative: 2, difference: 1 }); + assert.ok(!('total' in plan.alternatives[0].facts)); +}); + +test('the sentence names an axis and claims no cause', () => { + const plan = buildExecutionPlan({}, result({ + alternatives: [{ status: 'feasible', score: [0, 2, 0, 0, 900000] }], + })); + const { summary, cites } = plan.alternatives[0].presentation; + assert.match(summary, /axis 1/); + assert.deepEqual(cites, ['score', 'alternatives[].score']); + for (const causal of ['because', 'due to', 'caused']) { + assert.ok(!summary.toLowerCase().includes(causal), summary); + } +}); + +test('score vectors of different length are refused', () => { + assert.throws(() => buildExecutionPlan({}, result({ alternatives: [{ score: [0, 1] }] })), + (error) => /different length/.test(error.message)); +}); + +test('a result with no alternatives is well formed', () => { + // The common case, and today the only one. + const plan = buildExecutionPlan({}, result()); + assert.deepEqual(plan.alternatives, []); + assert.equal(plan.format, FORMAT); +}); + +test('an unpacked item keeps its proof level unsoftened', () => { + const plan = buildExecutionPlan({}, result({ + unpacked_items: [{ + item_id: 'ladder#1', item_type: 'ladder', reason: 'no_container_fits', + details: ['too long'], + proof: { level: 'observed', observations: [{ code: 'too_long' }] }, + }], + })); + assert.equal(plan.unplaced[0].facts.proof_level, 'observed'); + // The level appears in the sentence too: a reader must not be told "cannot fit" when + // the engine only observed that it did not. + assert.match(plan.unplaced[0].presentation.summary, /observed/); +}); + +test('a result without a status is not a validated result', () => { + assert.throws(() => buildExecutionPlan({}, { containers: [] }), + (error) => /validated result/.test(error.message)); +}); + +test('the canonical form sorts keys, which JSON.stringify does not', () => { + // The assertion the other three implementations do not need: `JSON.stringify` emits + // insertion order, so without the sort this would not be comparable with them. + const plan = buildExecutionPlan({}, result()); + const canonical = canonicalPlanJson(plan); + assert.ok(canonical.startsWith('{"alternatives":'), canonical.slice(0, 40)); + assert.ok(!canonical.includes(', ')); + assert.ok(JSON.stringify(plan).startsWith('{"format":'), 'insertion order still differs'); +}); + +test('the canonical form never reorders a sequence', () => { + // Steps are ordered on purpose; sorting them would be a different plan. + const canonical = canonicalPlanJson( + buildExecutionPlan({}, result(), { loadingOrders: { 0: [1, 0] } })); + const roundTrip = JSON.parse(canonical); + assert.deepEqual(roundTrip.containers[0].steps.map((s) => s.sequence), [1, 2]); + assert.equal(roundTrip.containers[0].steps[0].placement.position_ticks.x, 1600000); +}); + +test('the adapter imports no solver and no validator', async () => { + // The dependency direction from docs/EXECUTION-PLAN.md, as the cheapest test of it. + const { readFileSync } = await import('node:fs'); + const source = readFileSync(new URL('../execution.js', import.meta.url), 'utf8'); + for (const forbidden of ['./fallback.js', './contact-graph.js', 'require(']) { + assert.ok(!source.includes(forbidden), forbidden); + } +}); + +// -------------------------------------------------------------------------------------- +// The three paths the corpus does not reach. Python and PHP cover them from their own +// suites; this package measured 97.87% without them, which on a derived-document adapter +// means the refusal and the equal-score wording were shipped untested. +// -------------------------------------------------------------------------------------- + +test('a placement missing a tick on any axis is refused, and the message names the axis', () => { + // `ticks` is the exact integer the reference is built from. Falling back to the rendered + // `value` would put a rounded millimetre where a coordinate belongs, so its absence has + // to be an error rather than a substitution. + for (const axis of ['x', 'y', 'z']) { + const broken = placement('cube', 0); + delete broken.position[axis].ticks; + assert.throws( + () => placementReference(0, broken), + (error) => error instanceof ExecutionPlanError + && error.message.includes(`position.${axis}.ticks`), + `axis ${axis} should be named in the refusal`, + ); + } +}); + +test('an axis that is not an object at all is refused rather than read as undefined', () => { + const broken = placement('cube', 0); + broken.position.y = 0; + assert.throws(() => placementReference(0, broken), ExecutionPlanError); +}); + +test('an alternative scoring identically to the winner records no first difference', () => { + // The honest wording for a tie: the score is what the solver recorded, and it does not + // say why one option was taken over an equal one. Claiming a cause here would invent + // evidence the result does not contain. + const plan = buildExecutionPlan({}, result({ + score: [0, 1, 0, 0, 1000000], + alternatives: [{ score: [0, 1, 0, 0, 1000000], status: 'best_found' }], + })); + const [alternative] = plan.alternatives; + assert.equal(alternative.facts.first_difference, null); + assert.match(alternative.presentation.summary, /scored identically/); + assert.match(alternative.presentation.summary, /does not record why/); + assert.deepEqual(alternative.presentation.cites, ['score', 'alternatives[].score']); +}); + +test('an alternative that differs reports the first axis it differs on', () => { + const plan = buildExecutionPlan({}, result({ + score: [0, 1, 0, 0, 1000000], + alternatives: [{ score: [0, 1, 0, 5, 1000000], status: 'best_found' }], + })); + const { first_difference: difference } = plan.alternatives[0].facts; + assert.equal(difference.index, 3); + assert.equal(difference.winner, 0); + assert.equal(difference.alternative, 5); +}); diff --git a/test/fallback.test.mjs b/test/fallback.test.mjs index edd2c22..82e1f92 100644 --- a/test/fallback.test.mjs +++ b/test/fallback.test.mjs @@ -5,7 +5,7 @@ import test from 'node:test'; import { Deadline, SequenceReplayError, UNSUPPORTED_FIELDS, UnsupportedFeatureError, BoundOverflowError, __inspectHullShapeForTests, __objectiveBoundsForTests, - __occupiesLessThanItsBoxForTests, aggregateTermination, + __occupiesLessThanItsBoxForTests, __candidatePrefixForTests, __groupBatchesForTests, aggregateTermination, explainUnpackedItem, explanationForUnpackedItem, packFallback, rebalanceWeight, verifyLoadingPrefixBusinessRules, } from '../fallback.js'; @@ -36,6 +36,30 @@ const box = (id, length = 200, width = 200, height = 200, rest = {}) => ({ const placements = (result) => result.containers.flatMap((container) => container.placements); const at = (placement) => [placement.position.x.ticks, placement.position.y.ticks, placement.position.z.ticks]; + +test('bounded candidate retention equals the stable full-sort prefix', () => { + const streams = [[], [1], Array(300).fill(7), + Array.from({length: 300}, (_, i) => i), + Array.from({length: 300}, (_, i) => 300 - i), + Array.from({length: 300}, (_, i) => ((i * 73) % 31) - 15), + [1e25, -1e25, 0, -0, 1e25, -1e25]]; + for (const scores of streams) { + const full = scores.map((score, ordinal) => ({score, ordinal})) + .sort((a, b) => a.score - b.score).map(entry => entry.ordinal); + for (const width of [1, 2, 3, 7, 128, 512]) { + assert.deepEqual(__candidatePrefixForTests(scores, width), full.slice(0, width)); + } + } +}); + +test('group batching preserves first occurrence and member order', () => { + const items = ['00', null, '0', '00', '1', '0', null, '1'] + .map((group, id) => ({group, id})); + assert.deepEqual(__groupBatchesForTests(items).map(batch => batch.map(item => item.id)), + [[0, 3], [1], [2, 5], [4, 7], [6]]); + assert.deepEqual(__groupBatchesForTests([]), []); + assert.deepEqual(__groupBatchesForTests(items), __groupBatchesForTests(items)); +}); // A cross-language fixture kept in the native workspace tree; a published copy of this // package does not carry it. const rebalanceFixtureUrl = new URL('../../../../conformance/scene/rebalance-fixtures.json', import.meta.url); @@ -803,6 +827,29 @@ test('an injected clock expires mid-search without sleeping', () => { assert.equal(result.summary.packed_item_count + result.summary.unpacked_item_count, 8); }); +// The beam search stops for three reasons -- its node limit, the deadline, or the effort +// budget -- and all three leave the same loop. When it stopped early it used to hand back +// the beam's leader without the batches it never reached, so those items were neither +// placed nor reported unpacked: 12 requested, 1 placed, 0 unpacked, reported `feasible`. +// Rust's `try_pack_into_beam` records the same defect and its fix; Python and PHP return +// their complete incumbent instead. The node limit is the deterministic trigger, so this +// needs no clock and covers the deadline and effort exits by construction. +test('a beam search stopped early still accounts for every item it never reached', () => { + for (const limit of [1, 2, 3, 4]) { + const result = packFallback(request( + [cube('a', 100, { quantity: 4 }), cube('b', 80, { quantity: 4 }), cube('c', 60, { quantity: 4 })], + [box('crate')], + { configuration: { container_plan_beam_width: 16, container_plan_node_limit: limit, time_limit_ms: 600000 } }, + )); + const placed = placements(result).length; + assert.equal(placed, result.summary.packed_item_count, + `node limit ${limit}: the summary counts placements the result does not contain`); + assert.equal(placed + result.unpacked_items.length, 12, + `node limit ${limit}: items were neither placed nor reported unpacked`); + assert.equal(result.summary.unpacked_item_count, result.unpacked_items.length); + } +}); + test('Deadline accepts an injected monotonic clock', () => { const deadline = new Deadline(3, checkBudgetClock()); assert.equal(deadline.expired(), false); diff --git a/test/package-exports.test.mjs b/test/package-exports.test.mjs new file mode 100644 index 0000000..e5eac4b --- /dev/null +++ b/test/package-exports.test.mjs @@ -0,0 +1,73 @@ +/** + * What a consumer can actually import. + * + * `files` and `exports` are two independent gates and they failed independently. On + * 2026-09-09 `execution.js` was listed in `files` but absent from `exports`, so the module + * shipped inside the tarball and `import '@packvium/engine/execution.js'` still threw + * `ERR_PACKAGE_PATH_NOT_EXPORTED` — a documented public entry point that no consumer could + * reach. Nothing in the suite noticed, because every in-repo caller uses a relative path + * (`../execution.js`), which bypasses `exports` entirely. + * + * So these tests import by *package name*. A self-reference resolves through the real + * `exports` map, which is the gate the relative paths never touch. + */ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const PACKAGE_ROOT = path.dirname(path.dirname(fileURLToPath(import.meta.url))); +const manifest = JSON.parse(fs.readFileSync(path.join(PACKAGE_ROOT, 'package.json'), 'utf8')); + +test('the main entry resolves by package name and carries the packing surface', async () => { + const main = await import(manifest.name); + for (const name of ['pack', 'packJson', 'rebalanceWeight', 'commerce', 'backend']) { + assert.equal(typeof main[name], name === 'commerce' ? 'object' : 'function', name); + } +}); + +test('the execution plan resolves by package name, not only by relative path', async () => { + const execution = await import(`${manifest.name}/execution.js`); + assert.equal(typeof execution.buildExecutionPlan, 'function'); + assert.equal(typeof execution.canonicalPlanJson, 'function'); + assert.equal(typeof execution.placementReference, 'function'); + assert.equal(execution.FORMAT, 'packvium-execution-plan/v1'); +}); + +test('every declared export target exists, and so does the types file beside it', () => { + for (const [subpath, entry] of Object.entries(manifest.exports)) { + for (const [condition, target] of Object.entries(entry)) { + const resolved = path.join(PACKAGE_ROOT, target); + assert.ok(fs.existsSync(resolved), + `exports["${subpath}"].${condition} points at ${target}, which does not exist`); + } + } +}); + +test('every exported subpath is also published', () => { + // `files` decides what is in the tarball; `exports` decides what can be imported from it. + // A subpath present in one and missing from the other is broken either way round. + const published = new Set(manifest.files); + for (const subpath of Object.keys(manifest.exports)) { + if (subpath === '.') continue; + for (const target of Object.values(manifest.exports[subpath])) { + const name = target.replace(/^\.\//, ''); + assert.ok(published.has(name), + `exports names ${name}, which "files" does not publish — it would be missing from the tarball`); + } + } +}); + +// Written into every package by `scripts/export-public.py` rather than kept in the source +// tree, so their absence here is correct and their presence in the tarball is not this +// test's business. +const GENERATED_AT_EXPORT = new Set(['SECURITY.md', 'CHANGELOG.md', 'CONTRIBUTING.md']); + +test('every published file exists in the source tree or is generated by the export', () => { + for (const entry of manifest.files) { + if (GENERATED_AT_EXPORT.has(entry)) continue; + assert.ok(fs.existsSync(path.join(PACKAGE_ROOT, entry)), + `"files" publishes ${entry}, which does not exist`); + } +});