Skip to content

armgit / kwant

Public Imported from GitHub
0

Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.

Parallel Universe slice 1: scenario store, container harness, dated price table

Lin (kwant bot)6a9840038689
diff --git a/docs/parallel-universe.md b/docs/parallel-universe.md
new file mode 100644
index 00000000..9b2071b9
--- /dev/null
+++ b/docs/parallel-universe.md
@@ -0,0 +1,59 @@
+# Parallel Universe
+
+Compares up to three ways to deploy one app ("stay on managed hosting, move to a VPS, or go serverless?") without
+a cloud account or any spending. The code is `src/parallel/`, `src/db/parallel.rs` and `src/server/parallel_routes.rs`.
+
+**Status: slice 1.** This covers the scenario store, the container harness and the price table. The branch runner (one bot per option)
+and the comparison report come next. The full design is in `/home/maus/shared/ship-software-safely/parallel-universe/design.md`.
+
+## Where numbers come from
+
+Every number is a `Figure` with a `tag`:
+
+| tag | meaning | carries |
+|---|---|---|
+| `verified` | measured on this machine by the harness | `command` (exact docker/oha argv), `raw_output` (oha's JSON, ≤ 64 KB), `measured_at` |
+| `estimate` | computed from the price table | `source_url`, `as_of`, `stale` (older than 180 days), `assumptions` |
+| `speculation` | neither measured nor priced | `note` |
+
+Latency measured here is this server's, not the provider's. A report must say so.
+
+## Price table
+
+The table is `src/parallel/prices.json`, compiled in. Each entry was read by hand from the provider's public page on its `as_of` date. The
+server never fetches prices. To update an entry, edit the JSON in a commit and give it a new `as_of`. `prices::check_table` (a unit
+test) refuses an entry without an https source, with a future date or with negative prices. Currencies are not converted.
+
+The table was seeded on 2026-10-20 with Hetzner CPX02/CPX12 (EUR, excl. VAT), DigitalOcean Basic 1/2 GiB, Fly.io shared-cpu-1x 512 MB/1 GB
+and AWS Lambda x86 us-east-1.
+
+## Container harness (`parallel::harness::run_branch`)
+
+1. It creates `docker network create --internal`, a network with no default route, so there's no internet, no host and no production. Ports 8799/8800 can't be reached.
+2. It builds the app with `docker build --network none` (offline), or uses an image already on the machine.
+3. It runs the app with `--cpus`, `--memory` (= `--memory-swap`), `--pids-limit`, `--cap-drop ALL` plus a few file/uid caps, and
+ `no-new-privileges`. **Nothing is ever published on a host port.**
+4. It waits for the health path (an oha probe, below 50 % of the time limit).
+5. It runs the load: oha (`ghcr.io/hatoo/oha:1.16.0`, `docker pull` it once) in a second limited container on the same network.
+6. It samples memory with `docker stats`.
+7. It removes every container, the network and a built image on success, failure and timeout. Whatever can't be removed is
+ returned in `cleanup_errors`. Every object carries the label `kwnt.pu.run=<run id>`, and `harness::sweep` removes leftovers by
+ that label. It never touches `kwnt-browser-*` or `kwnt-executor-*`.
+
+Limits per option: 0.1–2 CPUs, 64–2048 MB, 16–512 pids, 30–900 s. At most 3 options, reserving at most 3072 MB together.
+
+## API (person-only: no token 401, bot or wrong token 403)
+
+- `GET/POST /api/parallel/scenarios`, `GET/PUT/DELETE /api/parallel/scenarios/:id`. A body that fails validation gets a 400 `{error}`.
+- `GET /api/parallel/prices` returns `{prices, stale_after_days}`.
+- `POST /api/parallel/estimate {plan, traffic}` returns `{figures: [Figure]}`.
+
+A scenario is `{title, question, requirements, traffic: {monthly_requests, peak_rps, avg_response_kb, avg_duration_ms},
+load: {requests, concurrency, path}, criteria: [{key: cost|p95_latency|ops_burden|rollback, weight 0–10}], options: [{key,
+label, plan?, app: {image | context (+dockerfile), port, health_path}, limits, ops_notes, rollback_notes}]}`.
+
+## Tests
+
+`cargo test --test parallel_test` covers the API. `-- --include-ignored` also runs the harness against a synthetic Python app. That needs
+Docker, `kwnt-executor:v1` and the oha image. It covers measuring, cleanup after an app that never answers, and the network reaching
+neither the internet nor the host.
diff --git a/src/db/mod.rs b/src/db/mod.rs
index efeabe98..8b8a8e26 100644
--- a/src/db/mod.rs
+++ b/src/db/mod.rs
@@ -3,6 +3,7 @@ pub mod profiles;
pub mod continuity;
pub mod threads;
pub mod zombie;
+pub mod parallel;
pub mod history;
pub mod attachments;
pub mod questions;
@@ -136,6 +137,7 @@ impl Database {
db.migrate_history().await?;
db.migrate_away().await?;
db.migrate_zombie().await?;
+ db.migrate_parallel().await?;
if spaces {
let migration = db.migrate_spaces(data_dir, fresh).await?;
db.require_spaces_schema(&migration).await?;
diff --git a/src/db/parallel.rs b/src/db/parallel.rs
new file mode 100644
index 00000000..edd95a41
--- /dev/null
+++ b/src/db/parallel.rs
@@ -0,0 +1,108 @@
+//! Parallel Universe's scenarios (`pu_scenarios`). The nested parts (requirements, traffic, load,
+//! criteria, options) are JSON columns checked in Rust by `parallel::Scenario::validate`, so a new
+//! field needs no table rebuild.
+
+use super::{Database, DbError};
+use crate::parallel::Scenario;
+use chrono::{DateTime, Utc};
+use sqlx::FromRow;
+
+#[derive(FromRow)]
+struct ScenarioRow {
+ id: String,
+ title: String,
+ question: String,
+ requirements: String,
+ traffic: String,
+ load: String,
+ criteria: String,
+ options: String,
+ created_at: DateTime<Utc>,
+ updated_at: DateTime<Utc>,
+}
+
+impl ScenarioRow {
+ fn into_scenario(self) -> Result<Scenario, DbError> {
+ Ok(Scenario {
+ id: self.id,
+ title: self.title,
+ question: self.question,
+ requirements: serde_json::from_str(&self.requirements)?,
+ traffic: serde_json::from_str(&self.traffic)?,
+ load: serde_json::from_str(&self.load)?,
+ criteria: serde_json::from_str(&self.criteria)?,
+ options: serde_json::from_str(&self.options)?,
+ created_at: self.created_at,
+ updated_at: self.updated_at,
+ })
+ }
+}
+
+const COLUMNS: &str = "id, title, question, requirements, traffic, load, criteria, options, created_at, updated_at";
+
+impl Database {
+ pub(super) async fn migrate_parallel(&self) -> Result<(), DbError> {
+ sqlx::query(
+ "CREATE TABLE IF NOT EXISTS pu_scenarios (
+ id TEXT PRIMARY KEY,
+ title TEXT NOT NULL,
+ question TEXT NOT NULL DEFAULT '',
+ requirements TEXT NOT NULL DEFAULT '{}',
+ traffic TEXT NOT NULL,
+ load TEXT NOT NULL,
+ criteria TEXT NOT NULL DEFAULT '[]',
+ options TEXT NOT NULL DEFAULT '[]',
+ created_at TIMESTAMP NOT NULL,
+ updated_at TIMESTAMP NOT NULL
+ )",
+ )
+ .execute(&self.pool)
+ .await?;
+ Ok(())
+ }
+
+ /// Newest change first.
+ pub async fn pu_scenarios(&self) -> Result<Vec<Scenario>, DbError> {
+ let rows: Vec<ScenarioRow> = sqlx::query_as(&format!("SELECT {COLUMNS} FROM pu_scenarios ORDER BY updated_at DESC LIMIT 200"))
+ .fetch_all(&self.pool)
+ .await?;
+ rows.into_iter().map(ScenarioRow::into_scenario).collect()
+ }
+
+ pub async fn pu_scenario(&self, id: &str) -> Result<Option<Scenario>, DbError> {
+ let row: Option<ScenarioRow> = sqlx::query_as(&format!("SELECT {COLUMNS} FROM pu_scenarios WHERE id = ?"))
+ .bind(id)
+ .fetch_optional(&self.pool)
+ .await?;
+ row.map(ScenarioRow::into_scenario).transpose()
+ }
+
+ /// Inserts `s`, or replaces everything but `created_at` of the scenario with its id.
+ pub async fn pu_put_scenario(&self, s: &Scenario) -> Result<(), DbError> {
+ sqlx::query(&format!(
+ "INSERT INTO pu_scenarios ({COLUMNS}) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
+ ON CONFLICT(id) DO UPDATE SET
+ title = excluded.title, question = excluded.question, requirements = excluded.requirements,
+ traffic = excluded.traffic, load = excluded.load, criteria = excluded.criteria,
+ options = excluded.options, updated_at = excluded.updated_at"
+ ))
+ .bind(&s.id)
+ .bind(&s.title)
+ .bind(&s.question)
+ .bind(serde_json::to_string(&s.requirements)?)
+ .bind(serde_json::to_string(&s.traffic)?)
+ .bind(serde_json::to_string(&s.load)?)
+ .bind(serde_json::to_string(&s.criteria)?)
+ .bind(serde_json::to_string(&s.options)?)
+ .bind(s.created_at)
+ .bind(s.updated_at)
+ .execute(&self.pool)
+ .await?;
+ Ok(())
+ }
+
+ /// Whether a scenario was deleted.
+ pub async fn pu_delete_scenario(&self, id: &str) -> Result<bool, DbError> {
+ Ok(sqlx::query("DELETE FROM pu_scenarios WHERE id = ?").bind(id).execute(&self.pool).await?.rows_affected() > 0)
+ }
+}
diff --git a/src/lib.rs b/src/lib.rs
index ebdb29a7..79c3166d 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -5,6 +5,7 @@ pub mod drivers;
pub mod embedded;
pub mod import;
pub mod mcp;
+pub mod parallel;
pub mod profiles;
pub mod router;
pub mod routines;
diff --git a/src/parallel/harness.rs b/src/parallel/harness.rs
new file mode 100644
index 00000000..e382837f
--- /dev/null
+++ b/src/parallel/harness.rs
@@ -0,0 +1,436 @@
+//! Runs one deployment option in throwaway containers and measures it.
+//!
+//! For each branch: an `--internal` docker network (no route to the internet, the host or
+//! production), the app container with CPU, memory and process limits and no published port,
+//! an oha load test from a second container on that network, and a memory sample. Everything it
+//! created is removed afterwards, whether the run succeeded, failed or timed out; every object
+//! carries the label `kwnt.pu.run=<run id>`, so [`sweep`] can remove anything a crash left behind
+//! without touching other containers.
+
+use super::{AppSpec, Figure, Limits, LoadSpec};
+use chrono::Utc;
+use serde_json::Value;
+use std::time::Duration;
+use thiserror::Error;
+use tokio::process::Command;
+use tokio::time::{sleep, timeout, Instant};
+
+/// The load tool, run as a container next to the app (pinned; `docker pull` it once).
+pub const OHA_IMAGE: &str = "ghcr.io/hatoo/oha:1.16.0";
+pub const RUN_LABEL: &str = "kwnt.pu.run";
+
+#[derive(Debug, Error, PartialEq)]
+pub enum HarnessError {
+ #[error("Docker is not available on this machine")]
+ DockerUnavailable,
+ #[error("the load tool image is missing: run `docker pull {OHA_IMAGE}`")]
+ LoadToolMissing,
+ #[error("{0}")]
+ Invalid(String),
+ #[error("building the app failed: {0}")]
+ Build(String),
+ #[error("starting the app failed: {0}")]
+ Start(String),
+ #[error("the app did not answer on its port in time")]
+ NotReady,
+ #[error("the load test failed: {0}")]
+ Load(String),
+ #[error("the branch ran past its time limit")]
+ Timeout,
+}
+
+/// What to run for one option.
+#[derive(Debug, Clone)]
+pub struct BranchSpec {
+ pub run_id: String,
+ pub branch: String,
+ pub app: AppSpec,
+ pub limits: Limits,
+ pub load: LoadSpec,
+}
+
+/// What one branch produced. `cleanup_errors` is empty when everything it made is gone.
+#[derive(Debug)]
+pub struct BranchOutcome {
+ pub result: Result<Vec<Figure>, HarnessError>,
+ pub cleanup_errors: Vec<String>,
+}
+
+/// The docker objects one branch creates.
+#[derive(Debug, Clone, PartialEq)]
+pub struct Names {
+ pub label: String,
+ pub network: String,
+ pub app: String,
+ pub probe: String,
+ pub load: String,
+ pub image: String,
+}
+
+impl Names {
+ pub fn new(run_id: &str, branch: &str) -> Self {
+ let run: String = run_id.chars().filter(|c| c.is_ascii_alphanumeric()).take(8).collect::<String>().to_lowercase();
+ let prefix = format!("kwnt-pu-{run}-{branch}");
+ Names {
+ label: format!("{RUN_LABEL}={run_id}"),
+ network: format!("{prefix}-net"),
+ app: format!("{prefix}-app"),
+ probe: format!("{prefix}-probe"),
+ load: format!("{prefix}-load"),
+ image: format!("{prefix}:run"),
+ }
+ }
+}
+
+fn s(v: &[&str]) -> Vec<String> {
+ v.iter().map(|x| x.to_string()).collect()
+}
+
+pub fn network_args(n: &Names) -> Vec<String> {
+ s(&["network", "create", "--internal", "--label", &n.label, &n.network])
+}
+
+/// An offline build: the Dockerfile cannot download anything.
+pub fn build_args(n: &Names, app: &AppSpec) -> Option<Vec<String>> {
+ let context = app.context.as_deref()?;
+ let dockerfile = std::path::Path::new(context).join(app.dockerfile.as_deref().unwrap_or("Dockerfile"));
+ Some(s(&["build", "--network", "none", "--label", &n.label, "-t", &n.image, "-f", &dockerfile.to_string_lossy(), context]))
+}
+
+/// The app container: limited, on the internal network only, no published port.
+pub fn app_args(n: &Names, app: &AppSpec, limits: &Limits) -> Vec<String> {
+ let image = app.image.clone().unwrap_or_else(|| n.image.clone());
+ let memory = format!("{}m", limits.memory_mb);
+ s(&[
+ "run", "-d", "--name", &n.app, "--network", &n.network, "--label", &n.label,
+ "--cpus", &format!("{}", limits.cpus), "--memory", &memory, "--memory-swap", &memory,
+ "--pids-limit", &limits.pids.to_string(),
+ "--cap-drop", "ALL", "--cap-add", "CHOWN", "--cap-add", "SETUID", "--cap-add", "SETGID",
+ "--cap-add", "NET_BIND_SERVICE", "--cap-add", "DAC_OVERRIDE", "--cap-add", "FOWNER",
+ "--security-opt", "no-new-privileges", "--restart", "no",
+ &image,
+ ])
+}
+
+fn target(n: &Names, app: &AppSpec, path: &str) -> String {
+ format!("http://{}:{}{}", n.app, app.port, path)
+}
+
+pub fn probe_args(n: &Names, app: &AppSpec) -> Vec<String> {
+ s(&[
+ "run", "--rm", "--name", &n.probe, "--network", &n.network, "--label", &n.label, "--cpus", "0.5", "--memory", "128m",
+ OHA_IMAGE, "-n", "1", "-t", "2s", "--no-tui", "--output-format", "json", &target(n, app, &app.health_path),
+ ])
+}
+
+pub fn load_args(n: &Names, app: &AppSpec, load: &LoadSpec) -> Vec<String> {
+ s(&[
+ "run", "--rm", "--name", &n.load, "--network", &n.network, "--label", &n.label, "--cpus", "1", "--memory", "256m",
+ OHA_IMAGE, "-n", &load.requests.to_string(), "-c", &load.concurrency.to_string(), "-t", "10s",
+ "--no-tui", "--output-format", "json", &target(n, app, &load.path),
+ ])
+}
+
+struct Out {
+ ok: bool,
+ stdout: String,
+ stderr: String,
+}
+
+async fn docker(args: &[String], limit: Duration) -> Result<Out, String> {
+ let run = Command::new("docker").args(args).kill_on_drop(true).output();
+ match timeout(limit, run).await {
+ Err(_) => Err(format!("docker {} timed out", args.first().map(String::as_str).unwrap_or(""))),
+ Ok(Err(e)) => Err(e.to_string()),
+ Ok(Ok(o)) => Ok(Out {
+ ok: o.status.success(),
+ stdout: String::from_utf8_lossy(&o.stdout).into_owned(),
+ stderr: crate::zombie::clip(String::from_utf8_lossy(&o.stderr).trim(), 2000),
+ }),
+ }
+}
+
+pub async fn docker_available() -> bool {
+ matches!(docker(&s(&["version", "--format", "{{.Server.Version}}"]), Duration::from_secs(3)).await, Ok(o) if o.ok)
+}
+
+/// What oha printed, as figures. `None` when it is not oha's JSON.
+pub fn parse_oha(raw: &str) -> Option<OhaSummary> {
+ let v: Value = serde_json::from_str(raw).ok()?;
+ let lat = &v["metrics"]["latency_ms"];
+ let codes = v["statusCodeDistribution"].as_object();
+ let total: u64 = codes.map(|c| c.values().filter_map(Value::as_u64).sum()).unwrap_or(0);
+ let ok: u64 = codes
+ .map(|c| c.iter().filter(|(k, _)| k.starts_with('2') || k.starts_with('3')).filter_map(|(_, v)| v.as_u64()).sum())
+ .unwrap_or(0);
+ Some(OhaSummary {
+ p50_ms: lat["p50"].as_f64()?,
+ p95_ms: lat["p95"].as_f64()?,
+ p99_ms: lat["p99"].as_f64()?,
+ requests_per_sec: v["metrics"]["requests_per_sec"].as_f64()?,
+ success_rate: v["metrics"]["success_rate"].as_f64()?,
+ responses: total,
+ ok_responses: ok,
+ })
+}
+
+#[derive(Debug, Clone, PartialEq)]
+pub struct OhaSummary {
+ pub p50_ms: f64,
+ pub p95_ms: f64,
+ pub p99_ms: f64,
+ pub requests_per_sec: f64,
+ /// Requests that got any answer (oha's own measure).
+ pub success_rate: f64,
+ pub responses: u64,
+ /// 2xx and 3xx.
+ pub ok_responses: u64,
+}
+
+/// `docker stats` memory ("12.5MiB / 512MiB") in MB.
+pub fn parse_mem_mb(s: &str) -> Option<f64> {
+ let used = s.split('/').next()?.trim();
+ let split = used.find(|c: char| c.is_ascii_alphabetic())?;
+ let (num, unit) = used.split_at(split);
+ let n: f64 = num.trim().parse().ok()?;
+ let factor = match unit {
+ "B" => 1.0 / (1024.0 * 1024.0),
+ "KiB" | "kB" | "KB" => 1.0 / 1024.0,
+ "MiB" | "MB" => 1.0,
+ "GiB" | "GB" => 1024.0,
+ _ => return None,
+ };
+ Some((n * factor * 10.0).round() / 10.0)
+}
+
+fn command_line(args: &[String]) -> String {
+ std::iter::once("docker").chain(args.iter().map(String::as_str)).collect::<Vec<_>>().join(" ")
+}
+
+impl BranchSpec {
+ pub fn validate(&self) -> Result<(), HarnessError> {
+ if self.run_id.chars().filter(|c| c.is_ascii_alphanumeric()).count() < 8 || self.run_id.len() > 64 {
+ return Err(HarnessError::Invalid("run id needs at least 8 letters or digits".into()));
+ }
+ if !super::is_slug(&self.branch, 32) {
+ return Err(HarnessError::Invalid("branch must be a slug".into()));
+ }
+ self.app.validate().map_err(HarnessError::Invalid)?;
+ self.limits.validate().map_err(HarnessError::Invalid)?;
+ if let Some(c) = &self.app.context {
+ if !std::path::Path::new(c).is_dir() {
+ return Err(HarnessError::Invalid("context is not a directory".into()));
+ }
+ }
+ Ok(())
+ }
+}
+
+/// Builds, starts, loads and measures one option, then removes everything it made.
+pub async fn run_branch(spec: &BranchSpec) -> BranchOutcome {
+ if let Err(e) = spec.validate() {
+ return BranchOutcome { result: Err(e), cleanup_errors: Vec::new() };
+ }
+ if !docker_available().await {
+ return BranchOutcome { result: Err(HarnessError::DockerUnavailable), cleanup_errors: Vec::new() };
+ }
+ let names = Names::new(&spec.run_id, &spec.branch);
+ let limit = Duration::from_secs(spec.limits.timeout_secs);
+ let result = match timeout(limit, steps(spec, &names, Instant::now() + limit / 2)).await {
+ Ok(r) => r,
+ Err(_) => Err(HarnessError::Timeout),
+ };
+ let cleanup_errors = cleanup(&names, spec.app.context.is_some()).await;
+ BranchOutcome { result, cleanup_errors }
+}
+
+async fn steps(spec: &BranchSpec, n: &Names, ready_by: Instant) -> Result<Vec<Figure>, HarnessError> {
+ let step = Duration::from_secs(spec.limits.timeout_secs);
+ let inspect = docker(&s(&["image", "inspect", "--format", "{{.Id}}", OHA_IMAGE]), Duration::from_secs(10)).await;
+ if !matches!(inspect, Ok(ref o) if o.ok) {
+ return Err(HarnessError::LoadToolMissing);
+ }
+ let o = docker(&network_args(n), Duration::from_secs(30)).await.map_err(HarnessError::Start)?;
+ if !o.ok {
+ return Err(HarnessError::Start(o.stderr));
+ }
+ if let Some(args) = build_args(n, &spec.app) {
+ let o = docker(&args, step).await.map_err(HarnessError::Build)?;
+ if !o.ok {
+ return Err(HarnessError::Build(o.stderr));
+ }
+ }
+ let o = docker(&app_args(n, &spec.app, &spec.limits), Duration::from_secs(60)).await.map_err(HarnessError::Start)?;
+ if !o.ok {
+ return Err(HarnessError::Start(o.stderr));
+ }
+ // ready once the health path answers with anything below 500
+ loop {
+ if let Ok(o) = docker(&probe_args(n, &spec.app), Duration::from_secs(20)).await {
+ if parse_oha(&o.stdout).is_some_and(|p| p.responses > 0 && p.ok_responses == p.responses) {
+ break;
+ }
+ }
+ let running = docker(&s(&["inspect", "-f", "{{.State.Running}}", &n.app]), Duration::from_secs(10)).await;
+ if !matches!(running, Ok(ref o) if o.stdout.trim() == "true") {
+ return Err(HarnessError::Start("the app container exited".into()));
+ }
+ if Instant::now() >= ready_by {
+ return Err(HarnessError::NotReady);
+ }
+ sleep(Duration::from_secs(1)).await;
+ }
+ let args = load_args(n, &spec.app, &spec.load);
+ let o = docker(&args, step).await.map_err(HarnessError::Load)?;
+ let at = Utc::now();
+ let summary = parse_oha(&o.stdout).ok_or_else(|| HarnessError::Load(if o.stderr.is_empty() { "no result".into() } else { o.stderr.clone() }))?;
+ let cmd = command_line(&args);
+ let raw = o.stdout.trim();
+ let mut figures = vec![
+ Figure::verified("p50_latency", summary.p50_ms, "ms", &cmd, raw, at),
+ Figure::verified("p95_latency", summary.p95_ms, "ms", &cmd, raw, at),
+ Figure::verified("p99_latency", summary.p99_ms, "ms", &cmd, raw, at),
+ Figure::verified("requests_per_sec", summary.requests_per_sec, "1/s", &cmd, raw, at),
+ Figure::verified("success_rate", summary.success_rate, "ratio", &cmd, raw, at),
+ ];
+ if summary.responses > 0 {
+ figures.push(Figure::verified("ok_share", summary.ok_responses as f64 / summary.responses as f64, "ratio", &cmd, raw, at));
+ }
+ let stats = s(&["stats", "--no-stream", "--format", "{{.MemUsage}}", &n.app]);
+ if let Ok(o) = docker(&stats, Duration::from_secs(20)).await {
+ if let Some(mb) = parse_mem_mb(o.stdout.trim()) {
+ figures.push(Figure::verified("memory_after_load", mb, "MB", &command_line(&stats), o.stdout.trim(), Utc::now()));
+ }
+ }
+ Ok(figures)
+}
+
+fn gone(stderr: &str) -> bool {
+ let e = stderr.to_lowercase();
+ e.contains("no such") || e.contains("not found")
+}
+
+/// Removes everything `n` names; what could not be removed comes back as messages.
+pub async fn cleanup(n: &Names, built: bool) -> Vec<String> {
+ let mut errors = Vec::new();
+ let run = |args: Vec<String>| async move {
+ match docker(&args, Duration::from_secs(60)).await {
+ Ok(o) if o.ok || gone(&o.stderr) => None,
+ Ok(o) => Some(format!("{}: {}", command_line(&args), o.stderr)),
+ Err(e) => Some(format!("{}: {e}", command_line(&args))),
+ }
+ };
+ for name in [&n.load, &n.probe, &n.app] {
+ errors.extend(run(s(&["rm", "-f", name])).await);
+ }
+ errors.extend(run(s(&["network", "rm", &n.network])).await);
+ if built {
+ errors.extend(run(s(&["rmi", "-f", &n.image])).await);
+ }
+ errors
+}
+
+/// Removes every container, network and image with the run label (one run's, or all runs'
+/// when `run_id` is `None`). Returns how many objects were removed.
+pub async fn sweep(run_id: Option<&str>) -> Result<usize, String> {
+ let filter = match run_id {
+ Some(id) => format!("label={RUN_LABEL}={id}"),
+ None => format!("label={RUN_LABEL}"),
+ };
+ let mut removed = 0;
+ for (list, rm) in [
+ (s(&["ps", "-aq", "--filter", &filter]), s(&["rm", "-f"])),
+ (s(&["network", "ls", "-q", "--filter", &filter]), s(&["network", "rm"])),
+ (s(&["images", "-q", "--filter", &filter]), s(&["rmi", "-f"])),
+ ] {
+ let o = docker(&list, Duration::from_secs(30)).await?;
+ let ids: Vec<String> = o.stdout.split_whitespace().map(String::from).collect();
+ if ids.is_empty() {
+ continue;
+ }
+ let mut args = rm;
+ args.extend(ids.iter().cloned());
+ let o = docker(&args, Duration::from_secs(60)).await?;
+ if !o.ok {
+ return Err(o.stderr);
+ }
+ removed += ids.len();
+ }
+ Ok(removed)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn app() -> AppSpec {
+ AppSpec { image: Some("kwnt-executor:v1".into()), context: None, dockerfile: None, port: 8080, health_path: "/".into() }
+ }
+
+ #[test]
+ fn names_are_scoped_to_the_run_and_branch() {
+ let n = Names::new("3f2a9c1e-0000-4000", "vps");
+ assert_eq!(n.app, "kwnt-pu-3f2a9c1e-vps-app");
+ assert_eq!(n.network, "kwnt-pu-3f2a9c1e-vps-net");
+ assert_eq!(n.label, "kwnt.pu.run=3f2a9c1e-0000-4000");
+ assert!(!n.app.starts_with("kwnt-browser") && !n.app.starts_with("kwnt-executor"));
+ }
+
+ #[test]
+ fn the_app_runs_limited_on_an_internal_network_with_no_published_port() {
+ let n = Names::new("3f2a9c1e", "vps");
+ let limits = Limits { cpus: 0.5, memory_mb: 256, pids: 64, timeout_secs: 60 };
+ let a = app_args(&n, &app(), &limits);
+ let pairs: Vec<(String, String)> = a.windows(2).map(|w| (w[0].clone(), w[1].clone())).collect();
+ for (k, v) in [("--cpus", "0.5"), ("--memory", "256m"), ("--memory-swap", "256m"), ("--pids-limit", "64"), ("--network", n.network.as_str()), ("--cap-drop", "ALL")] {
+ assert!(pairs.contains(&(k.into(), v.into())), "{k} {v} in {a:?}");
+ }
+ for args in [a, network_args(&n), probe_args(&n, &app()), load_args(&n, &app(), &LoadSpec::default())] {
+ assert!(!args.iter().any(|x| x == "-p" || x.starts_with("--publish") || x == "-P" || x == "--network=host" || x == "host" || x == "--privileged"), "{args:?}");
+ assert!(!args.iter().any(|x| x.contains("8799") || x.contains("8800")), "{args:?}");
+ }
+ assert!(network_args(&n).contains(&"--internal".to_string()));
+ }
+
+ #[test]
+ fn builds_are_offline_and_labelled() {
+ let n = Names::new("3f2a9c1e", "vps");
+ let spec = AppSpec { image: None, context: Some("/tmp/ctx".into()), dockerfile: Some("deploy/Dockerfile".into()), port: 80, health_path: "/".into() };
+ let b = build_args(&n, &spec).unwrap();
+ assert_eq!(&b[..3], ["build", "--network", "none"]);
+ assert!(b.contains(&"/tmp/ctx/deploy/Dockerfile".to_string()) && b.contains(&n.label));
+ assert!(build_args(&n, &app()).is_none());
+ assert_eq!(app_args(&n, &spec, &Limits::default()).last().unwrap(), &n.image);
+ }
+
+ #[test]
+ fn oha_json_and_docker_stats_are_read() {
+ let raw = r#"{"summary":{"successRate":1.0},"metrics":{"success_rate":1.0,"requests_per_sec":1045.1,
+ "latency_ms":{"min":2.0,"mean":4.4,"p50":4.28,"p95":6.698,"p99":9.78,"max":9.78}},
+ "statusCodeDistribution":{"200":45,"404":5}}"#;
+ let o = parse_oha(raw).unwrap();
+ assert_eq!((o.p95_ms, o.responses, o.ok_responses), (6.698, 50, 45));
+ assert!(parse_oha("Error: connection refused").is_none());
+ assert_eq!(parse_mem_mb("12.5MiB / 512MiB"), Some(12.5));
+ assert_eq!(parse_mem_mb("1.5GiB / 2GiB"), Some(1536.0));
+ assert_eq!(parse_mem_mb("800KiB / 64MiB"), Some(0.8));
+ assert_eq!(parse_mem_mb("--"), None);
+ }
+
+ #[test]
+ fn a_bad_spec_is_refused_before_docker_is_touched() {
+ let mut spec = BranchSpec { run_id: "short".into(), branch: "vps".into(), app: app(), limits: Limits::default(), load: LoadSpec::default() };
+ assert!(matches!(spec.validate(), Err(HarnessError::Invalid(_))));
+ spec.run_id = "3f2a9c1e-aaaa".into();
+ spec.branch = "VPS; rm -rf /".into();
+ assert!(matches!(spec.validate(), Err(HarnessError::Invalid(_))));
+ spec.branch = "vps".into();
+ spec.app.image = Some("--privileged".into());
+ assert!(matches!(spec.validate(), Err(HarnessError::Invalid(_))));
+ spec.app.image = Some("kwnt-executor:v1".into());
+ spec.limits.memory_mb = 8192;
+ assert!(matches!(spec.validate(), Err(HarnessError::Invalid(_))));
+ spec.limits.memory_mb = 256;
+ assert_eq!(spec.validate(), Ok(()));
+ }
+}
diff --git a/src/parallel/mod.rs b/src/parallel/mod.rs
new file mode 100644
index 00000000..4aad7f01
--- /dev/null
+++ b/src/parallel/mod.rs
@@ -0,0 +1,328 @@
+//! Parallel Universe: compares up to three ways to deploy one app ("current host vs a VPS vs
+//! serverless") without spending anything. Each option is tried in a throwaway container on this
+//! machine ([`harness`]); costs come from a dated price table checked into the repo ([`prices`]).
+//!
+//! Every number is a [`Figure`] tagged [`Tag::Verified`] (measured here, with the command and its
+//! raw output), [`Tag::Estimate`] (computed from a priced plan, with the source and its date) or
+//! [`Tag::Speculation`] (neither). No cloud account is used and the server never fetches prices.
+//!
+//! See docs/parallel-universe.md.
+
+pub mod harness;
+pub mod prices;
+
+use chrono::{DateTime, NaiveDate, Utc};
+use serde::{Deserialize, Serialize};
+
+/// Most options one scenario compares (the server has 4 GB of RAM).
+pub const MAX_OPTIONS: usize = 3;
+/// What all options of a scenario may reserve together.
+pub const MAX_TOTAL_MEMORY_MB: u32 = 3072;
+/// Longest raw output kept on a verified figure.
+pub const MAX_RAW_OUTPUT: usize = 64 * 1024;
+
+/// What a scenario asks and how it is judged.
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct Scenario {
+ #[serde(default)]
+ pub id: String,
+ pub title: String,
+ #[serde(default)]
+ pub question: String,
+ #[serde(default)]
+ pub requirements: Requirements,
+ pub traffic: Traffic,
+ #[serde(default)]
+ pub load: LoadSpec,
+ #[serde(default)]
+ pub criteria: Vec<Criterion>,
+ pub options: Vec<DeployOption>,
+ #[serde(default = "Utc::now")]
+ pub created_at: DateTime<Utc>,
+ #[serde(default = "Utc::now")]
+ pub updated_at: DateTime<Utc>,
+}
+
+#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
+pub struct Requirements {
+ #[serde(default)]
+ pub notes: String,
+ #[serde(default)]
+ pub min_memory_mb: Option<u32>,
+ #[serde(default)]
+ pub needs_persistent_disk: bool,
+ #[serde(default)]
+ pub regions: Vec<String>,
+}
+
+/// The traffic the estimates assume.
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct Traffic {
+ pub monthly_requests: u64,
+ #[serde(default)]
+ pub peak_rps: f64,
+ /// Average response size, for egress.
+ #[serde(default)]
+ pub avg_response_kb: f64,
+ /// Average time one request runs, for per-second (function) pricing.
+ #[serde(default)]
+ pub avg_duration_ms: f64,
+}
+
+/// The load test the harness runs against each option.
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct LoadSpec {
+ pub requests: u32,
+ pub concurrency: u32,
+ pub path: String,
+}
+
+impl Default for LoadSpec {
+ fn default() -> Self {
+ Self { requests: 2000, concurrency: 10, path: "/".into() }
+ }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum CriterionKey {
+ Cost,
+ P95Latency,
+ OpsBurden,
+ Rollback,
+}
+
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct Criterion {
+ pub key: CriterionKey,
+ pub weight: u8,
+}
+
+/// One way to deploy the app.
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct DeployOption {
+ /// Unique within the scenario: a lowercase slug, used in container names.
+ pub key: String,
+ pub label: String,
+ /// A price-table id; none means the cost is speculation.
+ #[serde(default)]
+ pub plan: Option<String>,
+ pub app: AppSpec,
+ #[serde(default)]
+ pub limits: Limits,
+ #[serde(default)]
+ pub ops_notes: String,
+ #[serde(default)]
+ pub rollback_notes: String,
+}
+
+/// What runs in the container: an image already on this machine, or a directory to build.
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct AppSpec {
+ #[serde(default)]
+ pub image: Option<String>,
+ /// Absolute directory with a Dockerfile, built offline.
+ #[serde(default)]
+ pub context: Option<String>,
+ /// Relative to `context`.
+ #[serde(default)]
+ pub dockerfile: Option<String>,
+ /// The port the app listens on inside its container (never published on the host).
+ pub port: u16,
+ #[serde(default = "root_path")]
+ pub health_path: String,
+}
+
+fn root_path() -> String {
+ "/".into()
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
+pub struct Limits {
+ pub cpus: f64,
+ pub memory_mb: u32,
+ pub pids: u32,
+ pub timeout_secs: u64,
+}
+
+impl Default for Limits {
+ fn default() -> Self {
+ Self { cpus: 1.0, memory_mb: 512, pids: 128, timeout_secs: 300 }
+ }
+}
+
+impl Limits {
+ pub fn validate(&self) -> Result<(), String> {
+ if !(0.1..=2.0).contains(&self.cpus) {
+ return Err("cpus must be between 0.1 and 2".into());
+ }
+ if !(64..=2048).contains(&self.memory_mb) {
+ return Err("memory_mb must be between 64 and 2048".into());
+ }
+ if !(16..=512).contains(&self.pids) {
+ return Err("pids must be between 16 and 512".into());
+ }
+ if !(30..=900).contains(&self.timeout_secs) {
+ return Err("timeout_secs must be between 30 and 900".into());
+ }
+ Ok(())
+ }
+}
+
+/// A slug for container names: `a-z`, `0-9`, `-`, starting with a letter or digit.
+pub fn is_slug(s: &str, max: usize) -> bool {
+ !s.is_empty()
+ && s.len() <= max
+ && s.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')
+ && !s.starts_with('-')
+}
+
+/// An image reference docker accepts and that cannot be read as a flag.
+pub fn is_image_ref(s: &str) -> bool {
+ !s.is_empty()
+ && s.len() <= 256
+ && !s.starts_with('-')
+ && s.chars().all(|c| c.is_ascii_alphanumeric() || "./:_@-".contains(c))
+}
+
+fn is_url_path(s: &str) -> bool {
+ s.starts_with('/') && s.len() <= 512 && s.chars().all(|c| c.is_ascii_graphic())
+}
+
+impl AppSpec {
+ pub fn validate(&self) -> Result<(), String> {
+ match (&self.image, &self.context) {
+ (Some(image), None) => {
+ if !is_image_ref(image) {
+ return Err("image must be a docker image name like name:tag".into());
+ }
+ if self.dockerfile.is_some() {
+ return Err("dockerfile goes with context, not image".into());
+ }
+ }
+ (None, Some(context)) => {
+ let p = std::path::Path::new(context);
+ if !p.is_absolute() || context.len() > 1024 || p.components().any(|c| matches!(c, std::path::Component::ParentDir)) {
+ return Err("context must be an absolute directory without ..".into());
+ }
+ if let Some(f) = &self.dockerfile {
+ let fp = std::path::Path::new(f);
+ if f.is_empty() || fp.is_absolute() || fp.components().any(|c| !matches!(c, std::path::Component::Normal(_))) {
+ return Err("dockerfile must be a path inside context".into());
+ }
+ }
+ }
+ _ => return Err("an option needs exactly one of image or context".into()),
+ }
+ if self.port == 0 {
+ return Err("port must be 1–65535".into());
+ }
+ if !is_url_path(&self.health_path) {
+ return Err("health_path must start with /".into());
+ }
+ Ok(())
+ }
+}
+
+impl Scenario {
+ /// Checks every field the person sent; `Err` is a sentence for them.
+ pub fn validate(&self) -> Result<(), String> {
+ let title = self.title.trim();
+ if title.is_empty() || title.chars().count() > 120 {
+ return Err("title must be 1–120 characters".into());
+ }
+ if self.question.chars().count() > 2000 || self.requirements.notes.chars().count() > 4000 {
+ return Err("question or notes are too long".into());
+ }
+ if self.requirements.regions.len() > 10 || self.requirements.regions.iter().any(|r| r.chars().count() > 40) {
+ return Err("at most 10 regions, 40 characters each".into());
+ }
+ let t = &self.traffic;
+ if t.monthly_requests > 100_000_000_000 {
+ return Err("monthly_requests is too large".into());
+ }
+ for (name, v) in [("peak_rps", t.peak_rps), ("avg_response_kb", t.avg_response_kb), ("avg_duration_ms", t.avg_duration_ms)] {
+ if !v.is_finite() || !(0.0..=1e7).contains(&v) {
+ return Err(format!("{name} must be a number from 0"));
+ }
+ }
+ if !(1..=100_000).contains(&self.load.requests) || !(1..=64).contains(&self.load.concurrency) {
+ return Err("load: requests 1–100000, concurrency 1–64".into());
+ }
+ if !is_url_path(&self.load.path) {
+ return Err("load path must start with /".into());
+ }
+ let mut seen = Vec::new();
+ for c in &self.criteria {
+ if c.weight > 10 {
+ return Err("criterion weights are 0–10".into());
+ }
+ if seen.contains(&c.key) {
+ return Err("each criterion at most once".into());
+ }
+ seen.push(c.key);
+ }
+ if self.options.is_empty() || self.options.len() > MAX_OPTIONS {
+ return Err(format!("a scenario has 1–{MAX_OPTIONS} options"));
+ }
+ let mut keys = Vec::new();
+ let mut memory = 0;
+ for o in &self.options {
+ if !is_slug(&o.key, 32) {
+ return Err("option keys are lowercase letters, digits and -, at most 32".into());
+ }
+ if keys.contains(&o.key.as_str()) {
+ return Err("option keys must be unique".into());
+ }
+ keys.push(o.key.as_str());
+ let label = o.label.trim();
+ if label.is_empty() || label.chars().count() > 80 {
+ return Err("option labels are 1–80 characters".into());
+ }
+ if o.ops_notes.chars().count() > 2000 || o.rollback_notes.chars().count() > 2000 {
+ return Err("option notes are too long".into());
+ }
+ if let Some(plan) = &o.plan {
+ if prices::find(plan).is_none() {
+ return Err(format!("no price-table plan called {plan}"));
+ }
+ }
+ o.app.validate().map_err(|e| format!("{}: {e}", o.key))?;
+ o.limits.validate().map_err(|e| format!("{}: {e}", o.key))?;
+ memory += o.limits.memory_mb;
+ }
+ if memory > MAX_TOTAL_MEMORY_MB {
+ return Err(format!("the options may reserve at most {MAX_TOTAL_MEMORY_MB} MB together"));
+ }
+ Ok(())
+ }
+}
+
+/// Where a number comes from.
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+#[serde(tag = "tag", rename_all = "snake_case")]
+pub enum Tag {
+ /// Measured on this machine: the exact command and what it printed.
+ Verified { command: String, raw_output: String, measured_at: DateTime<Utc> },
+ /// Computed from a priced plan.
+ Estimate { source_url: String, as_of: NaiveDate, stale: bool, assumptions: Vec<String> },
+ /// Neither measured nor sourced.
+ Speculation { note: String },
+}
+
+/// One number in a comparison.
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct Figure {
+ pub metric: String,
+ pub value: f64,
+ pub unit: String,
+ #[serde(flatten)]
+ pub tag: Tag,
+}
+
+impl Figure {
+ pub fn verified(metric: &str, value: f64, unit: &str, command: &str, raw_output: &str, at: DateTime<Utc>) -> Self {
+ let raw = crate::zombie::clip(raw_output, MAX_RAW_OUTPUT);
+ Figure { metric: metric.into(), value, unit: unit.into(), tag: Tag::Verified { command: command.into(), raw_output: raw, measured_at: at } }
+ }
+}
diff --git a/src/parallel/prices.json b/src/parallel/prices.json
new file mode 100644
index 00000000..cbfc7c0f
--- /dev/null
+++ b/src/parallel/prices.json
@@ -0,0 +1,108 @@
+{
+ "_note": "Read by hand from each provider's public page on as_of. Edit in a commit with a new as_of; the server never fetches prices.",
+ "prices": [
+ {
+ "id": "hetzner-cpx02",
+ "provider": "Hetzner",
+ "plan": "CPX02 (Regular Performance)",
+ "kind": "vm",
+ "currency": "EUR",
+ "monthly": 6.49,
+ "vcpu": 1,
+ "memory_mb": 1024,
+ "included_egress_gb": 20480,
+ "source_url": "https://www.hetzner.com/cloud/regular-performance/",
+ "as_of": "2026-10-20",
+ "notes": "EU-Central (FSN1, NBG1, HEL1), excl. VAT, 20 GB NVMe. The page marked it \"currently unavailable\" that day."
+ },
+ {
+ "id": "hetzner-cpx12",
+ "provider": "Hetzner",
+ "plan": "CPX12 (Regular Performance)",
+ "kind": "vm",
+ "currency": "EUR",
+ "monthly": 11.99,
+ "vcpu": 1,
+ "memory_mb": 2048,
+ "included_egress_gb": 20480,
+ "source_url": "https://www.hetzner.com/cloud/regular-performance/",
+ "as_of": "2026-10-20",
+ "notes": "EU-Central (FSN1, NBG1, HEL1), excl. VAT, 40 GB NVMe. The page marked it \"currently unavailable\" that day."
+ },
+ {
+ "id": "do-basic-1gb",
+ "provider": "DigitalOcean",
+ "plan": "Basic Droplet 1 GiB / 1 vCPU",
+ "kind": "vm",
+ "currency": "USD",
+ "monthly": 6.0,
+ "vcpu": 1,
+ "memory_mb": 1024,
+ "included_egress_gb": 1000,
+ "source_url": "https://www.digitalocean.com/pricing/droplets",
+ "as_of": "2026-10-20",
+ "notes": "Shared CPU, 25 GiB SSD, 1,000 GiB transfer."
+ },
+ {
+ "id": "do-basic-2gb",
+ "provider": "DigitalOcean",
+ "plan": "Basic Droplet 2 GiB / 1 vCPU",
+ "kind": "vm",
+ "currency": "USD",
+ "monthly": 12.0,
+ "vcpu": 1,
+ "memory_mb": 2048,
+ "included_egress_gb": 2000,
+ "source_url": "https://www.digitalocean.com/pricing/droplets",
+ "as_of": "2026-10-20",
+ "notes": "Shared CPU, 50 GiB SSD, 2,000 GiB transfer."
+ },
+ {
+ "id": "fly-shared-1x-512",
+ "provider": "Fly.io",
+ "plan": "shared-cpu-1x, 512 MB",
+ "kind": "container",
+ "currency": "USD",
+ "monthly": 3.69,
+ "vcpu": 1,
+ "memory_mb": 512,
+ "included_egress_gb": 0,
+ "egress_per_gb": 0.02,
+ "source_url": "https://docs.fly.io/about/pricing",
+ "as_of": "2026-10-20",
+ "notes": "iad/ewr, the lowest-priced regions; running all month. Egress $0.02/GB in North America and Europe."
+ },
+ {
+ "id": "fly-shared-1x-1gb",
+ "provider": "Fly.io",
+ "plan": "shared-cpu-1x, 1 GB",
+ "kind": "container",
+ "currency": "USD",
+ "monthly": 6.7,
+ "vcpu": 1,
+ "memory_mb": 1024,
+ "included_egress_gb": 0,
+ "egress_per_gb": 0.02,
+ "source_url": "https://docs.fly.io/about/pricing",
+ "as_of": "2026-10-20",
+ "notes": "iad/ewr, the lowest-priced regions; running all month. Egress $0.02/GB in North America and Europe."
+ },
+ {
+ "id": "aws-lambda-x86-use1",
+ "provider": "AWS",
+ "plan": "Lambda x86, us-east-1",
+ "kind": "function",
+ "currency": "USD",
+ "monthly": 0.0,
+ "per_million_requests": 0.2,
+ "per_gb_second": 0.0000166667,
+ "free_requests": 1000000,
+ "free_gb_seconds": 400000,
+ "vcpu": 0,
+ "memory_mb": 512,
+ "source_url": "https://aws.amazon.com/lambda/pricing/",
+ "as_of": "2026-10-20",
+ "notes": "First compute tier only. memory_mb is the function size assumed. Excludes API Gateway, data transfer and logs."
+ }
+ ]
+}
diff --git a/src/parallel/prices.rs b/src/parallel/prices.rs
new file mode 100644
index 00000000..f70047fe
--- /dev/null
+++ b/src/parallel/prices.rs
@@ -0,0 +1,240 @@
+//! The dated price table (`prices.json`, compiled in) and the monthly cost estimate.
+//!
+//! Prices are read by hand from each provider's public page and committed with the date they
+//! were read. The server never fetches a price. An estimate quotes its source and date and lists
+//! every assumption; currencies are never converted (a rate would need a source of its own).
+
+use super::{Figure, Tag, Traffic};
+use chrono::{NaiveDate, Utc};
+use serde::{Deserialize, Serialize};
+use std::sync::OnceLock;
+
+/// A price older than this is still used, but the estimate says it is stale.
+pub const STALE_AFTER_DAYS: i64 = 180;
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum PlanKind {
+ /// A server billed by the month.
+ Vm,
+ /// A container billed while it runs (here: all month).
+ Container,
+ /// Billed per request and per GB-second.
+ Function,
+}
+
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct PriceEntry {
+ pub id: String,
+ pub provider: String,
+ pub plan: String,
+ pub kind: PlanKind,
+ pub currency: String,
+ /// The flat monthly price (0 for functions).
+ pub monthly: f64,
+ #[serde(default)]
+ pub per_million_requests: Option<f64>,
+ #[serde(default)]
+ pub per_gb_second: Option<f64>,
+ #[serde(default)]
+ pub free_requests: Option<u64>,
+ #[serde(default)]
+ pub free_gb_seconds: Option<f64>,
+ pub vcpu: u32,
+ pub memory_mb: u32,
+ #[serde(default)]
+ pub included_egress_gb: Option<f64>,
+ #[serde(default)]
+ pub egress_per_gb: Option<f64>,
+ pub source_url: String,
+ pub as_of: NaiveDate,
+ pub notes: String,
+}
+
+#[derive(Deserialize)]
+struct Table {
+ prices: Vec<PriceEntry>,
+}
+
+/// Every priced plan.
+pub fn table() -> &'static [PriceEntry] {
+ static TABLE: OnceLock<Vec<PriceEntry>> = OnceLock::new();
+ TABLE.get_or_init(|| {
+ serde_json::from_str::<Table>(include_str!("prices.json")).expect("prices.json is valid (checked by its test)").prices
+ })
+}
+
+pub fn find(id: &str) -> Option<&'static PriceEntry> {
+ table().iter().find(|p| p.id == id)
+}
+
+/// Problems with the table itself: every entry needs an https source, a past date, sane numbers.
+pub fn check_table(entries: &[PriceEntry], today: NaiveDate) -> Vec<String> {
+ let mut problems = Vec::new();
+ let mut ids = Vec::new();
+ for p in entries {
+ if ids.contains(&p.id.as_str()) {
+ problems.push(format!("{}: duplicate id", p.id));
+ }
+ ids.push(p.id.as_str());
+ if !super::is_slug(&p.id, 64) {
+ problems.push(format!("{}: id is not a slug", p.id));
+ }
+ if url::Url::parse(&p.source_url).map(|u| u.scheme() != "https" || u.host_str().is_none()).unwrap_or(true) {
+ problems.push(format!("{}: source_url must be an https address", p.id));
+ }
+ if p.as_of > today {
+ problems.push(format!("{}: as_of is in the future", p.id));
+ }
+ if p.currency.len() != 3 || !p.currency.chars().all(|c| c.is_ascii_uppercase()) {
+ problems.push(format!("{}: currency must be a 3-letter code", p.id));
+ }
+ let numbers = [Some(p.monthly), p.per_million_requests, p.per_gb_second, p.free_gb_seconds, p.included_egress_gb, p.egress_per_gb];
+ if numbers.iter().flatten().any(|v| !v.is_finite() || *v < 0.0) {
+ problems.push(format!("{}: prices must be numbers from 0", p.id));
+ }
+ if p.kind == PlanKind::Function && (p.per_million_requests.is_none() || p.per_gb_second.is_none()) {
+ problems.push(format!("{}: a function plan needs per_million_requests and per_gb_second", p.id));
+ }
+ }
+ problems
+}
+
+/// The monthly cost of running on `p` under `traffic`, as an estimate with its assumptions.
+pub fn estimate_monthly(p: &PriceEntry, traffic: &Traffic, today: NaiveDate) -> Figure {
+ let mut assumptions = vec![format!("{} {} ({}), price read {}", p.provider, p.plan, p.notes, p.as_of)];
+ let egress_gb = traffic.monthly_requests as f64 * traffic.avg_response_kb / (1024.0 * 1024.0);
+ let mut total = p.monthly;
+ match p.kind {
+ PlanKind::Vm | PlanKind::Container => {
+ assumptions.push(format!("one instance running the whole month: {:.2} {}", p.monthly, p.currency));
+ let included = p.included_egress_gb.unwrap_or(0.0);
+ let over = (egress_gb - included).max(0.0);
+ match p.egress_per_gb {
+ Some(rate) => {
+ total += over * rate;
+ assumptions.push(format!(
+ "egress {egress_gb:.1} GB ({} requests × {} KB), {included} GB included, {rate} {}/GB above",
+ traffic.monthly_requests, traffic.avg_response_kb, p.currency
+ ));
+ }
+ None if over > 0.0 => assumptions.push(format!("egress {egress_gb:.1} GB is above the {included} GB included; overage not priced")),
+ None => assumptions.push(format!("egress {egress_gb:.1} GB fits the {included} GB included")),
+ }
+ assumptions.push(format!("{} vCPU / {} MB is enough for the load (not checked here)", p.vcpu, p.memory_mb));
+ }
+ PlanKind::Function => {
+ let rate_req = p.per_million_requests.unwrap_or(0.0);
+ let rate_gbs = p.per_gb_second.unwrap_or(0.0);
+ let billed_req = traffic.monthly_requests.saturating_sub(p.free_requests.unwrap_or(0)) as f64;
+ let gb_seconds = traffic.monthly_requests as f64 * (traffic.avg_duration_ms / 1000.0) * (p.memory_mb as f64 / 1024.0);
+ let billed_gbs = (gb_seconds - p.free_gb_seconds.unwrap_or(0.0)).max(0.0);
+ total += billed_req / 1e6 * rate_req + billed_gbs * rate_gbs;
+ assumptions.push(format!(
+ "{} requests × {} ms at {} MB = {gb_seconds:.0} GB-s; free tier {} requests and {} GB-s taken off",
+ traffic.monthly_requests,
+ traffic.avg_duration_ms,
+ p.memory_mb,
+ p.free_requests.unwrap_or(0),
+ p.free_gb_seconds.unwrap_or(0.0)
+ ));
+ assumptions.push(format!("{rate_req} {} per million requests, {rate_gbs} {} per GB-s", p.currency, p.currency));
+ }
+ }
+ let stale = (today - p.as_of).num_days() > STALE_AFTER_DAYS;
+ if stale {
+ assumptions.push(format!("the price is more than {STALE_AFTER_DAYS} days old"));
+ }
+ Figure {
+ metric: "monthly_cost".into(),
+ value: (total * 100.0).round() / 100.0,
+ unit: p.currency.clone(),
+ tag: Tag::Estimate { source_url: p.source_url.clone(), as_of: p.as_of, stale, assumptions },
+ }
+}
+
+/// The cost figure for an option: an estimate when it names a plan, otherwise speculation.
+pub fn cost_figure(plan: Option<&str>, traffic: &Traffic) -> Figure {
+ match plan.and_then(find) {
+ Some(p) => estimate_monthly(p, traffic, Utc::now().date_naive()),
+ None => Figure {
+ metric: "monthly_cost".into(),
+ value: 0.0,
+ unit: String::new(),
+ tag: Tag::Speculation { note: "no priced plan chosen for this option".into() },
+ },
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn traffic(requests: u64) -> Traffic {
+ Traffic { monthly_requests: requests, peak_rps: 10.0, avg_response_kb: 20.0, avg_duration_ms: 100.0 }
+ }
+
+ #[test]
+ fn the_checked_in_table_is_sound() {
+ let problems = check_table(table(), Utc::now().date_naive());
+ assert!(problems.is_empty(), "{problems:?}");
+ assert!(table().len() >= 5);
+ }
+
+ #[test]
+ fn a_bad_entry_is_refused() {
+ let mut p = find("do-basic-1gb").unwrap().clone();
+ p.source_url = "http://example.com".into();
+ p.as_of = NaiveDate::from_ymd_opt(2999, 1, 1).unwrap();
+ p.monthly = -1.0;
+ let problems = check_table(&[p.clone(), p], NaiveDate::from_ymd_opt(2026, 10, 20).unwrap());
+ for needle in ["duplicate", "https", "future", "from 0"] {
+ assert!(problems.iter().any(|m| m.contains(needle)), "{needle}: {problems:?}");
+ }
+ }
+
+ #[test]
+ fn a_vm_costs_its_monthly_price_while_egress_fits() {
+ let today = NaiveDate::from_ymd_opt(2026, 10, 21).unwrap();
+ let f = estimate_monthly(find("do-basic-1gb").unwrap(), &traffic(1_000_000), today);
+ assert_eq!(f.value, 6.0);
+ assert_eq!(f.unit, "USD");
+ let Tag::Estimate { source_url, stale, assumptions, .. } = &f.tag else { panic!("{f:?}") };
+ assert_eq!(source_url, "https://www.digitalocean.com/pricing/droplets");
+ assert!(!stale);
+ assert!(assumptions.iter().any(|a| a.contains("fits")), "{assumptions:?}");
+ }
+
+ #[test]
+ fn egress_above_the_included_amount_is_priced_where_a_rate_is_known() {
+ let today = NaiveDate::from_ymd_opt(2026, 10, 21).unwrap();
+ // 10 M × 20 KB ≈ 190.7 GB at $0.02 = $3.81, plus $3.69
+ let f = estimate_monthly(find("fly-shared-1x-512").unwrap(), &traffic(10_000_000), today);
+ assert_eq!(f.value, 7.5);
+ }
+
+ #[test]
+ fn a_function_bills_requests_and_gb_seconds_above_the_free_tier() {
+ let today = NaiveDate::from_ymd_opt(2026, 10, 21).unwrap();
+ // 10 M requests: 9 M billed = $1.80; 10 M × 0.1 s × 0.5 GB = 500 000 GB-s, 100 000 billed = $1.67
+ let f = estimate_monthly(find("aws-lambda-x86-use1").unwrap(), &traffic(10_000_000), today);
+ assert_eq!(f.value, 3.47);
+ // inside the free tier it costs nothing
+ assert_eq!(estimate_monthly(find("aws-lambda-x86-use1").unwrap(), &traffic(100_000), today).value, 0.0);
+ }
+
+ #[test]
+ fn an_old_price_is_marked_stale_and_no_plan_is_speculation() {
+ let later = NaiveDate::from_ymd_opt(2027, 6, 1).unwrap();
+ let f = estimate_monthly(find("do-basic-1gb").unwrap(), &traffic(1), later);
+ assert!(matches!(f.tag, Tag::Estimate { stale: true, .. }), "{f:?}");
+ assert!(matches!(cost_figure(None, &traffic(1)).tag, Tag::Speculation { .. }));
+ assert!(matches!(cost_figure(Some("nope"), &traffic(1)).tag, Tag::Speculation { .. }));
+ }
+
+ #[test]
+ fn currencies_are_never_converted() {
+ let f = cost_figure(Some("hetzner-cpx02"), &traffic(1000));
+ assert_eq!((f.value, f.unit.as_str()), (6.49, "EUR"));
+ }
+}
diff --git a/src/server/auth.rs b/src/server/auth.rs
index 9286429e..1fbbd279 100644
--- a/src/server/auth.rs
+++ b/src/server/auth.rs
@@ -183,7 +183,7 @@ fn exempt(path: &str) -> bool {
|| path == "/api/mcp/self"
}
-/// Routes only the person may call: saved passwords and the password vault (Bitwarden), answering an approval card, the
+/// Routes only the person may call: saved passwords and the password vault (Bitwarden), answering an approval card, Loose ends and Parallel Universe, the
/// approvals switch, and deleting a bot or team or undoing a bot action or import (those delete saved passwords too). They need the token from this machine too, because a bot's shell runs on
/// this machine and would otherwise reach them with a bare `curl`. Turn tokens are refused by the
/// handlers themselves (403).
@@ -194,6 +194,8 @@ pub fn person_only(method: &Method, path: &str) -> bool {
["", "api", "passwords", ..] => true,
// Loose ends read the person's mail: bots never see or change them
["", "api", "zombie", ..] => true,
+ // Parallel Universe starts containers on this machine from a directory the person names
+ ["", "api", "parallel", ..] => true,
["", "api", "approvals", _, "resolve"] => *method == Method::POST,
["", "api", "spaces" | "kwants", _, "approvals"] => *method != Method::GET && *method != Method::HEAD,
["", "api", "kwants" | "teams", _] => *method == Method::DELETE,
@@ -492,6 +494,8 @@ mod tests {
assert!(person_only(&post, "/api/passwords/migrate"));
assert!(person_only(&get, "/api/zombie/cases"));
assert!(person_only(&post, "/api/zombie/sources/s1/test"));
+ assert!(person_only(&get, "/api/parallel/prices"));
+ assert!(person_only(&post, "/api/parallel/scenarios"));
assert!(person_only(&post, "/api/approvals/a1/resolve"));
assert!(person_only(&put, "/api/spaces/s1/approvals"));
assert!(person_only(&put, "/api/kwants/k1/approvals"));
diff --git a/src/server/mod.rs b/src/server/mod.rs
index 54a867ff..69994a3c 100644
--- a/src/server/mod.rs
+++ b/src/server/mod.rs
@@ -27,6 +27,7 @@ pub mod import_routes;
pub mod approval_modes;
pub mod passwords;
pub mod zombie_routes;
+pub mod parallel_routes;
use crate::broker::PermissionBroker;
use crate::config::Config;
@@ -222,6 +223,13 @@ pub fn create_router(state: AppState) -> Router {
.route("/api/zombie/status", get(zombie_routes::status))
.route("/api/zombie/settings", get(zombie_routes::get_settings).put(zombie_routes::put_settings))
.route("/api/zombie/reviews", get(zombie_routes::reviews))
+ .route("/api/parallel/scenarios", get(parallel_routes::list).post(parallel_routes::create))
+ .route(
+ "/api/parallel/scenarios/:id",
+ get(parallel_routes::get_one).put(parallel_routes::update).delete(parallel_routes::delete),
+ )
+ .route("/api/parallel/prices", get(parallel_routes::list_prices))
+ .route("/api/parallel/estimate", post(parallel_routes::estimate))
.route("/api/mcp/servers", get(mcp_routes::list_servers).post(mcp_routes::create_server))
.route(
"/api/mcp/servers/:id",
diff --git a/src/server/parallel_routes.rs b/src/server/parallel_routes.rs
new file mode 100644
index 00000000..6fd0ec07
--- /dev/null
+++ b/src/server/parallel_routes.rs
@@ -0,0 +1,120 @@
+//! Parallel Universe API. Person-only (see `auth::person_only`): a scenario points the harness
+//! at a directory and starts containers on this machine, so bots never call it.
+//!
+//! - `GET /api/parallel/scenarios` → `{scenarios: [Scenario]}`.
+//! - `POST /api/parallel/scenarios` Scenario (no id) → 201 Scenario; 400 `{error}` when invalid.
+//! - `GET /api/parallel/scenarios/:id` → Scenario.
+//! - `PUT /api/parallel/scenarios/:id` Scenario → Scenario (keeps id and created_at).
+//! - `DELETE /api/parallel/scenarios/:id` → `{deleted: true}`.
+//! - `GET /api/parallel/prices` → `{prices: [PriceEntry], stale_after_days}`.
+//! - `POST /api/parallel/estimate {plan, traffic}` → `{figures: [Figure]}` (no Docker, no network).
+
+#![allow(clippy::result_large_err)]
+
+use super::AppState;
+use crate::parallel::{prices, Scenario, Traffic};
+use axum::{
+ extract::{rejection::JsonRejection, Path, State},
+ http::{HeaderMap, StatusCode},
+ response::{IntoResponse, Response},
+ Json,
+};
+use chrono::Utc;
+use serde::Deserialize;
+use serde_json::json;
+
+const REFUSAL: &str = "only the person can manage Parallel Universe scenarios";
+
+type Res = Result<Response, Response>;
+
+fn error(status: StatusCode, message: &str) -> Response {
+ (status, Json(json!({"error": message}))).into_response()
+}
+
+fn db_error(e: crate::db::DbError) -> Response {
+ tracing::warn!("parallel api: database error: {e}");
+ error(StatusCode::INTERNAL_SERVER_ERROR, "kwant could not read or save its scenarios")
+}
+
+async fn person(state: &AppState, headers: &HeaderMap) -> Result<(), Response> {
+ super::mcp_suggest::refuse_agent_tokens(state, headers, REFUSAL).await
+}
+
+fn body<T>(b: Result<Json<T>, JsonRejection>) -> Result<T, Response> {
+ b.map(|Json(v)| v).map_err(|e| error(StatusCode::BAD_REQUEST, &format!("invalid scenario: {}", e.body_text())))
+}
+
+pub async fn list(State(state): State<AppState>, headers: HeaderMap) -> Res {
+ person(&state, &headers).await?;
+ let scenarios = state.db.pu_scenarios().await.map_err(db_error)?;
+ Ok(Json(json!({"scenarios": scenarios})).into_response())
+}
+
+pub async fn create(State(state): State<AppState>, headers: HeaderMap, b: Result<Json<Scenario>, JsonRejection>) -> Res {
+ person(&state, &headers).await?;
+ let mut s = body(b)?;
+ s.validate().map_err(|e| error(StatusCode::BAD_REQUEST, &e))?;
+ let now = Utc::now();
+ s.id = uuid::Uuid::new_v4().to_string();
+ s.title = s.title.trim().to_string();
+ s.created_at = now;
+ s.updated_at = now;
+ state.db.pu_put_scenario(&s).await.map_err(db_error)?;
+ Ok((StatusCode::CREATED, Json(s)).into_response())
+}
+
+async fn scenario_or_404(state: &AppState, id: &str) -> Result<Scenario, Response> {
+ state.db.pu_scenario(id).await.map_err(db_error)?.ok_or_else(|| error(StatusCode::NOT_FOUND, "no such scenario"))
+}
+
+pub async fn get_one(State(state): State<AppState>, headers: HeaderMap, Path(id): Path<String>) -> Res {
+ person(&state, &headers).await?;
+ Ok(Json(scenario_or_404(&state, &id).await?).into_response())
+}
+
+pub async fn update(State(state): State<AppState>, headers: HeaderMap, Path(id): Path<String>, b: Result<Json<Scenario>, JsonRejection>) -> Res {
+ person(&state, &headers).await?;
+ let old = scenario_or_404(&state, &id).await?;
+ let mut s = body(b)?;
+ s.validate().map_err(|e| error(StatusCode::BAD_REQUEST, &e))?;
+ s.id = old.id;
+ s.title = s.title.trim().to_string();
+ s.created_at = old.created_at;
+ s.updated_at = Utc::now();
+ state.db.pu_put_scenario(&s).await.map_err(db_error)?;
+ Ok(Json(s).into_response())
+}
+
+pub async fn delete(State(state): State<AppState>, headers: HeaderMap, Path(id): Path<String>) -> Res {
+ person(&state, &headers).await?;
+ if !state.db.pu_delete_scenario(&id).await.map_err(db_error)? {
+ return Err(error(StatusCode::NOT_FOUND, "no such scenario"));
+ }
+ Ok(Json(json!({"deleted": true})).into_response())
+}
+
+pub async fn list_prices(State(state): State<AppState>, headers: HeaderMap) -> Res {
+ person(&state, &headers).await?;
+ Ok(Json(json!({"prices": prices::table(), "stale_after_days": prices::STALE_AFTER_DAYS})).into_response())
+}
+
+#[derive(Deserialize)]
+pub struct EstimateBody {
+ pub plan: Option<String>,
+ pub traffic: Traffic,
+}
+
+pub async fn estimate(State(state): State<AppState>, headers: HeaderMap, b: Result<Json<EstimateBody>, JsonRejection>) -> Res {
+ person(&state, &headers).await?;
+ let b = body(b)?;
+ let t = &b.traffic;
+ if t.monthly_requests > 100_000_000_000 || [t.peak_rps, t.avg_response_kb, t.avg_duration_ms].iter().any(|v| !v.is_finite() || *v < 0.0 || *v > 1e7) {
+ return Err(error(StatusCode::BAD_REQUEST, "traffic numbers must be from 0 and not huge"));
+ }
+ if let Some(p) = &b.plan {
+ if prices::find(p).is_none() {
+ return Err(error(StatusCode::BAD_REQUEST, &format!("no price-table plan called {p}")));
+ }
+ }
+ Ok(Json(json!({"figures": [prices::cost_figure(b.plan.as_deref(), t)]})).into_response())
+}
diff --git a/tests/parallel_test.rs b/tests/parallel_test.rs
new file mode 100644
index 00000000..1eac3018
--- /dev/null
+++ b/tests/parallel_test.rs
@@ -0,0 +1,304 @@
+//! Parallel Universe (`parallel`): the person-only scenario API, validation, the estimate route,
+//! and (ignored without Docker) the container harness against a tiny synthetic app.
+//!
+//! `cargo test --test parallel_test -- --ignored --nocapture` runs the harness tests; they need
+//! Docker, the `kwnt-executor:v1` image and `ghcr.io/hatoo/oha:1.16.0`.
+
+use axum::{
+ body::{to_bytes, Body},
+ http::{Request, StatusCode},
+ Router,
+};
+use kwnt::{
+ broker::PermissionBroker,
+ config::Config,
+ db::{spaces::SpaceId, Database},
+ parallel::{
+ harness::{self, BranchSpec, HarnessError, Names},
+ AppSpec, Limits, LoadSpec, Tag,
+ },
+ router::LayaRouter,
+ server::{continuity::SelfScope, create_router, mcp_runtime, AppState},
+ tools::ToolRunner,
+};
+use serde_json::{json, Value};
+use std::path::Path;
+use tempfile::{tempdir, TempDir};
+use tower::ServiceExt;
+
+struct Env {
+ app: Router,
+ state: AppState,
+ _tmp: TempDir,
+}
+
+async fn setup() -> Env {
+ let tmp = tempdir().unwrap();
+ let data = tmp.path().join("data");
+ let db = Database::init(&data).await.unwrap();
+ let config = Config { data_dir: data.clone(), browser_cdp_url: Some("http://127.0.0.1:9".into()), ..Config::default() };
+ let state = AppState::new(config.clone(), db, ToolRunner::new(data.join("workspace")), PermissionBroker::new(), LayaRouter::new(config.laya_url.clone()));
+ Env { app: create_router(state.clone()), state, _tmp: tmp }
+}
+
+async fn call(app: &Router, method: &str, uri: &str, bearer: Option<&str>, body: Option<Value>) -> (StatusCode, Value) {
+ let mut req = Request::builder().method(method).uri(uri).header("content-type", "application/json");
+ if let Some(t) = bearer {
+ req = req.header("authorization", format!("Bearer {t}"));
+ }
+ let body = body.map(|b| Body::from(b.to_string())).unwrap_or_else(Body::empty);
+ let resp = app.clone().oneshot(req.body(body).unwrap()).await.unwrap();
+ let status = resp.status();
+ let bytes = to_bytes(resp.into_body(), usize::MAX).await.unwrap();
+ (status, serde_json::from_slice(&bytes).unwrap_or(Value::Null))
+}
+
+impl Env {
+ async fn person(&self, method: &str, uri: &str, body: Option<Value>) -> (StatusCode, Value) {
+ call(&self.app, method, uri, Some(self.state.api_token.reveal()), body).await
+ }
+ async fn turn_token(&self, folder: &Path) -> String {
+ let bot = self.state.db.list_kwants(&SpaceId::default_space()).await.unwrap().remove(0);
+ let scope = SelfScope { kwant_id: bot.id.clone(), kwant_name: bot.name.clone(), ..Default::default() };
+ mcp_runtime::prepare_turn_with_self(&self.state, &bot, None, Some(folder.to_path_buf()), Some(scope)).await.unwrap().1
+ }
+}
+
+fn scenario() -> Value {
+ json!({
+ "title": " Move the shop off managed hosting? ",
+ "question": "Should I move my app from managed hosting to my own VPS?",
+ "requirements": {"notes": "Postgres stays where it is", "needs_persistent_disk": false, "regions": ["eu"]},
+ "traffic": {"monthly_requests": 3000000, "peak_rps": 40, "avg_response_kb": 25, "avg_duration_ms": 80},
+ "load": {"requests": 500, "concurrency": 8, "path": "/"},
+ "criteria": [{"key": "cost", "weight": 5}, {"key": "p95_latency", "weight": 3}, {"key": "rollback", "weight": 2}],
+ "options": [
+ {"key": "vps", "label": "Hetzner VPS", "plan": "hetzner-cpx12",
+ "app": {"image": "kwnt-executor:v1", "port": 8080}, "limits": {"cpus": 1.0, "memory_mb": 512, "pids": 128, "timeout_secs": 120}},
+ {"key": "fly", "label": "Fly.io", "plan": "fly-shared-1x-512", "app": {"context": "/tmp/app", "port": 8080}},
+ {"key": "lambda", "label": "Lambda", "plan": "aws-lambda-x86-use1", "app": {"image": "kwnt-executor:v1", "port": 8080}}
+ ]
+ })
+}
+
+#[tokio::test]
+async fn every_route_is_the_persons_only() {
+ let e = setup().await;
+ let folder = tempdir().unwrap();
+ let turn = e.turn_token(folder.path()).await;
+ let routes: Vec<(&str, &str, Option<Value>)> = vec![
+ ("GET", "/api/parallel/scenarios", None),
+ ("POST", "/api/parallel/scenarios", Some(scenario())),
+ ("GET", "/api/parallel/scenarios/x", None),
+ ("PUT", "/api/parallel/scenarios/x", Some(scenario())),
+ ("DELETE", "/api/parallel/scenarios/x", None),
+ ("GET", "/api/parallel/prices", None),
+ ("POST", "/api/parallel/estimate", Some(json!({"plan": "do-basic-1gb", "traffic": {"monthly_requests": 1}}))),
+ ];
+ for (method, uri, body) in &routes {
+ let (s, v) = call(&e.app, method, uri, None, body.clone()).await;
+ assert_eq!(s, StatusCode::UNAUTHORIZED, "{method} {uri} without a token: {v}");
+ let (s, v) = call(&e.app, method, uri, Some(&turn), body.clone()).await;
+ assert_eq!(s, StatusCode::FORBIDDEN, "{method} {uri} with a bot's turn token: {v}");
+ let (s, v) = call(&e.app, method, uri, Some("not-the-token"), body.clone()).await;
+ assert_eq!(s, StatusCode::FORBIDDEN, "{method} {uri} with a wrong token: {v}");
+ }
+ assert!(e.state.db.pu_scenarios().await.unwrap().is_empty(), "nothing was stored by a refused call");
+}
+
+#[tokio::test]
+async fn the_person_keeps_scenarios() {
+ let e = setup().await;
+ let (s, created) = e.person("POST", "/api/parallel/scenarios", Some(scenario())).await;
+ assert_eq!(s, StatusCode::CREATED, "{created}");
+ let id = created["id"].as_str().unwrap().to_string();
+ assert_eq!(created["title"], "Move the shop off managed hosting?");
+ assert_eq!(created["options"][1]["limits"], json!({"cpus": 1.0, "memory_mb": 512, "pids": 128, "timeout_secs": 300}), "defaults filled in");
+ assert_eq!(created["options"][0]["app"]["health_path"], "/");
+
+ let (s, list) = e.person("GET", "/api/parallel/scenarios", None).await;
+ assert_eq!(s, StatusCode::OK);
+ assert_eq!(list["scenarios"].as_array().unwrap().len(), 1);
+ let (_, got) = e.person("GET", &format!("/api/parallel/scenarios/{id}"), None).await;
+ assert_eq!(got, created);
+
+ let mut changed = scenario();
+ changed["title"] = json!("VPS or not");
+ changed["options"].as_array_mut().unwrap().truncate(2);
+ changed["id"] = json!("someone-elses-id");
+ let (s, updated) = e.person("PUT", &format!("/api/parallel/scenarios/{id}"), Some(changed)).await;
+ assert_eq!(s, StatusCode::OK, "{updated}");
+ assert_eq!((updated["id"].as_str(), updated["title"].as_str()), (Some(id.as_str()), Some("VPS or not")));
+ assert_eq!(updated["created_at"], created["created_at"]);
+ assert_eq!(updated["options"].as_array().unwrap().len(), 2);
+
+ let (s, _) = e.person("DELETE", &format!("/api/parallel/scenarios/{id}"), None).await;
+ assert_eq!(s, StatusCode::OK);
+ let (s, _) = e.person("GET", &format!("/api/parallel/scenarios/{id}"), None).await;
+ assert_eq!(s, StatusCode::NOT_FOUND);
+ let (s, _) = e.person("DELETE", &format!("/api/parallel/scenarios/{id}"), None).await;
+ assert_eq!(s, StatusCode::NOT_FOUND);
+}
+
+#[tokio::test]
+async fn bad_scenarios_are_refused_and_not_stored() {
+ let e = setup().await;
+ type Change = Box<dyn Fn(&mut Value)>;
+ let cases: Vec<(&str, Change)> = vec![
+ ("four options", Box::new(|v| { let o = v["options"][0].clone(); let mut o4 = o.clone(); o4["key"] = json!("four"); v["options"].as_array_mut().unwrap().push(o4); })),
+ ("no options", Box::new(|v| v["options"] = json!([]))),
+ ("duplicate key", Box::new(|v| v["options"][1]["key"] = json!("vps"))),
+ ("key not a slug", Box::new(|v| v["options"][0]["key"] = json!("VPS; rm"))),
+ ("unknown plan", Box::new(|v| v["options"][0]["plan"] = json!("aws-ec2-free"))),
+ ("image that is a flag", Box::new(|v| v["options"][0]["app"]["image"] = json!("--privileged"))),
+ ("image and context", Box::new(|v| v["options"][0]["app"]["context"] = json!("/tmp/app"))),
+ ("relative context", Box::new(|v| v["options"][1]["app"]["context"] = json!("app"))),
+ ("context with ..", Box::new(|v| v["options"][1]["app"]["context"] = json!("/tmp/../etc"))),
+ ("dockerfile outside", Box::new(|v| v["options"][1]["app"]["dockerfile"] = json!("../Dockerfile"))),
+ ("port 0", Box::new(|v| v["options"][0]["app"]["port"] = json!(0))),
+ ("too much cpu", Box::new(|v| v["options"][0]["limits"]["cpus"] = json!(8))),
+ ("too much memory", Box::new(|v| v["options"][0]["limits"]["memory_mb"] = json!(4096))),
+ ("too much memory together", Box::new(|v| for o in v["options"].as_array_mut().unwrap() { o["limits"] = json!({"cpus": 1, "memory_mb": 2048, "pids": 128, "timeout_secs": 60}); })),
+ ("timeout too long", Box::new(|v| v["options"][0]["limits"]["timeout_secs"] = json!(3600))),
+ ("load too big", Box::new(|v| v["load"]["concurrency"] = json!(1000))),
+ ("load path", Box::new(|v| v["load"]["path"] = json!("http://prod.example.com/"))),
+ ("criterion twice", Box::new(|v| v["criteria"] = json!([{"key": "cost", "weight": 1}, {"key": "cost", "weight": 2}]))),
+ ("unknown criterion", Box::new(|v| v["criteria"] = json!([{"key": "vibes", "weight": 1}]))),
+ ("empty title", Box::new(|v| v["title"] = json!(" "))),
+ ("negative traffic", Box::new(|v| v["traffic"]["peak_rps"] = json!(-1))),
+ ];
+ for (name, change) in cases {
+ let mut v = scenario();
+ change(&mut v);
+ let (s, body) = e.person("POST", "/api/parallel/scenarios", Some(v)).await;
+ assert_eq!(s, StatusCode::BAD_REQUEST, "{name}: {body}");
+ assert!(body["error"].is_string(), "{name}: {body}");
+ }
+ assert!(e.state.db.pu_scenarios().await.unwrap().is_empty());
+}
+
+#[tokio::test]
+async fn prices_and_estimates_name_their_source() {
+ let e = setup().await;
+ let (s, v) = e.person("GET", "/api/parallel/prices", None).await;
+ assert_eq!(s, StatusCode::OK);
+ let prices = v["prices"].as_array().unwrap();
+ assert!(prices.iter().all(|p| p["source_url"].as_str().unwrap().starts_with("https://") && p["as_of"].is_string()));
+
+ let (s, v) = e.person("POST", "/api/parallel/estimate", Some(json!({"plan": "do-basic-1gb", "traffic": {"monthly_requests": 1000000, "avg_response_kb": 20}}))).await;
+ assert_eq!(s, StatusCode::OK, "{v}");
+ let f = &v["figures"][0];
+ assert_eq!((f["tag"].as_str(), f["value"].as_f64(), f["unit"].as_str()), (Some("estimate"), Some(6.0), Some("USD")));
+ assert_eq!(f["source_url"], "https://www.digitalocean.com/pricing/droplets");
+ assert!(!f["assumptions"].as_array().unwrap().is_empty());
+
+ let (_, v) = e.person("POST", "/api/parallel/estimate", Some(json!({"plan": null, "traffic": {"monthly_requests": 1}}))).await;
+ assert_eq!(v["figures"][0]["tag"], "speculation");
+ let (s, _) = e.person("POST", "/api/parallel/estimate", Some(json!({"plan": "nope", "traffic": {"monthly_requests": 1}}))).await;
+ assert_eq!(s, StatusCode::BAD_REQUEST);
+}
+
+// ---- the harness against real Docker (ignored: needs Docker and two local images) ----
+
+fn docker(args: &[&str]) -> String {
+ let o = std::process::Command::new("docker").args(args).output().unwrap();
+ String::from_utf8_lossy(&o.stdout).trim().to_string()
+}
+
+/// Every object a run could leave behind.
+fn leftovers(run_id: &str) -> String {
+ let filter = format!("label=kwnt.pu.run={run_id}");
+ [docker(&["ps", "-aq", "--filter", &filter]), docker(&["network", "ls", "-q", "--filter", &filter]), docker(&["images", "-q", "--filter", &filter])]
+ .join(" ")
+ .trim()
+ .to_string()
+}
+
+/// A tiny app: Python's file server, built offline from the local executor image.
+fn synthetic_app(dir: &Path, cmd: &str) -> AppSpec {
+ std::fs::write(dir.join("Dockerfile"), format!("FROM kwnt-executor:v1\nWORKDIR /srv\nRUN echo hello > index.html\nCMD {cmd}\n")).unwrap();
+ AppSpec { image: None, context: Some(dir.to_string_lossy().into()), dockerfile: None, port: 8080, health_path: "/".into() }
+}
+
+#[tokio::test]
+#[ignore]
+async fn harness_measures_a_synthetic_app_and_leaves_nothing_behind() {
+ let ctx = tempdir().unwrap();
+ let run_id = format!("pu{}", uuid::Uuid::new_v4().simple());
+ let spec = BranchSpec {
+ run_id: run_id.clone(),
+ branch: "vps".into(),
+ app: synthetic_app(ctx.path(), r#"["python3", "-m", "http.server", "8080"]"#),
+ limits: Limits { cpus: 0.5, memory_mb: 128, pids: 64, timeout_secs: 120 },
+ load: LoadSpec { requests: 300, concurrency: 5, path: "/".into() },
+ };
+ let out = harness::run_branch(&spec).await;
+ let figures = out.result.expect("the branch ran");
+ assert!(out.cleanup_errors.is_empty(), "{:?}", out.cleanup_errors);
+ for f in &figures {
+ println!("{} = {} {}", f.metric, f.value, f.unit);
+ let Tag::Verified { command, raw_output, .. } = &f.tag else { panic!("{f:?}") };
+ assert!(command.starts_with("docker "), "{command}");
+ assert!(!raw_output.is_empty());
+ }
+ let get = |m: &str| figures.iter().find(|f| f.metric == m).map(|f| f.value);
+ assert!(get("p95_latency").unwrap() > 0.0);
+ assert_eq!(get("ok_share"), Some(1.0));
+ assert!(get("memory_after_load").unwrap() > 0.0 && get("memory_after_load").unwrap() <= 128.0);
+ assert_eq!(leftovers(&run_id), "", "containers, network and image are gone");
+}
+
+#[tokio::test]
+#[ignore]
+async fn an_app_that_never_answers_is_cleaned_up_too() {
+ let ctx = tempdir().unwrap();
+ let run_id = format!("pu{}", uuid::Uuid::new_v4().simple());
+ let spec = BranchSpec {
+ run_id: run_id.clone(),
+ branch: "dead".into(),
+ app: synthetic_app(ctx.path(), r#"["sleep", "infinity"]"#),
+ limits: Limits { cpus: 0.25, memory_mb: 64, pids: 16, timeout_secs: 30 },
+ load: LoadSpec::default(),
+ };
+ let out = harness::run_branch(&spec).await;
+ assert!(matches!(out.result, Err(HarnessError::NotReady) | Err(HarnessError::Timeout)), "{:?}", out.result);
+ assert!(out.cleanup_errors.is_empty(), "{:?}", out.cleanup_errors);
+ assert_eq!(leftovers(&run_id), "");
+}
+
+#[tokio::test]
+#[ignore]
+async fn the_internal_network_reaches_neither_the_internet_nor_the_host() {
+ let run_id = format!("pu{}", uuid::Uuid::new_v4().simple());
+ let n = Names::new(&run_id, "probe");
+ let args = harness::network_args(&n);
+ let args: Vec<&str> = args.iter().map(String::as_str).collect();
+ docker(&args);
+ let gateway = docker(&["network", "inspect", "bridge", "-f", "{{(index .IPAM.Config 0).Gateway}}"]);
+ let try_url = |url: &str| {
+ let o = std::process::Command::new("docker")
+ .args(["run", "--rm", "--label", &n.label, "--network", &n.network, "kwnt-executor:v1", "curl", "-s", "-m", "5", "-o", "/dev/null", "-w", "%{http_code}", url])
+ .output()
+ .unwrap();
+ String::from_utf8_lossy(&o.stdout).trim().to_string()
+ };
+ // the branch network's own gateway is the host too
+ let own_gateway = docker(&["network", "inspect", &n.network, "-f", "{{(index .IPAM.Config 0).Gateway}}"]);
+ assert!(!own_gateway.is_empty());
+ let mut urls = vec!["https://example.com/".to_string(), "http://host.docker.internal:8799/".into()];
+ for gw in [&gateway, &own_gateway] {
+ urls.extend([format!("http://{gw}:8799/"), format!("http://{gw}:8800/")]);
+ }
+ for url in &urls {
+ assert_eq!(try_url(url), "000", "{url} must be unreachable from the branch network");
+ }
+ // and there is no default route out at all
+ let routes = std::process::Command::new("docker")
+ .args(["run", "--rm", "--label", &n.label, "--network", &n.network, "kwnt-executor:v1", "cat", "/proc/net/route"])
+ .output()
+ .unwrap();
+ let routes = String::from_utf8_lossy(&routes.stdout);
+ assert!(!routes.lines().skip(1).any(|l| l.split_whitespace().nth(1) == Some("00000000")), "{routes}");
+ assert!(harness::sweep(Some(&run_id)).await.unwrap() >= 1);
+ assert_eq!(leftovers(&run_id), "");
+}