diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..1d0aab7 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,133 @@ +# Changelog + +All notable changes to this project are listed here. The format follows +[Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and versions follow +[Semantic Versioning](https://semver.org/). + +## [1.1.0] - 2026-11-12 + +This release fixes the findings of an outside verification of v1.0.0. They are +described in [docs/verification-findings.md](docs/verification-findings.md). +The formal results there (TLA+, Lean, Prolog, conformance traces) apply to +v1.0.0. v1.1.0 has not been formally re-verified. Its fixes are covered by +unit tests, seeded random tests and the sandbox suite. + +### Fixed + +- F-1 (high): a hedge admitted after an `observe` broke a bound could never + settle. Admission now counts every outcome of every open record, including + its release. Every open record can now be resolved: a Reserved one by + cancel, a dispatched one by its executor's report. + [F-1](docs/verification-findings.md#f-1-high-disturbed-state-hedge-wedge) +- F-2 (high): in the `risk` fixture, a position that a completed hedge relied + on could not be released. A hedge must now stay in bounds if the position is + later reported unexecuted. + [F-2](docs/verification-findings.md#f-2-high-healthy-state-release-wedge-in-the-risk-fixture) +- F-2b: a release could leave the value range and fail `Arithmetic`. The + release is now inside the admission interval. + [F-2b](docs/verification-findings.md#f-2b-a-release-can-leave-the-value-range) +- F-3 (low): one actor could use up all 256 lifetime records with free + submit-and-cancel cycles. The pool now keeps a window of the 256 most recent + records. [F-3](docs/verification-findings.md#f-3-low-lifetime-record-exhaustion) +- F-4 (low): a recipe's actor could be its own executor. `new` now rejects + such a config (`InvalidConfig`). The owner may still be a recipe's + executor; the repository owner decided to allow it. + [F-4](docs/verification-findings.md#f-4-low-a-principal-can-attest-its-own-work) +- F-5 (low): at version u32::MAX every transition failed, including + settlement. Submit, dispatch, pause and observe now stop 768 versions + earlier, so acknowledgment, settlement and cancellation always remain + available. + [F-5](docs/verification-findings.md#f-5-low-version-saturation-freezes-every-transition) +- F-6 (low): one long-open record blocked the snapshot refresh. The owner can + now restate the current values at any time. + [F-6](docs/verification-findings.md#f-6-low-an-open-record-blocks-the-only-snapshot-refresh) +- NT-F1 (medium, diagnostics): the documented build dropped every panic + message. `scripts/build.sh` now sets `--cfg near` and fails if a Wasm does + not import `env.panic_utf8`. + [NT-F1](docs/verification-findings.md#nt-f1-medium-diagnostics-not-safety-the-documented-build-drops-every-panic-message) +- NT-F2 (low): `reconcile` kept an attached deposit. It now rejects any + deposit. [NT-F2](docs/verification-findings.md#nt-f2-low-reconcile-keeps-an-attached-deposit) +- NT-F4 (low): a promise result that was not a JSON string made the callback + panic. `on_result` now reads the raw result; anything but one JSON string of + at most 64 bytes becomes Unknown. + [NT-F4](docs/verification-findings.md#nt-f4-low-a-non-string-promise-result-does-not-become-unknown) + +### Changed + +- Stricter admission. Two kinds of request that v1.0.0 admitted are refused: + a reservation that by itself reduces a violated metric (recovery must come + from completion), and a request that is in bounds only while another open + record's reservation stays in place. In the `risk` fixture, with one credit + position open, the largest admitted selloff hedge is 6 units, not 8. + Confirmed by the repository owner. +- Record window. The pool keeps the 256 most recent commitments. A submit + prunes the oldest one when it is completed or cancelled, and fails `Full` + while it is open. A dispatched oldest record closes only when its executor + reports, so a silent executor can hold submit at `Full`. Ids keep + counting, and a pruned id is `NotFound` (including a repeated executor + `settle`, which v1.0.0 accepted). `get_pool` gains `first_id` and + `completed_units`; prerequisites count completed units over the pool's + life. `get_commitments` takes `from` as an id. Confirmed by the + repository owner. +- `cancel` of a Completed record fails `InvalidState` (was `Pending`). + Dispatched, Active and Unknown records still fail `Pending`. +- Version reserve: submit, dispatch, `set_paused` and `observe` fail + `Arithmetic` from `VERSION_CAP` (u32::MAX - 768). `preview` reports it too. +- Executor retention. The synthetic executor forgets a job once the newest + id the lock has vouched for is 256 or more past its id. That newest id is + the largest one for which the lock's `execute` created a job, or whose + `settle` (from `finish` or `confirm_not_executed`) the lock accepted, + recorded by a new private callback `on_settled`; both methods still + return the lock's result. An `execute` of an id that already has a job + moves nothing. + Forgotten id: `execute` returns `"cancelled"`, `confirm_not_executed` + fails `stale id`, `finish` fails `unknown job`. At most 256 jobs have ids + at or below the newest id, so honest use holds 256 jobs plus + confirmations in flight. The cap is 512 (v1.0.0: 256 over the executor's + life). It is reached only with at least 256 jobs above the newest id + (more if fewer sit at or below it): confirmations the lock refused, which + keep their jobs (a typo of a far id for good), or confirmations whose + callback has not run. At the cap `confirm_not_executed` fails `full`, and + if executes keep failing the lock can stay at `Full` + ([docs/api.md](docs/api.md#executor-protocol)). +- Wasm import surface (NT-F3). Both contracts create promises with + `promise_create`, `promise_then` and `promise_return` instead of near-sdk's + `Promise`. The 15 host imports for accounts, deploys, keys, transfers and + staking are gone, and `scripts/build.sh` fails if one comes back. It also + fails on any import that is not on its list of the current 18 contract and + 16 executor imports (the executor's `on_settled` reads the lock's `settle` + result). `dispatch`, `reconcile`, `finish` and `confirm_not_executed` + return `()` in Rust; on chain the result is still that of the promise each + returns: `on_result` for `dispatch` and `reconcile`, the lock's `settle` + for `finish` and `confirm_not_executed`. +- Build: `scripts/build.sh` sets `RUSTFLAGS="--cfg near"`, and + `artifacts/build.json` records the flags and each Wasm's imports. +- `on_result` logs a result for an id with no record (`error: "NotFound"`) + instead of panicking. +- Stored state. The lock's pool gains `first_id` and `completed_units`, and + the executor gains `newest`. A v1.0.0 deployment cannot be upgraded in + place: its state would not load. Deploy v1.1.0 to fresh accounts; no + migration is provided. + +### Docs + +- An acknowledgment that does not change the status is `Ok` without a + version change. The docs now say so (the code already did). +- [docs/api.md](docs/api.md) describes the events. Their format version + stays `1.0.0`: no event shape changed. It also says that the read methods + keep a deposit sent with a transaction. +- [docs/api.md](docs/api.md) has a gas table, measured on the v1.1.0 Wasm at + a maximum-size state by `crates/sandbox/tests/res1.rs` (ignored by + default; run it with `--ignored`). Executor `finish` and + `confirm_not_executed` need 70 Tgas (least measured 55; 56 for `finish` + with 512 jobs). +- [docs/verification-findings.md](docs/verification-findings.md) gives each + finding's status. + +## [1.0.0] - 2026-11-12 + +First release (commit `80fb89e`, not tagged): the pool core, the NEAR +contract, the synthetic executor, six scenarios, the local demo and static +UIs, and the sandbox integration tests. It is the baseline the outside +verification checked: its core, contract and executor are byte-identical to +commit `a4bb5c3`. diff --git a/Cargo.lock b/Cargo.lock index 898e694..e6e535b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2434,7 +2434,7 @@ checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" [[package]] name = "pool-contract" -version = "1.0.0" +version = "1.1.0" dependencies = [ "near-sdk", "pool-core", @@ -2442,7 +2442,7 @@ dependencies = [ [[package]] name = "pool-core" -version = "1.0.0" +version = "1.1.0" dependencies = [ "borsh", "serde", @@ -2450,7 +2450,7 @@ dependencies = [ [[package]] name = "pool-demo" -version = "1.0.0" +version = "1.1.0" dependencies = [ "pool-core", "serde_json", @@ -2458,14 +2458,14 @@ dependencies = [ [[package]] name = "pool-executor" -version = "1.0.0" +version = "1.1.0" dependencies = [ "near-sdk", ] [[package]] name = "pool-sandbox" -version = "1.0.0" +version = "1.1.0" dependencies = [ "near-workspaces", "pool-core", diff --git a/Cargo.toml b/Cargo.toml index 0040a1e..01f0fd2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,7 +4,7 @@ default-members = ["crates/core", "crates/contract", "crates/executor", "crates/ resolver = "2" [workspace.package] -version = "1.0.0" +version = "1.1.0" edition = "2021" license = "MIT" repository = "https://github.com/difflabai/shared-pool-controls" diff --git a/README.md b/README.md index 5891122..e74d42b 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,7 @@ Agents submit an owner-defined recipe and exact integer quantity. The core checks caller authority, freshness, prerequisites, resource bounds and `V(after) <= V(before)`, then atomically reserves the commitment. The execution adapter accepts calls only from the lock. Unknown outcomes retain reservations. -**Status:** implemented prototype with Rust tests and NEAR sandbox integration tests. Not independently audited or deployed to a public network. [Formal verification](https://github.com/difflabai/formalver/pull/31) includes completed Lean model proofs and TLA+ checks; the overall effort is in progress, with Rust-core Kani verification pending and reported settlement/liveness findings unresolved in that PR. Credits, GPU jobs, physical delivery, and financial positions are synthetic. The risk coefficients are illustrative, not a production portfolio model. +**Status:** implemented prototype with Rust tests and NEAR sandbox integration tests. Not independently audited or deployed to a public network. This is v1.1.0. [Formal verification](https://github.com/difflabai/formalver/pull/31) of v1.0.0 includes completed Lean model proofs and TLA+ checks; Rust-core Kani verification is pending. v1.1.0 fixes the settlement/liveness and other findings that verification reported ([findings](docs/verification-findings.md), [changelog](CHANGELOG.md)). The fixes are tested but not formally re-verified. Credits, GPU jobs, physical delivery, and financial positions are synthetic. The risk coefficients are illustrative, not a production portfolio model. ## Hackathon review path @@ -60,7 +60,7 @@ The separate [`ui/live.html`](ui/live.html) is a static NEAR console: read any c python3 scripts/smoke.py # local HTTP demo; start server first ``` -`near-workspaces` downloads its sandbox binary on first use. Network access and a supported host are required. `artifacts/build.json` records source revision, dirty status, Rust version, Cargo.lock hash, and Wasm hashes. This is a local build manifest, not an independent reproducibility or deployment attestation. +`near-workspaces` downloads its sandbox binary on first use. Network access and a supported host are required. `build.sh` builds with `RUSTFLAGS="--cfg near"` and fails if a Wasm does not import `env.panic_utf8` (without the flag, failed calls carry no error name). It also fails if a Wasm imports a host function for an action other than a function call (deploy, keys, transfer, stake, accounts), or any import not on its reviewed list. `artifacts/build.json` records source revision, dirty status, Rust version, Rust flags, Cargo.lock hash, and each Wasm's hash and imports. This is a local build manifest, not an independent reproducibility or deployment attestation. ## Small architecture @@ -74,18 +74,19 @@ python3 scripts/smoke.py # local HTTP demo; start server first | [`ui`](ui) | Static scenario lab and live NEAR console | | [`scenarios`](scenarios) | Generated configurations and reproducible decision traces | -One pool per deployment; immutable recipes, principals and policy. At most 32 metrics, 32 recipes, 64 potential terms and 256 lifetime commitments. Fixed limits bound computation and storage. The 257th commitment is rejected; rotate to a new deployment rather than pruning replay protection. The owner funds storage. This favors inspection and verification over indefinite production operation. +One pool per deployment; immutable recipes, principals and policy. At most 32 metrics, 32 recipes and 64 potential terms. The pool keeps a window of the 256 most recent commitments. A new commitment prunes the oldest one if it is completed or cancelled; while the oldest is still open, submit fails `Full`, even if every other commitment has ended. The actor or owner can cancel the oldest while it is reserved; once dispatched, it closes only when its executor reports. So an executor that never reports can hold submit at `Full`. The synthetic executor forgets a job once the newest id the lock vouched for (by an `execute` that created a job, or by accepting a confirmation or `finish`) is 256 or more past its id; the lock has pruned that record by then. Honest use holds at most 256 jobs plus confirmations in flight, under a cap of 512. Confirmations the lock refuses (operator errors) keep their jobs, a typo of a far id for good; at least 256 of them above its newest id (more if fewer jobs sit at or below it) fill the cap and stop further confirmations, and if executions then keep failing that can hold submit at `Full` the same way ([API](docs/api.md#executor-protocol)). Ids keep counting, and a pruned id is `NotFound`; the event log keeps pruned records. Replay protection is the version, not retention. Prerequisites count completed units over the pool's whole life. Fixed limits bound computation and storage. The owner funds storage. The window replaces v1.0.0's 256 lifetime commitments (finding F-3); it is tested, not formally verified. -Read the [API](docs/api.md), [state-machine specification](docs/spec.md), [updated implementation plan](docs/implementation-plan.md), and [verification handoff](docs/verification-handoff.md). +Read the [API](docs/api.md), [state-machine specification](docs/spec.md), [updated implementation plan](docs/implementation-plan.md), [verification handoff](docs/verification-handoff.md), [verification findings](docs/verification-findings.md), and [changelog](CHANGELOG.md). ## Important boundaries - Hard bounds and the potential are different checks. A lower score cannot buy permission to breach a protected limit. - Pending commitments count immediately. Pending negative-risk hedge effects do not provide headroom before fill. +- No unexecuted position backs a hedge: a hedge must stay in bounds if the position is later reported unexecuted. - Cancellation after dispatch needs authenticated evidence of nonexecution. A timeout or failed receipt is insufficient. -- The administrator and registered execution/evidence accounts are trusted. The owner can update observed facts only when there are no unresolved commitments; it cannot edit policy. That observation can raise energy or reveal a limit breach. +- The administrator and registered execution/evidence accounts are trusted. The owner can update observed facts only when there are no unresolved commitments, and can restate the current values at any time to renew the snapshot; it cannot edit policy. That observation can raise energy or reveal a limit breach. - Only admitted reservation transitions promise nonincreasing energy. Settlement, cancellation, observations, fairness, economic correctness and eventual completion have separate assumptions. - The adapter boundary is real in the sandbox. Real brokers, cloud providers or warehouses would need enforceable integrations with no alternate credentials/path around the gate. - The prototype uses no real escrow token. Hiring credits are accounting fixtures, not NEAR balances. -The architecture follows [`difflabai/trust-framework`](https://github.com/difflabai/trust-framework/tree/249f932d84b91fbc6f82abd0668cac6c0503fc42/contracts/approval): a pure core and thin wrapper. Its proofs do **not** apply to this code. Dedicated [shared-pool formal verification](https://github.com/difflabai/formalver/pull/31) targets the contract source pinned at `a4bb5c3`: Lean proofs cover the model transcription, TLA+ checks a bounded model, and conformance traces connect the models to the Rust core. Kani verification and refinement work remain pending. The PR reports high-severity settlement/liveness findings F-1 and F-2; consult its current status and findings before deploying. Changes to the contract or policy require review against the proof assumptions. +The architecture follows [`difflabai/trust-framework`](https://github.com/difflabai/trust-framework/tree/249f932d84b91fbc6f82abd0668cac6c0503fc42/contracts/approval): a pure core and thin wrapper. Its proofs do **not** apply to this code. Dedicated [shared-pool formal verification](https://github.com/difflabai/formalver/pull/31) targets v1.0.0, with the contract source pinned at `a4bb5c3`: Lean proofs cover the model transcription, TLA+ checks a bounded model, and conformance traces connect the models to the Rust core. Kani verification and refinement work remain pending. It reported high-severity settlement/liveness findings F-1 and F-2 (with F-2b), and lower-severity findings F-3 to F-6 and NT-F1 to NT-F4. v1.1.0 fixes all of them, F-4 only for a recipe whose actor is its executor (by the repository owner's decision, the owner may be a recipe's executor); see [docs/verification-findings.md](docs/verification-findings.md). Those formal results apply to v1.0.0. v1.1.0 changes admission, record retention and the version limit, and has not been re-verified. Changes to the contract or policy require review against the proof assumptions. diff --git a/SECURITY.md b/SECURITY.md index 528d4d9..adf15f7 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -4,7 +4,7 @@ This is an unaudited, not-formally-verified prototype. Do not treat synthetic cr Trust assumptions: immutable configuration is honestly designed; registered executor/operator truthfully reports execution; the owner truthfully reports observed values; NEAR runtime/SDK behavior is correct; the deployment account's upgrade authority is controlled. The lock cannot stop external actions using bypass credentials. -Attack surfaces intentionally limited: no agent-provided deltas, no arbitrary external method or account, no dynamic policy code, no unbounded logs in state, no frontend keys, no automatic timeout releases. Limits are fixed and terminal records retained to preserve ID replay protection. +Attack surfaces intentionally limited: no agent-provided deltas, no arbitrary external method or account, no dynamic policy code, no unbounded logs in state, no frontend keys, no automatic timeout releases. Limits are fixed. The pool keeps its 256 most recent records and prunes the oldest only once it is completed or cancelled. Ids keep counting, so a pruned id is never reused. Replay protection comes from the request's version, not from retaining records. The local Rust server is a **simulator**: identities are selectable and independent-provider evidence is a button. It binds to 127.0.0.1, validates Host/Origin, requires JSON POST for API access, uses an allowlist for static files and caps requests. Do not reverse-proxy it publicly or use it as an authenticated production gateway. diff --git a/crates/contract/src/lib.rs b/crates/contract/src/lib.rs index ae660aa..6e83c05 100644 --- a/crates/contract/src/lib.rs +++ b/crates/contract/src/lib.rs @@ -1,5 +1,5 @@ //! Thin NEAR shell: identity, storage, receipts, and asynchronous execution. -use near_sdk::{env, near, AccountId, Gas, PanicOnDefault, Promise, PromiseError}; +use near_sdk::{env, near, require, AccountId, Gas, NearToken, PanicOnDefault}; use pool_core::{Commitment, Config, Decision, Pool, Request}; #[near(contract_state)] @@ -51,11 +51,14 @@ impl Contract { pub fn get_pool(&self) -> Pool { self.pool.clone() } + /// Up to `limit` (at most 50) retained records, from id `from` on. Ids + /// below `get_pool().first_id` were pruned; a page starting there begins + /// at the oldest retained record. pub fn get_commitments(&self, from: u32, limit: u32) -> Vec { self.pool .records .iter() - .skip(from as usize) + .skip(from.saturating_sub(self.pool.first_id) as usize) .take(limit.min(50) as usize) .cloned() .collect() @@ -76,26 +79,24 @@ impl Contract { ); Submission { decision, id } } - pub fn dispatch(&mut self, id: u32) -> Promise { + pub fn dispatch(&mut self, id: u32) { must(self.pool.dispatch(&caller(), id, now())); - let c = &self.pool.records[id as usize]; + let c = must(self.pool.record(id)); let r = &self.pool.config.recipes[c.recipe as usize]; let args = near_sdk::serde_json::to_vec( &near_sdk::serde_json::json!({"id":id,"recipe":c.recipe,"units":c.units}), ) .unwrap(); - Promise::new(r.executor.parse().unwrap()) - .function_call( - "execute", - args, - near_sdk::NearToken::from_yoctonear(0), - Gas::from_tgas(30), - ) - .then(self.callback(id)) + call_then_callback(&r.executor, "execute", &args, Gas::from_tgas(30), id); } /// Any observer may request reconciliation; no authority is granted by this call. - pub fn reconcile(&self, id: u32) -> Promise { - let c = self.pool.records.get(id as usize).expect("NotFound"); + pub fn reconcile(&self, id: u32) { + // NT-F2: near-sdk generates the nonpayable check only for &mut self methods. + require!( + env::attached_deposit().is_zero(), + "Method reconcile doesn't accept deposit" + ); + let c = must(self.pool.record(id)); assert!( matches!( c.status, @@ -106,24 +107,30 @@ impl Contract { "InvalidState" ); let r = &self.pool.config.recipes[c.recipe as usize]; - Promise::new(r.executor.parse().unwrap()) - .function_call( - "status", - near_sdk::serde_json::to_vec(&near_sdk::serde_json::json!({"id":id})).unwrap(), - near_sdk::NearToken::from_yoctonear(0), - Gas::from_tgas(10), - ) - .then(self.callback(id)) + let args = near_sdk::serde_json::to_vec(&near_sdk::serde_json::json!({"id":id})).unwrap(); + call_then_callback(&r.executor, "status", &args, Gas::from_tgas(10), id); } #[private] - pub fn on_result(&mut self, id: u32, #[callback_result] result: Result) { - let executor = self - .pool - .records - .get(id as usize) - .map(|c| self.pool.config.recipes[c.recipe as usize].executor.clone()) - .expect("NotFound"); - let status = result.unwrap_or_else(|_| "unknown".into()); + pub fn on_result(&mut self, id: u32) { + // NT-F4: read the raw result. A failed call, a missing result, more than + // 64 bytes, or anything but one JSON string is "unknown". No promise result + // and no id makes this callback panic. + let status = if env::promise_results_count() == 1 { + env::promise_result_checked(0, 64) + .ok() + .and_then(|b| near_sdk::serde_json::from_slice::(&b).ok()) + } else { + None + } + .unwrap_or_else(|| "unknown".into()); + let Ok(c) = self.pool.record(id) else { + // No such record: nothing to update, so log the result and return. + return event( + "reconciled", + near_sdk::serde_json::json!({"id":id,"outcome":status,"error":"NotFound"}), + ); + }; + let executor = self.pool.config.recipes[c.recipe as usize].executor.clone(); let update = match status.as_str() { "completed" => self.pool.settle(&executor, id, true), "cancelled" => self.pool.settle(&executor, id, false), @@ -159,20 +166,32 @@ impl Contract { ); } } -impl Contract { - fn callback(&self, id: u32) -> Promise { - Promise::new(env::current_account_id()).function_call( - "on_result", - near_sdk::serde_json::to_vec(&near_sdk::serde_json::json!({"id":id})).unwrap(), - near_sdk::NearToken::from_yoctonear(0), - Gas::from_tgas(30), - ) - } +/// Calls `method` on the executor with no deposit, then this contract's +/// `on_result({id})` with 30 Tgas, and makes the callback's result the result +/// of the current call. NT-F3: this uses near-sdk's low-level promise functions. +/// Its `Promise` type links the host functions for every action (deploy, keys, +/// transfer, stake, accounts); build.sh fails if any of them is imported. +fn call_then_callback(executor: &str, method: &str, args: &[u8], gas: Gas, id: u32) { + let zero = NearToken::from_yoctonear(0); + let call = env::promise_create(executor.parse().unwrap(), method, args, zero, gas); + let callback = env::promise_then( + call, + env::current_account_id(), + "on_result", + near_sdk::serde_json::to_vec(&near_sdk::serde_json::json!({"id":id})).unwrap(), + zero, + Gas::from_tgas(30), + ); + env::promise_return(callback); } #[cfg(test)] mod tests { use super::*; - use near_sdk::{test_utils::VMContextBuilder, testing_env}; + use near_sdk::mock::MockAction; + use near_sdk::serde_json::{json, Value}; + use near_sdk::test_utils::{get_created_receipts, get_logs, VMContextBuilder}; + use near_sdk::{testing_env, NearToken, PromiseResult}; + use pool_core::Status; fn context(actor: &str) { let mut b = VMContextBuilder::new(); b.current_account_id("pool.test.near".parse().unwrap()) @@ -198,4 +217,236 @@ mod tests { assert_eq!(c.get_pool().values[3], 4); assert_eq!(c.get_commitments(0, 100).len(), 1); } + /// The pool calling its own callback, with these promise results. + fn callback_context(results: Vec) { + let mut b = VMContextBuilder::new(); + b.current_account_id("pool.test.near".parse().unwrap()) + .predecessor_account_id("pool.test.near".parse().unwrap()) + .block_timestamp(100_000_000_000); + testing_env!( + b.build(), + near_sdk::test_vm_config(), + near_sdk::RuntimeFeesConfig::test(), + Default::default(), + results + ); + } + /// The gpu pool with record 0 (recipe 0, 4 units) Dispatched. + fn dispatched() -> Contract { + context("pool.test.near"); + let mut c = Contract::new(pool_core::fixtures::config("gpu").unwrap()); + context("research.test.near"); + let q = Request { + recipe: 0, + units: 4, + version: 0, + expires_at: 200, + }; + assert_eq!(c.submit(q).id, Some(0)); + c.dispatch(0); + assert_eq!(c.get_pool().records[0].status, Status::Dispatched); + c + } + /// The single event logged by the last call. + fn last_event() -> near_sdk::serde_json::Value { + let logs = get_logs(); + assert_eq!(logs.len(), 1, "{logs:?}"); + near_sdk::serde_json::from_str(logs[0].strip_prefix("EVENT_JSON:").unwrap()).unwrap() + } + /// A function call: (method, JSON args, deposit in yocto, gas in Tgas, unused-gas weight). + type Call = (String, Value, u128, u64, u64); + /// Every receipt created by the last call: (receiver, receipts it waits for, calls). + fn receipts() -> Vec<(String, Vec, Vec)> { + get_created_receipts() + .into_iter() + .map(|r| { + let calls = r.actions.into_iter().map(|a| match a { + MockAction::FunctionCallWeight { + method_name, + args, + attached_deposit, + prepaid_gas, + gas_weight, + .. + } => ( + String::from_utf8(method_name).unwrap(), + near_sdk::serde_json::from_slice(&args).unwrap(), + attached_deposit.as_yoctonear(), + prepaid_gas.as_tgas(), + gas_weight.0, + ), + other => panic!("not a function call: {other:?}"), + }); + ( + r.receiver_id.to_string(), + r.receipt_indices, + calls.collect(), + ) + }) + .collect() + } + #[test] + fn dispatch_and_reconcile_call_the_executor_then_on_result() { + let call = |method: &str, args: Value, tgas: u64| (method.to_string(), args, 0, tgas, 0); + let on_result = ( + "pool.test.near".to_string(), + vec![0], + vec![call("on_result", json!({"id":0}), 30)], + ); + let c = dispatched(); + let execute = call("execute", json!({"id":0,"recipe":0,"units":4}), 30); + assert_eq!( + receipts(), + vec![ + ("executor.test.near".into(), vec![], vec![execute]), + on_result.clone() + ] + ); + context("anyone.test.near"); + c.reconcile(0); + let status = call("status", json!({"id":0}), 10); + assert_eq!( + receipts(), + vec![ + ("executor.test.near".into(), vec![], vec![status]), + on_result + ] + ); + } + #[test] + #[should_panic(expected = "Method reconcile doesn't accept deposit")] + fn nt_f2_reconcile_rejects_deposit() { + let c = dispatched(); + let mut b = VMContextBuilder::new(); + b.current_account_id("pool.test.near".parse().unwrap()) + .predecessor_account_id("anyone.test.near".parse().unwrap()) + .attached_deposit(NearToken::from_yoctonear(1)); + testing_env!(b.build()); + c.reconcile(0); + } + #[test] + fn reconcile_without_deposit_is_open_to_anyone() { + let c = dispatched(); + context("anyone.test.near"); + c.reconcile(0); + } + #[test] + fn nt_f4_non_string_result_becomes_unknown() { + use Status::{Active, Cancelled, Completed, Unknown}; + let ok = |b: &[u8]| vec![PromiseResult::Successful(b.to_vec())]; + // "completed" as a JSON string padded with trailing whitespace to n bytes. + let padded = |n: usize| { + let mut s = b"\"completed\"".to_vec(); + s.resize(n, b' '); + s + }; + let long = format!("\"{}\"", "a".repeat(10_000)); + // (case, promise results, record status afterwards, logged outcome) + let cases: Vec<(&str, Vec, Status, &str)> = vec![ + ("number", ok(b"5"), Unknown, "unknown"), + ("object", ok(br#"{"status":"active"}"#), Unknown, "unknown"), + ("array", ok(br#"["active"]"#), Unknown, "unknown"), + ("null", ok(b"null"), Unknown, "unknown"), + ("empty", ok(b""), Unknown, "unknown"), + ("unquoted", ok(b"completed"), Unknown, "unknown"), + ("invalid UTF-8", ok(b"\"\xff\xfe\""), Unknown, "unknown"), + ("10 kB string", ok(long.as_bytes()), Unknown, "unknown"), + ("65 bytes", ok(&padded(65)), Unknown, "unknown"), + ("failed", vec![PromiseResult::Failed], Unknown, "unknown"), + ("no result", vec![], Unknown, "unknown"), + ( + "two results", + vec![ + PromiseResult::Successful(b"\"active\"".to_vec()), + PromiseResult::Successful(b"\"active\"".to_vec()), + ], + Unknown, + "unknown", + ), + ("other string", ok(b"\"bogus\""), Unknown, "bogus"), + ("active", ok(b"\"active\""), Active, "active"), + ("64 bytes", ok(&padded(64)), Completed, "completed"), + ("cancelled", ok(b"\"cancelled\""), Cancelled, "cancelled"), + ]; + for (name, results, status, outcome) in cases { + let mut c = dispatched(); + callback_context(results); + c.on_result(0); + let p = c.get_pool(); + assert_eq!(p.records[0].status, status, "{name}"); + // Only a definitive cancellation releases the 4 reserved units. + let held = if status == Cancelled { 0 } else { 4 }; + assert_eq!(p.values[3], held, "{name}"); + let e = last_event(); + assert_eq!(e["event"], "reconciled", "{name}"); + assert_eq!(e["data"][0]["outcome"], outcome, "{name}"); + assert!(e["data"][0]["error"].is_null(), "{name}"); + } + } + /// The gpu pool after 257 submit and cancel cycles: record 0 is pruned, + /// records 1-256 are retained and Cancelled. + fn pruned() -> Contract { + context("pool.test.near"); + let mut c = Contract::new(pool_core::fixtures::config("gpu").unwrap()); + for id in 0..=pool_core::MAX_RECORDS as u32 { + context("research.test.near"); + let q = Request { + recipe: 0, + units: 1, + version: c.get_pool().version, + expires_at: 200, + }; + assert_eq!(c.submit(q).id, Some(id)); + c.cancel(id); + } + let p = c.get_pool(); + assert_eq!((p.first_id, p.records.len()), (1, pool_core::MAX_RECORDS)); + c + } + /// F-3: `get_commitments.from` is an id, and a result for a pruned id is + /// logged like any unknown id. + #[test] + fn f3_commitments_page_by_id_after_a_prune() { + let mut c = pruned(); + let ids = |from: u32, limit: u32| -> Vec { + c.get_commitments(from, limit) + .iter() + .map(|r| r.id) + .collect() + }; + assert_eq!(ids(0, 3), vec![1, 2, 3]); + assert_eq!(ids(1, 3), vec![1, 2, 3]); + assert_eq!(ids(255, 50), vec![255, 256]); + assert_eq!(ids(257, 5), Vec::::new()); + assert_eq!(ids(100, 100), (100..150).collect::>()); + let before = c.get_pool(); + callback_context(vec![PromiseResult::Successful(b"\"completed\"".to_vec())]); + c.on_result(0); + assert_eq!(c.get_pool(), before); + assert_eq!( + last_event()["data"][0], + json!({"id":0,"outcome":"completed","error":"NotFound"}) + ); + } + #[test] + #[should_panic(expected = "NotFound")] + fn f3_reconcile_of_a_pruned_id_is_not_found() { + let c = pruned(); + context("anyone.test.near"); + c.reconcile(0); + } + #[test] + fn nt_f4_result_for_unknown_id_is_logged() { + let mut c = dispatched(); + let before = c.get_pool(); + for id in [1, 7, u32::MAX] { + callback_context(vec![PromiseResult::Successful(b"\"completed\"".to_vec())]); + c.on_result(id); + assert_eq!(c.get_pool(), before); + assert_eq!( + last_event()["data"][0], + near_sdk::serde_json::json!({"id":id,"outcome":"completed","error":"NotFound"}) + ); + } + } } diff --git a/crates/core/src/findings.rs b/crates/core/src/findings.rs new file mode 100644 index 0000000..0d81a08 --- /dev/null +++ b/crates/core/src/findings.rs @@ -0,0 +1,1022 @@ +//! Regression tests for the v1.0.0 findings in docs/verification-findings.md. +//! +//! Each v1.1 fix rewrites its reproducer into a test of the fixed +//! behaviour. A reproducer whose fix has not landed yet still pins v1.0.0, +//! including the faulty result, so the fix commit has to change it. +use super::*; + +const OWNER: &str = "owner.test.near"; +const EXEC: &str = "executor.test.near"; +const EXPIRES: u64 = 1_000; + +fn pool(name: &str) -> Pool { + Pool::new(fixtures::config(name).unwrap(), 100).unwrap() +} +fn actor(p: &Pool, recipe: u32) -> String { + p.config.recipes[recipe as usize].actor.clone() +} +fn req(p: &Pool, recipe: u32, units: u32) -> Request { + Request { + recipe, + units, + version: p.version, + expires_at: EXPIRES, + } +} +fn submit(p: &mut Pool, recipe: u32, units: u32, now: u64) -> Result { + let a = actor(p, recipe); + let q = req(p, recipe, units); + p.submit(&a, q, now) +} +/// Reserved -> Dispatched -> Active, as the actor's dispatch and an "active" callback. +fn dispatch_active(p: &mut Pool, id: u32, now: u64) { + let a = actor(p, p.record(id).unwrap().recipe); + p.dispatch(&a, id, now).unwrap(); + p.acknowledge(id, true).unwrap(); +} +fn metric(min: i64, max: i64, initial: i64) -> Metric { + Metric { + name: "m".into(), + unit: "u".into(), + initial, + min, + max, + } +} +fn recipe(actor: &str, reserve: Vec, complete: Vec, max_units: u32) -> Recipe { + Recipe { + name: "r".into(), + actor: actor.into(), + executor: EXEC.into(), + reserve, + complete, + max_units, + requires: vec![], + } +} +fn config(metrics: Vec, recipes: Vec) -> Config { + Config { + name: "finding".into(), + owner: OWNER.into(), + metrics, + terms: vec![Term { + metric: 1, + target: 0, + weight: 1, + shape: Shape::Target, + }], + recipes, + max_age_seconds: 0, + } +} + +/// LIVE: every open record can be resolved. On a clone, a Reserved record +/// is cancelled by its actor and by the owner, and a Dispatched, Active or +/// Unknown record is settled both ways by its executor. Every one of these +/// exits must be Ok and must not raise any metric's violation. +fn assert_live(p: &Pool) { + let before = p.violations(&p.values); + for c in p.records.iter().filter(|c| open(&c.status)) { + let r = &p.config.recipes[c.recipe as usize]; + let mut tries = [p.clone(), p.clone()]; + let (names, results) = if c.status == Status::Reserved { + ( + ["cancel by actor", "cancel by owner"], + [ + tries[0].cancel(&r.actor, c.id, u64::MAX), + tries[1].cancel(&p.config.owner, c.id, u64::MAX), + ], + ) + } else { + ( + ["settle(true)", "settle(false)"], + [ + tries[0].settle(&r.executor, c.id, true), + tries[1].settle(&r.executor, c.id, false), + ], + ) + }; + for ((q, result), name) in tries.iter().zip(results).zip(names) { + assert_eq!( + result, + Ok(()), + "record {} ({:?}): {name} fails in {p:?}", + c.id, + c.status + ); + let after = q.violations(&q.values); + assert!( + after.iter().zip(&before).all(|(a, b)| a <= b), + "record {}: {name} raises a violation in {p:?}", + c.id + ); + } + } +} + +/// INV-RES: per metric, the interval spanned by every outcome of every open +/// record (stay open, complete, release) stays in the value range and has +/// the same violation as the values. Computed here independently of +/// Pool::envelope. +fn assert_inv_res(p: &Pool) { + let mut low = p.values.clone(); + let mut high = p.values.clone(); + for c in p.records.iter().filter(|c| open(&c.status)) { + let r = &p.config.recipes[c.recipe as usize]; + let u = i64::from(c.units); + for i in 0..p.values.len() { + let (d, x) = (r.complete[i] * u, -r.reserve[i] * u); + low[i] += d.min(x).min(0); + high[i] += d.max(x).max(0); + } + } + let point = p.violations(&p.values); + for (i, m) in p.config.metrics.iter().enumerate() { + assert!( + bounded(low[i]) && bounded(high[i]), + "metric {i} interval leaves the value range in {p:?}" + ); + let interval = (m.min - low[i]).max(0) as u64 + (high[i] - m.max).max(0) as u64; + assert_eq!(interval, point[i], "INV-RES fails for metric {i} in {p:?}"); + } +} + +/// F-1 (high), fixed: an observe puts metric 0 at 12 (max 10). v1.0.0 +/// admitted a hedge that reserves -2 and completes +2 on metric 0, and the +/// record could then never become terminal. Releasing it would put metric 0 +/// back to 12, above the 10 its reservation reached, so v1.1 refuses it. +/// formalver trace 0. +#[test] +fn f1_hedge_that_cures_by_reservation_is_refused() { + const HEDGER: &str = "hedger.test.near"; + let c = config( + vec![metric(0, 10, 5), metric(-100, 100, 5)], + vec![recipe(HEDGER, vec![-2, 0], vec![2, -5], 1)], + ); + let mut p = Pool::new(c, 100).unwrap(); + p.observe(OWNER, vec![12, 5], 100).unwrap(); + let before = p.clone(); + let q = req(&p, 0, 1); + let d = p.preview(HEDGER, &q, 100); + assert!(!d.allowed); + assert_eq!(d.reason, "Bounds"); + assert_eq!(p.best_quantity(HEDGER, &q, 100), None); + assert_eq!(p.submit(HEDGER, q, 100), Err(Error::Bounds)); + assert_eq!(p, before); + // Nothing is open, so the owner can still restate the measured values. + p.observe(OWNER, vec![5, 5], 103).unwrap(); +} + +/// F-1, the shape that stays allowed: in the same disturbed state, a hedge +/// that reserves only collateral (metric 1) and cures metric 0 when it +/// completes is admitted, and every exit stays open. The same holds for the +/// risk fixture's selloff hedge at selloff loss 110 (max 100). +#[test] +fn f1_recovery_by_completion_is_admitted_and_live() { + const HEDGER: &str = "hedger.test.near"; + let c = config( + vec![metric(0, 10, 5), metric(-100, 100, 5)], + vec![recipe(HEDGER, vec![0, -1], vec![-3, 0], 1)], + ); + let mut p = Pool::new(c, 100).unwrap(); + p.observe(OWNER, vec![12, 5], 100).unwrap(); + let id = submit(&mut p, 0, 1, 100).unwrap(); + assert_eq!(p.values, vec![12, 4]); + assert_live(&p); + dispatch_active(&mut p, id, 100); + assert_live(&p); + p.settle(EXEC, id, true).unwrap(); + assert_eq!(p.values, vec![9, 4]); + + let mut r = pool("risk"); + r.observe(OWNER, vec![110, 40, 30, 40], 100).unwrap(); + let hedge = submit(&mut r, 3, 2, 100).unwrap(); + assert_eq!(r.values, vec![110, 40, 30, 36]); + assert_live(&r); + dispatch_active(&mut r, hedge, 100); + assert_live(&r); + r.settle(EXEC, hedge, true).unwrap(); + assert_eq!(r.values[0], 90); +} + +/// F-2 (high), fixed: the risk fixture, healthy. v1.0.0 admitted a hedge +/// of 8 units only because a credit position's +20 selloff loss was +/// counted; after the hedge completed, the position's honest settle(false) +/// failed. v1.1 sizes the hedge as if the position were released: 8 and 7 +/// units are refused and best_quantity suggests 6. Once the position has +/// executed, it does back 8 units. formalver trace 209. +#[test] +fn f2_hedge_cannot_rely_on_an_unexecuted_position() { + let mut p = pool("risk"); + let position = submit(&mut p, 0, 1, 100).unwrap(); + let before = p.clone(); + assert_eq!(submit(&mut p, 3, 8, 100), Err(Error::Bounds)); + assert_eq!(submit(&mut p, 3, 7, 100), Err(Error::Bounds)); + assert_eq!(p, before); + let best = p.best_quantity("macro.test.near", &req(&p, 3, 8), 100); + assert_eq!(best.map(|q| q.units), Some(6)); + let hedge = submit(&mut p, 3, 6, 100).unwrap(); + assert_live(&p); + dispatch_active(&mut p, position, 100); + dispatch_active(&mut p, hedge, 100); + p.settle(EXEC, hedge, true).unwrap(); + assert_eq!(p.values[0], 20); + assert_live(&p); + p.settle(EXEC, position, false).unwrap(); + assert_eq!(p.values[0], 0); + p.observe(OWNER, vec![60, 40, 30, 40], 102).unwrap(); + + let mut q = pool("risk"); + let done = submit(&mut q, 0, 1, 100).unwrap(); + dispatch_active(&mut q, done, 100); + q.settle(EXEC, done, true).unwrap(); + submit(&mut q, 3, 8, 100).unwrap(); + assert_live(&q); +} + +/// F-2, Reserved form, fixed: the position is never dispatched and the +/// hedge completes. The actor and the owner can cancel the position, also +/// at now = 1000, when its request has expired and the snapshot is stale. +#[test] +fn f2_reserved_position_can_always_be_cancelled() { + let mut p = pool("risk"); + let position = submit(&mut p, 0, 1, 100).unwrap(); + assert_eq!(submit(&mut p, 3, 7, 100), Err(Error::Bounds)); + let hedge = submit(&mut p, 3, 6, 100).unwrap(); + dispatch_active(&mut p, hedge, 100); + p.settle(EXEC, hedge, true).unwrap(); + assert_eq!(p.values, vec![20, 45, 30, 23]); + assert_live(&p); + p.clone().cancel(OWNER, position, 101).unwrap(); + p.clone().cancel(OWNER, position, EXPIRES).unwrap(); + p.cancel("credit.test.near", position, EXPIRES).unwrap(); + assert_eq!(p.values, vec![0, 40, 30, 28]); + assert_eq!(p.records[position as usize].status, Status::Cancelled); + p.observe(OWNER, vec![60, 40, 30, 40], EXPIRES).unwrap(); +} + +/// F-2b, fixed: in v1.0.0 record b's completion relied on record a's +/// reservation of -1,000,000, so undoing a left the value range and failed +/// Arithmetic. v1.1 counts a's release in b's interval: b x100 and x67 fail +/// Arithmetic at admission, x66 is admitted, and after b completes a can be +/// cancelled or settled false. formalver trace 208. +#[test] +fn f2b_release_stays_in_the_value_range() { + const A: &str = "agent.test.near"; + let c = config( + vec![metric(-MAX_VALUE, MAX_VALUE, 0), metric(-10, 10, 0)], + vec![ + recipe(A, vec![-MAX_VALUE, 0], vec![0, 0], 1), + recipe(A, vec![0, 0], vec![15_000, 0], 100), + ], + ); + let mut p = Pool::new(c, 100).unwrap(); + let a = submit(&mut p, 0, 1, 100).unwrap(); + let before = p.clone(); + assert_eq!(submit(&mut p, 1, 100, 100), Err(Error::Arithmetic)); + assert_eq!(submit(&mut p, 1, 67, 100), Err(Error::Arithmetic)); + assert_eq!(p, before); + let best = p.best_quantity(A, &req(&p, 1, 100), 100); + assert_eq!(best.map(|q| q.units), Some(66)); + let b = submit(&mut p, 1, 66, 100).unwrap(); + assert_live(&p); + dispatch_active(&mut p, b, 100); + p.settle(EXEC, b, true).unwrap(); + assert_eq!(p.values[0], -10_000); + assert_live(&p); + let mut flight = p.clone(); + dispatch_active(&mut flight, a, 101); + flight.settle(EXEC, a, false).unwrap(); + assert_eq!(flight.values[0], 990_000); + p.clone().cancel(OWNER, a, 101).unwrap(); + p.cancel(A, a, 101).unwrap(); + assert_eq!(p.values[0], 990_000); +} + +/// xorshift64, so the random test needs no dependency. +struct Rng(u64); +impl Rng { + fn next(&mut self) -> u64 { + self.0 ^= self.0 << 13; + self.0 ^= self.0 >> 7; + self.0 ^= self.0 << 17; + self.0 + } + /// Uniform enough in [lo, hi]. + fn range(&mut self, lo: i64, hi: i64) -> i64 { + lo + (self.next() % (hi - lo + 1) as u64) as i64 + } + fn coin(&mut self) -> bool { + self.next() & 1 == 0 + } +} +/// Half of the effects are zero, the rest in [-3, 3]. +fn effect(g: &mut Rng) -> i64 { + if g.coin() { + 0 + } else { + g.range(-3, 3) + } +} +/// Small random configuration: 1-3 metrics with narrow bounds, 1-2 terms, +/// 1-3 recipes with small effects, two actors, two executors. +fn random_config(g: &mut Rng) -> Config { + let n = g.range(1, 3) as usize; + let metrics = (0..n) + .map(|_| { + let min = g.range(-6, 2); + let max = min + g.range(2, 12); + metric(min, max, g.range(min, max)) + }) + .collect(); + let shapes = [Shape::Target, Shape::Excess, Shape::Deficit]; + let terms = (0..g.range(1, 2)) + .map(|_| Term { + metric: g.range(0, n as i64 - 1) as u32, + target: g.range(-4, 6), + weight: g.range(1, 3) as u32, + shape: shapes[g.range(0, 2) as usize].clone(), + }) + .collect(); + let recipes = (0..g.range(1, 3)) + .map(|i| Recipe { + name: "r".into(), + actor: ["a1.test.near", "a2.test.near"][g.range(0, 1) as usize].into(), + executor: ["x1.test.near", "x2.test.near"][g.range(0, 1) as usize].into(), + reserve: (0..n).map(|_| effect(g)).collect(), + complete: (0..n).map(|_| effect(g)).collect(), + max_units: g.range(1, 3) as u32, + requires: if i > 0 && g.range(0, 4) == 0 { + vec![(0, 1)] + } else { + vec![] + }, + }) + .collect(); + Config { + name: "random".into(), + owner: OWNER.into(), + metrics, + terms, + recipes, + max_age_seconds: if g.range(0, 3) == 0 { 50 } else { 0 }, + } +} + +/// Measured values up to 3 outside each metric's bounds. +fn observed(g: &mut Rng, p: &Pool) -> Vec { + let m = &p.config.metrics; + m.iter().map(|m| g.range(m.min - 3, m.max + 3)).collect() +} +/// LIVE on random runs: 300 seeded random configurations, 60 random calls +/// each, including observes that put metrics out of bounds. After every +/// call: a rejected call leaves the pool unchanged; preview agrees with +/// submit; an admission leaves every metric's violation unchanged and no +/// other call but observe raises one (HARD-STEP); an observe with a record +/// open changes no value or record; INV-RES holds; and every open record +/// can be resolved (assert_live). +#[test] +fn live_all_on_random_runs() { + let (mut admitted, mut admitted_disturbed, mut exits, mut exits_disturbed) = (0, 0, 0, 0); + let mut refreshes = 0; + for seed in 1..=300u64 { + let mut g = Rng(seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1); + let mut p = Pool::new(random_config(&mut g), 100).unwrap(); + let mut ghost = vec![]; + let mut now = 100u64; + // Half of the runs start from an observed, often disturbed, state. + if g.coin() { + let values = observed(&mut g, &p); + p.observe(OWNER, values, now).unwrap(); + } + for _ in 0..60 { + if g.range(0, 9) == 0 { + now += g.range(1, 30) as u64; + } + let before = p.clone(); + let violated = p.violations(&p.values).iter().any(|v| *v > 0); + let next = i64::from(p.first_id) + p.records.len() as i64; + let id = g.range((next - 6).max(0), next) as u32; + let known = p.record(id).ok().map(|c| { + let r = &p.config.recipes[c.recipe as usize]; + (r.actor.clone(), r.executor.clone()) + }); + let (actor, executor) = known.unwrap_or(("a1.test.near".into(), "x1.test.near".into())); + let k = g.range(0, 99); + let (result, is_submit, is_observe) = if k < 30 { + let recipe = g.range(0, p.config.recipes.len() as i64 - 1) as u32; + let r = &p.config.recipes[recipe as usize]; + let a = r.actor.clone(); + // Mostly a valid quantity; one call in eight asks for one too many. + let most = i64::from(r.max_units) + i64::from(g.range(0, 7) == 0); + let q = Request { + recipe, + units: g.range(1, most) as u32, + version: p.version, + expires_at: now + 100, + }; + let allowed = p.preview(&a, &q, now).allowed; + let result = p.submit(&a, q, now).map(|_| ()); + assert_eq!(allowed, result.is_ok(), "preview disagrees with submit"); + (result, true, false) + } else if k < 48 { + (p.dispatch(&actor, id, now), false, false) + } else if k < 60 { + (p.acknowledge(id, g.coin()), false, false) + } else if k < 78 { + (p.settle(&executor, id, g.coin()), false, false) + } else if k < 88 { + let who = if g.coin() { OWNER.to_string() } else { actor }; + (p.cancel(&who, id, now), false, false) + } else if k < 96 { + let values = if g.range(0, 2) == 0 { + p.values.clone() + } else { + observed(&mut g, &p) + }; + (p.observe(OWNER, values, now), false, true) + } else { + // Paused about a quarter of the time. + (p.set_paused(OWNER, g.range(0, 3) == 0), false, false) + }; + if result.is_err() { + assert_eq!(p, before, "a rejected call changed the pool"); + } else if is_observe { + // With a record open, only a restatement of the values passes. + if before.records.iter().any(|c| open(&c.status)) { + assert_eq!((&p.values, &p.records), (&before.values, &before.records)); + refreshes += 1; + } + } else { + let (old, new) = (before.violations(&before.values), p.violations(&p.values)); + if is_submit { + assert_eq!(new, old, "an admission changed a violation"); + admitted += 1; + admitted_disturbed += usize::from(violated); + } else { + assert!(new.iter().zip(&old).all(|(a, b)| a <= b), "HARD-STEP"); + let closed = before + .records + .iter() + .zip(&p.records) + .any(|(a, b)| open(&a.status) && !open(&b.status)); + exits += usize::from(closed); + exits_disturbed += usize::from(closed && violated); + } + } + record_history(&mut ghost, &p); + assert_window(&p, &ghost); + assert_inv_res(&p); + assert_live(&p); + } + } + // The run is not vacuous: it admits and resolves records, also in + // states where some metric is out of bounds. + println!("admitted {admitted} ({admitted_disturbed} disturbed), exits {exits} ({exits_disturbed} disturbed), refreshes with records open {refreshes}"); + assert!(admitted > 500 && admitted_disturbed > 30); + assert!(exits > 200 && exits_disturbed > 20); + assert!(refreshes > 20); +} + +/// WIN: `records` is a window of at most MAX_RECORDS records with +/// consecutive ids from `first_id`, and `completed_units` is the per-recipe +/// sum of Completed units in `ghost`, a full history of every record that +/// was ever submitted (pruned ones included). Every id below `first_id` is +/// NotFound, and its record in `ghost` was terminal. +fn assert_window(p: &Pool, ghost: &[Commitment]) { + assert!(p.records.len() <= MAX_RECORDS); + for (k, c) in p.records.iter().enumerate() { + assert_eq!(c.id, p.first_id + k as u32, "ids are not affine in {p:?}"); + } + assert_eq!(ghost.len(), p.first_id as usize + p.records.len()); + assert_eq!(&ghost[p.first_id as usize..], &p.records[..]); + for c in &ghost[..p.first_id as usize] { + assert!(!open(&c.status), "record {} was pruned while open", c.id); + assert_eq!(p.record(c.id), Err(Error::NotFound)); + } + let mut units = vec![0u32; p.config.recipes.len()]; + for c in ghost.iter().filter(|c| c.status == Status::Completed) { + units[c.recipe as usize] += c.units; + } + assert_eq!(p.completed_units, units); +} +/// The ghost history after a call: the records of `p`, appended to or +/// replacing the matching entries of `ghost`. +fn record_history(ghost: &mut Vec, p: &Pool) { + for c in &p.records { + match ghost.get_mut(c.id as usize) { + Some(g) => *g = c.clone(), + None => { + assert_eq!(c.id as usize, ghost.len(), "an id was skipped"); + ghost.push(c.clone()); + } + } + } +} + +/// F-3 (low), fixed: in v1.0.0 one actor could fill the 256 lifetime +/// records with submit and cancel, and every later submit, by any actor, +/// failed Full. v1.1 keeps a window of the 256 most recent records: a +/// submit drops the oldest record when it is terminal, ids keep counting, +/// and a pruned id is NotFound. Full remains only while the oldest retained +/// record is open, and closing that record frees the window. formalver +/// trace 207 (a smaller config). +#[test] +fn f3_window_frees_terminal_records_and_keeps_ids() { + let mut p = pool("gpu"); + let mut ghost = vec![]; + for _ in 0..MAX_RECORDS { + let id = submit(&mut p, 0, 1, 100).unwrap(); + p.cancel("research.test.near", id, 100).unwrap(); + record_history(&mut ghost, &p); + } + assert_eq!((p.records.len(), p.first_id), (MAX_RECORDS, 0)); + // Another actor's submit prunes record 0 and gets the next id. + let front = submit(&mut p, 2, 1, 100).unwrap(); + assert_eq!(front, 256); + record_history(&mut ghost, &p); + assert_eq!((p.records.len(), p.first_id), (MAX_RECORDS, 1)); + assert_eq!((p.records[0].id, p.records[255].id), (1, 256)); + assert_window(&p, &ghost); + let before = p.clone(); + assert_eq!(p.record(0), Err(Error::NotFound)); + assert_eq!(p.cancel(OWNER, 0, 100), Err(Error::NotFound)); + assert_eq!(p.settle(EXEC, 0, false), Err(Error::NotFound)); + assert_eq!( + p.dispatch("research.test.near", 0, 100), + Err(Error::NotFound) + ); + assert_eq!(p.acknowledge(0, true), Err(Error::NotFound)); + assert_eq!(p, before); + + // Record 256 stays Reserved while 255 more cycles prune records 1-255. + for _ in 0..MAX_RECORDS - 1 { + let id = submit(&mut p, 0, 1, 100).unwrap(); + p.cancel("research.test.near", id, 100).unwrap(); + record_history(&mut ghost, &p); + } + assert_window(&p, &ghost); + assert_eq!( + (p.first_id, p.records[0].id, p.records[0].status.clone()), + (256, 256, Status::Reserved) + ); + let full = p.clone(); + let q = req(&p, 0, 1); + let d = p.preview("research.test.near", &q, 100); + assert_eq!((d.allowed, d.reason.as_str()), (false, "Full")); + assert_eq!(p.best_quantity("research.test.near", &q, 100), None); + assert_eq!(p.submit("research.test.near", q, 100), Err(Error::Full)); + assert_eq!(p, full); + assert_live(&p); + + // In flight, the front record still blocks until its executor settles. + let mut flight = p.clone(); + flight.dispatch("evaluation.test.near", front, 100).unwrap(); + assert_eq!(submit(&mut flight, 0, 1, 100), Err(Error::Full)); + flight.settle(EXEC, front, true).unwrap(); + assert_eq!(submit(&mut flight, 0, 1, 100), Ok(512)); + assert_eq!(flight.completed_units, vec![0, 0, 1, 0, 0, 0]); + + // The owner cancels the front record; the next submit prunes it. + p.cancel(OWNER, front, 100).unwrap(); + record_history(&mut ghost, &p); + assert_eq!(submit(&mut p, 0, 1, 100), Ok(512)); + record_history(&mut ghost, &p); + assert_eq!(p.first_id, 257); + assert_window(&p, &ghost); + assert_eq!(p.record(front), Err(Error::NotFound)); +} + +/// F-3: prerequisites read the lifetime `completed_units` counter, so +/// pruning a Completed record does not undo them. In the hiring fixture +/// the review needs 2 completed research units and 3 implementation units. +/// Both Completed records are pruned and the review is still admitted. +#[test] +fn f3_prerequisites_survive_pruning() { + let mut p = pool("hiring"); + let mut ghost = vec![]; + for (recipe, units) in [(0, 2), (1, 3)] { + let id = submit(&mut p, recipe, units, 100).unwrap(); + dispatch_active(&mut p, id, 100); + p.settle(EXEC, id, true).unwrap(); + } + assert_eq!(p.completed_units, vec![2, 3, 0]); + // Submit and cancel reviews until both Completed records are pruned. + while p.first_id < 2 { + let id = submit(&mut p, 2, 1, 100).unwrap(); + p.cancel(OWNER, id, 100).unwrap(); + record_history(&mut ghost, &p); + } + assert_eq!(p.first_id, 2); + assert_window(&p, &ghost); + assert!(p.records.iter().all(|c| c.status == Status::Cancelled)); + assert_eq!(p.completed_units, vec![2, 3, 0]); + let review = submit(&mut p, 2, 2, 100).unwrap(); + dispatch_active(&mut p, review, 100); + p.settle(EXEC, review, true).unwrap(); + assert_eq!(p.completed_units, vec![2, 3, 2]); +} + +/// The window on random runs: 10 seeded configurations, 3,000 random calls +/// each, enough for the window to fill and prune many times. Each has 1-3 +/// metrics with random recipe effects and bounds 60-150 either side of +/// zero, plus one metric that no recipe touches and that carries the only +/// potential term, so admission is limited by the hard bounds, not by +/// energy. A call on a record picks the oldest one a quarter of the time +/// and an open one half of the time; one record in 32 is never picked the +/// second way, so the oldest record is sometimes open when the window is +/// full. Every 1,500 calls every open record is resolved and the initial +/// values are observed again, so completions do not push the values into a +/// corner. After every call: a rejected call leaves the pool unchanged, +/// preview agrees with submit, Full means 256 retained records with the +/// oldest open, an admission into a full window prunes exactly one record, +/// ids stay affine, only terminal records are pruned, `completed_units` +/// equals the lifetime count, and INV-RES holds. Every 20 calls, every open +/// record can be resolved (assert_live). +#[test] +fn window_on_random_runs() { + let (mut prunes, mut fulls, mut runs_pruning, mut runs_full) = (0, 0, 0, 0); + for seed in 1..=10u64 { + let mut g = Rng(seed.wrapping_mul(0xD1B5_4A32_D192_ED03) | 1); + let n = g.range(1, 3) as usize; + let mut metrics: Vec = (0..n) + .map(|_| { + let (min, max) = (g.range(-150, -60), g.range(60, 150)); + metric(min, max, g.range(-10, 10)) + }) + .collect(); + metrics.push(metric(-10, 10, 0)); + // Effects on the first n metrics; none on the last one. + let effects = |g: &mut Rng| -> Vec { + (0..=n).map(|k| if k < n { effect(g) } else { 0 }).collect() + }; + let recipes = (0..g.range(1, 3)) + .map(|i| Recipe { + name: "r".into(), + actor: ["a1.test.near", "a2.test.near"][g.range(0, 1) as usize].into(), + executor: ["x1.test.near", "x2.test.near"][g.range(0, 1) as usize].into(), + reserve: effects(&mut g), + complete: effects(&mut g), + max_units: g.range(1, 3) as u32, + requires: if i > 0 && g.coin() { + vec![(0, 1)] + } else { + vec![] + }, + }) + .collect(); + let c = Config { + name: "window".into(), + owner: OWNER.into(), + terms: vec![Term { + metric: n as u32, + target: 0, + weight: 1, + shape: Shape::Target, + }], + metrics, + recipes, + max_age_seconds: 0, + }; + let mut p = Pool::new(c, 100).unwrap(); + let initial = p.values.clone(); + let mut ghost = vec![]; + let fulls_before = fulls; + for step in 0..3_000 { + let before = p.clone(); + let next = i64::from(p.first_id) + p.records.len() as i64; + let tended: Vec = p + .records + .iter() + .filter(|c| open(&c.status) && c.id % 32 != 5) + .map(|c| c.id) + .collect(); + let pick = g.range(0, 3); + let id = match pick { + 0 => p.first_id, + 1 => g.range(i64::from(p.first_id), next) as u32, + _ if !tended.is_empty() => tended[g.range(0, tended.len() as i64 - 1) as usize], + _ => g.range((next - 6).max(0), next) as u32, + }; + let known = p.record(id).ok().map(|c| { + let r = &p.config.recipes[c.recipe as usize]; + (r.actor.clone(), r.executor.clone(), c.status.clone()) + }); + let tending = pick >= 2 && !tended.is_empty() && g.coin(); + // k: < 40 submit, < 55 dispatch, < 62 acknowledge, < 82 settle, + // < 97 cancel, else observe. Half of the calls on a tended record + // move it to its next state or to an exit. + let (k, actor, executor) = match known { + Some((a, x, Status::Reserved)) if tending => (if g.coin() { 40 } else { 82 }, a, x), + Some((a, x, _)) if tending => (if g.range(0, 3) == 0 { 55 } else { 62 }, a, x), + Some((a, x, _)) => (g.range(0, 99), a, x), + None => (g.range(0, 99), "a1.test.near".into(), "x1.test.near".into()), + }; + let result = if k < 40 { + let recipe = g.range(0, p.config.recipes.len() as i64 - 1) as u32; + let r = &p.config.recipes[recipe as usize]; + let a = r.actor.clone(); + let q = Request { + recipe, + units: g.range(1, i64::from(r.max_units)) as u32, + version: p.version, + expires_at: 1_000, + }; + let allowed = p.preview(&a, &q, 100).allowed; + let result = p.submit(&a, q, 100); + assert_eq!(allowed, result.is_ok(), "preview disagrees with submit"); + let full = before.records.len() == MAX_RECORDS; + match result { + Err(Error::Full) => { + assert!(full && open(&before.records[0].status)); + fulls += 1; + } + Ok(new) => { + assert_eq!(new, next as u32); + assert_eq!(p.first_id, before.first_id + u32::from(full)); + prunes += usize::from(full); + } + Err(_) => {} + } + result.map(|_| ()) + } else if k < 55 { + p.dispatch(&actor, id, 100) + } else if k < 62 { + p.acknowledge(id, g.coin()) + } else if k < 82 { + p.settle(&executor, id, g.coin()) + } else if k < 97 { + let who = if g.coin() { OWNER.to_string() } else { actor }; + p.cancel(&who, id, 100) + } else { + // Restate the values, or reset them if every record is terminal. + let values = if g.coin() { + initial.clone() + } else { + p.values.clone() + }; + p.observe(OWNER, values, 100) + }; + if result.is_err() { + assert_eq!(p, before, "a rejected call changed the pool"); + } + record_history(&mut ghost, &p); + assert_window(&p, &ghost); + assert_inv_res(&p); + if step % 20 == 0 { + assert_live(&p); + } + // Every 1,500 calls, resolve every open record and observe the + // initial values again, so completions do not drift the values + // into a corner where nothing is admitted. + if step % 1_500 == 1_499 { + let open_ids: Vec = p + .records + .iter() + .filter(|c| open(&c.status)) + .map(|c| c.id) + .collect(); + for id in open_ids { + let c = p.record(id).unwrap().clone(); + let r = p.config.recipes[c.recipe as usize].clone(); + if c.status == Status::Reserved { + p.cancel(&r.actor, id, 100).unwrap(); + } else { + p.settle(&r.executor, id, g.coin()).unwrap(); + } + record_history(&mut ghost, &p); + } + p.observe(OWNER, initial.clone(), 100).unwrap(); + } + } + runs_pruning += usize::from(p.first_id > 0); + runs_full += usize::from(fulls > fulls_before); + } + println!( + "prunes {prunes}, Full {fulls}; runs that pruned {runs_pruning}, that hit Full {runs_full}" + ); + assert!(prunes > 1_000 && fulls > 20 && runs_pruning >= 6 && runs_full >= 3); +} + +/// F-4 (low), fixed: v1.0.0 accepted a recipe whose actor is its executor, +/// and one whose actor and executor are both the owner; in the hiring +/// fixture each could then accept its own work (spec:64). v1.1 rejects +/// both. The owner may still be a recipe's actor or its executor, but not +/// both. formalver trace 210 (a smaller config). +#[test] +fn f4_actor_cannot_be_its_own_executor() { + const WORKER: &str = "research.test.near"; + let mut c = fixtures::config("hiring").unwrap(); + c.recipes[0].executor = WORKER.into(); + assert_eq!(c.validate(), Err(Error::InvalidConfig)); + assert_eq!(Pool::new(c, 100), Err(Error::InvalidConfig)); + let mut c = fixtures::config("hiring").unwrap(); + c.recipes[1].actor = OWNER.into(); + c.recipes[1].executor = OWNER.into(); + assert_eq!(c.validate(), Err(Error::InvalidConfig)); + assert_eq!(Pool::new(c, 100), Err(Error::InvalidConfig)); + + // Owner as actor, with an independent executor: valid and usable. + let mut c = fixtures::config("hiring").unwrap(); + c.recipes[1].actor = OWNER.into(); + let mut p = Pool::new(c, 100).unwrap(); + let o = submit(&mut p, 1, 3, 100).unwrap(); + dispatch_active(&mut p, o, 100); + assert_eq!(p.settle(OWNER, o, true), Err(Error::Unauthorized)); + p.settle(EXEC, o, true).unwrap(); + assert_eq!(p.values[6], 3); + // Owner as executor of another account's recipe: valid. + let mut c = fixtures::config("hiring").unwrap(); + c.recipes[1].executor = OWNER.into(); + assert_eq!(c.validate(), Ok(())); + for name in fixtures::NAMES { + assert_eq!(fixtures::config(name).map(|c| c.validate()), Ok(Ok(()))); + } +} + +/// F-5 (low), fixed: v1.0.0 froze every transition at version u32::MAX, +/// settlement of in-flight records included. v1.1 stops submit, dispatch, +/// set_paused and observe at VERSION_CAP, 768 versions below u32::MAX, and +/// keeps the rest as a reserve: acknowledgment, settlement and cancellation +/// still work above the cap. Reaching the cap takes about 2^32 effective +/// transitions, so the test sets the field. +#[test] +fn f5_open_records_resolve_above_the_version_cap() { + let mut p = pool("gpu"); + let flight = submit(&mut p, 0, 1, 100).unwrap(); + p.dispatch("research.test.near", flight, 100).unwrap(); + let reserved = submit(&mut p, 2, 1, 100).unwrap(); + p.version = VERSION_CAP; + let frozen = p.clone(); + // preview now agrees with submit (v1.0.0 said allowed here). + let q = req(&p, 4, 1); + let d = p.preview("data.test.near", &q, 100); + assert!(!d.allowed); + assert_eq!(d.reason, "Arithmetic"); + assert_eq!(p.best_quantity("data.test.near", &q, 100), None); + assert_eq!(p.submit("data.test.near", q, 100), Err(Error::Arithmetic)); + assert_eq!( + p.dispatch("evaluation.test.near", reserved, 100), + Err(Error::Arithmetic) + ); + assert_eq!(p.set_paused(OWNER, true), Err(Error::Arithmetic)); + assert_eq!( + p.observe(OWNER, frozen.values.clone(), 100), + Err(Error::Arithmetic) + ); + assert_eq!(p, frozen); + assert_live(&p); + // The longest path of the in-flight record, and the cancel. + p.acknowledge(flight, false).unwrap(); + p.acknowledge(flight, true).unwrap(); + p.settle(EXEC, flight, true).unwrap(); + p.cancel("evaluation.test.near", reserved, 100).unwrap(); + assert_eq!(p.version, VERSION_CAP + 4); + assert!(p.records.iter().all(|c| !open(&c.status))); + // The pool is retired: nothing new starts, also with every record terminal. + let values = p.values.clone(); + assert_eq!(p.observe(OWNER, values, 100), Err(Error::Arithmetic)); + assert_eq!(submit(&mut p, 4, 1, 100), Err(Error::Arithmetic)); +} + +/// F-5, paused form, fixed: in v1.0.0 a paused pool at version u32::MAX +/// could not be unpaused, observed or settled. In v1.1 the last pause that +/// fits takes the version to VERSION_CAP. From there pause, unpause and +/// observe fail Arithmetic, and the open records still resolve. +#[test] +fn f5_paused_pool_at_the_cap_still_settles() { + let mut p = pool("gpu"); + let initial = p.values.clone(); + let flight = submit(&mut p, 0, 1, 100).unwrap(); + p.dispatch("research.test.near", flight, 100).unwrap(); + let reserved = submit(&mut p, 2, 1, 100).unwrap(); + p.version = VERSION_CAP - 1; + p.set_paused(OWNER, true).unwrap(); + assert_eq!(p.version, VERSION_CAP); + let frozen = p.clone(); + assert_eq!(p.set_paused(OWNER, false), Err(Error::Arithmetic)); + assert_eq!(p.set_paused(OWNER, true), Err(Error::Arithmetic)); + assert_eq!( + p.observe(OWNER, frozen.values.clone(), 100), + Err(Error::Arithmetic) + ); + assert_eq!(p, frozen); + assert_live(&p); + p.settle(EXEC, flight, false).unwrap(); + p.cancel(OWNER, reserved, 100).unwrap(); + assert_eq!(p.values, initial); + assert_eq!(p.version, VERSION_CAP + 2); + assert!(p.paused); +} + +/// F-5: the reserve is exactly enough. All 256 records are Dispatched when +/// the version reaches VERSION_CAP. Each then takes the longest path +/// (Unknown, Active, Completed), three increments, and the version ends at +/// exactly u32::MAX. +#[test] +fn f5_reserve_is_exactly_enough() { + const A: &str = "agent.test.near"; + assert_eq!( + u64::from(VERSION_CAP) + 3 * MAX_RECORDS as u64, + u64::from(u32::MAX) + ); + let c = config( + vec![metric(0, 10, 5), metric(-100, 100, 5)], + vec![recipe(A, vec![0, 0], vec![0, 0], 1)], + ); + let mut p = Pool::new(c, 100).unwrap(); + let last = MAX_RECORDS as u32 - 1; + for id in 0..last { + assert_eq!(submit(&mut p, 0, 1, 100), Ok(id)); + p.dispatch(A, id, 100).unwrap(); + } + // The last submit and dispatch are the last two increments below the cap. + p.version = VERSION_CAP - 2; + assert_eq!(submit(&mut p, 0, 1, 100), Ok(last)); + p.dispatch(A, last, 100).unwrap(); + assert_eq!(p.version, VERSION_CAP); + for id in 0..=last { + p.acknowledge(id, false).unwrap(); + p.acknowledge(id, true).unwrap(); + p.settle(EXEC, id, true).unwrap(); + } + assert_eq!(p.version, u32::MAX); + assert!(p.records.iter().all(|c| c.status == Status::Completed)); +} + +/// F-6 (low), fixed: the risk fixture has max_age 300 and was observed at +/// 100. At now = 401, with one record Active and one Reserved, submit and +/// dispatch fail SnapshotExpired. In v1.0.0 observe failed Pending until +/// every record was terminal. v1.1 lets the owner restate the current +/// values with records open: the values and records stay as they are, the +/// snapshot timestamp is renewed and the version moves by one. New values +/// still wait for every record to be terminal. formalver trace 211 (a +/// smaller config). +#[test] +fn f6_owner_refreshes_the_snapshot_with_records_open() { + let mut p = pool("risk"); + let slow = submit(&mut p, 0, 1, 100).unwrap(); + dispatch_active(&mut p, slow, 100); + let next = submit(&mut p, 3, 1, 100).unwrap(); + assert_eq!(submit(&mut p, 1, 1, 401), Err(Error::SnapshotExpired)); + assert_eq!( + p.dispatch("macro.test.near", next, 401), + Err(Error::SnapshotExpired) + ); + let before = p.clone(); + let fixture = vec![60, 40, 30, 40]; + assert_eq!(p.observe(OWNER, fixture, 401), Err(Error::Pending)); + let current = p.values.clone(); + assert_eq!( + p.observe("credit.test.near", current.clone(), 401), + Err(Error::Unauthorized) + ); + assert_eq!(p, before); + p.observe(OWNER, current.clone(), 401).unwrap(); + assert_eq!(p.observed_at, 401); + assert_eq!(p.version, before.version + 1); + assert_eq!(p.values, current); + assert_eq!(p.records, before.records); + assert_eq!(p.records[slow as usize].status, Status::Active); + assert_live(&p); + p.dispatch("macro.test.near", next, 401).unwrap(); + submit(&mut p, 3, 1, 401).unwrap(); + assert_live(&p); +} + +/// div-cancel-terminal-name, fixed: v1.0.0 answered a cancel of a +/// Completed record with Pending, a name that suggests an open commitment. +/// v1.1 says InvalidState, as settle does for conflicting terminal +/// evidence. Dispatched, Active and Unknown records keep Pending: their +/// executor's evidence is pending. A repeated cancel is an Ok no-op. +#[test] +fn cancel_names_conflicting_and_in_flight_states() { + let mut p = pool("gpu"); + let done = submit(&mut p, 0, 1, 100).unwrap(); + dispatch_active(&mut p, done, 100); + p.settle(EXEC, done, true).unwrap(); + let sent = submit(&mut p, 0, 1, 100).unwrap(); + p.dispatch("research.test.near", sent, 100).unwrap(); + let active = submit(&mut p, 0, 1, 100).unwrap(); + dispatch_active(&mut p, active, 100); + let unknown = submit(&mut p, 2, 1, 100).unwrap(); + p.dispatch("evaluation.test.near", unknown, 100).unwrap(); + p.acknowledge(unknown, false).unwrap(); + let cancelled = submit(&mut p, 4, 1, 100).unwrap(); + p.cancel("data.test.near", cancelled, 100).unwrap(); + let before = p.clone(); + let expected = [ + (done, Err(Error::InvalidState)), + (sent, Err(Error::Pending)), + (active, Err(Error::Pending)), + (unknown, Err(Error::Pending)), + (cancelled, Ok(())), + ]; + for (id, result) in expected { + let a = actor(&p, p.record(id).unwrap().recipe); + assert_eq!(p.cancel(&a, id, 100), result, "record {id} by its actor"); + assert_eq!(p.cancel(OWNER, id, 100), result, "record {id} by the owner"); + assert_eq!(p.cancel("attacker", id, 100), Err(Error::Unauthorized)); + } + assert_eq!(p, before); +} diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index 575827c..aed1170 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -2,6 +2,8 @@ //! See docs/spec.md for the transition system and explicit trust assumptions. #![forbid(unsafe_code)] +#[cfg(test)] +mod findings; pub mod fixtures; #[cfg(test)] mod tests; @@ -9,10 +11,17 @@ mod tests; pub const MAX_METRICS: usize = 32; pub const MAX_RECIPES: usize = 32; pub const MAX_TERMS: usize = 64; +/// Records retained in a pool's window (`Pool::records`). pub const MAX_RECORDS: usize = 256; pub const MAX_VALUE: i64 = 1_000_000; pub const MAX_WEIGHT: u32 = 1_000; pub const MAX_UNITS: u32 = 100; +/// Submit, dispatch, set_paused and observe fail Arithmetic from this +/// version on. The 3 * MAX_RECORDS versions above it are a reserve: an open +/// record needs at most three more increments to become terminal +/// (Dispatched -> Unknown -> Active -> terminal), so acknowledgment, +/// settlement and cancellation can never overflow the version. +pub const VERSION_CAP: u32 = u32::MAX - 3 * MAX_RECORDS as u32; macro_rules! data { ($($item:item)*) => {$ ( @@ -37,7 +46,11 @@ data! { pub enum Status { Reserved, Dispatched, Active, Unknown, Completed, Cancelled } pub struct Commitment { pub id: u32, pub recipe: u32, pub units: u32, pub expires_at: u64, pub status: Status } pub struct Decision { pub allowed: bool, pub reason: String, pub before: String, pub after: Option, pub terms_before: Vec, pub terms_after: Vec, pub candidate: Option> } - pub struct Pool { pub config: Config, pub values: Vec, pub version: u32, pub observed_at: u64, pub paused: bool, pub records: Vec } + /// `records` holds the at most MAX_RECORDS most recent commitments, oldest + /// first: `records[k].id == first_id + k`. Older records were terminal + /// when submit pruned them. `completed_units[r]` counts recipe r's + /// Completed units over the pool's lifetime, pruned records included. + pub struct Pool { pub config: Config, pub values: Vec, pub version: u32, pub observed_at: u64, pub paused: bool, pub records: Vec, pub first_id: u32, pub completed_units: Vec } pub enum Error { InvalidConfig, Unauthorized, Paused, Stale, Expired, SnapshotExpired, InvalidRecipe, InvalidUnits, Prerequisite, Full, Arithmetic, Bounds, Energy, InvalidState, NotFound, Pending } } impl std::fmt::Display for Error { @@ -110,9 +123,11 @@ impl Config { } } for (i, r) in self.recipes.iter().enumerate() { + // An actor that is also its recipe's executor would attest its own work. if !short(&r.name) || !short(&r.actor) || !short(&r.executor) + || r.actor == r.executor || r.reserve.len() != n || r.complete.len() != n || r.max_units == 0 @@ -139,6 +154,7 @@ impl Pool { pub fn new(config: Config, now: u64) -> Result { config.validate()?; let values = config.metrics.iter().map(|m| m.initial).collect(); + let completed_units = vec![0; config.recipes.len()]; Ok(Self { config, values, @@ -146,6 +162,8 @@ impl Pool { observed_at: now, paused: false, records: vec![], + first_id: 0, + completed_units, }) } pub fn energy_terms(&self, values: &[i64]) -> Result, Error> { @@ -180,8 +198,11 @@ impl Pool { .map(|(v, m)| (m.min - v).max(0) as u64 + (v - m.max).max(0) as u64) .collect() } - /// Check all pending completion subsets conservatively per metric. A pending - /// hedge cannot provide hard-limit headroom before the hedge executes. + /// Per metric, an interval that contains every outcome of every open record + /// (it stays open, completes, or releases its reservation) and of `extra`, + /// with record `skip` left out. A pending hedge gives no hard-limit headroom + /// before it executes, and no admission can rely on another record's + /// reservation staying in place. fn envelope( &self, values: &[i64], @@ -192,11 +213,19 @@ impl Pool { let mut high = values.to_vec(); let mut apply = |r: &Recipe, units: u32| -> Result<(), Error> { for i in 0..values.len() { + // d: completion delta; x: release delta (cancel or settle(false)). let d = r.complete[i] .checked_mul(i64::from(units)) .ok_or(Error::Arithmetic)?; - low[i] = low[i].checked_add(d.min(0)).ok_or(Error::Arithmetic)?; - high[i] = high[i].checked_add(d.max(0)).ok_or(Error::Arithmetic)?; + let x = r.reserve[i] + .checked_mul(-i64::from(units)) + .ok_or(Error::Arithmetic)?; + low[i] = low[i] + .checked_add(d.min(x).min(0)) + .ok_or(Error::Arithmetic)?; + high[i] = high[i] + .checked_add(d.max(x).max(0)) + .ok_or(Error::Arithmetic)?; if !bounded(low[i]) || !bounded(high[i]) { return Err(Error::Arithmetic); } @@ -213,6 +242,11 @@ impl Pool { } Ok((low, high)) } + /// No metric's interval violation may exceed its violation now or at + /// `candidate`. Since every admission passes this check, in every reachable + /// state each metric's interval violation equals its current violation, and + /// every completion or release of an open record passes this check too + /// (LIVE, docs/verification-handoff.md). fn check_bounds( &self, candidate: &[i64], @@ -221,9 +255,10 @@ impl Pool { ) -> Result<(), Error> { let (low, high) = self.envelope(candidate, extra, skip)?; let old = self.violations(&self.values); + let new = self.violations(candidate); for (i, m) in self.config.metrics.iter().enumerate() { let v = (m.min - low[i]).max(0) as u64 + (high[i] - m.max).max(0) as u64; - if v > old[i] { + if v > old[i].min(new[i]) { return Err(Error::Bounds); } } @@ -247,7 +282,9 @@ impl Pool { { return Err(Error::SnapshotExpired); } - if self.records.len() >= MAX_RECORDS { + // A full window frees a slot by pruning its oldest record, which must + // be terminal. + if self.records.len() >= MAX_RECORDS && open(&self.records[0].status) { return Err(Error::Full); } let r = self @@ -261,14 +298,10 @@ impl Pool { if req.units == 0 || req.units > r.max_units { return Err(Error::InvalidUnits); } - if r.requires.iter().any(|(p, units)| { - self.records - .iter() - .filter(|c| c.recipe == *p && c.status == Status::Completed) - .map(|c| c.units) - .sum::() - < *units - }) { + if r.requires + .iter() + .any(|(p, units)| self.completed_units[*p as usize] < *units) + { return Err(Error::Prerequisite); } let next = add(&self.values, &r.reserve, req.units)?; @@ -283,6 +316,9 @@ impl Pool { { return Err(Error::Energy); } + if self.version >= VERSION_CAP { + return Err(Error::Arithmetic); + } Ok(next) } pub fn preview(&self, caller: &str, req: &Request, now: u64) -> Decision { @@ -324,7 +360,15 @@ impl Pool { pub fn submit(&mut self, caller: &str, req: Request, now: u64) -> Result { let next = self.candidate(caller, &req, now)?; let version = self.version.checked_add(1).ok_or(Error::Arithmetic)?; - let id = self.records.len() as u32; + let id = self + .first_id + .checked_add(self.records.len() as u32) + .ok_or(Error::Arithmetic)?; + // candidate() checked that the oldest record is terminal. + if self.records.len() >= MAX_RECORDS { + self.records.remove(0); + self.first_id += 1; + } self.records.push(Commitment { id, recipe: req.recipe, @@ -336,13 +380,30 @@ impl Pool { self.version = version; Ok(id) } - fn record(&self, id: u32) -> Result<&Commitment, Error> { - self.records.get(id as usize).ok_or(Error::NotFound) + /// Position of the record with this id in `records`. A pruned id, or one + /// not yet issued, is `NotFound`. + fn index(&self, id: u32) -> Result { + id.checked_sub(self.first_id) + .map(|k| k as usize) + .filter(|k| *k < self.records.len()) + .ok_or(Error::NotFound) + } + /// The retained record with this id, or `NotFound`. + pub fn record(&self, id: u32) -> Result<&Commitment, Error> { + Ok(&self.records[self.index(id)?]) } fn bump(&mut self) -> Result<(), Error> { self.version = self.version.checked_add(1).ok_or(Error::Arithmetic)?; Ok(()) } + /// The increment for calls that start or administer work. It stops at + /// VERSION_CAP, which keeps the reserve for resolving open records. + fn bump_new(&mut self) -> Result<(), Error> { + if self.version >= VERSION_CAP { + return Err(Error::Arithmetic); + } + self.bump() + } pub fn dispatch(&mut self, caller: &str, id: u32, now: u64) -> Result<(), Error> { let c = self.record(id)?; let r = &self.config.recipes[c.recipe as usize]; @@ -366,8 +427,9 @@ impl Pool { { return Err(Error::SnapshotExpired); } - self.bump()?; - self.records[id as usize].status = Status::Dispatched; + let k = self.index(id)?; + self.bump_new()?; + self.records[k].status = Status::Dispatched; Ok(()) } /// Wrapper must only call this from its private runtime callback. @@ -383,11 +445,12 @@ impl Pool { }; // reconcile is permissionless: a no-op must not bump the version, or // anyone could repeatedly invalidate every in-flight request. - if self.records[id as usize].status == next { + let k = self.index(id)?; + if self.records[k].status == next { return Ok(()); } self.bump()?; - self.records[id as usize].status = next; + self.records[k].status = next; Ok(()) } pub fn cancel(&mut self, caller: &str, id: u32, now: u64) -> Result<(), Error> { @@ -399,6 +462,11 @@ impl Pool { if c.status == Status::Cancelled { return Ok(()); } + // Completed is conflicting terminal evidence, as in settle. An + // in-flight record waits for its executor's evidence. + if c.status == Status::Completed { + return Err(Error::InvalidState); + } if c.status != Status::Reserved { return Err(Error::Pending); } @@ -410,12 +478,13 @@ impl Pool { let r = &self.config.recipes[c.recipe as usize]; let undo: Vec = r.reserve.iter().map(|d| -d).collect(); let next = add(&self.values, &undo, c.units)?; - // A dependent commitment can prevent release. Retain encumbrance until - // dependencies are resolved; do not corrupt a downstream reservation. + // The release is still checked. Admission counted it in the envelope, + // so in a reachable state this check passes; no release is forced. self.check_bounds(&next, None, Some(id))?; + let k = self.index(id)?; self.bump()?; self.values = next; - self.records[id as usize].status = Status::Cancelled; + self.records[k].status = Status::Cancelled; Ok(()) } /// Authenticated executor attests completion or definitive nonexecution. @@ -442,33 +511,38 @@ impl Pool { } let next = add(&self.values, &r.complete, c.units)?; self.check_bounds(&next, None, Some(id))?; + let (k, recipe, units) = (self.index(id)?, c.recipe as usize, c.units); self.bump()?; self.values = next; - self.records[id as usize].status = Status::Completed; + self.records[k].status = Status::Completed; + // Lifetime count for prerequisites; pruning the record keeps it. + self.completed_units[recipe] = self.completed_units[recipe].saturating_add(units); Ok(()) } pub fn set_paused(&mut self, caller: &str, paused: bool) -> Result<(), Error> { if caller != self.config.owner { return Err(Error::Unauthorized); } - self.bump()?; + self.bump_new()?; self.paused = paused; Ok(()) } /// New externally observed baseline, only when no obligations are unresolved. - /// Does not change immutable policy. May expose a hard-limit violation. + /// Restating the current values is allowed at any time: it changes no + /// value or record and renews the snapshot timestamp. Does not change + /// immutable policy. New values may expose a hard-limit violation. pub fn observe(&mut self, caller: &str, values: Vec, now: u64) -> Result<(), Error> { if caller != self.config.owner { return Err(Error::Unauthorized); } - if self.records.iter().any(|c| open(&c.status)) { + if values != self.values && self.records.iter().any(|c| open(&c.status)) { return Err(Error::Pending); } if values.len() != self.values.len() || values.iter().any(|v| !bounded(*v)) { return Err(Error::Bounds); } self.energy(&values)?; - self.bump()?; + self.bump_new()?; self.values = values; self.observed_at = now; Ok(()) diff --git a/crates/core/src/tests.rs b/crates/core/src/tests.rs index 6679251..eac305d 100644 --- a/crates/core/src/tests.rs +++ b/crates/core/src/tests.rs @@ -222,7 +222,15 @@ fn arithmetic_and_record_limits() { status: Status::Cancelled, }) .collect(); + // A full window is Full only while its oldest record is open. + p.records[0].status = Status::Reserved; + let before = p.clone(); assert_eq!(submit(&mut p, 0, 1), Err(Error::Full)); + assert_eq!(p, before); + p.records[0].status = Status::Cancelled; + assert_eq!(submit(&mut p, 0, 1), Ok(MAX_RECORDS as u32)); + assert_eq!((p.first_id, p.records.len()), (1, MAX_RECORDS)); + assert_eq!(p.records[MAX_RECORDS - 1].id, MAX_RECORDS as u32); } #[test] diff --git a/crates/demo/src/main.rs b/crates/demo/src/main.rs index 38edd1b..a64d069 100644 --- a/crates/demo/src/main.rs +++ b/crates/demo/src/main.rs @@ -24,7 +24,7 @@ fn request(p: &Pool, r: u32, u: u32, time: u64) -> Request { } } fn finish_at(p: &mut Pool, id: u32, time: u64) -> Result<(), pool_core::Error> { - let c = p.records[id as usize].clone(); + let c = p.record(id)?.clone(); let r = p.config.recipes[c.recipe as usize].clone(); if c.status == Status::Reserved { p.dispatch(&r.actor, id, time)?; @@ -95,7 +95,7 @@ fn api(path: &str, body: &[u8], pools: &mut BTreeMap) -> Result finish_at(p, id, now()), diff --git a/crates/executor/src/lib.rs b/crates/executor/src/lib.rs index 811d1ce..5f2e89c 100644 --- a/crates/executor/src/lib.rs +++ b/crates/executor/src/lib.rs @@ -1,5 +1,18 @@ //! Synthetic, enforced adapter. It holds no real assets and runs no real jobs. -use near_sdk::{env, near, AccountId, Gas, NearToken, PanicOnDefault, Promise}; +use near_sdk::{env, near, AccountId, Gas, NearToken, PanicOnDefault, PromiseError}; +/// The lock retains its 256 most recent records (pool_core::MAX_RECORDS). A +/// job whose id is this far behind `newest` belongs to a pruned, terminal +/// record, so it is forgotten. +const WINDOW: u64 = 256; +/// Jobs held at most. Job ids are distinct and each is above +/// `newest - WINDOW`, so at most WINDOW of them are at or below `newest`. +/// Every other job is a confirmation above `newest` whose `on_settled` has +/// not run yet, or whose `settle` the lock refused. So the cap needs at +/// least WINDOW such jobs above `newest`. +const MAX_JOBS: usize = 512; +/// Gas for the lock's `settle`, and for this contract's `on_settled` after it. +const SETTLE_TGAS: u64 = 40; +const ON_SETTLED_TGAS: u64 = 10; #[near(serializers=[borsh,json])] #[derive(Clone)] pub struct Job { @@ -15,6 +28,11 @@ pub struct Executor { operator: AccountId, jobs: Vec, mode: String, + /// The largest id the lock has vouched for: one whose `execute` created a + /// job (an `execute` of an id that has a job moves nothing), or one whose + /// `settle` from this executor it accepted. Either way the lock retained + /// that record then, so every id WINDOW or more below it was pruned. + newest: u32, } #[near] impl Executor { @@ -26,6 +44,7 @@ impl Executor { operator, jobs: vec![], mode: "normal".into(), + newest: 0, } } pub fn set_mode(&mut self, mode: String) { @@ -36,6 +55,10 @@ impl Executor { ); self.mode = mode; } + /// Starts job `id` once and raises `newest` to it; an id that has a job (a + /// repeat, or a confirmation's) returns its status and moves nothing. An id + /// WINDOW or more behind `newest` returns "cancelled" and starts nothing: + /// the lock pruned its record, so it is terminal and never dispatched again. pub fn execute(&mut self, id: u32, recipe: u32, units: u32) -> String { assert_eq!( env::predecessor_account_id(), @@ -46,7 +69,13 @@ impl Executor { assert!(j.recipe == recipe && j.units == units, "payload mismatch"); return j.status.clone(); } - assert!(self.jobs.len() < 256, "full"); + // A forgotten id belongs to a pruned record: never start it. + if u64::from(id) + WINDOW <= u64::from(self.newest) { + return "cancelled".into(); + } + // The lock dispatched `id`, so it retains the record. + self.advance(id); + assert!(self.jobs.len() < MAX_JOBS, "full"); assert_ne!(self.mode, "panic", "injected failure"); let status = if self.mode == "reject" { "cancelled" @@ -73,8 +102,10 @@ impl Executor { .map(|j| j.status.clone()) .unwrap_or_else(|| "unknown".into()) } - /// Independent provider/acceptor attests exact completion or definitive cancellation. - pub fn finish(&mut self, id: u32, completed: bool) -> Promise { + /// Independent provider/acceptor attests exact completion or definitive + /// cancellation. If the lock accepts the settle, `on_settled` raises + /// `newest` to `id`; this is also how a refused confirmation is retried. + pub fn finish(&mut self, id: u32, completed: bool) { self.operator(); let j = self .jobs @@ -87,24 +118,46 @@ impl Executor { "terminal outcome conflict" ); j.status = next.into(); - self.notify(id, completed) + self.notify(id, completed); } - /// Definitive evidence for an execute receipt that failed before creating a job. - pub fn confirm_not_executed(&mut self, id: u32, recipe: u32, units: u32) -> Promise { + /// Definitive evidence for an execute receipt that failed before creating + /// a job. A forgotten id fails "stale id". The job is stored first and kept + /// whatever the lock answers. If the lock accepts the settle, `on_settled` + /// raises `newest` to `id`. If it refuses (an unassigned or pruned id, a + /// record still Reserved, another outcome recorded, another executor's + /// recipe), the job stays until `newest` is WINDOW or more past its id, for + /// good if the lock never reaches that id. MAX_JOBS is reached only with at + /// least WINDOW jobs above `newest`, refused or waiting for `on_settled`. + pub fn confirm_not_executed(&mut self, id: u32, recipe: u32, units: u32) { self.operator(); assert!(!self.jobs.iter().any(|j| j.id == id), "job exists"); - assert!(self.jobs.len() < 256, "full"); + assert!(u64::from(id) + WINDOW > u64::from(self.newest), "stale id"); + assert!(self.jobs.len() < MAX_JOBS, "full"); self.jobs.push(Job { id, recipe, units, status: "cancelled".into(), }); - self.notify(id, false) + self.notify(id, false); } pub fn get_jobs(&self) -> Vec { self.jobs.clone() } + /// Private callback of `notify`, after the lock's `settle({id,..})`. The + /// lock accepts a settle only for a record it retains, so on success every + /// id WINDOW or more below `id` is pruned there: raise `newest`, as + /// `execute` does. A refused settle changes nothing; the transaction + /// already reports the lock's error. `#[private]` admits only this + /// account, and only `notify` gives it a promise result. + #[private] + pub fn on_settled(&mut self, id: u32) { + assert_eq!(env::promise_results_count(), 1, "not a settle callback"); + // Settle returns no value, but any success counts (even `Err(TooLong)`). + if env::promise_result_checked(0, 0) != Err(PromiseError::Failed) { + self.advance(id); + } + } } impl Executor { fn operator(&self) { @@ -114,15 +167,405 @@ impl Executor { "only independent operator" ); } - fn notify(&self, id: u32, completed: bool) -> Promise { - Promise::new(self.lock.clone()).function_call( + /// The lock retained record `id` at some moment, so every id WINDOW or + /// more below it was pruned then: terminal, and never dispatched again. + /// Raises `newest` to `id` and forgets those jobs. + fn advance(&mut self, id: u32) { + self.newest = self.newest.max(id); + let newest = u64::from(self.newest); + self.jobs.retain(|j| u64::from(j.id) + WINDOW > newest); + } + /// Calls the lock's `settle({id,completed})`, then this contract's + /// `on_settled({id})`. The call's result stays the lock's (Ok, or its + /// error): `on_settled` waits on `settle` but is not returned. NT-F3: + /// low-level promise functions only, never near-sdk's `Promise` type. + fn notify(&self, id: u32, completed: bool) { + let zero = NearToken::from_yoctonear(0); + let args = |v: near_sdk::serde_json::Value| near_sdk::serde_json::to_vec(&v).unwrap(); + let settle = env::promise_create( + self.lock.clone(), "settle", - near_sdk::serde_json::to_vec( - &near_sdk::serde_json::json!({"id":id,"completed":completed}), - ) - .unwrap(), - NearToken::from_yoctonear(0), - Gas::from_tgas(40), + args(near_sdk::serde_json::json!({"id":id,"completed":completed})), + zero, + Gas::from_tgas(SETTLE_TGAS), + ); + env::promise_then( + settle, + env::current_account_id(), + "on_settled", + args(near_sdk::serde_json::json!({"id":id})), + zero, + Gas::from_tgas(ON_SETTLED_TGAS), + ); + env::promise_return(settle); + } +} +#[cfg(test)] +mod tests { + use super::*; + use near_sdk::mock::MockAction; + use near_sdk::serde_json::{json, Value}; + use near_sdk::test_utils::{get_created_receipts, VMContextBuilder}; + use near_sdk::{testing_env, PromiseResult}; + fn caller(account: &str) { + let mut b = VMContextBuilder::new(); + b.current_account_id("executor.test.near".parse().unwrap()) + .predecessor_account_id(account.parse().unwrap()); + testing_env!(b.build()); + } + /// A receipt holding one function call: (receiver, receipts it waits for, + /// method, JSON args, deposit in yocto, gas in Tgas, unused-gas weight). + type Receipt = (String, Vec, String, Value, u128, u64, u64); + /// Every receipt created by the last call. + fn receipts() -> Vec { + get_created_receipts() + .into_iter() + .map(|r| match &r.actions[..] { + [MockAction::FunctionCallWeight { + method_name, + args, + attached_deposit, + prepaid_gas, + gas_weight, + .. + }] => ( + r.receiver_id.to_string(), + r.receipt_indices.clone(), + String::from_utf8(method_name.clone()).unwrap(), + near_sdk::serde_json::from_slice(args).unwrap(), + attached_deposit.as_yoctonear(), + prepaid_gas.as_tgas(), + gas_weight.0, + ), + _ => panic!("not one function call: {r:?}"), + }) + .collect() + } + /// What `notify` creates: the lock's settle (40 Tgas), then this + /// contract's `on_settled` (10 Tgas), which waits for it. + fn settle(id: u32, completed: bool) -> Vec { + vec![ + ( + "pool.test.near".into(), + vec![], + "settle".into(), + json!({"id":id,"completed":completed}), + 0, + 40, + 0, + ), + ( + "executor.test.near".into(), + vec![0], + "on_settled".into(), + json!({"id":id}), + 0, + 10, + 0, + ), + ] + } + /// The executor's own `on_settled(id)` after the lock accepted (`ok`) or + /// refused its settle. + fn settled(e: &mut Executor, id: u32, ok: bool) { + let result = if ok { + PromiseResult::Successful(vec![]) + } else { + PromiseResult::Failed + }; + settled_with(e, id, result); + } + /// The executor's own `on_settled(id)` with the given settle result. + fn settled_with(e: &mut Executor, id: u32, result: PromiseResult) { + let mut b = VMContextBuilder::new(); + b.current_account_id("executor.test.near".parse().unwrap()) + .predecessor_account_id("executor.test.near".parse().unwrap()); + testing_env!( + b.build(), + near_sdk::test_vm_config(), + near_sdk::RuntimeFeesConfig::test(), + Default::default(), + vec![result] + ); + e.on_settled(id); + } + fn confirm(e: &mut Executor, id: u32) { + caller("operator.test.near"); + e.confirm_not_executed(id, 0, 1); + } + /// The lock executes each id in `ids`; each starts. + fn execute(e: &mut Executor, ids: impl IntoIterator) { + caller("pool.test.near"); + for id in ids { + assert_eq!(e.execute(id, 0, 1), "active"); + } + } + /// The executor's stored state, as bytes. + fn stored(e: &Executor) -> Vec { + near_sdk::borsh::to_vec(e).unwrap() + } + /// The mock runtime cannot see which promise `notify` returns. The + /// sandbox test `confirmed_failed_executes_keep_the_executor_at_256_jobs` + /// checks it: a refused confirmation's transaction fails with the lock's + /// error (`NotFound`), while its `on_settled` receipt succeeds. + #[test] + fn finish_and_confirm_call_settle_on_the_lock() { + caller("executor.test.near"); + let mut e = Executor::new( + "pool.test.near".parse().unwrap(), + "operator.test.near".parse().unwrap(), + ); + caller("pool.test.near"); + assert_eq!(e.execute(0, 0, 4), "active"); + assert_eq!(receipts(), vec![]); + caller("operator.test.near"); + e.finish(0, true); + assert_eq!(receipts(), settle(0, true)); + caller("operator.test.near"); + e.confirm_not_executed(1, 0, 2); + assert_eq!(receipts(), settle(1, false)); + let jobs: Vec<_> = e.jobs.iter().map(|j| (j.id, j.status.as_str())).collect(); + assert_eq!(jobs, vec![(0, "completed"), (1, "cancelled")]); + } + fn executor() -> Executor { + caller("executor.test.near"); + Executor::new( + "pool.test.near".parse().unwrap(), + "operator.test.near".parse().unwrap(), ) } + fn ids(e: &Executor) -> Vec { + e.jobs.iter().map(|j| j.id).collect() + } + /// F-3: executing id N + 256 forgets job N. A later execute of N starts + /// nothing and returns "cancelled"; retained jobs keep their status. + #[test] + fn f3_execute_forgets_jobs_256_ids_behind_the_newest() { + let mut e = executor(); + caller("pool.test.near"); + for id in 0..256 { + assert_eq!(e.execute(id, 0, 1), "active"); + } + assert_eq!(ids(&e), (0..256).collect::>()); + assert_eq!(e.execute(256, 0, 1), "active"); + assert_eq!((e.newest, ids(&e)), (256, (1..=256).collect::>())); + assert_eq!(e.status(0), "unknown"); + assert_eq!(e.execute(0, 0, 1), "cancelled"); + assert_eq!((e.newest, ids(&e)), (256, (1..=256).collect::>())); + assert_eq!(e.execute(1, 0, 1), "active"); + // A jump forgets every job up to the new id - 256. + assert_eq!(e.execute(300, 0, 1), "active"); + let mut expected: Vec = (45..=256).collect(); + expected.push(300); + assert_eq!(ids(&e), expected); + // An id below the newest but within the window still starts once. + assert_eq!(e.execute(299, 0, 1), "active"); + assert_eq!(e.newest, 300); + assert_eq!(receipts(), vec![]); + } + /// After an execute of id 256, id 1 can still be confirmed as not + /// executed (id 0 is stale, below). A confirmation the lock refuses, such + /// as a typo of a far higher id, moves nothing, so nothing becomes stale. + #[test] + fn f3_confirm_is_accepted_up_to_255_ids_behind() { + let mut e = executor(); + caller("pool.test.near"); + e.execute(256, 0, 1); + caller("operator.test.near"); + e.confirm_not_executed(1_000_000, 0, 1); + settled(&mut e, 1_000_000, false); + assert_eq!(e.newest, 256); + caller("operator.test.near"); + e.confirm_not_executed(1, 0, 1); + assert_eq!(ids(&e), vec![256, 1_000_000, 1]); + assert_eq!(receipts(), settle(1, false)); + } + #[test] + #[should_panic(expected = "stale id")] + fn f3_stale_confirm_not_executed_panics() { + let mut e = executor(); + caller("pool.test.near"); + e.execute(256, 0, 1); + caller("operator.test.near"); + e.confirm_not_executed(0, 0, 1); + } + /// One execute of a higher id frees the cap: at most 256 jobs remain at + /// or below the new newest id. + #[test] + fn f3_an_execute_frees_the_cap() { + let mut e = executor(); + for id in 1..=512 { + caller("operator.test.near"); + e.confirm_not_executed(id, 0, 1); + } + assert_eq!((e.jobs.len(), e.newest), (512, 0)); + caller("pool.test.near"); + assert_eq!(e.execute(600, 0, 1), "active"); + let mut expected: Vec = (345..=512).collect(); + expected.push(600); + assert_eq!(ids(&e), expected); + caller("operator.test.near"); + e.confirm_not_executed(601, 0, 1); + assert_eq!(e.jobs.len(), 170); + } + /// D-1: the lock accepting a confirmation's settle moves `newest` and + /// forgets every job 256 or more below it, as an execute does. An + /// accepted settle of a lower id moves nothing. + #[test] + fn d1_an_accepted_settle_moves_newest_and_forgets() { + let mut e = executor(); + execute(&mut e, 0..=255); + confirm(&mut e, 300); + assert_eq!((e.newest, e.jobs.len()), (255, 257)); + settled(&mut e, 300, true); + let mut expected: Vec = (45..=255).collect(); + expected.push(300); + assert_eq!((e.newest, ids(&e)), (300, expected.clone())); + let before = stored(&e); + settled(&mut e, 100, true); + assert_eq!(stored(&e), before); + // Id 44 is forgotten: its record was pruned, so nothing starts. + caller("pool.test.near"); + assert_eq!(e.execute(44, 0, 1), "cancelled"); + assert_eq!((e.newest, ids(&e)), (300, expected)); + } + /// D-1: a refused settle changes nothing, whichever job it was for. + #[test] + fn d1_a_refused_settle_changes_nothing() { + let mut e = executor(); + execute(&mut e, 0..=10); + confirm(&mut e, 400); + assert_eq!(e.status(400), "cancelled"); + assert_eq!(e.newest, 10); + // A confirmation job above the newest id, an executed job, an absent id. + for id in [400, 5, 1_000] { + let before = stored(&e); + settled(&mut e, id, false); + assert_eq!(stored(&e), before, "refused settle of {id}"); + } + assert_eq!(e.newest, 10); + assert_eq!(ids(&e).len(), 12); + } + /// D-1: the shipped lock's `settle` returns nothing, but a success with a + /// value counts as accepted too (`promise_result_checked` with a bound + /// of 0 bytes reports it as `TooLong`, not `Failed`). + #[test] + fn d1_a_settle_success_with_a_value_counts_as_accepted() { + let mut e = executor(); + execute(&mut e, 0..=255); + confirm(&mut e, 300); + settled_with(&mut e, 300, PromiseResult::Successful(vec![1])); + let mut expected: Vec = (45..=255).collect(); + expected.push(300); + assert_eq!((e.newest, ids(&e)), (300, expected)); + } + /// D-1: `on_settled` needs the one promise result `notify` gives it. The + /// executor account calling it directly has none. (`#[private]` exists + /// only in the Wasm entry point; the sandbox tests it.) + #[test] + #[should_panic(expected = "not a settle callback")] + fn d1_on_settled_needs_one_promise_result() { + let mut e = executor(); + caller("executor.test.near"); + e.on_settled(5); + } + /// D-1, decision (a): `finish` also calls `on_settled`. A refused + /// confirmation (as for a record still Reserved) moves nothing, and nor + /// does the lock's later `execute` of that id, which answers from the + /// stored job. The operator's retry `finish(id, false)`, once accepted, + /// moves `newest`. + #[test] + fn d1_finish_moves_newest_too() { + let mut e = executor(); + execute(&mut e, 0..=255); + confirm(&mut e, 300); + settled(&mut e, 300, false); + assert_eq!((e.newest, e.jobs.len()), (255, 257)); + caller("pool.test.near"); + assert_eq!(e.execute(300, 0, 1), "cancelled"); + assert_eq!((e.newest, e.jobs.len()), (255, 257)); + caller("operator.test.near"); + e.finish(300, false); + assert_eq!(receipts(), settle(300, false)); + settled(&mut e, 300, true); + let mut expected: Vec = (45..=255).collect(); + expected.push(300); + assert_eq!((e.newest, ids(&e)), (300, expected)); + } + /// D-1: a refused job is not freed when `newest` passes its id; it is + /// forgotten only once `newest` is 256 or more past it. + #[test] + fn d1_a_refused_job_is_forgotten_256_past_its_id() { + let mut e = executor(); + confirm(&mut e, 300); + settled(&mut e, 300, false); + execute(&mut e, [400]); + assert_eq!(ids(&e), vec![300, 400]); + confirm(&mut e, 555); + settled(&mut e, 555, true); + assert_eq!((e.newest, ids(&e)), (555, vec![300, 400, 555])); + confirm(&mut e, 556); + settled(&mut e, 556, true); + assert_eq!((e.newest, ids(&e)), (556, vec![400, 555, 556])); + } + /// D-1: accepted confirmations alone keep at most 256 jobs (v1.1.0 before + /// this change reached the 512-job cap after 512 of them). + #[test] + fn d1_accepted_confirmations_keep_256_jobs() { + let mut e = executor(); + for id in 0..1_000u32 { + confirm(&mut e, id); + settled(&mut e, id, true); + assert_eq!(e.jobs.len(), (id as usize + 1).min(256), "after {id}"); + } + assert_eq!((e.newest, ids(&e)), (999, (744..=999).collect::>())); + } + /// D-1: with 256 jobs at or below `newest`, 256 refused confirmations + /// above it fill the cap, and the 257th fails "full". + #[test] + #[should_panic(expected = "full")] + fn d1_256_refused_jobs_above_a_full_window_fill_the_cap() { + let mut e = executor(); + execute(&mut e, 0..=255); + for id in 300..556u32 { + confirm(&mut e, id); + settled(&mut e, id, false); + } + assert_eq!((e.newest, e.jobs.len()), (255, 512)); + confirm(&mut e, 556); + } + /// D-1: with fewer jobs at or below `newest`, more refused jobs fit above + /// it: the cap counts all jobs. + #[test] + fn d1_with_fewer_jobs_below_newest_more_refused_jobs_fit() { + let mut e = executor(); + execute(&mut e, 0..=99); + for id in 300..712u32 { + confirm(&mut e, id); + settled(&mut e, id, false); + } + assert_eq!((e.newest, e.jobs.len()), (99, 512)); + } + /// D-1: callbacks may run in any order; the result is the same. + #[test] + fn d1_callbacks_in_any_order() { + let run = |reverse: bool| { + let mut e = executor(); + for id in 0..300u32 { + confirm(&mut e, id); + } + // All 300 confirmations in flight: no callback has run yet. + assert_eq!((e.newest, e.jobs.len()), (0, 300)); + let mut order: Vec = (0..300).collect(); + if reverse { + order.reverse(); + } + for id in order { + settled(&mut e, id, true); + } + assert_eq!((e.newest, ids(&e)), (299, (44..=299).collect::>())); + stored(&e) + }; + assert_eq!(run(true), run(false)); + } } diff --git a/crates/sandbox/tests/integration.rs b/crates/sandbox/tests/integration.rs index b9afae6..15897cc 100644 --- a/crates/sandbox/tests/integration.rs +++ b/crates/sandbox/tests/integration.rs @@ -1,6 +1,6 @@ //! Real Wasm/receipt integration. Run scripts/sandbox.sh after building both Wasm files. -use near_workspaces::{Account, Contract}; -use pool_core::{fixtures, Pool, Request, Status}; +use near_workspaces::{types::NearToken, Account, Contract}; +use pool_core::{fixtures, Config, Metric, Pool, Recipe, Request, Shape, Status, Term}; use serde_json::{json, Value}; use std::{ collections::BTreeMap, @@ -33,15 +33,34 @@ async fn call(a: &Account, c: &Contract, method: &str, args: Value) -> Value { assert!(result.is_success(), "{method}: {result:?}"); result.json().unwrap_or(Value::Null) } -async fn fail(a: &Account, c: &Contract, method: &str, args: Value) { +/// The call must fail with a panic message that contains `expected`. A Wasm +/// built without `--cfg near` traps with no message, so this also checks the build. +async fn fail(a: &Account, c: &Contract, method: &str, args: Value, expected: &str) { + fail_paying(a, c, method, args, NearToken::from_yoctonear(0), expected).await +} +/// `fail` with a deposit attached. +async fn fail_paying( + a: &Account, + c: &Contract, + method: &str, + args: Value, + deposit: NearToken, + expected: &str, +) { let r = a .call(c.id(), method) .args_json(args) + .deposit(deposit) .max_gas() .transact() .await .unwrap(); assert!(r.is_failure(), "expected {method} to fail"); + let text = r.into_result().unwrap_err().to_string(); + assert!( + text.contains("Smart contract panicked: ") && text.contains(expected), + "{method}: expected a panic with {expected:?}, got {text}" + ); } #[tokio::test] async fn five_scenarios_execute_through_the_actual_gate() { @@ -99,9 +118,17 @@ async fn five_scenarios_execute_through_the_actual_gate() { &executor, "execute", json!({"id":id,"recipe":r,"units":u}), + "only lock may execute", + ) + .await; + fail( + actor, + &lock, + "settle", + json!({"id":id,"completed":true}), + "Unauthorized", ) .await; - fail(actor, &lock, "settle", json!({"id":id,"completed":true})).await; call(actor, &lock, "dispatch", json!({"id":id})).await; reference.dispatch(actor.id().as_str(), id, now()).unwrap(); reference.acknowledge(id, true).unwrap(); @@ -130,7 +157,14 @@ async fn five_scenarios_execute_through_the_actual_gate() { reference.energy(&reference.values).unwrap(), reference.records.len() ); - fail(&owner, &lock, "on_result", json!({"id":0})).await; + fail( + &owner, + &lock, + "on_result", + json!({"id":0}), + "Method on_result is private", + ) + .await; } } #[tokio::test] @@ -166,8 +200,19 @@ async fn unknown_outcomes_stale_requests_and_reconciliation() { call(&owner, &executor, "set_mode", json!({"mode":"unknown"})).await; call(&actor, &lock, "dispatch", json!({"id":0})).await; assert_eq!(state(&lock).await.records[0].status, Status::Unknown); - fail(&actor, &lock, "cancel", json!({"id":0})).await; + fail(&actor, &lock, "cancel", json!({"id":0}), "Pending").await; assert_eq!(state(&lock).await.values[3], 4); + // NT-F2: reconcile is nonpayable like every other mutating method. + fail_paying( + &actor, + &lock, + "reconcile", + json!({"id":0}), + NearToken::from_yoctonear(1), + "Method reconcile doesn't accept deposit", + ) + .await; + assert_eq!(state(&lock).await.records[0].status, Status::Unknown); call(&actor, &lock, "reconcile", json!({"id":0})).await; assert_eq!(state(&lock).await.records[0].status, Status::Active); call( @@ -206,5 +251,588 @@ async fn unknown_outcomes_stale_requests_and_reconciliation() { ) .await; assert_eq!(state(&lock).await.values[3], 0); - fail(&actor, &lock, "observe", json!({"values":[0,0,0,0,0]})).await; + fail( + &actor, + &lock, + "observe", + json!({"values":[0,0,0,0,0]}), + "Unauthorized", + ) + .await; +} +/// F-3: 300 records dispatched and settled end to end. The lock keeps the +/// 256 most recent (first_id 44) and the executor at most 256 jobs. In v1.0.0 +/// the 257th record could not be admitted, and the executor would have +/// panicked "full" at the 257th id. A pruned id is NotFound in the lock and +/// forgotten by the executor. Most records run in reject mode, where the +/// execute result settles them through on_result; ids 0-9 and 290-299 run +/// in normal mode and the operator finishes them. +#[tokio::test] +async fn window_of_300_records_through_the_executor() { + let worker = near_workspaces::sandbox().await.unwrap(); + let owner = worker.dev_create_account().await.unwrap(); + let actor = worker.dev_create_account().await.unwrap(); + let lock = worker.dev_deploy(&wasm("pool_contract")).await.unwrap(); + let executor = worker.dev_deploy(&wasm("pool_executor")).await.unwrap(); + // One record holds one unit of a 10-unit capacity until it ends either way. + let cfg = Config { + name: "window".into(), + owner: owner.id().to_string(), + metrics: vec![Metric { + name: "In flight".into(), + unit: "jobs".into(), + initial: 0, + min: 0, + max: 10, + }], + terms: vec![Term { + metric: 0, + target: 10, + weight: 1, + shape: Shape::Excess, + }], + recipes: vec![Recipe { + name: "job".into(), + actor: actor.id().to_string(), + executor: executor.id().to_string(), + reserve: vec![1], + complete: vec![-1], + max_units: 1, + requires: vec![], + }], + max_age_seconds: 0, + }; + call(lock.as_account(), &lock, "new", json!({"config":cfg})).await; + call( + executor.as_account(), + &executor, + "new", + json!({"lock":lock.id(),"operator":owner.id()}), + ) + .await; + let mut reference = state(&lock).await; + let x = executor.id().as_str(); + let mut mode = "normal"; + for id in 0..300u32 { + let normal = !(10..290).contains(&id); + let wanted = if normal { "normal" } else { "reject" }; + if mode != wanted { + call(&owner, &executor, "set_mode", json!({"mode":wanted})).await; + mode = wanted; + } + let req = Request { + recipe: 0, + units: 1, + version: reference.version, + expires_at: now() + 3600, + }; + let result = call(&actor, &lock, "submit", json!({"request":req})).await; + assert_eq!(result["id"], id, "{result}"); + reference.submit(actor.id().as_str(), req, now()).unwrap(); + call(&actor, &lock, "dispatch", json!({"id":id})).await; + reference.dispatch(actor.id().as_str(), id, now()).unwrap(); + if normal { + reference.acknowledge(id, true).unwrap(); + call( + &owner, + &executor, + "finish", + json!({"id":id,"completed":true}), + ) + .await; + reference.settle(x, id, true).unwrap(); + } else { + reference.settle(x, id, false).unwrap(); + } + if id % 50 == 0 || id == 256 { + assert_eq!(state(&lock).await, reference, "record {id}"); + } + } + let p = state(&lock).await; + assert_eq!(p, reference); + assert_eq!((p.first_id, p.records.len()), (44, 256)); + assert_eq!(p.completed_units, vec![20]); + assert!(p + .records + .iter() + .all(|c| matches!(c.status, Status::Completed | Status::Cancelled))); + let jobs: Vec = executor.view("get_jobs").await.unwrap().json().unwrap(); + let ids: Vec = jobs.iter().map(|j| j["id"].as_u64().unwrap()).collect(); + assert_eq!(ids, (44..300).collect::>()); + let page = |from: u32| { + let lock = &lock; + async move { + let v: Vec = lock + .view("get_commitments") + .args_json(json!({"from":from,"limit":50})) + .await + .unwrap() + .json() + .unwrap(); + v.iter() + .map(|c| c["id"].as_u64().unwrap()) + .collect::>() + } + }; + assert_eq!(page(0).await, (44..94).collect::>()); + assert_eq!(page(290).await, (290..300).collect::>()); + // Pruned id 0: NotFound in the lock, forgotten by the executor. + fail(&actor, &lock, "reconcile", json!({"id":0}), "NotFound").await; + fail(&actor, &lock, "cancel", json!({"id":0}), "NotFound").await; + fail( + &owner, + &executor, + "finish", + json!({"id":0,"completed":true}), + "unknown job", + ) + .await; + fail( + &owner, + &executor, + "confirm_not_executed", + json!({"id":0,"recipe":0,"units":1}), + "stale id", + ) + .await; + let status: String = executor + .view("status") + .args_json(json!({"id":0})) + .await + .unwrap() + .json() + .unwrap(); + assert_eq!(status, "unknown"); + assert_eq!(state(&lock).await, reference); + println!( + "PASS window: first_id {}, {} records, {} executor jobs", + p.first_id, + p.records.len(), + ids.len() + ); +} +/// The executor's job ids, in the order it holds them. +async fn job_ids(executor: &Contract) -> Vec { + let jobs: Vec = executor.view("get_jobs").await.unwrap().json().unwrap(); + jobs.iter().map(|j| j["id"].as_u64().unwrap()).collect() +} +/// D-1 (owner decision Q4): 300 records whose `execute` fails, each confirmed +/// not executed by the operator. The lock accepts each confirmation's settle, +/// and the executor's private callback `on_settled` then moves its newest id, +/// so it holds at most 256 jobs. Before this change it forgot nothing without +/// a successful `execute`: 257 jobs after the confirmation of id 256, and the +/// 512-job cap after 512. Then, on the real host: a refused confirmation +/// keeps its job and the transaction reports the lock's error; `on_settled` +/// is private; a Reserved record confirmed too early is cancelled when it is +/// dispatched, after which `finish(id, false)` moves the newest id; the pool +/// is not wedged. +#[tokio::test] +async fn confirmed_failed_executes_keep_the_executor_at_256_jobs() { + let worker = near_workspaces::sandbox().await.unwrap(); + let owner = worker.dev_create_account().await.unwrap(); + let actor = worker.dev_create_account().await.unwrap(); + let lock = worker.dev_deploy(&wasm("pool_contract")).await.unwrap(); + let executor = worker.dev_deploy(&wasm("pool_executor")).await.unwrap(); + // One record holds one unit of a 10-unit capacity until it ends either way. + let cfg = Config { + name: "confirmations".into(), + owner: owner.id().to_string(), + metrics: vec![Metric { + name: "In flight".into(), + unit: "jobs".into(), + initial: 0, + min: 0, + max: 10, + }], + terms: vec![Term { + metric: 0, + target: 10, + weight: 1, + shape: Shape::Excess, + }], + recipes: vec![Recipe { + name: "job".into(), + actor: actor.id().to_string(), + executor: executor.id().to_string(), + reserve: vec![1], + complete: vec![-1], + max_units: 1, + requires: vec![], + }], + max_age_seconds: 0, + }; + call(lock.as_account(), &lock, "new", json!({"config":cfg})).await; + call( + executor.as_account(), + &executor, + "new", + json!({"lock":lock.id(),"operator":owner.id()}), + ) + .await; + call(&owner, &executor, "set_mode", json!({"mode":"panic"})).await; + let mut reference = state(&lock).await; + let (a, x) = (actor.id().as_str(), executor.id().as_str()); + let mut last = None; + for id in 0..300u32 { + let req = Request { + recipe: 0, + units: 1, + version: reference.version, + expires_at: now() + 3600, + }; + let result = call(&actor, &lock, "submit", json!({"request":req})).await; + assert_eq!(result["id"], id, "{result}"); + reference.submit(a, req, now()).unwrap(); + // execute fails (panic mode), so on_result marks the record Unknown. + call(&actor, &lock, "dispatch", json!({"id":id})).await; + reference.dispatch(a, id, now()).unwrap(); + reference.acknowledge(id, false).unwrap(); + let r = owner + .call(executor.id(), "confirm_not_executed") + .args_json(json!({"id":id,"recipe":0,"units":1})) + .max_gas() + .transact() + .await + .unwrap(); + assert!(r.is_success(), "confirm {id}: {:?}", r.failures()); + reference.settle(x, id, false).unwrap(); + if [0, 50, 100, 150, 200, 250, 255, 256, 257, 299].contains(&id) { + // The bound: the newest id is `id`, so at most 256 jobs remain. + let held = job_ids(&executor).await; + assert_eq!( + held, + (u64::from(id.saturating_sub(255))..=u64::from(id)).collect::>(), + "executor jobs after the confirmation of {id}: {} jobs", + held.len() + ); + assert_eq!(state(&lock).await, reference, "record {id}"); + } + last = Some(r); + } + let p = state(&lock).await; + assert_eq!(p, reference); + assert_eq!((p.first_id, p.records.len()), (44, 256)); + assert!(p.records.iter().all(|c| c.status == Status::Cancelled)); + let jobs: Vec = executor.view("get_jobs").await.unwrap().json().unwrap(); + assert!(jobs.iter().all(|j| j["status"] == "cancelled")); + let window: Vec = (44..300).collect(); + assert_eq!(job_ids(&executor).await, window); + // The confirmation of 299: the executor's call and its on_settled, and + // the lock's settle, all succeed. + let r = last.unwrap(); + let on = |account: &near_workspaces::AccountId| { + r.receipt_outcomes() + .iter() + .filter(|o| &o.executor_id == account) + .map(|o| o.is_success()) + .collect::>() + }; + assert_eq!( + (on(executor.id()), on(lock.id())), + (vec![true, true], vec![true]) + ); + // Forgotten id 43: stale for a confirmation, unknown for finish. + fail( + &owner, + &executor, + "confirm_not_executed", + json!({"id":43,"recipe":0,"units":1}), + "stale id", + ) + .await; + fail( + &owner, + &executor, + "finish", + json!({"id":43,"completed":false}), + "unknown job", + ) + .await; + // A refused confirmation (an unassigned id): the transaction fails with + // the lock's error; on_settled still runs, changes nothing, and the job + // stays (no rollback). + let r = owner + .call(executor.id(), "confirm_not_executed") + .args_json(json!({"id":10_000,"recipe":0,"units":1})) + .max_gas() + .transact() + .await + .unwrap(); + let on = |account: &near_workspaces::AccountId| { + r.receipt_outcomes() + .iter() + .filter(|o| &o.executor_id == account) + .map(|o| o.is_success()) + .collect::>() + }; + assert_eq!( + (on(executor.id()), on(lock.id())), + (vec![true, true], vec![false]) + ); + let text = r.into_result().unwrap_err().to_string(); + assert!( + text.contains("Smart contract panicked: NotFound"), + "refused confirmation: {text}" + ); + let mut held = window.clone(); + held.push(10_000); + assert_eq!(job_ids(&executor).await, held); + assert_eq!(state(&lock).await, reference); + // on_settled is private, and needs the settle's result. An id of 600 + // would forget every job below 345 if either call went through. + fail( + &owner, + &executor, + "on_settled", + json!({"id":600}), + "Method on_settled is private", + ) + .await; + fail( + executor.as_account(), + &executor, + "on_settled", + json!({"id":600}), + "not a settle callback", + ) + .await; + assert_eq!(job_ids(&executor).await, held); + // A Reserved record confirmed too early: the lock refuses (InvalidState), + // the job stays and pre-cancels the id. + call(&owner, &executor, "set_mode", json!({"mode":"normal"})).await; + let req = Request { + recipe: 0, + units: 1, + version: reference.version, + expires_at: now() + 3600, + }; + let result = call(&actor, &lock, "submit", json!({"request":req})).await; + assert_eq!(result["id"], 300, "{result}"); + reference.submit(a, req, now()).unwrap(); + fail( + &owner, + &executor, + "confirm_not_executed", + json!({"id":300,"recipe":0,"units":1}), + "InvalidState", + ) + .await; + assert_eq!(state(&lock).await, reference); + held.push(300); + assert_eq!(job_ids(&executor).await, held, "job 300 pushed, 44 held"); + // Dispatch: execute answers "cancelled" from job 300, so the lock + // cancels the record. An execute that finds a stored job moves no newest + // id, so job 44 stays. + call(&actor, &lock, "dispatch", json!({"id":300})).await; + reference.dispatch(a, 300, now()).unwrap(); + reference.settle(x, 300, false).unwrap(); + let p = state(&lock).await; + assert_eq!(p, reference); + assert_eq!(p.record(300).unwrap().status, Status::Cancelled); + assert_eq!(job_ids(&executor).await, held); + // finish(300, false) is now accepted (a same-outcome no-op at the lock); + // its on_settled raises the newest id to 300 and forgets job 44. + call( + &owner, + &executor, + "finish", + json!({"id":300,"completed":false}), + ) + .await; + reference.settle(x, 300, false).unwrap(); + assert_eq!(state(&lock).await, reference); + let mut held: Vec = (45..300).collect(); + held.extend([10_000, 300]); + assert_eq!(job_ids(&executor).await, held, "finish moved the newest id"); + // Not wedged: the next record runs end to end. + let req = Request { + recipe: 0, + units: 1, + version: reference.version, + expires_at: now() + 3600, + }; + let result = call(&actor, &lock, "submit", json!({"request":req})).await; + assert_eq!(result["id"], 301, "{result}"); + reference.submit(a, req, now()).unwrap(); + call(&actor, &lock, "dispatch", json!({"id":301})).await; + reference.dispatch(a, 301, now()).unwrap(); + reference.acknowledge(301, true).unwrap(); + assert_eq!(state(&lock).await, reference); + let mut held: Vec = (46..300).collect(); + held.extend([10_000, 300, 301]); + assert_eq!(job_ids(&executor).await, held, "execute forgot job 45"); + call( + &owner, + &executor, + "finish", + json!({"id":301,"completed":true}), + ) + .await; + reference.settle(x, 301, true).unwrap(); + let p = state(&lock).await; + assert_eq!(p, reference); + assert_eq!(p.record(301).unwrap().status, Status::Completed); + assert_eq!((p.first_id, p.completed_units.clone()), (46, vec![1])); + println!( + "PASS confirmed failed executes: first_id {}, {} records, at most 256 executor jobs from confirmations, {} jobs at the end", + p.first_id, + p.records.len(), + held.len() + ); +} +/// A Wasm executor whose `execute` returns the JSON number `5` and whose +/// `status` returns a JSON string of 70 bytes. Neither is one JSON string of +/// at most 64 bytes. Hand-assembled: one import (`env.value_return`), one page +/// of memory, two exports, two data segments. +fn non_string_executor() -> Vec { + fn uleb(mut n: usize, out: &mut Vec) { + loop { + let byte = (n & 0x7f) as u8; + n >>= 7; + if n == 0 { + out.push(byte); + return; + } + out.push(byte | 0x80); + } + } + fn bytes(b: &[u8], out: &mut Vec) { + uleb(b.len(), out); + out.extend_from_slice(b); + } + fn section(id: u8, items: &[Vec], out: &mut Vec) { + let mut body = vec![]; + uleb(items.len(), &mut body); + items.iter().for_each(|i| body.extend_from_slice(i)); + out.push(id); + bytes(&body, out); + } + let long = format!("\"{}\"", "a".repeat(68)); + // (offset, data) of each value; offsets and lengths are below 64, so each + // i32.const and i64.const operand is one signed LEB128 byte. + let values: [(u8, &[u8]); 2] = [(0, b"5"), (8, long.as_bytes())]; + assert!(values.iter().all(|(o, d)| *o < 64 && d.len() < 128)); + let mut m = b"\0asm\x01\0\0\0".to_vec(); + // Types: 0 = (i64, i64) -> (), 1 = () -> (). + section(1, &[vec![0x60, 2, 0x7e, 0x7e, 0], vec![0x60, 0, 0]], &mut m); + let mut import = vec![]; + bytes(b"env", &mut import); + bytes(b"value_return", &mut import); + import.extend([0, 0]); + section(2, &[import], &mut m); + section(3, &[vec![1], vec![1]], &mut m); + section(5, &[vec![0, 1]], &mut m); + let export = |name: &[u8], func: u8| { + let mut e = vec![]; + bytes(name, &mut e); + e.extend([0, func]); + e + }; + section(7, &[export(b"execute", 1), export(b"status", 2)], &mut m); + // value_return(len, ptr) with each value, then end. + let body = |(offset, data): (u8, &[u8])| { + let len = data.len() as u8; + // A value of 64 or more needs a second byte as signed LEB128. + let mut code = vec![0, 0x42]; + if len < 64 { + code.push(len); + } else { + code.extend([len, 0]); + code[2] |= 0x80; + } + code.extend([0x42, offset, 0x10, 0, 0x0b]); + let mut b = vec![]; + bytes(&code, &mut b); + b + }; + section(10, &[body(values[0]), body(values[1])], &mut m); + let data = |(offset, d): (u8, &[u8])| { + let mut s = vec![0, 0x41, offset, 0x0b]; + bytes(d, &mut s); + s + }; + section(11, &[data(values[0]), data(values[1])], &mut m); + m +} +/// NT-F4 on the real host: an executor result that is not one JSON string of +/// at most 64 bytes leaves the record Unknown, and the callback does not fail. +#[tokio::test] +async fn non_string_executor_results_leave_the_record_unknown() { + let worker = near_workspaces::sandbox().await.unwrap(); + let owner = worker.dev_create_account().await.unwrap(); + let actor = worker.dev_create_account().await.unwrap(); + let lock = worker.dev_deploy(&wasm("pool_contract")).await.unwrap(); + let executor = worker.dev_deploy(&non_string_executor()).await.unwrap(); + // The executor returns these exact bytes; it does not fail. + let long = format!("\"{}\"", "a".repeat(68)); + for (method, value) in [("execute", "5"), ("status", long.as_str())] { + let r = executor.view(method).await.unwrap(); + assert_eq!(r.result, value.as_bytes(), "{method}"); + } + let mut cfg = fixtures::config("gpu").unwrap(); + cfg.owner = owner.id().to_string(); + for r in &mut cfg.recipes { + r.actor = actor.id().to_string(); + r.executor = executor.id().to_string(); + } + call(lock.as_account(), &lock, "new", json!({"config":cfg})).await; + let mut reference = state(&lock).await; + let req = Request { + recipe: 0, + units: 4, + version: 0, + expires_at: now() + 3600, + }; + assert_eq!( + call(&actor, &lock, "submit", json!({"request":req})).await["id"], + 0 + ); + reference.submit(actor.id().as_str(), req, now()).unwrap(); + let reconciled = |r: &near_workspaces::result::ExecutionFinalResult| -> Vec { + r.logs() + .iter() + .filter_map(|l| l.strip_prefix("EVENT_JSON:")) + .map(|j| serde_json::from_str::(j).unwrap()) + .filter(|e| e["event"] == "reconciled") + .map(|e| e["data"][0].clone()) + .collect() + }; + let expected = vec![json!({"id":0,"outcome":"unknown","error":null})]; + // execute returns 5. + let r = actor + .call(lock.id(), "dispatch") + .args_json(json!({"id":0})) + .max_gas() + .transact() + .await + .unwrap(); + assert!(r.is_success(), "dispatch: {:?}", r.failures()); + assert_eq!(reconciled(&r), expected); + reference.dispatch(actor.id().as_str(), 0, now()).unwrap(); + reference.acknowledge(0, false).unwrap(); + assert_eq!(state(&lock).await, reference); + assert_eq!(reference.records[0].status, Status::Unknown); + // status returns a 70-byte string: still Unknown, no version change. + let r = actor + .call(lock.id(), "reconcile") + .args_json(json!({"id":0})) + .max_gas() + .transact() + .await + .unwrap(); + assert!(r.is_success(), "reconcile: {:?}", r.failures()); + assert_eq!(reconciled(&r), expected); + assert_eq!(state(&lock).await, reference); + // The reservation is held until the executor account reports. + call( + executor.as_account(), + &lock, + "settle", + json!({"id":0,"completed":false}), + ) + .await; + reference.settle(executor.id().as_str(), 0, false).unwrap(); + assert_eq!(state(&lock).await, reference); + assert_eq!(reference.records[0].status, Status::Cancelled); + println!("PASS non-string results: 5 and a 70-byte string leave the record Unknown"); } diff --git a/crates/sandbox/tests/res1.rs b/crates/sandbox/tests/res1.rs new file mode 100644 index 0000000..c6e4af0 --- /dev/null +++ b/crates/sandbox/tests/res1.rs @@ -0,0 +1,1233 @@ +//! RES-1: gas at the largest state, measured on the Wasm that +//! `scripts/build.sh` writes. Slow (about eight minutes), so `scripts/sandbox.sh` +//! skips it. Run it after `scripts/build.sh` with +//! `cargo test -p pool-sandbox --locked --test res1 -- --ignored --nocapture`. +//! It writes `artifacts/res1.json`. The figures in docs/api.md come from it. +//! +//! Adapted from the outside verification's RES-1 sandbox test, which ran on +//! v1.0.0. The configuration has every size at its limit: 32 metrics with +//! 128-byte names and units, 64 terms, 32 recipes with 128-byte names, 64-byte +//! actor and executor ids, full effect vectors, recipe i requires every j < i. +//! The state is built with real transactions only: 31 Completed +//! prerequisites, then recipe-31 reservations of 100 units up to 256 records, +//! then 31 more submits that each prune a Completed front record, so the pool +//! retains 256 open records and the next submit is `Full`. +//! +//! At that state it measures the gas burnt by each receipt, and the least +//! whole Tgas of prepaid gas for `dispatch`, `reconcile`, and the executor's +//! `finish` and `confirm_not_executed`. Every smaller amount from 40 Tgas up +//! must fail with "Exceeded the prepaid gas." in its first receipt, run +//! nothing on the other contract, log nothing, and leave both contracts' raw +//! storage byte-identical and the pool equal to the host-side core. +//! `finish` and `confirm_not_executed` call the lock's `settle` (40 Tgas) and +//! then the executor's private callback `on_settled` (10 Tgas); every +//! measured `on_settled` must burn less than 6 Tgas. +//! +//! Then it fills the executor to its 512-job cap through confirmations the +//! lock refuses (unassigned ids), and measures `status`, `finish` (with its +//! `on_settled`) and `execute` there. +#![allow(clippy::too_many_arguments)] + +use near_workspaces::network::Sandbox; +use near_workspaces::result::{ExecutionFinalResult, ExecutionOutcome}; +use near_workspaces::types::NearToken; +use near_workspaces::{Account, AccountId, Contract, Worker}; +use pool_core::{Config, Metric, Pool, Recipe, Request, Shape, Status, Term, MAX_RECORDS}; +use serde_json::{json, Value}; +use std::collections::HashMap; +use std::path::PathBuf; +use std::time::Instant; + +const TGAS: u64 = 1_000_000_000_000; +const TX_GAS_LIMIT: u64 = 300 * TGAS; +const OUT_OF_GAS: &str = "Exceeded the prepaid gas."; +const N_METRICS: usize = 32; +const N_RECIPES: usize = 32; +/// Gas the executor attaches to its `on_settled`, and the most any measured +/// `on_settled` may burn (so at least 4 Tgas of it remain). +const ON_SETTLED_TGAS: u64 = 10; +const ON_SETTLED_LIMIT: u64 = 6 * TGAS; + +fn root() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../..") +} + +fn wasm(name: &str) -> Vec { + std::fs::read(root().join(format!("target/wasm32-unknown-unknown/release/{name}.wasm"))) + .expect("run scripts/build.sh first") +} + +fn tgas(g: u64) -> f64 { + (g as f64 / TGAS as f64 * 100.0).round() / 100.0 +} + +async fn subaccount(worker: &Worker, name: &str, near: u128) -> Account { + worker + .root_account() + .unwrap() + .create_subaccount(name) + .initial_balance(NearToken::from_near(near)) + .transact() + .await + .unwrap() + .into_result() + .unwrap() +} + +async fn deploy(worker: &Worker, name: &str, near: u128, code: &[u8]) -> Contract { + subaccount(worker, name, near) + .await + .deploy(code) + .await + .unwrap() + .into_result() + .unwrap() +} + +async fn block_now(worker: &Worker) -> u64 { + worker.view_block().await.unwrap().timestamp() / 1_000_000_000 +} + +async fn tx(a: &Account, receiver: &AccountId, method: &str, args: Value) -> ExecutionFinalResult { + a.call(receiver, method) + .args_json(args) + .max_gas() + .transact() + .await + .unwrap_or_else(|e| panic!("{method}: rpc error {e:?}")) +} + +async fn tx_gas( + a: &Account, + receiver: &AccountId, + method: &str, + args: Value, + gas: u64, +) -> ExecutionFinalResult { + a.call(receiver, method) + .args_json(args) + .gas(near_workspaces::types::Gas::from_gas(gas)) + .transact() + .await + .unwrap_or_else(|e| panic!("{method} with {gas} gas: rpc error {e:?}")) +} + +/// The final result must be a success (a failed inner receipt is allowed). +async fn ok(a: &Account, receiver: &AccountId, method: &str, args: Value) -> ExecutionFinalResult { + let r = tx(a, receiver, method, args).await; + assert!(r.is_success(), "{method} failed: {:?}", r.failures()); + r +} + +async fn pool(c: &Contract) -> Pool { + c.view("get_pool").await.unwrap().json().unwrap() +} + +async fn jobs(exec: &Contract) -> Vec { + exec.view("get_jobs").await.unwrap().json().unwrap() +} + +async fn raw_state(worker: &Worker, id: &AccountId) -> HashMap, Vec> { + worker.view_state(id).await.unwrap() +} + +fn events(logs: &[String]) -> Vec { + logs.iter() + .filter_map(|l| l.strip_prefix("EVENT_JSON:")) + .map(|j| serde_json::from_str(j).unwrap()) + .collect() +} + +fn receipts_on<'a>(r: &'a ExecutionFinalResult, account: &AccountId) -> Vec<&'a ExecutionOutcome> { + r.receipt_outcomes() + .iter() + .filter(|o| &o.executor_id == account) + .collect() +} + +/// A `finish` or `confirm_not_executed`: the executor's call and its +/// `on_settled` both succeed, and the lock's `settle` succeeds iff +/// `accepted`. Returns the gas `on_settled` burnt, which must be under +/// ON_SETTLED_LIMIT. +fn on_settled( + what: &str, + r: &ExecutionFinalResult, + exec: &AccountId, + lock: &AccountId, + accepted: bool, +) -> u64 { + let (on_exec, on_lock) = (receipts_on(r, exec), receipts_on(r, lock)); + assert!( + on_exec.len() == 2 && on_exec.iter().all(|o| o.is_success()), + "{what}: executor receipts {:?}", + r.failures() + ); + assert!( + on_lock.len() == 1 && on_lock[0].is_success() == accepted, + "{what}: the lock's settle should {}", + if accepted { "succeed" } else { "fail" } + ); + let g = on_exec[1].gas_burnt.as_gas(); + assert!( + g < ON_SETTLED_LIMIT, + "{what}: on_settled burnt {g} gas, the limit is {ON_SETTLED_LIMIT}" + ); + g +} + +/// The `reconciled` events logged on `account`. +fn reconciled(r: &ExecutionFinalResult, account: &AccountId) -> Vec { + let logs: Vec = receipts_on(r, account) + .iter() + .flat_map(|o| o.logs.clone()) + .collect(); + events(&logs) + .into_iter() + .filter(|e| e["event"] == "reconciled") + .map(|e| e["data"][0].clone()) + .collect() +} + +fn long(c: char, len: usize, tag: usize) -> String { + let t = tag.to_string(); + format!("{}{}", c.to_string().repeat(len - t.len()), t) +} + +fn max_config(owner: &AccountId, actor: &AccountId, executor: &AccountId) -> Config { + let metrics = (0..N_METRICS) + .map(|i| Metric { + name: long('M', 128, i), + unit: long('U', 128, i), + initial: 0, + min: -1_000_000, + max: 1_000_000, + }) + .collect(); + let mut terms = vec![]; + for i in 0..N_METRICS as u32 { + terms.push(Term { + metric: i, + target: 0, + weight: 1000, + shape: Shape::Target, + }); + terms.push(Term { + metric: i, + target: 0, + weight: 1000, + shape: if i % 2 == 0 { + Shape::Excess + } else { + Shape::Deficit + }, + }); + } + let recipes = (0..N_RECIPES) + .map(|i| Recipe { + name: long('R', 128, i), + actor: actor.to_string(), + executor: executor.to_string(), + reserve: vec![0; N_METRICS], + complete: (0..N_METRICS) + .map(|j| if (i + j) % 2 == 0 { 1 } else { -1 }) + .collect(), + max_units: 100, + requires: (0..i as u32).map(|j| (j, 1)).collect(), + }) + .collect(); + Config { + name: long('N', 128, 0), + owner: owner.to_string(), + metrics, + terms, + recipes, + max_age_seconds: 86_400, + } +} + +struct Gas { + rows: Vec, +} + +impl Gas { + /// Records the gas burnt by each receipt of `r` on `on` and the + /// transaction total; returns the largest receipt. `budgets`: for each + /// (i, b), receipt index i (in the order of `on`) must burn less than + /// the static gas b. + fn add( + &mut self, + what: &str, + r: &ExecutionFinalResult, + on: &[(&AccountId, &str)], + budgets: &[(usize, u64)], + ) -> u64 { + let mut receipts = vec![]; + for (account, label) in on { + for o in receipts_on(r, account) { + receipts.push(json!({ "on": label, "gas_tgas": tgas(o.gas_burnt.as_gas()), "gas": o.gas_burnt.as_gas(), "ok": o.is_success() })); + } + } + let max = receipts + .iter() + .map(|v| v["gas"].as_u64().unwrap()) + .max() + .unwrap_or(0); + let total = r.total_gas_burnt.as_gas(); + let mut row = json!({ "call": what, "tx_total_tgas": tgas(total), "receipts": receipts, "margin_to_300_tgas": tgas(TX_GAS_LIMIT - total) }); + let mut checked = vec![]; + for &(i, b) in budgets { + let g = row["receipts"][i]["gas"].as_u64().unwrap(); + checked.push(json!({ "receipt": i, "on": row["receipts"][i]["on"], "attached_budget_tgas": b / TGAS, "margin_to_budget_tgas": tgas(b.saturating_sub(g)) })); + assert!(g < b, "{what}: receipt {i} burnt {g} of its {b} budget"); + } + if !checked.is_empty() { + row["budgets"] = json!(checked); + } + assert!(total < TX_GAS_LIMIT, "{what}: {total} gas"); + eprintln!("RES-1 {row}"); + self.rows.push(row); + max + } +} + +/// `actor` submits recipe 31 x 100 at the reference's version; must be +/// admitted; applied to the reference. Returns (id, outcome). +async fn submit_open( + actor: &Account, + lock: &Contract, + reference: &mut Pool, + expires_at: u64, + now: u64, + curve: &mut Vec<(usize, u32, u64)>, +) -> (u32, ExecutionFinalResult) { + let req = Request { + recipe: 31, + units: 100, + version: reference.version, + expires_at, + }; + let r = ok(actor, lock.id(), "submit", json!({ "request": req })).await; + let v: Value = r.clone().json().unwrap(); + assert_eq!( + v["decision"]["allowed"], + true, + "submit at {} records: {v}", + reference.records.len() + ); + let id = reference.submit(actor.id().as_str(), req, now).unwrap(); + assert_eq!(v["id"], id); + let open = reference + .records + .iter() + .filter(|c| !matches!(c.status, Status::Completed | Status::Cancelled)) + .count(); + curve.push(( + reference.records.len(), + open as u32, + receipts_on(&r, lock.id())[0].gas_burnt.as_gas(), + )); + (id, r) +} + +/// One call with `tgas_prepaid` Tgas. On success returns the outcome. On +/// failure checks that it ran out of gas in its first receipt (on +/// `receiver`) and that nothing else happened; returns the row. +async fn attempt( + worker: &Worker, + signer: &Account, + receiver: &AccountId, + method: &str, + args: &Value, + tgas_prepaid: u64, + lock: &Contract, + exec: &Contract, + reference: &Pool, + id: u32, + status: Status, +) -> Result { + let (pool_raw, exec_raw) = ( + raw_state(worker, lock.id()).await, + raw_state(worker, exec.id()).await, + ); + let r = tx_gas(signer, receiver, method, args.clone(), tgas_prepaid * TGAS).await; + if r.is_success() { + return Ok(r); + } + let what = format!("{method} {args} with {tgas_prepaid} Tgas"); + let failures = r.failures(); + assert_eq!(failures.len(), 1, "{what}: {failures:?}"); + let f = failures[0]; + assert_eq!( + &f.executor_id, receiver, + "{what}: failed on {}", + f.executor_id + ); + let text = format!("{:?}", r.clone().into_result().unwrap_err()); + assert!( + text.contains(OUT_OF_GAS), + "{what}: not an out-of-gas failure: {text}" + ); + assert_eq!( + receipts_on(&r, receiver).len(), + 1, + "{what}: more than one receipt on {receiver}" + ); + for other in [lock.id(), exec.id()] + .into_iter() + .filter(|o| *o != receiver) + { + assert!( + receipts_on(&r, other).is_empty(), + "{what}: a receipt ran on {other}" + ); + } + let logs: Vec = r.logs().iter().map(|l| l.to_string()).collect(); + assert!( + logs.is_empty() && events(&logs).is_empty(), + "{what}: log or event from a failed call: {logs:?}" + ); + assert_eq!( + raw_state(worker, lock.id()).await, + pool_raw, + "{what}: pool storage changed" + ); + assert_eq!( + raw_state(worker, exec.id()).await, + exec_raw, + "{what}: executor storage changed" + ); + let p = pool(lock).await; + assert_eq!(&p, reference, "{what}: pool differs from the reference"); + assert_eq!(p.record(id).unwrap().status, status, "{what}"); + Err(json!({ + "call": method, "args": args, "prepaid_tgas": tgas_prepaid, "ok": false, "failure": OUT_OF_GAS, + "failed_receipt_on": receiver, "failed_receipt_burnt_tgas": tgas(f.gas_burnt.as_gas()), + "receipts_on_other_contract": 0, "events": 0, "pool_storage_unchanged": true, "executor_storage_unchanged": true, + "record_status_after": format!("{status:?}"), + })) +} + +/// The smallest whole-Tgas prepaid gas, counting up from `from`, for which +/// the call succeeds; every smaller amount must fail as `attempt` checks. +async fn min_prepaid( + worker: &Worker, + signer: &Account, + receiver: &AccountId, + method: &str, + args: Value, + from: u64, + lock: &Contract, + exec: &Contract, + reference: &Pool, + id: u32, + status: Status, + rows: &mut Vec, +) -> (u64, ExecutionFinalResult) { + let mut g = from; + loop { + assert!( + g * TGAS <= TX_GAS_LIMIT, + "{method} {args}: no success up to 300 Tgas" + ); + match attempt( + worker, + signer, + receiver, + method, + &args, + g, + lock, + exec, + reference, + id, + status.clone(), + ) + .await + { + Ok(r) => { + eprintln!( + "RES-1 {method} {args}: smallest whole-Tgas prepaid gas that succeeds: {g}" + ); + return (g, r); + } + Err(row) => rows.push(row), + } + g += 1; + } +} + +fn open_count(p: &Pool) -> usize { + p.records + .iter() + .filter(|c| !matches!(c.status, Status::Completed | Status::Cancelled)) + .count() +} + +#[tokio::test] +#[ignore = "slow (about eight minutes); run with --ignored after scripts/build.sh"] +async fn res_1_gas_at_max_state() { + let t0 = Instant::now(); + let worker = near_workspaces::sandbox() + .await + .expect("start near-sandbox"); + let owner = subaccount(&worker, &"o".repeat(54), 40).await; + let actor = subaccount(&worker, &"a".repeat(54), 60).await; + let lock = deploy(&worker, "pool", 50, &wasm("pool_contract")).await; + let exec = deploy(&worker, &"x".repeat(54), 50, &wasm("pool_executor")).await; + assert_eq!( + (actor.id().as_str().len(), exec.id().as_str().len()), + (64, 64) + ); + let cfg = max_config(owner.id(), actor.id(), exec.id()); + cfg.validate().expect("max config validates"); + let r_new = ok( + lock.as_account(), + lock.id(), + "new", + json!({ "config": cfg }), + ) + .await; + let _ = ok( + exec.as_account(), + exec.id(), + "new", + json!({ "lock": lock.id(), "operator": owner.id() }), + ) + .await; + let mut reference: Pool = pool(&lock).await; + assert_eq!( + reference, + Pool::new(cfg.clone(), reference.observed_at).unwrap() + ); + let (a, x, o) = ( + actor.id().to_string(), + exec.id().to_string(), + owner.id().to_string(), + ); + let now = block_now(&worker).await; + let expires_at = now + 3 * 3600; + let pool_on = [(lock.id(), "pool")]; + let both = [(lock.id(), "pool"), (exec.id(), "exec")]; + let mut gas = Gas { rows: vec![] }; + let mut curve: Vec<(usize, u32, u64)> = vec![]; + let mut below = vec![]; + let mut minimum = vec![]; + gas.add("new (max config)", &r_new, &pool_on, &[]); + + // ---- A. 31 Completed prerequisites (recipe i x 1), then open + // recipe-31 reservations of 100 units up to 255 records. + for i in 0..31u32 { + let req = Request { + recipe: i, + units: 1, + version: reference.version, + expires_at, + }; + let r = ok(&actor, lock.id(), "submit", json!({ "request": req })).await; + let v: Value = r.clone().json().unwrap(); + assert_eq!(v["decision"]["allowed"], true, "prerequisite {i}: {v}"); + let id = reference.submit(&a, req, now).unwrap(); + curve.push(( + reference.records.len(), + 1, + receipts_on(&r, lock.id())[0].gas_burnt.as_gas(), + )); + let _ = ok(&actor, lock.id(), "dispatch", json!({ "id": id })).await; + reference.dispatch(&a, id, now).unwrap(); + reference.acknowledge(id, true).unwrap(); + let _ = ok( + &owner, + exec.id(), + "finish", + json!({ "id": id, "completed": true }), + ) + .await; + reference.settle(&x, id, true).unwrap(); + } + assert_eq!(pool(&lock).await, reference, "after prerequisites"); + assert_eq!(&reference.completed_units[..31], &[1u32; 31][..]); + while reference.records.len() < MAX_RECORDS - 1 { + let _ = submit_open(&actor, &lock, &mut reference, expires_at, now, &mut curve).await; + } + assert_eq!(pool(&lock).await, reference, "at 255 records"); + eprintln!("255 records in {:?}", t0.elapsed()); + + // ---- B. Admissions. + let req = Request { + recipe: 31, + units: 100, + version: reference.version, + expires_at, + }; + let r = ok( + &actor, + lock.id(), + "preview", + json!({ "actor": actor.id(), "request": req }), + ) + .await; + let d: Value = r.clone().json().unwrap(); + assert_eq!(d["allowed"], true, "{d}"); + gas.add( + "preview at 255 records, 224 open (as a transaction)", + &r, + &pool_on, + &[], + ); + // #256: 224 open records in the envelope, no prune (v1.0.0's worst case). + let (id, r) = submit_open(&actor, &lock, &mut reference, expires_at, now, &mut curve).await; + assert_eq!((id, reference.first_id), (255, 0)); + gas.add( + "submit #256 (224 open records, no prune)", + &r, + &pool_on, + &[], + ); + // #257: the oldest record (id 0) is Completed, so this submit prunes it. + let (id, r) = submit_open(&actor, &lock, &mut reference, expires_at, now, &mut curve).await; + assert_eq!( + (id, reference.first_id, reference.records.len()), + (256, 1, 256) + ); + gas.add( + "submit #257 (225 open records, prunes id 0)", + &r, + &pool_on, + &[], + ); + assert_eq!(pool(&lock).await, reference, "after the first prune"); + while reference.first_id < 30 { + let _ = submit_open(&actor, &lock, &mut reference, expires_at, now, &mut curve).await; + } + let (id, r) = submit_open(&actor, &lock, &mut reference, expires_at, now, &mut curve).await; + assert_eq!((id, reference.first_id), (286, 31)); + let submit_max = gas.add( + "submit #287 (255 open records, prunes the last Completed record)", + &r, + &pool_on, + &[], + ); + assert_eq!(open_count(&reference), 256); + assert_eq!(pool(&lock).await, reference, "256 open records"); + // Full: the oldest retained record (id 31) is open. + let req = Request { + recipe: 31, + units: 100, + version: reference.version, + expires_at, + }; + let r = ok(&actor, lock.id(), "submit", json!({ "request": req })).await; + let v: Value = r.clone().json().unwrap(); + assert_eq!( + (v["decision"]["reason"].as_str(), v["id"].is_null()), + (Some("Full"), true), + "{v}" + ); + gas.add( + "submit #288 (rejected Full: the oldest record is open)", + &r, + &pool_on, + &[], + ); + assert_eq!(pool(&lock).await, reference, "after Full"); + + // Reads. + let r = ok(&actor, lock.id(), "get_pool", json!({})).await; + let json_len = r.clone().into_result().unwrap().raw_bytes().unwrap().len(); + let get_pool_tx = gas.add("get_pool (as a transaction)", &r, &pool_on, &[]); + let r = ok( + &actor, + lock.id(), + "get_commitments", + json!({ "from": 0, "limit": 1000 }), + ) + .await; + let page: Vec = r.clone().json().unwrap(); + assert_eq!( + (page.len(), page[0]["id"].as_u64(), page[49]["id"].as_u64()), + (50, Some(31), Some(80)) + ); + gas.add( + "get_commitments(0, 1000) -> ids 31..80 (as a transaction)", + &r, + &pool_on, + &[], + ); + let state_bytes = raw_state(&worker, lock.id()) + .await + .get(b"STATE".as_slice()) + .map(Vec::len) + .unwrap(); + let storage_usage = lock.view_account().await.unwrap().storage_usage; + + // ---- C. Owner calls and a release at 256 open records. + for paused in [true, false] { + let r = ok(&owner, lock.id(), "set_paused", json!({ "paused": paused })).await; + reference.set_paused(&o, paused).unwrap(); + gas.add( + &format!("set_paused({paused}), 256 open records"), + &r, + &pool_on, + &[], + ); + } + let r = ok( + &owner, + lock.id(), + "observe", + json!({ "values": reference.values }), + ) + .await; + let chain = pool(&lock).await; + reference + .observe(&o, reference.values.clone(), chain.observed_at) + .unwrap(); + assert_eq!(chain, reference, "after the refresh"); + gas.add( + "observe (restates the values), 256 open records", + &r, + &pool_on, + &[], + ); + // cancel the oldest record: its release is checked against 255 other open records. + let r = ok(&actor, lock.id(), "cancel", json!({ "id": 31 })).await; + reference.cancel(&a, 31, now).unwrap(); + gas.add( + "cancel (release; 255 other open records)", + &r, + &pool_on, + &[], + ); + let (id, r) = submit_open(&actor, &lock, &mut reference, expires_at, now, &mut curve).await; + assert_eq!( + (id, reference.first_id, open_count(&reference)), + (287, 32, 256) + ); + gas.add( + "submit #288 after the cancel (255 open records, prunes id 31)", + &r, + &pool_on, + &[], + ); + assert_eq!(pool(&lock).await, reference, "256 open records again"); + + // ---- D. Prepaid gas sweeps at 256 open records. + assert_eq!( + jobs(&exec).await.len(), + 31, + "executor jobs before the dispatch sweep" + ); + let (ra, rb, rc) = (287u32, 286u32, 285u32); + let (min_dispatch, r) = min_prepaid( + &worker, + &actor, + lock.id(), + "dispatch", + json!({ "id": ra }), + 40, + &lock, + &exec, + &reference, + ra, + Status::Reserved, + &mut below, + ) + .await; + reference.dispatch(&a, ra, now).unwrap(); + reference.acknowledge(ra, true).unwrap(); + assert_eq!( + pool(&lock).await, + reference, + "after dispatch at the minimum" + ); + let dispatch_burnt = receipts_on(&r, lock.id())[0].gas_burnt.as_gas(); + gas.add( + &format!("dispatch #{ra} with {min_dispatch} Tgas prepaid (the minimum)"), + &r, + &both, + &[(1, 30 * TGAS)], + ); + minimum.push(json!({ + "call": "dispatch", "state": "pool 256 records, all open (Reserved); executor 31 jobs", + "min_prepaid_tgas": min_dispatch, "fails_at_tgas": format!("40..={}", min_dispatch - 1), + "static_gas_attached_tgas": "execute 30 + on_result 30", "first_receipt_burnt_tgas": tgas(dispatch_burnt), + })); + for g in [40, min_dispatch - 1] { + let row = attempt( + &worker, + &actor, + lock.id(), + "dispatch", + &json!({ "id": rb }), + g, + &lock, + &exec, + &reference, + rb, + Status::Reserved, + ) + .await + .expect_err("dispatch below the minimum succeeded on a second record"); + below.push(row); + } + let r = ok(&actor, lock.id(), "dispatch", json!({ "id": rb })).await; + reference.dispatch(&a, rb, now).unwrap(); + reference.acknowledge(rb, true).unwrap(); + gas.add( + &format!("dispatch #{rb} with 300 Tgas after failed low-gas attempts"), + &r, + &both, + &[(1, 30 * TGAS)], + ); + let r = tx_gas( + &actor, + lock.id(), + "dispatch", + json!({ "id": rc }), + min_dispatch * TGAS, + ) + .await; + assert!( + r.is_success(), + "dispatch #{rc} with {min_dispatch} Tgas: {:?}", + r.failures() + ); + reference.dispatch(&a, rc, now).unwrap(); + reference.acknowledge(rc, true).unwrap(); + assert_eq!(pool(&lock).await, reference); + gas.add( + &format!("dispatch #{rc} with {min_dispatch} Tgas prepaid (the minimum, again)"), + &r, + &both, + &[(1, 30 * TGAS)], + ); + + let (min_reconcile, r) = min_prepaid( + &worker, + &owner, + lock.id(), + "reconcile", + json!({ "id": ra }), + 40, + &lock, + &exec, + &reference, + ra, + Status::Active, + &mut below, + ) + .await; + assert_eq!( + pool(&lock).await, + reference, + "reconcile of an Active record is a no-op" + ); + gas.add( + &format!("reconcile #{ra} with {min_reconcile} Tgas prepaid (the minimum)"), + &r, + &both, + &[(1, 30 * TGAS)], + ); + minimum.push(json!({ + "call": "reconcile", "state": "pool 256 records, all open, record Active; executor 3 jobs", + "min_prepaid_tgas": min_reconcile, "fails_at_tgas": format!("40..={}", min_reconcile - 1), + "static_gas_attached_tgas": "status 10 + on_result 30", "first_receipt_burnt_tgas": tgas(receipts_on(&r, lock.id())[0].gas_burnt.as_gas()), + })); + + // on_result that releases (execute returns "cancelled"): checked against 255 other open records. + let _ = ok(&owner, exec.id(), "set_mode", json!({ "mode": "reject" })).await; + let r = ok(&actor, lock.id(), "dispatch", json!({ "id": 284 })).await; + reference.dispatch(&a, 284, now).unwrap(); + reference.settle(&x, 284, false).unwrap(); + assert_eq!(pool(&lock).await, reference, "on_result released 284"); + assert_eq!( + reconciled(&r, lock.id()), + vec![json!({ "id": 284, "outcome": "cancelled", "error": null })] + ); + gas.add( + "dispatch, execute returns cancelled, on_result releases (255 other open records)", + &r, + &both, + &[(1, 30 * TGAS)], + ); + // on_result for a failed execute: Unknown. + let _ = ok(&owner, exec.id(), "set_mode", json!({ "mode": "panic" })).await; + let r = ok(&actor, lock.id(), "dispatch", json!({ "id": 283 })).await; + reference.dispatch(&a, 283, now).unwrap(); + reference.acknowledge(283, false).unwrap(); + assert_eq!(pool(&lock).await, reference, "283 Unknown"); + gas.add( + "dispatch, execute fails, on_result marks Unknown", + &r, + &both, + &[(1, 30 * TGAS)], + ); + let _ = ok(&owner, exec.id(), "set_mode", json!({ "mode": "normal" })).await; + + // ---- E. The executor at its retention bound (256 jobs: ids 32..=287). + for id in 32..282u32 { + let _ = ok(&actor, lock.id(), "dispatch", json!({ "id": id })).await; + reference.dispatch(&a, id, now).unwrap(); + reference.acknowledge(id, true).unwrap(); + if id % 32 == 0 { + assert_eq!(pool(&lock).await, reference, "at record {id}"); + } + } + assert_eq!(pool(&lock).await, reference, "254 jobs"); + assert_eq!(jobs(&exec).await.len(), 254); + eprintln!("254 jobs in {:?}", t0.elapsed()); + // confirm_not_executed of 283 (Unknown, no job): 254 -> 255 jobs, then settle(false). + let (min_confirm, r) = min_prepaid( + &worker, + &owner, + exec.id(), + "confirm_not_executed", + json!({ "id": 283, "recipe": 31, "units": 100 }), + 40, + &lock, + &exec, + &reference, + 283, + Status::Unknown, + &mut below, + ) + .await; + reference.settle(&x, 283, false).unwrap(); + assert_eq!(pool(&lock).await, reference, "after confirm at the minimum"); + // The executor's receipts (its call, then on_settled), then the lock's settle. + let exec_first = [(exec.id(), "exec"), (lock.id(), "pool")]; + let notify_budgets = [(1, ON_SETTLED_TGAS * TGAS), (2, 40 * TGAS)]; + gas.add(&format!("confirm_not_executed with {min_confirm} Tgas prepaid (the minimum) -> settle(false) [40 Tgas], on_settled [10 Tgas]"), &r, &exec_first, ¬ify_budgets); + let on_settled_after_confirm = on_settled("confirm 283", &r, exec.id(), lock.id(), true); + minimum.push(json!({ + "call": "confirm_not_executed (executor)", "state": "executor 254 jobs (255 after); pool 256 records, 254 open, the record Unknown", + "min_prepaid_tgas": min_confirm, "fails_at_tgas": format!("40..={}", min_confirm - 1), + "static_gas_attached_tgas": "settle 40 + on_settled 10", "first_receipt_burnt_tgas": tgas(receipts_on(&r, exec.id())[0].gas_burnt.as_gas()), + "on_settled_burnt_tgas": tgas(on_settled_after_confirm), + })); + // The 256th job. + let last = 282u32; + let r = ok(&actor, lock.id(), "dispatch", json!({ "id": last })).await; + reference.dispatch(&a, last, now).unwrap(); + reference.acknowledge(last, true).unwrap(); + assert_eq!(pool(&lock).await, reference); + gas.add( + "dispatch at the retention bound (exec.execute: 255 jobs -> 256)", + &r, + &both, + &[(1, 30 * TGAS)], + ); + let execute_256 = receipts_on(&r, exec.id())[0].gas_burnt.as_gas(); + assert!(execute_256 < 30 * TGAS); + let js = jobs(&exec).await; + let mut ids: Vec = js.iter().map(|j| j["id"].as_u64().unwrap()).collect(); + assert_eq!(js.last().unwrap()["id"].as_u64(), Some(last as u64)); + ids.sort(); + assert_eq!( + ids, + (32..=287).collect::>(), + "executor holds exactly the window" + ); + let r = ok(&owner, lock.id(), "reconcile", json!({ "id": last })).await; + assert_eq!( + pool(&lock).await, + reference, + "reconcile of an Active record is a no-op" + ); + gas.add( + "reconcile at the retention bound (exec.status: 256 jobs, the job is last)", + &r, + &both, + &[(1, 30 * TGAS)], + ); + let status_256 = receipts_on(&r, exec.id())[0].gas_burnt.as_gas(); + assert!(status_256 < 10 * TGAS); + let (min_finish, r) = min_prepaid( + &worker, + &owner, + exec.id(), + "finish", + json!({ "id": last, "completed": true }), + 40, + &lock, + &exec, + &reference, + last, + Status::Active, + &mut below, + ) + .await; + reference.settle(&x, last, true).unwrap(); + assert_eq!(pool(&lock).await, reference, "after finish at the minimum"); + gas.add(&format!("finish at the retention bound with {min_finish} Tgas prepaid (the minimum) -> settle(true) [40 Tgas], on_settled [10 Tgas]"), &r, &exec_first, ¬ify_budgets); + let finish_256 = receipts_on(&r, exec.id())[0].gas_burnt.as_gas(); + let on_settled_256 = on_settled("finish 282", &r, exec.id(), lock.id(), true); + minimum.push(json!({ + "call": "finish (executor)", "state": "executor 256 jobs (the last job); pool 256 records, 253 open", + "min_prepaid_tgas": min_finish, "fails_at_tgas": format!("40..={}", min_finish - 1), + "static_gas_attached_tgas": "settle 40 + on_settled 10", "first_receipt_burnt_tgas": tgas(finish_256), + "on_settled_burnt_tgas": tgas(on_settled_256), + })); + // settle both ways by the executor key. + for (id, completed) in [(100u32, true), (101u32, false)] { + let r = ok( + exec.as_account(), + lock.id(), + "settle", + json!({ "id": id, "completed": completed }), + ) + .await; + reference.settle(&x, id, completed).unwrap(); + gas.add( + &format!("settle({completed}) by the executor key (about 250 other open records)"), + &r, + &pool_on, + &[], + ); + } + assert_eq!(pool(&lock).await, reference, "256 jobs, final"); + let exec_state = raw_state(&worker, exec.id()) + .await + .get(b"STATE".as_slice()) + .map(Vec::len) + .unwrap(); + + // ---- F. The executor at its job cap (512), the largest state it can + // reach. An accepted confirmation moves the executor's newest id (its + // on_settled), so honest use no longer gets here: only confirmations the + // lock refuses (operator error) or confirmations whose on_settled has not + // run yet do, and the executor's work is the same either way, so this + // bounds every reachable state. The cheapest route: the operator confirms + // the 256 ids 289..=544, above the newest id (287), that the lock has not + // assigned. Each adds a "cancelled" job; its settle fails NotFound on the + // lock, which changes nothing there, and its on_settled takes the refused + // branch. The final state, 256 jobs at or below the newest id and 256 + // refused jobs above it, is the operator-error case of docs/api.md's + // executor protocol. + let (mut confirm_512, mut on_settled_refused) = (0, 0); + for id in 289..=544u32 { + let r = tx( + &owner, + exec.id(), + "confirm_not_executed", + json!({ "id": id, "recipe": 31, "units": 100 }), + ) + .await; + let g = on_settled(&format!("confirm {id}"), &r, exec.id(), lock.id(), false); + on_settled_refused = on_settled_refused.max(g); + let text = format!("{:?}", r.clone().into_result().unwrap_err()); + assert!(text.contains("NotFound"), "confirm {id}: {text}"); + if id == 544 { + confirm_512 = receipts_on(&r, exec.id())[0].gas_burnt.as_gas(); + gas.add("confirm_not_executed of an unassigned id, 511 jobs -> 512 (the lock's settle fails NotFound; on_settled changes nothing)", &r, &exec_first, ¬ify_budgets); + } + } + assert_eq!(jobs(&exec).await.len(), 512); + assert_eq!( + pool(&lock).await, + reference, + "the confirmations changed nothing on the lock" + ); + eprintln!("512 jobs in {:?}", t0.elapsed()); + // One more confirmation fails "full" on the executor and never reaches the lock. + let r = tx( + &owner, + exec.id(), + "confirm_not_executed", + json!({ "id": 545, "recipe": 31, "units": 100 }), + ) + .await; + let text = format!("{:?}", r.clone().into_result().unwrap_err()); + assert!( + text.contains("full") && receipts_on(&r, lock.id()).is_empty(), + "{text}" + ); + assert_eq!(jobs(&exec).await.len(), 512); + let exec_state_512 = raw_state(&worker, exec.id()) + .await + .get(b"STATE".as_slice()) + .map(Vec::len) + .unwrap(); + // status with 512 jobs: reconcile of an Active record changes nothing. + let r = ok(&owner, lock.id(), "reconcile", json!({ "id": 281 })).await; + assert_eq!( + pool(&lock).await, + reference, + "reconcile at the job cap is a no-op" + ); + gas.add( + "reconcile at the job cap (exec.status: 512 jobs)", + &r, + &both, + &[(1, 30 * TGAS)], + ); + let status_512 = receipts_on(&r, exec.id())[0].gas_burnt.as_gas(); + assert!(status_512 < 10 * TGAS); + // finish with 512 jobs: the least prepaid gas. + let (min_finish_512, r) = min_prepaid( + &worker, + &owner, + exec.id(), + "finish", + json!({ "id": 281, "completed": true }), + 40, + &lock, + &exec, + &reference, + 281, + Status::Active, + &mut below, + ) + .await; + reference.settle(&x, 281, true).unwrap(); + assert_eq!(pool(&lock).await, reference, "after finish at the job cap"); + gas.add(&format!("finish at the job cap with {min_finish_512} Tgas prepaid (the minimum) -> settle(true) [40 Tgas], on_settled [10 Tgas]"), &r, &exec_first, ¬ify_budgets); + let finish_512 = receipts_on(&r, exec.id())[0].gas_burnt.as_gas(); + // Accepted: on_settled scans and rewrites all 512 jobs. + let on_settled_512 = on_settled("finish 281", &r, exec.id(), lock.id(), true); + assert_eq!(jobs(&exec).await.len(), 512, "finish 281 forgot nothing"); + minimum.push(json!({ + "call": "finish (executor) at the job cap", "state": "executor 512 jobs; pool 256 records, 251 open", + "min_prepaid_tgas": min_finish_512, "fails_at_tgas": format!("40..={}", min_finish_512 - 1), + "static_gas_attached_tgas": "settle 40 + on_settled 10", "first_receipt_burnt_tgas": tgas(finish_512), + "on_settled_burnt_tgas": tgas(on_settled_512), + })); + // execute of a new id with 512 jobs: finish the front record (32), submit + // (prunes it, id 288) and dispatch. execute forgets job 32 and adds 288. + let _ = ok( + &owner, + exec.id(), + "finish", + json!({ "id": 32, "completed": true }), + ) + .await; + reference.settle(&x, 32, true).unwrap(); + let (id, _) = submit_open(&actor, &lock, &mut reference, expires_at, now, &mut curve).await; + assert_eq!((id, reference.first_id), (288, 33)); + let r = ok(&actor, lock.id(), "dispatch", json!({ "id": 288 })).await; + reference.dispatch(&a, 288, now).unwrap(); + reference.acknowledge(288, true).unwrap(); + assert_eq!( + pool(&lock).await, + reference, + "after dispatch at the job cap" + ); + gas.add( + "dispatch at the job cap (exec.execute: 512 jobs, forgets id 32, adds 288)", + &r, + &both, + &[(1, 30 * TGAS)], + ); + let execute_512 = receipts_on(&r, exec.id())[0].gas_burnt.as_gas(); + assert!(execute_512 < 30 * TGAS); + let ids: Vec = jobs(&exec) + .await + .iter() + .map(|j| j["id"].as_u64().unwrap()) + .collect(); + assert_eq!(ids.len(), 512); + assert!(!ids.contains(&32) && ids.contains(&288)); + assert_eq!(pool(&lock).await, reference, "final"); + + let on_settled_max = [ + on_settled_after_confirm, + on_settled_256, + on_settled_512, + on_settled_refused, + ] + .into_iter() + .max() + .unwrap(); + let on_settled_margin = ON_SETTLED_TGAS * TGAS - on_settled_max; + eprintln!( + "RES-1 on_settled: after confirm {}, at 256 jobs {}, at 512 jobs {}, refused (max) {}; margin {} of {ON_SETTLED_TGAS} Tgas", + tgas(on_settled_after_confirm), + tgas(on_settled_256), + tgas(on_settled_512), + tgas(on_settled_refused), + tgas(on_settled_margin) + ); + let worst = gas + .rows + .iter() + .filter(|r| !r["call"].as_str().unwrap().starts_with("new")) + .flat_map(|r| { + r["receipts"] + .as_array() + .unwrap() + .iter() + .filter(|x| x["on"] == "pool") + .map(|x| x["gas"].as_u64().unwrap()) + }) + .max() + .unwrap(); + let table: Vec = minimum + .iter() + .map(|m| { + format!( + "{:<32} min {:>3} Tgas, fails at {:>8}, first receipt {:>5} Tgas, {}", + m["call"].as_str().unwrap(), + m["min_prepaid_tgas"], + m["fails_at_tgas"].as_str().unwrap(), + m["first_receipt_burnt_tgas"], + m["state"].as_str().unwrap() + ) + }) + .collect(); + eprintln!( + "RES-1 minimum prepaid gas (whole Tgas):\n{}", + table.join("\n") + ); + for row in &gas.rows { + let rs: Vec = row["receipts"] + .as_array() + .unwrap() + .iter() + .map(|r| format!("{} {}", r["on"].as_str().unwrap(), r["gas_tgas"])) + .collect(); + eprintln!( + "RES-1 {:<100} tx {:>6} Tgas | {}", + row["call"].as_str().unwrap(), + row["tx_total_tgas"], + rs.join(", ") + ); + } + let curve_rows: Vec = curve + .iter() + .enumerate() + .filter(|(i, _)| *i == 0 || *i % 32 == 31 || *i >= 254) + .map(|(i, (n, open, g))| json!({ "submit": i + 1, "records_after": n, "open_after": open, "pool_receipt_tgas": tgas(*g) })) + .collect(); + let out = json!({ + "property": "RES-1", + "result": "pass", + "build": std::fs::read(root().join("artifacts/build.json")).ok().and_then(|b| serde_json::from_slice::(&b).ok()), + "state": { + "metrics": 32, "terms": 64, "recipes": 32, "max_requires": 31, "records": 256, "open_at_full": 256, + "state_bytes_at_full": state_bytes, "storage_usage_bytes_at_full": storage_usage, "get_pool_json_bytes_at_full": json_len, + "executor_state_bytes_at_256_jobs": exec_state, "executor_state_bytes_at_512_jobs": exec_state_512, "built_by": "real transactions only", + }, + "worst_pool_receipt_tgas": tgas(worst), + "submit_287_pool_receipt_tgas": tgas(submit_max), + "get_pool_tx_tgas": tgas(get_pool_tx), + "minimum_prepaid_gas": minimum, + "executor": { + "execute_256th_tgas": tgas(execute_256), "status_at_256_tgas": tgas(status_256), "finish_last_of_256_tgas": tgas(finish_256), + "confirm_511_to_512_tgas": tgas(confirm_512), "status_at_512_tgas": tgas(status_512), "finish_at_512_tgas": tgas(finish_512), + "finish_min_prepaid_at_512_tgas": min_finish_512, "execute_at_512_tgas": tgas(execute_512), + "confirm_min_prepaid_tgas": min_confirm, "finish_min_prepaid_at_256_tgas": min_finish, + "on_settled_after_confirm_tgas": tgas(on_settled_after_confirm), "on_settled_at_256_tgas": tgas(on_settled_256), + "on_settled_at_512_tgas": tgas(on_settled_512), "on_settled_refused_tgas": tgas(on_settled_refused), + "on_settled_attached_tgas": ON_SETTLED_TGAS, "on_settled_margin_tgas": tgas(on_settled_margin), + }, + "calls": gas.rows, + "submit_gas_by_submit": curve_rows, + "below_minimum_attempts": below, + "seconds": t0.elapsed().as_secs(), + }); + let text = serde_json::to_string_pretty(&out).unwrap() + "\n"; + let path = root().join("artifacts/res1.json"); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(&path, &text).unwrap(); + eprintln!("wrote {} after {:?}", path.display(), t0.elapsed()); +} diff --git a/docs/api.md b/docs/api.md index 5d6f609..3ef1c47 100644 --- a/docs/api.md +++ b/docs/api.md @@ -1,21 +1,23 @@ # NEAR API -One immutable pool per deployment. All mutating methods are nonpayable; fund storage by transferring NEAR to the deployment account separately. Local demonstration credits have no relationship to attached deposits. +This page describes v1.1.0. Changes from v1.0.0 are listed in the [changelog](../CHANGELOG.md). + +One immutable pool per deployment. All mutating methods are nonpayable, including `reconcile`; fund storage by transferring NEAR to the deployment account separately. The read methods (`get_pool`, `get_commitments`, `preview`, and the executor's `status` and `get_jobs`) are meant for view calls. They have no deposit check, so one sent as a transaction keeps any attached deposit; do not attach one. Local demonstration credits have no relationship to attached deposits. | Method | Arguments | Authority / result | |---|---|---| | `new` | `{config}` | Private initializer: only the deployment account itself. One-time init. | -| `get_pool` | `{}` | Entire bounded state, including immutable policy and up to 256 records. | -| `get_commitments` | `{from,limit}` | Read page, max 50. | +| `get_pool` | `{}` | Entire bounded state: immutable policy, the 256 most recent records, `first_id` (id of the oldest retained record) and `completed_units` (per recipe, over the pool's life). | +| `get_commitments` | `{from,limit}` | Read page, max 50, from id `from`. Ids below `first_id` were pruned; a page starting there begins at `first_id`. | | `preview` | `{actor,request}` | Advisory Decision; actor is only a hypothetical identity. | | `submit` | `{request}` | Predecessor must equal recipe actor. Returns `{decision,id}`; no id on rejection. | | `dispatch` | `{id}` | Recipe actor; Reserved -> Dispatched and calls fixed executor. | | `reconcile` | `{id}` | Anyone may query the fixed executor; private callback applies authentic result. | | `settle` | `{id,completed}` | Only that recipe's executor; false means definitive nonexecution, never unknown. | -| `cancel` | `{id}` | Actor or owner; only undispatched Reserved records. | +| `cancel` | `{id}` | Actor or owner; only undispatched Reserved records. Dispatched, Active or Unknown: `Pending`. Completed: `InvalidState`. Already Cancelled: Ok, no change. | | `set_paused` | `{paused}` | Owner; blocks admission and dispatch. | -| `observe` | `{values}` | Owner; no unresolved commitments. May raise energy. | -| `on_result` | `{id}` plus runtime promise result | Private callback, not a public evidence submission endpoint. | +| `observe` | `{values}` | Owner; new values only when every record is terminal. Restating the current values is allowed at any time and renews the snapshot timestamp. May raise energy. | +| `on_result` | `{id}` plus runtime promise result | Private callback, not a public evidence submission endpoint. It never panics on its input: a result for an id with no record changes nothing and is logged (`reconciled` with `error: "NotFound"`). | Request example: @@ -23,24 +25,45 @@ Request example: {"recipe":0,"units":4,"version":0,"expires_at":1794500000} ``` -Use the current version from `get_pool` and an expiry 10 minutes ahead; the example timestamp is illustrative. Maximum is 24 hours. `preview` and `submit` return the same decision structure. If version changed, reload and re-preview. Every successful state transition changes version; terminal duplicate settlement is idempotent. +A submit prunes the oldest retained record when 256 are retained and it is terminal; while it is open, submit fails `Full`, even if the other 255 are terminal. A Reserved oldest record can be cancelled by its actor or the owner. A Dispatched, Active or Unknown one closes only when its executor reports (`settle`, or a `reconcile` that returns `completed` or `cancelled`), so an executor that never reports keeps submit at `Full`. Every call on a pruned id fails `NotFound`, including a repeated executor `settle` (v1.0.0 returned Ok). The event log keeps pruned records. + +Use the current version from `get_pool` and an expiry 10 minutes ahead; the example timestamp is illustrative. Maximum is 24 hours. `preview` and `submit` return the same decision structure. If version changed, reload and re-preview. Every effective state transition increments version by exactly 1. Calls that change nothing return Ok and leave the version alone: a repeated terminal settlement, a repeated cancel, an acknowledgment that does not change the status, a late acknowledgment. Submit, dispatch, pause and observe stop 768 versions below u32::MAX (`Arithmetic`); acknowledgment, settlement and cancellation always remain available. Decision fields: `allowed`, `reason`, decimal-string `before` and optional `after`, decimal-string per-term scores, candidate metric vector. Reasons include Unauthorized, Paused, Stale, Expired, SnapshotExpired, InvalidRecipe, InvalidUnits, Prerequisite, Full, Arithmetic, Bounds, Energy. `after` can be present for a rejected request to explain its prospective score; it is not accepted state. +Events are logged as `EVENT_JSON:{"standard":"shared_pool","version":"1.0.0","event":...,"data":[...]}`. The kinds are `decision` (every submit, admitted or not), `reconciled`, `settled`, `cancelled`, `paused` and `observed`. `version` is the event format version, not the package version. It stays `1.0.0` in v1.1.0 because no event shape changed; `reconciled` can now carry `error: "NotFound"`. + There is no `dampen` mutation: a caller previews an explicit reduced quantity and signs a new exact request. Date changes and substitutions use separate recipes, never silent terms changes. ## Executor protocol -`execute({id,recipe,units}) -> "active" | "cancelled" | "unknown"`. Only the lock may call. `status({id})` additionally returns `"completed"`. Runtime failures and unexpected strings become Unknown in the wrapper. Fixed executor identity plus immutable recipe/quantity bind dispatch to the reservation. A production adapter must implement idempotency, authoritative cancellation and fill semantics. +`execute({id,recipe,units}) -> "active" | "cancelled" | "unknown"`. Only the lock may call. `status({id})` additionally returns `"completed"`. In the wrapper, any result that is not one JSON string of at most 64 bytes becomes Unknown: a runtime failure, a number, `null`, an object, invalid bytes, a longer result. So does an unexpected string. Fixed executor identity plus immutable recipe/quantity bind dispatch to the reservation. A production adapter must implement idempotency, authoritative cancellation and fill semantics. + +The synthetic adapter has `new({lock,operator})`, `set_mode({mode})`, `finish({id,completed})`, `confirm_not_executed({id,recipe,units})`, `get_jobs({})`, and the private callback `on_settled({id})`. Modes normal/reject/unknown/panic support fault injection. These are testing features, not a real asset gateway. It forgets a job once its id is 256 or more behind its newest id: the largest id for which the lock's `execute` created a job, or whose `settle` from this executor the lock accepted. Either way the lock held that record then, so it has pruned every id 256 or more below. An `execute` of an id that already has a job (a repeat, or a confirmation's job) returns the stored status and moves nothing. `execute` of a forgotten id returns `"cancelled"` and starts nothing; `confirm_not_executed` of one fails `stale id`, and `finish` fails `unknown job`. `finish` and `confirm_not_executed` record the job's outcome first, then call the lock's `settle`; the call's result is the lock's (success, or the lock's error such as `NotFound`). `on_settled` then runs on the executor and, if the lock accepted, raises the newest id. If the lock refused, nothing else changes and the job stays: it is the executor's evidence. Job ids are distinct, so at most 256 jobs have ids at or below the newest id; every other job is a confirmation above it whose callback has not run, or that the lock refused. Honest use holds at most 256 jobs plus confirmations in flight. The lock refuses a confirmation of an unassigned or pruned id (`NotFound`), of a record still Reserved (`InvalidState`), of one whose other outcome is recorded (`InvalidState`), or of another executor's recipe (`Unauthorized`). Such a job is forgotten only once the newest id is 256 or more past its id; for an id the lock never reaches, such as a typo of 1000000, that is never, and no method removes it. It also makes that id's later `execute` return `"cancelled"`: a Reserved record confirmed too early is cancelled when it is dispatched (if the confirmation's recipe or units differ from the record's, that `execute` fails `payload mismatch` instead and the record goes Unknown); either way, `finish({id, completed:false})` is accepted and moves the newest id. It holds at most 512 jobs, so the cap is reached only with at least 256 jobs above the newest id (more if fewer sit at or below it). At the cap `confirm_not_executed` fails `full`, and so does an `execute` that frees no job. While it is full, an `execute` that fails before reaching it leaves its record Unknown, and that record cannot be confirmed. If that goes on until the lock holds 256 records, the oldest of them is such a record and none is Reserved, then submit fails `Full`, nothing can be dispatched, and no new `execute` can arrive. The exits are a `settle` signed by the executor account's own key, or an accepted `finish({id, completed:false})` of a refused job whose record the lock now holds as cancelled or open, which raises the newest id and can free space. A production adapter needs its own retention rule. + +## Gas + +Attach at least this much prepaid gas. The figures were measured on the v1.1 Wasm in near-sandbox 2.13.4, at a maximum-size state: 32 metrics, 64 terms, 32 recipes (one requires the other 31), and 256 retained records: all open for `dispatch` and `reconcile`, 251 to 254 open for the executor calls. For `finish` the executor held 256 jobs, and then 512, its cap. Each Attach figure is a round number at least 10 Tgas above the least that succeeded. The margins are 30 Tgas for `dispatch`, which attaches the most gas to its promises; 14 for `reconcile`; 14 or more for `finish` and `confirm_not_executed`; and 15 over the largest receipt for the other calls. + +| Call | Gas it attaches to its promises | Least that succeeded | Attach | +|---|---|---|---| +| `dispatch` | `execute` 30 + `on_result` 30 | 70 Tgas | 100 Tgas | +| `reconcile` | `status` 10 + `on_result` 30 | 46 Tgas | 60 Tgas | +| executor `finish`, `confirm_not_executed` | the lock's `settle` 40 + `on_settled` 10 | 55 Tgas (`confirm_not_executed` with 254 jobs, `finish` with 256); `finish` with 512 jobs 56 | 70 Tgas | +| `submit`, `cancel`, `settle`, `observe`, `set_paused` | none | largest receipt 14.81 Tgas (a `submit` with 255 open records) | 30 Tgas | -The synthetic adapter has `new({lock,operator})`, `set_mode({mode})`, `finish({id,completed})`, `confirm_not_executed({id,recipe,units})`, and `get_jobs({})`. Modes normal/reject/unknown/panic support fault injection. These are testing features, not a real asset gateway. +- Every smaller whole-Tgas amount from 40 Tgas up failed with "Exceeded the prepaid gas." and changed neither contract. +- The gas attached to promises is fixed; extra prepaid gas is not passed on. At that state `on_result` burnt at most 10.92 of its 30 Tgas (a release), `execute` 2.46 of 30, `status` 1.76 of 10, the lock's `settle` after `finish` or `confirm_not_executed` at most 10.87 of 40, and `on_settled` 2.47 of 10. With 512 jobs, `execute` burnt 3.65 of 30, `status` 2.29 of 10, and `on_settled` 3.68 of 10 (3.66 after a refused settle). +- A call with too little gas fails without changing either contract; retry with more gas. A lost executor notification is recovered with `reconcile`. +- The contracts do not check prepaid gas. Smaller states need less. Another build or protocol version can change these figures. +- The measuring test is `crates/sandbox/tests/res1.rs`, adapted from the outside verification's RES-1 sandbox test. It takes about eight minutes, so `scripts/sandbox.sh` skips it. Run it after `scripts/build.sh` with `cargo test -p pool-sandbox --locked --test res1 -- --ignored --nocapture`; it writes `artifacts/res1.json`. `confirm_not_executed` was swept with 254 jobs only. Near the cap its executor receipt (from 511 to 512 jobs) burnt 4.39 Tgas, the same as `finish`'s with 512 jobs, which needed 56, so count on 56 for both there; 70 covers it. The test fails if any `on_settled` it measures burns 6 Tgas or more. ## Deployment preparation -1. Build with `scripts/build.sh`; retain Wasm and manifest. +1. Build with `scripts/build.sh`; retain Wasm and manifest. It sets `RUSTFLAGS="--cfg near"`, the flag `cargo near` sets, so a failed call reports its error name (for example `Smart contract panicked: Pending`). Without the flag near-sdk drops every panic message. The script fails if either Wasm does not import `env.panic_utf8`, or imports a host function for an action other than a function call (deploy, keys, transfer, stake, accounts, global contracts, any `promise_batch_*`). It also fails on any import that is not in its list of the 18 contract and 16 executor imports, so a new host function is reviewed before it ships. Any other build of the deployed Wasm must also set `--cfg near`. 2. Create/fund a lock account, executor account, owner/operator account and agent accounts on your selected network using your normal NEAR tooling. -3. Copy a generated `scenarios/*/config.json`; replace owner, all actor identities and executor identities with those accounts. Keep policy coefficients unchanged unless deliberately designing a new policy. -4. Deploy pool_contract.wasm and pool_executor.wasm. Initialize each contract from its own deployment account (private initializer), setting the configured owner/operator and the lock ID. Prefer an atomic deploy-and-initialize transaction. +3. Copy a generated `scenarios/*/config.json`; replace owner, all actor identities and executor identities with those accounts. A recipe's actor and executor must be different accounts; `new` rejects the config otherwise (`InvalidConfig`). Keep policy coefficients unchanged unless deliberately designing a new policy. +4. Deploy pool_contract.wasm and pool_executor.wasm. Initialize each contract from its own deployment account (private initializer), setting the configured owner/operator and the lock ID. Prefer an atomic deploy-and-initialize transaction. Use fresh accounts: v1.1.0 stores more state than v1.0.0 in both contracts, so it cannot replace v1.0.0 code in place, and no migration is provided. 5. Verify code hashes, config, funding and account access keys. Load `ui/live.html` with your account and expected code hash. 6. Preview/submit as the recipe actor; dispatch; independently confirm through the executor. Never put full-access keys in the static UI. diff --git a/docs/implementation-plan.md b/docs/implementation-plan.md index 9212b69..5d47220 100644 --- a/docs/implementation-plan.md +++ b/docs/implementation-plan.md @@ -23,7 +23,7 @@ Deliver a pure core, NEAR wrapper, enforced synthetic executor, deterministic sc - Per-metric hard bounds and three squared-potential primitives. Aggregate metrics encode coupled constraints. - Exact submission only. A Rust planner suggests a reduced quantity; the user/agent explicitly resubmits. Later dates are distinct recipes. - Version equality replaces a separate nonce system for accepted-request replay protection. -- At most 256 lifetime commitments; no pruning or live migrations. +- A window of the 256 most recent commitments; older terminal ones are pruned; replay protection is the version, not retention. No live migrations. - Static synthetic scheduling windows, not a production time/calendar engine. - Independent authenticated executor evidence replaces a generalized evidence/signature protocol. - No LLM dependency, frontend framework, JavaScript build chain, optimization solver, or database. @@ -40,8 +40,8 @@ Admission: 1. Check caller, pause flag, request version, short expiry, observation freshness and record limit. 2. Check recipe, quantity and completed-unit prerequisites. 3. Apply owner-defined reservation delta to a copy of the metric vector. -4. Compute a conservative interval for all outstanding completion effects. Each pending completion may occur independently; do not assume an unfilled hedge offsets an adverse position. -5. Check hard limits; in a disturbed baseline, require no worsening of each metric's violation. +4. Compute a conservative interval for every outcome of every open record: each may stay open, complete or be released, independently. Do not assume an unfilled hedge offsets an adverse position, or that an unexecuted position stays in place. +5. Check hard limits: no metric's interval violation may exceed its violation before the request or after the reservation. 6. Check nonincreasing potential at reservation. For an already hard-violating state require strict decrease at the proposed completed state as well. 7. Append an immutable commitment payload and atomically replace the vector. @@ -55,7 +55,7 @@ Reserved -> Dispatched -> Active -> Completed. Missing/malformed/failed acknowle Reserve before dispatch. Bind dispatch ID to exact recipe and units. Synthetic executor accepts only the lock; an independent operator confirms completion/cancellation. Store terminal evidence before notification so reconciliation can recover a lost callback. Repeated evidence is idempotent; conflicting terminal evidence rejects. -The administrator can pause admissions/dispatch and refresh observed values only with no unresolved records. Neither operation changes policy. Observations may raise energy. No production upgrade-lock claim is made. +The administrator can pause admissions/dispatch and change observed values only with no unresolved records. Restating the current values, which renews the snapshot timestamp, is allowed at any time. Neither operation changes policy. Observations may raise energy. No production upgrade-lock claim is made. ## Scenario 1 — GPU cooperative diff --git a/docs/judges-guide.md b/docs/judges-guide.md index 9a8fd3f..df1272e 100644 --- a/docs/judges-guide.md +++ b/docs/judges-guide.md @@ -49,15 +49,15 @@ See the README for prerequisites. Sandbox setup downloads a binary on first use Implemented: pure Rust core, NEAR wrapper, synthetic executor, deterministic scripted agents, static UI, local RPC/wallet console. The console signing path is implemented but has not been exercised with a public wallet/deployment by the automated suite. -Not implemented: public-network deployment, live LLM agents, real escrow/payments, production resource adapters, NEAR Intents integration, TEE/privacy. The earlier approval-contract architecture inspired this structure; its proofs do not transfer. The fixed lifetime record bound and trusted observation/evidence roles are documented in the README and specification. +Not implemented: public-network deployment, live LLM agents, real escrow/payments, production resource adapters, NEAR Intents integration, TEE/privacy. The earlier approval-contract architecture inspired this structure; its proofs do not transfer. The 256-record window and trusted observation/evidence roles are documented in the README and specification. ## Formal verification -[Formal verification PR #31](https://github.com/difflabai/formalver/pull/31) targets contract source pinned at `a4bb5c3`. It reports completed Lean model proofs, bounded TLA+ safety checks, Prolog requirements checks, and conformance traces against the Rust core and NEAR shell. These are substantive verification results, with distinct scopes; they are not a completed proof of every deployed Rust/Wasm behavior. +[Formal verification PR #31](https://github.com/difflabai/formalver/pull/31) targets v1.0.0, with contract source pinned at `a4bb5c3`. It reports completed Lean model proofs, bounded TLA+ safety checks, Prolog requirements checks, and conformance traces against the Rust core and NEAR shell. These are substantive verification results, with distinct scopes; they are not a completed proof of every deployed Rust/Wasm behavior. -The new station fixture is not part of that pinned verification revision; it has a dedicated Rust regression test. The core admission algorithm is unchanged. +The new station fixture is not part of that pinned verification revision; it has a dedicated Rust regression test. -The PR is a draft labeled **In-Progress**. Kani verification of the real Rust core and refinement obligations remain pending. It reports high-severity settlement/liveness findings F-1 and F-2. Present those findings alongside the proofs, and inspect the PR's current status before making a deployment claim. Modifying the contract or its policy requires reviewing the proof assumptions and rerunning applicable checks. +The PR is a draft labeled **In-Progress**. Kani verification of the real Rust core and refinement obligations remain pending. It reported high-severity settlement/liveness findings F-1 and F-2 and several lower-severity findings. v1.1.0 fixes all of them (F-4 only for a recipe whose actor is its executor; by the repository owner's decision, the owner may be a recipe's executor), which changes admission, record retention and the version limit ([findings](verification-findings.md), [changelog](../CHANGELOG.md)). The fixes are tested but not formally re-verified. Present the findings and fixes alongside the proofs, and inspect the PR's current status before making a deployment claim. Modifying the contract or its policy requires reviewing the proof assumptions and rerunning applicable checks. ## Presentation rationale and official sources diff --git a/docs/spec.md b/docs/spec.md index 9296ae7..12482b5 100644 --- a/docs/spec.md +++ b/docs/spec.md @@ -1,12 +1,14 @@ # Core specification -This document specifies the implemented prototype, not a claim of completed formal verification. +This document describes v1.1.0 of the implemented prototype. It is not a claim of completed formal verification. An outside verification checked v1.0.0; v1.1.0 fixes its findings and has not been re-verified ([verification findings](verification-findings.md), [changelog](../CHANGELOG.md)). ## State and identity -`Pool = (config, values, version, observed_at, paused, records)`. +`Pool = (config, values, version, observed_at, paused, records, first_id, completed_units)`. -Config is immutable. It contains one owner, bounded named metrics, potential terms and recipes. Each recipe has one exact actor account, one exact executor account, reservation effects, completion effects, a maximum quantity and earlier-recipe completion prerequisites `(recipe_id, minimum_completed_units)`. The dependency order is acyclic by construction. +`records` is a window of at most 256 records, oldest first, with consecutive ids: `records[k].id = first_id + k`. Ids never repeat. `completed_units[r]` is the number of units of recipe r that have completed over the pool's life, pruned records included. + +Config is immutable. It contains one owner, bounded named metrics, potential terms and recipes. Each recipe has one exact actor account, one exact executor account distinct from the actor, reservation effects, completion effects, a maximum quantity and earlier-recipe completion prerequisites `(recipe_id, minimum_completed_units)`. The dependency order is acyclic by construction. Both initializers are private to their own deployment account, preventing initialization by an unrelated caller. The NEAR wrapper authorizes by immediate predecessor account, not a JSON actor field and not `signer_account_id`. Calls through an intermediary are attributed to that intermediary. Account owners and deployed account code are part of the trust boundary. Preview accepts a proposed actor but conveys no authorization. @@ -16,13 +18,13 @@ Metric values and coefficients lie in [-1,000,000, 1,000,000]. Every update is c Input: `(caller, recipe, units, expected_version, expires_at, now)`. -Check paused, version equality, expiry strictly after now and at most one day ahead, observation freshness if configured, record bound, recipe validity, exact caller, quantity range, and completed-unit prerequisites. Compute candidate values by adding the recipe's reservation delta times units, with checked arithmetic. +Check paused, version equality, expiry strictly after now and at most one day ahead, observation freshness if configured, record bound (`Full` only when 256 records are retained and the oldest is open), recipe validity, exact caller, quantity range, and completed-unit prerequisites (`completed_units`). Compute candidate values by adding the recipe's reservation delta times units, with checked arithmetic. -For each metric compute a conservative interval containing every subset of outstanding completion effects, plus the proposed completion effect. Independent positive effects contribute to the high endpoint and negative effects to the low endpoint. Check this interval against the configured hard bound. In a healthy state, all intervals must fit. In a disturbed state, no metric's violation amount may exceed its current violation. +For each metric compute a conservative interval that contains every outcome of every open record, plus the proposed one. Each record may stay open, complete (add its completion effect) or be released (subtract its reservation effect), independently of the others. Positive effects contribute to the high endpoint and negative effects to the low endpoint. Check this interval against the configured hard bound. No metric's interval violation may exceed its violation before the request or its violation after the reservation. In a healthy state, all intervals must fit. -Then require V(candidate) <= V(current). In a state already violating hard bounds also require V(candidate + proposed_completion) < V(current). This allows a recovery hedge to reserve collateral while its beneficial stress effect waits for fill. This is only a recovery admission rule; it is not a guarantee that execution arrives or recovery completes. +Then require V(candidate) <= V(current). In a state already violating hard bounds also require V(candidate + proposed_completion) < V(current). This allows a recovery hedge to reserve collateral while its beneficial stress effect waits for fill. A reservation never changes a metric's violation amount; recovery comes from completion. This is only a recovery admission rule; it is not a guarantee that execution arrives or recovery completes. -On success append a Reserved record, replace values, increment version. On rejection return an error with no state change. The wrapper may emit a rejection event but does not consume a nonce or persist an audit record. Accepted requests cannot replay at the original version. A new version constitutes a new deliberate request; there is no separate client nonce mechanism. +On success append a Reserved record with id `first_id + len(records)`, replace values, increment version. If 256 records are retained, first drop the oldest, which is terminal, and increment `first_id`. A pruned id is `NotFound` for every call; its history stays in the event log. On rejection return an error with no state change. The wrapper may emit a rejection event but does not consume a nonce or persist an audit record. Accepted requests cannot replay at the original version. A new version constitutes a new deliberate request; there is no separate client nonce mechanism. `preview` calls the same checker and returns candidate values, score terms and reason. It is advisory. `best_quantity` is an offchain bounded enumeration of positive quantities up to the requested maximum. It minimizes energy then favors larger quantity. There is no global optimality claim. It only suggests; the caller explicitly submits the changed action. @@ -36,22 +38,24 @@ Hard constraints are axis-aligned metric bounds. Coupled constraints use additio - Reserved -> Dispatched: exact actor, unpaused, unexpired, fresh risk snapshot; wrapper creates the promise after state update. - Dispatched/Unknown -> Active: private acknowledgment says adapter accepted dispatch. -- Dispatched/Unknown -> Unknown: missing, malformed or failed acknowledgment; retain values. -- Dispatched/Active/Unknown -> Completed: recipe executor attests completion; add completion delta, check remaining completion envelope, increment version. No energy comparison is imposed on externally attested settlement. -- Reserved -> Cancelled: actor or owner cancels before dispatch. Subtract reservation delta and check other pending effects. +- Dispatched/Unknown -> Unknown: missing, malformed or failed acknowledgment; retain values. Unknown -> Unknown is an Ok no-op without a version change (`reconcile` is permissionless). +- Dispatched/Active/Unknown -> Completed: recipe executor attests completion; add completion delta, check the envelope of the remaining open records, add the units to `completed_units`, increment version. No energy comparison is imposed on externally attested settlement. +- Reserved -> Cancelled: actor or owner cancels before dispatch. Subtract reservation delta and check other pending effects. A cancel of a Dispatched, Active or Unknown record returns `Pending`: the executor's evidence is pending. A cancel of a Completed record returns `InvalidState`. - Dispatched/Active/Unknown -> Cancelled: executor attests definitive nonexecution; same checked inverse update. -- Same completion/cancellation repeated: idempotent. Conflicting terminal evidence: reject. -- Late acknowledgment after terminal settlement: ignored. +- Same completion/cancellation repeated: idempotent, Ok without a version change. Conflicting terminal evidence: reject with `InvalidState`. +- Late acknowledgment after terminal settlement: ignored, Ok without a version change. + +Admission refuses any commitment whose outcomes could make a metric worse than now, so the checked inverse cannot fail in a reachable state. There is still no forced administrative release. -A checked inverse can fail if another commitment depends on its contribution. The original commitment remains encumbered; resolve dependent work first. There is no forced administrative release that bypasses these checks. In the supplied fixtures, physical availability and risk-credit timing prevent ordinary unsafe reliance on unexecuted work. +Version reserve: submit (as its last check, so `preview` reports it), dispatch, `set_paused` and `observe` fail `Arithmetic` once version reaches `VERSION_CAP = u32::MAX - 768`. Acknowledgment, settlement and cancellation keep the plain checked increment. An open record needs at most three more increments (Dispatched -> Unknown -> Active -> terminal) and there are at most 256 records, so these never overflow. At the cap the pool admits nothing new but every open record can still be resolved. No automatic expiry of a dispatched request. A deadline does not prove nonexecution. Reconciliation queries the fixed executor by immutable ID. Unknown is distinct from cancelled. An executed but unacknowledged job remains a liability. -The mock adapter keeps a bounded immutable association between ID and recipe/quantity. Duplicate dispatch with identical payload returns the prior outcome; a different payload rejects. Only the lock can execute. Only the independent operator can finish/cancel a job. It stores terminal evidence before notifying the lock so a failed notification can be reconciled later. True end-to-end exactly-once physical execution is not claimed. +The mock adapter keeps a bounded immutable association between ID and recipe/quantity. Duplicate dispatch with identical payload returns the prior outcome; a different payload rejects. It forgets a job once its id is 256 or more behind the newest id the lock has vouched for: one for which the lock's `execute` created a job, or one whose `settle` from this executor it accepted (the private callback `on_settled` reads the lock's answer). An `execute` of an id that already has a job returns the stored status and moves nothing. The lock held that record then, so it has pruned every id 256 or more below; such a record is terminal. `execute` of a forgotten id starts nothing and returns `"cancelled"`; `confirm_not_executed` of one fails. A production adapter may forget an id only once it is 256 behind an id the lock dispatched or accepted a settle for. Only the lock can execute. Only the independent operator can finish/cancel a job. It stores terminal evidence before notifying the lock so a failed notification can be reconciled later. True end-to-end exactly-once physical execution is not claimed. ## External observations and administration -`set_paused` is owner-only and increments version. Pausing blocks new admissions and dispatch, not settlement or reconciliation. `observe` is owner-only and allowed only when every record is terminal. It replaces bounded measured values and refreshes the snapshot timestamp, without changing policy or deleting history. It can create a hard-limit violation. This is a trusted external fact assertion, not an energy-checked trade. +`set_paused` is owner-only and increments version. Pausing blocks new admissions and dispatch, not settlement or reconciliation. `observe` is owner-only. It sets new values only when every record is terminal; restating the current values is allowed at any time and renews the snapshot timestamp. It replaces bounded measured values and refreshes the snapshot timestamp, without changing policy. New values can create a hard-limit violation. This is a trusted external fact assertion, not an energy-checked trade. No policy upgrades, role mutation, arbitrary funds transfer, dynamic plugins, or reset entry point. Deployment-account full-access keys can still replace code; verify deployment upgrade authority separately. The owner is not thereby assumed powerless. @@ -63,7 +67,7 @@ Inventory: planning positions move at reservation. Physical source availability Hiring: reservation consumes discretionary funds or a review earmark and increases coverage plus escrow. Independent acceptance moves escrow to lifetime spending. Coverage remains after payment. `free + earmark + escrow + paid + protected = 10`. Review needs completed research units >=2 and implementation units >=3. No worker can authorize its own acceptance through the wrapper. -Risk: values are conservative scenario losses in $100k units. Positive loss contributions reserve immediately; hedge benefit occurs only on completion. Collateral encumbrance remains until an explicit later measured baseline. There is no automatic sale/close model or partial fill support. Each mock trade is an atomic synthetic position. No pending hedge offsets are netted into new trade capacity. +Risk: values are conservative scenario losses in $100k units. Positive loss contributions reserve immediately; hedge benefit occurs only on completion. Collateral encumbrance remains until an explicit later measured baseline. There is no automatic sale/close model or partial fill support. Each mock trade is an atomic synthetic position. No pending hedge offsets are netted into new trade capacity. No unexecuted position backs a hedge: a hedge must stay in bounds if the position is later reported unexecuted. ## Intended proof boundary diff --git a/docs/verification-findings.md b/docs/verification-findings.md new file mode 100644 index 0000000..4bb0efa --- /dev/null +++ b/docs/verification-findings.md @@ -0,0 +1,644 @@ +# Verification findings for v1.0.0 + +This page lists the problems an outside verification effort found in +v1.0.0 of the contract. + +**Status.** v1.1.0 fixes every finding below. For F-4 it rejects only a +recipe whose actor is its executor; the repository owner decided that the +owner may remain a recipe's executor. The repository owner also accepted +the record window (F-3) and the stricter admission (F-1, F-2). Each +finding has a **Status** line with the fixing commit and the tests that +check the fix; [CHANGELOG.md](../CHANGELOG.md) lists the changes. The +formal results cited here apply to v1.0.0. v1.1.0 has not been formally +re-verified: its fixes are checked by tests in this repository only. The +commit hashes on this page are commits of +[PR #4](https://github.com/difflabai/shared-pool-controls/pull/4), which +lists them. + +**Reproducers and regression tests.** In v1.0.0 each core finding had a +reproducer test in `crates/core/src/findings.rs` (commit `94f27ff`) that +passed and asserted the faulty result. Each v1.1 fix rewrote its +reproducer into a regression test of the fixed behaviour. The **Reproducer** +paragraphs below name the v1.0.0 tests; the **Status** lines name the v1.1.0 +tests. The shell findings point to the tests that show them in the +verification project. + +**Scope.** The verification ran on commit `a4bb5c3`, the head of PR #1. +`crates/core/src/lib.rs`, `crates/contract` and `crates/executor` are +byte-identical between `a4bb5c3` and v1.0.0 (`80fb89e`). The rest of the +diff is package versions, the `station` scenario, fixture and tests, the +demo, docs, UI, `scripts/smoke.py` and the Pages workflow. +Every finding below applies to v1.0.0. + +**Line references.** `spec:N`, `api:N` and `handoff:N` are line N of +`docs/spec.md`, `docs/api.md` and `docs/verification-handoff.md` in v1.0.0. + +**Formal evidence.** In [difflabai/formalver](https://github.com/difflabai/formalver), +draft [PR #31](https://github.com/difflabai/formalver/pull/31), under +[`projects/shared-pool/`](https://github.com/difflabai/formalver/tree/b9c495b8fa47e395d662a348f1cc7e352018aea5/projects/shared-pool) +at commit `b9c495b`. Paths in this page are relative to that directory. +Section 4 of its `strategy.md` is the full record. The **Evidence** +paragraphs below cite results as that section reports them. In this +repository the findings are checked by the regression tests in +`crates/core/src/findings.rs` (the v1.0.0 reproducers, rewritten for +v1.1.0) and by the unit, build and sandbox tests that v1.1.0 added. The +TLC, Lean, Prolog, shell and sandbox results of the verification project +were not re-run for this page, and none of them covers v1.1.0. + +## How the findings were found + +The formalver project checked the code with several independent methods: + +- **TLA+.** A model of the core, checked with TLC for safety and liveness + in small universes. +- **Lean 4.** A transcription of the core, with proofs about the + transcription. They are not proofs about the Rust code. +- **Prolog.** A reference model with consistency checks against the docs, + an exhaustive search of small state spaces (MC-1) and a trace replay + (MC-2). +- **Conformance traces.** 212 call sequences generated from the real + `pool-core`. TLA+, Lean, Prolog and the shell tests replay each one and + get the same results and post-states. +- **Host and wasm tests of the NEAR shell.** The `#[near]` methods called as + Rust functions, and both wasm builds (`scripts/build.sh`, and the same + with `--cfg near`) run in an interpreter over near-vm-runner's mocked + runtime. +- **Sandbox.** Both wasm files on a local near-workspaces chain, compared + with the host core. +- **Kani** (bounded model checking of the Rust core) is in progress. It has + produced no results yet. + +Nothing here is a proof about the Rust core or the NEAR shell. The Lean +results hold for the transcription, and the TLC and MC-1 results hold +within their bounds. The rest are tests. The findings do not depend on any +of that: each one is a concrete call sequence that gives the stated result +on the real code. + +## Summary + +Severity rates the harm to a property the docs promise. + +| ID | Severity | Effect | v1.0.0 reproducer | Status | +|---|---|---|---|---| +| F-1 | high | After an `observe` breaks a bound, an admitted recovery hedge can be left with no way to settle, and the pool cannot be observed again (shown for the trace-0 configuration). | `f1_disturbed_state_hedge_can_never_settle` | fixed in v1.1.0 (`59e404f`) | +| F-2 | high | In the supplied `risk` fixture, with every metric in bounds, a position that a completed hedge relied on cannot be released by `settle(false)` or `cancel`. | `f2_risk_position_cannot_be_released_after_hedge_completes`, `f2_risk_reserved_position_is_stuck_after_hedge_completes` | fixed in v1.1.0 (`59e404f`) | +| F-2b | high (part of F-2) | A release is not bounded by the envelope, so it can fail `Arithmetic`. | `f2b_release_outside_value_range_fails_arithmetic` | fixed in v1.1.0 (`59e404f`) | +| F-3 | low | One actor can use all 256 lifetime records with free submit-and-cancel cycles. Every later `submit` fails `Full`. | `f3_submit_cancel_cycles_exhaust_lifetime_records` | fixed in v1.1.0 (`1f01d43`) | +| F-4 | low | `validate` accepts a recipe whose actor is its executor, or the owner. That account settles its own work. | `f4_validate_accepts_actor_or_owner_as_executor` | fixed in v1.1.0 for actor = executor (`dc774f8`); the owner may be a recipe's executor by the repository owner's decision | +| F-5 | low | At version u32::MAX every transition fails `Arithmetic`, including settlement and unpausing. | `f5_version_max_freezes_settlement_and_every_transition`, `f5_paused_pool_at_version_max_cannot_unpause` | fixed in v1.1.0 (`da43188`) | +| F-6 | low | With `max_age_seconds > 0`, one long-open record blocks `observe`, so `submit` and `dispatch` fail `SnapshotExpired` until it settles. | `f6_open_record_blocks_the_snapshot_refresh` | fixed in v1.1.0 (`3eaf1cb`) | +| NT-F1 | medium (diagnostics, not safety) | The documented build omits `--cfg near`. Every on-chain failure is a bare trap with no message. | formalver `near-tests`, `sandbox` | fixed in v1.1.0 (`effd174`) | +| NT-F2 | low | `reconcile` accepts and keeps an attached deposit. | formalver `near-tests` | fixed in v1.1.0 (`1d441c5`) | +| NT-F3 | informational | The wasm imports 15 host functions for accounts, deploys, keys, transfers and staking. | formalver `near-tests` | fixed in v1.1.0 (`3598902`) | +| NT-F4 | low | A promise result that is not a JSON string makes the callback panic. The record does not become Unknown. | formalver `near-tests` | fixed in v1.1.0 (`1d441c5`) | + +## Core findings + +### F-1 (high): disturbed-state hedge wedge + +**Status.** Fixed in v1.1.0 (`59e404f`). Admission now counts every +outcome of every open record (stay open, complete, release), and compares +each metric's interval violation with the smaller of its violation before +the request and after the reservation. In this configuration the hedge is +refused (`Bounds`). Every open record can now be resolved: a Reserved one +by cancel, a dispatched one by its executor's report. +Regression tests: `f1_hedge_that_cures_by_reservation_is_refused`, +`f1_recovery_by_completion_is_admitted_and_live`, `live_all_on_random_runs`. +Formal re-verification pending. + +**What happens.** An `observe` puts metric 0 at 12, above its max of 10. +The recovery rule (spec:21, spec:23) admits a hedge that reserves −2 on +metric 0 and completes +2. Admission compares the envelope's violation (2) +with the current one (2), so it passes. The completion lowers the potential +(metric 1 goes from 5 to 0), so the strict-decrease rule passes too. Once +the hedge is reserved, metric 0 is 10 and the pool is healthy. Every later +check compares with a violation of 0: + +- `settle(true)` fails `Bounds`: the completion takes metric 0 to 12. +- `settle(false)` fails `Bounds`: the release takes metric 0 back to 12. +- `cancel` fails `Pending` for the actor and the owner, because the record + was dispatched. +- `observe` fails `Pending`, because a record is open (spec:54). + +In this configuration no later call helps: the record never becomes +terminal, and the pool can never be observed again. In other +configurations a later admission that lowers metric 0 can let +`settle(true)` pass, as in F-2. On a local chain the executor commits +"completed", and its notification to the pool fails `Bounds`. The executor +then refuses to change its answer, so the two contracts disagree +permanently. + +**Why it matters.** spec:46 says a checked inverse "can fail if another +commitment depends on its contribution" and to "resolve dependent work +first". Here no other commitment exists, so there is nothing to resolve. +handoff:31 makes liveness conditional on "resolving dependencies and +receiving authoritative evidence". The executor's evidence arrives, and +neither outcome can be applied. + +**Reproducer.** `f1_disturbed_state_hedge_can_never_settle`; formalver +trace 0. + +```text +config metric 0 in [0, 10] initial 5, metric 1 in [-100, 100] initial 5 + term metric 1, target 0, weight 1, Target + recipe 0: actor H, executor X, reserve [-2, 0], complete [2, -5], max_units 1 +observe(owner, [12, 5], 100) Ok metric 0 is 2 over its max +submit(H, {recipe 0, units 1, version 1}, 100) Ok(0) values [10, 5] +dispatch(H, 0, 101); acknowledge(0, true) Ok record 0 Active +settle(X, 0, true) Bounds would give [12, 0] +settle(X, 0, false) Bounds would give [12, 5] +cancel(owner, 0, 102); cancel(H, 0, 102) Pending +observe(owner, [5, 5], 103) Pending +``` + +**Evidence.** +- Lean: `f1_forever` and `f1_never_terminal` in + `lean/PoolLean/Witness.lean`. For this configuration, every later call + sequence leaves the record Active and every `observe` failing. This is a + result about the Lean transcription. +- TLA+: `Witness_Wedge` (`tla/Props.tla`) reaches the wedge at depth 4 + under `MC_Safety`. + TLA-LIVE-F1 (`tla/MC_Liveness_F1.cfg`) violates LIVE-2. + `MC_Liveness_F1Shape.cfg` shows that, in its small universe, every LIVE-2 + counterexample is this wedge. +- Prolog: `prolog/tests/test_model.pl` "F-1 witness". MC-1 universe `wedge` + has 228 dead states. +- Shell: `near-tests/tests/wedge.rs`, from Dispatched, Unknown and Active, + on the host and both wasm builds. +- Sandbox: `rt_wedge_f1_end_to_end` in `sandbox/tests/runtime.rs` + (RT-WEDGE in `sandbox/RESULTS.md`). + +### F-2 (high): healthy-state release wedge in the `risk` fixture + +**Status.** Fixed in v1.1.0 (`59e404f`), by the same change as F-1. With +the position open, 8- and 7-unit hedges are refused and 6 units are +admitted. After the hedge completes, the position can still be released by +`settle(false)` or `cancel`. Regression tests: +`f2_hedge_cannot_rely_on_an_unexecuted_position`, +`f2_reserved_position_can_always_be_cancelled`. Formal re-verification +pending. + +**What happens.** There is no `observe`, and every metric is in bounds. A +credit position (recipe 0, 1 unit) reserves +20 selloff loss: 60 becomes +80. A selloff hedge (recipe 3, 8 units, −10 selloff loss per unit on +completion) is admitted only because that +20 is counted: the low end of the +envelope is 80 − 80 = 0. Without the position, the same hedge fails +`Bounds` (60 − 80 < 0). Both are dispatched. The hedge completes, and +selloff loss is 0. The position's trade never ran, so the executor's honest +report is `settle(false)`. Releasing the +20 would give 0 − 20 < 0: + +- `settle(false)` fails `Bounds`. +- `cancel` fails `Pending` for the actor and the owner. +- `observe` fails `Pending`. + +`settle(true)`, a report of a trade that did not happen, succeeds. While the +snapshot is fresh, a new admission that adds 20 selloff loss (2 equity +units) also lets the release pass, at the cost of new, unrelated exposure. +After the snapshot expires (observed at 100, `max_age_seconds` 300), +`submit` fails `SnapshotExpired`. Then `settle(true)` is the only call that +ends the record. + +If the position was never dispatched, the same check makes `cancel` fail +`Bounds`. With a 7-unit hedge, selloff loss ends at 10 and the release would +give −10. Once the request has expired and the snapshot is stale, `dispatch` +fails `Expired`, `submit` fails `SnapshotExpired`, `settle` fails +`InvalidState` and `observe` fails `Pending`. No call changes the record or +the values again; `set_paused` only changes the pause flag and the version. +formalver's strategy.md notes that the same check blocks `cancel` of a +Reserved position. The expiry step is not in formalver; this repository's +`f2_risk_reserved_position_is_stuck_after_hedge_completes` shows it. + +**Why it matters.** spec:46: "In the supplied fixtures, physical +availability and risk-credit timing prevent ordinary unsafe reliance on +unexecuted work." Here a hedge in a supplied fixture relies on an +unexecuted position. spec:46 also says "resolve dependent work first". The +dependent hedge is resolved (Completed), and the release still fails. +api:14 says `settle(false)` means "definitive nonexecution". The honest +report is refused, and the false one is accepted. handoff:23 (RISK) is the +related obligation. It is not contradicted: the hedge's headroom comes from +the position's pending reservation, not from pending negative exposure. + +**Reproducer.** `f2_risk_position_cannot_be_released_after_hedge_completes`; +formalver trace 209. + +```text +fixture risk: selloff, funding, volatility, collateral = [60, 40, 30, 40] + max_age 300, observed at 100 +submit(credit, {recipe 0, units 1}, 100) Ok(0) values [80, 45, 30, 35] +submit(macro, {recipe 3, units 8}, 100) Ok(1) values [80, 45, 30, 19] +dispatch and acknowledge(true) for 0 and 1 Ok both Active +settle(executor, 1, true) Ok selloff loss 0 +settle(executor, 0, false) Bounds release would give -20 +cancel(owner, 0); cancel(credit, 0) Pending +observe(owner, [60, 40, 30, 40], 102) Pending +submit(equity, {recipe 1, units 2}, 401) SnapshotExpired +settle(executor, 0, true) Ok +``` + +**Evidence.** +- Trace 209 (`f2-risk`, from `f2_risk()` in `conformance/src/main.rs`), + reported equal under TLC, Lean, Prolog (MC-2) and the shell. +- Prolog: `prolog/tests/test_model.pl` "F-2 witness" (7-unit hedge). The + C-5 release search (`prolog/verification/consistency.pl`) finds 20 + counterexamples in `risk` and none in `gpu`, `friday`, `inventory` or + `hiring`. MC-1 universe `reliance` has 150 release-blocked healthy states. +- TLA+: TLA-LIVE-F2 (`tla/MC_Liveness_F2.cfg`, with weak fairness of the + honest `settle(false)` and of `cancel`) violates LIVE-2. + `MC_Liveness_F2Shape.cfg` shows that, in its small universe, every LIVE-2 + counterexample is this wedge. + +### F-2b: a release can leave the value range + +**Status.** Fixed in v1.1.0 (`59e404f`). The release is inside the +admission interval, so b x 100 fails `Arithmetic` at admission and b x 66 +is admitted; after b completes, a can be cancelled. Regression test: +`f2b_release_stays_in_the_value_range`. Formal re-verification pending. + +**What happens.** A release subtracts the reservation +(`values - reserve * units`), and nothing bounds that result in advance. If +a sibling's completion relied on a large reservation, the release can leave +±1,000,000, and `add` fails `Arithmetic`. `cancel` (actor and owner) and the +honest `settle(false)` fail `Arithmetic`, `observe` fails `Pending`, and +`settle(true)` succeeds. The TLA+ layer found it. + +**Why it matters.** As F-2, with a different error. + +**Reproducer.** `f2b_release_outside_value_range_fails_arithmetic`; +formalver trace 208. + +```text +config metric 0 in [-1,000,000, 1,000,000] initial 0 + metric 1 in [-10, 10] initial 0; term metric 1, target 0, Target + recipe 0 (a): reserve [-1,000,000, 0], complete [0, 0], max_units 1 + recipe 1 (b): reserve [0, 0], complete [15,000, 0], max_units 100 +submit(A, a x 1) Ok(0) metric 0 = -1,000,000 +submit(A, b x 100) Ok(1) envelope high 500,000 +dispatch, acknowledge(true), settle(X, 1, true) Ok metric 0 = 500,000 +cancel(A, 0); cancel(owner, 0) Arithmetic release would give 1,500,000 +dispatch, acknowledge(true), settle(X, 0, false) Arithmetic +observe(owner, [500,000, 0]) Pending +settle(X, 0, true) Ok +``` + +**Evidence.** Trace 208 (`release-arith`, from `release_arith()` in +`conformance/src/main.rs`), reported equal under TLC, Lean, Prolog and the +shell. + +### F-3 (low): lifetime record exhaustion + +**Status.** Fixed in v1.1.0 (`1f01d43`). The pool keeps a window of the +256 most recent records. A submit prunes the oldest record when it is +terminal and fails `Full` only while it is open. That record can be +closed: by its actor or the owner while it is Reserved, and by its +executor's report once it is dispatched (F-1's fix makes each of these +calls succeed). Until a dispatched oldest record's executor reports, +submit stays `Full`, even if the other 255 records are terminal. +Prerequisites count completed units over the pool's life. The executor +forgets jobs once the newest id for which the lock's `execute` created a +job or the lock accepted a settle is 256 or more past them, and holds at +most 512 jobs. Honest confirmations no longer fill that cap (`4d69f19`); +[api.md](api.md#executor-protocol) says when refused confirmations can. +Regression tests: `f3_window_frees_terminal_records_and_keeps_ids`, +`f3_prerequisites_survive_pruning`, `window_on_random_runs`, the contract +and executor `f3_*` tests, the executor `d1_*` tests, and the sandbox +tests `window_of_300_records_through_the_executor` and +`confirmed_failed_executes_keep_the_executor_at_256_jobs`. Formal +re-verification pending. + +**What happens.** Records are never deleted (spec:54: `observe` does not +delete history), and `submit` fails `Full` at 256 records. A submit followed +by a cancel costs only gas, so one actor can use all 256 records. After +that, every `submit` by every actor fails `Full`, also after an `observe`. +Nothing frees a record. + +**Why it matters.** handoff:34: "256 lifetime records bound ordinary +growth." They do, but the bound is also a lifetime budget that one actor can +spend for everyone. api:8 states the limit without this consequence. + +**Reproducer.** `f3_submit_cancel_cycles_exhaust_lifetime_records`; +formalver trace 207 (a smaller config). + +```text +fixture gpu +256 x { submit(research, {recipe 0, units 1}) Ok(id); cancel(research, id) Ok } +submit(evaluation, {recipe 2, units 1}) Full +observe(owner, values) Ok +submit(evaluation, {recipe 2, units 1}) Full +``` + +**Evidence.** +- Trace 207 (`full`, 515 calls), reported replayed by TLC (it also kills + TLA+ mutants 13 and 25), Lean (REF-5L), Prolog (MC-2) and + `near-tests/tests/traces.rs`. +- Sandbox: RES-1 (`sandbox/tests/resources.rs`). Submit #257 fails `Full` + on chain. + +### F-4 (low): a principal can attest its own work + +**Status.** Fixed in v1.1.0 (`dc774f8`). `validate` rejects a recipe whose +actor is its executor (`InvalidConfig`), so both mutations below are +refused. The owner may be a recipe's actor, or its executor, when the +other role is a different account: the repository owner decided to allow +it. This is the owner's decision, not an open question. Regression test: +`f4_actor_cannot_be_its_own_executor`. Formal re-verification pending. + +**What happens.** `Config::validate` does not compare a recipe's actor with +its executor or with the owner. A recipe with actor = executor, or with +actor = executor = owner, validates. That account can then submit, dispatch +and settle its own work as completed. + +**Why it matters.** spec:64 (hiring): "No worker can authorize its own +acceptance through the wrapper." spec:50 calls the account that finishes +jobs "the independent operator". The wrapper's checks work as written; the +configuration lets the roles coincide. + +**Reproducer.** `f4_validate_accepts_actor_or_owner_as_executor`; formalver +trace 210 (a smaller config). + +```text +fixture hiring, with recipe 0 executor := research (its actor) + and recipe 1 actor := executor := owner +validate() Ok +research: submit(recipe 0, 2 units), dispatch, acknowledge(true) Ok +settle(research, 0, true) Ok +owner: submit(recipe 1, 3 units), dispatch, acknowledge(true) Ok +settle(owner, 1, true) Ok +paid lifetime = 5, with no independent acceptance +``` + +**Evidence.** +- Trace 210 (`f4-self`), reported equal under TLC, Lean, Prolog and the + shell. +- Prolog: `prolog/tests/test_model.pl` "F-4 witness". + `prolog/extract.py` records that `validate` has no role checks. + +### F-5 (low): version saturation freezes every transition + +**Status.** Fixed in v1.1.0 (`da43188`). Submit, dispatch, `set_paused` +and `observe` fail `Arithmetic` from `VERSION_CAP` (u32::MAX - 768). +Acknowledgment, settlement and cancellation still bump the version by 1 and +always remain available: an open record needs at most three more bumps, +and at most 256 records are open. At the cap a paused pool stays paused, +and its open records still settle. Regression tests: +`f5_open_records_resolve_above_the_version_cap`, +`f5_paused_pool_at_the_cap_still_settles`, `f5_reserve_is_exactly_enough`. +Formal re-verification pending. + +**What happens.** Every effective transition adds 1 to `version` with +`checked_add`. At `version = u32::MAX` every transition fails `Arithmetic`: +`settle` both ways, `acknowledge`, `dispatch`, `cancel`, `set_paused` +(including `set_paused(false)` on a paused pool) and `observe` when no +record is open. With an open record, `observe` fails `Pending` first. State +is unchanged, and in-flight records can never settle. + +Reaching it takes 2³² − 1 = 4,294,967,295 effective transitions. From +reading the code, every bump other than `set_paused` and `observe` belongs +to a record: at most one submit, one dispatch, two acknowledgments and one +settle or cancel each, so at most 1,280 in all. The rest would have to come +from the owner's `set_paused` and `observe`. + +**Why it matters.** handoff:34 documents "Version overflow is an explicit +rejection", which is what happens. The effect on in-flight records is not +documented. spec:54 says pausing does not block "settlement or +reconciliation"; at u32::MAX both are blocked. + +**Reproducer.** `f5_version_max_freezes_settlement_and_every_transition` +and `f5_paused_pool_at_version_max_cannot_unpause`. Pool fields are public, +so the tests set the version. + +```text +fixture gpu; record 0 Dispatched (research), record 1 Reserved (evaluation) +version := u32::MAX +settle(executor, 0, true); settle(executor, 0, false) Arithmetic +acknowledge(0, true); acknowledge(0, false) Arithmetic +dispatch(evaluation, 1); cancel(evaluation, 1) Arithmetic +set_paused(owner, true) Arithmetic +observe(owner, values) Pending + +fixture gpu; set_paused(owner, true); version := u32::MAX +set_paused(owner, false) Arithmetic +observe(owner, [0, 0, 0, 0, 0]) Arithmetic +``` + +**Evidence.** +- No conformance trace: the highest version in the traces is 513. +- Prolog: `prolog/tests/test_model.pl` "F-5 witness" (paused, version + u32::MAX, record 0 Dispatched). +- Lean: the proofs kill `lean/mutants/04-version-overflow-off-by-one.patch`. +- Sandbox: RT-REVERT (`rt_revert_core_errors_write_nothing` in + `sandbox/tests/runtime.rs`) writes version u32::MAX into the on-chain + state. `set_paused` and `submit` fail, and storage is unchanged. + +### F-6 (low): an open record blocks the only snapshot refresh + +**Status.** Fixed in v1.1.0 (`3eaf1cb`). The owner can restate the current +values at any time, which renews the snapshot timestamp. New values still +need every record terminal. Regression test: +`f6_owner_refreshes_the_snapshot_with_records_open`. Formal re-verification +pending. + +**What happens.** With `max_age_seconds > 0`, `submit` and `dispatch` need +a snapshot no older than `max_age_seconds` (spec:19, spec:37). Only +`observe` refreshes it, and `observe` needs every record terminal (spec:54). +If one record stays open past `max_age_seconds`, nobody can submit or +dispatch, and the owner cannot refresh the snapshot, until the executor +settles that record. Reserved records can be cancelled. Dispatched records +wait for the executor; they do not expire (spec:48). + +**Why it matters.** The docs state each rule on its own (spec:19, 37, 54). +They do not state the combination: one slow job stops admissions for every +actor. + +**Reproducer.** `f6_open_record_blocks_the_snapshot_refresh`; formalver +trace 211 (a smaller config, `max_age_seconds` 50). + +```text +fixture risk: max_age 300, observed at 100 +submit(credit, recipe 0 x 1, 100); dispatch; acknowledge(true) record 0 Active +submit(macro, recipe 3 x 1, 100) record 1 Reserved +at now = 401: +submit(equity, recipe 1 x 1) SnapshotExpired +dispatch(macro, 1) SnapshotExpired +observe(owner, [60, 40, 30, 40]) Pending +cancel(macro, 1) Ok +observe(owner, [60, 40, 30, 40]) Pending record 0 is still Active +settle(executor, 0, true) Ok +observe(owner, [60, 40, 30, 40]) Ok +submit(equity, recipe 1 x 1) Ok +``` + +**Evidence.** +- Trace 211 (`f6-stale`), reported equal under TLC, Lean, Prolog and the + shell. +- Prolog: `prolog/tests/test_model.pl` "F-6 witness", on the risk fixture. + +## Shell, build and runtime findings + +v1.0.0's tests did not reproduce these. The contract's unit tests call the +`#[near]` methods as plain Rust functions, and near-sdk generates the +deposit checks and the `#[callback_result]` decoding only for wasm32. The +formalver tests named below run the wasm. v1.1.0 adds build, unit and +sandbox checks for each fix; the formalver tests were not re-run. + +### NT-F1 (medium; diagnostics, not safety): the documented build drops every panic message + +**Status.** Fixed in v1.1.0 (`effd174`). `scripts/build.sh` sets +`RUSTFLAGS="--cfg near"` and fails if a Wasm does not import +`env.panic_utf8`. The sandbox helper `fail` asserts the error text, so a +build without the flag fails the sandbox suite. + +**What happens.** api:40 says to build with `scripts/build.sh`, which runs +plain `cargo build --target wasm32-unknown-unknown`. Without `--cfg near`, +near-sdk 5.29.1 compiles its off-chain fallbacks: `env::panic_str` becomes +`eprintln!` plus `panic!()`, and the wasm does not import `panic_utf8`. +Every on-chain failure is a bare `unreachable` trap. State still reverts, +but a caller cannot tell `Pending` from `Bounds` from `Unauthorized`. +`cargo near build`, or `RUSTFLAGS="--cfg near"`, keeps the messages. + +**Why it matters.** `must` in `crates/contract/src/lib.rs` turns every core +error into `env::panic_str`, so the error names are the contract's error +interface, and api:28 lists them. The upstream sandbox helper `fail` +(`crates/sandbox/tests/integration.rs:36`) only asserts `is_failure()`, so +it does not notice. + +**Evidence.** +- `nt_f1_upstream_build_drops_every_panic_message` in + `near-tests/tests/shell.rs`. +- Sandbox: `sb1_upstream_build_loses_panic_messages` in + `sandbox/tests/runtime.rs` (SB-1 in `sandbox/RESULTS.md`). + +### NT-F2 (low): `reconcile` keeps an attached deposit + +**Status.** Fixed in v1.1.0 (`1d441c5`). `reconcile` rejects any deposit +("Method reconcile doesn't accept deposit"). Tests: +`nt_f2_reconcile_rejects_deposit`, and a 1 yoctoNEAR `reconcile` in the +sandbox suite. + +**What happens.** `reconcile` takes `&self`, so near-sdk generates no +nonpayable check for it. A call with an attached deposit succeeds. Its two +outgoing calls carry 0, so the contract keeps the deposit. + +**Why it matters.** api:3: "All mutating methods are nonpayable." + +**Evidence.** `nt_f2_reconcile_accepts_and_keeps_an_attached_deposit` in +`near-tests/tests/shell.rs` (both wasm builds, 1 NEAR attached). + +### NT-F3 (informational): host imports the contracts never use + +**Status.** Fixed in v1.1.0 (`3598902`). Both contracts create promises +with `promise_create`, `promise_then` and `promise_return` instead of +near-sdk's `Promise`. The 15 imports are gone: the contract imports 18 host +functions and the executor 16 (13 until its `on_settled` callback, +`4d69f19`). `scripts/build.sh` fails if a Wasm imports a host function for +any action other than a function call, or any import that is not on its +list of those 18 and 16. + +**What happens.** Both contracts, in both builds, import 15 host functions +that create or delete accounts, deploy code (including global contracts), +add or delete keys (including gas keys), transfer or stake. near-sdk's +generic `Promise` code links them. The source uses only `function_call` +actions, and no wasm call in the formalver suite (more than 50,000) reached +one of them. The import list alone cannot rule them out; a reviewer has to +read the code. + +**Why it matters.** No doc line is broken. It weakens the evidence that the +deployed code cannot move funds or change keys (spec:56 leaves deployment +authority to a separate check). + +**Evidence.** `wasm-surface.expected` lists every import and marks these 15 +`forbidden`. `near-tests/run.sh surface`: the SURF-2 check fails on exactly +these imports, as expected. + +### NT-F4 (low): a non-string promise result does not become Unknown + +**Status.** Fixed in v1.1.0 (`1d441c5`). `on_result` reads the raw +promise result. Anything but one JSON string of at most 64 bytes becomes +Unknown, and a result for an id with no record is logged instead of +panicking. Tests: `nt_f4_non_string_result_becomes_unknown`, +`nt_f4_result_for_unknown_id_is_logged`, and the sandbox test +`non_string_executor_results_leave_the_record_unknown` (a hand-made Wasm +executor returns `5` and a 70-byte string). + +**What happens.** `on_result` takes +`#[callback_result] result: Result`. If the executor +returns a value that is not a JSON string (unquoted `completed`, empty, +`null`, `42`, an array or an object), near-sdk cannot decode it and the +callback panics. The record stays as it was, for example Dispatched, +instead of becoming Unknown. `reconcile` can retry. The supplied executor +always returns strings. + +**Why it matters.** api:34: "Runtime failures and unexpected strings become +Unknown in the wrapper." Strings do. Other JSON values do not. + +**Evidence.** `sh3_non_string_promise_results_fail_the_callback` in +`near-tests/tests/shell.rs` (six payloads, both wasm builds). + +## Docs vs code + +| ID | Docs | Code | Suggested resolution | +|---|---|---|---| +| `div-ack-noop-version` | spec:39 lists "Dispatched/Unknown -> Unknown". api:26: "Every successful state transition changes version". | `acknowledge` returns `Ok` without a version bump when the status would not change. The code comment says why: `reconcile` is permissionless, so a bump on a no-op would let anyone invalidate every in-flight request. The existing test `repeated_unknown_reconciliation_does_not_change_version` pins it. | The code is right. Change the docs. | +| `div-cancel-terminal-name` | spec:41-43 and api:15: cancel applies only to undispatched Reserved records. | Cancelling a Completed or dispatched record fails `Pending`, a name that suggests an open commitment. `div_cancel_of_completed_or_dispatched_record_says_pending` pins it. | Return `InvalidState`, as `dispatch` and `settle` do for a record in the wrong status, or document `Pending`. | + +**Status.** Both resolved in v1.1.0 (`138ef98`). `div-ack-noop-version`: +spec and api now say that a call that changes nothing, such as an +acknowledgment that does not change the status, returns `Ok` without a +version change. `div-cancel-terminal-name`: `cancel` of a Completed record +fails `InvalidState`; Dispatched, Active and Unknown records still fail +`Pending`. Test: `cancel_names_conflicting_and_in_flight_states`. + +## Measured minimum prepaid gas + +docs/api.md gives no prepaid gas per method. The formalver sandbox measured +the least prepaid gas that succeeds at a maximum-size state: 32 metrics, 64 +terms, 32 recipes and 256 records (225 of them open), 45,613 bytes of Borsh +state. It counted up one whole Tgas at a time from 40 Tgas. + +| Call | Fails at | Least that succeeds | Gas the call attaches to its promises | +|---|---|---|---| +| `dispatch` | 40 to 69 Tgas | 70 Tgas | `execute` 30 + `on_result` 30 | +| `reconcile` | 40 to 45 Tgas | 46 Tgas | `status` 10 + `on_result` 30 | +| executor `finish` | 40 to 42 Tgas | 43 Tgas | notify 40 | + +- Both builds give the same minimums. +- A failing attempt changes nothing: no receipt runs on the other contract, + and the storage of both contracts is byte-identical afterwards. +- At 70 Tgas, `dispatch` has under 1 Tgas spare. A documented figure needs + headroom. +- The `dispatch` and `reconcile` sweeps ran with the executor at 31 and 34 + jobs. Only `finish` was swept with the executor at its 256-job cap. +- The worst single pool receipt at that state is `submit` #256, at 12.56 + Tgas. + +Evidence: `res_1_gas_at_max_state` and `res_1_min_prepaid_gas_and_executor_cap` +in `sandbox/tests/resources.rs`; RES-1 in `sandbox/RESULTS.md`; OQ-9 in +`strategy.md`. + +**Status.** v1.1.0 adds a gas table to [docs/api.md](api.md#gas) +(`e47f1e5`). It was measured on the v1.1 Wasm with a test adapted from +the RES-1 tests, with the same metrics, terms and recipes and 256 +retained records. The open records differ from the v1.0.0 sweep above +(225 of 256): all 256 were open for `dispatch` and `reconcile`, and 251 +to 254 for the executor calls. The test is now +`crates/sandbox/tests/res1.rs` (ignored by default; it takes about eight +minutes). The minimums for `dispatch` (70 Tgas) and `reconcile` (46) are +the same as above. Executor `finish` and `confirm_not_executed` need 55 +Tgas (`confirm_not_executed` swept with 254 jobs), and `finish` with the +executor at its 512-job cap 56: they now also attach 10 Tgas to the +executor's `on_settled` (`4d69f19`). Before that change both needed 43, +and `finish` at the cap 44. The largest single receipt is a `submit` +with 255 open records, at 14.81 Tgas. + +## Observation (not a finding) + +At `version = u32::MAX`, `preview` returns `allowed: true` for a request +that `submit` then rejects with `Arithmetic`. `submit` checks the version +bump after the checker that `preview` shares. The contract's `submit` runs +`preview` first and then `must(submit)`, so on chain the call panics +instead of returning a rejected decision. +`f5_version_max_freezes_settlement_and_every_transition` pinned it. + +**Status.** Closed in v1.1.0 (`da43188`). The version check is now part of +the admission that `preview` shares, so `preview` reports `Arithmetic` from +`VERSION_CAP` on. `f5_open_records_resolve_above_the_version_cap` checks +it. diff --git a/docs/verification-handoff.md b/docs/verification-handoff.md index 360e3c4..397dd78 100644 --- a/docs/verification-handoff.md +++ b/docs/verification-handoff.md @@ -15,30 +15,37 @@ Start with `crates/core/src/lib.rs` and `docs/spec.md`. The default pool-core bu | ATOM | All rejected core mutations preserve the full state | submit, dispatch, settle, cancel, observe | | STALE | Request computed at a prior accepted version cannot replay | candidate, submit | | ASYNC | Unknown outcomes retain reservation until authoritative terminal evidence | acknowledge, settle, cancel | -| TERM | Terminal repeated evidence is idempotent; conflicting outcome cannot apply | settle | -| DEP | Prerequisite requires completed units, not acknowledgment or partial completion | candidate | +| TERM | Terminal repeated evidence is idempotent; conflicting outcome cannot apply | settle, cancel | +| DEP | Prerequisite requires completed units, not acknowledgment or partial completion; pruning keeps the count | candidate, settle (`completed_units`) | | BIND | Each dispatch ID fixes actor recipe, units and executor | Commitment and wrapper dispatch | | STOCK | Inventory fixture conserves available + transit and never spends inbound pipeline | fixtures + lifecycle | | CASH | Hiring fixture conserves free + earmark + escrow + paid + protected; payment preserves coverage | fixtures + lifecycle | -| RISK | Pending negative exposure does not grant new risk headroom | risk fixture + envelope | +| RISK | Pending negative exposure does not grant new risk headroom, and no hedge relies on an unexecuted position | risk fixture + envelope | +| LIVE | Every open record can be resolved | envelope, check_bounds, release, settle | +| WIN | At most 256 retained records with consecutive ids; `Full` only while the oldest is open; only terminal records are pruned, and a pruned id is `NotFound` | candidate, submit, index | +| EXEC | The executor never forgets an id whose lock record is retained: `newest` rises only to an id for which the lock's `execute` created a job, or for which the lock accepted a `settle` (`on_settled` after a successful result); an `execute` of an id that already has a job moves nothing. At most 256 jobs have ids at or below `newest`; every other job is a confirmation above it, refused by the lock or waiting for `on_settled`. At most 512 jobs; at the cap it refuses a new id (`full`), even one whose record is retained (see the job-cap nuance) | executor execute, confirm_not_executed, on_settled | Prove transition-preservation from a well-formed state reachable through public methods. Pool fields are public to make model/harness construction easy; malformed arbitrary Rust values are outside ordinary deployed reachability. If you broaden the theorem to arbitrary deserialized values, add and prove state validation first. Config validates initial values within bounds; observations may intentionally introduce violations. Important nuances: -- Recovery admission uses nonincrease at reservation and strict decrease for the proposed completed state. It does not prove eventual completion or safety under arbitrary future market moves. -- Hard checks account for independent subsets of completion effects using intervals. This overapproximation can reject feasible correlated bundles; it should never underapproximate the modeled independent effects. -- A rejected checked inverse release leaves liability intact. Liveness is conditional on resolving dependencies and receiving authoritative evidence. +- Recovery admission uses nonincrease at reservation and strict decrease for the proposed completed state. A reservation never changes a metric's violation amount. It does not prove eventual completion or safety under arbitrary future market moves. +- Hard checks use intervals that contain every outcome of every open record: it stays open, completes, or releases its reservation. This overapproximation can reject feasible correlated bundles; it should never underapproximate the modeled independent effects. +- Admission requires each metric's interval violation to be at most its violation before the request and after the reservation. So in every reachable state each metric's interval violation equals its current violation, and no completion or release can fail the bounds check (LIVE). The version reserve below means the version increment cannot fail either. Liveness is conditional only on authoritative evidence and gas. These rules were added after the v1.0.0 verification (findings F-1, F-2, F-2b and F-5 in verification-findings.md). They are tested, not formally re-verified. - Fixed policy is part of the theorem. Owner observations, executor honesty, and source model adequacy are assumptions, not consequences of a low potential. - Energy is not checked on lifecycle reversal or observation. Do not accidentally state an all-transition monotonicity theorem. -- Version overflow is an explicit rejection; 256 lifetime records bound ordinary growth. Pause/observe still advance version. +- Version reserve: submit, dispatch, pause and observe stop 768 versions below u32::MAX (`VERSION_CAP`, `Arithmetic`); acknowledgment, settlement and cancellation always remain available. An open record needs at most three more increments (Dispatched -> Unknown -> Active -> terminal) and there are at most 256 records, so the reserve is exactly enough. Every effective transition still increments version by exactly 1. Pause/observe still advance version. +- Record window: the pool keeps its 256 most recent records. A submit into a full window prunes the oldest record if it is terminal and fails `Full` if it is open. By LIVE that record can be closed: by its actor or the owner while Reserved, and by its executor's report once dispatched. Until the executor reports, submit stays `Full` (head-of-line). Ids never repeat, a pruned id is `NotFound`, and replay protection is the version, not retention. Prerequisites read `completed_units`, a lifetime count updated by `settle(true)`. The executor forgets a job once its id is 256 or more behind the newest id the lock vouched for (an `execute` that created a job, or an accepted `settle`); the lock has pruned that record, so it is terminal and never dispatched again. This replaces v1.0.0's 256 lifetime records (finding F-3); it is tested, not formally re-verified. +- Executor job cap: the synthetic executor holds at most 512 jobs. Job ids are distinct, so at most 256 have ids at or below its newest id. The lock accepts honest confirmations, and each accepted one moves the newest id, so honest use holds 256 jobs plus confirmations in flight. The cap needs at least 256 jobs above the newest id (more if fewer sit at or below it): confirmations the lock refused (operator error: an unassigned or pruned id, a record still Reserved, a record whose other outcome is recorded, or another executor's recipe, `Unauthorized`) or confirmations whose `on_settled` has not run. A refused job is forgotten only once the newest id is 256 or more past its id, so never for an id the lock does not reach. At the cap, `confirm_not_executed` fails `full`, and so does an `execute` that frees no job. If executes then keep failing, their records stay Unknown and cannot be confirmed; once the lock holds 256 records, the oldest of them Unknown and none Reserved, submit fails `Full` and nothing can be dispatched. The exits are a `settle` signed with the executor account's own key, or an accepted `finish(id, false)` of a refused job whose record the lock holds as cancelled or open. LIVE still holds at the lock (the executor's `settle` would succeed), but in that state the synthetic executor contract may not be able to send it. `docs/api.md` (Executor protocol) gives the details. ## Boundary checks -The NEAR shell serializes the same core with borsh. Review `predecessor_account_id`, init authority, callback privacy, private callback's promise-result mapping, persistent state atomicity, and bounded gas/storage. The synthetic executor is independent code and must be included if claiming end-to-end gating. Unknown receipt failure cannot imply a refund. +The NEAR shell serializes the same core with borsh. Review `predecessor_account_id`, init authority, callback privacy, private callback's promise-result mapping (the lock's `on_result`; the executor's `on_settled`, which is private, needs exactly one promise result and moves the newest id only when the lock's `settle` succeeded), persistent state atomicity, and bounded gas/storage. The synthetic executor is independent code and must be included if claiming end-to-end gating. Unknown receipt failure cannot imply a refund. + +Both contracts create promises only with `promise_create`, `promise_then` and `promise_return`, and every promise is a function call with no deposit. Neither Wasm imports a host function for any other action: deploy, keys, transfer, stake, account creation or deletion, global contracts, or any `promise_batch_*` function. `scripts/build.sh` fails if one is imported, and also on any import not on its reviewed list (18 for the contract, 16 for the executor). This was added after the v1.0.0 verification (finding NT-F3); it is checked by the build, not formally re-verified. Account upgrades, oracle dishonesty, physical delivery, real broker fills, and deployment locks are outside the current tests. There is no real token custody. Do not inherit formalver's labels or proofs: the design pattern is reused, not its implementation theorem. ## Existing evidence -Unit tests cover scenario fixtures, accepted/rejected branches, stale requests, unauthorized identities, pending stock, earmarks, completed-unit prerequisites, duplicate settlement, recovery hedges and conservative pending exposure. Sandbox tests execute both Wasm binaries and compare full state/decisions with the pure core. HTTP smoke checks exercise the local Rust interface. Add mutation testing and proof canaries in the verification work; neither is currently a formal-verification result. +Unit tests cover scenario fixtures, accepted/rejected branches, stale requests, unauthorized identities, pending stock, earmarks, completed-unit prerequisites, duplicate settlement, recovery hedges, conservative pending exposure, the version reserve and the record window. A seeded random test (`live_all_on_random_runs`) checks after every call that every open record can be resolved, that no call but observe raises a metric's violation, that an observe with a record open changes no value or record, that each interval violation equals the current violation, and that a rejected call changes nothing. A second one (`window_on_random_runs`) fills and prunes the window and checks the window rules after every call. Sandbox tests execute both Wasm binaries and compare full state/decisions with the pure core. HTTP smoke checks exercise the local Rust interface. Add mutation testing and proof canaries in the verification work; neither is currently a formal-verification result. diff --git a/nearhackathon.md b/nearhackathon.md index b585a6d..c7bd5d7 100644 --- a/nearhackathon.md +++ b/nearhackathon.md @@ -15,7 +15,7 @@ This repository is a submission to the **November 2026 NEAR Hackathon**. - The Rust core, the NEAR lock contract, and the synthetic executor adapter in [`crates`](crates). - Six scenarios (station power, GPU compute, delivery capacity, inventory, worker budgets, and risk headroom) with Rust-generated traces in [`scenarios`](scenarios). - A static explorer and NEAR console in [`ui`](ui), plus a guide for configuring and deploying the contract against your own resource contention problem. -- Formal verification of the contract, in progress, in the companion PR above; it is part of the submission and is evaluated with it. It includes Lean model proofs and TLA+ checks; Rust-core Kani verification is pending and that PR reports settlement/liveness findings that are not yet resolved. +- Formal verification of the contract, in progress, in the companion PR above; it is part of the submission and is evaluated with it. It includes Lean model proofs and TLA+ checks of v1.0.0; Rust-core Kani verification is pending. v1.1.0 fixes the settlement/liveness and other findings that PR reported ([findings](docs/verification-findings.md)); the fixes are tested but not formally re-verified. The [judge walkthrough](docs/judges-guide.md) has a 90-second demo script and a claim-to-evidence map. The contract is not independently audited and has not been deployed to a public network. diff --git a/scenarios/friday/trace.json b/scenarios/friday/trace.json index 266b1b3..9b9646d 100644 --- a/scenarios/friday/trace.json +++ b/scenarios/friday/trace.json @@ -1,5 +1,13 @@ { "initial": { + "completed_units": [ + 0, + 0, + 0, + 0, + 0, + 0 + ], "config": { "max_age_seconds": 0, "metrics": [ @@ -240,6 +248,7 @@ } ] }, + "first_id": 0, "observed_at": 1794441600, "paused": false, "records": [], @@ -290,6 +299,14 @@ }, "id": 0, "pool": { + "completed_units": [ + 4, + 0, + 0, + 0, + 0, + 0 + ], "config": { "max_age_seconds": 0, "metrics": [ @@ -530,6 +547,7 @@ } ] }, + "first_id": 0, "observed_at": 1794441600, "paused": false, "records": [ @@ -592,6 +610,14 @@ }, "id": 1, "pool": { + "completed_units": [ + 4, + 0, + 2, + 0, + 0, + 0 + ], "config": { "max_age_seconds": 0, "metrics": [ @@ -832,6 +858,7 @@ } ] }, + "first_id": 0, "observed_at": 1794441600, "paused": false, "records": [ @@ -901,6 +928,14 @@ }, "id": null, "pool": { + "completed_units": [ + 4, + 0, + 2, + 0, + 0, + 0 + ], "config": { "max_age_seconds": 0, "metrics": [ @@ -1141,6 +1176,7 @@ } ] }, + "first_id": 0, "observed_at": 1794441600, "paused": false, "records": [ @@ -1210,6 +1246,14 @@ }, "id": 2, "pool": { + "completed_units": [ + 4, + 0, + 2, + 0, + 2, + 0 + ], "config": { "max_age_seconds": 0, "metrics": [ @@ -1450,6 +1494,7 @@ } ] }, + "first_id": 0, "observed_at": 1794441600, "paused": false, "records": [ @@ -1526,6 +1571,14 @@ }, "id": 3, "pool": { + "completed_units": [ + 4, + 0, + 2, + 0, + 2, + 2 + ], "config": { "max_age_seconds": 0, "metrics": [ @@ -1766,6 +1819,7 @@ } ] }, + "first_id": 0, "observed_at": 1794441600, "paused": false, "records": [ @@ -1849,6 +1903,14 @@ }, "id": 4, "pool": { + "completed_units": [ + 4, + 0, + 2, + 2, + 2, + 2 + ], "config": { "max_age_seconds": 0, "metrics": [ @@ -2089,6 +2151,7 @@ } ] }, + "first_id": 0, "observed_at": 1794441600, "paused": false, "records": [ diff --git a/scenarios/gpu/trace.json b/scenarios/gpu/trace.json index 67c8625..746d9d0 100644 --- a/scenarios/gpu/trace.json +++ b/scenarios/gpu/trace.json @@ -1,5 +1,13 @@ { "initial": { + "completed_units": [ + 0, + 0, + 0, + 0, + 0, + 0 + ], "config": { "max_age_seconds": 0, "metrics": [ @@ -202,6 +210,7 @@ } ] }, + "first_id": 0, "observed_at": 1794441600, "paused": false, "records": [], @@ -248,6 +257,14 @@ }, "id": 0, "pool": { + "completed_units": [ + 4, + 0, + 0, + 0, + 0, + 0 + ], "config": { "max_age_seconds": 0, "metrics": [ @@ -450,6 +467,7 @@ } ] }, + "first_id": 0, "observed_at": 1794441600, "paused": false, "records": [ @@ -508,6 +526,14 @@ }, "id": 1, "pool": { + "completed_units": [ + 4, + 0, + 2, + 0, + 0, + 0 + ], "config": { "max_age_seconds": 0, "metrics": [ @@ -710,6 +736,7 @@ } ] }, + "first_id": 0, "observed_at": 1794441600, "paused": false, "records": [ @@ -775,6 +802,14 @@ }, "id": null, "pool": { + "completed_units": [ + 4, + 0, + 2, + 0, + 0, + 0 + ], "config": { "max_age_seconds": 0, "metrics": [ @@ -977,6 +1012,7 @@ } ] }, + "first_id": 0, "observed_at": 1794441600, "paused": false, "records": [ @@ -1042,6 +1078,14 @@ }, "id": 2, "pool": { + "completed_units": [ + 4, + 0, + 2, + 0, + 2, + 0 + ], "config": { "max_age_seconds": 0, "metrics": [ @@ -1244,6 +1288,7 @@ } ] }, + "first_id": 0, "observed_at": 1794441600, "paused": false, "records": [ @@ -1316,6 +1361,14 @@ }, "id": 3, "pool": { + "completed_units": [ + 4, + 0, + 2, + 0, + 2, + 2 + ], "config": { "max_age_seconds": 0, "metrics": [ @@ -1518,6 +1571,7 @@ } ] }, + "first_id": 0, "observed_at": 1794441600, "paused": false, "records": [ @@ -1597,6 +1651,14 @@ }, "id": 4, "pool": { + "completed_units": [ + 4, + 0, + 2, + 2, + 2, + 2 + ], "config": { "max_age_seconds": 0, "metrics": [ @@ -1799,6 +1861,7 @@ } ] }, + "first_id": 0, "observed_at": 1794441600, "paused": false, "records": [ diff --git a/scenarios/hiring/trace.json b/scenarios/hiring/trace.json index e0a453c..96b0ea6 100644 --- a/scenarios/hiring/trace.json +++ b/scenarios/hiring/trace.json @@ -1,5 +1,10 @@ { "initial": { + "completed_units": [ + 0, + 0, + 0 + ], "config": { "max_age_seconds": 0, "metrics": [ @@ -175,6 +180,7 @@ } ] }, + "first_id": 0, "observed_at": 1794441600, "paused": false, "records": [], @@ -223,6 +229,11 @@ }, "id": null, "pool": { + "completed_units": [ + 0, + 0, + 0 + ], "config": { "max_age_seconds": 0, "metrics": [ @@ -398,6 +409,7 @@ } ] }, + "first_id": 0, "observed_at": 1794441600, "paused": false, "records": [], @@ -450,6 +462,11 @@ }, "id": 0, "pool": { + "completed_units": [ + 2, + 0, + 0 + ], "config": { "max_age_seconds": 0, "metrics": [ @@ -625,6 +642,7 @@ } ] }, + "first_id": 0, "observed_at": 1794441600, "paused": false, "records": [ @@ -685,6 +703,11 @@ }, "id": 1, "pool": { + "completed_units": [ + 2, + 3, + 0 + ], "config": { "max_age_seconds": 0, "metrics": [ @@ -860,6 +883,7 @@ } ] }, + "first_id": 0, "observed_at": 1794441600, "paused": false, "records": [ @@ -927,6 +951,11 @@ }, "id": 2, "pool": { + "completed_units": [ + 2, + 3, + 2 + ], "config": { "max_age_seconds": 0, "metrics": [ @@ -1102,6 +1131,7 @@ } ] }, + "first_id": 0, "observed_at": 1794441600, "paused": false, "records": [ diff --git a/scenarios/inventory/trace.json b/scenarios/inventory/trace.json index 8a2e4c3..60c1dcf 100644 --- a/scenarios/inventory/trace.json +++ b/scenarios/inventory/trace.json @@ -1,5 +1,10 @@ { "initial": { + "completed_units": [ + 0, + 0, + 0 + ], "config": { "max_age_seconds": 0, "metrics": [ @@ -153,6 +158,7 @@ } ] }, + "first_id": 0, "observed_at": 1794441600, "paused": false, "records": [], @@ -199,6 +205,11 @@ }, "id": null, "pool": { + "completed_units": [ + 0, + 0, + 0 + ], "config": { "max_age_seconds": 0, "metrics": [ @@ -352,6 +363,7 @@ } ] }, + "first_id": 0, "observed_at": 1794441600, "paused": false, "records": [], @@ -402,6 +414,11 @@ }, "id": 0, "pool": { + "completed_units": [ + 0, + 2, + 0 + ], "config": { "max_age_seconds": 0, "metrics": [ @@ -555,6 +572,7 @@ } ] }, + "first_id": 0, "observed_at": 1794441600, "paused": false, "records": [ @@ -613,6 +631,11 @@ }, "id": 1, "pool": { + "completed_units": [ + 0, + 2, + 2 + ], "config": { "max_age_seconds": 0, "metrics": [ @@ -766,6 +789,7 @@ } ] }, + "first_id": 0, "observed_at": 1794441600, "paused": false, "records": [ diff --git a/scenarios/risk/trace.json b/scenarios/risk/trace.json index 3060b83..ea49e4d 100644 --- a/scenarios/risk/trace.json +++ b/scenarios/risk/trace.json @@ -1,5 +1,11 @@ { "initial": { + "completed_units": [ + 0, + 0, + 0, + 0 + ], "config": { "max_age_seconds": 300, "metrics": [ @@ -133,6 +139,7 @@ } ] }, + "first_id": 0, "observed_at": 1794441600, "paused": false, "records": [], @@ -173,6 +180,12 @@ }, "id": null, "pool": { + "completed_units": [ + 0, + 0, + 0, + 0 + ], "config": { "max_age_seconds": 300, "metrics": [ @@ -306,6 +319,7 @@ } ] }, + "first_id": 0, "observed_at": 1794441600, "paused": false, "records": [], @@ -350,6 +364,12 @@ }, "id": 0, "pool": { + "completed_units": [ + 1, + 0, + 0, + 0 + ], "config": { "max_age_seconds": 300, "metrics": [ @@ -483,6 +503,7 @@ } ] }, + "first_id": 0, "observed_at": 1794441600, "paused": false, "records": [ @@ -535,6 +556,12 @@ }, "id": null, "pool": { + "completed_units": [ + 1, + 0, + 0, + 0 + ], "config": { "max_age_seconds": 300, "metrics": [ @@ -668,6 +695,7 @@ } ] }, + "first_id": 0, "observed_at": 1794441600, "paused": false, "records": [ @@ -720,6 +748,12 @@ }, "id": 1, "pool": { + "completed_units": [ + 1, + 0, + 0, + 1 + ], "config": { "max_age_seconds": 300, "metrics": [ @@ -853,6 +887,7 @@ } ] }, + "first_id": 0, "observed_at": 1794441600, "paused": false, "records": [ @@ -912,6 +947,12 @@ }, "id": 2, "pool": { + "completed_units": [ + 1, + 1, + 0, + 1 + ], "config": { "max_age_seconds": 300, "metrics": [ @@ -1045,6 +1086,7 @@ } ] }, + "first_id": 0, "observed_at": 1794441600, "paused": false, "records": [ diff --git a/scenarios/station/trace.json b/scenarios/station/trace.json index b0e5fc8..ae0cf09 100644 --- a/scenarios/station/trace.json +++ b/scenarios/station/trace.json @@ -1,5 +1,13 @@ { "initial": { + "completed_units": [ + 0, + 0, + 0, + 0, + 0, + 0 + ], "config": { "max_age_seconds": 0, "metrics": [ @@ -202,6 +210,7 @@ } ] }, + "first_id": 0, "observed_at": 1794441600, "paused": false, "records": [], @@ -248,6 +257,14 @@ }, "id": 0, "pool": { + "completed_units": [ + 4, + 0, + 0, + 0, + 0, + 0 + ], "config": { "max_age_seconds": 0, "metrics": [ @@ -450,6 +467,7 @@ } ] }, + "first_id": 0, "observed_at": 1794441600, "paused": false, "records": [ @@ -508,6 +526,14 @@ }, "id": 1, "pool": { + "completed_units": [ + 4, + 0, + 2, + 0, + 0, + 0 + ], "config": { "max_age_seconds": 0, "metrics": [ @@ -710,6 +736,7 @@ } ] }, + "first_id": 0, "observed_at": 1794441600, "paused": false, "records": [ @@ -775,6 +802,14 @@ }, "id": null, "pool": { + "completed_units": [ + 4, + 0, + 2, + 0, + 0, + 0 + ], "config": { "max_age_seconds": 0, "metrics": [ @@ -977,6 +1012,7 @@ } ] }, + "first_id": 0, "observed_at": 1794441600, "paused": false, "records": [ @@ -1042,6 +1078,14 @@ }, "id": 2, "pool": { + "completed_units": [ + 4, + 0, + 2, + 0, + 0, + 4 + ], "config": { "max_age_seconds": 0, "metrics": [ @@ -1244,6 +1288,7 @@ } ] }, + "first_id": 0, "observed_at": 1794441600, "paused": false, "records": [ @@ -1316,6 +1361,14 @@ }, "id": 3, "pool": { + "completed_units": [ + 4, + 0, + 2, + 2, + 0, + 4 + ], "config": { "max_age_seconds": 0, "metrics": [ @@ -1518,6 +1571,7 @@ } ] }, + "first_id": 0, "observed_at": 1794441600, "paused": false, "records": [ diff --git a/scripts/build.sh b/scripts/build.sh index 9bf8c00..9c326b7 100755 --- a/scripts/build.sh +++ b/scripts/build.sh @@ -1,12 +1,87 @@ #!/usr/bin/env bash set -euo pipefail cd "$(dirname "$0")/.." +# near-sdk calls the on-chain host functions (panic_utf8 and others) only under +# cfg(near), which cargo-near sets. Without it every failed call is a bare trap +# with no error name. CARGO_ENCODED_RUSTFLAGS would override RUSTFLAGS. With +# --target given, RUSTFLAGS does not reach build scripts or proc-macros. +unset CARGO_ENCODED_RUSTFLAGS +export RUSTFLAGS="--cfg near" cargo build -p pool-contract -p pool-executor --target wasm32-unknown-unknown --release --locked mkdir -p artifacts python3 - <<'PY' -import hashlib,json,pathlib,subprocess -paths=[pathlib.Path('target/wasm32-unknown-unknown/release')/(n+'.wasm') for n in ['pool_contract','pool_executor']] -manifest={'source_commit':subprocess.check_output(['git','rev-parse','HEAD'],text=True).strip(),'dirty':bool(subprocess.check_output(['git','status','--porcelain'],text=True).strip()),'rustc':subprocess.check_output(['rustc','--version'],text=True).strip(),'cargo_lock_sha256':hashlib.sha256(pathlib.Path('Cargo.lock').read_bytes()).hexdigest(),'wasm':{str(p):{'sha256':hashlib.sha256(p.read_bytes()).hexdigest(),'bytes':p.stat().st_size} for p in paths}} +import hashlib,json,os,pathlib,subprocess,sys + +def leb(b,i): + """Unsigned LEB128 at b[i]; returns (value, next index).""" + r=s=0 + while True: + x=b[i]; i+=1; r|=(x&0x7f)<Three ships.
One power grid.
No exceptions.// Reserve first. Dispatch second. commit(next);

