From 9d5d0af0d7581ff74cb9a2f360f910d7b15c245d Mon Sep 17 00:00:00 2001 From: loggger101 Date: Sun, 15 Nov 2026 18:51:43 -0500 Subject: [PATCH 1/3] Prototype: the cargo knapsack in Rust (cargo_core + optional binding) rust/cargo_core ports optimal_payload_mix, _hold_refining and _capped_sale_value operation for operation; plain Rust, so economicspace's es_core can link it with no Python boundary. rust/cargo_py is an optional PyO3 module (spacevalue_cargo_rs) with the same signatures; nothing in spacevalue imports it. tests/test_cargo_rust.py replays every golden call through it (0 differ) and fuzzes 120,000 hostile calls against the Python, exceptions included (0 differ). The planted_knapsack_defect build fails all six tests. Skips without the module unless SPACEVALUE_REQUIRE_RUST=1. Full suite: 189 passed. Co-Authored-By: Claude Opus 5.5 --- rust/README.md | 89 +++++++++ rust/cargo_core/Cargo.toml | 14 ++ rust/cargo_core/src/lib.rs | 356 +++++++++++++++++++++++++++++++++++ rust/cargo_py/Cargo.lock | 177 +++++++++++++++++ rust/cargo_py/Cargo.toml | 22 +++ rust/cargo_py/pyproject.toml | 12 ++ rust/cargo_py/src/lib.rs | 344 +++++++++++++++++++++++++++++++++ tests/test_cargo_rust.py | 227 ++++++++++++++++++++++ 8 files changed, 1241 insertions(+) create mode 100644 rust/README.md create mode 100644 rust/cargo_core/Cargo.toml create mode 100644 rust/cargo_core/src/lib.rs create mode 100644 rust/cargo_py/Cargo.lock create mode 100644 rust/cargo_py/Cargo.toml create mode 100644 rust/cargo_py/pyproject.toml create mode 100644 rust/cargo_py/src/lib.rs create mode 100644 tests/test_cargo_rust.py diff --git a/rust/README.md b/rust/README.md new file mode 100644 index 0000000..c4814c8 --- /dev/null +++ b/rust/README.md @@ -0,0 +1,89 @@ +# rust/: the cargo knapsack in Rust (prototype) + +**Status:** a prototype on branch `rust-cargo-prototype`. Not merged, not +released, and nothing in `spacevalue` imports it. The Python in +`spacevalue/cargo.py` stays the reference and the default. + +## What it is + +Two crates: + +| crate | is | used by | +|---|---|---| +| `cargo_core` | `optimal_payload_mix`, `_hold_refining` and `_capped_sale_value`, ported operation for operation from `cargo.py`; plain Rust, no Python | `cargo_py` here, and economicspace's `es_core`, which links it directly | +| `cargo_py` | an optional PyO3 module, `spacevalue_cargo_rs`, with the same three names and signatures | `tests/test_cargo_rust.py` | + +The point of keeping the port here rather than in economicspace: the copy +lives next to the code it copies and is tested against it by the same suite, +so a change to the knapsack that is not made in both places fails here, +before a release, not later in economicspace. + +## The contract + +The golden test's: the same result bit for bit, and the same arguments +afterwards (`caps` is consumed in place). What a port gets wrong, and how +this one copies the Python: + +- `sorted(..., key=lambda p: -p[2])` is a stable sort on the negated price. + Any stable sort agrees with timsort when no price is NaN, so a NaN price is + handed back to the Python. +- Python's `min(a, b)` keeps `a` unless `b < a`; `max(items, key=...)` keeps + the first item unless a later key is strictly greater. +- `mix_kg` is a dict: a name keeps the position of its first insertion. +- `caps` is spent on a local copy and written back only on success, so a call + handed to the Python finds the caller's dict untouched. +- Where the Python raises (an infinite payload from which nothing was taken + ends in `max()` of an empty mix), the Python runs, so the same exception + surfaces. + +The binding hands a call to the Python, untouched, whenever it cannot read +the inputs exactly: a non-float where a float goes, an int past 2**53, a caps +value that is neither float nor None, a NaN in the answer. `counts()` says how +many calls each side answered. + +## Measured (2026-11-15, Windows, CPython 3.14) + +| check | result | +|---|---| +| golden replay, `optimal_payload_mix` / `_hold_refining` / `_capped_sale_value` | 256 / 416 / 67 recorded calls, 0 differ | +| fuzz against the Python | 60,000 + 30,000 + 30,000 calls, 0 differ (exceptions compared too) | +| plant (`planted_knapsack_defect`: one ulp in every take and in the capped sale's value) | all six tests fail | +| the whole suite with the binding installed | 189 passed | +| per call, through the Python boundary | 1.9x / 1.3x / 3.7x faster: about 1 to 3.5 us saved per call | + +Called from Python, the binding is worth little: the boundary costs about as +much as the walk. The gain is in `es_core`, where the sizing loop calls +`cargo_core` with no boundary at all (economicspace's +`rust/es_core/README.md` has those numbers). + +## Build and test + +Build outside OneDrive (inside it, build scripts fail with "output path is +not a writable directory"): + + export CARGO_TARGET_DIR="$HOME/.cargo-target/spacevalue_cargo" + cd rust/cargo_py + python -m maturin build --release -o dist + python -m pip install --force-reinstall --no-deps dist/spacevalue_cargo_rs-*.whl + cd ../.. + SPACEVALUE_REQUIRE_RUST=1 python -m pytest tests/test_cargo_rust.py + +Without the module, `test_cargo_rust.py` skips; `SPACEVALUE_REQUIRE_RUST=1` +turns that skip into a failure, and the gate always sets it, so the check +cannot pass by not running. The planted build, which must fail all six: + + python -m maturin build --release --features planted_knapsack_defect -o dist-plant + +## Before this could merge (not done) + +- CI: build the binding on the three hosts in `tests.yml` and run + `test_cargo_rust.py` with `SPACEVALUE_REQUIRE_RUST=1`; build and run the + planted copy, expecting failure. Without that, a knapsack change that skips + the Rust copy only fails on a machine that happens to have it built. +- Decide how economicspace's `es_core` pins `cargo_core`: a git dependency at + the same tag as the spacevalue pin, held together by a check, as check 7 + holds the Python pins. +- Decide whether `spacevalue.cargo` should ever dispatch to the binding + itself. The per-call numbers above say probably not. +- A change to the knapsack is then a change to both copies, and the golden + fixture re-recorded only with the calc release that moves it, as now. diff --git a/rust/cargo_core/Cargo.toml b/rust/cargo_core/Cargo.toml new file mode 100644 index 0000000..5d72316 --- /dev/null +++ b/rust/cargo_core/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "spacevalue_cargo_core" +version = "0.1.0" +edition = "2021" +description = "PROTOTYPE: spacevalue.cargo's payload knapsack in Rust, bit-identical to the Python" +license = "MIT" +publish = false + +[lib] +path = "src/lib.rs" + +[features] +# Flips one ulp of every positive take: the gates must catch it. +planted_knapsack_defect = [] diff --git a/rust/cargo_core/src/lib.rs b/rust/cargo_core/src/lib.rs new file mode 100644 index 0000000..260bf4e --- /dev/null +++ b/rust/cargo_core/src/lib.rs @@ -0,0 +1,356 @@ +//! PROTOTYPE: `spacevalue.cargo`'s payload knapsack in Rust. +//! +//! Three functions, ported operation for operation from `spacevalue/cargo.py`: +//! `optimal_payload_mix`, `_hold_refining` and `_capped_sale_value`. The +//! contract is the one `tests/test_cargo_golden.py` holds the Python to: the +//! same bits. Every float operation below is the Python's, in the Python's +//! order and association; read each against its line in cargo.py. +//! +//! What the Python does that Rust must copy, and where: +//! * `sorted(phases, key=lambda p: -p[2])` is a STABLE sort on the negated +//! price. Any stable sort agrees with timsort under a strict weak order, +//! which floats are once NaN is excluded (`has_nan_price` refuses it). +//! * `min(a, b)` returns `a` unless `b < a`; `max(items, key=...)` keeps the +//! first item unless a later key is strictly greater (`>`). +//! * `mix` is a dict: a name keeps the position of its first insertion. +//! * `caps` is consumed in place. Here it is a local copy the caller writes +//! back only on success, so a refused call leaves the caller's dict as it +//! found it and the Python can run instead. +//! +//! Nothing here allocates per item beyond the walk's own lists, and nothing +//! depends on Python: es_core links this crate directly, and the PyO3 binding +//! in `rust/cargo_py` is a thin shell over it. + +/// One row of `asteroid_phase_table`: `(name, mass_fraction, usd_per_kg)`. +#[derive(Clone, Copy, Debug)] +pub struct Phase<'a> { + pub name: &'a str, + pub frac: f64, + pub price: f64, +} + +/// `caps` together with `cap_keys`, as the walk reads and spends them, asked +/// by PHASE name: the map resolves the market key itself, exactly as the +/// Python's `cap_keys.get(name, name) if cap_keys else name` does per item. +/// `None` values are absent keys: `caps.get(key)` cannot tell them apart and +/// neither branch writes one. +pub trait Caps { + fn get(&self, phase: &str) -> Option; + fn set(&mut self, phase: &str, v: f64); +} + +/// A small owned caps map (insertion-ordered; the walk only ever updates keys +/// that exist, so order is never changed by it). `key_of` is `cap_keys` +/// (empty when `cap_keys` is None or empty, which the Python treats alike). +#[derive(Clone, Debug, Default)] +pub struct CapsVec { + pub entries: Vec<(String, f64)>, + pub touched: Vec, + pub key_of: Vec<(String, String)>, +} + +impl CapsVec { + pub fn new(entries: Vec<(String, f64)>, key_of: Vec<(String, String)>) -> Self { + let n = entries.len(); + CapsVec { entries, touched: vec![false; n], key_of } + } + fn index(&self, phase: &str) -> Option { + let key = match self.key_of.iter().find(|(n, _)| n == phase) { + Some((_, k)) => k.as_str(), + None => phase, + }; + self.entries.iter().position(|(k, _)| k == key) + } +} + +impl Caps for CapsVec { + fn get(&self, phase: &str) -> Option { + self.index(phase).map(|i| self.entries[i].1) + } + fn set(&mut self, phase: &str, v: f64) { + if let Some(i) = self.index(phase) { + self.entries[i].1 = v; + self.touched[i] = true; + } + } +} + +#[inline(always)] +fn py_min(a: f64, b: f64) -> f64 { + if b < a { b } else { a } +} + +#[inline(always)] +fn planted(take: f64) -> f64 { + #[cfg(feature = "planted_knapsack_defect")] + { + if take > 0.0 { + return f64::from_bits(take.to_bits() ^ 1); + } + } + take +} + +pub fn planted_defect() -> bool { + cfg!(feature = "planted_knapsack_defect") +} + +/// True if any price is NaN: the sort would not be a strict weak order, and +/// timsort's answer would then depend on its merge pattern. +pub fn has_nan_price(phases: &[Phase<'_>]) -> bool { + phases.iter().any(|p| p.price.is_nan()) +} + +/// `sorted(phases, key=lambda p: -p[2])`. Caller guarantees no NaN price. +pub fn by_price<'a>(phases: &[Phase<'a>]) -> Vec> { + let mut v = phases.to_vec(); + v.sort_by(|a, b| (-a.price).partial_cmp(&(-b.price)).unwrap()); + v +} + +/// The full result dict. `None` is the empty dict (no `loaded_kg` key). +#[derive(Clone, Debug, PartialEq)] +pub struct Mix<'a> { + pub value_usd: f64, + pub usd_per_kg: f64, + pub loaded_kg: f64, + pub mix_kg: Vec<(&'a str, f64)>, + pub surplus_kg: f64, + pub dominant_phase: &'a str, + pub dominant_frac: f64, +} + +#[derive(Clone, Debug, PartialEq)] +pub enum MixOut<'a> { + /// `want_phase` was given: the bare float. + Want(f64), + /// The dict; `None` is the empty-load dict. + Full(Option>), + /// The Python raises here (`max()` of an empty mix, reached when + /// `loaded` is NaN, i.e. an infinite payload nothing was taken from): + /// the caller must run the Python so the same exception surfaces. + Raises, +} + +/// `optimal_payload_mix`. `ordered` is `by_price(phases)` (the Python's +/// `_PHASE_ORDER_CACHE`), computed once by the caller per phase table. +/// `phases_empty` stands for `not phases` on the ORIGINAL list. +#[allow(clippy::too_many_arguments)] +pub fn optimal_payload_mix<'a, C: Caps>( + payload_kg: f64, + feed_kg: f64, + ordered: &[Phase<'a>], + recovery: f64, + want_phase: Option<&str>, + mut caps: Option<&mut C>, + surplus_price_frac: f64, +) -> MixOut<'a> { + if payload_kg <= 0.0 || ordered.is_empty() { + return if want_phase.is_some() { MixOut::Want(0.0) } else { MixOut::Full(None) }; + } + + // The tiered walk (v1.22.0): each phase twice, full price then discount. + let tiered_mode = caps.is_some() && surplus_price_frac > 0.0 && want_phase.is_none(); + let tiered_list: Vec>; + let walk: &[Phase<'a>] = if tiered_mode { + let frac = if surplus_price_frac < 1.0 { surplus_price_frac } else { 1.0 }; + let mut t: Vec> = Vec::with_capacity(2 * ordered.len()); + for p in ordered { + t.push(*p); + t.push(Phase { name: p.name, frac: p.frac, price: p.price * frac }); + } + t.sort_by(|a, b| (-a.price).partial_cmp(&(-b.price)).unwrap()); + tiered_list = t; + &tiered_list + } else { + ordered + }; + // `tier_taken`, a dict keyed by name; small, so a linear map. + let mut tier_taken: Vec<(&'a str, f64)> = Vec::new(); + + let mut remaining = payload_kg; + let mut total = 0.0f64; + let mut surplus_kg = 0.0f64; + let mut mix: Vec<(&'a str, f64)> = Vec::new(); + for p in walk { + if remaining <= 0.0 { + break; + } + let (available, full_tier, had); + if !tiered_mode { + available = feed_kg * p.frac * recovery; + full_tier = true; + had = 0.0; + } else { + let h = tier_taken.iter().find(|(n, _)| *n == p.name).map(|(_, v)| *v).unwrap_or(-1.0); + full_tier = h < 0.0; + if full_tier { + had = 0.0; + available = feed_kg * p.frac * recovery; + } else { + had = h; + available = feed_kg * p.frac * recovery - had; + } + } + let mut take = py_min(available, remaining); + if full_tier { + if let Some(c) = caps.as_deref_mut() { + if let Some(allowance) = c.get(p.name) { + if allowance < take { + take = allowance; + } + c.set(p.name, allowance - take); + } + } + } + if tiered_mode { + let v = had + take; + match tier_taken.iter_mut().find(|(n, _)| *n == p.name) { + Some(e) => e.1 = v, + None => tier_taken.push((p.name, v)), + } + } + if take <= 0.0 { + continue; + } + let take = planted(take); + if let Some(w) = want_phase { + if p.name == w { + return MixOut::Want(take); + } + remaining -= take; + continue; + } + if full_tier { + match mix.iter_mut().find(|(n, _)| *n == p.name) { + Some(e) => e.1 = take, + None => mix.push((p.name, take)), + } + } else { + match mix.iter_mut().find(|(n, _)| *n == p.name) { + Some(e) => e.1 += take, + None => mix.push((p.name, 0.0 + take)), + } + surplus_kg += take; + } + total += take * p.price; + remaining -= take; + } + + if want_phase.is_some() { + return MixOut::Want(0.0); + } + let loaded = payload_kg - remaining; + if loaded <= 0.0 { + return MixOut::Full(None); + } + // max(mix.items(), key=kv[1]): first item unless a later one is strictly + // greater. `loaded` is NaN when the payload is infinite, and then the + // mix can be empty and the Python's `max()` raises. + if mix.is_empty() { + return MixOut::Raises; + } + let mut dom = mix[0]; + for e in &mix[1..] { + if e.1 > dom.1 { + dom = *e; + } + } + MixOut::Full(Some(Mix { + value_usd: total, + usd_per_kg: total / loaded, + loaded_kg: loaded, + mix_kg: mix, + surplus_kg, + dominant_phase: dom.0, + dominant_frac: dom.1 / loaded, + })) +} + +/// `_hold_refining`: `(refining Wh, Some(water kg) or None)`. +/// `refinery` is `None` or `(per_phase lookup, raw Wh/kg)`; `per_phase(name)` +/// is `per_phase.get(name, 0.0)`. `phases_empty` is `not phases`. +/// `None` where the Python raises (see `MixOut::Raises`). +pub fn hold_refining<'a>( + refinery: Option<(&dyn Fn(&str) -> f64, f64)>, + ordered: &[Phase<'a>], + payload_kg: f64, + feed_kg: f64, + beneficiate: bool, + recovery: f64, +) -> Option<(f64, Option)> { + let Some((per_phase, raw_wh_per_kg)) = refinery else { return Some((0.0, None)) }; + if payload_kg <= 0.0 { + return Some((0.0, None)); + } + if !beneficiate || ordered.is_empty() { + return Some((payload_kg * raw_wh_per_kg, None)); + } + let out = optimal_payload_mix::(payload_kg, feed_kg, ordered, recovery, None, None, 0.0); + let mix: Vec<(&str, f64)> = match out { + MixOut::Full(Some(m)) => m.mix_kg, + MixOut::Raises => return None, + _ => Vec::new(), + }; + let mut wh = 0.0f64; + for (name, kg) in &mix { + wh += kg * per_phase(name); + } + let water = mix.iter().find(|(n, _)| *n == "water").map(|(_, v)| *v).unwrap_or(0.0); + Some((wh, Some(water))) +} + +/// One `sale_terms` entry: `(kg, price, annual market kg, market key)`. +#[derive(Clone, Copy, Debug)] +pub struct SaleTerm<'a> { + pub kg: f64, + pub price: f64, + pub mkt: f64, + pub key: &'a str, +} + +/// `_capped_sale_value`: `(value_usd, unsold_kg, surplus_kg)`. Caller +/// guarantees no NaN price (the grant order is a sort on it). +pub fn capped_sale_value(terms: &[SaleTerm<'_>], window_yr: f64, surplus_price_frac: f64) -> (f64, f64, f64) { + let sells = surplus_price_frac > 0.0; + let mut order: Vec = (0..terms.len()).collect(); + order.sort_by(|&a, &b| (-terms[a].price).partial_cmp(&(-terms[b].price)).unwrap()); + let mut remaining: Vec<(&str, f64)> = Vec::new(); + let mut grants = vec![0.0f64; terms.len()]; + for &i in &order { + let t = terms[i]; + let allowance = match remaining.iter().find(|(k, _)| *k == t.key) { + Some((_, v)) => *v, + None => t.mkt * window_yr, + }; + grants[i] = if t.kg > allowance { allowance } else { t.kg }; + let left = if t.kg > allowance { 0.0 } else { allowance - t.kg }; + match remaining.iter_mut().find(|(k, _)| *k == t.key) { + Some(e) => e.1 = left, + None => remaining.push((t.key, left)), + } + } + let (mut value, mut unsold, mut surplus) = (0.0f64, 0.0f64, 0.0f64); + for (i, t) in terms.iter().enumerate() { + let granted = grants[i]; + if t.kg > granted { + let over = t.kg - granted; + value += granted * t.price; + if sells { + value += over * t.price * surplus_price_frac; + surplus += over; + } else { + unsold += over; + } + } else { + value += t.kg * t.price; + } + } + #[cfg(feature = "planted_knapsack_defect")] + { + if value != 0.0 { + value = f64::from_bits(value.to_bits() ^ 1); + } + } + (value, unsold, surplus) +} diff --git a/rust/cargo_py/Cargo.lock b/rust/cargo_py/Cargo.lock new file mode 100644 index 0000000..5fd930f --- /dev/null +++ b/rust/cargo_py/Cargo.lock @@ -0,0 +1,177 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "indoc" +version = "2.0.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a37b2691796cffeb8a8cd305ac66e65841559f147f4e63231d0eafa4db5384d1" +dependencies = [ + "rustversion", +] + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "memoffset" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a" +dependencies = [ + "autocfg", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "portable-atomic" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "pyo3" +version = "0.26.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ba0117f4212101ee6544044dae45abe1083d30ce7b29c4b5cbdfa2354e07383" +dependencies = [ + "indoc", + "libc", + "memoffset", + "once_cell", + "portable-atomic", + "pyo3-build-config", + "pyo3-ffi", + "pyo3-macros", + "unindent", +] + +[[package]] +name = "pyo3-build-config" +version = "0.26.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fc6ddaf24947d12a9aa31ac65431fb1b851b8f4365426e182901eabfb87df5f" +dependencies = [ + "target-lexicon", +] + +[[package]] +name = "pyo3-ffi" +version = "0.26.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "025474d3928738efb38ac36d4744a74a400c901c7596199e20e45d98eb194105" +dependencies = [ + "libc", + "pyo3-build-config", +] + +[[package]] +name = "pyo3-macros" +version = "0.26.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e64eb489f22fe1c95911b77c44cc41e7c19f3082fc81cce90f657cdc42ffded" +dependencies = [ + "proc-macro2", + "pyo3-macros-backend", + "quote", + "syn", +] + +[[package]] +name = "pyo3-macros-backend" +version = "0.26.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "100246c0ecf400b475341b8455a9213344569af29a3c841d29270e53102e0fcf" +dependencies = [ + "heck", + "proc-macro2", + "pyo3-build-config", + "quote", + "syn", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "spacevalue_cargo_core" +version = "0.1.0" + +[[package]] +name = "spacevalue_cargo_rs" +version = "0.1.0" +dependencies = [ + "pyo3", + "spacevalue_cargo_core", +] + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "target-lexicon" +version = "0.13.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c447be3a2abfa84b2d91680c56600bd6b2873866de27b36ec911be705e291da" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "unindent" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7264e107f553ccae879d21fbea1d6724ac785e8c3bfc762137959b5802826ef3" diff --git a/rust/cargo_py/Cargo.toml b/rust/cargo_py/Cargo.toml new file mode 100644 index 0000000..7f0f2fb --- /dev/null +++ b/rust/cargo_py/Cargo.toml @@ -0,0 +1,22 @@ +[package] +name = "spacevalue_cargo_rs" +version = "0.1.0" +edition = "2021" +description = "PROTOTYPE: optional Python binding of spacevalue_cargo_core" +license = "MIT" +publish = false + +[lib] +name = "spacevalue_cargo_rs" +crate-type = ["cdylib"] + +[dependencies] +pyo3 = { version = "=0.26.0", features = ["extension-module"] } +spacevalue_cargo_core = { path = "../cargo_core" } + +[features] +planted_knapsack_defect = ["spacevalue_cargo_core/planted_knapsack_defect"] + +[profile.release] +lto = true +codegen-units = 1 diff --git a/rust/cargo_py/pyproject.toml b/rust/cargo_py/pyproject.toml new file mode 100644 index 0000000..2aac40b --- /dev/null +++ b/rust/cargo_py/pyproject.toml @@ -0,0 +1,12 @@ +[build-system] +requires = ["maturin>=1.9,<2.0"] +build-backend = "maturin" + +[project] +name = "spacevalue_cargo_rs" +version = "0.1.0" +description = "PROTOTYPE: spacevalue.cargo's knapsack in Rust (optional; spacevalue never needs it)" +requires-python = ">=3.12" + +[tool.maturin] +features = ["pyo3/extension-module"] diff --git a/rust/cargo_py/src/lib.rs b/rust/cargo_py/src/lib.rs new file mode 100644 index 0000000..1d2293c --- /dev/null +++ b/rust/cargo_py/src/lib.rs @@ -0,0 +1,344 @@ +//! PROTOTYPE: the optional Python binding of `spacevalue_cargo_core`. +//! +//! Same names, same signatures and same results as `spacevalue.cargo`'s +//! `optimal_payload_mix`, `_hold_refining` and `_capped_sale_value`. Any +//! input the Rust path cannot be sure of (a non-exact float, a NaN price, an +//! int past 2**53, a caps value that is neither float nor None) is handed to +//! the Python function itself, untouched, and counted; so is any answer with +//! a NaN in it. `caps` is written back only after the Rust walk succeeded. + +use pyo3::prelude::*; +use pyo3::types::{PyBool, PyDict, PyFloat, PyInt, PyList, PyString, PyTuple}; +use spacevalue_cargo_core as core; +use std::sync::atomic::{AtomicU64, Ordering::Relaxed}; + +static FAST: AtomicU64 = AtomicU64::new(0); +static SLOW: AtomicU64 = AtomicU64::new(0); + +fn exact_f(v: &Bound<'_, PyAny>) -> Option { + v.downcast_exact::().ok().map(|f| f.value()) +} + +/// A float, or an int that converts exactly (what `float(x)` gives). +fn float_or_int(v: &Bound<'_, PyAny>) -> Option { + if let Some(f) = exact_f(v) { + return Some(f); + } + let n: i64 = v.downcast_exact::().ok()?.extract().ok()?; + if n.abs() <= (1i64 << 53) { Some(n as f64) } else { None } +} + +/// The phase list: exact `(str, float, float)` tuples in a list. `None` for +/// anything else. Names are copied out (the walk outlives the borrow). +fn read_phases(v: &Bound<'_, PyAny>) -> Option> { + let l = v.downcast_exact::().ok()?; + let mut out = Vec::with_capacity(l.len()); + for item in l.iter() { + let t = item.downcast_exact::().ok()?; + if t.len() != 3 { + return None; + } + let name = t.get_item(0).ok()?.downcast_exact::().ok()?.to_str().ok()?.to_owned(); + let frac = exact_f(&t.get_item(1).ok()?)?; + let price = exact_f(&t.get_item(2).ok()?)?; + out.push((name, frac, price)); + } + Some(out) +} + +fn as_phases(owned: &[(String, f64, f64)]) -> Vec> { + owned.iter().map(|(n, f, p)| core::Phase { name: n.as_str(), frac: *f, price: *p }).collect() +} + +fn py_cargo<'py>(py: Python<'py>) -> PyResult> { + py.import("spacevalue.cargo") +} + +fn slow<'py>(py: Python<'py>, name: &str, args: Bound<'py, PyTuple>, kwargs: Option<&Bound<'py, PyDict>>) -> PyResult> { + SLOW.fetch_add(1, Relaxed); + py_cargo(py)?.getattr(name)?.call(args, kwargs) +} + +fn mix_nan(m: &core::Mix<'_>) -> bool { + m.value_usd.is_nan() || m.usd_per_kg.is_nan() || m.loaded_kg.is_nan() || m.surplus_kg.is_nan() + || m.dominant_frac.is_nan() || m.mix_kg.iter().any(|(_, v)| v.is_nan()) +} + +fn mix_dict<'py>(py: Python<'py>, out: Option<&core::Mix<'_>>) -> PyResult> { + let d = PyDict::new(py); + match out { + None => { + d.set_item("value_usd", 0.0)?; + d.set_item("usd_per_kg", 0.0)?; + d.set_item("mix_kg", PyDict::new(py))?; + d.set_item("dominant_phase", py.None())?; + d.set_item("dominant_frac", 0.0)?; + d.set_item("surplus_kg", 0.0)?; + } + Some(m) => { + let mk = PyDict::new(py); + for (n, v) in &m.mix_kg { + mk.set_item(*n, *v)?; + } + d.set_item("value_usd", m.value_usd)?; + d.set_item("usd_per_kg", m.usd_per_kg)?; + d.set_item("loaded_kg", m.loaded_kg)?; + d.set_item("mix_kg", mk)?; + d.set_item("surplus_kg", m.surplus_kg)?; + d.set_item("dominant_phase", m.dominant_phase)?; + d.set_item("dominant_frac", m.dominant_frac)?; + } + } + Ok(d) +} + +/// Inputs of one `optimal_payload_mix` call, read exactly, or None. +struct MixIn { + payload: f64, + feed: f64, + phases: Vec<(String, f64, f64)>, + recovery: f64, + want: Option, + caps: Option, + surplus: f64, +} + +fn read_mix_in( + payload: &Bound<'_, PyAny>, feed: &Bound<'_, PyAny>, phases: &Bound<'_, PyAny>, + recovery: &Bound<'_, PyAny>, want: &Bound<'_, PyAny>, caps: &Bound<'_, PyAny>, + cap_keys: &Bound<'_, PyAny>, surplus: &Bound<'_, PyAny>, +) -> Option { + let payload = float_or_int(payload)?; + let feed = float_or_int(feed)?; + let phases = read_phases(phases)?; + let recovery = float_or_int(recovery)?; + let want = if want.is_none() { None } else { Some(want.downcast_exact::().ok()?.to_str().ok()?.to_owned()) }; + // `cap_keys.get(name, name) if cap_keys else name`: an empty dict is + // falsy, so None and {} are one case. + let mut key_of = Vec::new(); + if !cap_keys.is_none() { + let d = cap_keys.downcast_exact::().ok()?; + for (k, v) in d.iter() { + let k = k.downcast_exact::().ok()?.to_str().ok()?.to_owned(); + let v = v.downcast_exact::().ok()?.to_str().ok()?.to_owned(); + key_of.push((k, v)); + } + } + let caps = if caps.is_none() { + None + } else { + let d = caps.downcast_exact::().ok()?; + let mut entries = Vec::with_capacity(d.len()); + for (k, v) in d.iter() { + let k = k.downcast_exact::().ok()?.to_str().ok()?.to_owned(); + if v.is_none() { + continue; // `caps.get(key)` is None: never read, never written + } + entries.push((k, exact_f(&v)?)); + } + Some(core::CapsVec::new(entries, key_of)) + }; + let surplus = exact_f(surplus)?; + if phases.iter().any(|p| p.2.is_nan()) { + return None; + } + Some(MixIn { payload, feed, phases, recovery, want, caps, surplus }) +} + +#[pyfunction] +#[pyo3(signature = (payload_kg, feed_kg, phases, recovery, want_phase=None, caps=None, cap_keys=None, surplus_price_frac=None))] +#[allow(clippy::too_many_arguments)] +fn optimal_payload_mix<'py>( + py: Python<'py>, + payload_kg: Bound<'py, PyAny>, + feed_kg: Bound<'py, PyAny>, + phases: Bound<'py, PyAny>, + recovery: Bound<'py, PyAny>, + want_phase: Option>, + caps: Option>, + cap_keys: Option>, + surplus_price_frac: Option>, +) -> PyResult> { + let none = py.None().into_bound(py); + let want_b = want_phase.clone().unwrap_or_else(|| none.clone()); + let caps_b = caps.clone().unwrap_or_else(|| none.clone()); + let keys_b = cap_keys.clone().unwrap_or_else(|| none.clone()); + let zero = PyFloat::new(py, 0.0).into_any(); + let surplus_b = surplus_price_frac.clone().unwrap_or(zero); + let fallback = |py: Python<'py>| -> PyResult> { + let args = PyTuple::new(py, [payload_kg.clone(), feed_kg.clone(), phases.clone(), recovery.clone()])?; + let kw = PyDict::new(py); + if let Some(v) = &want_phase { kw.set_item("want_phase", v)?; } + if let Some(v) = &caps { kw.set_item("caps", v)?; } + if let Some(v) = &cap_keys { kw.set_item("cap_keys", v)?; } + if let Some(v) = &surplus_price_frac { kw.set_item("surplus_price_frac", v)?; } + slow(py, "optimal_payload_mix", args, Some(&kw)) + }; + let Some(mut inp) = read_mix_in(&payload_kg, &feed_kg, &phases, &recovery, &want_b, &caps_b, &keys_b, &surplus_b) else { + return fallback(py); + }; + let ph = as_phases(&inp.phases); + let ordered = core::by_price(&ph); + let mut caps_local = inp.caps.take(); + let out = core::optimal_payload_mix(inp.payload, inp.feed, &ordered, inp.recovery, + inp.want.as_deref(), caps_local.as_mut(), inp.surplus); + match out { + core::MixOut::Want(v) => { + if v.is_nan() { + return fallback(py); + } + if let (Some(c), Some(d)) = (&caps_local, &caps) { write_back(c, d)?; } + FAST.fetch_add(1, Relaxed); + Ok(PyFloat::new(py, v).into_any()) + } + core::MixOut::Raises => fallback(py), + core::MixOut::Full(m) => { + if let Some(m) = &m { + if mix_nan(m) { + return fallback(py); + } + } + if let (Some(c), Some(d)) = (&caps_local, &caps) { write_back(c, d)?; } + FAST.fetch_add(1, Relaxed); + Ok(mix_dict(py, m.as_ref())?.into_any()) + } + } +} + +/// `caps[key] = allowance - take` for every key the walk spent. Each key +/// already existed, so the dict's order is unchanged, as in the Python. +fn write_back(c: &core::CapsVec, d: &Bound<'_, PyAny>) -> PyResult<()> { + let d = d.downcast_exact::()?; + for (i, (k, v)) in c.entries.iter().enumerate() { + if c.touched[i] { + d.set_item(k, *v)?; + } + } + Ok(()) +} + +#[pyfunction] +#[pyo3(name = "_hold_refining")] +fn hold_refining<'py>( + py: Python<'py>, + refinery: Bound<'py, PyAny>, + phases: Bound<'py, PyAny>, + payload_kg: Bound<'py, PyAny>, + feed_kg: Bound<'py, PyAny>, + beneficiate: Bound<'py, PyAny>, + recovery: Bound<'py, PyAny>, +) -> PyResult> { + let fallback = |py: Python<'py>| { + let args = PyTuple::new(py, [refinery.clone(), phases.clone(), payload_kg.clone(), + feed_kg.clone(), beneficiate.clone(), recovery.clone()])?; + slow(py, "_hold_refining", args, None) + }; + // (per_phase dict as pairs, raw Wh/kg), or None. + let reff: Option<(Vec<(String, f64)>, f64)> = if refinery.is_none() { + None + } else { + let parsed = (|| -> Option<(Vec<(String, f64)>, f64)> { + let t = refinery.downcast_exact::().ok()?; + if t.len() != 2 { return None; } + let d = t.get_item(0).ok()?; + let d = d.downcast_exact::().ok()?; + let mut m = Vec::with_capacity(d.len()); + for (k, v) in d.iter() { + m.push((k.downcast_exact::().ok()?.to_str().ok()?.to_owned(), exact_f(&v)?)); + } + Some((m, exact_f(&t.get_item(1).ok()?)?)) + })(); + match parsed { Some(p) => Some(p), None => return fallback(py) } + }; + let (Some(payload), Some(feed), Some(rec)) = (float_or_int(&payload_kg), float_or_int(&feed_kg), float_or_int(&recovery)) else { + return fallback(py); + }; + let Ok(ben) = beneficiate.downcast_exact::().map(|b| b.is_true()) else { return fallback(py) }; + let owned: Vec<(String, f64, f64)> = if phases.is_none() { + Vec::new() + } else { + match read_phases(&phases) { Some(p) => p, None => return fallback(py) } + }; + if owned.iter().any(|p| p.2.is_nan()) { + return fallback(py); + } + let ph = as_phases(&owned); + let ordered = core::by_price(&ph); + let r = match &reff { + None => core::hold_refining(None, &ordered, payload, feed, ben, rec), + Some((m, raw)) => { + let f = |name: &str| -> f64 { m.iter().find(|(k, _)| k == name).map(|(_, v)| *v).unwrap_or(0.0) }; + core::hold_refining(Some((&f, *raw)), &ordered, payload, feed, ben, rec) + } + }; + let Some(r) = r else { return fallback(py) }; + if r.0.is_nan() || r.1.is_some_and(|w| w.is_nan()) { + return fallback(py); + } + FAST.fetch_add(1, Relaxed); + let water: Bound<'py, PyAny> = match r.1 { + None => py.None().into_bound(py), + Some(w) => PyFloat::new(py, w).into_any(), + }; + Ok(PyTuple::new(py, [PyFloat::new(py, r.0).into_any(), water])?.into_any()) +} + +#[pyfunction] +#[pyo3(name = "_capped_sale_value", signature = (sale_terms, window_yr, surplus_price_frac=None))] +fn capped_sale_value<'py>( + py: Python<'py>, + sale_terms: Bound<'py, PyAny>, + window_yr: Bound<'py, PyAny>, + surplus_price_frac: Option>, +) -> PyResult> { + let fallback = |py: Python<'py>| { + let args = PyTuple::new(py, [sale_terms.clone(), window_yr.clone()])?; + let kw = PyDict::new(py); + if let Some(v) = &surplus_price_frac { kw.set_item("surplus_price_frac", v)?; } + slow(py, "_capped_sale_value", args, Some(&kw)) + }; + let parsed = (|| -> Option<(Vec<(f64, f64, f64, String)>, f64, f64)> { + let l = sale_terms.downcast_exact::().ok()?; + let mut v = Vec::with_capacity(l.len()); + for it in l.iter() { + let t = it.downcast_exact::().ok()?; + if t.len() != 4 { return None; } + v.push((exact_f(&t.get_item(0).ok()?)?, exact_f(&t.get_item(1).ok()?)?, + exact_f(&t.get_item(2).ok()?)?, + t.get_item(3).ok()?.downcast_exact::().ok()?.to_str().ok()?.to_owned())); + } + let w = exact_f(&window_yr)?; + let s = match &surplus_price_frac { None => 0.0, Some(b) => exact_f(b)? }; + if v.iter().any(|t| t.1.is_nan()) { return None; } + Some((v, w, s)) + })(); + let Some((owned, w, s)) = parsed else { return fallback(py) }; + let terms: Vec> = owned.iter().map(|(kg, p, m, k)| core::SaleTerm { kg: *kg, price: *p, mkt: *m, key: k.as_str() }).collect(); + let (a, b, c) = core::capped_sale_value(&terms, w, s); + if a.is_nan() || b.is_nan() || c.is_nan() { + return fallback(py); + } + FAST.fetch_add(1, Relaxed); + Ok(PyTuple::new(py, [a, b, c])?.into_any()) +} + +/// (calls answered in Rust, calls handed to the Python). +#[pyfunction] +fn counts() -> (u64, u64) { + (FAST.load(Relaxed), SLOW.load(Relaxed)) +} + +#[pyfunction] +fn planted_defect() -> bool { + core::planted_defect() +} + +#[pymodule] +fn spacevalue_cargo_rs(m: &Bound<'_, PyModule>) -> PyResult<()> { + m.add_function(wrap_pyfunction!(optimal_payload_mix, m)?)?; + m.add_function(wrap_pyfunction!(hold_refining, m)?)?; + m.add_function(wrap_pyfunction!(capped_sale_value, m)?)?; + m.add_function(wrap_pyfunction!(counts, m)?)?; + m.add_function(wrap_pyfunction!(planted_defect, m)?)?; + Ok(()) +} diff --git a/tests/test_cargo_rust.py b/tests/test_cargo_rust.py new file mode 100644 index 0000000..ccae8c2 --- /dev/null +++ b/tests/test_cargo_rust.py @@ -0,0 +1,227 @@ +# -*- coding: utf-8 -*- +"""PROTOTYPE: the Rust knapsack (`spacevalue_cargo_rs`) gives the Python's bits. + +The optional extension built from `rust/cargo_py` re-implements three +functions of `spacevalue.cargo`: `optimal_payload_mix`, `_hold_refining` and +`_capped_sale_value`. Its contract is the golden test's: the same result, +float for float, and the same arguments afterwards (the knapsack spends the +`caps` dict it is given). Two checks hold it there: + + * every recorded call in the golden fixture, replayed through the + extension and compared exactly as `test_cargo_golden.py` compares the + Python (the same encoder, so the last bit); + * a seeded fuzz against the Python itself, aimed at what a port gets wrong: + price ties (the sort must be stable), negative and zero prices, duplicate + phase names, `None` caps values, markets shared through `cap_keys`, the + surplus tier at, below and above 1.0, int arguments, infinities. + +The extension is optional, so without it these tests skip, which would make +them a check that never runs: `SPACEVALUE_REQUIRE_RUST=1` turns the skip into +a failure, and the gate (`rust/cargo_py/README.md`) always sets it. A build +with the `planted_knapsack_defect` feature must FAIL here; the gate proves it. +""" + +import copy +import gzip +import json +import math +import os +import random + +import pytest + +from spacevalue import _cargo_codec +from spacevalue import cargo + +try: + import spacevalue_cargo_rs as rs +except ImportError: # pragma: no cover - exercised only without the build + rs = None + if os.environ.get("SPACEVALUE_REQUIRE_RUST") == "1": + raise + +pytestmark = pytest.mark.skipif(rs is None, reason="spacevalue_cargo_rs not built") + +HERE = os.path.dirname(os.path.abspath(__file__)) +FIXTURE = os.path.join(HERE, "data", "cargo-calc-1.32.0", "calls.json.gz") +PORTED = ("optimal_payload_mix", "_hold_refining", "_capped_sale_value") + + +def _expand(e, blobs): + if isinstance(e, list): + if len(e) == 2 and e[0] == "ref": + return _expand(blobs[e[1]], blobs) + return [_expand(v, blobs) for v in e] + return e + + +@pytest.mark.parametrize("fn", PORTED) +def test_rust_replays_every_recorded_call(fn): + with gzip.open(FIXTURE, "rt", encoding="utf-8") as f: + body = json.load(f) + dec = _cargo_codec.Decoder(body["blobs"]) + calls = [c for c in body["calls"] if c["fn"] == fn] + assert calls + enc = _cargo_codec.Encoder() + fast0, slow0 = rs.counts() + differ = [] + for c in calls: + args = dec.dec(c["args"]) + kwargs = dec.dec(c["kwargs"]) + result = getattr(rs, fn)(*args, **kwargs) + got = [enc.enc(result), enc.enc(list(args)), enc.enc(dict(kwargs))] + want = [c["result"], c["args_after"], c["kwargs_after"]] + if _expand(got, enc.blobs) != _expand(want, body["blobs"]): + differ.append(c["variant"]) + fast, slow = rs.counts() + assert not differ, "%d of %d %s calls differ (cells: %s)" % ( + len(differ), len(calls), fn, ", ".join(sorted(set(differ)))) + # A replay the extension handed back to the Python proves nothing. + assert fast - fast0 >= 0.9 * len(calls), (fn, fast - fast0, slow - slow0) + + +# ── fuzz ──────────────────────────────────────────────────────────────────── + +NAMES = ["water", "kamacite", "taenite", "olivine", "pyroxene", "troilite", + "silicates", "other (bulk silicate)", "carbon", "pgm"] +PRICES = [0.0, -0.0, 0.05, 1.0, 2.5, 2.5, 12.0, 1500.0, -3.0, 40000.0] + + +def _float(r, scale): + k = r.random() + if k < 0.08: + return 0.0 + if k < 0.12: + return float(r.choice([1, 2, 7])) + if k < 0.14: + return math.inf + return r.random() * scale + + +def _phases(r): + n = r.choice([0, 1, 2, 3, 4, 6, 8, 10]) + pool = NAMES[:] + out = [] + for _ in range(n): + name = r.choice(NAMES) if r.random() < 0.1 else (pool.pop(r.randrange(len(pool))) if pool else "x") + frac = r.choice([0.0, 0.5, 1e-9]) if r.random() < 0.15 else r.random() + price = r.choice(PRICES) if r.random() < 0.5 else r.uniform(-5, 5000) + out.append((name, frac, price)) + return out + + +def _caps(r, phases): + if r.random() < 0.4: + return None, None + caps = {} + keys = {} + for name, _f, _p in phases: + if r.random() < 0.3: + keys[name] = r.choice(["silicates", "metals", name]) + for key in set(keys.values()) | {p[0] for p in phases}: + k = r.random() + if k < 0.1: + caps[key] = None + elif k < 0.2: + caps[key] = 0.0 + elif k < 0.3: + continue + else: + caps[key] = r.random() * 2000 + if r.random() < 0.2: + keys = {} + elif r.random() < 0.2: + keys = None + return caps, keys + + +def _payload(r): + k = r.random() + if k < 0.05: + return 0.0 + if k < 0.08: + return -1.0 + if k < 0.12: + return r.choice([500, 1000]) + if k < 0.13: + return math.inf + return r.random() * 5000 + + +def _same(a, b): + enc = _cargo_codec.Encoder() + return _expand(enc.enc(a), enc.blobs) == _expand(enc.enc(b), enc.blobs) + + +def _call(f, *a, **kw): + """The result, or the exception's type and text: the port must raise + where the Python raises, and the same thing.""" + try: + return ("ok", f(*a, **kw)) + except Exception as e: # noqa: BLE001 - compared, not swallowed + return ("raised", type(e).__name__, str(e)) + + +def test_rust_mix_matches_python_on_hostile_inputs(): + r = random.Random(20261115) + differ = [] + for i in range(60000): + phases = _phases(r) + caps, keys = _caps(r, phases) + kw = {} + if r.random() < 0.3: + kw["want_phase"] = r.choice(["water"] + [p[0] for p in phases] if phases else ["water"]) + if caps is not None: + kw["caps"] = caps + if keys is not None: + kw["cap_keys"] = keys + if r.random() < 0.6: + kw["surplus_price_frac"] = r.choice([0.0, 0.5, 1.0, 1.5, r.random()]) + args = (_payload(r), _float(r, 20000) if r.random() < 0.9 else r.choice([3000, 0]), + phases, r.choice([0.9, 1.0, r.random()])) + kw_py, kw_rs = copy.deepcopy(kw), copy.deepcopy(kw) + want = _call(cargo.optimal_payload_mix, *copy.deepcopy(args), **kw_py) + got = _call(rs.optimal_payload_mix, *copy.deepcopy(args), **kw_rs) + if not (_same(want, got) and _same(kw_py, kw_rs)): + differ.append((i, args, kw)) + assert not differ, "%d differ; first %r" % (len(differ), differ[0]) + fast, slow = rs.counts() + assert fast > slow + + +def test_rust_hold_refining_matches_python(): + r = random.Random(7) + differ = [] + for i in range(30000): + phases = _phases(r) + if r.random() < 0.1: + phases = None + refinery = None + if r.random() < 0.85: + per = {p[0]: r.random() * 50 for p in (phases or []) if r.random() < 0.8} + refinery = (per, r.random() * 30) + args = (refinery, phases, _payload(r), _float(r, 20000), r.random() < 0.7, + r.choice([0.9, 1.0, r.random()])) + want = _call(cargo._hold_refining, *copy.deepcopy(args)) + got = _call(rs._hold_refining, *copy.deepcopy(args)) + if not _same(want, got): + differ.append((i, args)) + assert not differ, "%d differ; first %r" % (len(differ), differ[0]) + + +def test_rust_capped_sale_matches_python(): + r = random.Random(11) + differ = [] + for i in range(30000): + terms = [] + for _ in range(r.choice([0, 1, 2, 4, 7])): + terms.append((_float(r, 3000), r.choice(PRICES) if r.random() < 0.5 else r.uniform(-5, 5000), + _float(r, 500), r.choice(["silicates", "metals", "water", "pgm"]))) + args = [terms, r.choice([0.0, 0.25, 1.0, r.random() * 10])] + if r.random() < 0.6: + args.append(r.choice([0.0, 0.5, 1.0, r.random()])) + want = _call(cargo._capped_sale_value, *copy.deepcopy(args)) + got = _call(rs._capped_sale_value, *copy.deepcopy(args)) + if not _same(want, got): + differ.append((i, args)) + assert not differ, "%d differ; first %r" % (len(differ), differ[0]) From 793b575c0c1f21c20e7c62fb7db5dada8df2df59 Mon Sep 17 00:00:00 2001 From: loggger101 Date: Mon, 16 Nov 2026 11:16:38 -0500 Subject: [PATCH 2/3] Rust cargo tests: each fuzz gates its own fast-path share The hold and capped-sale fuzzes had no share check, and the mix fuzz read process-wide counters, so a build answering everything through the Python fallback compared the Python with itself and passed. Each now requires Rust to have answered more calls than it handed back, counted since the test began (planted all-fallback: 3 of 3 caught). SPACEVALUE_REQUIRE_RUST accepts any value but unset or 0. Ignore cargo_core's Cargo.lock, which cargo test regenerates. Co-Authored-By: Claude Opus 5.5 --- .gitignore | 2 ++ tests/test_cargo_rust.py | 20 +++++++++++++++++--- 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/.gitignore b/.gitignore index 992f81e..20aae64 100644 --- a/.gitignore +++ b/.gitignore @@ -17,3 +17,5 @@ Thumbs.db # Default build output spacevalue_data/ +# a library crate: its lock is regenerated by `cargo test` (cargo_py commits its own) +rust/cargo_core/Cargo.lock diff --git a/tests/test_cargo_rust.py b/tests/test_cargo_rust.py index ccae8c2..4e73dc4 100644 --- a/tests/test_cargo_rust.py +++ b/tests/test_cargo_rust.py @@ -37,7 +37,7 @@ import spacevalue_cargo_rs as rs except ImportError: # pragma: no cover - exercised only without the build rs = None - if os.environ.get("SPACEVALUE_REQUIRE_RUST") == "1": + if os.environ.get("SPACEVALUE_REQUIRE_RUST", "") not in ("", "0"): raise pytestmark = pytest.mark.skipif(rs is None, reason="spacevalue_cargo_rs not built") @@ -153,6 +153,16 @@ def _same(a, b): return _expand(enc.enc(a), enc.blobs) == _expand(enc.enc(b), enc.blobs) +def _fast_share_since(c0): + """(fast, slow) since the counts `c0`; fails if Rust answered none, or + fewer calls than it handed back (a fuzz answered by the fallback would + only compare the Python with itself).""" + fast, slow = rs.counts() + fast, slow = fast - c0[0], slow - c0[1] + assert fast > 0 and fast > slow, ("fast", fast, "slow", slow) + return fast, slow + + def _call(f, *a, **kw): """The result, or the exception's type and text: the port must raise where the Python raises, and the same thing.""" @@ -164,6 +174,7 @@ def _call(f, *a, **kw): def test_rust_mix_matches_python_on_hostile_inputs(): r = random.Random(20261115) + c0 = rs.counts() differ = [] for i in range(60000): phases = _phases(r) @@ -185,12 +196,12 @@ def test_rust_mix_matches_python_on_hostile_inputs(): if not (_same(want, got) and _same(kw_py, kw_rs)): differ.append((i, args, kw)) assert not differ, "%d differ; first %r" % (len(differ), differ[0]) - fast, slow = rs.counts() - assert fast > slow + _fast_share_since(c0) def test_rust_hold_refining_matches_python(): r = random.Random(7) + c0 = rs.counts() differ = [] for i in range(30000): phases = _phases(r) @@ -207,10 +218,12 @@ def test_rust_hold_refining_matches_python(): if not _same(want, got): differ.append((i, args)) assert not differ, "%d differ; first %r" % (len(differ), differ[0]) + _fast_share_since(c0) def test_rust_capped_sale_matches_python(): r = random.Random(11) + c0 = rs.counts() differ = [] for i in range(30000): terms = [] @@ -225,3 +238,4 @@ def test_rust_capped_sale_matches_python(): if not _same(want, got): differ.append((i, args)) assert not differ, "%d differ; first %r" % (len(differ), differ[0]) + _fast_share_since(c0) From 54fe95f6ad50cc08454ca65666e137488ee76a5b Mon Sep 17 00:00:00 2001 From: loggger101 Date: Tue, 17 Nov 2026 21:49:26 -0500 Subject: [PATCH 3/3] 0.7.1: CI builds and tests the Rust knapsack copy; spacevalue_cargo_rs ships from the tag (no number moves) --- .github/workflows/tests.yml | 51 +++++++++++++++++++++++++++++++++++++ CHANGELOG.md | 23 +++++++++++++++++ rust/README.md | 18 +++++++------ spacevalue/__init__.py | 2 +- 4 files changed, 85 insertions(+), 9 deletions(-) diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 3fcf82e..19604e4 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -32,6 +32,57 @@ jobs: - name: The snapshots match SHA256SUMS run: python -m spacevalue quotes check + # rust/: the knapsack's Rust copy, which economicspace's es_core links. A + # knapsack change made only in cargo.py fails here, not on whichever machine + # happens to have the binding built. The planted build (one ulp in every + # take) must fail all six Rust tests, or the tests could not see a defect; + # SPACEVALUE_REQUIRE_RUST=1 turns their skip-when-missing into a failure. + # The good binding is installed the way a consumer installs it, `pip + # install` of rust/cargo_py, which builds cargo_core by its relative path. + rust: + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, windows-latest, macos-latest] + python-version: ["3.13", "3.14"] + env: + SPACEVALUE_REQUIRE_RUST: "1" + steps: + - uses: actions/checkout@v5 + - uses: actions/setup-python@v6 + with: + python-version: ${{ matrix.python-version }} + - name: Install + shell: bash + run: python -m pip install -e ".[test]" maturin==1.9.6 + # No `cargo test`: cargo_core has no Rust tests (it is tested only + # against cargo.py, through the binding), and a step that passes on zero + # tests would read as coverage it is not. + - name: The planted build fails every Rust test + shell: bash + run: | + python -m maturin build --release --features planted_knapsack_defect -m rust/cargo_py/Cargo.toml -o dist-plant + python -m pip install --force-reinstall --no-deps dist-plant/spacevalue_cargo_rs-*.whl + python -c "import spacevalue_cargo_rs as r; assert r.planted_defect()" + set +e + python -m pytest -q -p no:cacheprovider tests/test_cargo_rust.py > plant.log 2>&1 + rc=$? + set -e + tail -3 plant.log + [ $rc -ne 0 ] || { echo "the planted build PASSED the Rust tests"; exit 1; } + grep -Eq "^6 failed" plant.log || { echo "expected all 6 Rust tests to fail"; exit 1; } + - name: The good build, installed as a consumer installs it + shell: bash + run: | + python -m pip install --force-reinstall --no-deps ./rust/cargo_py + python -c "import spacevalue_cargo_rs as r; assert not r.planted_defect()" + - name: The Rust tests, then the whole suite with the binding installed + shell: bash + run: | + python -m pytest -q -p no:cacheprovider tests/test_cargo_rust.py + python -m pytest -q + # The editable install above reads the tree, so it cannot see a snapshot or # a module missing from the wheel. This installs the built wheel and uses # it from a directory where the source is not importable. diff --git a/CHANGELOG.md b/CHANGELOG.md index 0d78906..303a450 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -135,6 +135,29 @@ code. ## Package releases +### 0.7.1 - 2026-11-17 + +Data contract 1.21.0, unchanged, and **no number moves**: nothing under +`spacevalue/` changed except `__version__`. This adds `rust/`, a Rust copy of +`cargo.py`'s knapsack (`optimal_payload_mix`, `_hold_refining`, +`_capped_sale_value`) for economicspace's `es_core` to link, and an optional +binding of it, `spacevalue_cargo_rs`. `spacevalue` never imports either. + +- `rust/cargo_core` (plain Rust) is the port; `rust/cargo_py` (PyO3) binds + it. The binding is a separate package, installed from this tag with + `pip install "spacevalue_cargo_rs @ git+https://github.com/loggger101/spacevalue@v0.7.1#subdirectory=rust/cargo_py"` + (it needs a Rust toolchain). It is not a `spacevalue` extra, which would + make every install of the package need one. +- `tests/test_cargo_rust.py` holds the binding to the Python bit for bit + (the golden replay, and fuzzed calls with exceptions compared); it skips + without the binding unless `SPACEVALUE_REQUIRE_RUST=1`. +- CI's new `rust` job, on the three hosts and Python 3.13 and 3.14: the + planted build (`planted_knapsack_defect`) failing all six Rust tests, the + good binding installed as a consumer installs it, and the whole suite with + it. A knapsack change made only in `cargo.py` now fails here. There is no + `cargo test` step: `cargo_core` has no Rust tests, only the comparison with + `cargo.py` through the binding. + ### 0.7.0 - 2026-11-12 Data contract **1.21.0**, above: spacecost is pinned at `v0.17.1`, was diff --git a/rust/README.md b/rust/README.md index c4814c8..2376102 100644 --- a/rust/README.md +++ b/rust/README.md @@ -1,8 +1,11 @@ # rust/: the cargo knapsack in Rust (prototype) -**Status:** a prototype on branch `rust-cargo-prototype`. Not merged, not -released, and nothing in `spacevalue` imports it. The Python in -`spacevalue/cargo.py` stays the reference and the default. +**Status:** shipped with spacevalue 0.7.1, tested by CI's `rust` job, and +still optional: nothing in `spacevalue` imports it. The Python in +`spacevalue/cargo.py` stays the reference and the default. Install the +binding from the tag (it needs a Rust toolchain): + + pip install "spacevalue_cargo_rs @ git+https://github.com/loggger101/spacevalue@v0.7.1#subdirectory=rust/cargo_py" ## What it is @@ -74,12 +77,11 @@ cannot pass by not running. The planted build, which must fail all six: python -m maturin build --release --features planted_knapsack_defect -o dist-plant -## Before this could merge (not done) +## Open -- CI: build the binding on the three hosts in `tests.yml` and run - `test_cargo_rust.py` with `SPACEVALUE_REQUIRE_RUST=1`; build and run the - planted copy, expecting failure. Without that, a knapsack change that skips - the Rust copy only fails on a machine that happens to have it built. +- (Done in 0.7.1.) CI: the `rust` job in `tests.yml` builds the binding on + the three hosts and runs `test_cargo_rust.py` with + `SPACEVALUE_REQUIRE_RUST=1`, after the planted copy has failed all six. - Decide how economicspace's `es_core` pins `cargo_core`: a git dependency at the same tag as the spacevalue pin, held together by a check, as check 7 holds the Python pins. diff --git a/spacevalue/__init__.py b/spacevalue/__init__.py index d64db6c..502910c 100644 --- a/spacevalue/__init__.py +++ b/spacevalue/__init__.py @@ -33,7 +33,7 @@ # The PACKAGE release. Not the data contract: that is # `MineralValueConfig.pipeline_version`, stamped into every row. -__version__ = "0.7.0" +__version__ = "0.7.1" # Each public name, and the submodule that defines it. _LAZY = {name: "catalog" for name in (