Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,18 @@ What changed in `packvium/native-bridge` on Packagist, release by release. The f
[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.5.0]

A refused request now reads the same on both backends (see *Fixed*).

### Fixed

- **`quality` with a minimum support ratio answers on the Rust backend.** It failed with
`solution_failed_validation` where the PHP backend answered.
- **A refused request reads the same on both backends.** On the Rust backend `NativePacker::pack()`
returned `['status' => 'error', 'error' => ...]` with no code; it now throws
`InvalidRequestException` with the code, reason and field, as the PHP backend does.

## [1.4.0]

A version-alignment release. The bridge itself is unchanged; nothing breaks 1.3.0.
Expand Down
26 changes: 26 additions & 0 deletions CITATION.cff
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
cff-version: 1.2.0
message: "If you use Packvium in your research, please cite it as below."
title: "Packvium native bridge for PHP"
type: software
authors:
- name: "Packvium contributors"
website: "https://packvium.com"
version: "1.5.0"
license: MIT
url: "https://packvium.com"
repository-code: "https://github.com/toxakara/packvium-php-bridge"
repository-artifact: "https://packagist.org/packages/packvium/native-bridge"
abstract: >-
Packvium backend bridge: the Rust engine over FFI when available, pure PHP otherwise.
keywords:
- 3d-bin-packing
- bin-packing
- 3d-packing
- cartonization
- container-loading
- pallet-packing
- truck-loading
- packing-algorithm
- logistics
- deterministic
- ffi
104 changes: 91 additions & 13 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,21 +18,45 @@ only when you want the native backend; neither is required for the PHP fallback.

## Quick start

The request is the same plain array `packvium/packvium` reads with `ArrayCodec::pack()` —
the JSON document every Packvium engine accepts. Lengths and weights are strings, parsed
into exact integers, so `'0.1'` is a tenth of a millimetre and never a rounded float.

```php
<?php

use Packvium\Native\NativePacker;

$request = [
'units' => ['length' => 'mm'],
'configuration' => [
// Counted work bounds the search, so both backends stop at a reproducible point;
// the time limit is only a safety fuse.
'effort_budget' => ['max_search_nodes' => 20000],
'time_limit_ms' => 60000,
],
'items' => [
['id' => 'mug', 'quantity' => 6, 'weight' => '400 g',
'dimensions' => ['length' => '120', 'width' => '120', 'height' => '100']],
],
'containers' => [
['id' => 'box', 'max_payload' => '20 kg',
'inner_dimensions' => ['length' => '400', 'width' => '300', 'height' => '250']],
],
];

$packer = new NativePacker('/opt/packvium/libpackvium_ffi.so');
$result = $packer->pack($request);

echo $packer->backend(), PHP_EOL; // "rust" or "php"
echo $result['status'], PHP_EOL;
echo $result['status'], PHP_EOL; // "feasible"
```

Pass the same request format used by `packvium/packvium`. If the extension, library or
health check is unavailable, `NativePacker` selects the PHP backend instead of failing
the packing request.
The shared library is the `packvium-ffi` crate's C ABI build, named by platform:
`libpackvium_ffi.so` on Linux, `libpackvium_ffi.dylib` on macOS and `packvium_ffi.dll` on
Windows. If the extension, library or health check is unavailable, `NativePacker` selects
the PHP backend instead of failing the packing request. Log `backend()` once at startup:
it is how you learn that a deployment you believed was accelerated quietly fell back.

Omit the library path (or pass `null`) to always use the pure-PHP backend — useful in a
test suite or on a host that never provisions the shared library:
Expand All @@ -42,23 +66,60 @@ $packer = new NativePacker(); // no library path: pure PHP, deterministic eith
echo $packer->backend(), PHP_EOL; // "php"
```

The two backends are independent engines held to the same request and result contract.
Each answer is independently validated, but they are not held to identical placements: on
some requests the compiled engine chooses a different arrangement, or one that scores
differently. Pin one backend if you need byte-identical plans across hosts.

## Errors

A malformed request is refused before anything is solved, with the same message from
either backend — `invalid_request: <field>: <detail>`, where `<field>` is a JSON Pointer
into your request. How it reaches you differs:

- **PHP backend:** `pack()` throws `Packvium\Serialization\InvalidRequestException` (an
`InvalidArgumentException`) with `reason()`, `field()` and `detail()`, or its subclass
`Packvium\Validation\FixedPlacementException` for `fixed_placements` that cannot hold.
- **Rust backend:** `pack()` returns an array `['status' => 'error', 'error' => <message>]`
instead of throwing. The message is the same string; there are no separate fields.

Handle both until your deployment runs only one:

```php
use Packvium\Serialization\InvalidRequestException;