Recovery from an externally disturbed state has additional checks. See the full specification for exact semantics.

-
01

A pure Rust core

Bounded data, checked integer arithmetic, fixed recipes. No NEAR dependency in the core’s default build.

02

A NEAR execution boundary

The synthetic adapter accepts execution only from the lock. Callback failure does not automatically release a commitment.

03

A precise claim

Accepted reservations do not increase the configured potential. External events can. Lean model proofs and TLA+ checks are complete; Rust-core verification remains in progress. Explore the formal verification.

+
01

A pure Rust core

Bounded data, checked integer arithmetic, fixed recipes. No NEAR dependency in the core’s default build.

02

A NEAR execution boundary

The synthetic adapter accepts execution only from the lock. Callback failure does not automatically release a commitment.

03

A precise claim

Accepted reservations do not increase the configured potential. External events can. Lean model proofs and TLA+ checks of v1.0.0 are complete; Rust-core verification remains in progress. Explore the formal verification.

Make it yours

Configure it for your own contention problem. Deploy it on NEAR.

Everything that makes the six scenarios different is data. Describe your shared resource in one JSON policy, then deploy the same tested Wasm.

    @@ -175,7 +175,7 @@

    Three ships.
    One power grid.
    No exceptions.

    Use the deployment checklist for account setup, then open the NEAR console with your account and expected code hash.

