diff --git a/CHANGELOG.md b/CHANGELOG.md index 7ed940cd..13922b7f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,16 @@ and listed with their assets on the ### Added +- **The store is warmed for a ref before a lane needs it** (ADR-0065, + #290): `[prepare] warm = ["origin/main"]`. devstack reads the ref every + minute (it never fetches); a new commit, quiet for two minutes, is + checked out under `.devstack/warm/` as git checks it out, with an index + of its own, and each service's `prepare` with `outputs` is made into the + store unless it has the key, in the background. The nodes this + repository's lanes ran on get a warm lease that runs only `prepare` into + the member's store there and ends; a node's policy can refuse them + (`warm = false`), a node before 0.24.0 is not asked. A file with `warm` + says `requires = "0.24.0"`. - **The dashboard shows the store of what `prepare` makes** (ADR-0062, #291). A service's detail view says where its last `prepare` outputs came from: copied out of the store (the key, the copy's time, what `prepare` diff --git a/crates/devstack-config/src/lib.rs b/crates/devstack-config/src/lib.rs index 9cdd786d..f273897a 100644 --- a/crates/devstack-config/src/lib.rs +++ b/crates/devstack-config/src/lib.rs @@ -59,6 +59,10 @@ pub const STOP_SINCE: &str = "0.21.0"; /// (ADR-0062): a file that sets one wants `requires` at least this. pub const OUTPUTS_SINCE: &str = "0.23.0"; +/// The first devstack that knows `[prepare] warm` (ADR-0065): a file that +/// sets it wants `requires` at least this. +pub const WARM_SINCE: &str = "0.24.0"; + /// `"1.2.3"`, `"v1.2"`, `"1"` as numbers; `None` when malformed. A /// pre-release or build suffix (`1.2.3-rc1`, `1.2.3+abc`) is ignored here; /// [`version_order`] takes it into account. diff --git a/crates/devstack-config/src/model.rs b/crates/devstack-config/src/model.rs index 0747fddc..344cf184 100644 --- a/crates/devstack-config/src/model.rs +++ b/crates/devstack-config/src/model.rs @@ -42,12 +42,28 @@ pub struct Stack { /// repository. #[serde(default)] pub agents: Agents, + /// `[prepare]`: the store of what `prepare` makes, beyond one service + /// (ADR-0065). + #[serde(default)] + pub prepare: PrepareSettings, /// The profile this stack runs with, once applied ([`Stack::with_profile`]). #[serde(skip)] #[schemars(skip)] pub profile: Option, } +/// `[prepare]`: the store of what `prepare` makes (ADR-0062), beyond one +/// service. +#[derive(Debug, Clone, Default, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct PrepareSettings { + /// Refs whose `prepare` outputs are made ahead into the store, here and + /// on the nodes this repository's lanes use, e.g. `["origin/main"]` + /// (ADR-0065): devstack watches them, it never fetches. + #[serde(default)] + pub warm: Vec, +} + /// `[agents]`: what devstack writes for the coding agents that work in the /// repository. #[derive(Debug, Clone, Default, Deserialize, JsonSchema)] diff --git a/crates/devstack-config/src/validate.rs b/crates/devstack-config/src/validate.rs index 7d9ed95e..6361b94b 100644 --- a/crates/devstack-config/src/validate.rs +++ b/crates/devstack-config/src/validate.rs @@ -334,6 +334,33 @@ pub fn validate(stack: &Stack) -> Vec { if stack.stack.name.trim().is_empty() { c.err("stack.name", "must not be empty"); } + // A ref devstack hands to git as it is: never an option, never a range. + for r in &stack.prepare.warm { + let bad = r.trim().is_empty() + || r.starts_with('-') + || r.contains("..") + || r.chars() + .any(|ch| ch.is_whitespace() || "~^:?*[\\".contains(ch)); + if bad { + c.err( + "prepare.warm", + format!("`{r}`: a ref such as `origin/main`"), + ); + } + c.literal("prepare.warm", r); + } + if !stack.prepare.warm.is_empty() + && !stack + .services + .values() + .filter_map(|s| s.prepare.as_ref()) + .any(|p| !p.outputs.is_empty()) + { + c.err( + "prepare.warm", + "no service's `prepare` names `outputs`: nothing would be kept to warm", + ); + } if let Some(r) = &stack.stack.requires && crate::version_triple(r).is_none() { @@ -1115,6 +1142,22 @@ pub fn warnings(stack: &Stack) -> Vec { }); } } + let warm = crate::version_order(crate::WARM_SINCE); + if !stack.prepare.warm.is_empty() + && stack + .stack + .requires + .as_deref() + .is_none_or(|r| crate::version_order(r) < warm) + { + out.push(Issue { + path: "prepare.warm".into(), + message: format!( + "a devstack before {v} does not know this key and fails on it with \"unknown field\": `requires = \"{v}\"` makes it ask to be updated instead", + v = crate::WARM_SINCE + ), + }); + } let stop = crate::version_order(crate::STOP_SINCE); if stack .stack diff --git a/crates/devstack-config/tests/stack_files.rs b/crates/devstack-config/tests/stack_files.rs index b7e6280a..d0fdff2f 100644 --- a/crates/devstack-config/tests/stack_files.rs +++ b/crates/devstack-config/tests/stack_files.rs @@ -782,6 +782,45 @@ fn prepare_outputs_are_directories_inside_the_repository_and_hold_its_links() { } } +#[test] +fn prepare_warm_names_refs_and_needs_outputs_to_warm() { + use devstack_config::{WARM_SINCE, validate::warnings}; + let with = |warm: &str, outputs: bool| { + let prep = if outputs { + "{ run = \"npm ci\", outputs = [\"web/node_modules\"] }" + } else { + "{ run = \"npm ci\" }" + }; + format!( + "{}\n[prepare]\nwarm = {warm}\n", + MINIMAL.replace("port = 5000", &format!("port = 5000\nprepare = {prep}")) + ) + }; + let mut s = from_str(&with("[\"origin/main\"]", true), Path::new("t")).unwrap(); + assert_eq!(s.prepare.warm, ["origin/main"]); + assert!( + warnings(&s) + .iter() + .any(|i| i.path == "prepare.warm" && i.message.contains(WARM_SINCE)) + ); + s.stack.requires = Some(WARM_SINCE.into()); + assert!(warnings(&s).iter().all(|i| i.path != "prepare.warm")); + for bad in ["--upload-pack=x", "main..dev", "a b", "HEAD~1", "x:y", " "] { + let issues = invalid(&with(&format!("[\"{bad}\"]"), true)); + assert!( + issues.iter().any(|i| i.contains("prepare.warm")), + "{bad}: {issues:?}" + ); + } + let issues = invalid(&with("[\"origin/main\"]", false)); + assert!( + issues + .iter() + .any(|i| i.contains("nothing would be kept to warm")), + "{issues:?}" + ); +} + #[test] fn working_directories_and_the_output_stay_inside_the_repository() { let issues = invalid(&format!( diff --git a/crates/devstack-daemon/src/api.rs b/crates/devstack-daemon/src/api.rs index 2cf32be1..0449cd16 100644 --- a/crates/devstack-daemon/src/api.rs +++ b/crates/devstack-daemon/src/api.rs @@ -38,6 +38,7 @@ pub fn router(state: AppState) -> axum::Router { axum::Router::new() .route("/v1/stack", get(stack)) .route("/v1/telemetry/take", post(telemetry_take)) + .route("/v1/warm", get(warm_view)) .route("/v1/up", post(up)) .route("/v1/down", post(down)) .route("/v1/shutdown", post(shutdown)) @@ -221,6 +222,12 @@ async fn stack(State(s): State) -> Response { Json(s.sup.view()).into_response() } +/// `GET /v1/warm`: in a warm lease's container on a node, whether its +/// `prepare` runs are done and what each did (ADR-0065 point 5). +async fn warm_view() -> Response { + Json(crate::warm::lane_view()).into_response() +} + /// `POST /v1/telemetry/take`: in the daemon of a lane on a node, the /// diagnostic lines kept since the last take, for its requester to send /// under its consent (#287); `{"lines": []}` elsewhere. diff --git a/crates/devstack-daemon/src/lanes.rs b/crates/devstack-daemon/src/lanes.rs index ade5cce5..6690524f 100644 --- a/crates/devstack-daemon/src/lanes.rs +++ b/crates/devstack-daemon/src/lanes.rs @@ -256,6 +256,9 @@ struct Worktree { /// or removable drive gone for a moment) before its lane is forgotten, with /// its containers and volumes. A worktree removed with git goes at once. const MISSING_GRACE: std::time::Duration = std::time::Duration::from_secs(10 * 60); +/// The lane name of a warm lease (ADR-0065 point 5), then the ref: a +/// worktree's lane name never has `--` (`lane_name` folds them). +const WARM_LANE: &str = "warm--"; /// How often the worktrees of lanes on nodes are checked for their links /// (ADR-0063): their inputs read, a copy or `prepare` only when they changed. const NODE_LINKS_EVERY: std::time::Duration = std::time::Duration::from_secs(15); @@ -888,6 +891,7 @@ impl Lanes { })); me.follow(); me.follow_node_links(); + me.follow_warm(); me } @@ -1109,6 +1113,150 @@ impl Lanes { }); } + /// Warm the store for the refs of `[prepare] warm` (ADR-0065): here, + /// then on the nodes this repository's lanes use. One ref at a time, in + /// the background, under the one-`prepare`-at-a-time lock. + pub fn follow_warm(self: &Arc) { + if self.main.stack.prepare.warm.is_empty() || crate::remote_lane() { + return; + } + let weak = Arc::downgrade(self); + let _ = std::thread::Builder::new() + .name("lanes-warm".into()) + .spawn(move || { + let mut watch = crate::warm::Watch::default(); + loop { + std::thread::sleep(crate::warm::every()); + let Some(me) = weak.upgrade() else { return }; + if me.main.closed() { + return; + } + for (r, commit) in watch.due(&me.main) { + let closed = || me.main.closed(); + match crate::warm::warm_here(&me.main, &r, &commit, &closed) { + Ok(checkout) => { + drop(checkout); + me.warm_nodes(&r, &commit, &closed); + crate::warm::note_done(&me.main, &r, &commit); + } + Err(e) => crate::diag::warn( + "prepare_warm_failed", + serde_json::json!({ "ref": r, "commit": commit, "error": e }), + ), + } + } + } + }); + } + + /// The nodes this repository's lanes use, warmed for the commit checked + /// out at `checkout` (ADR-0065 point 5). + fn warm_nodes(&self, r: &str, commit: &str, cancel: &dyn Fn() -> bool) { + let repo = self.main.stack.stack.name.clone(); + // The nodes this repository's lanes ran on, while one of them is + // kept or runs there, and that know warm leases. + let mut nodes: Vec = Vec::new(); + let names: Vec = self.known.lock().unwrap().keys().cloned().collect(); + for name in names { + for on in crate::remote::ran_on(&self.state_dir(&name)) { + if !nodes.iter().any(|n| n.node.id == on.node.id) { + nodes.push(on); + } + } + } + nodes.retain(|on| { + crate::remote::slots_on(&self.rt, &on.pool, on.node.clone()).is_ok_and(|slots| { + slots + .iter() + .any(|s| s.repo == repo && !s.lane.starts_with(WARM_LANE)) + }) + }); + if nodes.is_empty() { + return; + } + // A checkout of its own: the one warmed here holds this machine's + // outputs, which are not the node's. + let checkout = match crate::warm::Checkout::new(&self.main, r, commit, "node") + .and_then(|co| co.completer()().map(|()| co)) + { + Ok(co) => co, + Err(e) => { + crate::diag::warn( + "prepare_warm_failed", + serde_json::json!({ "ref": r, "commit": commit, "place": "remote", "error": e }), + ); + return; + } + }; + let slug: String = r + .chars() + .map(|c| { + if c.is_ascii_alphanumeric() { + c.to_ascii_lowercase() + } else { + '-' + } + }) + .collect(); + let lane = format!("{WARM_LANE}{slug}"); + let stack_file = self.stack_file_rel().to_string_lossy().replace('\\', "/"); + let synced = self.synced(); + let scratch = self + .main + .state_dir + .join("warm") + .join(format!("{slug}-remote")); + let need = crate::remote::Expected::default(); + for on in nodes { + if cancel() { + return; + } + let t0 = std::time::Instant::now(); + let spec = crate::remote::RemoteSpec { + name: &lane, + repo: &repo, + worktree: &checkout.src, + main: &self.main.repo, + extra: &synced, + sharing: None, + stack_file: &stack_file, + on: &on.node.id, + need: &need, + floor: None, + scratch: &scratch, + ports: Vec::new(), + port_offset: 0, + forward: false, + step: &|_, _| {}, + profile: None, + warm: true, + }; + match RemoteLane::warm(&self.rt, spec, cancel) { + Ok(results) => { + for x in results { + let event = if x["error"].is_string() { + "prepare_warm_failed" + } else { + "prepare_warmed" + }; + crate::diag::info( + event, + serde_json::json!({ "service": x["service"], "ref": r, + "commit": commit, "place": "remote", "node": on.node.name, + "done": x["done"], "error": x["error"], "ms": x["ms"] }), + ); + } + } + Err(e) => crate::diag::warn( + "prepare_warm_failed", + serde_json::json!({ "ref": r, "commit": commit, "place": "remote", + "node": on.node.name, "error": e, + "ms": t0.elapsed().as_millis() as u64 }), + ), + } + } + } + /// Keep the worktree of every lane on a node linked to a copy on this /// machine of what its `prepare` makes (ADR-0063), every /// [`NODE_LINKS_EVERY`]: a look at its inputs while nothing changed; a @@ -3088,6 +3236,7 @@ impl Lanes { forward, step, profile: profile.as_deref(), + warm: false, }) } diff --git a/crates/devstack-daemon/src/lib.rs b/crates/devstack-daemon/src/lib.rs index 12347a88..8c246368 100644 --- a/crates/devstack-daemon/src/lib.rs +++ b/crates/devstack-daemon/src/lib.rs @@ -23,6 +23,7 @@ pub mod timeline; pub mod token; pub mod udprelay; pub mod usage; +pub(crate) mod warm; pub mod watch; use serde::{Deserialize, Serialize}; @@ -293,6 +294,10 @@ pub fn serve(stack_file: &Path) -> Result<(), String> { let _watcher = watch::start(sup.clone()); // A dev server's rebuilds, from its output (ADR-0042). sup.follow_rebuilds(); + // A warm lease on a node runs `prepare` only (ADR-0065 point 5). + if warm::warm_lease() { + warm::run_lane(sup.clone()); + } let served = rt.block_on(async move { let listener = match listen_addr()? { diff --git a/crates/devstack-daemon/src/remote.rs b/crates/devstack-daemon/src/remote.rs index 5b9402b4..7205f113 100644 --- a/crates/devstack-daemon/src/remote.rs +++ b/crates/devstack-daemon/src/remote.rs @@ -22,6 +22,10 @@ const FULL_SYNC_EVERY: Duration = Duration::from_secs(30); const RENEW_EVERY: Duration = Duration::from_secs(30); /// How long a lease lives without a renewal (the node's TTL), and a margin. const LEASE_LIVES: Duration = Duration::from_secs(150); +/// How long a warm lease's `prepare` runs may take (ADR-0065 point 5). +const WARM_WITHIN: Duration = Duration::from_secs(30 * 60); +/// The first devstack whose node takes warm leases. +const WARM_SINCE_NODE: &str = "0.24.0"; /// How often the lane's state is read for the lists. const STATE_EVERY: Duration = Duration::from_secs(5); /// How often what the lane's daemon logged is taken for telemetry (#287): @@ -388,6 +392,8 @@ pub struct RemoteSpec<'a> { pub step: &'a (dyn Fn(u8, &str) + Send + Sync), /// The profile it runs with (ADR-0041). pub profile: Option<&'a str>, + /// A warm lease (ADR-0065 point 5): only `prepare`, no infrastructure. + pub warm: bool, } /// What a lane is expected to need as this machine estimates it (ADR-0049 @@ -563,6 +569,7 @@ impl RemoteLane { floor: spec.floor, profile: spec.profile.map(str::to_string), devstack: Some(Release::this()), + warm: spec.warm, }) .map_err(|e| format!("lease on `{}`: {e}", spec.on))?; // Another pool protocol misreads this machine (a newer coordinator @@ -661,6 +668,98 @@ impl RemoteLane { }) } + /// A warm lease on a node (ADR-0065 point 5): leased, `spec.worktree` (a + /// ref's checkout) synced as its mirror, started there (its container + /// runs only the `prepare` the member's store lacks), asked until its + /// runs are done, released. What each service's run did. + pub fn warm( + rt: &tokio::runtime::Handle, + spec: RemoteSpec<'_>, + cancel: &dyn Fn() -> bool, + ) -> Result, String> { + let Leased { + offer, + client, + list, + elsewhere, + .. + } = Self::lease(rt, &spec)?; + // A node that does not know warm leases would start a whole lane: it + // runs this release or a later one, or exactly this devstack. + let node_version = offer.node.devstack.as_ref().map(|r| r.version.as_str()); + let knows = node_version.and_then(devstack_config::version_order) + >= devstack_config::version_order(WARM_SINCE_NODE) + || node_version == Some(devstack_config::VERSION); + if !knows { + let _ = rt.block_on(client.release(&offer.id)); + return Err(format!( + "{} runs a devstack before {WARM_SINCE_NODE}, which takes no warm leases", + offer.node.name + )); + } + let renewing = { + let client = client.clone(); + let lease = offer.id.clone(); + rt.spawn(async move { + loop { + tokio::time::sleep(RENEW_EVERY).await; + let _ = client.renew(&lease).await; + } + }) + }; + let ran = (|| { + let mut hashes = HashCache::default(); + rt.block_on(client.sync_cached( + &offer.id, + spec.worktree, + &list, + &elsewhere, + &mut hashes, + &|_, _, _| {}, + )) + .map_err(|e| format!("sync: {e}"))?; + rt.block_on(client.start( + &offer.id, + spec.stack_file, + None, + 0, + None, + false, + Duration::from_secs(1800), + &|_| {}, + &|_, _| {}, + )) + .map_err(|e| format!("start: {e}"))?; + let until = Instant::now() + WARM_WITHIN; + loop { + if cancel() { + return Err("stopped".to_string()); + } + match rt.block_on(client.api(&offer.id, "GET", "/v1/warm", None)) { + Ok((200, body)) => { + if let Ok(v) = serde_json::from_str::(&body) + && v["done"] == true + { + return Ok(v["results"].as_array().cloned().unwrap_or_default()); + } + } + Ok((404, _)) => return Err("the lane's daemon runs no warm lease".into()), + _ => {} + } + if Instant::now() >= until { + return Err(format!( + "not done within {} min", + WARM_WITHIN.as_secs() / 60 + )); + } + std::thread::sleep(Duration::from_secs(2)); + } + })(); + renewing.abort(); + let _ = rt.block_on(client.release(&offer.id)); + ran + } + /// The rest of a start, which may take minutes (a first start pulls and /// builds images on the node): sync (step 2), start there (step 3), /// follow it. On failure the lease is released. diff --git a/crates/devstack-daemon/src/supervisor/copy.rs b/crates/devstack-daemon/src/supervisor/copy.rs index 8543d263..4402c32c 100644 --- a/crates/devstack-daemon/src/supervisor/copy.rs +++ b/crates/devstack-daemon/src/supervisor/copy.rs @@ -620,6 +620,93 @@ impl Supervisor { report(&views); } + /// `prepare` of `name` for a ref checked out at `root` (ADR-0065 + /// points 3, 4): there are the files of its `inputs` at least, and + /// `complete` checks out the rest. The key is a copy's, over those + /// files as git checked them out. `Ok(Warmed::Had)` when the store has + /// it; else the checkout is completed and prepared, and its outputs go + /// into the store. + pub(crate) fn warm_service( + &self, + name: &str, + svc: &Service, + root: &Path, + complete: Box Result<(), String> + Send>, + cancel: &dyn Fn() -> bool, + ) -> Result { + let Some(p) = svc.prepare.as_ref().filter(|p| !p.outputs.is_empty()) else { + return Err("its `prepare` names no `outputs`".into()); + }; + let globs = devstack_build::watch_set(&p.inputs).map_err(|e| e.to_string())?; + let mut files: Vec<(String, String)> = Vec::new(); + let wanted = |rel: &str| globs.as_ref().is_some_and(|g| g.is_match(rel)); + collect_files(root, root, &wanted, &mut files); + files.sort(); + let hashed = files.iter().map(|(rel, hash)| (rel.as_str(), hash.clone())); + let key = prepare_key(p, svc, hashed)?; + let cwd = p.cwd.as_ref().or(svc.cwd.as_ref()); + let job = PrepareJob { + key, + mark: root.parent().unwrap_or(root).join("prepared").join(name), + cwd: cwd.map_or_else(|| root.to_path_buf(), |c| root.join(c)), + run: p.run.clone(), + store: Ok(StoreUse { + root: root.to_path_buf(), + outputs: p.outputs.clone(), + version: p.version.clone(), + }), + before_run: Some(complete), + }; + let key = match self.store_key(name, &job, cancel)? { + Ok(k) => k, + Err(why) => return Err(why.unwrap_or_else(|| "it does not use the store".into())), + }; + if self.store().get(name, &key).is_some() { + return Ok(Warmed::Had(key)); + } + let t0 = Instant::now(); + self.run_prepare(name, job, cancel)?; + Ok(Warmed::Made(key, t0.elapsed())) + } + + /// In a warm lease's container (ADR-0065 point 5): `prepare` of every + /// service whose `prepare` names `outputs`, in the lane's copy, from the + /// member's store or run into it; what each did, for the requester. + pub(crate) fn warm_lane(&self, cancel: &dyn Fn() -> bool) -> Vec { + let mut out = Vec::new(); + for (name, svc) in &self.stack.services { + if svc.prepare.as_ref().is_none_or(|p| p.outputs.is_empty()) { + continue; + } + let t0 = Instant::now(); + let job = { + let mut snap = self.snapshot.lock().unwrap(); + snap.sync() + .map_err(|e| e.to_string()) + .and_then(|_| self.prepare_job(name, svc, &snap)) + }; + let done = match job { + Ok(None) => Ok("prepared before"), + Ok(Some(job)) => self.run_prepare(name, job, cancel).map(|v| { + let how = if v.source == "store" { + "from the store" + } else { + "prepared" + }; + self.set_prepare(name, v); + how + }), + Err(e) => Err(e), + }; + out.push(match done { + Ok(how) => serde_json::json!({ "service": name, "done": how, + "ms": t0.elapsed().as_millis() as u64 }), + Err(e) => serde_json::json!({ "service": name, "error": e }), + }); + } + out + } + /// The links [`Self::link_node_lane`] made in `worktree`, removed: the /// lane stopped, moved or went (ADR-0044 point 3 holds for them too). pub(crate) fn unlink_node_lane( @@ -1013,6 +1100,40 @@ pub struct NodeLink { pub why: Option, } +/// What [`Supervisor::warm_service`] did, with the store's key. +pub enum Warmed { + /// The store had it. + Had(String), + /// Prepared, in this long. + Made(String, Duration), +} + +/// The files below `dir` that `keep` wants, as paths below `root` with `/` +/// and the blake3 of their content: what a copy's manifest says of them. +fn collect_files( + root: &Path, + dir: &Path, + keep: &dyn Fn(&str) -> bool, + out: &mut Vec<(String, String)>, +) { + for e in std::fs::read_dir(dir).into_iter().flatten().flatten() { + let path = e.path(); + if e.file_type().is_ok_and(|t| t.is_dir()) { + collect_files(root, &path, keep, out); + continue; + } + let Ok(rel) = path.strip_prefix(root) else { + continue; + }; + let rel = rel.to_string_lossy().replace('\\', "/"); + if keep(&rel) + && let Ok(bytes) = std::fs::read(&path) + { + out.push((rel, blake3::hash(&bytes).to_hex().to_string())); + } + } +} + /// What [`link_one`] did. enum Linked { Made, @@ -1236,6 +1357,118 @@ mod tests { assert!(std::fs::symlink_metadata(wt.join("deps")).is_err()); } + /// A repository with one commit of `files`, and its main tree's + /// supervisor for `stack`. + fn warm_repo( + d: &Path, + stack: &str, + files: &[(&str, &str)], + rt: &tokio::runtime::Runtime, + ) -> Arc { + let git = |args: &[&str]| { + let ok = std::process::Command::new("git") + .args(["-c", "user.name=t", "-c", "user.email=t@t"]) + .args(args) + .current_dir(d) + .status() + .unwrap(); + assert!(ok.success(), "git {args:?}"); + }; + git(&["init", "-q"]); + git(&["config", "core.autocrlf", "false"]); + std::fs::write(d.join(".gitignore"), ".devstack\ndeps\n").unwrap(); + for (rel, text) in files { + std::fs::write(d.join(rel), text).unwrap(); + } + git(&["add", "-A"]); + git(&["commit", "-qm", "init"]); + let stack = devstack_config::from_str(stack, Path::new("t")).unwrap(); + Supervisor::new( + stack, + d.join("devstack.toml"), + d.to_path_buf(), + d.join(".devstack"), + devstack_proc::Options::default(), + rt.handle().clone(), + ) + .unwrap() + } + + const WARM_STACK: &str = "version = 1\n[stack]\nname = \"t\"\n[prepare]\nwarm = [\"HEAD\"]\n[services.web]\nkind = \"devserver\"\nrun = \"x\"\nport = 4200\nprepare = { run = \"mkdir deps && echo made> deps\\\\made.txt\", inputs = [\"package-lock.json\"], outputs = [\"deps\"] }\n"; + + #[test] + fn a_ref_whose_key_the_store_has_is_warm_after_its_inputs_are_read() { + let rt = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .unwrap(); + let d = tempfile::tempdir().unwrap(); + let sup = warm_repo( + d.path(), + WARM_STACK, + &[("package-lock.json", "{\"v\":1}"), ("app.js", "1")], + &rt, + ); + let svc = &sup.stack.services["web"]; + let p = svc.prepare.as_ref().unwrap(); + let key = prepare_key( + p, + svc, + [( + "package-lock.json", + blake3::hash(b"{\"v\":1}").to_hex().to_string(), + )] + .into_iter(), + ) + .unwrap(); + let made = d.path().join("made"); + std::fs::create_dir_all(made.join("deps")).unwrap(); + std::fs::write(made.join("deps/a.txt"), "a").unwrap(); + sup.store() + .put( + "web", + &store_key_of(&key, None), + &made, + &p.outputs, + Duration::ZERO, + ) + .unwrap(); + let co = crate::warm::warm_here(&sup, "HEAD", "HEAD", &|| false).unwrap(); + // Only the inputs were checked out: the store had the key. + assert!(co.src.join("package-lock.json").is_file()); + assert!(!co.src.join("app.js").exists()); + assert_eq!(sup.store().entries().len(), 1); + assert!(sup.notices().is_empty(), "{:?}", sup.notices()); + let dir = co.src.parent().unwrap().to_path_buf(); + drop(co); + assert!(!dir.exists(), "the checkout goes"); + } + + #[cfg(windows)] + #[test] + fn a_ref_whose_key_the_store_lacks_is_prepared_into_it() { + let rt = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .unwrap(); + let d = tempfile::tempdir().unwrap(); + let sup = warm_repo( + d.path(), + WARM_STACK, + &[("package-lock.json", "{\"v\":2}"), ("app.js", "1")], + &rt, + ); + let co = crate::warm::warm_here(&sup, "HEAD", "HEAD", &|| false).unwrap(); + assert!(co.src.join("app.js").is_file(), "the whole ref, to prepare"); + let entries = sup.store().entries(); + assert_eq!(entries.len(), 1, "{:?}", sup.notices()); + assert_eq!(entries[0].0.outputs, ["deps"]); + // A second look: the store has it now. + drop(co); + let co = crate::warm::warm_here(&sup, "HEAD", "HEAD", &|| false).unwrap(); + assert!(!co.src.join("app.js").exists()); + } + #[test] fn the_store_lists_its_entries_with_who_used_them_and_removes_one() { let d = tempfile::tempdir().unwrap(); diff --git a/crates/devstack-daemon/src/supervisor/mod.rs b/crates/devstack-daemon/src/supervisor/mod.rs index fbda088f..17504471 100644 --- a/crates/devstack-daemon/src/supervisor/mod.rs +++ b/crates/devstack-daemon/src/supervisor/mod.rs @@ -26,7 +26,9 @@ use tokio::sync::broadcast; mod artifacts; mod candidate; mod copy; -pub use copy::{NodeLink, StoreEntryView, StoreRemoveError, StoreView, store_remove, store_view}; +pub use copy::{ + NodeLink, StoreEntryView, StoreRemoveError, StoreView, Warmed, store_remove, store_view, +}; mod handover; mod infra; pub use infra::ContainerTarget; diff --git a/crates/devstack-daemon/src/warm.rs b/crates/devstack-daemon/src/warm.rs new file mode 100644 index 00000000..b8253c9b --- /dev/null +++ b/crates/devstack-daemon/src/warm.rs @@ -0,0 +1,332 @@ +//! The store of what `prepare` makes, warmed for refs before a lane needs +//! it (ADR-0065). devstack watches the refs of `[prepare] warm`, it never +//! fetches them; a new commit, unchanged for [`QUIET`], is checked out +//! beside the repository with an index of its own, and each service's +//! `prepare` with `outputs` is made into the store unless the store has its +//! key already. + +use crate::state::NoticeLevel; +use crate::supervisor::{Supervisor, Warmed}; +use std::collections::BTreeMap; +use std::io::Write; +use std::path::{Path, PathBuf}; +use std::process::{Command, Stdio}; +use std::sync::Arc; +use std::time::{Duration, Instant}; + +/// How often the refs are read. +const EVERY: Duration = Duration::from_secs(60); +/// How long a ref's new commit stays before it is warmed: a fetch, a pull, +/// a merge done. +const QUIET: Duration = Duration::from_secs(120); + +/// [`EVERY`], or `DEVSTACK_WARM_EVERY_MS` (tests). +pub(crate) fn every() -> Duration { + from_env("DEVSTACK_WARM_EVERY_MS").unwrap_or(EVERY) +} + +/// [`QUIET`], or `DEVSTACK_WARM_QUIET_MS` (tests). +fn quiet() -> Duration { + from_env("DEVSTACK_WARM_QUIET_MS").unwrap_or(QUIET) +} + +fn from_env(k: &str) -> Option { + std::env::var(k) + .ok()? + .trim() + .parse() + .ok() + .map(Duration::from_millis) +} + +/// In a warm lease's container: what its `prepare` runs did, once done. +static LANE: std::sync::Mutex>> = std::sync::Mutex::new(None); + +/// This daemon runs a warm lease on a node (`DEVSTACK_WARM`, ADR-0065 +/// point 5). +pub(crate) fn warm_lease() -> bool { + crate::remote_lane() && std::env::var_os("DEVSTACK_WARM").is_some_and(|v| v == "1") +} + +/// In a warm lease's container: its `prepare` runs, in the background; what +/// they did is `GET /v1/warm`'s once done. +pub(crate) fn run_lane(sup: Arc) { + let _ = std::thread::Builder::new() + .name("warm".into()) + .spawn(move || { + let done = sup.warm_lane(&|| sup.closed()); + *LANE.lock().unwrap() = Some(done); + }); +} + +/// `GET /v1/warm`: whether this daemon runs a warm lease, and what its +/// `prepare` runs did once they are done. +pub(crate) fn lane_view() -> serde_json::Value { + let done = LANE.lock().unwrap().clone(); + serde_json::json!({ "warm": warm_lease(), "done": done.is_some(), + "results": done.unwrap_or_default() }) +} + +/// What a daemon saw of the refs: each one's commit, and since when. +#[derive(Default)] +pub(crate) struct Watch { + seen: BTreeMap, +} + +impl Watch { + /// The refs to warm now, with their commit: new, quiet for long enough, + /// and not warmed before (the note survives a daemon's restart). + pub(crate) fn due(&mut self, sup: &Supervisor) -> Vec<(String, String)> { + let done = load_done(&done_file(sup)); + let mut out = Vec::new(); + for r in &sup.stack.prepare.warm { + let Some(commit) = rev_parse(&sup.repo, r) else { + continue; + }; + let e = self + .seen + .entry(r.clone()) + .or_insert_with(|| (commit.clone(), Instant::now())); + if e.0 != commit { + *e = (commit.clone(), Instant::now()); + } + if e.1.elapsed() >= quiet() && done.get(r) != Some(&commit) { + out.push((r.clone(), commit)); + } + } + out + } +} + +/// Where the commits warmed last are noted, by ref. +fn done_file(sup: &Supervisor) -> PathBuf { + sup.state_dir.join("warm").join("done.json") +} + +fn load_done(file: &Path) -> BTreeMap { + std::fs::read(file) + .ok() + .and_then(|b| serde_json::from_slice(&b).ok()) + .unwrap_or_default() +} + +/// `r`'s commit was warmed: not again, not after a restart either. +pub(crate) fn note_done(sup: &Supervisor, r: &str, commit: &str) { + let file = done_file(sup); + let mut done = load_done(&file); + done.insert(r.to_string(), commit.to_string()); + if let Some(dir) = file.parent() { + let _ = std::fs::create_dir_all(dir); + } + let _ = std::fs::write(&file, serde_json::to_vec_pretty(&done).unwrap_or_default()); +} + +/// The commit `r` names, if it names one. +fn rev_parse(repo: &Path, r: &str) -> Option { + let out = Command::new("git") + .args([ + "rev-parse", + "--verify", + "--quiet", + &format!("{r}^{{commit}}"), + ]) + .current_dir(repo) + .stdin(Stdio::null()) + .stderr(Stdio::null()) + .output() + .ok()?; + let c = String::from_utf8_lossy(&out.stdout).trim().to_string(); + (out.status.success() && !c.is_empty()).then_some(c) +} + +/// A commit checked out beside the repository as git checks it out (line +/// endings, filters), with an index of its own: the main tree's index, +/// worktree and list of worktrees stay as they are. Removed when dropped. +pub(crate) struct Checkout { + repo: PathBuf, + dir: PathBuf, + index: PathBuf, + /// The checked-out files: what a copy of the ref would hold. + pub src: PathBuf, +} + +impl Checkout { + pub(crate) fn new(sup: &Supervisor, r: &str, commit: &str, tag: &str) -> Result { + let slug: String = r + .chars() + .map(|c| if c.is_ascii_alphanumeric() { c } else { '-' }) + .collect(); + let dir = sup + .state_dir + .join("warm") + .join(format!("{slug}-{}{tag}", &commit[..commit.len().min(12)])); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(dir.join("src")).map_err(|e| e.to_string())?; + let co = Self { + repo: sup.repo.clone(), + index: dir.join("index"), + src: dir.join("src"), + dir, + }; + co.git(&["read-tree", commit], None)?; + Ok(co) + } + + /// `git` in the repository with this checkout's index; `input` on stdin. + fn git(&self, args: &[&str], input: Option<&[u8]>) -> Result { + let mut child = Command::new("git") + .args(args) + .current_dir(&self.repo) + .env("GIT_INDEX_FILE", &self.index) + .stdin(if input.is_some() { + Stdio::piped() + } else { + Stdio::null() + }) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .map_err(|e| format!("git: {e}"))?; + if let (Some(input), Some(mut stdin)) = (input, child.stdin.take()) { + stdin.write_all(input).map_err(|e| e.to_string())?; + } + let out = child.wait_with_output().map_err(|e| e.to_string())?; + if !out.status.success() { + return Err(format!( + "git {}: {}", + args.first().copied().unwrap_or(""), + String::from_utf8_lossy(&out.stderr).trim() + )); + } + Ok(String::from_utf8_lossy(&out.stdout).into_owned()) + } + + /// The commit's files, as paths below the repository. + pub(crate) fn files(&self) -> Result, String> { + Ok(self + .git(&["ls-files", "-z"], None)? + .split('\0') + .filter(|f| !f.is_empty()) + .map(str::to_string) + .collect()) + } + + fn prefix(&self) -> String { + format!("{}/", self.src.to_string_lossy().replace('\\', "/")) + } + + /// `files` of the commit checked out. + pub(crate) fn check_out(&self, files: &[&String]) -> Result<(), String> { + if files.is_empty() { + return Ok(()); + } + let mut list = Vec::new(); + for f in files { + list.extend_from_slice(f.as_bytes()); + list.push(0); + } + let prefix = format!("--prefix={}", self.prefix()); + self.git( + &["checkout-index", "-f", "-z", "--stdin", &prefix], + Some(&list), + ) + .map(|_| ()) + } + + /// What completes the checkout, once, for `prepare` to run in it. + pub(crate) fn completer(&self) -> Box Result<(), String> + Send> { + let (repo, index, prefix, mark) = ( + self.repo.clone(), + self.index.clone(), + self.prefix(), + self.dir.join("complete"), + ); + Box::new(move || { + if mark.is_file() { + return Ok(()); + } + let out = Command::new("git") + .args(["checkout-index", "-a", "-f", &format!("--prefix={prefix}")]) + .current_dir(&repo) + .env("GIT_INDEX_FILE", &index) + .stdin(Stdio::null()) + .output() + .map_err(|e| format!("git: {e}"))?; + if !out.status.success() { + return Err(format!( + "git checkout-index: {}", + String::from_utf8_lossy(&out.stderr).trim() + )); + } + std::fs::write(&mark, "").map_err(|e| e.to_string()) + }) + } +} + +impl Drop for Checkout { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.dir); + } +} + +/// Warm the store here for commit `commit` of ref `r` (ADR-0065 points 3, +/// 4): each service whose `prepare` names `outputs`, its inputs checked out +/// first, the rest only for a key the store lacks. Said in the diagnostic +/// log, a failure as a notice once per commit. The checkout, for the nodes. +pub(crate) fn warm_here( + sup: &Arc, + r: &str, + commit: &str, + cancel: &dyn Fn() -> bool, +) -> Result { + let co = Checkout::new(sup, r, commit, "")?; + let files = co.files()?; + for (name, svc) in &sup.stack.services { + let Some(p) = svc.prepare.as_ref().filter(|p| !p.outputs.is_empty()) else { + continue; + }; + if cancel() { + break; + } + let globs = devstack_build::watch_set(&p.inputs).ok().flatten(); + let inputs: Vec<&String> = files + .iter() + .filter(|f| globs.as_ref().is_some_and(|g| g.is_match(f.as_str()))) + .collect(); + let id = format!("prepare.warm.{name}"); + let warmed = co + .check_out(&inputs) + .and_then(|()| sup.warm_service(name, svc, &co.src, co.completer(), cancel)); + match warmed { + Ok(w) => { + sup.clear_notice(&id); + let (key, ms, had) = match w { + Warmed::Had(k) => (k, 0, true), + Warmed::Made(k, d) => (k, d.as_millis() as u64, false), + }; + crate::diag::info( + "prepare_warmed", + serde_json::json!({ "service": name, "key": key, "ref": r, + "commit": commit, "place": "local", "had": had, "ms": ms }), + ); + } + Err(e) if cancel() => return Err(e), + Err(e) => { + crate::diag::warn( + "prepare_warm_failed", + serde_json::json!({ "service": name, "ref": r, "commit": commit, + "place": "local", "error": e }), + ); + sup.set_notice( + &id, + NoticeLevel::Warn, + format!( + "`prepare` of {name} could not be warmed for `{r}` ({}): {e}. The first lane on that commit prepares itself.", + &commit[..commit.len().min(12)] + ), + ); + } + } + } + Ok(co) +} diff --git a/crates/devstack-hub/src/share.rs b/crates/devstack-hub/src/share.rs index 73a28f7b..8ed044c2 100644 --- a/crates/devstack-hub/src/share.rs +++ b/crates/devstack-hub/src/share.rs @@ -406,6 +406,7 @@ mod tests { floor: None, profile: None, devstack: None, + warm: false, }) .unwrap(); let rt = rt(); diff --git a/crates/devstack-node/src/coordinator.rs b/crates/devstack-node/src/coordinator.rs index 3cca2338..13cb20dc 100644 --- a/crates/devstack-node/src/coordinator.rs +++ b/crates/devstack-node/src/coordinator.rs @@ -627,6 +627,10 @@ pub struct LeaseRequest { /// node with the same pool protocol only. Absent from older requesters. #[serde(default, skip_serializing_if = "Option::is_none")] pub devstack: Option, + /// A warm lease (ADR-0065 point 5): the lane's container runs only the + /// `prepare` its member's store lacks, no infrastructure, then ends. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub warm: bool, } /// A member that runs lanes, as a requester reaches it. @@ -688,6 +692,10 @@ pub struct Lease { /// Whom its owner shares the lane with, and which services (ADR-0035). #[serde(default, skip_serializing_if = "Option::is_none")] pub shared: Option, + /// A warm lease (ADR-0065 point 5): the lane's container runs only the + /// `prepare` its member's store lacks, no infrastructure, then ends. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub warm: bool, } /// A lane shared with others in the pool (ADR-0035). @@ -1269,6 +1277,7 @@ async fn report( created: store::now(), expires_in: Some(x.expires_in), shared: None, + warm: false, }, // Admitted already: no node asks for it by token again. random_hex(24), @@ -1487,6 +1496,7 @@ async fn placement( floor: None, profile: q.profile.filter(|p| !p.is_empty()), devstack: Some(Release::this()), + warm: false, }; Ok(Json(placement_for(&s, &ms, &me, &r, true))) } @@ -1673,6 +1683,7 @@ async fn lease_create( created: store::now(), expires_in: None, shared: None, + warm: r.warm, }; leases.insert( id.clone(), @@ -2543,6 +2554,7 @@ mod placement_tests { created: 0, expires_in: None, shared: None, + warm: false, }, String::new(), std::time::Instant::now(), diff --git a/crates/devstack-node/src/lanerun.rs b/crates/devstack-node/src/lanerun.rs index 78f791d8..d65dcefa 100644 --- a/crates/devstack-node/src/lanerun.rs +++ b/crates/devstack-node/src/lanerun.rs @@ -84,6 +84,9 @@ pub struct LaneRun { /// (ADR-0062 point 3), mounted read-only at [`STORE_MOUNT`]; `None`: /// the lane gets none. pub store: Option, + /// A warm lease (ADR-0065 point 5): no infrastructure, and the lane's + /// daemon runs only `prepare` (`DEVSTACK_WARM`). + pub warm: bool, } /// Where a lane's container sees its member's store (read-only). @@ -717,7 +720,9 @@ impl LaneRun { // written, its containers created; nothing runs yet, so the network // rules go in first. let mut groups: Vec<(String, Group, Model)> = Vec::new(); - for name in order(&stack) { + // A warm lease runs `prepare` only: no group is made. + let names = if self.warm { Vec::new() } else { order(&stack) }; + for name in names { if self.started(&stack, &name).is_empty() { // Its profile leaves every container out: nothing is made. phase(&format!("infrastructure: {name}: left out by the profile")); @@ -956,6 +961,9 @@ impl LaneRun { args.extend(["-v", mount.as_str(), "-e", store.as_str()]); args.extend(["-e", out.as_str(), "-e", image.as_str()]); } + if self.warm { + args.extend(["-e", "DEVSTACK_WARM=1"]); + } if let Some(n) = networks.first() { args.extend(["--network", n.as_str()]); } @@ -1357,6 +1365,7 @@ mod tests { network: Network::Lan, secret: "s".into(), store: None, + warm: false, }; let g = run.mirror_group(&lane, "app"); // Every call of the group gets them: the node's own (`group`) too. diff --git a/crates/devstack-node/src/node.rs b/crates/devstack-node/src/node.rs index 380e1174..f7fd22b2 100644 --- a/crates/devstack-node/src/node.rs +++ b/crates/devstack-node/src/node.rs @@ -141,6 +141,10 @@ pub struct NodeLease { /// (Unix seconds); `None`: a fresh start. #[serde(default, skip_serializing_if = "Option::is_none")] pub kept: Option, + /// A warm lease (ADR-0065 point 5): the lane's container runs only the + /// `prepare` its member's store lacks, no infrastructure, then ends. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub warm: bool, } /// What a slot keeps about itself (`slots//slot.json`). @@ -446,6 +450,7 @@ impl Inner { stack_file: None, slot: Some(slot.to_string()), kept: None, + warm: false, }); // Its stack file, wherever it was: the default unless one is there. if let Some(f) = ["devstack.toml"] @@ -1115,6 +1120,7 @@ impl Inner { cpu_limit: None, network: crate::policy::Network::Lan, store: self.prepare_store(&l.member, &l.repo), + warm: l.warm, } } @@ -1587,6 +1593,14 @@ async fn admit( if let Err(why) = crate::policy::NodePolicy::admits_all(&all, &who, &tags, &lease.repo) { return Err(err(StatusCode::FORBIDDEN, format!("{}: {why}", s.name))); } + if lease.warm + && crate::policy::NodePolicy::strictest(&all).is_some_and(|p| p.warm == Some(false)) + { + return Err(err( + StatusCode::FORBIDDEN, + format!("{} takes no warm leases (its policy)", s.name), + )); + } // The node admits against what it has now (ADR-0031 point 4), and takes // a lane to need at least the least; checked below, with the lease // recorded in the same step. @@ -1643,6 +1657,7 @@ async fn admit( stack_file: None, slot: Some(slot.clone()), kept, + warm: lease.warm, }; let mut leases = s.leases.lock().unwrap(); let free = s.available_in(&leases); diff --git a/crates/devstack-node/src/policy.rs b/crates/devstack-node/src/policy.rs index aef98118..c6c2a20e 100644 --- a/crates/devstack-node/src/policy.rs +++ b/crates/devstack-node/src/policy.rs @@ -104,6 +104,10 @@ pub struct NodePolicy { /// (ADR-0039); only this node's own `policy.json` says `false`. #[serde(default, skip_serializing_if = "Option::is_none")] pub remote_update: Option, + /// Whether this node takes warm leases (ADR-0065 point 5): a member's + /// `prepare` run ahead into its store here. Not set: yes. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub warm: Option, } impl NodePolicy { @@ -173,6 +177,11 @@ impl NodePolicy { keep_lanes_hours: lower(a.keep_lanes_hours, p.keep_lanes_hours), keep_lanes_gib: lower(a.keep_lanes_gib, p.keep_lanes_gib), remote_update: a.remote_update.or(p.remote_update), + // `false` anywhere wins. + warm: match (a.warm, p.warm) { + (Some(false), _) | (_, Some(false)) => Some(false), + (x, y) => x.or(y), + }, }, }) }) diff --git a/crates/devstack-node/tests/lanerun.rs b/crates/devstack-node/tests/lanerun.rs index 5c392d91..dc3fa7f3 100644 --- a/crates/devstack-node/tests/lanerun.rs +++ b/crates/devstack-node/tests/lanerun.rs @@ -85,6 +85,7 @@ volumes: network: Network::Lan, secret: "s".into(), store: None, + warm: false, }; let project = format!("dsltest-{tag}"); let label = format!("label=com.docker.compose.project={project}"); diff --git a/crates/devstack-node/tests/node.rs b/crates/devstack-node/tests/node.rs index b40a50d6..e8a39f53 100644 --- a/crates/devstack-node/tests/node.rs +++ b/crates/devstack-node/tests/node.rs @@ -145,6 +145,7 @@ fn a_lane_is_leased_admitted_and_synced() { floor: None, profile: None, devstack: None, + warm: false, }); assert!(not_yet.unwrap_err().to_string().starts_with("409")); assert!( @@ -158,6 +159,7 @@ fn a_lane_is_leased_admitted_and_synced() { floor: None, profile: None, devstack: None, + warm: false, }) .is_err(), "the pool places on granted nodes only" @@ -192,6 +194,7 @@ fn a_lane_is_leased_admitted_and_synced() { floor: None, profile: None, devstack: None, + warm: false, }); assert!(too_much.unwrap_err().to_string().starts_with("409")); @@ -211,6 +214,7 @@ fn a_lane_is_leased_admitted_and_synced() { floor: None, profile: None, devstack: None, + warm: false, }) .unwrap(); assert_eq!(placed.node.id, node_id, "the coordinator picks the node"); @@ -229,6 +233,7 @@ fn a_lane_is_leased_admitted_and_synced() { floor: None, profile: None, devstack: None, + warm: false, }) .unwrap(); assert_eq!(offer.node.api, api); @@ -486,6 +491,7 @@ fn a_lane_is_leased_admitted_and_synced() { floor: None, profile: None, devstack: None, + warm: false, }) .unwrap(); assert!(matches!( @@ -537,6 +543,7 @@ fn a_lane_is_leased_admitted_and_synced() { floor: None, profile: None, devstack: None, + warm: false, }) .unwrap(); let lease2 = rt.block_on(client.admit(&again)).unwrap(); @@ -629,6 +636,7 @@ fn an_admin_pauses_a_node_and_ends_a_lease() { floor: None, profile: None, devstack: None, + warm: false, }) }; diff --git a/crates/devstack-node/tests/pool.rs b/crates/devstack-node/tests/pool.rs index 40289f73..5611db22 100644 --- a/crates/devstack-node/tests/pool.rs +++ b/crates/devstack-node/tests/pool.rs @@ -211,6 +211,7 @@ fn the_pool_knows_which_devstack_each_party_runs() { floor: None, profile: None, devstack, + warm: false, }) }; let newer = Release { diff --git a/crates/devstack/src/poolcmd.rs b/crates/devstack/src/poolcmd.rs index 87e03983..36b30342 100644 --- a/crates/devstack/src/poolcmd.rs +++ b/crates/devstack/src/poolcmd.rs @@ -719,6 +719,7 @@ pub fn run_lane(file: &Path, on: &str, lane: &str, keep: bool) -> Result<()> { floor: devstack_daemon::remote::floor_of(&stack.lane_need(None)), profile: None, devstack: Some(devstack_node::version::Release::this()), + warm: false, })?; println!( "lease {} on {} ({})", diff --git a/crates/devstack/tests/remote_lane.rs b/crates/devstack/tests/remote_lane.rs index 2d368320..f70e3e2e 100644 --- a/crates/devstack/tests/remote_lane.rs +++ b/crates/devstack/tests/remote_lane.rs @@ -231,6 +231,8 @@ fn a_lane_runs_on_a_node_of_the_pool() { .env("XDG_STATE_HOME", state.path()) .env("DEVSTACK_NO_HUB", "1") .env("DEVSTACK_NO_UPDATE_CHECK", "1") + .env("DEVSTACK_WARM_EVERY_MS", "2000") + .env("DEVSTACK_WARM_QUIET_MS", "0") .output() .unwrap(); let both = format!( @@ -251,6 +253,8 @@ fn a_lane_runs_on_a_node_of_the_pool() { .env("XDG_STATE_HOME", state.path()) .env("DEVSTACK_NO_HUB", "1") .env("DEVSTACK_NO_UPDATE_CHECK", "1") + .env("DEVSTACK_WARM_EVERY_MS", "2000") + .env("DEVSTACK_WARM_QUIET_MS", "0") .stdout(Stdio::piped()) .stderr(Stdio::piped()) .spawn() @@ -405,6 +409,47 @@ fn a_lane_runs_on_a_node_of_the_pool() { assert!(Instant::now() < until, "the node's store took nothing in"); std::thread::sleep(Duration::from_secs(1)); } + // The main tree's branch moves: its commit is warmed here, then on the + // node the lane ran on, by a warm lease (ADR-0065). + std::fs::write(main.join("moved.txt"), "1").unwrap(); + git(&main, &["add", "moved.txt"]); + git( + &main, + &[ + "-c", + "user.email=ci@example.invalid", + "-c", + "user.name=ci", + "commit", + // The hook of the worktree's commit above wants `deps`, which + // the main tree, running in place, has not. + "--no-verify", + "-qm", + "the branch moves", + ], + ); + let until = Instant::now() + Duration::from_secs(300); + loop { + let log = + std::fs::read_to_string(main.join(".devstack").join("daemon.log")).unwrap_or_default(); + let warmed = |place: &str| { + log.lines().any(|l| { + l.contains("\"prepare_warmed\"") && l.contains(&format!("\"place\":\"{place}\"")) + }) + }; + if warmed("local") && warmed("remote") { + break; + } + assert!( + Instant::now() < until && !log.contains("\"prepare_warm_failed\""), + "the commit was not warmed here and on the node:\n{}", + log.lines() + .filter(|l| l.contains("warm")) + .collect::>() + .join("\n") + ); + std::thread::sleep(Duration::from_secs(1)); + } let status = child.wait().unwrap(); let up = format!("{}{}", out.join().unwrap(), err.join().unwrap()); @@ -774,6 +819,8 @@ fn with_prepare(main: &Path) { ), 1, ); + // The main tree's commit warmed ahead, here and on the node (ADR-0065). + let toml = format!("{toml}\n[prepare]\nwarm = [\"HEAD\"]\n"); std::fs::write(&file, toml).unwrap(); let ignore = main.join(".gitignore"); let mut text = std::fs::read_to_string(&ignore).unwrap(); diff --git a/docs/adr/0065-the-store-is-warmed-for-a-ref-before-a-lane-needs-it.md b/docs/adr/0065-the-store-is-warmed-for-a-ref-before-a-lane-needs-it.md index 2a3c9370..38788fb0 100644 --- a/docs/adr/0065-the-store-is-warmed-for-a-ref-before-a-lane-needs-it.md +++ b/docs/adr/0065-the-store-is-warmed-for-a-ref-before-a-lane-needs-it.md @@ -1,6 +1,6 @@ # ADR-0065: The store is warmed for a ref before a lane needs it -- **Status:** Accepted (2026-10-26) +- **Status:** Accepted (2026-10-26); built, noted 2026-10-26 - **Date:** 2026-10-26 - **Deciders:** project owner - **Related:** [#290](https://github.com/nuetzliches/devstack/issues/290), [#277](https://github.com/nuetzliches/devstack/issues/277), [ADR-0062](0062-what-prepare-makes-is-kept-in-a-store-per-machine-and-repository-keyed-by-its-inputs.md) (the store, its key), [ADR-0063](0063-a-lane-on-a-node-links-its-worktree-to-a-copy-from-the-local-store.md), [ADR-0025](0025-a-lane-can-run-on-another-node.md), [ADR-0026](0026-placement-by-the-requester-admission-by-the-node.md), [ADR-0033](0033-a-node-decides-what-runs-on-it.md), [ADR-0038](0038-a-lanes-data-outlives-its-lease.md), [ADR-0015](0015-devstack-is-optional.md), [ADR-0023](0023-stack-file-compatibility.md) @@ -107,6 +107,24 @@ Where it will live: `prepare` only; `warm` in the node policy). - `docs/stack-file.md`, `docs/pool.md`, the store view of #291. +*Paths as built, noted 2026-10-26.* `crates/devstack-config` +(`PrepareSettings::warm`, validated as a ref devstack hands to git: no +option, no range, no whitespace; an error without a service whose `prepare` +names `outputs`; `WARM_SINCE`). `crates/devstack-daemon/src/warm.rs`: +`Watch` (every minute, two minutes quiet, the last commit warmed in +`.devstack/warm/done.json`), `Checkout` (`read-tree`, `checkout-index` with +`GIT_INDEX_FILE`; inputs first, `completer` for the rest), `warm_here`, +and in a warm lease's container `run_lane` and `GET /v1/warm`. +`supervisor/copy.rs`: `warm_service` (the key over the checked-out inputs), +`warm_lane`. `lanes.rs`: `follow_warm`, `warm_nodes` (the nodes of +`ran_on` whose slots hold a lane of the repository; a checkout of its own, +without this machine's outputs; the lane name `warm--`). `remote.rs`: +`RemoteLane::warm` (lease with `warm`, a node before 0.24.0 refused, sync, +start, `GET /v1/warm` until done, release). `crates/devstack-node`: +`warm` in `LeaseRequest`, `Lease`, `NodeLease`, `NodePolicy` (`false` +anywhere wins); `lanerun.rs` makes no Compose group for a warm lease and +sets `DEVSTACK_WARM`. + ## What this ADR does not say - That devstack fetches or pulls, or checks out a ref in the developer's diff --git a/docs/adr/README.md b/docs/adr/README.md index f5d59b77..7430fdd5 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -113,4 +113,4 @@ stay. | [0062](0062-what-prepare-makes-is-kept-in-a-store-per-machine-and-repository-keyed-by-its-inputs.md) | What `prepare` makes is kept in a store per machine and repository, keyed by its inputs | Accepted; measured and built on the developer's machine, and on nodes, noted 2026-10-26 | | [0063](0063-a-lane-on-a-node-links-its-worktree-to-a-copy-from-the-local-store.md) | A lane on a node links its worktree to a copy from the local store | Accepted; built, noted 2026-10-26 | | [0064](0064-every-compose-call-is-told-the-lane-it-runs-for.md) | Every Compose call is told the lane it runs for | Accepted; addendum 2026-10-26 (a lane on a node: native `{lane}`, `{lane_suffix}`, `DEVSTACK_LANE` follow its name) | -| [0065](0065-the-store-is-warmed-for-a-ref-before-a-lane-needs-it.md) | The store is warmed for a ref before a lane needs it | Accepted | +| [0065](0065-the-store-is-warmed-for-a-ref-before-a-lane-needs-it.md) | The store is warmed for a ref before a lane needs it | Accepted; built, noted 2026-10-26 | diff --git a/docs/dashboard-api.md b/docs/dashboard-api.md index 09367650..56510a85 100644 --- a/docs/dashboard-api.md +++ b/docs/dashboard-api.md @@ -386,6 +386,7 @@ type StoreView = { | `GET /v1/services/{name}/env?export=false` | JSON, its environment with each variable's origin (`devstack env`); `export=true`: only what Compose and the stack file give, for running it without devstack | | `GET /v1/runs/{id}/log` | text, a command run's output so far (the last 20 000 lines) | | `POST /v1/runs/{id}/cancel` | `202`; the run stops: its `exec` step's process tree is killed, its `run` step's job stopped, no further step starts; it ends `failed` with error `cancelled`. `409` when it is not running, `404` for no such run | +| `GET /v1/warm` | `{"warm": bool, "done": bool, "results": [{"service", "done"?: "from the store" \| "prepared" \| "prepared before", "error"?, "ms"?}]}`: in the daemon of a warm lease on a node ([ADR-0065](adr/0065-the-store-is-warmed-for-a-ref-before-a-lane-needs-it.md)), whether its `prepare` runs are done and what each did; `warm: false` in any other daemon | | `POST /v1/telemetry/take` | `{"lines": [...]}`: in the daemon of a lane on a node, the diagnostic lines it kept since the last take, which its requester sends with its own telemetry, under its consent ([ADR-0037](adr/0037-telemetry-goes-to-the-pools-collector-with-consent.md), addendum 2026-10-26); `{"lines": []}` in any other daemon | | `GET /v1/tunnel/{port}` with `Upgrade: devstack-tcp` | a raw TCP connection to that port on the daemon's machine (ADR-0029 point 4): a service's port on its loopback, or a lane's container port on the lane's network; other ports `403`. How the requester reaches the services of its lane on a node: each port it forwards here connects, through the node agent, to the lane daemon's tunnel there | | `GET /v1/tunnel/{port}` with `Upgrade: devstack-udp` | a UDP session to the lane's container published on `port` as UDP ([ADR-0056](adr/0056-a-lane-on-a-node-relays-its-udp-ports-through-a-tunnel-per-session.md)): each datagram a frame, its length as two bytes big-endian, then its bytes, both ways; the daemon sends them from a socket of the session's own. Other ports `403`, a container that does not resolve yet `502`. The requester opens one per client address of a UDP port it relays, and ends it after 60 s without a datagram either way | diff --git a/docs/pool.md b/docs/pool.md index c053ef40..eadbc3c7 100644 --- a/docs/pool.md +++ b/docs/pool.md @@ -120,7 +120,8 @@ why. A member that only shares from the dashboard is no node. server deployed as code. It holds on top of the admin's: both must admit a lane, the smaller limits and the stricter network win. Beyond an admin's fields it takes `keep_lanes_hours` and `keep_lanes_gib`: how long - and how much of stopped lanes it keeps (ADR-0038). + and how much of stopped lanes it keeps (ADR-0038), and `warm`: `false` + refuses warm leases (ADR-0065), which an admin's policy can say too. - It reads each lane's Compose model in a throwaway `docker:cli` container (`DEVSTACK_NODE_COMPOSE_IMAGE` names another image with `docker compose`), pulled once. @@ -343,7 +344,13 @@ The node keeps a stopped lane a week if it is dedicated, a day otherwise (`keep_lanes_hours` in its policy), and at most 20 GiB of one member's kept lanes, mirrors, builds and volumes together (`keep_lanes_gib`; the least recently used goes first); it removes them at once when the pool no longer -lists the member. A member's store of what `prepare` makes +lists the member. A stack with `[prepare] warm` (ADR-0065) asks the nodes +its lanes ran on for a **warm lease** after the ref moved: placed and +admitted like a lane, on the ref's checkout as its mirror (its slot is the +ref's, `warm--`), its container runs only the `prepare` the member's +store there lacks, starts no container of the stack, and the lease ends +when it is done. A node before 0.24.0 is not asked (it would start a whole +lane); a node whose policy says `warm = false` refuses it. A member's store of what `prepare` makes ([ADR-0062](adr/0062-what-prepare-makes-is-kept-in-a-store-per-machine-and-repository-keyed-by-its-inputs.md)), one per repository on the node, counts with its kept lanes: an entry no lane used for as long as a stopped lane is kept goes, and over the room the diff --git a/docs/stack-file.md b/docs/stack-file.md index 3cbc179a..461b51b7 100644 --- a/docs/stack-file.md +++ b/docs/stack-file.md @@ -618,6 +618,33 @@ lanes prepare in every copy. A file with `outputs` or `version` should say `requires = "0.23.0"` in `[stack]`. +### `[prepare] warm`: the store made ahead for a ref + +```toml +[prepare] +warm = ["origin/main"] +``` + +([ADR-0065](adr/0065-the-store-is-warmed-for-a-ref-before-a-lane-needs-it.md)) +The first lane after a lockfile change pays the whole `prepare`; with +`warm`, the main tree's daemon pays it ahead, in the background. It reads +each ref's commit every minute and never fetches: whoever fetches decides +when the ref moves. A new commit, unchanged for two minutes, is checked +out under `.devstack/warm/` as git checks it out (line endings and filters, +so the key is a checkout's), with an index of its own: your worktree, your +index and the list of worktrees stay as they are. First only each +service's `inputs`: when the store has their key, that is all. Otherwise +the whole ref is checked out there and `prepare` runs once, under the same +one-at-a-time lock as every `prepare` (a lane that needs the key meanwhile +waits and copies), and its `outputs` go into the store. Then the nodes this +repository's lanes ran on, while one of them is kept or runs there, get a +**warm lease**: a short lease of yours that runs only the `prepare` their +store lacks, without containers, and ends ([pool.md](pool.md)). A commit is +warmed once (also over a restart); a failure is a notice, retried at the +next commit. Each service whose `prepare` names `outputs` is warmed; a +`warm` without such a service is an error. A file with `warm` should say +`requires = "0.24.0"` in `[stack]`. + ## `[lanes]`: other worktrees ([ADR-0024](adr/0024-a-lane-is-a-supervisor-in-the-main-trees-daemon.md), [ADR-0030](adr/0030-each-lane-has-its-own-infrastructure.md); on other machines [ADR-0025](adr/0025-a-lane-can-run-on-another-node.md), [ADR-0028](adr/0028-lane-images.md), [ADR-0029](adr/0029-source-sync-and-port-forwarding-for-remote-lanes.md), [ADR-0035](adr/0035-lanes-can-be-shared-with-the-pool.md), and [pool.md](pool.md)) ```toml