Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`
Expand Down
4 changes: 4 additions & 0 deletions crates/devstack-config/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
16 changes: 16 additions & 0 deletions crates/devstack-config/src/model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Active>,
}

/// `[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<String>,
}

/// `[agents]`: what devstack writes for the coding agents that work in the
/// repository.
#[derive(Debug, Clone, Default, Deserialize, JsonSchema)]
Expand Down
43 changes: 43 additions & 0 deletions crates/devstack-config/src/validate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -334,6 +334,33 @@ pub fn validate(stack: &Stack) -> Vec<Issue> {
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()
{
Expand Down Expand Up @@ -1115,6 +1142,22 @@ pub fn warnings(stack: &Stack) -> Vec<Issue> {
});
}
}
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
Expand Down
39 changes: 39 additions & 0 deletions crates/devstack-config/tests/stack_files.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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!(
Expand Down
7 changes: 7 additions & 0 deletions crates/devstack-daemon/src/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down Expand Up @@ -221,6 +222,12 @@ async fn stack(State(s): State<AppState>) -> 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.
Expand Down
149 changes: 149 additions & 0 deletions crates/devstack-daemon/src/lanes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -888,6 +891,7 @@ impl Lanes {
}));
me.follow();
me.follow_node_links();
me.follow_warm();
me
}

Expand Down Expand Up @@ -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<Self>) {
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<crate::remote::RanOn> = Vec::new();
let names: Vec<String> = 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
Expand Down Expand Up @@ -3088,6 +3236,7 @@ impl Lanes {
forward,
step,
profile: profile.as_deref(),
warm: false,
})
}

Expand Down
5 changes: 5 additions & 0 deletions crates/devstack-daemon/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down Expand Up @@ -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()? {
Expand Down
Loading
Loading