-
Before you deploy for real

Replace every executor with an adapter you control. The bundled executor is synthetic: it proves the gate, not a connection to your GPUs, warehouse, or funds. A real adapter must implement the execute and status protocol, idempotency, and authoritative cancellation, and it must leave agents no route around the lock.

Policy and principals cannot be edited after initialization. A pool holds at most 32 metrics, 32 recipes, and 256 lifetime commitments; deploy a fresh pool to rotate. The contract is not independently audited and its formal verification is in progress, so test on testnet first.

+
Before you deploy for real

Replace every executor with an adapter you control. The bundled executor is synthetic: it proves the gate, not a connection to your GPUs, warehouse, or funds. A real adapter must implement the execute and status protocol, idempotency, and authoritative cancellation, and it must leave agents no route around the lock.

Policy and principals cannot be edited after initialization. A pool holds at most 32 metrics and 32 recipes, and keeps its 256 most recent commitments; a new one replaces the oldest once that has ended. The contract is not independently audited. Its formal verification covers v1.0.0; v1.1.0 fixes the reported findings, and the fixes are tested but not yet formally re-verified. Test on testnet first.

@@ -186,7 +186,7 @@

Three ships.
One power grid.
No exceptions.

Illustrative request: the real expiry is an integer timestamp. A stale version is rejected and must be reviewed again.

