diff --git a/crates/AGENTS.md b/crates/AGENTS.md index b6e37daab7..11985783fd 100644 --- a/crates/AGENTS.md +++ b/crates/AGENTS.md @@ -10,7 +10,7 @@ - Templates: `affine_tpl_` is built once per migration digest under an advisory lock, records the applied migrations in `_prisma_migrations`, and is left read-only (`IS_TEMPLATE`, `ALLOW_CONNECTIONS false`). Each test gets `test__` via `CREATE DATABASE ... TEMPLATE`. - Leases: every clone has a row in `postgres.public.test_db_leases` with a secret owner token; heartbeat and release need the token. Cloning, heartbeat, release and the reaper serialize per database on an advisory lock (the lease row, the clone and its TTL start are made under it), and the reaper re-checks expiry and `pg_stat_activity` under it before dropping (without `FORCE`), so a database being cloned, renewed or used is never dropped. `PgCluster` and `DbLease` alike reach the cluster only through a maintenance connection that re-checks the marker. - Redis: an explicit `AFFINE_TEST_REDIS_URL` isolated by the `test::` key prefix, or a private `redis:7-alpine` container. - - Containers carry `affine.test.env=true` and `affine.test.shared=true|false`; private ones also `affine.test.owner=`. `Container::remove_owned` (and `affine-test-env down`, which passes the `AFFINE_TEST_OWNER` that `up` wrote) removes only a private harness container named by its full 64-hex id, of the expected run; names, prefixes, unlabeled, foreign and shared containers are refused. A Docker-compatible CLI such as `podman` can be named in `AFFINE_TEST_CONTAINER_CLI`. + - Containers carry `affine.test.env=true` and `affine.test.shared=true|false`; private ones also `affine.test.owner=`. `Container::remove_owned(id, owner)` (used by drop, and by `affine-test-env down` with the `AFFINE_TEST_OWNER` that `up` wrote) removes only a container labeled `affine.test.shared=false` and owned by that non-empty run, named by its full 64-hex id; names, prefixes, unlabeled, foreign, unmarked and shared containers are refused. Concurrent `ensure_shared` callers converge on one container: losers of the name race wait (short backoff, 10 s from their own first lookup or start, so an image pull is not counted) until it runs; a stopped leftover of ours is removed without force and replaced, and a paused or unknown-state one is kept and reported. A Docker-compatible CLI such as `podman` can be named in `AFFINE_TEST_CONTAINER_CLI`. - `run.json`: `{ run_id, sha, lane, selected_targets, skipped_targets_with_reason, timings_ms, status }`, written by `affine-test-env run-json`. Both images are fully qualified and pinned to multi-arch index digests in `src/pg.rs` / `src/redis.rs`, in `.github/workflows/native-playground.yml`, and in `scripts/ci/check-l0-tier-a.mjs`, which fails when they differ; change all three together. diff --git a/crates/test-db-harness/src/bin/affine-test-env.rs b/crates/test-db-harness/src/bin/affine-test-env.rs index e5d0bec723..ae62a752a5 100644 --- a/crates/test-db-harness/src/bin/affine-test-env.rs +++ b/crates/test-db-harness/src/bin/affine-test-env.rs @@ -137,7 +137,7 @@ fn down(opts: &Opts) -> Result<()> { owner = Some(value); } else if key == PG_CONTAINER_ENV || key == REDIS_CONTAINER_ENV { let owner = owner.ok_or_else(|| Error::new(format!("{key} in {path} has no preceding {OWNER_ENV}")))?; - Container::remove_owned(value, Some(owner))?; + Container::remove_owned(value, owner)?; println!("removed {key} {value}"); } } diff --git a/crates/test-db-harness/src/docker.rs b/crates/test-db-harness/src/docker.rs index fd93a73e8e..5f5219038f 100644 --- a/crates/test-db-harness/src/docker.rs +++ b/crates/test-db-harness/src/docker.rs @@ -1,6 +1,7 @@ use std::{ net::SocketAddr, process::{Command, Output}, + time::{Duration, Instant}, }; use crate::{Error, Result, process_run_id}; @@ -8,8 +9,8 @@ use crate::{Error, Result, process_run_id}; /// Label on every container the harness starts; `down` and shared-container /// lookups only ever touch containers carrying it. pub const OWNER_LABEL: &str = "affine.test.env"; -/// `true` on the machine-wide shared container, which -/// [`Container::remove_owned`] never removes; `false` on private ones. +/// `true` on the machine-wide shared container; `false` on private ones. +/// [`Container::remove_owned`] removes only containers labeled `false`. pub const SHARED_LABEL: &str = "affine.test.shared"; /// Run id of the process that started a private container. pub const RUN_LABEL: &str = "affine.test.owner"; @@ -36,10 +37,15 @@ fn failure(what: &str, output: &Output) -> Error { )) } +/// How long [`Container::ensure_shared`] waits for a shared container +/// another caller is starting to come up. +const SHARED_START_TIMEOUT: Duration = Duration::from_secs(10); + /// A container publishing one port on a random `127.0.0.1` port. /// -/// A private container is removed on drop unless [`Container::detach`]ed; a -/// shared one (see [`Container::ensure_shared`]) outlives every handle. +/// A private container is owned by this run and removed on drop unless +/// [`Container::detach`]ed; a shared one (see [`Container::ensure_shared`]) +/// outlives every handle. #[derive(Debug)] pub struct Container { id: String, @@ -65,21 +71,74 @@ impl Container { /// Returns the running machine-wide container named `name`, starting it /// when there is none. Concurrent callers converge on one container: a - /// name conflict means another process started it first. The caller checks - /// that the service inside is ready. + /// caller that loses the race for the name waits (short backoff, 10 s + /// after its own first lookup or start, so an image pull does not count) + /// until the winner's container runs with its port published. A stopped + /// leftover of ours is removed and started again; a paused or unknown one + /// is left alone and reported. The caller checks that the service inside + /// is ready. pub fn ensure_shared(name: &str, image: &str, port: u16, docker_args: &[&str], command: &[&str]) -> Result { - let id = match running_labeled(name)? { - Some(id) => id, - None => match start(image, port, Some(name), docker_args, command) { - Ok(id) => id, - Err(e) => running_labeled(name)?.ok_or(e)?, - }, - }; - Ok(Self { - addr: published_addr(&id, port)?, + let shared = |id: String, addr| Self { id, + addr, remove_on_drop: false, - }) + }; + let mut deadline: Option = None; + let mut backoff = [20, 50, 100] + .into_iter() + .chain(std::iter::repeat(100)) + .map(Duration::from_millis); + let mut last_error = None; + loop { + match shared_state(name)? { + None => match start(image, port, Some(name), docker_args, command) { + Ok(id) => match published_addr(&id, port) { + Ok(addr) => return Ok(shared(id, addr)), + Err(e) => last_error = Some(e), + }, + // Losing the name race is fine: the next pass finds the winner. + Err(e) => last_error = Some(e), + }, + Some((id, state)) => match shared_action(&state) { + SharedAction::Use => match published_addr(&id, port) { + Ok(addr) => return Ok(shared(id, addr)), + Err(e) => last_error = Some(e), + }, + SharedAction::Wait => {} + SharedAction::Clear => { + // Not forced: a container that came back to life is kept. + if let Ok(output) = run_cli(&["rm", "-v", &id]) + && !output.status.success() + { + last_error = Some(failure(&format!("rm {id}"), &output)); + } + } + SharedAction::Refuse => { + return Err(Error::new(format!( + "shared container {name} ({id}) is in unexpected state {state:?}; unpause or remove it manually" + ))); + } + }, + } + // The window starts once this caller's first lookup or start is done, + // so pulling the image is not counted against it. + let deadline = *deadline.get_or_insert_with(|| Instant::now() + SHARED_START_TIMEOUT); + if Instant::now() >= deadline { + // One last look, so a container that just came up is not missed. + if let Some((id, state)) = shared_state(name)? + && shared_action(&state) == SharedAction::Use + && let Ok(addr) = published_addr(&id, port) + { + return Ok(shared(id, addr)); + } + return Err(last_error.unwrap_or_else(|| { + Error::new(format!( + "shared container {name} not running after {SHARED_START_TIMEOUT:?}" + )) + })); + } + std::thread::sleep(backoff.next().unwrap_or(Duration::from_millis(100))); + } } pub fn id(&self) -> &str { @@ -97,25 +156,24 @@ impl Container { } /// Leaves the container running after this handle is dropped and returns - /// its id for a later [`Container::remove`]. + /// its id. Remove it later with [`Container::remove_owned`] and this + /// run's [`crate::process_run_id`], its owner. pub fn detach(mut self) -> String { self.remove_on_drop = false; std::mem::take(&mut self.id) } - /// Force-removes a private container started by this harness, given its - /// full 64-hex id. See [`Container::remove_owned`]. - pub fn remove(id: &str) -> Result<()> { - Self::remove_owned(id, None) - } - - /// Force-removes a private container started by this harness. Refused, - /// never removed: anything but a full 64-hex container id (names and - /// prefixes could match another container), a container whose id differs, - /// one without the harness label, the shared container, and, when - /// `expected_owner` is given, a container another run started. - pub fn remove_owned(id: &str, expected_owner: Option<&str>) -> Result<()> { + /// Force-removes a private container this harness started for run + /// `expected_owner`. Refused, never removed: an empty owner, anything but + /// a full 64-hex container id (names and prefixes could match another + /// container), a container whose id differs, one without the harness + /// label, one not labeled private (the shared container, and containers + /// without the shared label), and a container another run started. + pub fn remove_owned(id: &str, expected_owner: &str) -> Result<()> { let refuse = |why: String| Error::new(format!("refusing to remove container {id:?}: {why}")); + if expected_owner.is_empty() { + return Err(refuse("no expected owner run given".into())); + } if id.len() != 64 || !id.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) { return Err(refuse("expected a full 64-hex container id".into())); } @@ -140,13 +198,13 @@ impl Container { if env != "true" { return Err(refuse(format!("it lacks the {OWNER_LABEL}=true label"))); } - if shared == "true" { - return Err(refuse("it is the machine-wide shared container".into())); + if shared != "false" { + return Err(refuse(format!( + "it is not labeled {SHARED_LABEL}=false (the machine-wide shared container, or an unknown one)" + ))); } - if let Some(expected) = expected_owner - && expected != owner - { - return Err(refuse(format!("it belongs to run {owner:?}, not {expected:?}"))); + if owner != expected_owner { + return Err(refuse(format!("it belongs to run {owner:?}, not {expected_owner:?}"))); } let output = run_cli(&["rm", "-f", "-v", id])?; if output.status.success() { @@ -160,11 +218,33 @@ impl Container { impl Drop for Container { fn drop(&mut self) { if self.remove_on_drop && !self.id.is_empty() { - let _ = Self::remove(&self.id); + let _ = Self::remove_owned(&self.id, process_run_id()); } } } +/// What [`Container::ensure_shared`] does with a shared container found in +/// a given Docker or Podman state. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum SharedAction { + Use, + /// Another caller is creating, restarting or stopping it. + Wait, + /// Stopped for good: remove it and start again. + Clear, + /// Paused or unknown: it may still hold other runs' databases. + Refuse, +} + +fn shared_action(state: &str) -> SharedAction { + match state { + "running" => SharedAction::Use, + "created" | "configured" | "initialized" | "restarting" | "removing" | "stopping" => SharedAction::Wait, + "exited" | "dead" | "stopped" => SharedAction::Clear, + _ => SharedAction::Refuse, + } +} + /// With `name`, the shared container; without, a private one owned by this /// run. fn start(image: &str, port: u16, name: Option<&str>, docker_args: &[&str], command: &[&str]) -> Result { @@ -197,10 +277,12 @@ fn start(image: &str, port: u16, name: Option<&str>, docker_args: &[&str], comma Ok(String::from_utf8_lossy(&output.stdout).trim().to_owned()) } -/// Id of the running, harness-labeled shared container named exactly `name`. -fn running_labeled(name: &str) -> Result> { +/// Id and state (`running`, `created`, `exited`, ...) of the harness-labeled +/// shared container named exactly `name`, in any state. +fn shared_state(name: &str) -> Result> { let output = run_cli(&[ "ps", + "-a", "--no-trunc", "--filter", &format!("label={OWNER_LABEL}=true"), @@ -208,10 +290,8 @@ fn running_labeled(name: &str) -> Result> { &format!("label={SHARED_LABEL}=true"), "--filter", &format!("name=^{name}$"), - "--filter", - "status=running", "--format", - "{{.ID}}", + "{{.ID}}|{{.State}}", ])?; if !output.status.success() { return Err(failure("ps", &output)); @@ -219,9 +299,9 @@ fn running_labeled(name: &str) -> Result> { Ok( String::from_utf8_lossy(&output.stdout) .lines() - .map(str::trim) - .find(|l| !l.is_empty()) - .map(str::to_owned), + .filter_map(|l| l.trim().split_once('|')) + .map(|(id, state)| (id.to_owned(), state.trim().to_ascii_lowercase())) + .next(), ) } @@ -237,3 +317,30 @@ fn published_addr(id: &str, port: u16) -> Result { .find(SocketAddr::is_ipv4) .ok_or_else(|| Error::new(format!("port {id} {port}/tcp returned no IPv4 address: {text:?}"))) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn shared_container_states_map_to_actions() { + let cases = [ + ("running", SharedAction::Use), + ("created", SharedAction::Wait), + ("configured", SharedAction::Wait), + ("initialized", SharedAction::Wait), + ("restarting", SharedAction::Wait), + ("removing", SharedAction::Wait), + ("stopping", SharedAction::Wait), + ("exited", SharedAction::Clear), + ("dead", SharedAction::Clear), + ("stopped", SharedAction::Clear), + ("paused", SharedAction::Refuse), + ("unknown", SharedAction::Refuse), + ("", SharedAction::Refuse), + ]; + for (state, action) in cases { + assert_eq!(shared_action(state), action, "{state:?}"); + } + } +} diff --git a/crates/test-db-harness/tests/services.rs b/crates/test-db-harness/tests/services.rs index b69e3c0f95..5da18ee7c5 100644 --- a/crates/test-db-harness/tests/services.rs +++ b/crates/test-db-harness/tests/services.rs @@ -351,7 +351,8 @@ fn redis_service_answers_and_scopes_keys_by_run_prefix() { } #[test] -fn container_remove_refuses_names_prefixes_foreign_unlabeled_and_shared_containers() { +fn container_remove_refuses_names_prefixes_foreign_unlabeled_unmarked_and_shared_containers() { + let me = test_db_harness::process_run_id(); let running = |id: &str| { let ps = container_cli() .args(["ps", "-q", "--no-trunc", "--filter", &format!("id={id}")]) @@ -359,40 +360,57 @@ fn container_remove_refuses_names_prefixes_foreign_unlabeled_and_shared_containe .unwrap(); !String::from_utf8_lossy(&ps.stdout).trim().is_empty() }; - let refused = |id: &str, owner: Option<&str>| Container::remove_owned(id, owner).unwrap_err().to_string(); + let refused = |id: &str, owner: &str| Container::remove_owned(id, owner).unwrap_err().to_string(); + let run_raw = |labels: &[&str]| { + let mut args = vec!["run", "-d", "--rm"]; + for label in labels { + args.extend(["--label", label]); + } + args.push(test_db_harness::redis::REDIS_IMAGE); + let out = container_cli().args(&args).output().unwrap(); + assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); + String::from_utf8_lossy(&out.stdout).trim().to_owned() + }; - // A container this harness did not start. - let out = container_cli() - .args(["run", "-d", "--rm", test_db_harness::redis::REDIS_IMAGE]) - .output() - .unwrap(); - assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); - let foreign = String::from_utf8_lossy(&out.stdout).trim().to_owned(); - let unlabeled = refused(&foreign, None); - let short = refused(&foreign[..12], None); - let _ = container_cli().args(["rm", "-f", &foreign]).output(); + // Containers this harness did not start, or started before the shared + // label existed: refused even with this run as the expected owner. + let foreign = run_raw(&[]); + let unmarked = run_raw(&["affine.test.env=true", &format!("affine.test.owner={me}")]); + let unlabeled = refused(&foreign, me); + let short = refused(&foreign[..12], me); + let no_shared_label = refused(&unmarked, me); + let no_owner = refused(&unmarked, ""); + for id in [&foreign, &unmarked] { + let _ = container_cli().args(["rm", "-f", id]).output(); + } assert!( unlabeled.contains("lacks the affine.test.env=true label"), "{unlabeled}" ); assert!(short.contains("full 64-hex container id"), "{short}"); + assert!( + no_shared_label.contains("not labeled affine.test.shared=false"), + "{no_shared_label}" + ); + assert!(no_owner.contains("no expected owner"), "{no_owner}"); - // A private container of another run. + // A private container of this run: another run id is refused, its own + // handle removes it. let private = Container::run(test_db_harness::redis::REDIS_IMAGE, 6379, &[], &[]).unwrap(); - let other_run = refused(private.id(), Some("another-run")); + let other_run = refused(private.id(), "another-run"); assert!(other_run.contains("belongs to run"), "{other_run}"); assert!(running(private.id())); let id = private.id().to_owned(); drop(private); assert!(!running(&id), "its own handle removes it"); - Container::remove(&"0".repeat(64)).unwrap(); + Container::remove_owned(&"0".repeat(64), me).unwrap(); // The shared PostgreSQL container, by id or by name. if std::env::var("AFFINE_TEST_PG_URL").is_err() { let cluster = PgCluster::from_env_or_docker().unwrap(); let shared = cluster.container_id().unwrap().to_owned(); - let by_id = refused(&shared, None); - assert!(by_id.contains("machine-wide shared container"), "{by_id}"); + let by_id = refused(&shared, me); + assert!(by_id.contains("affine.test.shared=false"), "{by_id}"); let name = String::from_utf8_lossy( &container_cli() .args(["inspect", "--format", "{{.Name}}", &shared]) @@ -403,11 +421,43 @@ fn container_remove_refuses_names_prefixes_foreign_unlabeled_and_shared_containe .trim() .trim_start_matches('/') .to_owned(); - assert!(refused(&name, None).contains("full 64-hex container id")); + assert!(refused(&name, me).contains("full 64-hex container id")); assert!(running(&shared), "shared container survives"); } } +#[test] +fn shared_container_cold_start_converges_for_concurrent_callers() { + // A fresh name, so all callers race a cold start. + let name = format!("affine-test-env-race-{}", test_db_harness::process_run_id()); + let barrier = Arc::new(Barrier::new(WORKERS)); + let results: Vec<_> = (0..WORKERS) + .map(|_| { + let (barrier, name) = (barrier.clone(), name.clone()); + std::thread::spawn(move || { + barrier.wait(); + Container::ensure_shared( + &name, + test_db_harness::redis::REDIS_IMAGE, + 6379, + &[], + &["redis-server", "--save", "", "--appendonly", "no"], + ) + .map(|c| (c.id().to_owned(), c.addr())) + .map_err(|e| e.to_string()) + }) + }) + .collect::>() + .into_iter() + .map(|h| h.join().unwrap()) + .collect(); + let ids: std::collections::BTreeSet<_> = results.iter().filter_map(|r| r.as_ref().ok()).collect(); + let _ = container_cli().args(["rm", "-f", &name]).output(); + let errors: Vec<_> = results.iter().filter_map(|r| r.as_ref().err()).collect(); + assert!(errors.is_empty(), "every caller gets the container: {errors:?}"); + assert_eq!(ids.len(), 1, "all callers converge on one container and port: {ids:?}"); +} + #[test] fn affine_test_env_cli_up_lease_release_reap_run_json_down() { let work = std::env::temp_dir().join(format!("tdh-cli-{}", test_db_harness::process_run_id())); @@ -549,3 +599,38 @@ fn affine_test_env_cli_up_lease_release_reap_run_json_down() { } let _ = std::fs::remove_dir_all(PathBuf::from(&work)); } + +#[test] +fn paused_shared_container_is_reported_and_kept() { + let name = format!("affine-test-env-paused-{}", test_db_harness::process_run_id()); + let start = || { + Container::ensure_shared( + &name, + test_db_harness::redis::REDIS_IMAGE, + 6379, + &[], + &["redis-server", "--save", "", "--appendonly", "no"], + ) + }; + let id = start().unwrap().id().to_owned(); + let paused = container_cli().args(["pause", &id]).output().unwrap(); + if paused.status.success() { + let refused = start().unwrap_err().to_string(); + let exists = container_cli() + .args(["ps", "-aq", "--no-trunc", "--filter", &format!("id={id}")]) + .output() + .unwrap(); + let _ = container_cli().args(["unpause", &id]).output(); + let _ = container_cli().args(["rm", "-f", &id]).output(); + assert!(refused.contains("unexpected state \"paused\""), "{refused}"); + assert!( + !String::from_utf8_lossy(&exists.stdout).trim().is_empty(), + "paused container kept" + ); + } else { + // This runtime cannot pause; the state table is covered by the unit test + // in src/docker.rs. + let _ = container_cli().args(["rm", "-f", &id]).output(); + eprintln!("pause unsupported: {}", String::from_utf8_lossy(&paused.stderr).trim()); + } +}