try {
$result = $packer->pack($request);
} catch (InvalidRequestException $e) {
$result = ['status' => 'error', 'error' => $e->getMessage()];
}
if ($result['status'] === 'error') {
// show $result['error'] to a person; it names the field and the rule it broke
}
```

A request that is valid but does not fit completely is not an error on either backend: the
result lists what was left out, and why, in `unpacked_items`. A native call that fails at
runtime (a bad pointer, unparseable output) disables the library for the rest of the
`NativePacker`'s life and retries the same request in pure PHP.

## Examples

Runnable, in [`examples/`](examples). Each one is a single file you can read top to bottom
and execute without a project around it.
Runnable, in [`examples/`](https://github.com/toxakara/packvium-php-bridge/tree/main/examples).
Each one is a single file you can read top to bottom and execute without a project around it.

| File | What it shows |
| --- | --- |
| [`basic.php`](examples/basic.php) | Pack through the bridge and report which backend answered. |
| [`shapes.php`](examples/shapes.php) | Items that are not their box: complementary wedges sharing one crate as `convex_hull`, and a cushion that compresses under load until the crush limit refuses it — the same numbers whichever backend loaded. |
| [`basic.php`](https://github.com/toxakara/packvium-php-bridge/blob/main/examples/basic.php) | Pack through the bridge and report which backend answered. |
| [`shapes.php`](https://github.com/toxakara/packvium-php-bridge/blob/main/examples/shapes.php) | Items that are not their box: complementary wedges sharing one crate as `convex_hull`, and a cushion that compresses under load until the crush limit refuses it — the same numbers whichever backend loaded. |

```bash
php examples/basic.php # pure PHP
php examples/basic.php /path/to/libpackvium.so # compiled engine
php examples/basic.php # pure PHP
php examples/basic.php /path/to/libpackvium_ffi.so # compiled engine
```

Running it both ways is the point: the same request must come back with the same answer
whichever backend served it.
Running it both ways is the point: the same request comes back as a valid answer in the
same shape whichever backend served it.

## When to use it

Expand All @@ -85,6 +146,23 @@ Documentation, the constraint reference and the benchmarks are at
| PHP FFI bridge — [`packvium/native-bridge`](https://packagist.org/packages/packvium/native-bridge) | `composer require packvium/native-bridge` | [packvium-php-bridge](https://github.com/toxakara/packvium-php-bridge) |
| Python native selector — `packvium-native` | from source until the native wheels ship | [packvium-python-adapter](https://github.com/toxakara/packvium-python-adapter) |

## Citation

If Packvium supports your research, cite it as software. GitHub's **Cite this repository**
button reads [`CITATION.cff`](https://github.com/toxakara/packvium-php-bridge/blob/main/CITATION.cff), and
[`codemeta.json`](https://github.com/toxakara/packvium-php-bridge/blob/main/codemeta.json) carries the same record in
CodeMeta form.

```bibtex
@software{packvium_php_bridge,
author = {{Packvium contributors}},
title = {Packvium native bridge for PHP},
version = {1.5.0},
license = {MIT},
url = {https://packvium.com}
}
```

## License

MIT. See [LICENSE](LICENSE).
MIT. See [LICENSE](https://github.com/toxakara/packvium-php-bridge/blob/main/LICENSE).
32 changes: 32 additions & 0 deletions codemeta.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
{
"@context": "https://w3id.org/codemeta/3.0",
"@type": "SoftwareSourceCode",
"name": "Packvium native bridge for PHP",
"description": "Packvium backend bridge: the Rust engine over FFI when available, pure PHP otherwise.",
"version": "1.5.0",
"license": "https://spdx.org/licenses/MIT",
"author": [
{
"@type": "Organization",
"name": "Packvium contributors",
"url": "https://packvium.com"
}
],
"url": "https://packvium.com",
"codeRepository": "https://github.com/toxakara/packvium-php-bridge",
"issueTracker": "https://github.com/toxakara/packvium-php-bridge/issues",
"programmingLanguage": "PHP",
"keywords": [
"3d-bin-packing",
"bin-packing",
"3d-packing",
"cartonization",
"container-loading",
"pallet-packing",
"truck-loading",
"packing-algorithm",
"logistics",
"deterministic",
"ffi"
]
}
5 changes: 3 additions & 2 deletions composer.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "packvium/native-bridge",
"description": "Optional FFI backend for Packvium with pure-PHP fallback",
"description": "Packvium backend bridge: the Rust engine over FFI when available, pure PHP otherwise.",
"type": "library",
"license": "MIT",
"authors": [
Expand All @@ -9,9 +9,10 @@
"homepage": "https://packvium.com"
}
],
"keywords": ["3d-bin-packing", "cartonization", "container-loading", "packing", "ffi"],
"keywords": ["3d-bin-packing", "bin-packing", "3d-packing", "cartonization", "container-loading", "pallet-packing", "truck-loading", "packing-algorithm", "logistics", "deterministic", "ffi"],
"homepage": "https://packvium.com",
"support": {
"docs": "https://packvium.com/docs",
"issues": "https://github.com/toxakara/packvium-php-bridge/issues",
"source": "https://github.com/toxakara/packvium-php-bridge"
},
Expand Down
20 changes: 12 additions & 8 deletions docs/GUARANTEES.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,9 @@ After a result reports `feasible` or `optimal` and passes independent validation
1/8 µg for weight. No coordinate is ever a binary floating-point number, so no
placement decision depends on rounding;
- **determinism** — identical input and identical seed produce an identical result, on
any platform and in any of the implementations;
any platform, when the search completes or stops on `configuration.effort_budget`. A
search stopped by `time_limit_ms` stops where the host's speed let it, so it may differ
between runs; the result says which limit stopped it;
- **complete accounting** — every requested item instance appears exactly once, either
placed or listed as unpacked with a reason code.

Expand All @@ -31,24 +33,26 @@ After a result reports `feasible` or `optimal` and passes independent validation
- **That your inputs are right.** Dimensions, weights and clearances are taken as given.
Round item exteriors outward, container interiors inward, and clearance outward before
you build the request.
- **Support for non-rectangular shapes.** Items and containers are rigid axis-aligned
cuboids; obstacles are rectangular. No cylinders, deformable bags, meshes or
irregular geometry.
- **Arbitrary shapes.** Containers are axis-aligned cuboids. An item is a cuboid, a convex
hull of vertices, or a cuboid that compresses by a declared ratio; obstacles are cuboids
or unions of them. Concave meshes, curved surfaces and free-form deformable bags are not
modelled — approximate them with a convex hull or a bounding cuboid.
- **A result before the deadline.** With a time limit set, the search may return
`time_limit` with a partial packing, or nothing placed at all.
- **Full load propagation.** Top-load limits are enforced against what rests *directly*
on an item, not against the accumulated mass of an entire stack above it.

## Not modelled at all

Deformable goods, dynamic shipping physics, contact-load propagation through arbitrary
support graphs, pallet-overhang standards, axle loads, unloading-route optimization, and
carrier tariff or rating catalogs. None of these are built in, and none are approximated
Dynamic shipping physics, contact-load propagation through arbitrary support graphs,
pallet-overhang standards, and route optimization. Axle loads, the unloading order of a
given stop sequence (`stop_index`, `access_directions`) and carrier rate tables are
modelled; choosing the route itself is not. None of the unmodelled items is approximated
silently — if you need them, they belong in your own layer above this library.

## Status of this release

Version `1.4.0` freezes the public API. Field names, status codes, the objective
Version `1.5.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.
Expand Down
2 changes: 1 addition & 1 deletion docs/UNITS-AND-NUMERICS.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ One internal length tick is `1/16000 mm`.
- `1 international inch = 25.4 mm = 406,400 ticks`
- common fractional inches through at least `1/128 in` are exact integers

Accepted inputs include integers, decimal strings, fractions (`3/16`) and mixed fractions (`12 3/8`), with `mm`, `cm`, `m`, `in`, `ft`, and ticks. Binary floating-point input is intentionally rejected by the Python API; PHP type declarations accept only integer/string/structured values.
Accepted inputs include integers, decimal strings, fractions (`3/16`) and mixed fractions (`12 3/8`), with `mm`, `cm`, `m`, `in`, `ft`, and ticks. A binary float with a fractional part is intentionally rejected by the Python API, by `Length` and `Weight` alike (`TypeError`); an integral float such as `100.0` is exact, and is what JavaScript sends for `100`, so it is accepted as that integer. PHP type declarations accept only integer/string/structured values.

## Weight

Expand Down
20 changes: 19 additions & 1 deletion src/NativePacker.php
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,25 @@ public function pack(array $request):array
if(!is_array($decoded)){
throw new \RuntimeException('Native backend returned a non-object response');
}
if(($decoded['status']??null)==='error'){
$code=(string)($decoded['code']??'invalid_request');
$reason=(string)($decoded['reason']??'invalid_value');
$field=(string)($decoded['field']??'');
$detail=(string)($decoded['detail']??($decoded['error']??'invalid request'));
if($code==='invalid_fixed_placement'&&class_exists(\Packvium\Validation\FixedPlacementException::class)){
throw new \Packvium\Validation\FixedPlacementException($detail,$reason,$field!==''?$field:'/fixed_placements');
}
if(class_exists(\Packvium\Serialization\InvalidRequestException::class)){
throw new \Packvium\Serialization\InvalidRequestException($reason,$field,$detail);
}
throw new \RuntimeException((string)($decoded['error']??'Native backend error'));
}
return $decoded;
}catch(\Packvium\Serialization\InvalidRequestException $refusal){
// A refused request is a domain-level rejection, not a bridge
// or FFI transport failure. Throw it directly so the native backend
// reports invalid requests identically to pure PHP without disabling FFI.
throw $refusal;
}catch(\Throwable $error){
// A library can become unusable after its constructor health check
// (bad return pointer, invalid JSON, runtime symbol failure). Disable
Expand All @@ -52,7 +70,7 @@ public function pack(array $request):array

if(!class_exists(\Packvium\Packer::class)){
throw new \RuntimeException(
'Install packvium/packvium 0.1.0 or provide a healthy Rust library path',
'Install packvium/packvium or provide a healthy Rust library path',
0,
$nativeFailure,
);
Expand Down
28 changes: 28 additions & 0 deletions tests/run.php
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,34 @@
throw new RuntimeException('Native pack() result has no string status field');
}
echo "OK native bridge FFI call against $library (status: {$result['status']})\n";

// /: verify that a refused request throws InvalidRequestException
// with matching code, reason, and field on both backends, and that refusal does
// not disable the native FFI backend.
$invalidRequest = [
'items' => [['id' => 'a', 'quantity' => 1, 'dimensions' => ['length' => '-10', 'width' => '10', 'height' => '10']]],
'containers' => [['id' => 'c', 'inner_dimensions' => ['length' => '20', 'width' => '20', 'height' => '20']]],
];
try {
$packer->pack($invalidRequest);
throw new RuntimeException('PHP backend should have refused invalid request');
} catch (\Packvium\Serialization\InvalidRequestException $e) {
if ($e->errorCode() !== 'invalid_request' || $e->reason() !== 'negative_measure' || $e->field() !== '/items/0/dimensions/length') {
throw new RuntimeException("Unexpected refusal on PHP backend: {$e->errorCode()} {$e->reason()} {$e->field()}");
}
}
try {
$native->pack($invalidRequest);
throw new RuntimeException('Native backend should have refused invalid request');
} catch (\Packvium\Serialization\InvalidRequestException $e) {
if ($e->errorCode() !== 'invalid_request' || $e->reason() !== 'negative_measure' || $e->field() !== '/items/0/dimensions/length') {
throw new RuntimeException("Unexpected refusal on Native backend: {$e->errorCode()} {$e->reason()} {$e->field()}");
}
}
if ($native->backend() !== 'rust') {
throw new RuntimeException('Native backend should not be disabled by an application refusal');
}
echo "OK native bridge request refusal parity across both backends\n";
}

// "selects native only when healthy and always falls back safely" is only
Expand Down
Loading