What happens after approval?
Reserved→Dispatched→Active→Completed

Unknown execution outcomes keep their encumbrance. Before dispatch, the actor or owner can cancel. After dispatch, release requires definitive nonexecution evidence from the registered executor.

-
What is—and isn’t—guaranteed?

The kernel checks the configured bounds and potential against a modeled state. It does not guarantee fairness, profitable trades, truthful external observations, or eventual completion. The immutable policy and registered evidence authorities are part of the trust boundary.

Compute jobs, deliveries, worker payments, and financial positions in this explorer are synthetic. Real-world enforcement requires an adapter without a route around the lock. Dedicated formal verification includes model proofs and checks; Rust-core Kani verification is pending. The verification PR also reports settlement/liveness findings. The contract is not independently audited.

+
What is—and isn’t—guaranteed?

The kernel checks the configured bounds and potential against a modeled state. It does not guarantee fairness, profitable trades, truthful external observations, or eventual completion. The immutable policy and registered evidence authorities are part of the trust boundary.

Compute jobs, deliveries, worker payments, and financial positions in this explorer are synthetic. Real-world enforcement requires an adapter without a route around the lock. Dedicated formal verification includes model proofs and checks; Rust-core Kani verification is pending. The verification PR also reports settlement/liveness findings. v1.1.0 fixes them (findings); the fixes are tested, not yet formally re-verified. The contract is not independently audited.

