Skip to main content

qualia_core_db/services/swarm/
mod.rs

1//! **The Swarm — verify-before-pay distributed jobs.**
2//!
3//! A swarm job is work that one node cannot (or should not) do alone, dispatched
4//! across the socially-defined network in one of three [`job::JobMode`]s:
5//!
6//! * **Personal** — your own devices cooperate (no payment).
7//! * **Collaborative** — done with named peers (no payment).
8//! * **Paid** — dispatched to a provider for payment (the *solar-excess* case: a node
9//!   with surplus renewable energy sells idle compute).
10//!
11//! ## The load-bearing invariant: verify before you pay
12//!
13//! A paid swarm is dual-use. The same dispatch is autonomy (your fabric works for
14//! you) *or* extraction (you pay for fabricated or wrong work, or a node lies about
15//! what it computed). What decides which is a **result-verification gate that runs
16//! before any payment instruction is emitted**:
17//!
18//! ```text
19//!   spec ──► execute (untrusted provider) ──► VERIFY (trusted local reference)
20//!                                                  │
21//!                                       Verified ──┴── Rejected
22//!                                          │             │
23//!                                    emit Pay         emit Refund
24//!                                    instruction      (no provider payment)
25//! ```
26//!
27//! Verification never trusts the executor — it re-derives correctness with a cheap
28//! **trusted reference** (Freivalds' algorithm for matrix products in O(n²); ranking
29//! reproduction for embedding artifacts; see [`verify`]). Only a `Verified` verdict
30//! lets [`settlement`] emit a [`crate::rpc::MicropaymentInstruction`]. **This library
31//! never moves funds** — it emits the instruction that the existing
32//! [`crate::ilp_dispatcher`] (the actual rail) executes under human authorisation.
33//!
34//! ## Reuse, not reinvention
35//!
36//! * Compute reuses [`crate::solvers::linear_algebra`] (matmul/matvec) and
37//!   [`crate::solvers::learning::kg_embedding`] (the real KGE trainer).
38//! * Money arithmetic reuses [`crate::modalities::value_flow`] (pool/discharge,
39//!   `eroi_viable` — the thermodynamic supply gate that refuses net-extractive jobs).
40//! * Payment transport reuses [`crate::ilp_dispatcher`].
41//!
42//! Kernel-class boundaries are explicit and CPU references are always present (§13):
43//! the executor is dispatch-ready, the verifier is the always-present CPU oracle.
44
45#![cfg(not(target_arch = "wasm32"))]
46
47pub mod dispatch;
48pub mod executor;
49pub mod isolate;
50pub mod job;
51pub mod settlement;
52pub mod verify;
53
54pub use dispatch::{run_job, DispatchOutcome};
55pub use executor::{JobExecutor, LocalKernelExecutor};
56pub use isolate::isolate_b_compute;
57pub use job::{content_id, JobInput, JobKind, JobMode, JobResult, JobSpec};
58pub use settlement::{price_paid_job, Escrow, EscrowState, SettlementOutcome};
59pub use verify::{verify, VerificationVerdict, VerifyPolicy};
60
61/// Fail-closed errors for swarm job handling.
62#[derive(Debug, Clone, PartialEq, Eq)]
63pub enum SwarmError {
64    /// Input dimensions are inconsistent for the declared kind.
65    InvalidJob,
66    /// A reused kernel (GEMM, trainer) failed.
67    KernelFailed,
68    /// The escrow was not in a state allowing the requested transition.
69    InvalidEscrowState,
70    /// A paid job's energy economics are net-extractive (E-ROI below floor) — refused.
71    NotEnergyViable,
72}
73
74impl core::fmt::Display for SwarmError {
75    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
76        match self {
77            SwarmError::InvalidJob => write!(f, "inconsistent job input"),
78            SwarmError::KernelFailed => write!(f, "reused compute kernel failed"),
79            SwarmError::InvalidEscrowState => write!(f, "invalid escrow state transition"),
80            SwarmError::NotEnergyViable => {
81                write!(f, "paid job is net-extractive (E-ROI below floor)")
82            }
83        }
84    }
85}
86impl std::error::Error for SwarmError {}