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: runs, run/poll routes, comparison report, startup sweep

Lin (kwant bot)bdfedbd911ac
diff --git a/docs/parallel-universe.md b/docs/parallel-universe.md
index 9b2071b9..57a30269 100644
--- a/docs/parallel-universe.md
+++ b/docs/parallel-universe.md
@@ -3,8 +3,8 @@
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`.
+**Status: slice 2.** This covers the scenario store, the container harness, the price table, runs and the comparison report.
+The multi-bot advisor (a bot per option) is slice 3, if wanted. The full design is in `/home/maus/shared/ship-software-safely/parallel-universe/design.md`.
## Where numbers come from
@@ -30,11 +30,15 @@ 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.
+2. It builds the app with `docker build --network none` (offline), or uses an image already on the machine. A scenario can set
+ `build_network: true` to give **the build step only** the default bridge network (never `host`), for apps that fetch packages
+ while building. The app and load containers stay on the internal network either way, and each branch of a run says
+ `build_network_used`.
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.
+5. It runs the load: oha 1.16.0, pinned by digest (`harness::OHA_IMAGE`; `docker pull` it once), in a second limited container on the
+ same network. Every `docker run` has `--pull never`, so nothing is downloaded during a run.
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
@@ -42,18 +46,47 @@ and AWS Lambda x86 us-east-1.
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.
+## Runs (`parallel::run`, table `pu_runs`)
+
+- One run at a time, server-wide (`Runner`). Starting another while one is going is a 409 `{code: "busy"}`.
+- The options run one after another, so only one branch's containers exist at a time.
+- A run copies the scenario when it starts. Editing or deleting the scenario later doesn't change a past run.
+- A run is `running`, then `finished` (every option was tried; each branch is `ok` or `failed` with an `error_code` from
+ `HarnessError::code`), or `interrupted` if the server stopped. It is saved after every step, so polling shows progress.
+- At the end, the run's label is swept once more. Anything that sweep removes or can't remove goes in `cleanup_errors`.
+- At startup, runs left `running` become `interrupted`, and their label (and that of runs with cleanup errors) is swept.
+ Only runs in this database are swept, so another kwnt on the same Docker keeps its containers.
+
+## Comparison report (`run::report`, in `GET /api/parallel/runs/:id`)
+
+Plain JSON: `{run_id, title, question, status, build_network_used, criteria, options: [{key, label, plan, status, error_code,
+measured: [verified Figure], cost: estimate|speculation Figure, notes: [{criterion: ops_burden|rollback, text, tag:
+"speculation", note}]}], leaders: [{criterion, option, value, unit, basis}], caveats: [string]}`.
+
+- `leaders` ranks only what can be compared: p95 among options that answered every request (verified), and cost among
+ estimates in one currency. Ops and rollback are never ranked.
+- The person's own `ops_notes`/`rollback_notes` are used when set. Otherwise kwant gives a general note for the plan's kind.
+ Either way it's tagged speculation.
+- `caveats` always says the numbers are from this server, not the provider's. It also says when the build had the network,
+ when prices are stale, when currencies differ, and when options failed.
+- The cost is computed when you read the report, so a price goes stale over time.
+
## 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]}`.
+- `POST /api/parallel/scenarios/:id/run` returns 202 `{run}`, or 409 `{error, code: "busy"}`.
+- `GET /api/parallel/runs` and `GET /api/parallel/scenarios/:id/runs` return `{runs, running}` (newest 50).
+- `GET /api/parallel/runs/:id` returns `{run, report}`. Poll it until `run.status` isn't `running`.
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}]}`.
+label, plan?, app: {image | context (+dockerfile), port, health_path}, limits, ops_notes, rollback_notes}], build_network: bool}`.
## 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.
+`cargo test --test parallel_test` covers the API and the run lifecycle with a fake harness, so it needs no Docker. `-- --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, the network reaching neither the internet nor the host, the build network only when
+asked, and a full run through the routes with 0 labelled leftovers.
diff --git a/src/db/parallel.rs b/src/db/parallel.rs
index edd95a41..8f7e1c22 100644
--- a/src/db/parallel.rs
+++ b/src/db/parallel.rs
@@ -1,8 +1,9 @@
-//! 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.
+//! Parallel Universe's scenarios (`pu_scenarios`) and runs (`pu_runs`). The nested parts
+//! (requirements, traffic, load, criteria, options; a run's scenario copy and branches) 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::run::{Run, RunStatus};
use crate::parallel::Scenario;
use chrono::{DateTime, Utc};
use sqlx::FromRow;
@@ -17,6 +18,7 @@ struct ScenarioRow {
load: String,
criteria: String,
options: String,
+ build_network: bool,
created_at: DateTime<Utc>,
updated_at: DateTime<Utc>,
}
@@ -32,13 +34,14 @@ impl ScenarioRow {
load: serde_json::from_str(&self.load)?,
criteria: serde_json::from_str(&self.criteria)?,
options: serde_json::from_str(&self.options)?,
+ build_network: self.build_network,
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";
+const COLUMNS: &str = "id, title, question, requirements, traffic, load, criteria, options, build_network, created_at, updated_at";
impl Database {
pub(super) async fn migrate_parallel(&self) -> Result<(), DbError> {
@@ -58,6 +61,27 @@ impl Database {
)
.execute(&self.pool)
.await?;
+ let has_build_network: Option<(String,)> =
+ sqlx::query_as("SELECT name FROM pragma_table_info('pu_scenarios') WHERE name = 'build_network'").fetch_optional(&self.pool).await?;
+ if has_build_network.is_none() {
+ sqlx::query("ALTER TABLE pu_scenarios ADD COLUMN build_network BOOLEAN NOT NULL DEFAULT 0").execute(&self.pool).await?;
+ }
+ sqlx::query(
+ "CREATE TABLE IF NOT EXISTS pu_runs (
+ id TEXT PRIMARY KEY,
+ scenario_id TEXT NOT NULL,
+ status TEXT NOT NULL,
+ scenario TEXT NOT NULL,
+ branches TEXT NOT NULL DEFAULT '[]',
+ cleanup_errors TEXT NOT NULL DEFAULT '[]',
+ started_at TIMESTAMP NOT NULL,
+ finished_at TIMESTAMP,
+ swept_at TIMESTAMP
+ )",
+ )
+ .execute(&self.pool)
+ .await?;
+ sqlx::query("CREATE INDEX IF NOT EXISTS pu_runs_scenario ON pu_runs (scenario_id, started_at)").execute(&self.pool).await?;
Ok(())
}
@@ -80,11 +104,11 @@ impl Database {
/// 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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
+ "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"
+ options = excluded.options, build_network = excluded.build_network, updated_at = excluded.updated_at"
))
.bind(&s.id)
.bind(&s.title)
@@ -94,6 +118,7 @@ impl Database {
.bind(serde_json::to_string(&s.load)?)
.bind(serde_json::to_string(&s.criteria)?)
.bind(serde_json::to_string(&s.options)?)
+ .bind(s.build_network)
.bind(s.created_at)
.bind(s.updated_at)
.execute(&self.pool)
@@ -106,3 +131,89 @@ impl Database {
Ok(sqlx::query("DELETE FROM pu_scenarios WHERE id = ?").bind(id).execute(&self.pool).await?.rows_affected() > 0)
}
}
+
+#[derive(FromRow)]
+struct RunRow {
+ id: String,
+ scenario_id: String,
+ status: String,
+ scenario: String,
+ branches: String,
+ cleanup_errors: String,
+ started_at: DateTime<Utc>,
+ finished_at: Option<DateTime<Utc>>,
+ swept_at: Option<DateTime<Utc>>,
+}
+
+impl RunRow {
+ fn into_run(self) -> Result<Run, DbError> {
+ Ok(Run {
+ id: self.id,
+ scenario_id: self.scenario_id,
+ status: serde_json::from_value(serde_json::Value::String(self.status))?,
+ scenario: serde_json::from_str(&self.scenario)?,
+ branches: serde_json::from_str(&self.branches)?,
+ cleanup_errors: serde_json::from_str(&self.cleanup_errors)?,
+ started_at: self.started_at,
+ finished_at: self.finished_at,
+ swept_at: self.swept_at,
+ })
+ }
+}
+
+const RUN_COLUMNS: &str = "id, scenario_id, status, scenario, branches, cleanup_errors, started_at, finished_at, swept_at";
+
+impl Database {
+ /// Inserts `r`, or replaces everything but `started_at` of the run with its id.
+ pub async fn pu_put_run(&self, r: &Run) -> Result<(), DbError> {
+ sqlx::query(&format!(
+ "INSERT INTO pu_runs ({RUN_COLUMNS}) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
+ ON CONFLICT(id) DO UPDATE SET
+ status = excluded.status, branches = excluded.branches, cleanup_errors = excluded.cleanup_errors,
+ finished_at = excluded.finished_at, swept_at = excluded.swept_at"
+ ))
+ .bind(&r.id)
+ .bind(&r.scenario_id)
+ .bind(r.status.as_str())
+ .bind(serde_json::to_string(&r.scenario)?)
+ .bind(serde_json::to_string(&r.branches)?)
+ .bind(serde_json::to_string(&r.cleanup_errors)?)
+ .bind(r.started_at)
+ .bind(r.finished_at)
+ .bind(r.swept_at)
+ .execute(&self.pool)
+ .await?;
+ Ok(())
+ }
+
+ pub async fn pu_run(&self, id: &str) -> Result<Option<Run>, DbError> {
+ let row: Option<RunRow> =
+ sqlx::query_as(&format!("SELECT {RUN_COLUMNS} FROM pu_runs WHERE id = ?")).bind(id).fetch_optional(&self.pool).await?;
+ row.map(RunRow::into_run).transpose()
+ }
+
+ /// Newest first; one scenario's runs, or every run.
+ pub async fn pu_runs(&self, scenario_id: Option<&str>, limit: u32) -> Result<Vec<Run>, DbError> {
+ let rows: Vec<RunRow> = match scenario_id {
+ Some(id) => sqlx::query_as(&format!("SELECT {RUN_COLUMNS} FROM pu_runs WHERE scenario_id = ? ORDER BY started_at DESC LIMIT ?"))
+ .bind(id)
+ .bind(limit)
+ .fetch_all(&self.pool)
+ .await?,
+ None => sqlx::query_as(&format!("SELECT {RUN_COLUMNS} FROM pu_runs ORDER BY started_at DESC LIMIT ?")).bind(limit).fetch_all(&self.pool).await?,
+ };
+ rows.into_iter().map(RunRow::into_run).collect()
+ }
+
+ /// Runs a previous process left behind: still `running`, or finished with cleanup errors and
+ /// not swept since.
+ pub async fn pu_runs_to_sweep(&self) -> Result<Vec<Run>, DbError> {
+ let rows: Vec<RunRow> = sqlx::query_as(&format!(
+ "SELECT {RUN_COLUMNS} FROM pu_runs WHERE status = ? OR (cleanup_errors != '[]' AND swept_at IS NULL) ORDER BY started_at LIMIT 500"
+ ))
+ .bind(RunStatus::Running.as_str())
+ .fetch_all(&self.pool)
+ .await?;
+ rows.into_iter().map(RunRow::into_run).collect()
+ }
+}
diff --git a/src/main.rs b/src/main.rs
index 0d63ae18..cfb9483a 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -154,6 +154,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
kwnt::server::passwords::warn_if_exposed(&state).await;
kwnt::server::scheduler::spawn_background(state.clone(), shutdown.clone());
kwnt::server::engine_routes::spawn_startup_check(state.clone());
+ kwnt::server::parallel_routes::spawn_startup_sweep(state.clone());
let app = create_router(state);
let addr = format!("{}:{}", config.host, config.port);
diff --git a/src/parallel/harness.rs b/src/parallel/harness.rs
index e382837f..02113b97 100644
--- a/src/parallel/harness.rs
+++ b/src/parallel/harness.rs
@@ -15,8 +15,9 @@ 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";
+/// The load tool, run as a container next to the app: oha 1.16.0, pinned by digest so a re-tagged
+/// image is never used (`docker pull` it once).
+pub const OHA_IMAGE: &str = "ghcr.io/hatoo/oha@sha256:3ec3dbf549ea197793482d47a6324797411406bbf438c2fe8b91f244ec641a2f";
pub const RUN_LABEL: &str = "kwnt.pu.run";
#[derive(Debug, Error, PartialEq)]
@@ -39,6 +40,22 @@ pub enum HarnessError {
Timeout,
}
+impl HarnessError {
+ /// A stable code the UI can switch on.
+ pub fn code(&self) -> &'static str {
+ match self {
+ HarnessError::DockerUnavailable => "docker_unavailable",
+ HarnessError::LoadToolMissing => "load_tool_missing",
+ HarnessError::Invalid(_) => "invalid",
+ HarnessError::Build(_) => "build_failed",
+ HarnessError::Start(_) => "start_failed",
+ HarnessError::NotReady => "not_ready",
+ HarnessError::Load(_) => "load_failed",
+ HarnessError::Timeout => "timeout",
+ }
+ }
+}
+
/// What to run for one option.
#[derive(Debug, Clone)]
pub struct BranchSpec {
@@ -47,6 +64,8 @@ pub struct BranchSpec {
pub app: AppSpec,
pub limits: Limits,
pub load: LoadSpec,
+ /// Lets `docker build` use the default bridge network. Never applies to the app or load containers.
+ pub build_network: bool,
}
/// What one branch produced. `cleanup_errors` is empty when everything it made is gone.
@@ -90,19 +109,21 @@ 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>> {
+/// An offline build (the Dockerfile cannot download anything), unless the scenario allows the
+/// build step the default bridge network. Never the host network.
+pub fn build_args(n: &Names, app: &AppSpec, build_network: bool) -> 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]))
+ let network = if build_network { "default" } else { "none" };
+ Some(s(&["build", "--network", network, "--label", &n.label, "-t", &n.image, "-f", &dockerfile.to_string_lossy(), context]))
}
-/// The app container: limited, on the internal network only, no published port.
+/// The app container: limited, on the internal network only, no published port, never pulled.
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,
+ "run", "-d", "--pull", "never", "--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",
@@ -118,14 +139,14 @@ fn target(n: &Names, app: &AppSpec, path: &str) -> String {
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",
+ "run", "--rm", "--pull", "never", "--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",
+ "run", "--rm", "--pull", "never", "--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),
])
@@ -254,7 +275,7 @@ async fn steps(spec: &BranchSpec, n: &Names, ready_by: Instant) -> Result<Vec<Fi
if !o.ok {
return Err(HarnessError::Start(o.stderr));
}
- if let Some(args) = build_args(n, &spec.app) {
+ if let Some(args) = build_args(n, &spec.app, spec.build_network) {
let o = docker(&args, step).await.map_err(HarnessError::Build)?;
if !o.ok {
return Err(HarnessError::Build(o.stderr));
@@ -390,16 +411,23 @@ mod tests {
assert!(!args.iter().any(|x| x.contains("8799") || x.contains("8800")), "{args:?}");
}
assert!(network_args(&n).contains(&"--internal".to_string()));
+ for args in [app_args(&n, &app(), &limits), probe_args(&n, &app()), load_args(&n, &app(), &LoadSpec::default())] {
+ assert!(args.windows(2).any(|w| w[0] == "--pull" && w[1] == "never"), "nothing is pulled: {args:?}");
+ }
}
#[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();
+ let b = build_args(&n, &spec, false).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!(build_args(&n, &app(), false).is_none());
+ // the opt-in build network is the default bridge, never the host's
+ let b = build_args(&n, &spec, true).unwrap();
+ assert_eq!(&b[..3], ["build", "--network", "default"]);
+ assert!(!b.iter().any(|x| x == "host"));
assert_eq!(app_args(&n, &spec, &Limits::default()).last().unwrap(), &n.image);
}
@@ -419,7 +447,7 @@ mod tests {
#[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() };
+ let mut spec = BranchSpec { run_id: "short".into(), branch: "vps".into(), app: app(), limits: Limits::default(), load: LoadSpec::default(), build_network: false };
assert!(matches!(spec.validate(), Err(HarnessError::Invalid(_))));
spec.run_id = "3f2a9c1e-aaaa".into();
spec.branch = "VPS; rm -rf /".into();
diff --git a/src/parallel/mod.rs b/src/parallel/mod.rs
index 4aad7f01..1540d052 100644
--- a/src/parallel/mod.rs
+++ b/src/parallel/mod.rs
@@ -10,6 +10,7 @@
pub mod harness;
pub mod prices;
+pub mod run;
use chrono::{DateTime, NaiveDate, Utc};
use serde::{Deserialize, Serialize};
@@ -37,6 +38,10 @@ pub struct Scenario {
#[serde(default)]
pub criteria: Vec<Criterion>,
pub options: Vec<DeployOption>,
+ /// Lets `docker build` (only) use the network, for apps that fetch packages while building.
+ /// The app and the load test always stay on the internal network. Off unless the person turns it on.
+ #[serde(default)]
+ pub build_network: bool,
#[serde(default = "Utc::now")]
pub created_at: DateTime<Utc>,
#[serde(default = "Utc::now")]
diff --git a/src/parallel/run.rs b/src/parallel/run.rs
new file mode 100644
index 00000000..323c0c00
--- /dev/null
+++ b/src/parallel/run.rs
@@ -0,0 +1,561 @@
+//! Runs a scenario: every option through the container harness, one after another, kept in
+//! `pu_runs` as it goes, then compared ([`report`]).
+//!
+//! One run at a time server-wide ([`Runner`]). Options run sequentially, so at most one branch's
+//! containers exist at once; the scenario's 3072 MB cap still holds if that ever changes. A run
+//! copies its scenario when it starts, so editing or deleting the scenario later never changes
+//! what a past run measured.
+//!
+//! When the server stops mid-run, the containers may outlive it. [`startup`] marks such runs
+//! `interrupted` and sweeps their label; it only sweeps runs this database knows, so another kwnt
+//! on the same Docker keeps its own containers.
+
+use super::harness::{self, BranchOutcome, BranchSpec};
+use super::prices::{self, PlanKind};
+use super::{CriterionKey, Figure, Scenario, Tag};
+use crate::db::{Database, DbError};
+use chrono::{DateTime, Utc};
+use serde::{Deserialize, Serialize};
+use std::future::Future;
+use std::pin::Pin;
+use std::sync::Arc;
+use tokio::sync::{Mutex, OwnedMutexGuard};
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum RunStatus {
+ Running,
+ /// Every option was tried (some may have failed).
+ Finished,
+ /// The server stopped before the run finished.
+ Interrupted,
+}
+
+impl RunStatus {
+ pub fn as_str(self) -> &'static str {
+ match self {
+ RunStatus::Running => "running",
+ RunStatus::Finished => "finished",
+ RunStatus::Interrupted => "interrupted",
+ }
+ }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum BranchStatus {
+ Pending,
+ Running,
+ Ok,
+ Failed,
+}
+
+/// One option's part of a run.
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct Branch {
+ pub key: String,
+ pub label: String,
+ pub status: BranchStatus,
+ /// `HarnessError::code`, for the UI.
+ #[serde(default)]
+ pub error_code: Option<String>,
+ #[serde(default)]
+ pub error: Option<String>,
+ /// All `verified`.
+ #[serde(default)]
+ pub figures: Vec<Figure>,
+ /// What the harness could not remove (empty when everything is gone).
+ #[serde(default)]
+ pub cleanup_errors: Vec<String>,
+ /// Whether `docker build` had the network for this option (only ever the build step).
+ #[serde(default)]
+ pub build_network_used: bool,
+ #[serde(default)]
+ pub started_at: Option<DateTime<Utc>>,
+ #[serde(default)]
+ pub finished_at: Option<DateTime<Utc>>,
+}
+
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct Run {
+ pub id: String,
+ pub scenario_id: String,
+ pub status: RunStatus,
+ /// The scenario as it was when the run started.
+ pub scenario: Scenario,
+ pub branches: Vec<Branch>,
+ /// Problems from the final label sweep.
+ pub cleanup_errors: Vec<String>,
+ pub started_at: DateTime<Utc>,
+ pub finished_at: Option<DateTime<Utc>>,
+ /// When a later start removed what this run left behind.
+ pub swept_at: Option<DateTime<Utc>>,
+}
+
+impl Run {
+ pub fn new(scenario: &Scenario) -> Self {
+ Run {
+ id: uuid::Uuid::new_v4().to_string(),
+ scenario_id: scenario.id.clone(),
+ status: RunStatus::Running,
+ scenario: scenario.clone(),
+ branches: scenario
+ .options
+ .iter()
+ .map(|o| Branch {
+ key: o.key.clone(),
+ label: o.label.clone(),
+ status: BranchStatus::Pending,
+ error_code: None,
+ error: None,
+ figures: Vec::new(),
+ cleanup_errors: Vec::new(),
+ build_network_used: false,
+ started_at: None,
+ finished_at: None,
+ })
+ .collect(),
+ cleanup_errors: Vec::new(),
+ started_at: Utc::now(),
+ finished_at: None,
+ swept_at: None,
+ }
+ }
+
+ /// Whether any option's build had the network.
+ pub fn build_network_used(&self) -> bool {
+ self.branches.iter().any(|b| b.build_network_used)
+ }
+}
+
+pub type BoxFut<T> = Pin<Box<dyn Future<Output = T> + Send>>;
+
+/// What runs a branch and sweeps a run's label: Docker in the server, a fake in tests.
+pub trait Harness: Send + Sync {
+ fn run_branch(&self, spec: BranchSpec) -> BoxFut<BranchOutcome>;
+ fn sweep(&self, run_id: String) -> BoxFut<Result<usize, String>>;
+}
+
+pub struct DockerHarness;
+
+impl Harness for DockerHarness {
+ fn run_branch(&self, spec: BranchSpec) -> BoxFut<BranchOutcome> {
+ Box::pin(async move { harness::run_branch(&spec).await })
+ }
+ fn sweep(&self, run_id: String) -> BoxFut<Result<usize, String>> {
+ Box::pin(async move {
+ if !harness::docker_available().await {
+ return Err("Docker is not available on this machine".into());
+ }
+ harness::sweep(Some(&run_id)).await
+ })
+ }
+}
+
+/// One run at a time, server-wide.
+pub struct Runner {
+ lock: Arc<Mutex<()>>,
+ pub harness: Arc<dyn Harness>,
+}
+
+impl Default for Runner {
+ fn default() -> Self {
+ Runner::with_harness(Arc::new(DockerHarness))
+ }
+}
+
+impl Runner {
+ pub fn with_harness(harness: Arc<dyn Harness>) -> Self {
+ Runner { lock: Default::default(), harness }
+ }
+
+ pub fn running(&self) -> bool {
+ self.lock.try_lock().is_err()
+ }
+
+ /// The right to run, or `None` while another run holds it.
+ pub fn try_begin(&self) -> Option<OwnedMutexGuard<()>> {
+ self.lock.clone().try_lock_owned().ok()
+ }
+}
+
+/// Tries every option of `run` in turn, saving after each step. `_guard` is held until the end.
+pub async fn execute(db: Database, harness: Arc<dyn Harness>, mut run: Run, _guard: OwnedMutexGuard<()>) -> Result<Run, DbError> {
+ let scenario = run.scenario.clone();
+ for (i, option) in scenario.options.iter().enumerate() {
+ run.branches[i].status = BranchStatus::Running;
+ run.branches[i].started_at = Some(Utc::now());
+ db.pu_put_run(&run).await?;
+ let spec = BranchSpec {
+ run_id: run.id.clone(),
+ branch: option.key.clone(),
+ app: option.app.clone(),
+ limits: option.limits,
+ load: scenario.load.clone(),
+ build_network: scenario.build_network,
+ };
+ let outcome = harness.run_branch(spec).await;
+ let b = &mut run.branches[i];
+ b.build_network_used = scenario.build_network && option.app.context.is_some();
+ b.cleanup_errors = outcome.cleanup_errors;
+ b.finished_at = Some(Utc::now());
+ match outcome.result {
+ Ok(figures) => {
+ b.status = BranchStatus::Ok;
+ b.figures = figures;
+ }
+ Err(e) => {
+ b.status = BranchStatus::Failed;
+ b.error_code = Some(e.code().into());
+ b.error = Some(e.to_string());
+ }
+ }
+ db.pu_put_run(&run).await?;
+ }
+ // anything a branch could not remove, by label
+ match harness.sweep(run.id.clone()).await {
+ Ok(0) => {}
+ Ok(n) => run.cleanup_errors.push(format!("the final sweep removed {n} leftover objects")),
+ Err(e) => run.cleanup_errors.push(format!("the final sweep failed: {e}")),
+ }
+ run.status = RunStatus::Finished;
+ run.finished_at = Some(Utc::now());
+ db.pu_put_run(&run).await?;
+ Ok(run)
+}
+
+/// At server start: marks runs a stopped server left `running` as interrupted, and removes what
+/// they (or runs whose cleanup failed) left in Docker. Returns how many objects were removed.
+pub async fn startup(db: &Database, harness: &dyn Harness) -> Result<usize, DbError> {
+ let mut removed = 0;
+ for mut run in db.pu_runs_to_sweep().await? {
+ if run.status == RunStatus::Running {
+ run.status = RunStatus::Interrupted;
+ run.finished_at = Some(Utc::now());
+ for b in &mut run.branches {
+ if matches!(b.status, BranchStatus::Pending | BranchStatus::Running) {
+ b.status = BranchStatus::Failed;
+ b.error_code = Some("interrupted".into());
+ b.error = Some("the server stopped during the run".into());
+ b.finished_at = run.finished_at;
+ }
+ }
+ }
+ match harness.sweep(run.id.clone()).await {
+ Ok(n) => {
+ removed += n;
+ run.swept_at = Some(Utc::now());
+ if n > 0 {
+ run.cleanup_errors.push(format!("removed {n} leftover objects at startup"));
+ }
+ }
+ Err(e) => tracing::info!("parallel: could not sweep run {}: {e}", run.id),
+ }
+ db.pu_put_run(&run).await?;
+ }
+ Ok(removed)
+}
+
+// ---- the comparison report ----
+
+/// A sentence about one criterion, tagged like a figure (always `speculation` here).
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct Note {
+ pub criterion: CriterionKey,
+ pub text: String,
+ #[serde(flatten)]
+ pub tag: Tag,
+}
+
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct OptionReport {
+ pub key: String,
+ pub label: String,
+ pub plan: Option<String>,
+ pub status: BranchStatus,
+ pub error_code: Option<String>,
+ pub error: Option<String>,
+ /// Measured on this server (`verified`).
+ pub measured: Vec<Figure>,
+ /// `estimate` from the price table, or `speculation` without a plan.
+ pub cost: Figure,
+ /// Ops burden and rollback: `speculation`.
+ pub notes: Vec<Note>,
+ pub build_network_used: bool,
+}
+
+/// The lowest value of one criterion, where it can be compared at all.
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct Leader {
+ pub criterion: CriterionKey,
+ pub option: String,
+ pub value: f64,
+ pub unit: String,
+ /// The tag of the figures compared: `verified` or `estimate`.
+ pub basis: String,
+}
+
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct Report {
+ pub run_id: String,
+ pub scenario_id: String,
+ pub title: String,
+ pub question: String,
+ pub status: RunStatus,
+ pub started_at: DateTime<Utc>,
+ pub finished_at: Option<DateTime<Utc>>,
+ pub build_network_used: bool,
+ pub criteria: Vec<super::Criterion>,
+ pub options: Vec<OptionReport>,
+ pub leaders: Vec<Leader>,
+ /// What the reader must keep in mind; shown above the table.
+ pub caveats: Vec<String>,
+}
+
+fn speculation(criterion: CriterionKey, text: String, note: &str) -> Note {
+ Note { criterion, text, tag: Tag::Speculation { note: note.into() } }
+}
+
+/// What running and rolling back usually take on a kind of plan, when the person wrote nothing.
+fn default_notes(kind: Option<PlanKind>) -> (&'static str, &'static str) {
+ match kind {
+ Some(PlanKind::Vm) => (
+ "You patch the system, run backups and watch the server yourself.",
+ "Keep the previous release on the server and switch back; you script that yourself.",
+ ),
+ Some(PlanKind::Container) => (
+ "The provider runs the machine; you still own the image, health checks and scaling settings.",
+ "Redeploy the previous image from the provider's dashboard or CLI.",
+ ),
+ Some(PlanKind::Function) => (
+ "No server to patch; cold starts, time limits and per-request limits become your concern.",
+ "Point the function back at its previous version.",
+ ),
+ None => ("No plan was chosen, so nothing is known about running it.", "No plan was chosen, so nothing is known about rolling it back."),
+ }
+}
+
+fn metric<'a>(figures: &'a [Figure], name: &str) -> Option<&'a Figure> {
+ figures.iter().find(|f| f.metric == name)
+}
+
+/// The comparison for `run`, computed from what it stored (cost staleness uses `today`).
+pub fn report(run: &Run, today: chrono::NaiveDate) -> Report {
+ let s = &run.scenario;
+ let mut options = Vec::new();
+ for (o, b) in s.options.iter().zip(&run.branches) {
+ let entry = o.plan.as_deref().and_then(prices::find);
+ let cost = match entry {
+ Some(p) => prices::estimate_monthly(p, &s.traffic, today),
+ None => prices::cost_figure(None, &s.traffic),
+ };
+ let (ops_default, rollback_default) = default_notes(entry.map(|p| p.kind));
+ let note = |criterion, own: &str, fallback: &str| {
+ if own.trim().is_empty() {
+ speculation(criterion, fallback.into(), "kwant's general note for this kind of plan, not measured")
+ } else {
+ speculation(criterion, own.trim().into(), "the person's own note, not measured")
+ }
+ };
+ let measured = ["p95_latency", "p50_latency", "p99_latency", "requests_per_sec", "ok_share", "success_rate", "memory_after_load"]
+ .iter()
+ .filter_map(|m| metric(&b.figures, m).cloned())
+ .collect();
+ options.push(OptionReport {
+ key: o.key.clone(),
+ label: o.label.clone(),
+ plan: o.plan.clone(),
+ status: b.status,
+ error_code: b.error_code.clone(),
+ error: b.error.clone(),
+ measured,
+ cost,
+ notes: vec![note(CriterionKey::OpsBurden, &o.ops_notes, ops_default), note(CriterionKey::Rollback, &o.rollback_notes, rollback_default)],
+ build_network_used: b.build_network_used,
+ });
+ }
+
+ let mut leaders = Vec::new();
+ // p95: only options that answered every request are comparable
+ let p95: Vec<(&OptionReport, &Figure)> = options
+ .iter()
+ .filter(|o| o.status == BranchStatus::Ok && metric(&o.measured, "ok_share").is_some_and(|f| f.value >= 1.0))
+ .filter_map(|o| metric(&o.measured, "p95_latency").map(|f| (o, f)))
+ .collect();
+ if p95.len() >= 2 {
+ let (o, f) = p95.iter().min_by(|a, b| a.1.value.total_cmp(&b.1.value)).unwrap();
+ leaders.push(Leader { criterion: CriterionKey::P95Latency, option: o.key.clone(), value: f.value, unit: f.unit.clone(), basis: "verified".into() });
+ }
+ // cost: only estimates in one currency (nothing is converted)
+ let costs: Vec<&OptionReport> = options.iter().filter(|o| matches!(o.cost.tag, Tag::Estimate { .. })).collect();
+ if costs.len() >= 2 && costs.iter().all(|o| o.cost.unit == costs[0].cost.unit) {
+ let o = costs.iter().min_by(|a, b| a.cost.value.total_cmp(&b.cost.value)).unwrap();
+ leaders.push(Leader { criterion: CriterionKey::Cost, option: o.key.clone(), value: o.cost.value, unit: o.cost.unit.clone(), basis: "estimate".into() });
+ }
+
+ let mut caveats = vec![
+ "Latency, throughput and memory were measured on this server inside a container, not on the provider's hardware.".to_string(),
+ "Ops burden and rollback notes are guesses, not measurements.".to_string(),
+ ];
+ if costs.len() >= 2 && !costs.iter().all(|o| o.cost.unit == costs[0].cost.unit) {
+ caveats.push("The costs are in different currencies and were not converted, so they are not ranked.".into());
+ }
+ if options.iter().any(|o| matches!(o.cost.tag, Tag::Estimate { stale: true, .. })) {
+ caveats.push(format!("Some prices are more than {} days old.", prices::STALE_AFTER_DAYS));
+ }
+ let with_network: Vec<&str> = options.iter().filter(|o| o.build_network_used).map(|o| o.key.as_str()).collect();
+ if !with_network.is_empty() {
+ caveats.push(format!(
+ "The build step had network access for: {}. The app and the load test never did.",
+ with_network.join(", ")
+ ));
+ }
+ if options.iter().any(|o| o.status == BranchStatus::Failed) {
+ caveats.push("Some options failed, so they have no measurements.".into());
+ }
+ if run.status == RunStatus::Interrupted {
+ caveats.push("The server stopped during this run; it is incomplete.".into());
+ }
+
+ Report {
+ run_id: run.id.clone(),
+ scenario_id: run.scenario_id.clone(),
+ title: s.title.clone(),
+ question: s.question.clone(),
+ status: run.status,
+ started_at: run.started_at,
+ finished_at: run.finished_at,
+ build_network_used: run.build_network_used(),
+ criteria: s.criteria.clone(),
+ options,
+ leaders,
+ caveats,
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::parallel::harness::HarnessError;
+ use crate::parallel::{AppSpec, Criterion, DeployOption, Limits, LoadSpec, Requirements, Traffic};
+ use chrono::NaiveDate;
+
+ fn option(key: &str, plan: Option<&str>, context: bool) -> DeployOption {
+ DeployOption {
+ key: key.into(),
+ label: key.to_uppercase(),
+ plan: plan.map(String::from),
+ app: AppSpec {
+ image: (!context).then(|| "kwnt-executor:v1".into()),
+ context: context.then(|| "/tmp/app".into()),
+ dockerfile: None,
+ port: 8080,
+ health_path: "/".into(),
+ },
+ limits: Limits::default(),
+ ops_notes: String::new(),
+ rollback_notes: String::new(),
+ }
+ }
+
+ fn scenario(options: Vec<DeployOption>) -> Scenario {
+ Scenario {
+ id: "s1".into(),
+ title: "VPS or not".into(),
+ question: "Move?".into(),
+ requirements: Requirements::default(),
+ traffic: Traffic { monthly_requests: 1_000_000, peak_rps: 10.0, avg_response_kb: 20.0, avg_duration_ms: 50.0 },
+ load: LoadSpec::default(),
+ criteria: vec![Criterion { key: CriterionKey::Cost, weight: 5 }],
+ options,
+ build_network: false,
+ created_at: Utc::now(),
+ updated_at: Utc::now(),
+ }
+ }
+
+ fn measured(p95: f64, ok: f64) -> Vec<Figure> {
+ let at = Utc::now();
+ vec![
+ Figure::verified("p95_latency", p95, "ms", "docker run … oha", "{}", at),
+ Figure::verified("requests_per_sec", 500.0, "1/s", "docker run … oha", "{}", at),
+ Figure::verified("ok_share", ok, "ratio", "docker run … oha", "{}", at),
+ Figure::verified("memory_after_load", 20.0, "MB", "docker stats", "20MiB / 128MiB", at),
+ ]
+ }
+
+ fn today() -> NaiveDate {
+ NaiveDate::from_ymd_opt(2026, 10, 21).unwrap()
+ }
+
+ #[test]
+ fn the_report_tags_every_number_and_ranks_only_what_is_comparable() {
+ let s = scenario(vec![option("vps", Some("do-basic-1gb"), false), option("fly", Some("fly-shared-1x-512"), true), option("lambda", None, false)]);
+ let mut run = Run::new(&s);
+ run.branches[0].status = BranchStatus::Ok;
+ run.branches[0].figures = measured(9.0, 1.0);
+ run.branches[1].status = BranchStatus::Ok;
+ run.branches[1].figures = measured(4.0, 1.0);
+ run.branches[2].status = BranchStatus::Failed;
+ run.branches[2].error_code = Some(HarnessError::NotReady.code().into());
+ run.status = RunStatus::Finished;
+ let r = report(&run, today());
+
+ assert_eq!(r.options.len(), 3);
+ for o in &r.options {
+ assert!(o.measured.iter().all(|f| matches!(f.tag, Tag::Verified { .. })));
+ assert!(o.notes.iter().all(|n| matches!(n.tag, Tag::Speculation { .. })));
+ assert_eq!(o.notes.iter().map(|n| n.criterion).collect::<Vec<_>>(), [CriterionKey::OpsBurden, CriterionKey::Rollback]);
+ }
+ assert!(matches!(r.options[0].cost.tag, Tag::Estimate { .. }));
+ assert!(matches!(r.options[2].cost.tag, Tag::Speculation { .. }), "no plan: cost is a guess");
+ assert!(r.options[2].measured.is_empty());
+ assert_eq!(r.options[2].error_code.as_deref(), Some("not_ready"));
+
+ let p95 = r.leaders.iter().find(|l| l.criterion == CriterionKey::P95Latency).unwrap();
+ assert_eq!((p95.option.as_str(), p95.value, p95.basis.as_str()), ("fly", 4.0, "verified"));
+ let cost = r.leaders.iter().find(|l| l.criterion == CriterionKey::Cost).unwrap();
+ assert_eq!((cost.option.as_str(), cost.unit.as_str(), cost.basis.as_str()), ("fly", "USD", "estimate"));
+ assert!(!r.leaders.iter().any(|l| matches!(l.criterion, CriterionKey::OpsBurden | CriterionKey::Rollback)), "guesses are never ranked");
+ assert!(r.caveats.iter().any(|c| c.contains("not on the provider's hardware")));
+ assert!(r.caveats.iter().any(|c| c.contains("failed")));
+ assert!(!r.build_network_used);
+ }
+
+ #[test]
+ fn an_option_that_dropped_requests_is_not_ranked_on_latency() {
+ let s = scenario(vec![option("a", None, false), option("b", None, false)]);
+ let mut run = Run::new(&s);
+ for (b, figures) in run.branches.iter_mut().zip([measured(1.0, 0.5), measured(5.0, 1.0)]) {
+ b.status = BranchStatus::Ok;
+ b.figures = figures;
+ }
+ let r = report(&run, today());
+ assert!(r.leaders.is_empty(), "only one option answered everything, and neither has a price: {:?}", r.leaders);
+ }
+
+ #[test]
+ fn currencies_are_not_ranked_against_each_other_and_stale_prices_are_said() {
+ let s = scenario(vec![option("hetzner", Some("hetzner-cpx12"), false), option("do", Some("do-basic-1gb"), false)]);
+ let r = report(&Run::new(&s), NaiveDate::from_ymd_opt(2027, 9, 1).unwrap());
+ assert!(!r.leaders.iter().any(|l| l.criterion == CriterionKey::Cost));
+ assert!(r.caveats.iter().any(|c| c.contains("different currencies")));
+ assert!(r.caveats.iter().any(|c| c.contains("days old")));
+ }
+
+ #[test]
+ fn the_persons_own_notes_win_and_the_build_network_is_reported() {
+ let mut o = option("vps", Some("do-basic-1gb"), true);
+ o.ops_notes = " I already run two of these ".into();
+ let mut s = scenario(vec![o, option("img", None, false)]);
+ s.build_network = true;
+ let mut run = Run::new(&s);
+ run.branches[0].build_network_used = true;
+ let r = report(&run, today());
+ assert_eq!(r.options[0].notes[0].text, "I already run two of these");
+ assert!(matches!(&r.options[0].notes[0].tag, Tag::Speculation { note } if note.contains("own note")));
+ assert!(r.options[0].notes[1].text.contains("previous release"), "VM default rollback note");
+ assert!(r.build_network_used && r.options[0].build_network_used && !r.options[1].build_network_used);
+ assert!(r.caveats.iter().any(|c| c.contains("network access for: vps")));
+ }
+}
diff --git a/src/server/mod.rs b/src/server/mod.rs
index 69994a3c..1900201a 100644
--- a/src/server/mod.rs
+++ b/src/server/mod.rs
@@ -82,6 +82,8 @@ pub struct AppState {
pub credentials: Arc<crate::sandbox::vault::PasswordVault>,
/// Zombie Mission Hunter: one scan at a time, and the last scan's report.
pub zombie: Arc<crate::zombie::hunt::Hunter>,
+ /// Parallel Universe: one run at a time, and the harness it uses.
+ pub parallel: Arc<crate::parallel::run::Runner>,
}
impl AppState {
@@ -123,6 +125,7 @@ impl AppState {
mcp_registry: Arc::new(crate::mcp::registry::McpRegistry::from_env()),
credentials: Arc::new(crate::sandbox::vault::PasswordVault::open(&config_data_dir)),
zombie: Default::default(),
+ parallel: Default::default(),
}
}
@@ -230,6 +233,10 @@ pub fn create_router(state: AppState) -> Router {
)
.route("/api/parallel/prices", get(parallel_routes::list_prices))
.route("/api/parallel/estimate", post(parallel_routes::estimate))
+ .route("/api/parallel/scenarios/:id/run", post(parallel_routes::start_run))
+ .route("/api/parallel/scenarios/:id/runs", get(parallel_routes::scenario_runs))
+ .route("/api/parallel/runs", get(parallel_routes::list_runs))
+ .route("/api/parallel/runs/:id", get(parallel_routes::get_run))
.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
index 6fd0ec07..a30d623c 100644
--- a/src/server/parallel_routes.rs
+++ b/src/server/parallel_routes.rs
@@ -8,11 +8,14 @@
//! - `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).
+//! - `POST /api/parallel/scenarios/:id/run` → 202 `{run}`; 409 `{error, code: "busy"}` while a run is going.
+//! - `GET /api/parallel/scenarios/:id/runs` and `GET /api/parallel/runs` → `{runs: [Run], running}`.
+//! - `GET /api/parallel/runs/:id` → `{run, report}` (poll it until `run.status` is not `running`).
#![allow(clippy::result_large_err)]
use super::AppState;
-use crate::parallel::{prices, Scenario, Traffic};
+use crate::parallel::{prices, run, Scenario, Traffic};
use axum::{
extract::{rejection::JsonRejection, Path, State},
http::{HeaderMap, StatusCode},
@@ -118,3 +121,50 @@ pub async fn estimate(State(state): State<AppState>, headers: HeaderMap, b: Resu
}
Ok(Json(json!({"figures": [prices::cost_figure(b.plan.as_deref(), t)]})).into_response())
}
+
+pub async fn start_run(State(state): State<AppState>, headers: HeaderMap, Path(id): Path<String>) -> Res {
+ person(&state, &headers).await?;
+ let scenario = scenario_or_404(&state, &id).await?;
+ let Some(guard) = state.parallel.try_begin() else {
+ return Err((StatusCode::CONFLICT, Json(json!({"error": "a run is already going; wait for it to finish", "code": "busy"}))).into_response());
+ };
+ let r = run::Run::new(&scenario);
+ state.db.pu_put_run(&r).await.map_err(db_error)?;
+ let (db, harness, bg) = (state.db.clone(), state.parallel.harness.clone(), r.clone());
+ tokio::spawn(async move {
+ if let Err(e) = run::execute(db, harness, bg, guard).await {
+ tracing::warn!("parallel: a run could not be saved: {e}");
+ }
+ });
+ Ok((StatusCode::ACCEPTED, Json(json!({"run": r}))).into_response())
+}
+
+pub async fn list_runs(State(state): State<AppState>, headers: HeaderMap) -> Res {
+ person(&state, &headers).await?;
+ let runs = state.db.pu_runs(None, 50).await.map_err(db_error)?;
+ Ok(Json(json!({"runs": runs, "running": state.parallel.running()})).into_response())
+}
+
+pub async fn scenario_runs(State(state): State<AppState>, headers: HeaderMap, Path(id): Path<String>) -> Res {
+ person(&state, &headers).await?;
+ let runs = state.db.pu_runs(Some(&id), 50).await.map_err(db_error)?;
+ Ok(Json(json!({"runs": runs, "running": state.parallel.running()})).into_response())
+}
+
+pub async fn get_run(State(state): State<AppState>, headers: HeaderMap, Path(id): Path<String>) -> Res {
+ person(&state, &headers).await?;
+ let r = state.db.pu_run(&id).await.map_err(db_error)?.ok_or_else(|| error(StatusCode::NOT_FOUND, "no such run"))?;
+ let report = run::report(&r, Utc::now().date_naive());
+ Ok(Json(json!({"run": r, "report": report})).into_response())
+}
+
+/// Marks runs a stopped server left behind as interrupted and removes their containers.
+pub fn spawn_startup_sweep(state: AppState) {
+ tokio::spawn(async move {
+ match run::startup(&state.db, state.parallel.harness.as_ref()).await {
+ Ok(0) => {}
+ Ok(n) => tracing::info!("parallel: removed {n} leftover containers, networks and images"),
+ Err(e) => tracing::warn!("parallel: startup sweep failed: {e}"),
+ }
+ });
+}
diff --git a/tests/parallel_test.rs b/tests/parallel_test.rs
index 1eac3018..fcf47b7f 100644
--- a/tests/parallel_test.rs
+++ b/tests/parallel_test.rs
@@ -2,7 +2,8 @@
//! 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`.
+//! Docker, the `kwnt-executor:v1` image and oha 1.16.0 (`harness::OHA_IMAGE`, pinned by digest).
+//! The run routes are tested with a fake harness, so they need no Docker.
use axum::{
body::{to_bytes, Body},
@@ -14,8 +15,9 @@ use kwnt::{
config::Config,
db::{spaces::SpaceId, Database},
parallel::{
- harness::{self, BranchSpec, HarnessError, Names},
- AppSpec, Limits, LoadSpec, Tag,
+ harness::{self, BranchOutcome, BranchSpec, HarnessError, Names},
+ run::{self, BoxFut, Harness, Run, RunStatus, Runner},
+ AppSpec, Figure, Limits, LoadSpec, Tag,
},
router::LayaRouter,
server::{continuity::SelfScope, create_router, mcp_runtime, AppState},
@@ -23,6 +25,7 @@ use kwnt::{
};
use serde_json::{json, Value};
use std::path::Path;
+use std::sync::{Arc, Mutex};
use tempfile::{tempdir, TempDir};
use tower::ServiceExt;
@@ -33,14 +36,76 @@ struct Env {
}
async fn setup() -> Env {
+ setup_with(None).await
+}
+
+async fn setup_with(harness: Option<Arc<dyn Harness>>) -> 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()));
+ let mut state = AppState::new(config.clone(), db, ToolRunner::new(data.join("workspace")), PermissionBroker::new(), LayaRouter::new(config.laya_url.clone()));
+ if let Some(h) = harness {
+ state.parallel = Arc::new(Runner::with_harness(h));
+ }
Env { app: create_router(state.clone()), state, _tmp: tmp }
}
+/// Measures nothing: an option called `dead` never gets ready, every other one is fast. A held
+/// gate keeps the first branch running until the test releases it.
+#[derive(Default)]
+struct Fake {
+ gate: Option<Arc<tokio::sync::Semaphore>>,
+ branches: Mutex<Vec<BranchSpec>>,
+ swept: Mutex<Vec<String>>,
+ leftovers: usize,
+}
+
+impl Harness for Fake {
+ fn run_branch(&self, spec: BranchSpec) -> BoxFut<BranchOutcome> {
+ self.branches.lock().unwrap().push(spec.clone());
+ let gate = self.gate.clone();
+ Box::pin(async move {
+ if let Some(g) = gate {
+ let _ = g.acquire().await.unwrap();
+ }
+ let at = chrono::Utc::now();
+ let result = if spec.branch == "dead" {
+ Err(HarnessError::NotReady)
+ } else {
+ let p95 = if spec.branch == "vps" { 8.0 } else { 3.0 };
+ Ok(vec![
+ Figure::verified("p95_latency", p95, "ms", "docker run … oha", "{\"fake\":true}", at),
+ Figure::verified("requests_per_sec", 900.0, "1/s", "docker run … oha", "{\"fake\":true}", at),
+ Figure::verified("ok_share", 1.0, "ratio", "docker run … oha", "{\"fake\":true}", at),
+ Figure::verified("memory_after_load", 21.5, "MB", "docker stats", "21.5MiB / 512MiB", at),
+ ])
+ };
+ BranchOutcome { result, cleanup_errors: Vec::new() }
+ })
+ }
+ fn sweep(&self, run_id: String) -> BoxFut<Result<usize, String>> {
+ self.swept.lock().unwrap().push(run_id);
+ let n = self.leftovers;
+ Box::pin(async move { Ok(n) })
+ }
+}
+
+impl Env {
+ /// Polls a run until it is no longer running.
+ async fn finished(&self, run_id: &str) -> Value {
+ for _ in 0..500 {
+ let (s, v) = self.person("GET", &format!("/api/parallel/runs/{run_id}"), None).await;
+ assert_eq!(s, StatusCode::OK, "{v}");
+ if v["run"]["status"] != "running" {
+ return v;
+ }
+ tokio::time::sleep(std::time::Duration::from_millis(10)).await;
+ }
+ panic!("run {run_id} never finished");
+ }
+}
+
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 {
@@ -94,6 +159,10 @@ async fn every_route_is_the_persons_only() {
("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}}))),
+ ("POST", "/api/parallel/scenarios/x/run", None),
+ ("GET", "/api/parallel/scenarios/x/runs", None),
+ ("GET", "/api/parallel/runs", None),
+ ("GET", "/api/parallel/runs/x", None),
];
for (method, uri, body) in &routes {
let (s, v) = call(&e.app, method, uri, None, body.clone()).await;
@@ -104,6 +173,7 @@ async fn every_route_is_the_persons_only() {
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");
+ assert!(e.state.db.pu_runs(None, 10).await.unwrap().is_empty(), "no run was started by a refused call");
}
#[tokio::test]
@@ -198,6 +268,185 @@ async fn prices_and_estimates_name_their_source() {
assert_eq!(s, StatusCode::BAD_REQUEST);
}
+fn run_scenario() -> Value {
+ let mut v = scenario();
+ v["options"] = json!([
+ {"key": "vps", "label": "DigitalOcean droplet", "plan": "do-basic-1gb", "app": {"image": "kwnt-executor:v1", "port": 8080},
+ "rollback_notes": "keep the last two releases"},
+ {"key": "fly", "label": "Fly.io", "plan": "fly-shared-1x-512", "app": {"context": "/tmp/app", "port": 8080}},
+ {"key": "dead", "label": "Never answers", "app": {"image": "kwnt-executor:v1", "port": 8080}}
+ ]);
+ v
+}
+
+#[tokio::test]
+async fn a_run_tries_every_option_and_reports_tagged_numbers() {
+ let fake = Arc::new(Fake::default());
+ let e = setup_with(Some(fake.clone())).await;
+ let (_, created) = e.person("POST", "/api/parallel/scenarios", Some(run_scenario())).await;
+ let id = created["id"].as_str().unwrap().to_string();
+
+ let (s, v) = e.person("POST", "/api/parallel/scenarios/nope/run", None).await;
+ assert_eq!(s, StatusCode::NOT_FOUND, "{v}");
+ let (s, started) = e.person("POST", &format!("/api/parallel/scenarios/{id}/run"), None).await;
+ assert_eq!(s, StatusCode::ACCEPTED, "{started}");
+ assert_eq!(started["run"]["status"], "running");
+ let run_id = started["run"]["id"].as_str().unwrap().to_string();
+
+ let done = e.finished(&run_id).await;
+ let (run, report) = (&done["run"], &done["report"]);
+ assert_eq!(run["status"], "finished");
+ assert!(run["finished_at"].is_string());
+ let statuses: Vec<&str> = run["branches"].as_array().unwrap().iter().map(|b| b["status"].as_str().unwrap()).collect();
+ assert_eq!(statuses, ["ok", "ok", "failed"]);
+ assert_eq!(run["branches"][2]["error_code"], "not_ready");
+ assert_eq!(run["branches"][1]["build_network_used"], false, "builds stay offline by default");
+
+ // the harness got each option, in order, with the run's own id and the scenario's load
+ let specs = fake.branches.lock().unwrap().clone();
+ assert_eq!(specs.iter().map(|b| b.branch.as_str()).collect::<Vec<_>>(), ["vps", "fly", "dead"]);
+ assert!(specs.iter().all(|b| b.run_id == run_id && b.load.requests == 500 && !b.build_network));
+ assert_eq!(fake.swept.lock().unwrap().as_slice(), std::slice::from_ref(&run_id), "the run's label is swept at the end");
+
+ // the report: measured = verified, cost = estimate or speculation, notes = speculation
+ let opts = report["options"].as_array().unwrap();
+ for o in opts {
+ assert!(o["measured"].as_array().unwrap().iter().all(|f| f["tag"] == "verified" && f["command"].is_string() && f["raw_output"].is_string()));
+ assert!(o["notes"].as_array().unwrap().iter().all(|n| n["tag"] == "speculation"));
+ }
+ assert_eq!(opts[0]["cost"]["tag"], "estimate");
+ assert_eq!(opts[0]["cost"]["source_url"], "https://www.digitalocean.com/pricing/droplets");
+ assert!(opts[0]["cost"]["as_of"].is_string() && opts[0]["cost"]["stale"] == false);
+ assert_eq!(opts[2]["cost"]["tag"], "speculation");
+ assert!(opts[2]["measured"].as_array().unwrap().is_empty());
+ assert_eq!(opts[0]["notes"][1]["text"], "keep the last two releases");
+ let leaders = report["leaders"].as_array().unwrap();
+ assert!(leaders.iter().any(|l| l["criterion"] == "p95_latency" && l["option"] == "fly" && l["basis"] == "verified"), "{leaders:?}");
+ assert!(leaders.iter().any(|l| l["criterion"] == "cost" && l["basis"] == "estimate"), "{leaders:?}");
+ assert!(report["caveats"].as_array().unwrap().iter().any(|c| c.as_str().unwrap().contains("not on the provider's hardware")));
+
+ // a run keeps the scenario as it was: editing it later changes nothing
+ let mut changed = run_scenario();
+ changed["title"] = json!("Something else");
+ e.person("PUT", &format!("/api/parallel/scenarios/{id}"), Some(changed)).await;
+ let (_, again) = e.person("GET", &format!("/api/parallel/runs/{run_id}"), None).await;
+ assert_eq!(again["report"]["title"], "Move the shop off managed hosting?");
+
+ let (_, list) = e.person("GET", "/api/parallel/runs", None).await;
+ assert_eq!((list["runs"].as_array().unwrap().len(), &list["running"]), (1, &json!(false)));
+ let (_, mine) = e.person("GET", &format!("/api/parallel/scenarios/{id}/runs"), None).await;
+ assert_eq!(mine["runs"][0]["id"], run_id.as_str());
+ let (s, _) = e.person("GET", "/api/parallel/runs/nope", None).await;
+ assert_eq!(s, StatusCode::NOT_FOUND);
+}
+
+#[tokio::test]
+async fn only_one_run_goes_at_a_time() {
+ let gate = Arc::new(tokio::sync::Semaphore::new(0));
+ let fake = Arc::new(Fake { gate: Some(gate.clone()), ..Default::default() });
+ let e = setup_with(Some(fake.clone())).await;
+ let (_, a) = e.person("POST", "/api/parallel/scenarios", Some(run_scenario())).await;
+ let (_, b) = e.person("POST", "/api/parallel/scenarios", Some(scenario())).await;
+ let (s, first) = e.person("POST", &format!("/api/parallel/scenarios/{}/run", a["id"].as_str().unwrap()), None).await;
+ assert_eq!(s, StatusCode::ACCEPTED);
+
+ // another scenario's run is refused too: the limit is server-wide
+ let (s, v) = e.person("POST", &format!("/api/parallel/scenarios/{}/run", b["id"].as_str().unwrap()), None).await;
+ assert_eq!((s, v["code"].as_str()), (StatusCode::CONFLICT, Some("busy")), "{v}");
+ let (_, list) = e.person("GET", "/api/parallel/runs", None).await;
+ assert_eq!((list["runs"].as_array().unwrap().len(), &list["running"]), (1, &json!(true)), "the refused start stored nothing");
+ let mut poll = Value::Null;
+ for _ in 0..500 {
+ poll = e.person("GET", &format!("/api/parallel/runs/{}", first["run"]["id"].as_str().unwrap()), None).await.1;
+ if poll["run"]["branches"][0]["status"] == "running" {
+ break;
+ }
+ tokio::time::sleep(std::time::Duration::from_millis(10)).await;
+ }
+ assert_eq!(poll["run"]["status"], "running");
+ assert_eq!(poll["run"]["branches"][0]["status"], "running");
+ assert_eq!(poll["run"]["branches"][1]["status"], "pending");
+
+ gate.add_permits(10);
+ e.finished(first["run"]["id"].as_str().unwrap()).await;
+ let (s, v) = e.person("POST", &format!("/api/parallel/scenarios/{}/run", b["id"].as_str().unwrap()), None).await;
+ assert_eq!(s, StatusCode::ACCEPTED, "free again once it finished: {v}");
+ e.finished(v["run"]["id"].as_str().unwrap()).await;
+}
+
+#[tokio::test]
+async fn the_build_network_is_off_unless_asked_and_said_when_used() {
+ let fake = Arc::new(Fake::default());
+ let e = setup_with(Some(fake.clone())).await;
+ let (_, plain) = e.person("POST", "/api/parallel/scenarios", Some(run_scenario())).await;
+ assert_eq!(plain["build_network"], false);
+ let mut v = run_scenario();
+ v["build_network"] = json!(true);
+ let (_, net) = e.person("POST", "/api/parallel/scenarios", Some(v)).await;
+ assert_eq!(net["build_network"], true);
+ let (_, got) = e.person("GET", &format!("/api/parallel/scenarios/{}", net["id"].as_str().unwrap()), None).await;
+ assert_eq!(got["build_network"], true, "stored");
+
+ let (_, started) = e.person("POST", &format!("/api/parallel/scenarios/{}/run", net["id"].as_str().unwrap()), None).await;
+ let done = e.finished(started["run"]["id"].as_str().unwrap()).await;
+ let used: Vec<bool> = done["run"]["branches"].as_array().unwrap().iter().map(|b| b["build_network_used"].as_bool().unwrap()).collect();
+ assert_eq!(used, [false, true, false], "only the option that builds (fly) had it");
+ assert!(fake.branches.lock().unwrap().iter().all(|b| b.build_network));
+ assert_eq!(done["report"]["build_network_used"], true);
+ assert!(done["report"]["caveats"].as_array().unwrap().iter().any(|c| c.as_str().unwrap().contains("network access for: fly")));
+}
+
+#[tokio::test]
+async fn a_run_a_stopped_server_left_behind_is_marked_and_swept_once() {
+ let e = setup().await;
+ let (_, created) = e.person("POST", "/api/parallel/scenarios", Some(run_scenario())).await;
+ let scenario = e.state.db.pu_scenario(created["id"].as_str().unwrap()).await.unwrap().unwrap();
+ let mut stuck = Run::new(&scenario);
+ stuck.branches[0].status = run::BranchStatus::Ok;
+ stuck.branches[1].status = run::BranchStatus::Running;
+ e.state.db.pu_put_run(&stuck).await.unwrap();
+ let mut clean = Run::new(&scenario);
+ clean.status = RunStatus::Finished;
+ e.state.db.pu_put_run(&clean).await.unwrap();
+
+ let fake = Fake { leftovers: 2, ..Default::default() };
+ assert_eq!(run::startup(&e.state.db, &fake).await.unwrap(), 2);
+ assert_eq!(fake.swept.lock().unwrap().as_slice(), std::slice::from_ref(&stuck.id), "a finished, clean run is left alone");
+ let after = e.state.db.pu_run(&stuck.id).await.unwrap().unwrap();
+ assert_eq!(after.status, RunStatus::Interrupted);
+ assert_eq!(after.branches.iter().map(|b| b.status).collect::<Vec<_>>(), [run::BranchStatus::Ok, run::BranchStatus::Failed, run::BranchStatus::Failed]);
+ assert_eq!(after.branches[1].error_code.as_deref(), Some("interrupted"));
+ assert!(after.swept_at.is_some() && after.cleanup_errors.iter().any(|c| c.contains("removed 2")));
+
+ let again = Fake::default();
+ assert_eq!(run::startup(&e.state.db, &again).await.unwrap(), 0);
+ assert!(again.swept.lock().unwrap().is_empty(), "swept runs are not swept again");
+}
+
+#[tokio::test]
+async fn a_slice_1_database_gains_build_network() {
+ let tmp = tempdir().unwrap();
+ let data = tmp.path().join("data");
+ let db = Database::init(&data).await.unwrap();
+ let path = data.join("kwnt.db");
+ assert!(path.exists(), "{path:?}");
+ let url = format!("sqlite://{}", path.display());
+ let pool = sqlx::SqlitePool::connect(&url).await.unwrap();
+ sqlx::query("DROP TABLE pu_runs").execute(&pool).await.unwrap();
+ sqlx::query("ALTER TABLE pu_scenarios DROP COLUMN build_network").execute(&pool).await.unwrap();
+ sqlx::query("INSERT INTO pu_scenarios (id, title, question, requirements, traffic, load, criteria, options, created_at, updated_at)
+ VALUES ('old', 'Old', '', '{}', '{\"monthly_requests\":1}', '{\"requests\":1,\"concurrency\":1,\"path\":\"/\"}', '[]', '[]', '2026-10-20T00:00:00Z', '2026-10-20T00:00:00Z')")
+ .execute(&pool)
+ .await
+ .unwrap();
+ pool.close().await;
+ drop(db);
+ let db = Database::init(&data).await.unwrap();
+ let old = db.pu_scenario("old").await.unwrap().unwrap();
+ assert!(!old.build_network);
+ assert!(db.pu_runs(None, 10).await.unwrap().is_empty());
+}
+
// ---- the harness against real Docker (ignored: needs Docker and two local images) ----
fn docker(args: &[&str]) -> String {
@@ -231,6 +480,7 @@ async fn harness_measures_a_synthetic_app_and_leaves_nothing_behind() {
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() },
+ build_network: false,
};
let out = harness::run_branch(&spec).await;
let figures = out.result.expect("the branch ran");
@@ -259,6 +509,7 @@ async fn an_app_that_never_answers_is_cleaned_up_too() {
app: synthetic_app(ctx.path(), r#"["sleep", "infinity"]"#),
limits: Limits { cpus: 0.25, memory_mb: 64, pids: 16, timeout_secs: 30 },
load: LoadSpec::default(),
+ build_network: false,
};
let out = harness::run_branch(&spec).await;
assert!(matches!(out.result, Err(HarnessError::NotReady) | Err(HarnessError::Timeout)), "{:?}", out.result);
@@ -302,3 +553,69 @@ async fn the_internal_network_reaches_neither_the_internet_nor_the_host() {
assert!(harness::sweep(Some(&run_id)).await.unwrap() >= 1);
assert_eq!(leftovers(&run_id), "");
}
+
+#[tokio::test]
+#[ignore]
+async fn the_build_reaches_the_network_only_when_asked() {
+ let ctx = tempdir().unwrap();
+ // the build step downloads nothing, it only opens a connection to a public resolver
+ std::fs::write(
+ ctx.path().join("Dockerfile"),
+ "FROM kwnt-executor:v1\nWORKDIR /srv\nRUN python3 -c \"import socket; socket.create_connection(('1.1.1.1', 53), 5)\" && echo ok > index.html\nCMD [\"python3\", \"-m\", \"http.server\", \"8080\"]\n",
+ )
+ .unwrap();
+ let app = AppSpec { image: None, context: Some(ctx.path().to_string_lossy().into()), dockerfile: None, port: 8080, health_path: "/".into() };
+ let limits = Limits { cpus: 0.5, memory_mb: 128, pids: 64, timeout_secs: 120 };
+ let load = LoadSpec { requests: 100, concurrency: 2, path: "/".into() };
+ for (build_network, expect_ok) in [(false, false), (true, true)] {
+ let run_id = format!("pu{}", uuid::Uuid::new_v4().simple());
+ let spec = BranchSpec { run_id: run_id.clone(), branch: "net".into(), app: app.clone(), limits, load: load.clone(), build_network };
+ let out = harness::run_branch(&spec).await;
+ match (&out.result, expect_ok) {
+ (Ok(_), true) => {}
+ (Err(HarnessError::Build(_)), false) => {}
+ (r, _) => panic!("build_network={build_network}: {r:?}"),
+ }
+ assert!(out.cleanup_errors.is_empty(), "{:?}", out.cleanup_errors);
+ assert_eq!(leftovers(&run_id), "", "build_network={build_network}");
+ }
+}
+
+#[tokio::test]
+#[ignore]
+async fn a_real_run_through_the_routes_leaves_nothing_behind() {
+ let e = setup_with(Some(Arc::new(run::DockerHarness))).await;
+ let a = tempdir().unwrap();
+ let b = tempdir().unwrap();
+ synthetic_app(a.path(), r#"["python3", "-m", "http.server", "8080"]"#);
+ synthetic_app(b.path(), r#"["python3", "-m", "http.server", "8080", "--bind", "0.0.0.0"]"#);
+ let mut v = scenario();
+ v["load"] = json!({"requests": 200, "concurrency": 4, "path": "/"});
+ v["options"] = json!([
+ {"key": "vps", "label": "DO droplet", "plan": "do-basic-1gb", "app": {"context": a.path(), "port": 8080},
+ "limits": {"cpus": 0.5, "memory_mb": 128, "pids": 64, "timeout_secs": 120}},
+ {"key": "fly", "label": "Fly.io", "plan": "fly-shared-1x-512", "app": {"context": b.path(), "port": 8080},
+ "limits": {"cpus": 0.25, "memory_mb": 96, "pids": 64, "timeout_secs": 120}}
+ ]);
+ let (_, created) = e.person("POST", "/api/parallel/scenarios", Some(v)).await;
+ let (s, started) = e.person("POST", &format!("/api/parallel/scenarios/{}/run", created["id"].as_str().unwrap()), None).await;
+ assert_eq!(s, StatusCode::ACCEPTED, "{started}");
+ let run_id = started["run"]["id"].as_str().unwrap().to_string();
+ let mut done = Value::Null;
+ for _ in 0..600 {
+ let (_, v) = e.person("GET", &format!("/api/parallel/runs/{run_id}"), None).await;
+ if v["run"]["status"] != "running" {
+ done = v;
+ break;
+ }
+ tokio::time::sleep(std::time::Duration::from_millis(500)).await;
+ }
+ println!("{}", serde_json::to_string_pretty(&done["report"]).unwrap());
+ assert_eq!(done["run"]["status"], "finished", "{done}");
+ for b in done["run"]["branches"].as_array().unwrap() {
+ assert_eq!(b["status"], "ok", "{b}");
+ assert!(b["cleanup_errors"].as_array().unwrap().is_empty(), "{b}");
+ }
+ assert!(done["run"]["cleanup_errors"].as_array().unwrap().is_empty());
+ assert_eq!(leftovers(&run_id), "");
+}