Inspect the selected scenario’s policy
Inspect the last Rust decision
Run a scenario decision to inspect its response.
@@ -200,8 +200,8 @@

Three ships.
One power grid.
No exceptions.Execution authority

Try going around the gate.

NEAR sandbox tests attempt direct executor calls and agent-authored settlement. Both fail; registered execution evidence is required.

Inspect the bypass tests ↗
Asynchronous safety

Keep uncertain work reserved.

Sandbox tests exercise stale requests, unknown execution outcomes, and reconciliation. A failed callback alone does not free capacity.

Inspect the verification handoff ↗
-

Formal verification, with evidence you can inspect

Dedicated verification of the contract includes Lean model proofs, bounded TLA+ checks, and conformance traces against the Rust core. The work targets source revision a4bb5c3. Kani verification of the Rust implementation remains pending; the PR reports high-severity settlement/liveness findings F-1 and F-2.

Read the formal verification results, scope & findings ↗
-

What you can verify today

Rust kernel, NEAR lock and synthetic executor, six deterministic scenarios, local Wasm integration tests, and a static explorer. The browser demo is a simulation or recorded replay—not a public-chain transaction.

Where the prototype stops

No public-network deployment, real payments, live LLM agents, NEAR Intents integration, or production provider adapters. Not independently audited. Formal verification is in progress and has identified settlement/liveness findings. Policy quality and trusted observations remain assumptions.

+

Formal verification, with evidence you can inspect

Dedicated verification of the contract includes Lean model proofs, bounded TLA+ checks, and conformance traces against the Rust core. The work targets source revision a4bb5c3. Kani verification of the Rust implementation remains pending; the PR reports high-severity settlement/liveness findings F-1 and F-2. v1.1.0 fixes them and the lower-severity findings (findings); the fixes are tested, not yet formally re-verified.

Read the formal verification results, scope & findings ↗
+

What you can verify today

Rust kernel, NEAR lock and synthetic executor, six deterministic scenarios, local Wasm integration tests, and a static explorer. The browser demo is a simulation or recorded replay—not a public-chain transaction.

Where the prototype stops

No public-network deployment, real payments, live LLM agents, NEAR Intents integration, or production provider adapters. Not independently audited. Formal verification of v1.0.0 is in progress and identified settlement/liveness findings; v1.1.0 fixes them, tested but not yet formally re-verified. Policy quality and trusted observations remain assumptions.

Open source · MIT licensed · Built for the NEAR ecosystem

Your shared resources.
Your deployed contract.

Modify the contract and policy for your application. Review the verification findings, connect your execution adapter, and deploy a gate your agents share.

Get the contract