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
11 changes: 11 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,17 @@ and listed with their assets on the
`singleton` the stop of main keeps for running lanes no longer shows main
as running with a Stop button; the stop says what keeps running, and for
which lanes.
- **`prepare` runs in the main tree too** (#630). Before a service starts
there (`up`, `start`, `restart`), its `prepare` runs in place when the
files of its `inputs` changed since it last ran there, or a directory of
its `outputs` is gone; the first start after this release runs it once.
A merge that brought new packages no longer leaves the dev server on the
old `node_modules`. The running instance is stopped first, so `npm ci`
can replace the files Windows keeps locked. A failing `prepare` stops the
start with its tail. While a service runs, here or in a lane, a change to
its `inputs` is a notice naming `devstack restart`; `restart_on` with the
lockfile makes it happen on every change. The main tree still does not use
the store (ADR-0062, amendment 2026-11-26).

### Fixed

Expand Down
171 changes: 171 additions & 0 deletions crates/devstack-daemon/src/supervisor/copy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -488,10 +488,116 @@ impl Supervisor {
{
self.set_prepare(name, view);
}
self.clear_notice(&format!("prepare.inputs.{name}"));
self.link_prepared(name, svc);
Ok(())
}

/// The main tree, prepared for `svc` before it starts there (#630): it
/// runs in place, so `prepare` runs in the tree itself when the files of
/// its `inputs` changed since it last ran there, or one of its `outputs`
/// is gone. A merge that brought packages would leave the dev server on
/// the old ones otherwise. Without the store: what it makes is the
/// tree's, not a copy's.
pub(super) fn tree_ready(
&self,
name: &str,
svc: &Service,
cancel: &dyn Fn() -> bool,
) -> Result<(), String> {
if let Some(job) = self.tree_prepare_job(name, svc)?
&& let Some(view) = self.run_prepare(name, job, cancel)?
{
self.set_prepare(name, view);
}
self.clear_notice(&format!("prepare.inputs.{name}"));
Ok(())
}

/// `rel`, a file of the `inputs` of `name`'s `prepare`, changed: while it
/// runs, it runs on what `prepare` made before, until its next start
/// prepares again (#630). Said, unless its `restart_on` restarts it.
pub fn prepare_inputs_changed(&self, name: &str, rel: &str) {
let Some(svc) = self.stack().services.get(name).cloned() else {
return;
};
let running = self
.slots
.lock()
.unwrap()
.get(name)
.is_some_and(|s| s.main.as_ref().is_some_and(|i| i.build_id.is_none()));
let restarts = devstack_build::watch_set(&svc.restart_on)
.ok()
.flatten()
.is_some_and(|g| {
g.is_match(rel) || rel.match_indices('/').any(|(i, _)| g.is_match(&rel[..i]))
});
if !running || restarts {
return;
}
self.set_notice(
&format!("prepare.inputs.{name}"),
NoticeLevel::Warn,
format!(
"`{rel}` changed: {name} still runs on what its `prepare` made before. `devstack restart {name}` runs `prepare` again; `restart_on = [\"{rel}\"]` does it on every change."
),
);
}

/// The `prepare` of `svc` the main tree needs before it starts there;
/// `None` when it has none, or it ran for these inputs and its outputs
/// are there.
pub(super) fn tree_prepare_job(
&self,
name: &str,
svc: &Service,
) -> Result<Option<PrepareJob>, String> {
let Some(p) = &svc.prepare else {
return Ok(None);
};
let files = self
.snapshot
.lock()
.unwrap()
.list()
.map_err(|e| e.to_string())?;
let inputs = devstack_build::watch_set(&p.inputs).map_err(|e| e.to_string())?;
let hashed: Vec<(String, String)> = files
.into_iter()
.filter(|rel| inputs.as_ref().is_some_and(|g| g.is_match(rel)))
.filter_map(|rel| {
let bytes = std::fs::read(self.repo.join(&rel)).ok()?;
Some((rel, blake3::hash(&bytes).to_hex().to_string()))
})
.collect();
let key = prepare_key(p, svc, hashed.iter().map(|(r, h)| (r.as_str(), h.clone())))?;
let marks = self.state_dir.join("prepared-tree");
let mark = marks.join(name);
let outputs: Vec<PathBuf> = p.outputs.iter().map(|o| self.repo.join(o)).collect();
if std::fs::read_to_string(&mark).is_ok_and(|k| k == key)
&& outputs.iter().all(|o| o.is_dir())
{
return Ok(None);
}
let cwd = p.cwd.as_ref().or(svc.cwd.as_ref());
Ok(Some(PrepareJob {
key,
mark,
// Two services whose `prepare` makes the same outputs prepare
// them once (#513).
shared: (!p.outputs.is_empty()).then(|| SharedMark {
mark: shared_mark(&marks.join("outputs"), &p.outputs),
outputs,
}),
cwd: cwd.map_or_else(|| self.repo.clone(), |c| self.repo.join(c)),
run: p.run.clone(),
store: Err(None),
before_run: None,
counted: Vec::new(),
}))
}

/// Whether what `prepare` installs is linked into the worktree
/// (ADR-0044): in a lane on this machine. The main tree runs in place
/// with its own; a lane on a node has no worktree there.
Expand Down Expand Up @@ -1834,6 +1940,71 @@ mod tests {
assert!(deps.join("in-use.txt").is_file());
}

// #630: the main tree runs in place; its `prepare` runs there when its
// inputs changed since it last ran, or what it makes is gone.
#[cfg(windows)]
#[test]
fn the_main_tree_is_prepared_in_place_when_its_inputs_changed() {
let rt = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap();
let d = tempfile::tempdir().unwrap();
let stack = "version = 1\n[stack]\nname = \"t\"\n[services.web]\nkind = \"devserver\"\nrun = \"x\"\nport = 4200\nprepare = { run = \"mkdir deps 2>nul & copy /y package-lock.json deps\\\\lock.json\", inputs = [\"package-lock.json\"], outputs = [\"deps\"] }\n";
let sup = warm_repo(
d.path(),
stack,
&[("package-lock.json", "{\"v\":1}"), ("app.js", "1")],
&rt,
);
let svc = sup.stack().services["web"].clone();
let deps = d.path().join("deps");
let lock = || std::fs::read_to_string(deps.join("lock.json")).unwrap_or_default();

// Never prepared here: it runs, in the tree itself.
sup.tree_ready("web", &svc, &|| false).unwrap();
assert_eq!(lock(), "{\"v\":1}", "{:?}", sup.notices());
assert!(!sup.snapshot.lock().unwrap().dir.join("deps").exists());

// Same inputs: what is there stays.
std::fs::write(deps.join("own.txt"), "mine").unwrap();
sup.tree_ready("web", &svc, &|| false).unwrap();
assert!(
deps.join("own.txt").is_file(),
"prepared again for the same inputs"
);

// New inputs (a merge brought packages): prepared again.
std::fs::write(d.path().join("package-lock.json"), "{\"v\":2}").unwrap();
sup.tree_ready("web", &svc, &|| false).unwrap();
assert_eq!(lock(), "{\"v\":2}");

// What it makes is gone: prepared again.
std::fs::remove_dir_all(&deps).unwrap();
sup.tree_ready("web", &svc, &|| false).unwrap();
assert_eq!(lock(), "{\"v\":2}");
}

// #630: a `prepare` that fails in the main tree stops the start with its
// tail, and the next start tries again.
#[cfg(windows)]
#[test]
fn a_failed_prepare_in_the_main_tree_stops_the_start_and_runs_again() {
let rt = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap();
let d = tempfile::tempdir().unwrap();
let stack = "version = 1\n[stack]\nname = \"t\"\n[services.web]\nkind = \"devserver\"\nrun = \"x\"\nport = 4200\nprepare = { run = \"if exist ok.txt (mkdir deps) else (echo no ok.txt & exit 3)\", inputs = [\"package-lock.json\"], outputs = [\"deps\"] }\n";
let sup = warm_repo(d.path(), stack, &[("package-lock.json", "{}")], &rt);
let svc = sup.stack().services["web"].clone();
let e = sup.tree_ready("web", &svc, &|| false).unwrap_err();
assert!(e.contains("code 3") && e.contains("no ok.txt"), "{e}");
std::fs::write(d.path().join("ok.txt"), "").unwrap();
sup.tree_ready("web", &svc, &|| false).unwrap();
assert!(d.path().join("deps").is_dir());
}

#[cfg(windows)]
#[test]
fn a_ref_whose_key_the_store_lacks_is_prepared_into_it() {
Expand Down
8 changes: 6 additions & 2 deletions crates/devstack-daemon/src/supervisor/lifecycle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -916,8 +916,12 @@ impl Supervisor {
is_main: bool,
cancel: &dyn Fn() -> bool,
) -> Result<Instance, String> {
if artifact.is_none() && self.runs_from_copy() {
self.copy_ready(name, svc, cancel)?;
if artifact.is_none() {
if self.runs_from_copy() {
self.copy_ready(name, svc, cancel)?;
} else {
self.tree_ready(name, svc, cancel)?;
}
}
let ctx = self.context(svc, artifact.map(|(_, d)| d.as_path()), port, is_main);
let env = {
Expand Down
8 changes: 7 additions & 1 deletion crates/devstack-daemon/src/supervisor/replace.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,13 @@ The running instance was left as it was."
return Err(STOPPED.into());
}
let running = self.slots.lock().unwrap()[name].main.is_some();
if svc.proxied() && running {
// The main tree prepares in place (#630): the running instance holds
// what `prepare` replaces (Windows locks open files), so it stops
// first instead of serving until a candidate took over.
let prepares_in_place = artifact.is_none()
&& !self.runs_from_copy()
&& self.tree_prepare_job(name, &svc)?.is_some();
if svc.proxied() && running && !prepares_in_place {
self.replace(name, &svc, artifact)?;
} else {
self.set_candidate(name, None);
Expand Down
21 changes: 19 additions & 2 deletions crates/devstack-daemon/src/watch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -391,9 +391,21 @@ fn watch(sup: Arc<Supervisor>) -> Result<Watcher, String> {
// What runs from a copy of the tree, to keep in step with it: a lane
// here, and a lane's daemon on a node, which is its own main tree there
// (its `lane` is empty) and runs from a copy of the mirror all the same.
// Services whose `prepare` the next start runs again when its inputs
// change (#630): a running one says so.
let prepared: Vec<(String, GlobSet)> = sup
.stack()
.services
.iter()
.filter(|(_, s)| runs(s))
.filter_map(|(n, s)| set(&s.prepare.as_ref()?.inputs).map(|g| (n.clone(), g)))
.collect();
let lane = sup.runs_from_copy();
let only_stack_file =
built.is_empty() && devservers.is_empty() && containers.is_empty() && !lane;
let only_stack_file = built.is_empty()
&& devservers.is_empty()
&& containers.is_empty()
&& prepared.is_empty()
&& !lane;
let stack_rel = sup
.stack_file()
.strip_prefix(&sup.repo)
Expand Down Expand Up @@ -451,6 +463,11 @@ fn watch(sup: Arc<Supervisor>) -> Result<Watcher, String> {
me.changed(n, &rel);
}
}
for (n, g) in &prepared {
if g.is_match(&rel) {
me.prepare_inputs_changed(n, &rel);
}
}
}
for (n, g) in &devservers {
if covers(g, &rel) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,9 @@ which needs no privilege, a symbolic link elsewhere.
4. A linked directory that is gone from the copy runs `prepare` again,
even with unchanged inputs.
5. The main working tree runs in place with its own directories, and a
lane on a node has no worktree there: neither links.
lane on a node has no worktree there: neither links. (*Since 2026-11-26*
the main tree's `prepare` runs in those directories itself,
ADR-0062's amendment.)

## Alternatives considered

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# ADR-0062: What `prepare` makes is kept in a store per machine and repository, keyed by its inputs

- **Status:** Accepted (2026-10-26); measured and built on the developer's machine, noted 2026-10-26; built on nodes, noted 2026-10-26; addendum 2026-10-28 (a node keeps the member's build artifacts too; card on the pull request)
- **Status:** Accepted (2026-10-26); measured and built on the developer's machine, noted 2026-10-26; built on nodes, noted 2026-10-26; addendum 2026-10-28 (a node keeps the member's build artifacts too; card on the pull request); amended 2026-11-26 (the main tree prepares in place, #630)
- **Date:** 2026-10-26
- **Deciders:** project owner
- **Related:** [#277](https://github.com/nuetzliches/devstack/issues/277), [ADR-0002](0002-processes-run-from-immutable-artifacts.md), [ADR-0024](0024-a-lane-is-a-supervisor-in-the-main-trees-daemon.md) (a lane runs from a copy), [ADR-0028](0028-lane-images.md) (point 3), [ADR-0033](0033-a-node-decides-what-runs-on-it.md), [ADR-0034](0034-a-machine-can-belong-to-several-pools.md), [ADR-0038](0038-a-lanes-data-outlives-its-lease.md) (slots, the member's disk cap), [ADR-0044](0044-a-lanes-prepared-directories-can-be-linked-into-its-worktree.md), [ADR-0049](0049-a-lanes-need-is-measured-disk-included.md), [ADR-0063](0063-a-lane-on-a-node-links-its-worktree-to-a-copy-from-the-local-store.md)
Expand Down Expand Up @@ -201,9 +201,25 @@ agent takes in; only the member's own lanes see it. Swept and counted like
the rest of the store. A start that finds its artifact there copies it
(`build_reused` with `source: store`) instead of building.

## Amendment 2026-11-26: the main tree prepares in place

Card approved by the owner on 2026-11-26 (#630), with the automatic variant
and the break it brings. A merge that brought packages left the main tree's
dev server on the old `node_modules`, and only its import errors said so.
Now `prepare` runs in the main tree itself before a service starts there
(`up`, `start`, `restart`), when the files of its `inputs` changed since it
last ran there (a mark under `.devstack/prepared-tree/`) or a directory of
its `outputs` is gone; never prepared there counts as changed, so the first
start after the release runs it once. A restart that prepares stops the
running instance first instead of starting a candidate beside it: Windows
keeps the files `npm ci` replaces locked. While a service runs, a change to
its `inputs` is a notice naming `restart` and `restart_on`. The main tree
still does not use the store: its outputs are the developer's tree, not a
copy.

## What this ADR does not say

- That the main working tree uses the store. It runs in place, with the
developer's own `node_modules`.
- That the main working tree uses the store. It runs in place; its
`prepare` runs there without the store (amendment 2026-11-26).
- That a store entry is ever linked into a worktree. ADR-0063 links a copy.
- Anything about warming the store for a ref before a lane needs it.
2 changes: 1 addition & 1 deletion docs/adr/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ stay.
| [0059](0059-a-services-stop-command-ends-what-its-run-started.md) | A service's `stop` command ends what its `run` started outside its process tree | Accepted |
| [0060](0060-the-tray-is-a-client-of-the-hub.md) | The tray is a client of the hub, a process of its own, on every desktop | Accepted |
| [0061](0061-the-dashboard-opens-in-its-installed-app.md) | The dashboard opens in its installed app, when there is one | Accepted |
| [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 | Addendum 2026-10-28 (a node keeps the member's build artifacts too); Accepted; measured and built on the developer's machine, and on nodes, noted 2026-10-26 |
| [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 | Addendum 2026-10-28 (a node keeps the member's build artifacts too); amended 2026-11-26 (the main tree prepares in place, #630); 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; addendum 2026-10-27 (two copies, the link moves when the new one is whole; an emptied copy is prepared again) |
| [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; built, noted 2026-10-26 |
Expand Down
11 changes: 9 additions & 2 deletions docs/stack-file.md
Original file line number Diff line number Diff line change
Expand Up @@ -689,8 +689,15 @@ copy). `cwd` defaults to the service's. `run` is required and, like `cwd`,
used as written: placeholders and `${VAR}` are an error there. `inputs` are
globs. Its output goes to
`.devstack/logs/<service>/prepare-*.log`; a failure stops the build or start
with its tail. The main working tree runs dev servers in place, with the
developer's own `node_modules`.
with its tail. The main working tree runs dev servers in place: there
`prepare` runs in the tree itself before the service starts (`up`, `start`,
`restart`), when the files of `inputs` changed since it last ran there or a
directory of `outputs` is gone (#630). A restart then stops the running
instance first, so `npm ci` can replace files it holds open. The main tree
does not use the store (`outputs` below) and links nothing. While a service
runs, here or in a lane, a change to a file of its `inputs` is a notice: it
runs on what `prepare` made before until its next start. To have that start
come by itself, add the lockfile to the dev server's `restart_on`.

```toml
[services.web]
Expand Down
5 changes: 5 additions & 0 deletions skills/devstack-config/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,11 @@ without a stack file starts from `devstack init` (a draft with TODOs).
main branch's lockfile prepared before the first lane needs it, add
`[prepare] warm = ["origin/main"]` (devstack never fetches; it watches the
ref) and `requires = "0.24.0"`.
- **The main tree runs `prepare` in place too**, before a service starts
there, when its `inputs` changed since it last ran or its `outputs` are
gone: after a merge that brought packages, `devstack restart web` installs
them (no hand-made `npm ci` under a running dev server). To do it on every
lockfile change, add the lockfile to the dev server's `restart_on`.
- **Lanes on other machines** (`devstack up --on <node>`) run in a Linux
container: `[lanes] image` (a toolchain image) or `[lanes] dockerfile`. Files
git ignores do not go there unless `[lanes] sync` names them (a dev
Expand Down
Loading