From e05bfddce05c92d08623359337fd85ed4099c022 Mon Sep 17 00:00:00 2001 From: Anthony Ettinger Date: Mon, 26 Oct 2026 07:55:43 +0000 Subject: [PATCH 1/3] Infernet temporal policies on c0mpute: infernet.temporal.train / infernet.temporal.infer; v0.2.34 Workers opt in with `c0mpute infernet temporal serve [--train] [--model ...]` and advertise only what `infernet model capabilities` reports (Infernet >= 0.1.66): runtime version, CPU/CUDA/MPS, RAM buckets, served model hashes. Buyers turn requirements into required_capabilities; a new per-workload OfferFilter validates temporal specs and keeps a training worker from bidding while busy (one job per node). - train: one single-node job per family over the existing auction. Spec carries a liquid-agent/v1 TrainJobV1; workers refuse unless privacy.mode=trusted_worker and upload_approved. Buyer serves the dataset from a token-gated transfer server, the worker runs `infernet model train --job`, uploads the artifacts, receipts with the model hash; the buyer verifies weights against the receipt. --worker allowlist (trusted workers), --yes consent after a preview, retries, idempotency reuse. - infer: a session open is auctioned; the winner holds the session's hidden state in `infernet model serve --stdio`. Calls are X25519/HKDF/AES-GCM sealed, answered only for the opener's peer id, exactly-once by call id. - c0mpute infernet temporal serve|train|predict|models; module.toml lists the workloads; DIP 0026. - Tests: unit (spec validation, tag filtering, crypto, transfer server, family selection) and a loopback e2e with a fake infernet covering the allowlist, GPU filtering, receipt-verified training, sticky sessions, a forged peer refused and late replays. Also run by hand end to end with the real Infernet CLI and CfC/GRU runtime. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 37 +- Cargo.toml | 2 +- apps/tui/package.json | 2 +- apps/web/package.json | 2 +- .../web/src/app/releases/latest.json/route.ts | 2 +- dips/0026-infernet-temporal-workloads.md | 95 ++++ dips/README.md | 1 + node/crates/c0mpute-cli/src/main.rs | 6 +- node/crates/c0mpute-cli/src/temporal.rs | 277 +++++++++++ node/crates/c0mpute-core/Cargo.toml | 5 + node/crates/c0mpute-core/src/buyer.rs | 22 +- node/crates/c0mpute-core/src/dispatch.rs | 21 + node/crates/c0mpute-core/src/lib.rs | 3 +- node/crates/c0mpute-core/src/runner.rs | 2 +- node/crates/c0mpute-core/src/temporal/caps.rs | 184 ++++++++ .../c0mpute-core/src/temporal/client.rs | 410 +++++++++++++++++ .../c0mpute-core/src/temporal/crypto.rs | 87 ++++ node/crates/c0mpute-core/src/temporal/http.rs | 116 +++++ node/crates/c0mpute-core/src/temporal/mod.rs | 254 ++++++++++ node/crates/c0mpute-core/src/temporal/node.rs | 92 ++++ .../c0mpute-core/src/temporal/runtime.rs | 128 ++++++ .../c0mpute-core/src/temporal/worker.rs | 433 ++++++++++++++++++ .../c0mpute-core/tests/fixtures/fake-infernet | 75 +++ .../crates/c0mpute-core/tests/temporal_e2e.rs | 151 ++++++ package.json | 2 +- packages/shared/package.json | 2 +- plugins/ads-manager/module.toml | 2 +- plugins/coinpay/module.toml | 2 +- plugins/crawl/module.toml | 2 +- plugins/ctv-ads/module.toml | 2 +- plugins/diffusion/module.toml | 2 +- plugins/embed/module.toml | 2 +- plugins/gameserver/module.toml | 2 +- plugins/hosting/module.toml | 2 +- plugins/infernet/module.toml | 21 +- plugins/live-stream/module.toml | 2 +- plugins/ocr/module.toml | 2 +- plugins/podcast-ads/module.toml | 2 +- plugins/podcasting/module.toml | 2 +- plugins/podcasts/module.toml | 2 +- plugins/render/module.toml | 2 +- plugins/secure-chat/module.toml | 2 +- plugins/storage/module.toml | 2 +- plugins/train/module.toml | 2 +- plugins/transcode/module.toml | 2 +- plugins/tts/module.toml | 2 +- plugins/whisper/module.toml | 2 +- 47 files changed, 2422 insertions(+), 50 deletions(-) create mode 100644 dips/0026-infernet-temporal-workloads.md create mode 100644 node/crates/c0mpute-cli/src/temporal.rs create mode 100644 node/crates/c0mpute-core/src/temporal/caps.rs create mode 100644 node/crates/c0mpute-core/src/temporal/client.rs create mode 100644 node/crates/c0mpute-core/src/temporal/crypto.rs create mode 100644 node/crates/c0mpute-core/src/temporal/http.rs create mode 100644 node/crates/c0mpute-core/src/temporal/mod.rs create mode 100644 node/crates/c0mpute-core/src/temporal/node.rs create mode 100644 node/crates/c0mpute-core/src/temporal/runtime.rs create mode 100644 node/crates/c0mpute-core/src/temporal/worker.rs create mode 100755 node/crates/c0mpute-core/tests/fixtures/fake-infernet create mode 100644 node/crates/c0mpute-core/tests/temporal_e2e.rs diff --git a/Cargo.lock b/Cargo.lock index 7450c404..cd203a75 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -476,7 +476,7 @@ checksum = "1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33" [[package]] name = "c0mpute-api" -version = "0.2.33" +version = "0.2.34" dependencies = [ "anyhow", "c0mpute-proto", @@ -491,7 +491,7 @@ dependencies = [ [[package]] name = "c0mpute-bench" -version = "0.2.33" +version = "0.2.34" dependencies = [ "anyhow", "blake3", @@ -502,7 +502,7 @@ dependencies = [ [[package]] name = "c0mpute-cli" -version = "0.2.33" +version = "0.2.34" dependencies = [ "anyhow", "axum", @@ -532,11 +532,13 @@ dependencies = [ [[package]] name = "c0mpute-core" -version = "0.2.33" +version = "0.2.34" dependencies = [ + "aes-gcm", "anyhow", "async-trait", "axum", + "base64", "blake3", "c0mpute-api", "c0mpute-bench", @@ -550,11 +552,13 @@ dependencies = [ "c0mpute-verify", "directories", "hex", + "hkdf", "libp2p", "rand 0.8.6", "reqwest", "serde", "serde_json", + "sha2", "tempfile", "tokio", "toml", @@ -562,11 +566,12 @@ dependencies = [ "tracing-subscriber", "url", "uuid", + "x25519-dalek", ] [[package]] name = "c0mpute-doctor" -version = "0.2.33" +version = "0.2.34" dependencies = [ "anyhow", "serde", @@ -578,7 +583,7 @@ dependencies = [ [[package]] name = "c0mpute-envelope" -version = "0.2.33" +version = "0.2.34" dependencies = [ "blake3", "bs58", @@ -591,7 +596,7 @@ dependencies = [ [[package]] name = "c0mpute-gateway" -version = "0.2.33" +version = "0.2.34" dependencies = [ "anyhow", "axum", @@ -613,7 +618,7 @@ dependencies = [ [[package]] name = "c0mpute-market" -version = "0.2.33" +version = "0.2.34" dependencies = [ "c0mpute-envelope", "serde", @@ -623,7 +628,7 @@ dependencies = [ [[package]] name = "c0mpute-net" -version = "0.2.33" +version = "0.2.34" dependencies = [ "anyhow", "async-trait", @@ -640,7 +645,7 @@ dependencies = [ [[package]] name = "c0mpute-placement" -version = "0.2.33" +version = "0.2.34" dependencies = [ "anyhow", "async-trait", @@ -661,7 +666,7 @@ dependencies = [ [[package]] name = "c0mpute-proto" -version = "0.2.33" +version = "0.2.34" dependencies = [ "blake3", "hex", @@ -673,7 +678,7 @@ dependencies = [ [[package]] name = "c0mpute-secure-chat" -version = "0.2.33" +version = "0.2.34" dependencies = [ "aes-gcm", "anyhow", @@ -696,7 +701,7 @@ dependencies = [ [[package]] name = "c0mpute-store" -version = "0.2.33" +version = "0.2.34" dependencies = [ "anyhow", "blake3", @@ -714,7 +719,7 @@ dependencies = [ [[package]] name = "c0mpute-transcode" -version = "0.2.33" +version = "0.2.34" dependencies = [ "anyhow", "c0mpute-proto", @@ -726,7 +731,7 @@ dependencies = [ [[package]] name = "c0mpute-update" -version = "0.2.33" +version = "0.2.34" dependencies = [ "anyhow", "hex", @@ -740,7 +745,7 @@ dependencies = [ [[package]] name = "c0mpute-verify" -version = "0.2.33" +version = "0.2.34" dependencies = [ "anyhow", "blake3", diff --git a/Cargo.toml b/Cargo.toml index c230bc93..ce898fa4 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -23,7 +23,7 @@ members = [ ] [workspace.package] -version = "0.2.33" +version = "0.2.34" edition = "2024" license = "MIT" repository = "https://github.com/profullstack/c0mpute" diff --git a/apps/tui/package.json b/apps/tui/package.json index dbe7ac31..30cbab39 100644 --- a/apps/tui/package.json +++ b/apps/tui/package.json @@ -1,6 +1,6 @@ { "name": "@c0mpute/tui", - "version": "0.2.33", + "version": "0.2.34", "private": true, "type": "module", "bin": { diff --git a/apps/web/package.json b/apps/web/package.json index 86648321..5ae1f355 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -1,6 +1,6 @@ { "name": "c0mpute", - "version": "0.2.33", + "version": "0.2.34", "private": true, "type": "module", "scripts": { diff --git a/apps/web/src/app/releases/latest.json/route.ts b/apps/web/src/app/releases/latest.json/route.ts index 12ae2a73..8fa75d53 100644 --- a/apps/web/src/app/releases/latest.json/route.ts +++ b/apps/web/src/app/releases/latest.json/route.ts @@ -28,7 +28,7 @@ export const dynamic = "force-dynamic"; * this in sync with the workspace version in `Cargo.toml` on each release so a * freshly built CLI reports "already latest" rather than a phantom upgrade. */ -const FALLBACK_VERSION = "0.2.33"; +const FALLBACK_VERSION = "0.2.34"; const FALLBACK_MIN_REQUIRED = "0.0.1"; type Channel = "stable" | "beta" | "nightly"; diff --git a/dips/0026-infernet-temporal-workloads.md b/dips/0026-infernet-temporal-workloads.md new file mode 100644 index 00000000..61bf41be --- /dev/null +++ b/dips/0026-infernet-temporal-workloads.md @@ -0,0 +1,95 @@ +--- +dip: 0026 +title: "Run Infernet temporal policies (liquid networks) as c0mpute workloads" +status: Accepted +authors: + - riotcoder@profullstack.com +created: 2026-10-26 +updated: 2026-10-26 +discussion: +implementation: node/crates/c0mpute-core/src/temporal/, node/crates/c0mpute-cli/src/temporal.rs +supersedes: +superseded-by: +--- + +## Summary + +Workers can train and serve Infernet's temporal-policy models (CfC and LTC +liquid neural networks from ncps, with a GRU baseline) through two workloads, +`infernet.temporal.train` and `infernet.temporal.infer`, on the existing +offer, bid, accept and receipt protocol. c0mpute runs no model code: it asks +the local `infernet` what it can execute and drives `infernet model train` +and `infernet model serve --stdio`. There is no new scheduler and no new +marketplace plugin; `plugins/infernet/module.toml` lists the two workloads. + +## Motivation + +The W3BS Liquid Agent pipeline (Infernet `docs/liquid-agent/`) learns small +UI policies from consented desktop demonstrations. Training is cheap enough +for one CPU, so the network's job is to let a user borrow a trusted machine +and to keep a stateful policy's hidden state on one worker while it serves a +session. + +## Detailed design + +Opt in on a worker (nothing is installed implicitly): + +```bash +infernet model runtime setup --yes # operator's choice +c0mpute infernet temporal serve --train # accept training jobs +c0mpute infernet temporal serve --model sha256: # serve a model +``` + +Capability tags (advertised only for what `infernet model capabilities --json` +reports): `infernet:temporal:train`, `infernet:temporal:infer`, +`infernet:temporal:runtime[:]`, `infernet:temporal:device:{cpu,cuda,mps}`, +`c0mpute:ram:gb+` buckets, and `infernet:temporal:model:` for +each loaded model. Buyers turn requirements (GPU, minimum RAM, runtime +version, model hash) into `required_capabilities`; the existing dispatcher +filter does the matching. An `OfferFilter` adds per-workload checks before a +bid: a train worker validates the spec and does not bid while it is busy +(one job per node); an infer worker bids only for models it holds. + +Training (`c0mpute infernet temporal train`): one single-node job per family +(CfC plus baselines). The spec carries a liquid-agent/v1 `TrainJobV1`, a +token-gated dataset URL served by the buyer, the dataset hash and an upload +URL. Workers refuse a job unless `privacy.mode = trusted_worker` and +`upload_approved = true`; the CLI refuses to send without `--yes` after a +preview. `--worker ` restricts bids to trusted workers. The worker +runs `infernet model train --job` (which re-verifies every hash and the +secret scan), uploads `manifest.json`, `model.safetensors` and `eval.json`, +and receipts with the model hash. The buyer accepts the artifacts only if +the weights hash equals the receipt's `output_hash` and the manifest's. +Repeated idempotency keys reuse the finished model; failed or timed-out jobs +are re-auctioned up to `--retries` times. + +Inference (`c0mpute infernet temporal predict --session `): the first call +auctions a session open; the winner opens the session in its runtime, +publishes its X25519 key half and receipts with the model hash. Later calls +are AES-256-GCM sealed with an HKDF key bound to the session and go only to +that worker, which answers only the peer that opened the session (gossipsub +signs the source). A call id cache gives exactly-once execution when the +buyer republishes. Sequence rules (duplicate, late, gap), TTL, capacity and +account scope are enforced by the Infernet runtime. + +## Compatibility + +Additive. Workers that do not run `temporal serve` never see these topics. +`c0mpute infernet ` still delegates to the infernet binary. + +## Security and privacy + +- A worker sees the redacted training data in plaintext; transport security + does not change that. Local training is the default upstream; remote + training is an explicit, previewed choice of a trusted worker. +- The dataset URL is gated by a random token; use `--public-url https://...` + off the LAN. Artifacts are verified by hash, not trusted. +- Session traffic is encrypted between buyer and worker; other subscribers of + the topic see only ciphertext and routing ids. + +## Not done + +- Cross-worker session failover (checkpoint transfer) over the network; the + runtime supports checkpoint/restore locally. +- Price discovery beyond the existing cooperative bid, and settlement wiring + for these receipts. diff --git a/dips/README.md b/dips/README.md index b991751b..43e2d61b 100644 --- a/dips/README.md +++ b/dips/README.md @@ -132,3 +132,4 @@ superseded-by: | 0016 | Abuse policy: CSAM hash blocklist, per-worker opt-in | Draft | | 0024 | Separate the protocol from every hosted service that accelerates it | Draft | | 0025 | Signed envelopes and native `did:c0mpute` identity | Draft | +| 0026 | Infernet temporal policies (liquid networks) as c0mpute workloads | Accepted | diff --git a/node/crates/c0mpute-cli/src/main.rs b/node/crates/c0mpute-cli/src/main.rs index c6317d8a..5c91f628 100644 --- a/node/crates/c0mpute-cli/src/main.rs +++ b/node/crates/c0mpute-cli/src/main.rs @@ -22,6 +22,7 @@ mod peers; mod storage; +mod temporal; use std::path::PathBuf; use std::process::Command; @@ -40,7 +41,7 @@ use clap::{Parser, Subcommand}; name = "c0mpute", version, about = "c0mpute.com — decentralized compute network", - long_about = "c0mpute.com CLI. Submit jobs, run a worker, manage modules.\n\nBuilt-in plugins:\n transcode (FFmpeg, in-process)\n coinpay (DID + payments, peer CLI)\n infernet (AI inference, peer CLI)\n\n c0mpute coinpay reputation did claim\n c0mpute transcode submit input.mov --preset hls\n c0mpute infernet chat --model qwen2.5:7b \"hello\"\n c0mpute infernet model list --node \n c0mpute infernet reservation pricing" + long_about = "c0mpute.com CLI. Submit jobs, run a worker, manage modules.\n\nBuilt-in plugins:\n transcode (FFmpeg, in-process)\n coinpay (DID + payments, peer CLI)\n infernet (AI inference, peer CLI)\n\n c0mpute coinpay reputation did claim\n c0mpute transcode submit input.mov --preset hls\n c0mpute infernet chat --model qwen2.5:7b \"hello\"\n c0mpute infernet model list --node \n c0mpute infernet reservation pricing\n c0mpute infernet temporal serve --model sha256: --train\n c0mpute infernet temporal predict --session s1 --input step.json" )] struct Cli { /// Override the config file location. @@ -495,6 +496,7 @@ async fn run_app(cli: Cli) -> Result<()> { Cmd::Uninstall { all, purge, yes } => run_uninstall(all, purge, yes), Cmd::Coinpay { args } => delegate("coinpay", &args), Cmd::Login => run_login(), + Cmd::Infernet { args } if args.first().map(String::as_str) == Some("temporal") => temporal::run(&args[1..]).await, Cmd::Infernet { mut args } => { // Default the network to c0mpute when caller didn't specify. if matches!(args.first().map(String::as_str), Some("run")) @@ -2870,7 +2872,7 @@ fn is_infernet_daemon_cmdline(raw: &[u8]) -> bool { infernet && has(b"start") && has(b"--foreground") } -fn which_on_path(bin: &str) -> Option { +pub(crate) fn which_on_path(bin: &str) -> Option { let path = std::env::var_os("PATH")?; for entry in std::env::split_paths(&path) { let candidate = entry.join(bin); diff --git a/node/crates/c0mpute-cli/src/temporal.rs b/node/crates/c0mpute-cli/src/temporal.rs new file mode 100644 index 00000000..148937e1 --- /dev/null +++ b/node/crates/c0mpute-cli/src/temporal.rs @@ -0,0 +1,277 @@ +//! `c0mpute infernet temporal serve|train|predict|models`: Infernet's +//! temporal policies (`infernet.temporal.train`, `infernet.temporal.infer`) +//! over c0mpute's job/receipt protocol. Everything else under +//! `c0mpute infernet` still goes to the infernet binary. + +use std::path::PathBuf; +use std::time::Duration; + +use anyhow::{Context, Result, bail}; +use c0mpute_core::temporal::caps::Requirements; +use c0mpute_core::temporal::client::{self, OpenRequest, SessionFile, TrainRequest}; +use c0mpute_core::temporal::node::{self, NetOptions, ServeOptions}; +use c0mpute_core::temporal::worker::ModelStore; +use clap::{Args, Parser, Subcommand}; +use serde_json::{Value, json}; + +#[derive(Parser, Debug)] +#[command(name = "c0mpute infernet temporal", about = "Temporal policies (CfC/LTC liquid networks, GRU baseline) on c0mpute workers")] +struct TemporalCli { + #[command(subcommand)] + cmd: Sub, +} + +#[derive(Args, Debug, Clone)] +struct NetArgs { + /// Extra bootstrap peer (multiaddr). Repeatable. + #[arg(long = "bootstrap")] + bootstrap: Vec, + /// Don't dial c0mpute.com's seed nodes (isolated / LAN-only runs). + #[arg(long)] + no_default_bootstrap: bool, + /// libp2p listen multiaddr (default /ip4/0.0.0.0/tcp/0). + #[arg(long)] + listen: Vec, +} + +#[derive(Subcommand, Debug)] +enum Sub { + /// Serve inference for models and/or accept training jobs on this node. + Serve { + /// Model dir or sha256: from the local store. Repeatable. + #[arg(long)] + model: Vec, + /// Also accept infernet.temporal.train jobs (one at a time). + #[arg(long)] + train: bool, + #[arg(long, default_value_t = 64)] + max_sessions: u32, + #[command(flatten)] + net: NetArgs, + }, + /// Train on a remote worker: one single-node job per family. + Train { + #[arg(long)] + dataset: PathBuf, + #[arg(long)] + output: PathBuf, + #[arg(long, default_value = "cfc")] + family: String, + /// Baseline families on the same splits (comma separated), e.g. gru. + #[arg(long, value_delimiter = ',')] + baseline: Vec, + /// Only accept bids from these worker peer ids (trusted workers). + #[arg(long)] + worker: Vec, + #[arg(long, default_value_t = 1.0)] + max_price: f64, + #[arg(long)] + gpu: bool, + #[arg(long)] + min_ram_gb: Option, + #[arg(long)] + runtime_version: Option, + /// How the worker reaches this machine's transfer server (use https off-LAN). + #[arg(long)] + public_url: Option, + #[arg(long, default_value = "0.0.0.0:0")] + bind: std::net::SocketAddr, + #[arg(long, default_value_t = 3600)] + timeout_s: u64, + #[arg(long, default_value_t = 1)] + retries: u32, + #[arg(long)] + epochs: Option, + #[arg(long)] + seed: Option, + #[arg(long)] + hidden: Option, + #[arg(long, default_value_t = 8)] + bid_window_s: u64, + /// Consent: send the redacted dataset to the winning worker. + #[arg(long)] + yes: bool, + #[arg(long)] + json: bool, + #[command(flatten)] + net: NetArgs, + }, + /// Send one observed step to a session (opened on first use, sticky to its worker). + Predict { + #[arg(long)] + session: String, + /// Step JSON: a PredictRequestV1 or {observation, dt_ms?, prev_action?, task?}. + #[arg(long)] + input: Option, + /// Model hash; needed to open a new session. + #[arg(long)] + model: Option, + #[arg(long)] + worker: Vec, + #[arg(long, default_value_t = 600)] + ttl: u64, + #[arg(long, default_value = "default")] + scope: String, + #[arg(long, default_value_t = 0.05)] + max_price: f64, + #[arg(long)] + reset: bool, + #[arg(long)] + close: bool, + #[arg(long, default_value_t = 4)] + bid_window_s: u64, + #[command(flatten)] + net: NetArgs, + }, + /// Local model store: list, or import a trained model dir. + Models { + #[arg(long)] + import: Option, + }, +} + +fn data_dir() -> PathBuf { + c0mpute_core::config::data_dir().unwrap_or_else(|| PathBuf::from("./c0mpute-data")).join("temporal") +} + +fn infernet_bin() -> Result { + if let Some(p) = std::env::var_os("C0MPUTE_INFERNET_BIN") { + return Ok(PathBuf::from(p)); + } + crate::which_on_path("infernet").context("infernet is not on PATH (install it: c0mpute plugin install infernet)") +} + +fn net_opts(a: &NetArgs, identity: &str) -> NetOptions { + NetOptions { identity_dir: data_dir().join(identity), listen: a.listen.clone(), bootstrap: a.bootstrap.clone(), default_bootstrap: !a.no_default_bootstrap } +} + +pub async fn run(args: &[String]) -> Result<()> { + let cli = TemporalCli::try_parse_from(std::iter::once("c0mpute infernet temporal".to_string()).chain(args.iter().cloned())).unwrap_or_else(|e| e.exit()); + let store = ModelStore::new(data_dir().join("models")); + match cli.cmd { + Sub::Models { import } => { + if let Some(dir) = import { + println!("{}", store.import(&dir)?); + return Ok(()); + } + if let Ok(rd) = std::fs::read_dir(&store.root) { + for e in rd.flatten() { + let m: Value = std::fs::read(e.path().join("manifest.json")).ok().and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or(json!({})); + println!("sha256:{} {} {}", e.file_name().to_string_lossy(), m["architecture"]["family"].as_str().unwrap_or("?"), m["created_at"].as_str().unwrap_or("")); + } + } + Ok(()) + } + Sub::Serve { model, train, max_sessions, net } => { + let o = ServeOptions { net: net_opts(&net, "serve"), infernet: infernet_bin()?, models: model, train, max_sessions, store, cache_root: data_dir().join("cache") }; + let s = node::serve(&o).await?; + eprintln!("serving as {} (runtime {}, cuda {})", s.net.peer_id().to_base58(), s.caps.runtime.version, s.caps.devices.cuda); + for a in s.net.listen_addrs().await.unwrap_or_default() { + eprintln!(" listening {a}/p2p/{}", s.net.peer_id().to_base58()); + } + eprintln!(" tags {}", s.tags.join(" ")); + tokio::signal::ctrl_c().await?; + if let Some(i) = s.infer { + i.runtime.shutdown().await; + } + Ok(()) + } + Sub::Train { dataset, output, family, baseline, worker, max_price, gpu, min_ram_gb, runtime_version, public_url, bind, timeout_s, retries, epochs, seed, hidden, bid_window_s, yes, json: as_json, net } => { + let mut families = vec![family]; + families.extend(baseline.into_iter().filter(|b| !b.is_empty())); + families.dedup(); + let mut hp = serde_json::Map::new(); + if let Some(v) = epochs { + hp.insert("epochs".into(), json!(v)); + } + if let Some(v) = seed { + hp.insert("seed".into(), json!(v)); + } + if let Some(v) = hidden { + hp.insert("hidden_units".into(), json!(v)); + } + let req = TrainRequest { + dataset_path: dataset, + output, + families, + workers: worker, + max_price_usd: max_price, + requirements: Requirements { gpu, min_ram_gb, runtime_version, model_hash: None }, + public_url, + bind, + timeout_s, + retries, + hyperparameters: Value::Object(hp), + bid_window: Duration::from_secs(bid_window_s), + }; + let p = client::preview(&req)?; + if !yes { + eprintln!("About to send dataset {} ({} episodes, {} bytes) for training {} on {} (max ${} per job).\n{}\nRe-run with --yes to send it.", p.dataset_hash, p.episodes, p.bytes, p.families.join(","), if p.workers.is_empty() { "any eligible worker".to_string() } else { p.workers.join(",") }, p.max_price_usd, p.note); + if as_json { + println!("{}", json!({"preview": p})); + } + std::process::exit(3); + } + let n = node::spawn_node(&net_opts(&net, "client")).await?; + settle(&n).await; + let out = client::train(n, &req).await?; + if as_json { + println!("{}", serde_json::to_string_pretty(&out)?); + } else { + for r in out["results"].as_array().into_iter().flatten() { + println!("{} {} episode_success {} worker {}", r["family"].as_str().unwrap_or(""), r["model_hash"].as_str().unwrap_or(""), r["eval"]["metrics"]["episode_success"], r["worker_peer_id"].as_str().unwrap_or("")); + } + println!("selected: {} (a liquid family wins only if it beats the GRU baseline)", out["selected"].as_str().unwrap_or("?")); + } + Ok(()) + } + Sub::Predict { session, input, model, worker, ttl, scope, max_price, reset, close, bid_window_s, net } => { + let dir = data_dir().join("sessions"); + let n = node::spawn_node(&net_opts(&net, "client")).await?; + settle(&n).await; + let mut sf = match SessionFile::load(&dir, &session)? { + Some(sf) => { + if model.as_ref().is_some_and(|m| m != &sf.model_hash) { + bail!("session {session} serves {}, not {}", sf.model_hash, model.unwrap()); + } + sf + } + None => { + let model = model.context("--model sha256: is needed to open a new session")?; + let sf = client::open_session(n.clone(), &OpenRequest { model_hash: model, session_id: session.clone(), ttl_s: ttl, account_scope: scope, workers: worker, max_price_usd: max_price, bid_window: Duration::from_secs(bid_window_s) }).await?; + sf.save(&dir)?; + eprintln!("session {} opened on worker {}", sf.session_id, sf.worker_peer_id); + sf + } + }; + let t = Duration::from_secs(30); + if reset { + let r = client::call(n.clone(), &sf, json!({"op": "reset"}), t).await?; + sf.next_seq = 0; + sf.save(&dir)?; + println!("{r}"); + } + if let Some(p) = input { + let step: Value = serde_json::from_slice(&std::fs::read(&p)?)?; + let req = client::predict_request(&step, &sf)?; + let r = client::call(n.clone(), &sf, json!({"op": "predict", "request": req}), t).await?; + if r["ok"] == json!(true) { + sf.next_seq = req["sequence_index"].as_i64().unwrap_or(sf.next_seq) + 1; + sf.save(&dir)?; + } + println!("{r}"); + } + if close { + let r = client::call(n.clone(), &sf, json!({"op": "close_session"}), t).await?; + let _ = std::fs::remove_file(SessionFile::path(&dir, &sf.session_id)); + println!("{r}"); + } + Ok(()) + } + } +} + +/// Give a fresh node's gossip mesh a moment before publishing (as `transcode submit` does). +async fn settle(_n: &T) { + tokio::time::sleep(Duration::from_secs(2)).await; +} diff --git a/node/crates/c0mpute-core/Cargo.toml b/node/crates/c0mpute-core/Cargo.toml index 60be4d87..5b2c9a90 100644 --- a/node/crates/c0mpute-core/Cargo.toml +++ b/node/crates/c0mpute-core/Cargo.toml @@ -32,6 +32,11 @@ uuid = { workspace = true } blake3 = { workspace = true } hex = { workspace = true } reqwest = { workspace = true } +sha2 = { workspace = true } +x25519-dalek = { workspace = true } +hkdf = { workspace = true } +aes-gcm = { workspace = true } +base64 = { workspace = true } [dev-dependencies] libp2p = { workspace = true } diff --git a/node/crates/c0mpute-core/src/buyer.rs b/node/crates/c0mpute-core/src/buyer.rs index eab2f3cb..ce6d3337 100644 --- a/node/crates/c0mpute-core/src/buyer.rs +++ b/node/crates/c0mpute-core/src/buyer.rs @@ -33,6 +33,9 @@ pub struct JobAuction { pub deadline: Duration, pub bid_window: Duration, pub receipt_timeout: Duration, + /// When non-empty, only bids from these peer ids are considered (the + /// buyer's trusted workers). Others are ignored, not rejected. + pub allowed_bidders: Vec, } impl JobAuction { @@ -45,9 +48,20 @@ impl JobAuction { deadline: Duration::from_secs(15 * 60), bid_window: DEFAULT_BID_WINDOW, receipt_timeout: DEFAULT_RECEIPT_TIMEOUT, + allowed_bidders: Vec::new(), } } + pub fn with_allowed_bidders(mut self, peers: Vec) -> Self { + self.allowed_bidders = peers; + self + } + + pub fn with_receipt_timeout(mut self, d: Duration) -> Self { + self.receipt_timeout = d; + self + } + pub fn with_required_capabilities(mut self, caps: Vec) -> Self { self.required_capabilities = caps; self @@ -124,6 +138,12 @@ pub async fn run_auction( if bid.job_id == job_id && bid.bidder_peer_id != offer.buyer_peer_id { + if !auction.allowed_bidders.is_empty() + && !auction.allowed_bidders.contains(&bid.bidder_peer_id) + { + debug!(%job_id, bidder = %bid.bidder_peer_id, "buyer: bid from a worker outside the allowlist ignored"); + continue; + } if !source_matches_claim(&msg, &bid.bidder_peer_id) { warn!( %job_id, @@ -257,7 +277,7 @@ async fn publish_json( /// `JobBid.bidder_peer_id` / `JobReceipt.worker_peer_id` are just self-reported /// strings inside the signed-later-but-not-yet payload, so without this check /// any peer can claim to be any other peer_id in a bid or completion receipt. -fn source_matches_claim(msg: &GossipMessage, claimed_peer_id: &str) -> bool { +pub(crate) fn source_matches_claim(msg: &GossipMessage, claimed_peer_id: &str) -> bool { match &msg.source { Some(source) => source.to_base58() == claimed_peer_id, None => false, diff --git a/node/crates/c0mpute-core/src/dispatch.rs b/node/crates/c0mpute-core/src/dispatch.rs index 9a55be33..79a7d26b 100644 --- a/node/crates/c0mpute-core/src/dispatch.rs +++ b/node/crates/c0mpute-core/src/dispatch.rs @@ -41,6 +41,21 @@ pub fn run_worker_subscriber( workload_type: String, advertised_tags: Vec, runner_tx: Option>, +) { + run_worker_subscriber_filtered(net, workload_type, advertised_tags, runner_tx, None) +} + +/// Extra per-workload eligibility, checked after the capability tags and +/// before bidding (spec validation, "busy", etc.). `false` = don't bid. +pub type OfferFilter = Arc bool + Send + Sync>; + +/// [`run_worker_subscriber`] with an [`OfferFilter`]. +pub fn run_worker_subscriber_filtered( + net: Arc, + workload_type: String, + advertised_tags: Vec, + runner_tx: Option>, + filter: Option, ) { tokio::spawn(async move { let topic = job_topic(&workload_type); @@ -71,6 +86,12 @@ pub fn run_worker_subscriber( if offer.workload_type != workload_type { continue; } + if let Some(f) = &filter { + if !f(&offer) { + debug!(job_id = %offer.job_id, "dispatch: offer filtered out"); + continue; + } + } handle_offer(&net, &topic, &offer, &advertised_tags).await; continue; } diff --git a/node/crates/c0mpute-core/src/lib.rs b/node/crates/c0mpute-core/src/lib.rs index 8313820b..b72153f2 100644 --- a/node/crates/c0mpute-core/src/lib.rs +++ b/node/crates/c0mpute-core/src/lib.rs @@ -12,11 +12,12 @@ pub mod register; pub mod runner; pub mod status_aggregator; pub mod supervisor; +pub mod temporal; pub use buyer::{AuctionOutcome, JobAuction, run_auction}; pub use capabilities::{Registry, advertise_loop, tags_from_config}; pub use config::Config; -pub use dispatch::{run_worker_subscriber, workload_types_from_roles}; +pub use dispatch::{OfferFilter, run_worker_subscriber, run_worker_subscriber_filtered, workload_types_from_roles}; pub use register::{Registration, run_register}; pub use runner::TranscodeJobInline; pub use supervisor::Supervisor; diff --git a/node/crates/c0mpute-core/src/runner.rs b/node/crates/c0mpute-core/src/runner.rs index d6f78751..468bd332 100644 --- a/node/crates/c0mpute-core/src/runner.rs +++ b/node/crates/c0mpute-core/src/runner.rs @@ -209,7 +209,7 @@ fn is_ipv6_private_or_local(ip: &std::net::Ipv6Addr) -> bool { || (segments[0..5] == [0, 0, 0, 0, 0] && segments[5] == 0xffff) } -async fn publish_receipt( +pub(crate) async fn publish_receipt( net: &Libp2pNetwork, accept: &JobAccept, output_hash: Option, diff --git a/node/crates/c0mpute-core/src/temporal/caps.rs b/node/crates/c0mpute-core/src/temporal/caps.rs new file mode 100644 index 00000000..5f04dd47 --- /dev/null +++ b/node/crates/c0mpute-core/src/temporal/caps.rs @@ -0,0 +1,184 @@ +//! What the local Infernet can execute, as capability tags. +//! +//! Tags are only advertised when `infernet model capabilities --json` +//! answers, i.e. the operator installed the infernet-liquid runtime +//! themselves (`infernet model runtime setup`). Nothing is installed or +//! downloaded from here. + +use std::path::Path; +use std::time::Duration; + +use anyhow::{Context, Result, bail}; +use serde::Deserialize; + +use super::{INFER_WORKLOAD, TRAIN_WORKLOAD}; + +pub const RAM_BUCKETS_GB: [u64; 7] = [2, 4, 8, 16, 32, 64, 128]; + +#[derive(Clone, Debug, Deserialize, PartialEq)] +pub struct RuntimeCaps { + pub workloads: Vec, + pub families: Vec, + pub devices: Devices, + pub ram_mb: u64, + #[serde(default)] + pub threads: u64, + pub runtime: RuntimeRef, +} + +#[derive(Clone, Debug, Default, Deserialize, PartialEq)] +pub struct Devices { + #[serde(default)] + pub cpu: bool, + #[serde(default)] + pub cuda: bool, + #[serde(default)] + pub mps: bool, +} + +#[derive(Clone, Debug, Deserialize, PartialEq)] +pub struct RuntimeRef { + pub name: String, + pub version: String, + pub lock_hash: String, +} + +/// Ask the local `infernet` what temporal workloads it can run. +pub async fn probe(infernet: &Path) -> Result { + let out = tokio::time::timeout( + Duration::from_secs(180), + tokio::process::Command::new(infernet) + .args(["model", "capabilities", "--json"]) + .stdin(std::process::Stdio::null()) + .output(), + ) + .await + .context("infernet model capabilities timed out")? + .with_context(|| format!("run {}", infernet.display()))?; + if !out.status.success() { + bail!( + "infernet model capabilities failed (runtime not installed? `infernet model runtime setup --yes`): {}", + String::from_utf8_lossy(&out.stderr).trim() + ); + } + serde_json::from_slice(&out.stdout).context("parse infernet model capabilities --json") +} + +pub fn model_tag(model_hash: &str) -> String { + format!("infernet:temporal:model:{}", model_hash.trim_start_matches("sha256:")) +} + +fn ram_tag(gb: u64) -> String { + format!("c0mpute:ram:{gb}gb+") +} + +/// Tags for a node whose Infernet reported `caps`, serving `models`. +/// `train` / `infer` say which workloads this node opted into. +pub fn tags(caps: &RuntimeCaps, models: &[String], train: bool, infer: bool) -> Vec { + let mut t = vec![ + "infernet:temporal:runtime".to_string(), + format!("infernet:temporal:runtime:{}", caps.runtime.version), + ]; + if train && caps.workloads.iter().any(|w| w == TRAIN_WORKLOAD) { + t.push(TRAIN_WORKLOAD.replace('.', ":")); + } + if infer && caps.workloads.iter().any(|w| w == INFER_WORKLOAD) { + t.push(INFER_WORKLOAD.replace('.', ":")); + } + t.push("infernet:temporal:device:cpu".into()); + if caps.devices.cuda { + t.push("infernet:temporal:device:cuda".into()); + } + if caps.devices.mps { + t.push("infernet:temporal:device:mps".into()); + } + for gb in RAM_BUCKETS_GB { + if caps.ram_mb >= gb * 1024 { + t.push(ram_tag(gb)); + } + } + if infer { + for m in models { + t.push(model_tag(m)); + } + } + t +} + +/// What a buyer needs from a worker. +#[derive(Clone, Debug, Default)] +pub struct Requirements { + pub gpu: bool, + pub min_ram_gb: Option, + pub runtime_version: Option, + pub model_hash: Option, +} + +/// Requirements → the `required_capabilities` of a `JobOffer`. The existing +/// dispatcher drops offers whose tags the worker does not advertise. +pub fn required_tags(workload: &str, r: &Requirements) -> Vec { + let mut t = vec![workload.replace('.', ":")]; + if r.gpu { + t.push("infernet:temporal:device:cuda".into()); + } + if let Some(min) = r.min_ram_gb { + let bucket = RAM_BUCKETS_GB.iter().copied().find(|b| *b >= min).unwrap_or(*RAM_BUCKETS_GB.last().unwrap()); + t.push(ram_tag(bucket)); + } + if let Some(v) = &r.runtime_version { + t.push(format!("infernet:temporal:runtime:{v}")); + } + if let Some(m) = &r.model_hash { + t.push(model_tag(m)); + } + t +} + +#[cfg(test)] +mod tests { + use super::*; + + fn caps(cuda: bool, ram_mb: u64) -> RuntimeCaps { + RuntimeCaps { + workloads: vec![TRAIN_WORKLOAD.into(), INFER_WORKLOAD.into()], + families: vec!["cfc".into(), "ltc".into(), "gru".into()], + devices: Devices { cpu: true, cuda, mps: false }, + ram_mb, + threads: 8, + runtime: RuntimeRef { name: "infernet-liquid".into(), version: "0.1.0".into(), lock_hash: format!("sha256:{}", "0".repeat(64)) }, + } + } + + fn eligible(adv: &[String], req: &[String]) -> bool { + req.iter().all(|r| adv.contains(r)) + } + + #[test] + fn filtering_by_runtime_device_ram_and_model() { + let m = format!("sha256:{}", "d".repeat(64)); + let cpu16 = tags(&caps(false, 16 * 1024), &[m.clone()], true, true); + let gpu64 = tags(&caps(true, 64 * 1024), &[], true, false); + let train_cpu = required_tags(TRAIN_WORKLOAD, &Requirements { min_ram_gb: Some(12), ..Default::default() }); + assert!(eligible(&cpu16, &train_cpu)); + assert!(eligible(&gpu64, &train_cpu)); + let train_gpu = required_tags(TRAIN_WORKLOAD, &Requirements { gpu: true, ..Default::default() }); + assert!(!eligible(&cpu16, &train_gpu)); + assert!(eligible(&gpu64, &train_gpu)); + let big = required_tags(TRAIN_WORKLOAD, &Requirements { min_ram_gb: Some(40), ..Default::default() }); + assert!(!eligible(&cpu16, &big)); + assert!(eligible(&gpu64, &big)); + let infer = required_tags(INFER_WORKLOAD, &Requirements { model_hash: Some(m.clone()), ..Default::default() }); + assert!(eligible(&cpu16, &infer)); + assert!(!eligible(&gpu64, &infer), "gpu64 did not opt into infer nor load the model"); + let ver = required_tags(TRAIN_WORKLOAD, &Requirements { runtime_version: Some("9.9.9".into()), ..Default::default() }); + assert!(!eligible(&cpu16, &ver)); + } + + #[test] + fn nothing_advertised_for_workloads_the_runtime_lacks() { + let mut c = caps(false, 8192); + c.workloads = vec![]; + let t = tags(&c, &[], true, true); + assert!(!t.iter().any(|x| x == "infernet:temporal:train" || x == "infernet:temporal:infer")); + } +} diff --git a/node/crates/c0mpute-core/src/temporal/client.rs b/node/crates/c0mpute-core/src/temporal/client.rs new file mode 100644 index 00000000..06ca5ec1 --- /dev/null +++ b/node/crates/c0mpute-core/src/temporal/client.rs @@ -0,0 +1,410 @@ +//! Buyer side: submit training to a (trusted) worker and drive inference +//! sessions that stay pinned to the worker that opened them. + +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::time::Duration; + +use anyhow::{Context, Result, bail}; +use c0mpute_net::topics::{JobStatus, job_topic}; +use c0mpute_net::{GossipMessage, Libp2pNetwork}; +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; +use sha2::{Digest, Sha256}; +use tokio::sync::broadcast; +use tokio::time::Instant; + +use super::caps::{Requirements, required_tags}; +use super::crypto; +use super::http::TransferServer; +use super::{INFER_WORKLOAD, SCHEMA_VERSION, SessionCall, SessionReady, SessionReply, SessionSpec, TRAIN_WORKLOAD, TrainSpec, select_family}; +use crate::buyer::{JobAuction, run_auction}; + +/// RFC 3339 UTC timestamp without pulling in a date crate. +pub fn now_rfc3339() -> String { + let secs = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0) as i64; + let (days, rem) = (secs.div_euclid(86_400), secs.rem_euclid(86_400)); + // civil_from_days (Howard Hinnant) + let z = days + 719_468; + let era = z.div_euclid(146_097); + let doe = z - era * 146_097; + let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + let mp = (5 * doy + 2) / 153; + let d = doy - (153 * mp + 2) / 5 + 1; + let m = if mp < 10 { mp + 3 } else { mp - 9 }; + let y = yoe + era * 400 + if m <= 2 { 1 } else { 0 }; + format!("{y:04}-{m:02}-{d:02}T{:02}:{:02}:{:02}Z", rem / 3600, rem % 3600 / 60, rem % 60) +} + +fn sha256_bytes(b: &[u8]) -> String { + format!("sha256:{}", hex::encode(Sha256::digest(b))) +} + +pub struct TrainRequest { + pub dataset_path: PathBuf, + pub output: PathBuf, + pub families: Vec, + pub workers: Vec, + pub max_price_usd: f64, + pub requirements: Requirements, + pub public_url: Option, + pub bind: std::net::SocketAddr, + pub timeout_s: u64, + pub retries: u32, + pub hyperparameters: Value, + pub bid_window: Duration, +} + +/// What the buyer is about to send, for the consent preview. +#[derive(Debug, Serialize)] +pub struct TrainPreview { + pub dataset_hash: String, + pub episodes: usize, + pub bytes: usize, + pub families: Vec, + pub workers: Vec, + pub max_price_usd: f64, + pub note: &'static str, +} + +pub const PRIVACY_NOTE: &str = "The winning worker receives the redacted dataset in plaintext to train on; transport security does not hide it from that worker. Only pick workers you trust."; + +pub fn read_dataset(p: &Path) -> Result<(Vec, String, usize)> { + let bytes = std::fs::read(p).with_context(|| format!("read {}", p.display()))?; + let v: Value = serde_json::from_slice(&bytes).context("dataset is not JSON")?; + if v["kind"] != "dataset_bundle" || v["schema_version"] != SCHEMA_VERSION { + bail!("{} is not a liquid-agent/v1 dataset_bundle", p.display()); + } + let hash = v["manifest"]["dataset_hash"].as_str().context("manifest.dataset_hash missing")?.to_string(); + let n = v["episodes"].as_array().map(|a| a.len()).unwrap_or(0); + Ok((bytes, hash, n)) +} + +pub fn preview(req: &TrainRequest) -> Result { + let (bytes, dataset_hash, episodes) = read_dataset(&req.dataset_path)?; + Ok(TrainPreview { + dataset_hash, + episodes, + bytes: bytes.len(), + families: req.families.clone(), + workers: req.workers.clone(), + max_price_usd: req.max_price_usd, + note: PRIVACY_NOTE, + }) +} + +pub fn train_job(family: &str, dataset_hash: &str, req: &TrainRequest) -> Value { + let mut hp = json!({"hidden_units": 64, "epochs": 40, "learning_rate": 0.005, "seed": 0}); + if let (Some(h), Some(o)) = (hp.as_object_mut(), req.hyperparameters.as_object()) { + for (k, v) in o { + h.insert(k.clone(), v.clone()); + } + } + let idem = blake3::hash(format!("{dataset_hash}|{family}|{hp}").as_bytes()).to_hex().to_string(); + let mut resources = json!({"device": if req.requirements.gpu { "cuda" } else { "auto" }, "gpu_required": req.requirements.gpu}); + if let Some(gb) = req.requirements.min_ram_gb { + resources["min_ram_mb"] = json!(gb * 1024); + } + json!({ + "schema_version": SCHEMA_VERSION, + "kind": "train_job", + "job_id": format!("tj_{}", &uuid::Uuid::new_v4().simple().to_string()[..16]), + "idempotency_key": &idem[..32], + "created_at": now_rfc3339(), + "dataset_hash": dataset_hash, + "dataset_ref": "c0mpute-transfer", + "model_type": family, + "hyperparameters": hp, + "resources": resources, + "limits": {"timeout_s": req.timeout_s, "max_retries": req.retries.min(5), "max_budget_usd": req.max_price_usd}, + "privacy": {"mode": "trusted_worker", "upload_approved": true, "worker_allowlist": req.workers}, + "retention": {"artifact_days": 30, "delete_dataset_after": true} + }) +} + +/// Train every family on remote worker(s), one single-node job each, and +/// verify the artifacts against the receipts. Output matches +/// `infernet model train --json` plus `receipts`. +pub async fn train(net: Arc, req: &TrainRequest) -> Result { + let (bytes, dataset_hash, _) = read_dataset(&req.dataset_path)?; + let server = TransferServer::start(req.bind, req.public_url.clone(), bytes).await?; + let tags = required_tags(TRAIN_WORKLOAD, &req.requirements); + let mut results = Vec::new(); + let mut receipts = Vec::new(); + for family in &req.families { + let job = train_job(family, &dataset_hash, req); + let spec = TrainSpec { + train_job: job, + dataset_url: server.dataset_url(), + dataset_hash: dataset_hash.clone(), + artifact_upload_url: Some(server.upload_url(family)), + }; + spec.validate()?; + let mut last_err = None; + let mut outcome = None; + for attempt in 0..=req.retries.min(5) { + let auction = JobAuction::new(TRAIN_WORKLOAD, serde_json::to_value(&spec)?) + .with_required_capabilities(tags.clone()) + .with_allowed_bidders(req.workers.clone()) + .with_max_price_usd(req.max_price_usd) + .with_bid_window(req.bid_window) + .with_deadline(Duration::from_secs(req.timeout_s + 600)) + .with_receipt_timeout(Duration::from_secs(req.timeout_s + 300)); + match run_auction(net.clone(), auction).await { + Ok(o) if o.receipt.status == JobStatus::Completed => { + outcome = Some(o); + break; + } + Ok(o) => last_err = Some(anyhow::anyhow!("worker {} reported {:?} (attempt {})", o.accepted_bid.bidder_peer_id, o.receipt.status, attempt + 1)), + Err(e) => last_err = Some(e.context(format!("attempt {}", attempt + 1))), + } + } + let Some(o) = outcome else { + return Err(last_err.unwrap_or_else(|| anyhow::anyhow!("training {family} failed"))); + }; + let files = server.take(family).await; + let weights = files.get("model.safetensors").context("worker did not upload model.safetensors")?; + let manifest_bytes = files.get("manifest.json").context("worker did not upload manifest.json")?; + let manifest: Value = serde_json::from_slice(manifest_bytes)?; + let got = sha256_bytes(weights); + let claimed = o.receipt.output_hash.clone().unwrap_or_default(); + if got != claimed || manifest["weights"]["weights_hash"].as_str() != Some(got.as_str()) { + bail!("artifact for {family} does not match the receipt: weights {got}, receipt {claimed}"); + } + if manifest["training"]["dataset_hash"].as_str() != Some(dataset_hash.as_str()) { + bail!("model for {family} was trained on a different dataset"); + } + let dir = req.output.join(family); + std::fs::create_dir_all(&dir)?; + for (name, data) in &files { + std::fs::write(dir.join(name), data)?; + } + let eval: Value = files.get("eval.json").and_then(|b| serde_json::from_slice(b).ok()).unwrap_or(json!({})); + receipts.push(json!({ + "job_id": o.receipt.job_id, "worker_peer_id": o.receipt.worker_peer_id, + "output_hash": o.receipt.output_hash, "status": "completed", "price_usd": o.accepted_bid.price_usd + })); + results.push(json!({"family": family, "model_dir": dir, "model_hash": got, "eval": eval, "worker_peer_id": o.receipt.worker_peer_id})); + } + let scores: Vec<(String, f64)> = results + .iter() + .map(|r| (r["family"].as_str().unwrap_or("").to_string(), r["eval"]["metrics"]["episode_success"].as_f64().unwrap_or(0.0))) + .collect(); + Ok(json!({"dataset_hash": dataset_hash, "results": results, "selected": select_family(&scores), "receipts": receipts})) +} + +// ── sessions ──────────────────────────────────────────────────────────── + +/// Local record of an open remote session (kept 0600 in the data dir). +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct SessionFile { + pub session_id: String, + pub model_hash: String, + pub worker_peer_id: String, + pub worker_pubkey: String, + pub client_secret: String, + pub account_scope: String, + pub next_seq: i64, + pub job_id: String, +} + +impl SessionFile { + pub fn path(dir: &Path, session_id: &str) -> PathBuf { + dir.join(format!("{session_id}.json")) + } + + pub fn load(dir: &Path, session_id: &str) -> Result> { + let p = Self::path(dir, session_id); + if !p.exists() { + return Ok(None); + } + Ok(Some(serde_json::from_slice(&std::fs::read(p)?)?)) + } + + pub fn save(&self, dir: &Path) -> Result<()> { + std::fs::create_dir_all(dir)?; + let p = Self::path(dir, &self.session_id); + std::fs::write(&p, serde_json::to_vec_pretty(self)?)?; + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o600))?; + } + Ok(()) + } + + fn key(&self) -> Result<[u8; 32]> { + crypto::session_key(&crypto::secret_from_hex(&self.client_secret)?, &self.worker_pubkey, &self.session_id) + } +} + +pub struct OpenRequest { + pub model_hash: String, + pub session_id: String, + pub ttl_s: u64, + pub account_scope: String, + pub workers: Vec, + pub max_price_usd: f64, + pub bid_window: Duration, +} + +/// Auction a session open; the winner holds the session from then on. +pub async fn open_session(net: Arc, req: &OpenRequest) -> Result { + let kp = crypto::keypair(); + let spec = SessionSpec { + model_hash: req.model_hash.clone(), + session_id: req.session_id.clone(), + ttl_s: req.ttl_s, + account_scope: req.account_scope.clone(), + client_pubkey: kp.public_hex.clone(), + }; + spec.validate()?; + let mut rx = net.messages(); + let tags = required_tags(INFER_WORKLOAD, &Requirements { model_hash: Some(req.model_hash.clone()), ..Default::default() }); + let auction = JobAuction::new(INFER_WORKLOAD, serde_json::to_value(&spec)?) + .with_required_capabilities(tags) + .with_allowed_bidders(req.workers.clone()) + .with_max_price_usd(req.max_price_usd) + .with_bid_window(req.bid_window) + .with_receipt_timeout(Duration::from_secs(60)); + let o = run_auction(net.clone(), auction).await?; + if o.receipt.status != JobStatus::Completed || o.receipt.output_hash.as_deref() != Some(req.model_hash.as_str()) { + bail!("worker {} could not open the session ({:?})", o.accepted_bid.bidder_peer_id, o.receipt.status); + } + let topic = job_topic(INFER_WORKLOAD); + let deadline = Instant::now() + Duration::from_secs(10); + while Instant::now() < deadline { + let msg = match tokio::time::timeout(deadline.saturating_duration_since(Instant::now()), rx.recv()).await { + Ok(Ok(m)) => m, + Ok(Err(broadcast::error::RecvError::Lagged(_))) => continue, + _ => break, + }; + if msg.topic != topic { + continue; + } + if let Ok(r) = serde_json::from_slice::(&msg.data) { + if r.t == "temporal_ready" && r.job_id == o.job_id && r.worker_peer_id == o.accepted_bid.bidder_peer_id && from(&msg, &r.worker_peer_id) { + return Ok(SessionFile { + session_id: req.session_id.clone(), + model_hash: req.model_hash.clone(), + worker_peer_id: r.worker_peer_id, + worker_pubkey: r.worker_pubkey, + client_secret: hex::encode(kp.secret.to_bytes()), + account_scope: req.account_scope.clone(), + next_seq: 0, + job_id: o.job_id, + }); + } + } + } + bail!("worker opened the session but its key never arrived") +} + +fn from(msg: &GossipMessage, peer: &str) -> bool { + msg.source.map(|p| p.to_base58()).as_deref() == Some(peer) +} + +/// One sealed call to the session's worker (republished until answered, +/// since a fresh gossip mesh may drop the first copy). +pub async fn call(net: Arc, sf: &SessionFile, body: Value, timeout: Duration) -> Result { + let key = sf.key()?; + let call_id = uuid::Uuid::new_v4().simple().to_string(); + let msg = SessionCall { + t: "temporal_call".into(), + session_id: sf.session_id.clone(), + worker_peer_id: sf.worker_peer_id.clone(), + call_id: call_id.clone(), + sealed: crypto::seal(&key, body.to_string().as_bytes())?, + }; + let topic = job_topic(INFER_WORKLOAD); + net.subscribe(&topic).await?; + let mut rx = net.messages(); + let payload = serde_json::to_vec(&msg)?; + let deadline = Instant::now() + timeout; + let mut next_send = Instant::now(); + while Instant::now() < deadline { + if Instant::now() >= next_send { + let _ = net.publish(&topic, payload.clone()).await; + next_send = Instant::now() + Duration::from_secs(2); + } + let wait = next_send.min(deadline).saturating_duration_since(Instant::now()); + match tokio::time::timeout(wait, rx.recv()).await { + Ok(Ok(m)) if m.topic == topic => { + if let Ok(r) = serde_json::from_slice::(&m.data) { + if r.t == "temporal_reply" && r.call_id == call_id && from(&m, &sf.worker_peer_id) { + let plain = crypto::open(&key, &r.sealed)?; + return Ok(serde_json::from_slice(&plain)?); + } + } + } + Ok(Err(broadcast::error::RecvError::Closed)) => bail!("network closed"), + _ => {} + } + } + bail!("E_TIMEOUT: worker {} did not answer (session lost? reopen it)", sf.worker_peer_id) +} + +/// Build a `PredictRequestV1` from a step file: either a full request or +/// `{observation, dt_ms?, prev_action?, task?}`. +pub fn predict_request(step: &Value, sf: &SessionFile) -> Result { + if step.get("observation").is_none() { + bail!("step needs an observation"); + } + let mut r = json!({ + "schema_version": SCHEMA_VERSION, + "kind": "predict_request", + "session_id": sf.session_id, + "model_hash": sf.model_hash, + "sequence_index": step.get("sequence_index").and_then(|v| v.as_i64()).unwrap_or(sf.next_seq), + "dt_ms": step.get("dt_ms").and_then(|v| v.as_u64()).unwrap_or(0), + "observation": step["observation"], + "prev_action": step.get("prev_action").cloned().unwrap_or(Value::Null) + }); + if let Some(t) = step.get("task") { + r["task"] = t.clone(); + } + Ok(r) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn rfc3339_shape() { + let t = now_rfc3339(); + assert_eq!(t.len(), 20); + assert!(t.ends_with('Z') && t.as_bytes()[10] == b'T'); + assert!(t.starts_with("20")); + } + + #[test] + fn train_job_is_remote_approved_and_stable_idempotency() { + let req = TrainRequest { + dataset_path: "x".into(), + output: "o".into(), + families: vec!["cfc".into()], + workers: vec!["peer1".into()], + max_price_usd: 0.5, + requirements: Requirements { min_ram_gb: Some(8), ..Default::default() }, + public_url: None, + bind: "127.0.0.1:0".parse().unwrap(), + timeout_s: 600, + retries: 1, + hyperparameters: json!({"epochs": 3}), + bid_window: Duration::from_secs(1), + }; + let h = format!("sha256:{}", "e".repeat(64)); + let a = train_job("cfc", &h, &req); + let b = train_job("cfc", &h, &req); + assert_eq!(a["idempotency_key"], b["idempotency_key"]); + assert_ne!(a["job_id"], b["job_id"]); + assert_ne!(train_job("gru", &h, &req)["idempotency_key"], a["idempotency_key"]); + assert_eq!(a["privacy"]["upload_approved"], true); + assert_eq!(a["hyperparameters"]["epochs"], 3); + assert_eq!(a["resources"]["min_ram_mb"], 8192); + let spec = TrainSpec { train_job: a, dataset_url: "http://h/d".into(), dataset_hash: h, artifact_upload_url: None }; + spec.validate().unwrap(); + } +} diff --git a/node/crates/c0mpute-core/src/temporal/crypto.rs b/node/crates/c0mpute-core/src/temporal/crypto.rs new file mode 100644 index 00000000..3ca69f83 --- /dev/null +++ b/node/crates/c0mpute-core/src/temporal/crypto.rs @@ -0,0 +1,87 @@ +//! Session call encryption: X25519 key agreement → HKDF-SHA256 → +//! AES-256-GCM. Gossip topics are readable by every subscriber, so the +//! observations and proposals of an inference session travel sealed between +//! the buyer and the one worker holding the session. This protects data on +//! the wire only; the worker necessarily sees plaintext. + +use aes_gcm::aead::{Aead, KeyInit}; +use aes_gcm::{Aes256Gcm, Nonce}; +use anyhow::{Result, anyhow, bail}; +use base64::Engine; +use base64::engine::general_purpose::STANDARD as B64; +use hkdf::Hkdf; +use rand::RngCore; +use sha2::Sha256; +use x25519_dalek::{PublicKey, StaticSecret}; + +pub struct KeyPair { + pub secret: StaticSecret, + pub public_hex: String, +} + +pub fn keypair() -> KeyPair { + let secret = StaticSecret::random_from_rng(rand::rngs::OsRng); + let public_hex = hex::encode(PublicKey::from(&secret).as_bytes()); + KeyPair { secret, public_hex } +} + +pub fn secret_from_hex(h: &str) -> Result { + let b: [u8; 32] = hex::decode(h)?.try_into().map_err(|_| anyhow!("secret must be 32 bytes"))?; + Ok(StaticSecret::from(b)) +} + +/// Shared session key; `session_id` binds it to one session. +pub fn session_key(secret: &StaticSecret, peer_pub_hex: &str, session_id: &str) -> Result<[u8; 32]> { + let p: [u8; 32] = hex::decode(peer_pub_hex)?.try_into().map_err(|_| anyhow!("public key must be 32 bytes"))?; + let shared = secret.diffie_hellman(&PublicKey::from(p)); + if !shared.was_contributory() { + bail!("weak peer public key"); + } + let hk = Hkdf::::new(Some(b"c0mpute/infernet.temporal/v1"), shared.as_bytes()); + let mut key = [0u8; 32]; + hk.expand(session_id.as_bytes(), &mut key).map_err(|_| anyhow!("hkdf expand"))?; + Ok(key) +} + +pub fn seal(key: &[u8; 32], plaintext: &[u8]) -> Result { + let cipher = Aes256Gcm::new_from_slice(key).map_err(|_| anyhow!("key"))?; + let mut nonce = [0u8; 12]; + rand::rngs::OsRng.fill_bytes(&mut nonce); + let ct = cipher.encrypt(Nonce::from_slice(&nonce), plaintext).map_err(|_| anyhow!("encrypt"))?; + let mut out = nonce.to_vec(); + out.extend(ct); + Ok(B64.encode(out)) +} + +pub fn open(key: &[u8; 32], sealed: &str) -> Result> { + let raw = B64.decode(sealed)?; + if raw.len() < 12 + 16 { + bail!("sealed payload too short"); + } + let cipher = Aes256Gcm::new_from_slice(key).map_err(|_| anyhow!("key"))?; + cipher.decrypt(Nonce::from_slice(&raw[..12]), &raw[12..]).map_err(|_| anyhow!("decrypt failed (wrong key or tampered)")) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn both_sides_derive_the_same_key_and_tamper_fails() { + let a = keypair(); + let b = keypair(); + let ka = session_key(&a.secret, &b.public_hex, "s1").unwrap(); + let kb = session_key(&b.secret, &a.public_hex, "s1").unwrap(); + assert_eq!(ka, kb); + assert_ne!(ka, session_key(&a.secret, &b.public_hex, "s2").unwrap()); + let s = seal(&ka, b"{\"op\":\"predict\"}").unwrap(); + assert_eq!(open(&kb, &s).unwrap(), b"{\"op\":\"predict\"}"); + let mut raw = B64.decode(&s).unwrap(); + let last = raw.len() - 1; + raw[last] ^= 1; + assert!(open(&kb, &B64.encode(raw)).is_err()); + let c = keypair(); + let kc = session_key(&c.secret, &a.public_hex, "s1").unwrap(); + assert!(open(&kc, &s).is_err()); + } +} diff --git a/node/crates/c0mpute-core/src/temporal/http.rs b/node/crates/c0mpute-core/src/temporal/http.rs new file mode 100644 index 00000000..4b43e1bd --- /dev/null +++ b/node/crates/c0mpute-core/src/temporal/http.rs @@ -0,0 +1,116 @@ +//! Buyer-side transfer server for remote training: serves the dataset +//! bundle to the winning worker and receives the trained artifacts. +//! +//! Every URL carries a random 128-bit token; only three artifact names are +//! accepted. Put it behind https (`--public-url https://...`) when the +//! worker is outside your LAN: the token gates access, it does not encrypt. +//! The buyer verifies every artifact against the receipt's model hash. + +use std::collections::HashMap; +use std::net::SocketAddr; +use std::sync::Arc; + +use anyhow::Result; +use axum::Router; +use axum::body::Bytes; +use axum::extract::{DefaultBodyLimit, Path, State}; +use axum::http::StatusCode; +use axum::routing::{get, put}; +use rand::RngCore; +use tokio::sync::Mutex; + +pub const ARTIFACTS: [&str; 3] = ["manifest.json", "model.safetensors", "eval.json"]; +const MAX_UPLOAD: usize = 1 << 30; + +#[derive(Clone)] +struct St { + token: String, + dataset: Arc>, + uploads: Arc>>>, +} + +pub struct TransferServer { + pub base_url: String, + pub local_addr: SocketAddr, + token: String, + uploads: Arc>>>, +} + +fn ok_slot(s: &str) -> bool { + !s.is_empty() && s.len() <= 64 && s.bytes().all(|b| b.is_ascii_alphanumeric() || b"_-".contains(&b)) +} + +async fn get_dataset(State(st): State, Path(token): Path) -> Result, StatusCode> { + if token != st.token { + return Err(StatusCode::NOT_FOUND); + } + Ok(st.dataset.as_ref().clone()) +} + +async fn put_artifact(State(st): State, Path((token, slot, file)): Path<(String, String, String)>, body: Bytes) -> StatusCode { + if token != st.token || !ok_slot(&slot) || !ARTIFACTS.contains(&file.as_str()) { + return StatusCode::NOT_FOUND; + } + st.uploads.lock().await.insert((slot, file), body.to_vec()); + StatusCode::CREATED +} + +impl TransferServer { + /// Bind `bind` and serve `dataset`. `public_base` is how the worker + /// reaches this server (defaults to `http://`). + pub async fn start(bind: SocketAddr, public_base: Option, dataset: Vec) -> Result { + let mut t = [0u8; 16]; + rand::rngs::OsRng.fill_bytes(&mut t); + let token = hex::encode(t); + let uploads = Arc::new(Mutex::new(HashMap::new())); + let st = St { token: token.clone(), dataset: Arc::new(dataset), uploads: uploads.clone() }; + let app = Router::new() + .route("/t/{token}/dataset.json", get(get_dataset)) + .route("/t/{token}/a/{slot}/{file}", put(put_artifact)) + .layer(DefaultBodyLimit::max(MAX_UPLOAD)) + .with_state(st); + let listener = tokio::net::TcpListener::bind(bind).await?; + let local_addr = listener.local_addr()?; + tokio::spawn(async move { + let _ = axum::serve(listener, app).await; + }); + let base_url = public_base.unwrap_or_else(|| format!("http://{local_addr}")).trim_end_matches('/').to_string(); + Ok(Self { base_url, local_addr, token, uploads }) + } + + pub fn dataset_url(&self) -> String { + format!("{}/t/{}/dataset.json", self.base_url, self.token) + } + + pub fn upload_url(&self, slot: &str) -> String { + format!("{}/t/{}/a/{}", self.base_url, self.token, slot) + } + + /// Artifacts uploaded for `slot`, by file name. + pub async fn take(&self, slot: &str) -> HashMap> { + let mut u = self.uploads.lock().await; + let keys: Vec<_> = u.keys().filter(|(s, _)| s == slot).cloned().collect(); + keys.into_iter().filter_map(|k| u.remove(&k).map(|v| (k.1, v))).collect() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[tokio::test] + async fn token_gates_dataset_and_uploads() { + let s = TransferServer::start("127.0.0.1:0".parse().unwrap(), None, b"{\"x\":1}".to_vec()).await.unwrap(); + let c = reqwest::Client::new(); + assert_eq!(c.get(s.dataset_url()).send().await.unwrap().bytes().await.unwrap().as_ref(), b"{\"x\":1}"); + let wrong = s.dataset_url().replace(&s.token, &"0".repeat(32)); + assert_eq!(c.get(wrong).send().await.unwrap().status(), 404); + let up = format!("{}/model.safetensors", s.upload_url("cfc")); + assert_eq!(c.put(&up).body("w").send().await.unwrap().status(), 201); + let bad = format!("{}/evil.sh", s.upload_url("cfc")); + assert_eq!(c.put(&bad).body("x").send().await.unwrap().status(), 404); + let got = s.take("cfc").await; + assert_eq!(got.get("model.safetensors").map(|v| v.as_slice()), Some(&b"w"[..])); + assert!(s.take("cfc").await.is_empty()); + } +} diff --git a/node/crates/c0mpute-core/src/temporal/mod.rs b/node/crates/c0mpute-core/src/temporal/mod.rs new file mode 100644 index 00000000..229a44a4 --- /dev/null +++ b/node/crates/c0mpute-core/src/temporal/mod.rs @@ -0,0 +1,254 @@ +//! Infernet temporal policies on c0mpute: workloads `infernet.temporal.train` +//! and `infernet.temporal.infer` (CfC/LTC liquid networks, GRU baseline). +//! +//! c0mpute stays the infrastructure layer. The model code lives in Infernet +//! (`infernet model train|serve`, which runs the isolated infernet-liquid +//! Python runtime); this module only: +//! +//! * advertises what the local Infernet can actually execute (`caps`), +//! * turns buyer requirements into the capability tags the existing +//! offer filter matches (runtime, CPU/GPU, RAM bucket, model hash), +//! * runs one training job per node (`worker::spawn_train_runner`), and +//! * keeps each inference session on the worker that holds its hidden +//! state (`worker::InferServer`), with predict calls end-to-end encrypted +//! between buyer and that worker over the job topic. +//! +//! Everything rides the existing offer → bid → accept → receipt protocol. +//! The receipt's `output_hash` is the model hash (`sha256:` of the +//! safetensors file) for training and for a session open. + +pub mod caps; +pub mod client; +pub mod crypto; +pub mod http; +pub mod node; +pub mod runtime; +pub mod worker; + +use anyhow::{Result, bail}; +use serde::{Deserialize, Serialize}; + +pub const TRAIN_WORKLOAD: &str = "infernet.temporal.train"; +pub const INFER_WORKLOAD: &str = "infernet.temporal.infer"; +pub const SCHEMA_VERSION: &str = "liquid-agent/v1"; +pub const FAMILIES: [&str; 3] = ["cfc", "ltc", "gru"]; + +/// `JobOffer.spec_inline` for `infernet.temporal.train`. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +pub struct TrainSpec { + /// A liquid-agent/v1 `TrainJobV1`. Infernet validates it fully; the + /// worker checks the fields that decide whether to bid at all. + pub train_job: serde_json::Value, + /// Where the worker fetches the `DatasetBundleV1` (http or https). + pub dataset_url: String, + /// Must equal `train_job.dataset_hash`; Infernet re-derives it from the + /// bundle and refuses a mismatch. + pub dataset_hash: String, + /// Base URL the worker PUTs `manifest.json`, `model.safetensors` and + /// `eval.json` to. Without it the artifacts stay on the worker. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub artifact_upload_url: Option, +} + +pub fn is_sha256_ref(s: &str) -> bool { + s.strip_prefix("sha256:") + .is_some_and(|h| h.len() == 64 && h.bytes().all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase())) +} + +fn is_http(u: &str) -> bool { + u.starts_with("http://") || u.starts_with("https://") +} + +impl TrainSpec { + pub fn family(&self) -> &str { + self.train_job.get("model_type").and_then(|v| v.as_str()).unwrap_or("") + } + + pub fn idempotency_key(&self) -> &str { + self.train_job.get("idempotency_key").and_then(|v| v.as_str()).unwrap_or("") + } + + /// The checks a worker runs before bidding. A remote job without the + /// user's upload approval is never accepted, whatever the buyer claims. + pub fn validate(&self) -> Result<()> { + let j = &self.train_job; + if j.get("schema_version").and_then(|v| v.as_str()) != Some(SCHEMA_VERSION) + || j.get("kind").and_then(|v| v.as_str()) != Some("train_job") + { + bail!("train_job is not a liquid-agent/v1 train_job"); + } + if !FAMILIES.contains(&self.family()) { + bail!("unknown model_type {:?}", self.family()); + } + if !is_sha256_ref(&self.dataset_hash) { + bail!("dataset_hash must be sha256:<64 hex>"); + } + if j.get("dataset_hash").and_then(|v| v.as_str()) != Some(self.dataset_hash.as_str()) { + bail!("train_job.dataset_hash differs from the offer's dataset_hash"); + } + let privacy = j.get("privacy").cloned().unwrap_or_default(); + if privacy.get("mode").and_then(|v| v.as_str()) != Some("trusted_worker") + || privacy.get("upload_approved").and_then(|v| v.as_bool()) != Some(true) + { + bail!("remote training needs privacy.mode=trusted_worker and upload_approved=true"); + } + if self.idempotency_key().len() < 8 { + bail!("train_job.idempotency_key is required"); + } + if !is_http(&self.dataset_url) { + bail!("dataset_url must be http(s)"); + } + if let Some(u) = &self.artifact_upload_url { + if !is_http(u) { + bail!("artifact_upload_url must be http(s)"); + } + } + Ok(()) + } +} + +/// `JobOffer.spec_inline` for `infernet.temporal.infer`: open one session. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +pub struct SessionSpec { + pub model_hash: String, + pub session_id: String, + pub ttl_s: u64, + /// Opaque tenant id; sessions never share state across scopes. + pub account_scope: String, + /// Buyer's X25519 public key (hex) for the session's call encryption. + pub client_pubkey: String, +} + +impl SessionSpec { + pub fn validate(&self) -> Result<()> { + if !is_sha256_ref(&self.model_hash) { + bail!("model_hash must be sha256:<64 hex>"); + } + if self.session_id.is_empty() + || self.session_id.len() > 64 + || !self.session_id.bytes().all(|b| b.is_ascii_alphanumeric() || b"_.-".contains(&b)) + { + bail!("session_id must be 1-64 of [A-Za-z0-9_.-]"); + } + if !(1..=86_400).contains(&self.ttl_s) { + bail!("ttl_s must be 1..86400"); + } + if self.client_pubkey.len() != 64 || hex::decode(&self.client_pubkey).is_err() { + bail!("client_pubkey must be 32 bytes hex"); + } + Ok(()) + } +} + +/// Worker → buyer after a session opens: the worker's half of the key exchange. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +pub struct SessionReady { + pub t: String, // "temporal_ready" + pub job_id: String, + pub session_id: String, + pub worker_peer_id: String, + pub worker_pubkey: String, + pub model_hash: String, +} + +/// Buyer → worker: one encrypted runtime op (`predict`, `reset`, +/// `close_session`, `checkpoint`) for a session that worker holds. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +pub struct SessionCall { + pub t: String, // "temporal_call" + pub session_id: String, + pub worker_peer_id: String, + pub call_id: String, + pub sealed: String, +} + +/// Worker → buyer: the encrypted runtime response. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +pub struct SessionReply { + pub t: String, // "temporal_reply" + pub session_id: String, + pub call_id: String, + pub sealed: String, +} + +/// The liquid-agent rule: a liquid family is chosen only when it beats the +/// GRU baseline on the predeclared metric (`episode_success`). +pub fn select_family(results: &[(String, f64)]) -> Option { + let baseline = results.iter().find(|(f, _)| f == "gru").or(results.first())?; + results + .iter() + .filter(|(f, s)| f != &baseline.0 && *s > baseline.1) + .max_by(|a, b| a.1.partial_cmp(&b.1).unwrap_or(std::cmp::Ordering::Equal)) + .or(Some(baseline)) + .map(|(f, _)| f.clone()) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn spec() -> TrainSpec { + let h = format!("sha256:{}", "a".repeat(64)); + TrainSpec { + train_job: json!({ + "schema_version": SCHEMA_VERSION, "kind": "train_job", "job_id": "tj_test_0001", + "idempotency_key": "idem-0001-abc", "dataset_hash": h, "model_type": "cfc", + "privacy": {"mode": "trusted_worker", "upload_approved": true} + }), + dataset_url: "http://127.0.0.1:1/d/x/dataset.json".into(), + dataset_hash: h, + artifact_upload_url: None, + } + } + + #[test] + fn train_spec_requires_upload_approval_and_matching_hash() { + assert!(spec().validate().is_ok()); + let mut s = spec(); + s.train_job["privacy"]["upload_approved"] = json!(false); + assert!(s.validate().unwrap_err().to_string().contains("upload_approved")); + let mut s = spec(); + s.train_job["privacy"]["mode"] = json!("local_only"); + assert!(s.validate().is_err()); + let mut s = spec(); + s.dataset_hash = format!("sha256:{}", "b".repeat(64)); + assert!(s.validate().unwrap_err().to_string().contains("differs")); + let mut s = spec(); + s.train_job["model_type"] = json!("transformer"); + assert!(s.validate().is_err()); + let mut s = spec(); + s.dataset_url = "file:///etc/passwd".into(); + assert!(s.validate().is_err()); + } + + #[test] + fn session_spec_validation() { + let ok = SessionSpec { + model_hash: format!("sha256:{}", "c".repeat(64)), + session_id: "s-1".into(), + ttl_s: 600, + account_scope: "acct".into(), + client_pubkey: "00".repeat(32), + }; + assert!(ok.validate().is_ok()); + let mut bad = ok.clone(); + bad.session_id = "a/b".into(); + assert!(bad.validate().is_err()); + let mut bad = ok.clone(); + bad.model_hash = "md5:1".into(); + assert!(bad.validate().is_err()); + let mut bad = ok; + bad.ttl_s = 0; + assert!(bad.validate().is_err()); + } + + #[test] + fn liquid_wins_only_by_beating_gru() { + let r = |v: &[(&str, f64)]| select_family(&v.iter().map(|(f, s)| (f.to_string(), *s)).collect::>()); + assert_eq!(r(&[("cfc", 0.9), ("gru", 0.9)]).as_deref(), Some("gru")); + assert_eq!(r(&[("cfc", 0.95), ("gru", 0.9)]).as_deref(), Some("cfc")); + assert_eq!(r(&[("cfc", 0.8), ("gru", 0.9), ("ltc", 0.92)]).as_deref(), Some("ltc")); + assert_eq!(r(&[("cfc", 0.8)]).as_deref(), Some("cfc")); + } +} diff --git a/node/crates/c0mpute-core/src/temporal/node.rs b/node/crates/c0mpute-core/src/temporal/node.rs new file mode 100644 index 00000000..976e4226 --- /dev/null +++ b/node/crates/c0mpute-core/src/temporal/node.rs @@ -0,0 +1,92 @@ +//! Process-level wiring for `c0mpute infernet temporal serve` and the buyer +//! commands: a libp2p node, capability ads and the two workload subscribers. + +use std::path::PathBuf; +use std::sync::Arc; +use std::sync::atomic::AtomicBool; +use std::time::Duration; + +use anyhow::{Context, Result, bail}; +use c0mpute_net::{Libp2pNetwork, Multiaddr, NetworkConfig, bootstrap}; +use tracing::info; + +use super::caps::{self, RuntimeCaps}; +use super::worker::{self, InferServer, ModelStore}; +use super::{INFER_WORKLOAD, TRAIN_WORKLOAD}; +use crate::capabilities; +use crate::dispatch; + +#[derive(Clone, Debug)] +pub struct NetOptions { + pub identity_dir: PathBuf, + pub listen: Vec, + pub bootstrap: Vec, + /// Also dial c0mpute.com's seeds (off for isolated/local runs). + pub default_bootstrap: bool, +} + +pub async fn spawn_node(o: &NetOptions) -> Result> { + std::fs::create_dir_all(&o.identity_dir)?; + let parse = |v: &[String]| -> Result> { v.iter().map(|s| s.parse::().with_context(|| format!("bad multiaddr {s}"))).collect() }; + let mut boot = parse(&o.bootstrap)?; + if o.default_bootstrap { + boot.extend(bootstrap::fetch_or_fallback(bootstrap::DEFAULT_BOOTSTRAP_URL, bootstrap::default_seeds()).await); + } + let listen = if o.listen.is_empty() { vec!["/ip4/0.0.0.0/tcp/0".to_string()] } else { o.listen.clone() }; + let cfg = NetworkConfig::for_dir(o.identity_dir.clone()).with_listen(parse(&listen)?).with_bootstrap(boot); + Ok(Arc::new(Libp2pNetwork::spawn(cfg).await?)) +} + +#[derive(Clone, Debug)] +pub struct ServeOptions { + pub net: NetOptions, + pub infernet: PathBuf, + /// Model dirs or `sha256:` hashes from the store to serve for inference. + pub models: Vec, + /// Accept `infernet.temporal.train` jobs too. + pub train: bool, + pub max_sessions: u32, + pub store: ModelStore, + pub cache_root: PathBuf, +} + +pub struct Serving { + pub net: Arc, + pub caps: RuntimeCaps, + pub tags: Vec, + pub infer: Option>, +} + +/// Start serving. Advertises only what the local Infernet reports it can run. +pub async fn serve(o: &ServeOptions) -> Result { + let caps = caps::probe(&o.infernet).await?; + if !o.train && o.models.is_empty() { + bail!("nothing to serve: pass --model and/or --train"); + } + let net = spawn_node(&o.net).await?; + let me = net.peer_id().to_base58(); + let mut resolved = Vec::new(); + for m in &o.models { + resolved.push(o.store.resolve(m)?); + } + let infer = if resolved.is_empty() { None } else { Some(InferServer::start(&o.infernet, &resolved, &me, o.max_sessions).await?) }; + let models: Vec = infer.as_ref().map(|s| s.models.clone()).unwrap_or_default(); + let tags = caps::tags(&caps, &models, o.train, infer.is_some()); + let mut hardware = serde_json::json!({"version": env!("CARGO_PKG_VERSION"), "temporal_runtime": caps.runtime.version, "ram_mb": caps.ram_mb, "cuda": caps.devices.cuda}); + hardware["models"] = serde_json::json!(models); + tokio::spawn(capabilities::advertise_loop(net.clone(), tags.clone(), hardware, capabilities::local_bench_score(), capabilities::DEFAULT_ADVERTISE_INTERVAL)); + if o.train { + let busy = Arc::new(AtomicBool::new(false)); + let tx = worker::spawn_train_runner(net.clone(), o.cache_root.clone(), o.infernet.clone(), o.store.clone(), busy.clone()); + dispatch::run_worker_subscriber_filtered(net.clone(), TRAIN_WORKLOAD.into(), tags.clone(), Some(tx), Some(worker::train_offer_filter(busy))); + } + if let Some(server) = &infer { + let tx = worker::spawn_infer_runner(net.clone(), server.clone()); + dispatch::run_worker_subscriber_filtered(net.clone(), INFER_WORKLOAD.into(), tags.clone(), Some(tx), Some(worker::infer_offer_filter(models.clone()))); + worker::spawn_call_listener(net.clone(), server.clone()); + } + info!(peer = %me, ?tags, "temporal: serving"); + // Let the subscriptions land before callers start publishing. + tokio::time::sleep(Duration::from_millis(300)).await; + Ok(Serving { net, caps, tags, infer }) +} diff --git a/node/crates/c0mpute-core/src/temporal/runtime.rs b/node/crates/c0mpute-core/src/temporal/runtime.rs new file mode 100644 index 00000000..bb18259f --- /dev/null +++ b/node/crates/c0mpute-core/src/temporal/runtime.rs @@ -0,0 +1,128 @@ +//! Client for `infernet model serve --stdio`: Infernet's temporal runtime +//! contract (NDJSON, protocol 1) on a child process. c0mpute never links +//! Python; the child is Infernet's, which runs its own pinned runtime. + +use std::collections::HashMap; +use std::path::Path; +use std::process::Stdio; +use std::sync::Arc; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::time::Duration; + +use anyhow::{Context, Result}; +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; +use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader}; +use tokio::process::{Child, ChildStdin, Command}; +use tokio::sync::{Mutex, oneshot}; + +/// The contract's error object (`code`, `message`, `retriable`). +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +pub struct RuntimeError { + pub code: String, + pub message: String, + #[serde(default)] + pub retriable: bool, +} + +impl std::fmt::Display for RuntimeError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{}: {}", self.code, self.message) + } +} + +impl std::error::Error for RuntimeError {} + +impl RuntimeError { + pub fn new(code: &str, message: impl Into) -> Self { + let retriable = matches!(code, "E_CAPACITY" | "E_TIMEOUT" | "E_RUNTIME"); + Self { code: code.into(), message: message.into(), retriable } + } +} + +type Pending = Arc>>>; + +pub struct RuntimeProc { + stdin: Mutex, + pending: Pending, + seq: AtomicU64, + child: Mutex, +} + +impl RuntimeProc { + /// Spawn ` model serve --stdio [extra]`. + pub async fn spawn(infernet: &Path, extra: &[String]) -> Result> { + let mut child = Command::new(infernet) + .args(["model", "serve", "--stdio"]) + .args(extra) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::inherit()) + .kill_on_drop(true) + .spawn() + .with_context(|| format!("spawn {} model serve --stdio", infernet.display()))?; + let stdin = child.stdin.take().context("runtime stdin")?; + let stdout = child.stdout.take().context("runtime stdout")?; + let pending: Pending = Arc::new(Mutex::new(HashMap::new())); + let p2 = pending.clone(); + tokio::spawn(async move { + let mut lines = BufReader::new(stdout).lines(); + while let Ok(Some(line)) = lines.next_line().await { + let Ok(msg) = serde_json::from_str::(&line) else { continue }; + if msg.get("event").is_some() { + continue; + } + let Some(id) = msg.get("id").and_then(|v| v.as_str()).map(str::to_string) else { continue }; + if let Some(tx) = p2.lock().await.remove(&id) { + let _ = tx.send(msg); + } + } + // Runtime gone: fail everything still waiting. + for (_, tx) in p2.lock().await.drain() { + let _ = tx.send(json!({"ok": false, "error": {"code": "E_RUNTIME", "message": "infernet runtime exited", "retriable": true}})); + } + }); + Ok(Arc::new(Self { stdin: Mutex::new(stdin), pending, seq: AtomicU64::new(0), child: Mutex::new(child) })) + } + + pub async fn request(&self, op: &str, params: Value, timeout: Duration) -> std::result::Result { + let id = format!("c{}", self.seq.fetch_add(1, Ordering::Relaxed) + 1); + let (tx, rx) = oneshot::channel(); + self.pending.lock().await.insert(id.clone(), tx); + let mut msg = json!({"v": 1, "id": id, "op": op}); + if let (Some(m), Value::Object(p)) = (msg.as_object_mut(), params) { + for (k, v) in p { + m.insert(k, v); + } + } + let line = format!("{msg}\n"); + { + let mut w = self.stdin.lock().await; + if w.write_all(line.as_bytes()).await.is_err() || w.flush().await.is_err() { + self.pending.lock().await.remove(&id); + return Err(RuntimeError::new("E_RUNTIME", "infernet runtime is not running")); + } + } + let reply = match tokio::time::timeout(timeout, rx).await { + Ok(Ok(v)) => v, + Ok(Err(_)) => return Err(RuntimeError::new("E_RUNTIME", "infernet runtime dropped the request")), + Err(_) => { + self.pending.lock().await.remove(&id); + return Err(RuntimeError::new("E_TIMEOUT", format!("{op} timed out"))); + } + }; + if reply.get("ok").and_then(|v| v.as_bool()) == Some(true) { + Ok(reply.get("result").cloned().unwrap_or(Value::Null)) + } else { + Err(reply + .get("error") + .and_then(|e| serde_json::from_value(e.clone()).ok()) + .unwrap_or_else(|| RuntimeError::new("E_RUNTIME", "malformed runtime reply"))) + } + } + + pub async fn shutdown(&self) { + let _ = self.request("shutdown", json!({}), Duration::from_secs(5)).await; + let _ = self.child.lock().await.kill().await; + } +} diff --git a/node/crates/c0mpute-core/src/temporal/worker.rs b/node/crates/c0mpute-core/src/temporal/worker.rs new file mode 100644 index 00000000..362d180b --- /dev/null +++ b/node/crates/c0mpute-core/src/temporal/worker.rs @@ -0,0 +1,433 @@ +//! Worker side: one training job per node at a time, and inference +//! sessions pinned to the node that holds their hidden state. + +use std::collections::HashMap; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::time::Duration; + +use anyhow::{Context, Result, bail}; +use c0mpute_net::topics::{JobAccept, JobStatus, job_topic}; +use c0mpute_net::{GossipMessage, Libp2pNetwork}; +use serde_json::{Value, json}; +use sha2::{Digest, Sha256}; +use tokio::sync::{Mutex, broadcast, mpsc}; +use tracing::{info, warn}; + +use super::crypto; +use super::http::ARTIFACTS; +use super::runtime::{RuntimeError, RuntimeProc}; +use super::{INFER_WORKLOAD, SessionCall, SessionReady, SessionReply, SessionSpec, TrainSpec}; +use crate::buyer::source_matches_claim; +use crate::runner::{AcceptedJob, publish_receipt}; + +const MAX_DATASET: u64 = 512 << 20; + +pub fn file_sha256(p: &Path) -> Result { + let mut h = Sha256::new(); + let mut f = std::fs::File::open(p).with_context(|| format!("open {}", p.display()))?; + std::io::copy(&mut f, &mut h)?; + Ok(format!("sha256:{}", hex::encode(h.finalize()))) +} + +/// Content-addressed local model store: `//{manifest.json,model.safetensors}`. +#[derive(Clone, Debug)] +pub struct ModelStore { + pub root: PathBuf, +} + +impl ModelStore { + pub fn new(root: PathBuf) -> Self { + Self { root } + } + + pub fn dir_for(&self, model_hash: &str) -> PathBuf { + self.root.join(model_hash.trim_start_matches("sha256:")) + } + + /// Copy a model directory in after checking its weights hash. Returns the hash. + pub fn import(&self, src: &Path) -> Result { + let manifest: Value = serde_json::from_slice(&std::fs::read(src.join("manifest.json"))?)?; + let want = manifest["weights"]["weights_hash"].as_str().context("manifest lacks weights.weights_hash")?.to_string(); + let file = manifest["weights"]["file"].as_str().unwrap_or("model.safetensors"); + let got = file_sha256(&src.join(file))?; + if got != want { + bail!("weights {got} do not match the manifest's {want}"); + } + let dst = self.dir_for(&want); + if dst != src { + std::fs::create_dir_all(&dst)?; + for f in ARTIFACTS { + if src.join(f).exists() { + std::fs::copy(src.join(f), dst.join(f))?; + } + } + } + Ok(want) + } + + /// Resolve `sha256:` or a directory path to a verified model dir. + pub fn resolve(&self, model: &str) -> Result<(PathBuf, String)> { + let dir = if model.starts_with("sha256:") { self.dir_for(model) } else { PathBuf::from(model) }; + let hash = self.import(&dir)?; + if model.starts_with("sha256:") && hash != model { + bail!("stored model {hash} is not {model}"); + } + Ok((self.dir_for(&hash), hash)) + } +} + +// ── training ──────────────────────────────────────────────────────────── + +async fn download(url: &str, dst: &Path) -> Result<()> { + let resp = reqwest::get(url).await?.error_for_status()?; + if resp.content_length().is_some_and(|n| n > MAX_DATASET) { + bail!("dataset larger than {} MiB", MAX_DATASET >> 20); + } + let bytes = resp.bytes().await?; + if bytes.len() as u64 > MAX_DATASET { + bail!("dataset larger than {} MiB", MAX_DATASET >> 20); + } + tokio::fs::write(dst, &bytes).await?; + Ok(()) +} + +/// Run `infernet model train` for one accepted job; returns the model dir and hash. +pub async fn run_train(infernet: &Path, job_dir: &Path, spec: &TrainSpec) -> Result<(PathBuf, String)> { + spec.validate()?; + tokio::fs::create_dir_all(job_dir).await?; + let dataset = job_dir.join("dataset.json"); + download(&spec.dataset_url, &dataset).await.context("fetch dataset")?; + let job_path = job_dir.join("job.json"); + tokio::fs::write(&job_path, serde_json::to_vec_pretty(&spec.train_job)?).await?; + let out_dir = job_dir.join("model"); + let timeout_s = spec.train_job["limits"]["timeout_s"].as_u64().unwrap_or(3600).clamp(1, 7 * 86_400); + let child = tokio::process::Command::new(infernet) + .args(["model", "train", "--json", "--dataset"]) + .arg(&dataset) + .arg("--output") + .arg(&out_dir) + .arg("--job") + .arg(&job_path) + .stdin(std::process::Stdio::null()) + .kill_on_drop(true) + .output(); + let out = tokio::time::timeout(Duration::from_secs(timeout_s), child) + .await + .map_err(|_| anyhow::anyhow!("E_TIMEOUT: training exceeded {timeout_s}s"))??; + if !out.status.success() { + bail!("infernet model train failed: {}", String::from_utf8_lossy(&out.stderr).lines().last().unwrap_or("").trim()); + } + let res: Value = serde_json::from_slice(&out.stdout).context("parse infernet model train --json")?; + let r0 = res["results"].get(0).context("no results from infernet model train")?; + let model_dir = PathBuf::from(r0["model_dir"].as_str().context("result lacks model_dir")?); + let claimed = r0["model_hash"].as_str().unwrap_or("").to_string(); + let actual = file_sha256(&model_dir.join("model.safetensors"))?; + if actual != claimed { + bail!("trained weights hash {actual} differs from infernet's {claimed}"); + } + Ok((model_dir, actual)) +} + +async fn upload(base: &str, model_dir: &Path) -> Result<()> { + let c = reqwest::Client::new(); + for f in ARTIFACTS { + let p = model_dir.join(f); + if !p.exists() { + continue; + } + c.put(format!("{base}/{f}")).body(tokio::fs::read(&p).await?).send().await?.error_for_status()?; + } + Ok(()) +} + +/// Runner for `infernet.temporal.train`. Jobs run one at a time (single +/// node, no multi-node training in v1). A repeated idempotency key reuses +/// the finished model instead of training again. +pub fn spawn_train_runner( + net: Arc, + cache_root: PathBuf, + infernet: PathBuf, + store: ModelStore, + busy: Arc, +) -> mpsc::Sender { + let (tx, mut rx) = mpsc::channel::(8); + tokio::spawn(async move { + let mut done: HashMap = HashMap::new(); + while let Some(job) = rx.recv().await { + let accept = job.accept.clone(); + busy.store(true, std::sync::atomic::Ordering::Relaxed); + let result: Result = async { + let spec: TrainSpec = serde_json::from_value(accept.spec_inline.clone().context("accept lacks spec_inline")?)?; + spec.validate()?; + let key = spec.idempotency_key().to_string(); + let (dir, hash) = match done.get(&key) { + Some(hit) => hit.clone(), + None => { + let job_dir = cache_root.join("temporal").join("jobs").join(&accept.job_id); + let r = run_train(&infernet, &job_dir, &spec).await?; + done.insert(key, r.clone()); + r + } + }; + if let Err(e) = store.import(&dir) { + warn!(err = %e, "temporal: could not keep the model in the local store"); + } + if let Some(base) = &spec.artifact_upload_url { + upload(base, &dir).await.context("upload artifacts")?; + } + Ok(hash) + } + .await; + busy.store(false, std::sync::atomic::Ordering::Relaxed); + match result { + Ok(hash) => { + info!(job_id = %accept.job_id, model = %hash, "temporal: training complete"); + publish_receipt(&net, &accept, Some(hash), JobStatus::Completed).await; + } + Err(e) => { + warn!(job_id = %accept.job_id, err = %e, "temporal: training failed"); + publish_receipt(&net, &accept, None, JobStatus::Failed).await; + } + } + } + }); + tx +} + +// ── inference ─────────────────────────────────────────────────────────── + +struct Held { + owner: String, + key: [u8; 32], + runtime_sid: String, +} + +/// Holds the runtime child and every session this node owns. +pub struct InferServer { + pub runtime: Arc, + pub models: Vec, + sessions: Mutex>, + /// Replies by call id: a republished call gets the first answer back + /// instead of running twice (exactly-once per call id). + replies: Mutex<(HashMap>, std::collections::VecDeque)>, +} + +const REPLY_CACHE: usize = 1024; + +fn held_key(owner: &str, sid: &str) -> String { + format!("{owner}:{sid}") +} + +impl InferServer { + /// Load every model (verifying its hash) into a fresh runtime. + pub async fn start(infernet: &Path, model_dirs: &[(PathBuf, String)], worker_id: &str, max_sessions: u32) -> Result> { + let rt = RuntimeProc::spawn(infernet, &["--worker".into(), worker_id.into(), "--max-sessions".into(), max_sessions.to_string()]).await?; + let mut models = Vec::new(); + for (dir, hash) in model_dirs { + let r = rt + .request("load", json!({"model_dir": dir, "expected_hash": hash}), Duration::from_secs(300)) + .await + .map_err(|e| anyhow::anyhow!("load {}: {e}", dir.display()))?; + models.push(r["model_hash"].as_str().unwrap_or(hash).to_string()); + } + Ok(Arc::new(Self { runtime: rt, models, sessions: Mutex::new(HashMap::new()), replies: Mutex::new((HashMap::new(), Default::default())) })) + } + + /// Open a session for `owner` (the buyer's authenticated peer id). + /// Returns our X25519 public key. + pub async fn open(&self, owner: &str, spec: &SessionSpec) -> Result { + spec.validate()?; + if !self.models.contains(&spec.model_hash) { + bail!("E_NOT_LOADED: model {} is not served here", spec.model_hash); + } + let runtime_sid = format!("{}.{}", &owner[owner.len().saturating_sub(16)..], spec.session_id); + self.runtime + .request( + "open_session", + json!({"model_hash": spec.model_hash, "session_id": runtime_sid, "ttl_s": spec.ttl_s, "account_scope": spec.account_scope}), + Duration::from_secs(30), + ) + .await + .map_err(|e| anyhow::anyhow!("{e}"))?; + let kp = crypto::keypair(); + let key = crypto::session_key(&kp.secret, &spec.client_pubkey, &spec.session_id)?; + self.sessions.lock().await.insert(held_key(owner, &spec.session_id), Held { owner: owner.into(), key, runtime_sid }); + Ok(kp.public_hex) + } + + /// Handle one sealed call from `owner`. Returns the sealed reply, or + /// None when the session is not ours (another worker's, or forged). + pub async fn call(&self, owner: &str, call: &SessionCall) -> Option { + let (key, runtime_sid) = { + let s = self.sessions.lock().await; + let h = s.get(&held_key(owner, &call.session_id))?; + if h.owner != owner { + return None; + } + (h.key, h.runtime_sid.clone()) + }; + let cache_key = format!("{owner}:{}:{}", call.session_id, call.call_id); + { + let mut c = self.replies.lock().await; + match c.0.get(&cache_key) { + Some(Some(hit)) => return Some(hit.clone()), + Some(None) => return None, // the first copy is still running and will answer + None => { + c.0.insert(cache_key.clone(), None); + } + } + } + let Ok(plain) = crypto::open(&key, &call.sealed) else { + self.replies.lock().await.0.remove(&cache_key); + return None; + }; + let reply = match self.dispatch(&runtime_sid, &call.session_id, &plain).await { + Ok(result) => json!({"ok": true, "result": result}), + Err(e) => json!({"ok": false, "error": e}), + }; + if serde_json::from_slice::(&plain).ok().and_then(|v| v["op"].as_str().map(str::to_string)).as_deref() == Some("close_session") { + self.sessions.lock().await.remove(&held_key(owner, &call.session_id)); + } + let sealed = crypto::seal(&key, reply.to_string().as_bytes()).ok()?; + let mut c = self.replies.lock().await; + c.0.insert(cache_key.clone(), Some(sealed.clone())); + c.1.push_back(cache_key); + while c.1.len() > REPLY_CACHE { + if let Some(old) = c.1.pop_front() { + c.0.remove(&old); + } + } + Some(sealed) + } + + async fn dispatch(&self, runtime_sid: &str, client_sid: &str, plain: &[u8]) -> std::result::Result { + let msg: Value = serde_json::from_slice(plain).map_err(|_| RuntimeError::new("E_BAD_REQUEST", "call is not JSON"))?; + let op = msg["op"].as_str().unwrap_or(""); + let t = Duration::from_secs(30); + let swap = |mut v: Value| { + if v.get("session_id").is_some() { + v["session_id"] = json!(client_sid); + } + v + }; + match op { + "predict" => { + let mut req = msg["request"].clone(); + if !req.is_object() { + return Err(RuntimeError::new("E_BAD_REQUEST", "predict needs request")); + } + req["session_id"] = json!(runtime_sid); + self.runtime.request("predict", json!({"request": req}), t).await.map(swap) + } + "reset" | "close_session" => self.runtime.request(op, json!({"session_id": runtime_sid}), t).await.map(swap), + _ => Err(RuntimeError::new("E_BAD_REQUEST", format!("op {op} is not allowed over the network"))), + } + } + + pub async fn session_count(&self) -> usize { + self.sessions.lock().await.len() + } +} + +/// Runner for `infernet.temporal.infer`: an accepted job opens one session, +/// publishes our key half, and receipts with the model hash. +pub fn spawn_infer_runner(net: Arc, server: Arc) -> mpsc::Sender { + let (tx, mut rx) = mpsc::channel::(32); + let topic = job_topic(INFER_WORKLOAD); + tokio::spawn(async move { + while let Some(job) = rx.recv().await { + let accept: JobAccept = job.accept; + let spec: Option = accept.spec_inline.clone().and_then(|v| serde_json::from_value(v).ok()); + let Some(spec) = spec else { + publish_receipt(&net, &accept, None, JobStatus::Failed).await; + continue; + }; + match server.open(&accept.buyer_peer_id, &spec).await { + Ok(pubkey) => { + let ready = SessionReady { + t: "temporal_ready".into(), + job_id: accept.job_id.clone(), + session_id: spec.session_id.clone(), + worker_peer_id: net.peer_id().to_base58(), + worker_pubkey: pubkey, + model_hash: spec.model_hash.clone(), + }; + if let Ok(b) = serde_json::to_vec(&ready) { + let _ = net.publish(&topic, b).await; + } + tokio::time::sleep(Duration::from_millis(50)).await; + publish_receipt(&net, &accept, Some(spec.model_hash.clone()), JobStatus::Completed).await; + } + Err(e) => { + warn!(job_id = %accept.job_id, err = %e, "temporal: session open failed"); + publish_receipt(&net, &accept, None, JobStatus::Failed).await; + } + } + } + }); + tx +} + +/// Answer sealed calls for sessions this node holds. Calls are accepted +/// only from the peer that opened the session (gossipsub-signed source). +pub fn spawn_call_listener(net: Arc, server: Arc) { + let topic = job_topic(INFER_WORKLOAD); + let me = net.peer_id().to_base58(); + let mut rx: broadcast::Receiver = net.messages(); + tokio::spawn(async move { + loop { + let msg = match rx.recv().await { + Ok(m) => m, + Err(broadcast::error::RecvError::Lagged(_)) => continue, + Err(_) => return, + }; + if msg.topic != topic { + continue; + } + let Ok(call) = serde_json::from_slice::(&msg.data) else { continue }; + if call.t != "temporal_call" || call.worker_peer_id != me { + continue; + } + let Some(src) = msg.source.map(|p| p.to_base58()) else { continue }; + if !source_matches_claim(&msg, &src) { + continue; + } + let (net, server, topic) = (net.clone(), server.clone(), topic.clone()); + tokio::spawn(async move { + if let Some(sealed) = server.call(&src, &call).await { + let reply = SessionReply { t: "temporal_reply".into(), session_id: call.session_id, call_id: call.call_id, sealed }; + if let Ok(b) = serde_json::to_vec(&reply) { + let _ = net.publish(&topic, b).await; + } + } + }); + } + }); +} + +/// Bid only on train offers whose spec passes [`TrainSpec::validate`] and +/// only while no training job is running here (one job per node). +pub fn train_offer_filter(busy: Arc) -> crate::dispatch::OfferFilter { + Arc::new(move |offer| { + if busy.load(std::sync::atomic::Ordering::Relaxed) { + return false; + } + offer + .spec_inline + .as_ref() + .and_then(|v| serde_json::from_value::(v.clone()).ok()) + .is_some_and(|s| s.validate().is_ok()) + }) +} + +/// Bid only on session offers for models this node serves. +pub fn infer_offer_filter(models: Vec) -> crate::dispatch::OfferFilter { + Arc::new(move |offer| { + offer + .spec_inline + .as_ref() + .and_then(|v| serde_json::from_value::(v.clone()).ok()) + .is_some_and(|s| s.validate().is_ok() && models.contains(&s.model_hash)) + }) +} diff --git a/node/crates/c0mpute-core/tests/fixtures/fake-infernet b/node/crates/c0mpute-core/tests/fixtures/fake-infernet new file mode 100755 index 00000000..e3f062ed --- /dev/null +++ b/node/crates/c0mpute-core/tests/fixtures/fake-infernet @@ -0,0 +1,75 @@ +#!/usr/bin/env python3 +"""Stand-in for the `infernet` CLI's temporal commands in c0mpute tests. + +Same command lines and JSON shapes as Infernet (model capabilities --json, +model train --json, model serve --stdio), no PyTorch: weights are a few +bytes derived from the job, so hashes are real and checkable. +""" +import hashlib, json, os, sys + +def sha(b): + return "sha256:" + hashlib.sha256(b).hexdigest() + +args = sys.argv[1:] +if args[:2] == ["model", "capabilities"]: + print(json.dumps({"workloads": ["infernet.temporal.train", "infernet.temporal.infer"], "families": ["cfc", "ltc", "gru"], + "research_families": ["ltc"], "devices": {"cpu": True, "cuda": False, "mps": False}, "ram_mb": 16384, + "threads": 4, "max_sessions": 64, "runtime": {"name": "infernet-liquid", "version": "0.1.0", "lock_hash": "sha256:" + "0" * 64}})) + sys.exit(0) + +def flag(name): + return args[args.index(name) + 1] if name in args else None + +if args[:2] == ["model", "train"]: + job = json.load(open(flag("--job"))) + bundle = json.load(open(flag("--dataset"))) + if bundle["manifest"]["dataset_hash"] != job["dataset_hash"]: + print("error: E_HASH_MISMATCH", file=sys.stderr); sys.exit(1) + out = flag("--output"); os.makedirs(out, exist_ok=True) + weights = ("weights:" + job["model_type"] + ":" + job["dataset_hash"]).encode() + open(os.path.join(out, "model.safetensors"), "wb").write(weights) + score = {"cfc": 0.8, "gru": 0.9, "ltc": 0.7}[job["model_type"]] + manifest = {"schema_version": "liquid-agent/v1", "kind": "model_manifest", "architecture": {"family": job["model_type"]}, + "weights": {"format": "safetensors", "file": "model.safetensors", "weights_hash": sha(weights), "size_bytes": len(weights)}, + "training": {"dataset_hash": job["dataset_hash"], "train_job_id": job["job_id"]}} + json.dump(manifest, open(os.path.join(out, "manifest.json"), "w")) + ev = {"model_hash": sha(weights), "dataset_hash": job["dataset_hash"], "split": "test", "metrics": {"episode_success": score}} + json.dump(ev, open(os.path.join(out, "eval.json"), "w")) + print(json.dumps({"dataset_hash": job["dataset_hash"], "results": [{"family": job["model_type"], "model_dir": out, "model_hash": sha(weights), "eval": ev}], "selected": job["model_type"]})) + sys.exit(0) + +if args[:2] == ["model", "serve"]: + models, sessions = set(), {} + for line in sys.stdin: + r = json.loads(line); rid = r.get("id"); op = r.get("op") + def ok(res): print(json.dumps({"v": 1, "id": rid, "ok": True, "result": res}), flush=True) + def err(code, msg): print(json.dumps({"v": 1, "id": rid, "ok": False, "error": {"code": code, "message": msg, "retriable": False}}), flush=True) + if op == "load": + m = json.load(open(os.path.join(r["model_dir"], "manifest.json")))["weights"]["weights_hash"] + if r.get("expected_hash") and r["expected_hash"] != m: err("E_MODEL_HASH", "mismatch"); continue + models.add(m); ok({"model_hash": m}) + elif op == "open_session": + if r["model_hash"] not in models: err("E_NOT_LOADED", "no"); continue + sessions[r["session_id"]] = {"seq": -1, "scope": r.get("account_scope")} + ok({"session_id": r["session_id"], "sequence_index": -1, "state": "active"}) + elif op == "predict": + q = r["request"]; s = sessions.get(q["session_id"]) + if s is None: err("E_SESSION_UNKNOWN", "no session"); continue + if q["sequence_index"] <= s["seq"]: err("E_SEQ_DUPLICATE" if q["sequence_index"] == s["seq"] else "E_SEQ_LATE", "seq"); continue + if q["sequence_index"] > s["seq"] + 1: err("E_SEQ_GAP", "gap"); continue + s["seq"] = q["sequence_index"] + ok({"kind": "action_proposal", "session_id": q["session_id"], "sequence_index": s["seq"], "action": {"type": "wait"}, "confidence": 0.9, "requires_approval": False, "abstain_reason": None}) + elif op in ("reset", "close_session"): + s = sessions.get(r["session_id"]) + if s is None: err("E_SESSION_UNKNOWN", "no session"); continue + if op == "reset": s["seq"] = -1 + else: sessions.pop(r["session_id"]) + ok({"session_id": r["session_id"], "sequence_index": -1, "state": "closed" if op == "close_session" else "active"}) + elif op == "shutdown": + ok({"bye": True}); break + else: + err("E_BAD_REQUEST", f"unknown op {op}") + sys.exit(0) + +print("fake infernet: unsupported " + " ".join(args), file=sys.stderr) +sys.exit(2) diff --git a/node/crates/c0mpute-core/tests/temporal_e2e.rs b/node/crates/c0mpute-core/tests/temporal_e2e.rs new file mode 100644 index 00000000..77d9c9f0 --- /dev/null +++ b/node/crates/c0mpute-core/tests/temporal_e2e.rs @@ -0,0 +1,151 @@ +//! End-to-end: a temporal worker and a buyer on loopback libp2p. A fake +//! `infernet` (tests/fixtures/fake-infernet, same CLI and JSON shapes, no +//! PyTorch) stands in for Infernet so this runs anywhere with python3. +//! Covers capability filtering, the trusted-worker allowlist, single-node +//! training with artifact upload verified against the receipt, and sticky +//! encrypted inference sessions that only their opener can drive. + +use std::path::PathBuf; +use std::time::Duration; + +use c0mpute_core::temporal::client::{self, OpenRequest, TrainRequest}; +use c0mpute_core::temporal::caps::Requirements; +use c0mpute_core::temporal::node::{self, NetOptions, ServeOptions}; +use c0mpute_core::temporal::worker::ModelStore; +use serde_json::json; +use tempfile::tempdir; + +fn fake_infernet() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/fake-infernet") +} + +fn bundle(dir: &std::path::Path) -> PathBuf { + let h = format!("sha256:{}", "ab".repeat(32)); + let p = dir.join("bundle.json"); + let b = json!({"schema_version": "liquid-agent/v1", "kind": "dataset_bundle", + "manifest": {"dataset_hash": h}, "episodes": [{"episode_id": "ep_test1"}]}); + std::fs::write(&p, serde_json::to_vec(&b).unwrap()).unwrap(); + p +} + +fn net(dir: &std::path::Path, bootstrap: Vec) -> NetOptions { + NetOptions { identity_dir: dir.to_path_buf(), listen: vec!["/ip4/127.0.0.1/tcp/0".into()], bootstrap, default_bootstrap: false } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn train_then_serve_a_sticky_session() { + let _ = tracing_subscriber::fmt().with_env_filter("c0mpute_core=info,c0mpute_net=warn").with_test_writer().try_init(); + let tmp = tempdir().unwrap(); + + // ── worker: accepts training ─────────────────────────────────────── + let store = ModelStore::new(tmp.path().join("w/models")); + let w = node::serve(&ServeOptions { + net: net(&tmp.path().join("w/id"), vec![]), + infernet: fake_infernet(), + models: vec![], + train: true, + max_sessions: 8, + store: store.clone(), + cache_root: tmp.path().join("w/cache"), + }) + .await + .expect("worker serves"); + assert!(w.tags.contains(&"infernet:temporal:train".to_string())); + assert!(!w.tags.contains(&"infernet:temporal:infer".to_string()), "no models, so no infer tag"); + let wid = w.net.peer_id().to_base58(); + let waddr = format!("{}/p2p/{wid}", w.net.listen_addrs().await.unwrap()[0]); + + let buyer = node::spawn_node(&net(&tmp.path().join("b/id"), vec![waddr.clone()])).await.unwrap(); + tokio::time::sleep(Duration::from_secs(2)).await; + + let mk = |families: Vec<&str>, workers: Vec, req: Requirements| TrainRequest { + dataset_path: bundle(tmp.path()), + output: tmp.path().join("out"), + families: families.into_iter().map(String::from).collect(), + workers, + max_price_usd: 0.1, + requirements: req, + public_url: None, + bind: "127.0.0.1:0".parse().unwrap(), + timeout_s: 60, + retries: 0, + hyperparameters: json!({}), + bid_window: Duration::from_secs(2), + }; + + // A worker outside the allowlist is never chosen. + let err = client::train(buyer.clone(), &mk(vec!["cfc"], vec!["12D3KooWNotTrusted".into()], Requirements::default())).await; + assert!(err.is_err(), "allowlist excluded the only worker"); + // Requirements the worker cannot meet: no bid. + let err = client::train(buyer.clone(), &mk(vec!["cfc"], vec![], Requirements { gpu: true, ..Default::default() })).await; + assert!(err.is_err(), "CPU worker must not bid on a GPU job"); + + // The real thing: CfC + GRU baseline on the trusted worker. + let out = client::train(buyer.clone(), &mk(vec!["cfc", "gru"], vec![wid.clone()], Requirements { min_ram_gb: Some(8), ..Default::default() })) + .await + .expect("training completes"); + let results = out["results"].as_array().unwrap(); + assert_eq!(results.len(), 2); + for r in results { + let dir = PathBuf::from(r["model_dir"].as_str().unwrap()); + let got = c0mpute_core::temporal::worker::file_sha256(&dir.join("model.safetensors")).unwrap(); + assert_eq!(r["model_hash"].as_str().unwrap(), got); + assert_eq!(r["worker_peer_id"], json!(wid)); + } + assert_eq!(out["receipts"].as_array().unwrap().len(), 2); + assert_eq!(out["selected"], json!("gru"), "fake scores: gru 0.9 > cfc 0.8, so the baseline stays"); + let cfc_hash = results[0]["model_hash"].as_str().unwrap().to_string(); + assert!(store.dir_for(&cfc_hash).join("manifest.json").exists(), "worker kept the model it trained"); + + // ── a second worker process serving that model for inference ─────── + let s = node::serve(&ServeOptions { + net: net(&tmp.path().join("s/id"), vec![waddr.clone()]), + infernet: fake_infernet(), + models: vec![cfc_hash.clone()], + train: false, + max_sessions: 8, + store: store.clone(), + cache_root: tmp.path().join("s/cache"), + }) + .await + .expect("infer worker serves"); + let sid_peer = s.net.peer_id().to_base58(); + assert!(s.tags.iter().any(|t| t.ends_with(cfc_hash.trim_start_matches("sha256:")))); + tokio::time::sleep(Duration::from_secs(3)).await; + + let sf = client::open_session( + buyer.clone(), + &OpenRequest { model_hash: cfc_hash.clone(), session_id: "s1".into(), ttl_s: 60, account_scope: "acct".into(), workers: vec![], max_price_usd: 0.01, bid_window: Duration::from_secs(2) }, + ) + .await + .expect("session opens"); + assert_eq!(sf.worker_peer_id, sid_peer, "only the infer worker serves this model"); + + let step = json!({"observation": {"app": "mail"}, "dt_ms": 0}); + let mut sf2 = sf.clone(); + for i in 0..3 { + let req = client::predict_request(&step, &sf2).unwrap(); + let r = client::call(buyer.clone(), &sf2, json!({"op": "predict", "request": req}), Duration::from_secs(20)).await.unwrap(); + assert_eq!(r["ok"], json!(true), "{r}"); + assert_eq!(r["result"]["sequence_index"], json!(i)); + assert_eq!(r["result"]["session_id"], json!("s1"), "client sees its own session id"); + sf2.next_seq += 1; + } + // Replaying an old index is refused by the runtime, not silently re-run. + let mut stale = sf.clone(); + stale.next_seq = 1; + let req = client::predict_request(&step, &stale).unwrap(); + let r = client::call(buyer.clone(), &stale, json!({"op": "predict", "request": req}), Duration::from_secs(20)).await.unwrap(); + assert_eq!(r["error"]["code"], json!("E_SEQ_LATE")); + + // Another peer that copied the session file cannot drive the session. + let thief = node::spawn_node(&net(&tmp.path().join("t/id"), vec![waddr])).await.unwrap(); + tokio::time::sleep(Duration::from_secs(2)).await; + let r = client::call(thief, &sf, json!({"op": "reset"}), Duration::from_secs(5)).await; + assert!(r.is_err(), "worker ignores calls from a peer that did not open the session"); + + let r = client::call(buyer.clone(), &sf, json!({"op": "close_session"}), Duration::from_secs(20)).await.unwrap(); + assert_eq!(r["ok"], json!(true)); + let r = client::call(buyer.clone(), &sf, json!({"op": "reset"}), Duration::from_secs(5)).await; + assert!(r.is_err(), "closed session no longer answers"); +} diff --git a/package.json b/package.json index f0ade1ad..0fe1ef9c 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "c0mpute-monorepo", - "version": "0.2.32", + "version": "0.2.34", "private": true, "workspaces": [ "apps/*", diff --git a/packages/shared/package.json b/packages/shared/package.json index 775fe6e2..8272afc1 100644 --- a/packages/shared/package.json +++ b/packages/shared/package.json @@ -1,6 +1,6 @@ { "name": "@c0mpute/shared", - "version": "0.2.32", + "version": "0.2.34", "private": true, "type": "module", "main": "./dist/index.js", diff --git a/plugins/ads-manager/module.toml b/plugins/ads-manager/module.toml index 41a25ccc..8cb409ed 100644 --- a/plugins/ads-manager/module.toml +++ b/plugins/ads-manager/module.toml @@ -18,7 +18,7 @@ [module] id = "ads-manager" name = "Ads Manager — shared ad operations layer" -version = "0.2.28" +version = "0.2.34" kind = "service" category = "applications" description = "Unified ad operations for the c0mpute network: campaign management, creative registry, publisher inventory, OpenRTB auction primitives, CoinPay escrow, and reporting. Required dependency for ctv-ads and all future ad format plugins." diff --git a/plugins/coinpay/module.toml b/plugins/coinpay/module.toml index fdd8093d..175e36a1 100644 --- a/plugins/coinpay/module.toml +++ b/plugins/coinpay/module.toml @@ -7,7 +7,7 @@ [module] id = "coinpay" name = "CoinPay — DID, payments, escrow, reputation" -version = "0.2.28" +version = "0.2.34" kind = "service" category = "applications" description = "Decentralized identifiers, wallet linking, escrow, signed receipts, and worker reputation. The trust spine of the c0mpute network." diff --git a/plugins/crawl/module.toml b/plugins/crawl/module.toml index d8eae4e5..d1f1bd7a 100644 --- a/plugins/crawl/module.toml +++ b/plugins/crawl/module.toml @@ -14,7 +14,7 @@ [module] id = "crawl" name = "Crawl — distributed web fetching" -version = "0.2.28" +version = "0.2.34" kind = "workload" category = "data" description = "Decentralized web crawling and page-rendering pool. Static fetches and JS-rendered pages, robots-aware, WARC-capable." diff --git a/plugins/ctv-ads/module.toml b/plugins/ctv-ads/module.toml index 2a4e3914..8140e414 100644 --- a/plugins/ctv-ads/module.toml +++ b/plugins/ctv-ads/module.toml @@ -20,7 +20,7 @@ [module] id = "ctv-ads" name = "CTV Ads — Connected TV ad marketplace" -version = "0.2.28" +version = "0.2.34" kind = "service" category = "applications" description = "Decentralised Connected TV advertising on the c0mpute network. VAST 4.x endpoint, OpenRTB real-time auction, cryptographically verified impressions, CoinPay settlement. Supports Roku, Fire TV, Apple TV, Smart TVs, and FAST channels. Live-stream integration for ad-monetised broadcasts." diff --git a/plugins/diffusion/module.toml b/plugins/diffusion/module.toml index 04fd81d3..6335e684 100644 --- a/plugins/diffusion/module.toml +++ b/plugins/diffusion/module.toml @@ -14,7 +14,7 @@ [module] id = "diffusion" name = "Diffusion — image generation" -version = "0.2.28" +version = "0.2.34" kind = "workload" category = "ai" description = "Decentralized image generation (Stable Diffusion, SDXL, Flux) on consumer/prosumer GPUs." diff --git a/plugins/embed/module.toml b/plugins/embed/module.toml index 3af54a89..6194e0f7 100644 --- a/plugins/embed/module.toml +++ b/plugins/embed/module.toml @@ -13,7 +13,7 @@ [module] id = "embed" name = "Embeddings — vector generation" -version = "0.2.28" +version = "0.2.34" kind = "workload" category = "ai" description = "Bulk text-embedding generation (sentence-transformers, BGE, Nomic) with CPU fallback and optional GPU acceleration." diff --git a/plugins/gameserver/module.toml b/plugins/gameserver/module.toml index 46819342..ca0d7645 100644 --- a/plugins/gameserver/module.toml +++ b/plugins/gameserver/module.toml @@ -14,7 +14,7 @@ [module] id = "gameserver" name = "Game server — Minecraft / Factorio / Valheim" -version = "0.2.28" +version = "0.2.34" kind = "workload" category = "infrastructure" description = "Continuous-reservation hosting for game servers. Multi-replica placement, persistent world state on c0mpute storage, proof-of-serve settlement." diff --git a/plugins/hosting/module.toml b/plugins/hosting/module.toml index 97800080..62c54750 100644 --- a/plugins/hosting/module.toml +++ b/plugins/hosting/module.toml @@ -12,7 +12,7 @@ [module] id = "hosting" name = "Hosting — censorship-resistant static sites" -version = "0.2.28" +version = "0.2.34" kind = "workload" category = "data" description = "Static-site hosting with multi-replica placement, mutable naming, epoch settlement, and slashable proof-of-serve. See DIP-0015." diff --git a/plugins/infernet/module.toml b/plugins/infernet/module.toml index 88400ed0..10747e2a 100644 --- a/plugins/infernet/module.toml +++ b/plugins/infernet/module.toml @@ -10,15 +10,15 @@ [module] id = "infernet" name = "Infernet Protocol — AI inference" -version = "0.2.28" +version = "0.2.34" kind = "workload" category = "ai" -description = "Decentralized AI inference workloads on c0mpute. Runs models on consumer/prosumer GPUs with model-hash and runtime-image verification." +description = "Decentralized AI inference workloads on c0mpute. Runs models on consumer/prosumer GPUs with model-hash and runtime-image verification. Also trains and serves temporal policies (CfC/LTC liquid networks, GRU baseline) on CPU or GPU." author = "Infernet Protocol" license = "MIT" homepage = "https://infernetprotocol.com" source = "https://github.com/infernetprotocol/infernet-protocol" -keywords = ["ai", "llm", "inference", "gpu"] +keywords = ["ai", "llm", "inference", "gpu", "temporal-policy", "liquid-neural-network", "cfc"] [module.requirements] c0mpute = ">=0.1.0" @@ -28,11 +28,26 @@ capabilities = ["gpu:nvidia?", "model-runtime"] [module.workloads] "infernet.inference" = { command = "chat", validation = "schema_and_spotcheck" } +# Temporal policies (liquid-agent/v1). Executed by Infernet >= 0.1.66 +# (`infernet model train --job` / `infernet model serve --stdio`, which run +# the infernet-liquid runtime the operator installs with +# `infernet model runtime setup --yes`). Workers opt in with +# `c0mpute infernet temporal serve [--train] [--model ...]` and advertise only +# what `infernet model capabilities` reports. Receipts carry the model hash. +"infernet.temporal.train" = { command = "model train", validation = "model_hash_and_eval_manifest", min_version = "0.1.66" } +"infernet.temporal.infer" = { command = "model serve", validation = "model_hash_session_affinity", min_version = "0.1.66" } [module.dispatch] mode = "subprocess" binary = "infernet" +[module.capabilities.temporal] +# Tags a temporal worker advertises; buyers require a subset. +runtime = "infernet:temporal:runtime:" +devices = ["infernet:temporal:device:cpu", "infernet:temporal:device:cuda", "infernet:temporal:device:mps"] +ram = "c0mpute:ram:gb+" +model = "infernet:temporal:model:" + [module.surfaces] cli = "infernet" # web = "c0mpute.com/infernet" # planned diff --git a/plugins/live-stream/module.toml b/plugins/live-stream/module.toml index 328cf17d..da4bbfdc 100644 --- a/plugins/live-stream/module.toml +++ b/plugins/live-stream/module.toml @@ -23,7 +23,7 @@ [module] id = "live-stream" name = "Live Stream — p2p HLS live streaming" -version = "0.2.28" +version = "0.2.34" kind = "service" category = "media" description = "Decentralized live video streaming via BitTorrent-style HLS segment swarming. Broadcaster pushes RTMP/SRT; c0mpute nodes swarm segments to viewers. No central CDN. Censorship-resistant. Per-GB micropayments via CoinPay." diff --git a/plugins/ocr/module.toml b/plugins/ocr/module.toml index 8431b87a..b3ae4eb8 100644 --- a/plugins/ocr/module.toml +++ b/plugins/ocr/module.toml @@ -12,7 +12,7 @@ [module] id = "ocr" name = "OCR — document text extraction" -version = "0.2.28" +version = "0.2.34" kind = "workload" category = "ai" description = "Decentralized OCR for PDFs and scanned documents (Tesseract, PaddleOCR, docTR) with CPU or GPU runners." diff --git a/plugins/podcast-ads/module.toml b/plugins/podcast-ads/module.toml index 018a751f..46306159 100644 --- a/plugins/podcast-ads/module.toml +++ b/plugins/podcast-ads/module.toml @@ -22,7 +22,7 @@ [module] id = "podcast-ads" name = "Podcast Ads — audio ad marketplace" -version = "0.2.28" +version = "0.2.34" kind = "service" category = "applications" description = "Decentralised audio advertising for c0mpute-hosted podcasts. DAAST 1.0 endpoint, dynamic ad insertion, Podcasting 2.0 revenue splits, and CoinPay settlement. Publishers sell ad slots; advertisers run campaigns — zero platform cut beyond protocol split." diff --git a/plugins/podcasting/module.toml b/plugins/podcasting/module.toml index 99115ef9..ca4214d5 100644 --- a/plugins/podcasting/module.toml +++ b/plugins/podcasting/module.toml @@ -20,7 +20,7 @@ [module] id = "podcasting" name = "Podcasting — p2p podcast publishing" -version = "0.2.28" +version = "0.2.34" kind = "service" category = "media" description = "Censorship-resistant podcast hosting on the c0mpute network. Upload episodes, stream live shows, auto-transcribe, and monetise via CoinPay subscriptions, pay-per-episode, value-for-value, and audio ads — with zero platform cut. RSS 2.0 + Podcasting 2.0 compatible with all major podcast apps." diff --git a/plugins/podcasts/module.toml b/plugins/podcasts/module.toml index b27b3c09..e0cdcbe7 100644 --- a/plugins/podcasts/module.toml +++ b/plugins/podcasts/module.toml @@ -19,7 +19,7 @@ [module] id = "podcasts" name = "Podcasts — p2p podcast listener" -version = "0.2.28" +version = "0.2.34" kind = "service" category = "media" description = "Discover, subscribe to, and play podcasts hosted on the c0mpute network or any standard RSS feed. Stream live episodes, tip creators directly via CoinPay, and participate in value-for-value streaming payments. Works alongside any existing podcast app via OPML export and local RSS proxy." diff --git a/plugins/render/module.toml b/plugins/render/module.toml index f6b7a9d0..59900633 100644 --- a/plugins/render/module.toml +++ b/plugins/render/module.toml @@ -13,7 +13,7 @@ [module] id = "render" name = "Render — Blender 3D rendering" -version = "0.2.28" +version = "0.2.34" kind = "workload" category = "media" description = "Decentralized 3D rendering using Blender headless (Cycles/Eevee) across consumer GPUs and CPUs." diff --git a/plugins/secure-chat/module.toml b/plugins/secure-chat/module.toml index 9c025137..8bc4b90d 100644 --- a/plugins/secure-chat/module.toml +++ b/plugins/secure-chat/module.toml @@ -18,7 +18,7 @@ [module] id = "secure-chat" name = "Secure Chat — E2E encrypted p2p messaging" -version = "0.2.28" +version = "0.2.34" kind = "service" category = "applications" description = "End-to-end encrypted peer-to-peer messaging across the c0mpute network. No central server. Keys stay with the user. Identity and reputation via CoinPay DID. Group chats, sealed-sender mode, and offline store-and-forward included." diff --git a/plugins/storage/module.toml b/plugins/storage/module.toml index c4d50d34..6f295a54 100644 --- a/plugins/storage/module.toml +++ b/plugins/storage/module.toml @@ -12,7 +12,7 @@ [module] id = "storage" name = "Storage — Reed-Solomon shard service" -version = "0.2.28" +version = "0.2.34" kind = "service" category = "data" description = "Reed-Solomon 10/14 shard storage with auto-repair. Compute-locality, E2E encryption, content-addressed, pay-as-you-go. See DIP-0012." diff --git a/plugins/train/module.toml b/plugins/train/module.toml index 052546d7..99a4eb11 100644 --- a/plugins/train/module.toml +++ b/plugins/train/module.toml @@ -13,7 +13,7 @@ [module] id = "train" name = "Fine-tune — LoRA/QLoRA training" -version = "0.2.28" +version = "0.2.34" kind = "workload" category = "ai" description = "Decentralized model fine-tuning (LoRA, QLoRA) on consumer/prosumer GPUs using axolotl or unsloth." diff --git a/plugins/transcode/module.toml b/plugins/transcode/module.toml index 4ee86da0..bfa6a4a1 100644 --- a/plugins/transcode/module.toml +++ b/plugins/transcode/module.toml @@ -7,7 +7,7 @@ [module] id = "transcode" name = "FFmpeg Transcoding" -version = "0.2.28" +version = "0.2.34" kind = "workload" category = "media" description = "Decentralized audio/video transcoding via FFmpeg with hardware acceleration (NVENC, QSV, AMF, VideoToolbox, AV1)." diff --git a/plugins/tts/module.toml b/plugins/tts/module.toml index 0c8ede53..53de6581 100644 --- a/plugins/tts/module.toml +++ b/plugins/tts/module.toml @@ -12,7 +12,7 @@ [module] id = "tts" name = "TTS — text-to-speech" -version = "0.2.28" +version = "0.2.34" kind = "workload" category = "ai" description = "Decentralized text-to-speech synthesis (Piper, Coqui XTTS, Kokoro) for narration, audiobooks, and accessibility." diff --git a/plugins/whisper/module.toml b/plugins/whisper/module.toml index 8c065a2f..81b9a494 100644 --- a/plugins/whisper/module.toml +++ b/plugins/whisper/module.toml @@ -11,7 +11,7 @@ [module] id = "whisper" name = "Whisper — speech-to-text" -version = "0.2.28" +version = "0.2.34" kind = "workload" category = "ai" description = "Decentralized speech-to-text transcription via whisper.cpp with optional GPU acceleration (CUDA, Metal, Vulkan)." From 9c07daeedc15e047b65ea4536fe2fbbaf1bcd00d Mon Sep 17 00:00:00 2001 From: Anthony Ettinger Date: Mon, 26 Oct 2026 07:57:59 +0000 Subject: [PATCH 2/3] fix(deps): next 16.4.1 and dompurify 3.4.17 for three critical advisories GHSA-2464-fhr4-w9xw and GHSA-673q-mjm6-r5xr (Next.js unauthenticated RCE), GHSA-cg2g-xh64-v4q7 (DOMPurify). Published after master's last green bun audit; next build verified locally. Co-Authored-By: Claude Opus 5.5 --- apps/web/package.json | 2 +- bun.lock | 30 +++++++++++++++--------------- 2 files changed, 16 insertions(+), 16 deletions(-) diff --git a/apps/web/package.json b/apps/web/package.json index 5ae1f355..d1c3de30 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -15,7 +15,7 @@ "@profullstack/x402-gateway": "^0.11.0", "@sqlitecloud/drivers": "^1.0.880", "ioredis": "^5.11.1", - "next": "16.3.8", + "next": "16.4.1", "posthog-js": "^1.381.0", "react": "^19.0.0", "react-dom": "^19.0.0" diff --git a/bun.lock b/bun.lock index 25c3cb28..d8f07f75 100644 --- a/bun.lock +++ b/bun.lock @@ -20,7 +20,7 @@ }, "apps/tui": { "name": "@c0mpute/tui", - "version": "0.2.31", + "version": "0.2.34", "bin": { "c0mpute-tui": "./src/index.ts", }, @@ -34,14 +34,14 @@ }, "apps/web": { "name": "c0mpute", - "version": "0.2.31", + "version": "0.2.34", "dependencies": { "@c0mpute/shared": "workspace:*", "@profullstack/footer": "latest", "@profullstack/x402-gateway": "^0.11.0", "@sqlitecloud/drivers": "^1.0.880", "ioredis": "^5.11.1", - "next": "16.3.8", + "next": "16.4.1", "posthog-js": "^1.381.0", "react": "^19.0.0", "react-dom": "^19.0.0", @@ -59,7 +59,7 @@ }, "packages/shared": { "name": "@c0mpute/shared", - "version": "0.2.31", + "version": "0.2.34", "devDependencies": { "typescript": "^5.8.0", }, @@ -200,23 +200,23 @@ "@jridgewell/trace-mapping": ["@jridgewell/trace-mapping@0.3.31", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw=="], - "@next/env": ["@next/env@16.3.8", "", {}, "sha512-Al9zqHVV7TJv0eFuOU4U7Lvv74PTih4Ch63sk2xCIpSTkE3udFnaOcnzP2lQVymiL7yS9Cj2iClUXlR3EQ5sEw=="], + "@next/env": ["@next/env@16.4.1", "", {}, "sha512-5sUUrrSvs/2/2LnLoesybMGx12EtPB46fdZ6RhAw0XDGSPxU2LFyQBB7yuEiOFFJPKmBY6+q2jTr1/AMbnp0/g=="], - "@next/swc-darwin-arm64": ["@next/swc-darwin-arm64@16.3.8", "", { "os": "darwin", "cpu": "arm64" }, "sha512-2JPRMh2nmQG5CiL7cXGL9AGwnPWJQ//cTtAUCT+w511QHk79SYz3LGv/pc5X643B/WEO0rvu3Yww0hqwt3kgeA=="], + "@next/swc-darwin-arm64": ["@next/swc-darwin-arm64@16.4.1", "", { "os": "darwin", "cpu": "arm64" }, "sha512-U+hQ5Gj3fpzf4fveTIF3dpUFYhaSW8vHhdAnbiIomzXzg7boreYFgBqprepXFtW4sw+aTttiNmg0gew/iFNhbg=="], - "@next/swc-darwin-x64": ["@next/swc-darwin-x64@16.3.8", "", { "os": "darwin", "cpu": "x64" }, "sha512-GZtCCOBKJ4leVIT/Th0llWKhD1ca92lzbQiS5R5ON9QkoiFnilFsebDae1JU2a3HWoKMEmEZWGs1AGLavVM72Q=="], + "@next/swc-darwin-x64": ["@next/swc-darwin-x64@16.4.1", "", { "os": "darwin", "cpu": "x64" }, "sha512-/hqC3V1XLUjhMASf/WridKdO9FXoEgN3HBWmtKbj00MPgnltutfraWJ3bYTpCRIgEIpbjJyOVLpYgAhh/BkdcQ=="], - "@next/swc-linux-arm64-gnu": ["@next/swc-linux-arm64-gnu@16.3.8", "", { "os": "linux", "cpu": "arm64" }, "sha512-O659ygeQYqneJ1fBKMpFxIFqYkYswu8IAS1OCKK/4f3ZgJJm1dRz4fVJZRi/kLLWjnBKnebOePA4WNv+sV1pVA=="], + "@next/swc-linux-arm64-gnu": ["@next/swc-linux-arm64-gnu@16.4.1", "", { "os": "linux", "cpu": "arm64" }, "sha512-GHzncHbcaS9g95kcvTNtKQW3aCLoR+xc3Jm7qrkpk1R+D2BjMHIPyvQGRPKCdMX95BsH/421jBUK06q9tEwzjw=="], - "@next/swc-linux-arm64-musl": ["@next/swc-linux-arm64-musl@16.3.8", "", { "os": "linux", "cpu": "arm64" }, "sha512-dSjKSyWpzxoO1d3DIZZcP4XJcNaKeLmxQMFOiYl5vuBRMmweIqnAhty8tAmRsvTss779cK1FtYnDMj40e4TQlg=="], + "@next/swc-linux-arm64-musl": ["@next/swc-linux-arm64-musl@16.4.1", "", { "os": "linux", "cpu": "arm64" }, "sha512-1SuJyDxW/PR9dHJat/ZRgcYLhuSZ+1psP4DlKb2tKIuXbjygqpLrJWRSq+onZQBv8LcmU67EIrmb6c3XTaJLjw=="], - "@next/swc-linux-x64-gnu": ["@next/swc-linux-x64-gnu@16.3.8", "", { "os": "linux", "cpu": "x64" }, "sha512-lbqOuz3RPRcv+o9msNsJw5x4+Y1ZwPTs6vmL6DCf7i0fZfvng/F59wyeDwqHIvV0mK//RBy/jJkZ+nCKsSMXjQ=="], + "@next/swc-linux-x64-gnu": ["@next/swc-linux-x64-gnu@16.4.1", "", { "os": "linux", "cpu": "x64" }, "sha512-Istng1hMGp9TGO4lUqeKLd70MPN/OOkucVTP2Nmj+gLkwBgmPqUw8CJYBCC7nbl/B/23bBCcjCI5Hsh6hazC1A=="], - "@next/swc-linux-x64-musl": ["@next/swc-linux-x64-musl@16.3.8", "", { "os": "linux", "cpu": "x64" }, "sha512-+316WswI8ScVgZeUd+1KGaXkHhaYQzCjvH/05TZSpJ8zBizb1a4G7DtO7F12jcBIqMOtsz9ji1t48fmKtzqsGA=="], + "@next/swc-linux-x64-musl": ["@next/swc-linux-x64-musl@16.4.1", "", { "os": "linux", "cpu": "x64" }, "sha512-aSC9wMNiZRRFVpPkPWBzRwLQxIGm/CiQcXyFF1XNcgodb+uMxdk7aSSGGpDXCbnvZdf4itjHxpOd5h7i7zaiYw=="], - "@next/swc-win32-arm64-msvc": ["@next/swc-win32-arm64-msvc@16.3.8", "", { "os": "win32", "cpu": "arm64" }, "sha512-ji0gd4kMYUxO+1fJBIbiBVRCjzG/lloiyCccnlebvb1ZJ5qXCPZqYg4Jl1DrrixnWNMKylzgpmMWx0yNDYXlzw=="], + "@next/swc-win32-arm64-msvc": ["@next/swc-win32-arm64-msvc@16.4.1", "", { "os": "win32", "cpu": "arm64" }, "sha512-t/myvwFDlypMUjRvbBf8qLPyuaB0iXYYdBtwMt6DM6f+60wtGr4bSYholdPqNeV5VUXZhrpMwfza829kmhS3iA=="], - "@next/swc-win32-x64-msvc": ["@next/swc-win32-x64-msvc@16.3.8", "", { "os": "win32", "cpu": "x64" }, "sha512-WcTlaKt/TWkh5kUjdJcUmB1XgZ+1c6fz4Y9fDHL73YNSdGaUWjceeWrrlwF0nv19iABYWC4iAq1oX1w4Bn0vfg=="], + "@next/swc-win32-x64-msvc": ["@next/swc-win32-x64-msvc@16.4.1", "", { "os": "win32", "cpu": "x64" }, "sha512-6ICqPo9awCkrtYNPhwkx1uU7rlFWrZRrIboDHS2LU+jv088UBYQtmJ25h6pCp27/+FZjF6BQ4Te4ErugyMeuBg=="], "@posthog/core": ["@posthog/core@1.30.9", "", { "dependencies": { "@posthog/types": "1.381.0" } }, "sha512-Cn004VJ7ZWQRaVQG7efh+pMtRMIVZznktngXe5I3E8wClRdMwCZaSa6jo/X04Oc04z8PeMp4GEcWVkdEhmAEXw=="], @@ -318,7 +318,7 @@ "detect-libc": ["detect-libc@2.1.2", "", {}, "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ=="], - "dompurify": ["dompurify@3.4.8", "", { "optionalDependencies": { "@types/trusted-types": "^2.0.7" } }, "sha512-yb1cEmaOum7wFvOCSQxyfgVlv5D47Rc30iZWoMpbDIWTnJ6grDDQyu2KFJzB2k7u0pMuJcQ1zphH//fFnw2tjQ=="], + "dompurify": ["dompurify@3.4.17", "", { "optionalDependencies": { "@types/trusted-types": "^2.0.7" } }, "sha512-B/pSlYVHQ58kqISD/yDjuJ1yfzI34m1gF4lAod2bwSRhiN4K5Cl3H8Af7hqB2PmTL911tdEudnnXn5FnhRoz0w=="], "drizzle-kit": ["drizzle-kit@0.31.10", "", { "dependencies": { "@drizzle-team/brocli": "^0.10.2", "@esbuild-kit/esm-loader": "^2.5.5", "esbuild": "^0.25.4", "tsx": "^4.21.0" }, "bin": { "drizzle-kit": "bin.cjs" } }, "sha512-7OZcmQUrdGI+DUNNsKBn1aW8qSoKuTH7d0mYgSP8bAzdFzKoovxEFnoGQp2dVs82EOJeYycqRtciopszwUf8bw=="], @@ -402,7 +402,7 @@ "napi-build-utils": ["napi-build-utils@2.0.0", "", {}, "sha512-GEbrYkbfF7MoNaoh2iGG84Mnf/WZfB0GdGEsM8wz7Expx/LlWf5U8t9nvJKXSp3qr5IsEbK04cBGhol/KwOsWA=="], - "next": ["next@16.3.8", "", { "dependencies": { "@next/env": "16.3.8", "@swc/helpers": "0.5.23", "baseline-browser-mapping": "^2.9.19", "caniuse-lite": "^1.0.30001579", "postcss": "8.5.23", "styled-jsx": "5.1.6" }, "optionalDependencies": { "@next/swc-darwin-arm64": "16.3.8", "@next/swc-darwin-x64": "16.3.8", "@next/swc-linux-arm64-gnu": "16.3.8", "@next/swc-linux-arm64-musl": "16.3.8", "@next/swc-linux-x64-gnu": "16.3.8", "@next/swc-linux-x64-musl": "16.3.8", "@next/swc-win32-arm64-msvc": "16.3.8", "@next/swc-win32-x64-msvc": "16.3.8", "sharp": "^0.35.4" }, "peerDependencies": { "@opentelemetry/api": "^1.1.0", "@playwright/test": "^1.51.1", "babel-plugin-react-compiler": "*", "react": "^18.2.0 || 19.0.0-rc-de68d2f4-20241204 || ^19.0.0", "react-dom": "^18.2.0 || 19.0.0-rc-de68d2f4-20241204 || ^19.0.0", "sass": "^1.3.0" }, "optionalPeers": ["@opentelemetry/api", "@playwright/test", "babel-plugin-react-compiler", "sass"], "bin": { "next": "dist/bin/next" } }, "sha512-U7QEZaTini6wKrb8A8hqLLqYQyCetegKjCpJOyxk642vWoMoU1x5PyZCJFvgYgiptA8xc5j/9xYlZFO7w9Sjmw=="], + "next": ["next@16.4.1", "", { "dependencies": { "@next/env": "16.4.1", "@swc/helpers": "0.5.23", "baseline-browser-mapping": "^2.9.19", "caniuse-lite": "^1.0.30001579", "postcss": "8.5.23", "styled-jsx": "5.1.6" }, "optionalDependencies": { "@next/swc-darwin-arm64": "16.4.1", "@next/swc-darwin-x64": "16.4.1", "@next/swc-linux-arm64-gnu": "16.4.1", "@next/swc-linux-arm64-musl": "16.4.1", "@next/swc-linux-x64-gnu": "16.4.1", "@next/swc-linux-x64-musl": "16.4.1", "@next/swc-win32-arm64-msvc": "16.4.1", "@next/swc-win32-x64-msvc": "16.4.1", "sharp": "^0.35.5" }, "peerDependencies": { "@opentelemetry/api": "^1.1.0", "@playwright/test": "^1.51.1", "babel-plugin-react-compiler": "*", "react": "^18.2.0 || 19.0.0-rc-de68d2f4-20241204 || ^19.0.0", "react-dom": "^18.2.0 || 19.0.0-rc-de68d2f4-20241204 || ^19.0.0", "sass": "^1.3.0" }, "optionalPeers": ["@opentelemetry/api", "@playwright/test", "babel-plugin-react-compiler", "sass"], "bin": { "next": "dist/bin/next" } }, "sha512-uc657V62E34fOI6W5NtG9IzwsPcms0Z60grz2MJGtglgD+pTFnNt4Yw2PzaU622tfX4vhrDgLZzicE2YlhI20Q=="], "node-abi": ["node-abi@3.92.0", "", { "dependencies": { "semver": "^7.3.5" } }, "sha512-KdHvFWZjEKDf0cakgFjebl371GPsISX2oZHcuyKqM7DtogIsHrqKeLTo8wBHxaXRAQlY2PsPlZmfo+9ZCxEREQ=="], From e3dbc958ed0eb98568a19d6763ef7db7201fefe5 Mon Sep 17 00:00:00 2001 From: Anthony Ettinger Date: Mon, 26 Oct 2026 08:05:44 +0000 Subject: [PATCH 3/3] temporal: retry auctions while the gossip mesh forms; seeds relay temporal topics; e2e dials the infer worker (no mDNS on CI) Co-Authored-By: Claude Opus 5.5 --- .../c0mpute-core/src/status_aggregator.rs | 5 +- .../c0mpute-core/src/temporal/client.rs | 52 +++++++++++++------ .../crates/c0mpute-core/tests/temporal_e2e.rs | 6 ++- 3 files changed, 46 insertions(+), 17 deletions(-) diff --git a/node/crates/c0mpute-core/src/status_aggregator.rs b/node/crates/c0mpute-core/src/status_aggregator.rs index ebac2646..c6ebc152 100644 --- a/node/crates/c0mpute-core/src/status_aggregator.rs +++ b/node/crates/c0mpute-core/src/status_aggregator.rs @@ -58,7 +58,10 @@ const DHT_CRAWL_INTERVAL: Duration = Duration::from_secs(30); /// worker daemon; `infernet.inference` is emitted by the infernet peer /// binary. Both always appear in the output (as zeros when idle) to mirror /// the page's stub shape. -const KNOWN_WORKLOADS: &[&str] = &["ffmpeg.transcode", "infernet.inference"]; +// The temporal workloads (DIP 0026) are listed so seeds running the +// aggregator also relay them for buyers that only know the seeds; their +// session calls are sealed, so the aggregator sees only ciphertext. +const KNOWN_WORKLOADS: &[&str] = &["ffmpeg.transcode", "infernet.inference", "infernet.temporal.train", "infernet.temporal.infer"]; /// Roles we always surface (even at zero) so the "workers by role" table /// stays populated. Extra roles observed on the wire are added dynamically. diff --git a/node/crates/c0mpute-core/src/temporal/client.rs b/node/crates/c0mpute-core/src/temporal/client.rs index 06ca5ec1..30f1218c 100644 --- a/node/crates/c0mpute-core/src/temporal/client.rs +++ b/node/crates/c0mpute-core/src/temporal/client.rs @@ -20,6 +20,22 @@ use super::http::TransferServer; use super::{INFER_WORKLOAD, SCHEMA_VERSION, SessionCall, SessionReady, SessionReply, SessionSpec, TRAIN_WORKLOAD, TrainSpec, select_family}; use crate::buyer::{JobAuction, run_auction}; +/// Run an auction, retrying while gossipsub has no subscriber for the topic +/// yet (a worker that just joined, or a fresh buyer node): those errors mean +/// "mesh still forming", not "no worker". Gives up after ~30 s. +pub async fn auction_with_mesh_retry(net: Arc, make: impl Fn() -> JobAuction) -> Result { + let mut tries = 0; + loop { + match run_auction(net.clone(), make()).await { + Err(e) if tries < 30 && { let m = format!("{e:#}"); m.contains("NoPeersSubscribedToTopic") || m.contains("InsufficientPeers") } => { + tries += 1; + tokio::time::sleep(Duration::from_secs(1)).await; + } + other => return other, + } + } +} + /// RFC 3339 UTC timestamp without pulling in a date crate. pub fn now_rfc3339() -> String { let secs = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0) as i64; @@ -144,14 +160,17 @@ pub async fn train(net: Arc, req: &TrainRequest) -> Result let mut last_err = None; let mut outcome = None; for attempt in 0..=req.retries.min(5) { - let auction = JobAuction::new(TRAIN_WORKLOAD, serde_json::to_value(&spec)?) - .with_required_capabilities(tags.clone()) - .with_allowed_bidders(req.workers.clone()) - .with_max_price_usd(req.max_price_usd) - .with_bid_window(req.bid_window) - .with_deadline(Duration::from_secs(req.timeout_s + 600)) - .with_receipt_timeout(Duration::from_secs(req.timeout_s + 300)); - match run_auction(net.clone(), auction).await { + let spec_v = serde_json::to_value(&spec)?; + let make = || { + JobAuction::new(TRAIN_WORKLOAD, spec_v.clone()) + .with_required_capabilities(tags.clone()) + .with_allowed_bidders(req.workers.clone()) + .with_max_price_usd(req.max_price_usd) + .with_bid_window(req.bid_window) + .with_deadline(Duration::from_secs(req.timeout_s + 600)) + .with_receipt_timeout(Duration::from_secs(req.timeout_s + 300)) + }; + match auction_with_mesh_retry(net.clone(), make).await { Ok(o) if o.receipt.status == JobStatus::Completed => { outcome = Some(o); break; @@ -262,13 +281,16 @@ pub async fn open_session(net: Arc, req: &OpenRequest) -> Result< spec.validate()?; let mut rx = net.messages(); let tags = required_tags(INFER_WORKLOAD, &Requirements { model_hash: Some(req.model_hash.clone()), ..Default::default() }); - let auction = JobAuction::new(INFER_WORKLOAD, serde_json::to_value(&spec)?) - .with_required_capabilities(tags) - .with_allowed_bidders(req.workers.clone()) - .with_max_price_usd(req.max_price_usd) - .with_bid_window(req.bid_window) - .with_receipt_timeout(Duration::from_secs(60)); - let o = run_auction(net.clone(), auction).await?; + let spec_v = serde_json::to_value(&spec)?; + let make = || { + JobAuction::new(INFER_WORKLOAD, spec_v.clone()) + .with_required_capabilities(tags.clone()) + .with_allowed_bidders(req.workers.clone()) + .with_max_price_usd(req.max_price_usd) + .with_bid_window(req.bid_window) + .with_receipt_timeout(Duration::from_secs(60)) + }; + let o = auction_with_mesh_retry(net.clone(), make).await?; if o.receipt.status != JobStatus::Completed || o.receipt.output_hash.as_deref() != Some(req.model_hash.as_str()) { bail!("worker {} could not open the session ({:?})", o.accepted_bid.bidder_peer_id, o.receipt.status); } diff --git a/node/crates/c0mpute-core/tests/temporal_e2e.rs b/node/crates/c0mpute-core/tests/temporal_e2e.rs index 77d9c9f0..a5048ee3 100644 --- a/node/crates/c0mpute-core/tests/temporal_e2e.rs +++ b/node/crates/c0mpute-core/tests/temporal_e2e.rs @@ -111,6 +111,10 @@ async fn train_then_serve_a_sticky_session() { .expect("infer worker serves"); let sid_peer = s.net.peer_id().to_base58(); assert!(s.tags.iter().any(|t| t.ends_with(cfc_hash.trim_start_matches("sha256:")))); + let saddr = format!("{}/p2p/{sid_peer}", s.net.listen_addrs().await.unwrap()[0]); + // The training worker does not subscribe to the infer topic, so it cannot + // relay it: session clients dial the infer worker (no mDNS on CI). + let buyer = node::spawn_node(&net(&tmp.path().join("b2/id"), vec![saddr.clone()])).await.unwrap(); tokio::time::sleep(Duration::from_secs(3)).await; let sf = client::open_session( @@ -139,7 +143,7 @@ async fn train_then_serve_a_sticky_session() { assert_eq!(r["error"]["code"], json!("E_SEQ_LATE")); // Another peer that copied the session file cannot drive the session. - let thief = node::spawn_node(&net(&tmp.path().join("t/id"), vec![waddr])).await.unwrap(); + let thief = node::spawn_node(&net(&tmp.path().join("t/id"), vec![saddr, waddr])).await.unwrap(); tokio::time::sleep(Duration::from_secs(2)).await; let r = client::call(thief, &sf, json!({"op": "reset"}), Duration::from_secs(5)).await; assert!(r.is_err(), "worker ignores calls from a peer that did not open the session");