cloud/reconciler/local_process.rs
1//! `[providers.compute] kind = "local-process"` — run a service's own compute
2//! component as a **kamaji-supervised host process** at the dev tier.
3//!
4//! ## Why this exists
5//!
6//! A component's `kind` says what the service *is*; the mirror's provider slot
7//! says how *this tier* runs it. That split already exists for storage —
8//! `mesofact-static` runs off `local-static` (files on disk) at dev and
9//! `miniflare-container` (containers) at pond, one component kind, two
10//! runtimes — and this is the same split for compute. A `kind = "container"`
11//! component now runs natively at dev and in docker at pond without the
12//! service declaring itself twice.
13//!
14//! The alternative — a `local-process` *component kind* — was rejected: it
15//! would make the artifact shape a property of the service rather than of the
16//! tier, which is exactly the fork that W265 exists to prevent.
17//!
18//! ## Why not just run the container at dev
19//!
20//! Because a container is a different filesystem, and at the dev tier that is
21//! a lie you have to maintain. yah-cloud-admin is the worked example: it reads
22//! `.yah/infra/machines/*.toml`, so its dev container has to bind-mount
23//! `.yah/infra` read-only into `/workspace/.yah/infra` and override
24//! `YAH_CLOUD_ADMIN_WORKSPACE_ROOT` to find it (see
25//! `crates/yah/cloud-admin/workload.toml`). Get the mount wrong and the
26//! service comes up *running, healthy, and describing a fleet of zero
27//! machines*. A host process inherits the operator's actual workspace and the
28//! whole class of failure disappears — along with a docker build per edit.
29//!
30//! ## Config
31//!
32//! The mirror opts in:
33//!
34//! ```toml
35//! # .yah/services/<svc>/mirrors/dev.toml
36//! shape = "local"
37//!
38//! [providers.compute]
39//! kind = "local-process"
40//! ```
41//!
42//! and the component's `workload.toml` describes the process:
43//!
44//! ```toml
45//! [process]
46//! # Cargo package to build before spawning. Omit for a prebuilt binary.
47//! cargo_package = "yah-cloud-admin"
48//! # Binary to exec, relative to the workspace root. Defaults to
49//! # target/<profile>/<cargo_package>.
50//! bin = "target/debug/yah-cloud-admin"
51//! # Extra argv after the binary.
52//! args = []
53//! # Port the process listens on. OPTIONAL. When present it is the readiness
54//! # signal and the mirror's `dev_url`. Omit it for a process that never
55//! # listens — a native GUI, a daemon on a unix socket, a batch loop — and
56//! # readiness falls back to "still alive after a short grace window",
57//! # with no `dev_url` for the Run tab to open.
58//! port = 4325
59//!
60//! [process.env]
61//! YAH_CLOUD_ADMIN_ADDR = "127.0.0.1:4325"
62//! ```
63//!
64//! ## Per-mirror `profile` override, and non-cargo builds
65//!
66//! `workload.toml` is one file shared by every mirror bound to this slot, so
67//! `profile` can be overridden per mirror — the only field that can, since
68//! it's the only one where two tiers of the *same* component legitimately
69//! want different values (a debug dev loop next to a release build, both
70//! pointed at the same `[process]` block):
71//!
72//! ```toml
73//! # .yah/services/<svc>/mirrors/release.toml
74//! shape = "local"
75//!
76//! [providers.compute]
77//! kind = "local-process"
78//! profile = "release"
79//! ```
80//!
81//! For a component with no runnable top-level binary from a plain
82//! `cargo build -p pkg` — a native macOS/iOS app, where Rust only supplies a
83//! static lib for Xcode to link — `pre_build` replaces `cargo_package`
84//! entirely: an operator-authored argv (same trust model as `compose.rs`'s
85//! post-write shell commands, R592-T2) run in `workspace_root` before `bin`
86//! is resolved, streamed into the Run tab's log tail exactly like a cargo
87//! build:
88//!
89//! ```toml
90//! [process]
91//! pre_build = ["./build-dist.sh", "arm64", "--sign"]
92//! bin = "app/macos/dist/NoiseTable.app/Contents/MacOS/NoiseTable"
93//! ```
94//!
95//! ## Portless components
96//!
97//! A process with no TCP listener is a first-class case, not a degenerate
98//! one: noisetable's desktop dev loop is a winit window with zero network
99//! surface. Do not paper over the gap by declaring a port the process never
100//! binds — that trips the readiness timeout below and tears down a perfectly
101//! healthy child, or (worse) adopts an unrelated listener that happens to
102//! answer. Omit `port` and the Run tab renders the row as a log-tail plus
103//! stop card instead of an iframe.
104//!
105//! ## …and what a portless component SHOULD do instead
106//!
107//! Dropping the port drops the only structured thing the supervisor knew
108//! about the process, which leaves log-grepping — for an operator and, worse,
109//! for an agent. So the house default for anything long-running is the
110//! **process-control channel** ([`crate::proc_control`]): a unix socket
111//! speaking one verb, `status`, answering with a document whose `state` uses
112//! kamaji's own `WorkloadState` vocabulary.
113//!
114//! ```toml
115//! [process]
116//! cargo_package = "dev"
117//! # no `port` — a winit window has nothing to bind
118//!
119//! [process.control]
120//! # nothing to configure: the socket path arrives as $YAH_CONTROL_SOCK
121//! ```
122//!
123//! With it, readiness stops being a guess: the process says `starting` while
124//! it loads and `running` when it is up, and an agent can ask what it is
125//! doing instead of parsing sentences out of stdout. A component that already
126//! serves HTTP declares `http_path` instead and shares one endpoint with the
127//! cloud tier's `Healthcheck`. The channel is optional — a process that
128//! declines it still runs, on liveness alone.
129//!
130//! @yah:relay(R715, "local-process compute provider: a dev tier that runs the binary, not a container")
131//! @yah:at(2026-08-03T22:21:13Z)
132//! @yah:status(open)
133//! @yah:assignee(agent:bundle-anthropic-ashguard)
134//! @yah:next("T1 (landed): LocalProcessReconciler + Provider::LocalProcess + native_support dedup + both dispatchers + the yah-cloud-admin dev/pond split. See the T1 handoff.")
135//! @yah:next("Follow-on: mesofact-dev's local-static arm and this reconciler now differ only in argv construction. W265 already plans to retire local-static when local-s3-fs lands - that is the moment to consider collapsing them.")
136//! @yah:next("Follow-on: the desktop mirror_run_up has no adopt-probe for local-process the way it does for mesofact-dev. Correct today because the reconciler reaps its predecessor, but an adopt path would let a re-click return the running URL without a rebuild.")
137//! @yah:gotcha("Naming rule this relay encodes, from the operator: if it runs in a container it is pond. Dev is the tier that runs against the operator's real filesystem. No service is required to have all three tiers - a service whose lowest tier is pond is fine.")
138//! @yah:gotcha("The runtime is a property of the MIRROR, not the component. A kind=container component runs natively at dev and in docker at pond, selected by the mirror's compute slot - the same split mesofact-static already had via providers.static (local-static at dev, miniflare-container at pond). Do NOT add a local-process COMPONENT kind: that makes artifact shape a property of the service and reintroduces the per-tier fork W265 exists to prevent.")
139//! @arch:see(.yah/docs/working/W265-service-capabilities-and-drivers.md)
140//!
141//! @yah:ticket(R715-T1, "LocalProcessReconciler + Provider::LocalProcess, wired into both dispatchers; yah-cloud-admin dev/pond split")
142//! @yah:status(review)
143//! @yah:at(2026-08-05T04:54:16Z)
144//! @yah:assignee(agent:bundle-anthropic-ashguard)
145//! @yah:phase(P1)
146//! @yah:parent(R715)
147//! @yah:next("R714-B1 (stop button no-ops on container mirrors) and R714-B2 (tier chip prints 'axum') were found during this work and filed separately - they predate it and are not regressions from it.")
148//! @yah:verify("cargo test --manifest-path oss/yubaba/Cargo.toml -p yah-cloud --lib - 688 passed, 0 failed")
149//! @yah:verify("cargo test -p yah --lib cloud:: - 108 passed")
150//! @yah:verify("cargo test -p xtask --test schema_drift --test workload_envelope - 4 passed")
151//! @yah:verify("MANUAL (done): yah cloud mirror up yah-cloud-admin --env dev binds 127.0.0.1:4325 with no container, and the process logs workspace=/Users/leif/ss/yah - the real checkout, not /workspace")
152//! @yah:verify("MANUAL (done): running mirror up twice in a row replaces the child (pid changes) instead of leaving a dead second instance behind an Address-already-in-use")
153//! @yah:gotcha("NativeRuntime's workload table is IN-MEMORY, so a second `mirror up` from a fresh process cannot see the first one's child. Without the owner.json sidecar + reap the new child dies on Address-already-in-use, wait_for_port sees the OLD listener answering, and the reconcile reports success while the just-edited binary is not what is running. This was observed live before the fix, not theorised. Do not remove the sidecar.")
154//! @yah:gotcha("yah-cloud-admin's pond tier moved to host port 4326 so both tiers can run at once. The container still listens on 4325 internally.")
155//! @yah:next("RESOLVED (R715-T1, 2026-08-04): the cloud.toml blocker comment was corrected by the peer whose uncommitted edits blocked it - lines 34-60 now carry the 2026-08-03 status (published image DONE, workload declaration DONE, cheers key STILL BLOCKED on both an issuer and a 0.8.21 yubaba roll). Nothing left to do there.")
156//! @yah:handoff("Re-verified independently on 2026-08-04 (session:5fe4274e, rune) rather than trusting the prior run's claims. All three automated suites green; counts are HIGHER than the ones recorded above because peers added tests since: yah-cloud lib 698 passed / 0 failed (was 688), yah lib cloud:: 111 passed (was 108), xtask schema_drift + workload_envelope 4 passed (unchanged).")
157//! @yah:verify("RE-VERIFIED 2026-08-04, sidecar survives across sessions: the owner.json left by the 2026-08-03 run ({pid:54869,port:4325}) still matched the live listener a day later - lsof -t on 4325 returned exactly 54869. That is the cross-process ownership link working in the wild, not in a test.")
158//! @yah:verify("RE-VERIFIED 2026-08-04, reap-and-replace: `cargo run -p yah -- cloud mirror up yah-cloud-admin --env dev` reaped pid 54869 (kill -0 confirms gone), spawned 71455, rewrote owner.json to {pid:71455,port:4325}, and 127.0.0.1:4325/ answers HTTP 200. No dead second instance, no Address-already-in-use.")
159//! @yah:verify("RE-VERIFIED 2026-08-04, the failure mode this tier exists to prevent: child cwd is /Users/leif/ss/yah (lsof -d cwd), `docker ps` shows NO cloud-admin container, and /partial/machines renders 9 machine rows against 9 files in .yah/infra/machines/ - us-west-001/002/003 + mac-builder among them. Not a fleet of zero.")
160//! @yah:verify("RE-VERIFIED 2026-08-04, both dispatcher arms compile: `cargo build -p yah` (app/yah/cli/src/cloud.rs:4705) and `cargo check -p desktop --lib` (app/yah/desktop/src/mirror_run.rs:624) are both clean.")
161//! @yah:gotcha("LEFT RUNNING: the re-verification above spawned yah-cloud-admin pid 71455 on 127.0.0.1:4325 and did not stop it - that matches the state found at session start (a dev-tier process was already up). Kill it with `kill $(lsof -nP -iTCP:4325 -sTCP:LISTEN -t)`, or just re-run `mirror up`, which reaps it.")
162//! @yah:gotcha("TRANSIENT, NOT THIS TICKET: `cargo run -p yah` failed once with E0599 mid-verification and compiled clean on immediate retry with no edit from this session - a peer's in-flight change on the shared tree. Same shape as the note in crates/yah/camp-service/tests/e2e.rs:35. If you see it, retry before investigating.")
163//!
164//! @yah:ticket(R715-T2, "Portless `local-process` compute slot — Run tab support for native GUI processes with no TCP listener")
165//! @yah:status(review)
166//! @yah:at(2026-08-14T21:27:45Z)
167//! @yah:assignee(agent:bundle-anthropic-ashguard)
168//! @yah:parent(R715)
169//! @yah:next("Make `[process].port` optional in `ProcessSpec` (this file). When absent, readiness = process spawned and still alive after a short grace window, instead of `wait_for_port`; the `up()` path returns `dev_url = None` to `into_running(...)` (RunningWorkload's dev_url is already `Option`, so this is a narrowing of ProcessSpec, not a new field anywhere downstream).")
170//! @yah:next("Mirror the same required->optional change for `port` on `run.spawn`'s schema and `SpawnArgs` (crates/yah/agent-tools/src/run_tools.rs) so an agent can supervise a portless process through the same tool used for app servers.")
171//! @yah:next("Run tab: a mirror/spawn with no dev_url should render as a log-tail + kill/restart card, no iframe, no URL bar — this is the `stdio` process row A046 (.yah/docs/architecture/A046-yah-run-tab.md) already sketches (`yah-rig (noise) stdio pid 4598 ... [logs] [kill]`) but neither shipped mechanism implements.")
172//! @yah:next("Real external consumer blocked on this today: noisetable's desktop dev loop (`cargo run -p dev` / `cargo run --release -p dev`, a winit native GUI window with zero network surface — no port to bind, ever). Full writeup + the service.toml/mirror.toml/workload.toml shape noisetable wants to declare once this lands: entambi repo, .yah/docs/working/W145-desktop-dev-run-tab.md.")
173//! @yah:gotcha("Do not let a consumer route around this by having the process bind a throwaway port it never uses for anything real — that just trips this reconciler's own `wait_for_port` timeout/teardown, or makes `run.spawn` poll a port that happens to be open for unrelated reasons. Both are worse than the honest gap. The fix belongs in this reconciler (and run_tools.rs), not in a consumer's workload.toml.")
174//! @yah:assumes("Readiness-as-'process alive after N ms grace window' is assumed to be an acceptable v1 fallback (matches what a bare `[kill]`-only scoreboard row needs). A richer readiness probe (e.g. an optional stdout regex match) would be nicer but isn't required to unblock the noisetable use case named above — confirm with whoever picks this up whether the simple version is sufficient, or whether R322-F4's LivePanel / RunStatePanel state model expects something richer for a 'ready' vs 'starting' distinction on portless rows.")
175//! @arch:see(.yah/docs/working/W265-service-capabilities-and-drivers.md)
176//! @arch:see(.yah/docs/architecture/A046-yah-run-tab.md)
177//! @arch:see(crates/yah/agent-tools/src/run_tools.rs)
178//! @yah:handoff("[process].port is now Option<u16> in the local-process reconciler. A portless component skips the port-contention check and wait_for_port; readiness falls back to ALIVE_GRACE (750ms) + pid_alive, dev_url is None, and OwnerRecord.port became Option<u16> with a serde default so sidecars written before this still parse (tested).")
179//! @yah:handoff("run.spawn: SpawnArgs.port is Option<u16> and the JSON schema no longer requires it; the wire still encodes portless as 0. The camp daemon's run_spawn_handler applies the same 750ms grace and fails the spawn with a log tail when a portless child exits immediately - it previously registered a healthy scoreboard row over a corpse. rpc::RunSpawnParams.port's doc claimed 0 meant OS-assigned, which the handler never did; corrected to say portless.")
180//! @yah:handoff("Run tab: MirrorPanel's running-with-no-dev_url state was the placeholder reading 'paste a local URL to preview it here' - advice that cannot be followed for a process that will never have one. Replaced with PortlessCard (host-process chip, what it is, pointer to the log panel and Stop, plus whatever the process reported). LivePanel's port column reads 'stdio' for a portless mirror or spawn and keeps the dash for task runs, via an exported transportLabel with 6 tests.")
181//! @yah:handoff("SCOPE ADDED MID-TICKET, at the operator's direction: the process-control channel. Dropping the port drops the only structured signal a supervisor had, leaving log-grepping - so portless is now paired with an opinionated default that anything long-running SHOULD expose. New module oss/yubaba/crates/cloud/src/proc_control.rs (client + wire types), new optional [process.control] in the reconciler, and W315-process-control-channel.md as the canon. Phase 2 filed as R715-F3.")
182//! @yah:handoff("The contract: one verb, `status`, over newline-JSON on a unix socket (path handed down as $YAH_CONTROL_SOCK) or GET /_yah/status for anything already serving HTTP - same document, two transports, so the cloud tier's Healthcheck{Http} probes the same endpoint the dev tier reads over a socket. `state` is the only required field and its vocabulary is EXACTLY kamaji_proto::WorkloadState, which is the whole compatibility claim: a workload's own report can be handed to the supervisor verbatim. Pinned by a test that fails if either side drifts.")
183//! @yah:handoff("Readiness in the reconciler is now a ladder: control channel > port bind > alive-after-grace. A declared channel supersedes the port because a bound port says nothing about whether the thing behind it finished booting, and a terminal state (failed/exited) short-circuits instead of burning the 20s timeout.")
184//! @yah:handoff("DISCOVERED AND FIXED, wider than the ticket: RunningWorkloadSummary dropped RunningWorkload.notes, so every operator-facing note a reconciler attached since R546-B12 was written into a struct nobody read. Added the field (+ TS type, + three desktop construction sites in mirror_observation.rs). It is what carries the process's own status line to the Run tab.")
185//! @yah:verify("cargo test --manifest-path oss/yubaba/Cargo.toml -p yah-cloud --lib - 830 passed / 0 failed (827 before the last batch). 20 in local_process, 10 in proc_control.")
186//! @yah:verify("END-TO-END, not just unit: three tests drive the real reconciler through kamaji's native backend against a temp workspace. a_portless_component_comes_up_with_no_dev_url spawns /bin/sleep with no port and asserts dev_url None, the liveness-only note, and an owner.json whose port is ABSENT rather than a placeholder zero. a_portless_component_that_exits_immediately_fails_the_reconcile runs /usr/bin/false and asserts the bring-up fails. a_control_channel_decides_readiness_when_declared holds the component at not-ready through a `starting` document and passes on `running`.")
187//! @yah:verify("cargo test -p yah-agent-tools --lib run_tools - 14 passed (was 12; +2 for the optional port).")
188//! @yah:verify("packages/yah/ui - bun run typecheck clean, bun run build clean, bun test src/components/run/ 111 passed / 0 failed.")
189//! @yah:verify("Full bun test 1717 pass / 14 fail / 8 errors. Identical failure counts to what R714-B2 recorded, and the failing names are the same pre-existing four files (StatusPill, dispatchNav, first-run, truncateArg) - no regression from this ticket.")
190//! @yah:verify("cargo check -p yah, cargo check -p desktop --lib, cargo test -p xtask --test schema_drift (3 passed) - all clean.")
191//! @yah:verify("NOT RUN: any manual desktop check. Nobody has looked at the rendered PortlessCard or the stdio transport chip in a running app - there is no portless service declared in this camp to bring up. The e2e reconciler tests cover the backend claim; the two UI changes are covered by tests and typecheck only.")
192//! @yah:gotcha("PRE-EXISTING RED GATE, not from this ticket: `cargo test -p xtask --test workload_envelope` fails on app/yah/web/chat/workload.toml and oss/mesofact/examples/hello/workload.toml, both `missing field routes`. That is R658-B1's known bug (routes written after [build], so TOML scopes it into build.routes) spread to two more files that were never added to KNOWN_GAPS. Both files are committed and untouched by this ticket. Deliberately NOT pinned into KNOWN_GAPS - silently widening the pin is what R658-B1 exists to stop; noted on that ticket instead.")
193//! @yah:gotcha("The reconciler unlinks the control socket path before spawning, because a leftover socket file makes bind fail with EADDRINUSE even with nobody listening. Consequence for anyone writing a test: a producer that binds BEFORE up() has its socket deleted out from under it. Bind after, which is the order a real child sees anyway.")
194//! @yah:gotcha("RESOLVED 2026-08-18 by R658-B1 (@Ashguard:libra): the red gate this ticket's gotcha flagged is now GREEN. app/yah/web/chat/workload.toml and oss/mesofact/examples/hello/workload.toml were migrated to put routes ABOVE [build], along with the other four files and the yah cloud site init scaffold. workload_spec::BuildConfig now carries serde(deny_unknown_fields) so the misplacement is a parse error naming routes. cargo test -p xtask --test workload_envelope passes. Nothing was pinned into KNOWN_GAPS - the four missing-field-routes entries were DELETED. No action needed here; this note exists so the gotcha is not read as still-true.")
195
196use std::collections::{BTreeMap, VecDeque};
197use std::net::{IpAddr, Ipv4Addr, SocketAddr};
198use std::path::PathBuf;
199use std::sync::Arc;
200use std::time::Duration;
201
202use anyhow::{bail, Context, Result};
203use async_trait::async_trait;
204use kamaji::native::NativeRuntime;
205use kamaji::{Kamaji, MeshAssignment, MeshIdent};
206use serde::Deserialize;
207use tokio::sync::{oneshot, Mutex as AsyncMutex};
208use tracing::{info, warn};
209use workload_spec::EnvVar;
210
211use super::native_support::{
212 capture_paths, native_spec, sanitize_ident, spawn_native_log_supervisor,
213};
214use super::{
215 into_running, wait_for_port, LogBuffer, PhaseCursor, ReconcileCtx, Reconciler, RunningWorkload,
216};
217use crate::proc_control::{self, ControlEndpoint, ReadyOutcome};
218use crate::{MirrorProviderSlot, MirrorShape, Provider};
219
220/// The slot role a natively-run compute component occupies on its mirror.
221const SLOT: &str = "compute";
222
223/// How long to wait for the process to bind its declared port before calling
224/// the reconcile failed. Generous because the first `cargo build` of a cold
225/// target dir is included in the caller's patience, not in this window — the
226/// build finishes before the spawn.
227const READY_TIMEOUT: Duration = Duration::from_secs(20);
228
229/// Readiness window for a component with no declared port: if the child is
230/// still alive this long after `deploy_workload` returned, call it up.
231///
232/// This is deliberately not a health check — a portless process has no
233/// surface to check. What it catches is the common failure the operator
234/// would otherwise see as a green row and an empty window: a binary that
235/// execs and dies immediately (missing dylib, bad argv, panic at startup).
236/// Anything that fails later shows up in the log tail, which is the only
237/// signal a portless process has.
238const ALIVE_GRACE: Duration = Duration::from_millis(750);
239
240/// True when `mirror` binds its compute slot to `local-process`. This is the
241/// dispatch predicate — callers use it to choose this reconciler over the
242/// container one for the same component kind.
243pub fn slot_declared(mirror: &crate::MirrorConfig) -> bool {
244 matches!(
245 mirror.providers.get(SLOT),
246 Some(MirrorProviderSlot::Inline {
247 kind: Provider::LocalProcess,
248 ..
249 })
250 )
251}
252
253/// `profile` from this mirror's `[providers.compute]` inline extra fields, if
254/// declared — the per-mirror override described on [`ProcessSpec::pre_build`]
255/// above `up()`. `None` for a `Reference` slot or an `Inline` slot with no
256/// `profile` key, both of which fall back to `workload.toml`'s own value.
257fn mirror_profile_override(mirror: &crate::MirrorConfig) -> Option<String> {
258 match mirror.providers.get(SLOT) {
259 Some(MirrorProviderSlot::Inline { fields, .. }) => fields
260 .get("profile")
261 .and_then(|v| v.as_str())
262 .map(str::to_string),
263 _ => None,
264 }
265}
266
267/// Reconciler for components bound to a `local-process` compute slot.
268#[derive(Debug, Default)]
269pub struct LocalProcessReconciler {
270 /// External sink to stream build+run output into, in place of the
271 /// private buffer `up()` would otherwise create. Lets a caller register
272 /// the buffer for polling BEFORE calling `up()`, so a slow `cargo build`
273 /// is visible to a poller while the reconcile is still in flight rather
274 /// than only after `up()` returns.
275 log_buf: Option<LogBuffer>,
276 /// Published the moment the build phase finishes (before readiness/spawn
277 /// even starts), so a caller polling an in-flight `up()` can render a
278 /// build→run transition live instead of only learning about it from the
279 /// finished [`RunningWorkload::build_log_end`].
280 build_log_end_sink: Option<PhaseCursor>,
281}
282
283impl LocalProcessReconciler {
284 pub fn new() -> Self {
285 Self::default()
286 }
287
288 /// Stream into a caller-owned [`LogBuffer`] instead of a private one.
289 pub fn with_log_buf(mut self, log_buf: LogBuffer) -> Self {
290 self.log_buf = Some(log_buf);
291 self
292 }
293
294 /// Publish the build→run boundary into a caller-owned [`PhaseCursor`] as
295 /// soon as it's known, rather than only once `up()` returns it.
296 pub fn with_build_log_end_sink(mut self, sink: PhaseCursor) -> Self {
297 self.build_log_end_sink = Some(sink);
298 self
299 }
300}
301
302/// On-disk `workload.toml` shape — only the `[process]` section is read here.
303/// Other sections (`[build]`, `[run]`) belong to the container reconciler and
304/// are ignored, so one component file can describe both tiers.
305#[derive(Debug, Default, Deserialize)]
306struct ProcessComponent {
307 #[serde(default)]
308 process: Option<ProcessSpec>,
309}
310
311#[derive(Debug, Deserialize)]
312struct ProcessSpec {
313 /// Argv of an operator-authored command to run before `cargo_package`'s
314 /// build (or standalone, when there is no `cargo_package` — e.g. a native
315 /// macOS/iOS component where the runnable artifact comes out of
316 /// `xcodebuild`, not `cargo build -p`, and Rust only supplies a static
317 /// lib for Xcode to link). Runs in `workspace_root`, streamed into
318 /// `log_buf` exactly like `cargo_build`, via the same [`run_streaming`].
319 /// Same trust model as `compose.rs`'s post-write shell commands (R592-T2:
320 /// operator-authored, not attacker input) — this is TOML the operator
321 /// wrote, not a request body.
322 #[serde(default)]
323 pre_build: Option<Vec<String>>,
324 /// Cargo package to `cargo build -p` before spawning. `None` → the binary
325 /// is expected to already exist.
326 #[serde(default)]
327 cargo_package: Option<String>,
328 /// Binary path relative to the workspace root (absolute taken as-is).
329 /// `None` → `target/<profile>/<cargo_package>`.
330 #[serde(default)]
331 bin: Option<String>,
332 /// Extra argv appended after the binary.
333 #[serde(default)]
334 args: Vec<String>,
335 /// Port the process listens on. Optional: when set it is both the
336 /// readiness signal and the `dev_url`; when absent the component is
337 /// portless (native GUI, unix socket, batch loop) and readiness falls
338 /// back to [`ALIVE_GRACE`].
339 #[serde(default)]
340 port: Option<u16>,
341 /// Environment for the child.
342 #[serde(default)]
343 env: BTreeMap<String, String>,
344 /// Cargo profile used for both the build and the default binary path.
345 #[serde(default = "default_profile")]
346 profile: String,
347 /// Opt in to the process-control channel ([`crate::proc_control`]) — the
348 /// house default for anything long-running. When present, the process's
349 /// own report decides readiness, which is strictly better than both other
350 /// signals: a bound port says nothing about whether the thing behind it
351 /// has finished booting, and a live pid says nothing at all.
352 #[serde(default)]
353 control: Option<ControlSpec>,
354}
355
356/// `[process.control]` — where to ask the process how it is doing.
357///
358/// Both fields optional and mutually exclusive in practice: give `http_path`
359/// for a process that already serves HTTP (it then shares an endpoint with
360/// the cloud tier's healthcheck), otherwise the channel is a unix socket
361/// whose path this reconciler chooses and passes down as `$YAH_CONTROL_SOCK`.
362#[derive(Debug, Default, Deserialize)]
363struct ControlSpec {
364 /// Override the supervisor-chosen socket path. Rarely needed — a process
365 /// that reads `$YAH_CONTROL_SOCK` needs nothing here.
366 #[serde(default)]
367 socket: Option<String>,
368 /// Serve the status document over HTTP at this path instead, against the
369 /// component's declared `port`. Defaults to
370 /// [`proc_control::DEFAULT_HTTP_PATH`] when set to an empty string.
371 #[serde(default)]
372 http_path: Option<String>,
373}
374
375fn default_profile() -> String {
376 "debug".to_string()
377}
378
379#[async_trait]
380impl Reconciler for LocalProcessReconciler {
381 fn kind(&self) -> &'static str {
382 "local-process"
383 }
384
385 async fn up(&self, ctx: ReconcileCtx<'_>) -> Result<RunningWorkload> {
386 ctx.materialize().await?;
387
388 // A host process is the operator's own machine by definition. Refusing
389 // non-local shapes here keeps a `local-process` slot from silently
390 // meaning "run it on my laptop" in a mirror that describes a fleet.
391 if !matches!(ctx.mirror.shape, MirrorShape::Local) {
392 bail!(
393 "component {}: `local-process` is a dev-tier compute slot — mirror shape is \
394 {:?}, not `local`. Deploy the cloud tier via `yah cloud workload deploy`.",
395 ctx.component.id,
396 ctx.mirror.shape,
397 );
398 }
399
400 let mut spec = load_process_spec(&ctx)?;
401 // A mirror can override `profile` (and only `profile` — everything
402 // else about the process is one declaration shared by every tier)
403 // via `[providers.compute]`'s inline extra fields, same pattern the
404 // schema already documents for other inline provider kinds ("bucket,
405 // zone, dns, …"). Without this, two mirrors pointing at the same
406 // component's workload.toml (e.g. noisetable-desktop's dev + release
407 // tiers) would be unable to build different profiles from one file.
408 if let Some(profile) = mirror_profile_override(ctx.mirror) {
409 spec.profile = profile;
410 }
411
412 // Created here, before the build, rather than down where the
413 // supervisor is spawned: `cargo_build` streams into it live, and
414 // `build_log_end` below records the cursor where build output stops
415 // and the spawned process's own stdout/stderr begins. A caller-
416 // supplied buffer (`with_log_buf`) is reused as-is so it can already
417 // be registered for polling before this call started.
418 let log_buf = self.log_buf.clone().unwrap_or_default();
419
420 // Build first, if asked. Doing this before the port probe means a
421 // compile error surfaces as a compile error, rather than as a bind
422 // timeout on a binary that was never rebuilt. Streamed into
423 // `log_buf` as it runs (not buffered until exit) so a slow or
424 // failing build shows progress in the Run tab instead of going
425 // silent until it's done — and, unlike the old `.output()` capture,
426 // a *successful* build's output is no longer discarded outright.
427 if let Some(argv) = &spec.pre_build {
428 run_pre_build(ctx.workspace_root, argv, &log_buf).await?;
429 }
430
431 let mut build_log_end = None;
432 if let Some(pkg) = &spec.cargo_package {
433 cargo_build(ctx.workspace_root, pkg, &spec.profile, &log_buf).await?;
434 let cursor = log_buf.cursor().await;
435 build_log_end = Some(cursor);
436 if let Some(sink) = &self.build_log_end_sink {
437 sink.set(cursor).await;
438 }
439 }
440
441 let bin = resolve_binary(&spec, ctx.workspace_root)?;
442
443 // Kamaji's native backend captures stdio under this dir; scope it per
444 // workspace so concurrent camps don't collide on the same ident.
445 let state_dir = ctx.workspace_root.join(".yah/jit/native");
446 let ident_str = sanitize_ident(&format!(
447 "local-process-{}-{}-{}",
448 ctx.service.name, ctx.env, ctx.component.id
449 ));
450 let ident = MeshIdent(ident_str.clone());
451
452 // Replace any predecessor before spawning. `ContainerReconciler` has
453 // the same semantics ("run clears any prior container of the same name
454 // first"), and here it is load-bearing rather than tidy: NativeRuntime
455 // keeps its workload table **in memory**, so a second `mirror up` from
456 // a fresh process knows nothing about the first. Without this the new
457 // child dies on `Address already in use`, `wait_for_port` sees the
458 // *old* listener still answering, and the reconcile reports success
459 // while the binary the operator just edited is not the one running.
460 // That is the R602-B4 foreign-listener failure with a friendlier
461 // disguise, and on the dev tier it is the single most costly thing
462 // this reconciler could get wrong.
463 let owner_path = state_dir.join(&ident_str).join("owner.json");
464 reap_predecessor(&owner_path).await;
465
466 // Anything still holding the port now is not ours. Refuse rather than
467 // adopt it: a `dev_url` that answers with someone else's service is
468 // worse than a failed bring-up. A portless component has no address to
469 // contend over, so there is nothing to check.
470 let addr = spec
471 .port
472 .map(|port| SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), port));
473 if let Some(addr) = addr {
474 if tokio::net::TcpStream::connect(addr).await.is_ok() {
475 bail!(
476 "component {}: {addr} is already held by a process this reconciler did not \
477 start. Stop it, or give [process] a different `port`.",
478 ctx.component.id,
479 );
480 }
481 }
482
483 let mut argv = vec![bin.display().to_string()];
484 argv.extend(spec.args.iter().cloned());
485
486 // Process-control channel. Resolved before the spawn because the
487 // socket variant has to reach the child in its environment — a
488 // conforming process binds `$YAH_CONTROL_SOCK` and does nothing when
489 // it is unset, so the same binary runs outside a camp untouched.
490 let control = control_endpoint(&spec, &state_dir, &ident_str);
491 if let Some(ControlEndpoint::Socket(path)) = &control {
492 // A socket file left by the predecessor makes `bind` fail with
493 // EADDRINUSE even though nothing is listening on it. Reaping the
494 // process does not remove it; unlinking here does.
495 if let Some(dir) = path.parent() {
496 tokio::fs::create_dir_all(dir).await.ok();
497 }
498 tokio::fs::remove_file(path).await.ok();
499 }
500
501 let mut env: Vec<EnvVar> = spec
502 .env
503 .iter()
504 .map(|(name, value)| EnvVar {
505 name: name.clone(),
506 value: workload_spec::EnvValue::Literal {
507 value: value.clone(),
508 },
509 })
510 .collect();
511 if let Some(ControlEndpoint::Socket(path)) = &control {
512 // Declared `[process.env]` wins: an operator who set the variable
513 // by hand meant it.
514 if !spec.env.contains_key(proc_control::CONTROL_SOCK_ENV) {
515 env.push(EnvVar {
516 name: proc_control::CONTROL_SOCK_ENV.to_string(),
517 value: workload_spec::EnvValue::Literal {
518 value: path.display().to_string(),
519 },
520 });
521 }
522 }
523
524 let workload = native_spec(&ident_str, argv, env);
525 let runtime = Arc::new(NativeRuntime::new(&state_dir));
526 let mesh = MeshAssignment::inlined(Ipv4Addr::LOCALHOST);
527
528 info!(
529 binary = %bin.display(),
530 port = ?spec.port,
531 ident = %ident_str,
532 "spawning local-process component (kamaji native backend)",
533 );
534
535 let deployed = runtime
536 .deploy_workload(&workload, &mesh)
537 .await
538 .with_context(|| {
539 format!(
540 "deploying component {} via kamaji native backend (binary {})",
541 ctx.component.id,
542 bin.display(),
543 )
544 })?;
545
546 let (stdout_path, stderr_path) = capture_paths(&state_dir, &ident_str);
547
548 // Record ownership so the *next* reconcile — in a different process,
549 // with a different in-memory NativeRuntime — can find and reap this
550 // child instead of colliding with it.
551 write_owner(&owner_path, deployed.task_pid as i32, spec.port).await;
552
553 // Readiness, best signal first.
554 //
555 // 1. The control channel, when declared: the process says when it is
556 // serving. Nothing else here can distinguish "bound" from "ready".
557 // 2. The port bind: a dead process must not hand the Run tab a URL
558 // that will never answer.
559 // 3. Still alive after a grace window: all a portless process that
560 // declines the channel can offer.
561 let mut notes: Vec<String> = Vec::new();
562
563 if let Some(endpoint) = &control {
564 match proc_control::wait_ready(endpoint, READY_TIMEOUT).await {
565 ReadyOutcome::Ready(status) => {
566 info!(
567 endpoint = %endpoint,
568 status = %status.summary(),
569 "local-process reported ready over its control channel",
570 );
571 notes.push(format!("control: {}", status.summary()));
572 }
573 ReadyOutcome::Terminal(status) => {
574 let tail = read_capture_tail(&stdout_path, &stderr_path).await;
575 runtime.teardown_workload(&ident).await.ok();
576 bail!(
577 "component {} reported `{}` on its control channel ({}){tail}",
578 ctx.component.id,
579 status.summary(),
580 endpoint,
581 );
582 }
583 ReadyOutcome::TimedOut { last } => {
584 let tail = read_capture_tail(&stdout_path, &stderr_path).await;
585 runtime.teardown_workload(&ident).await.ok();
586 let seen = match last {
587 Some(s) => format!("last reported `{}`", s.summary()),
588 None => "never answered — is it binding $YAH_CONTROL_SOCK?".to_string(),
589 };
590 bail!(
591 "component {} was not ready within {READY_TIMEOUT:?} on {endpoint} \
592 ({seen}){tail}",
593 ctx.component.id,
594 );
595 }
596 }
597 }
598
599 let dev_url = match addr {
600 Some(addr) => {
601 // Already ready per the control channel? Then the bind has
602 // happened by definition, and re-waiting would only add
603 // latency to a process that already said it is serving.
604 if control.is_none() && !wait_for_port(addr, READY_TIMEOUT).await {
605 warn!(addr = %addr, "local-process did not bind within timeout; tearing down");
606 let tail = read_capture_tail(&stdout_path, &stderr_path).await;
607 runtime.teardown_workload(&ident).await.ok();
608 bail!(
609 "component {} did not bind {addr} within {READY_TIMEOUT:?}{tail}",
610 ctx.component.id,
611 );
612 }
613 Some(format!("http://{addr}"))
614 }
615 None => {
616 if control.is_none() {
617 tokio::time::sleep(ALIVE_GRACE).await;
618 if !pid_alive(deployed.task_pid as i32) {
619 let tail = read_capture_tail(&stdout_path, &stderr_path).await;
620 runtime.teardown_workload(&ident).await.ok();
621 bail!(
622 "component {} (portless) exited within {ALIVE_GRACE:?} of \
623 starting{tail}",
624 ctx.component.id,
625 );
626 }
627 notes.push(
628 "portless with no [process.control] — readiness is liveness only; \
629 see yah-cloud's proc_control module"
630 .to_string(),
631 );
632 }
633 None
634 }
635 };
636 info!(dev_url = ?dev_url, pid = deployed.task_pid, "local-process ready");
637
638 let (shutdown_tx, shutdown_rx) = oneshot::channel::<()>();
639 let supervisor = spawn_native_log_supervisor(
640 runtime,
641 ident,
642 log_buf.clone(),
643 stdout_path,
644 stderr_path,
645 shutdown_rx,
646 );
647
648 Ok(into_running(
649 "local-process",
650 SLOT,
651 dev_url,
652 None,
653 Some(log_buf),
654 shutdown_tx,
655 supervisor,
656 )
657 .with_notes(notes)
658 .with_control(control)
659 .with_build_log_end(build_log_end))
660 }
661}
662
663/// Resolve `[process.control]` into an endpoint to poll, or `None` when the
664/// component declines the channel.
665///
666/// HTTP needs a port to hang off — a component asking for `http_path` without
667/// a `port` has contradicted itself, and falling back to the socket silently
668/// would hide that. It is reported as no endpoint at all rather than guessed
669/// at; the caller then treats the process as unmonitored, which is the honest
670/// reading of a self-contradicting declaration.
671fn control_endpoint(
672 spec: &ProcessSpec,
673 state_dir: &std::path::Path,
674 ident: &str,
675) -> Option<ControlEndpoint> {
676 let control = spec.control.as_ref()?;
677 if let Some(path) = &control.http_path {
678 let port = spec.port?;
679 let path = if path.is_empty() {
680 proc_control::DEFAULT_HTTP_PATH
681 } else {
682 path
683 };
684 return Some(ControlEndpoint::Http(format!(
685 "http://127.0.0.1:{port}{path}"
686 )));
687 }
688 let sock = match &control.socket {
689 Some(s) => PathBuf::from(s),
690 None => state_dir.join(ident).join("control.sock"),
691 };
692 Some(ControlEndpoint::Socket(sock))
693}
694
695/// Read `<workload_dir>/workload.toml` and pull out its `[process]` section.
696fn load_process_spec(ctx: &ReconcileCtx<'_>) -> Result<ProcessSpec> {
697 let path = ctx.workload_dir().join("workload.toml");
698 let src =
699 std::fs::read_to_string(&path).with_context(|| format!("reading {}", path.display()))?;
700 let parsed: ProcessComponent =
701 toml::from_str(&src).with_context(|| format!("parsing {}", path.display()))?;
702 parsed.process.with_context(|| {
703 format!(
704 "component {} is bound to a `local-process` compute slot but {} declares no \
705 [process] section — add one with at least `bin` or `cargo_package`",
706 ctx.component.id,
707 path.display(),
708 )
709 })
710}
711
712/// Resolve the binary to exec: explicit `bin`, else the cargo convention.
713fn resolve_binary(spec: &ProcessSpec, workspace_root: &std::path::Path) -> Result<PathBuf> {
714 let rel = match (&spec.bin, &spec.cargo_package) {
715 (Some(bin), _) => PathBuf::from(bin),
716 (None, Some(pkg)) => PathBuf::from(format!("target/{}/{pkg}", spec.profile)),
717 (None, None) => bail!(
718 "[process] declares neither `bin` nor `cargo_package` — one is needed to know \
719 what to run"
720 ),
721 };
722 let path = if rel.is_absolute() {
723 rel
724 } else {
725 workspace_root.join(rel)
726 };
727 if !path.exists() {
728 bail!(
729 "[process] binary {} does not exist — set `cargo_package` to have it built, or \
730 point `bin` at an existing file",
731 path.display(),
732 );
733 }
734 Ok(path)
735}
736
737/// Run `[process.pre_build]`'s argv to completion in `workspace_root`,
738/// streamed live into `log_buf` via the same [`run_streaming`] `cargo_build`
739/// uses. Runs before `cargo_package`'s build (if any) so a failing pre_build
740/// step surfaces as its own error rather than as a confusing downstream
741/// build/spawn failure.
742async fn run_pre_build(
743 workspace_root: &std::path::Path,
744 argv: &[String],
745 log_buf: &LogBuffer,
746) -> Result<()> {
747 let (program, args) = argv
748 .split_first()
749 .context("[process.pre_build] argv must have at least one element")?;
750 let mut cmd = tokio::process::Command::new(program);
751 cmd.args(args);
752 cmd.current_dir(workspace_root);
753
754 info!(cmd = %argv.join(" "), "running [process.pre_build] for local-process component");
755 let (ok, stderr_tail) = run_streaming(cmd, log_buf)
756 .await
757 .with_context(|| format!("spawning pre_build command `{}`", argv.join(" ")))?;
758 if !ok {
759 bail!(
760 "[process.pre_build] `{}` failed:\n{}",
761 argv.join(" "),
762 stderr_tail.join("\n")
763 );
764 }
765 Ok(())
766}
767
768/// Lines of trailing stderr [`run_streaming`] keeps in memory to fold into a
769/// failure's error message. Compiler diagnostics are what an operator needs
770/// to act on a failed build; the full transcript is in `log_buf` regardless.
771const STDERR_TAIL_CAP: usize = 30;
772
773/// `cargo build -p <pkg>` in the workspace root, streamed live into `log_buf`
774/// (R715 follow-up — the desktop has no console to inherit stdout/stderr
775/// into, so this is the only way build progress reaches the Run tab, and
776/// unlike a buffer-then-discard capture it doesn't drop a *successful*
777/// build's output on the floor).
778async fn cargo_build(
779 workspace_root: &std::path::Path,
780 pkg: &str,
781 profile: &str,
782 log_buf: &LogBuffer,
783) -> Result<()> {
784 let mut cmd = tokio::process::Command::new("cargo");
785 cmd.arg("build").arg("-p").arg(pkg);
786 if profile == "release" {
787 cmd.arg("--release");
788 } else if profile != "debug" {
789 cmd.arg("--profile").arg(profile);
790 }
791 cmd.current_dir(workspace_root);
792
793 info!(
794 package = pkg,
795 profile, "cargo build for local-process component"
796 );
797 let (ok, stderr_tail) = run_streaming(cmd, log_buf)
798 .await
799 .with_context(|| format!("spawning `cargo build -p {pkg}`"))?;
800 if !ok {
801 bail!("cargo build -p {pkg} failed:\n{}", stderr_tail.join("\n"));
802 }
803 Ok(())
804}
805
806/// Run `cmd` to completion, streaming stdout and stderr into `log_buf`
807/// line-by-line as they're produced — not buffered until exit, so a slow
808/// command shows progress instead of going silent until it's done. Returns
809/// whether it exited successfully plus the last [`STDERR_TAIL_CAP`] stderr
810/// lines, which a caller can fold into its own error on failure without
811/// re-reading `log_buf` (a compiler's diagnostics land on stderr, so that's
812/// the stream worth quoting back).
813async fn run_streaming(mut cmd: tokio::process::Command, log_buf: &LogBuffer) -> Result<(bool, Vec<String>)> {
814 use tokio::io::{AsyncBufReadExt, BufReader};
815
816 cmd.stdout(std::process::Stdio::piped());
817 cmd.stderr(std::process::Stdio::piped());
818 let mut child = cmd.spawn().context("spawning command")?;
819 let stdout = child.stdout.take().expect("stdout piped above");
820 let stderr = child.stderr.take().expect("stderr piped above");
821
822 let stderr_tail: Arc<AsyncMutex<VecDeque<String>>> = Arc::new(AsyncMutex::new(VecDeque::new()));
823
824 let out_task = {
825 let log_buf = log_buf.clone();
826 tokio::spawn(async move {
827 let mut lines = BufReader::new(stdout).lines();
828 while let Ok(Some(line)) = lines.next_line().await {
829 log_buf.push(line).await;
830 }
831 })
832 };
833 let err_task = {
834 let log_buf = log_buf.clone();
835 let tail = stderr_tail.clone();
836 tokio::spawn(async move {
837 let mut lines = BufReader::new(stderr).lines();
838 while let Ok(Some(line)) = lines.next_line().await {
839 log_buf.push(line.clone()).await;
840 let mut t = tail.lock().await;
841 t.push_back(line);
842 if t.len() > STDERR_TAIL_CAP {
843 t.pop_front();
844 }
845 }
846 })
847 };
848
849 let status = child
850 .wait()
851 .await
852 .context("waiting on spawned command")?;
853 // The drain tasks were spawned onto the runtime above, so they've been
854 // reading concurrently with `wait()` regardless of join order; awaiting
855 // them here just confirms both pipes hit EOF before returning the tail.
856 let _ = out_task.await;
857 let _ = err_task.await;
858
859 let tail = stderr_tail.lock().await.iter().cloned().collect();
860 Ok((status.success(), tail))
861}
862
863/// What a previous `up()` recorded about the child it left running.
864///
865/// This exists because [`NativeRuntime`]'s workload table is in-memory: a
866/// `yah cloud mirror up` from the shell and a ▶ click in the desktop are
867/// different processes, and neither can see the other's children. The sidecar
868/// is the only thing that makes "replace the predecessor" possible across them.
869#[derive(Debug, serde::Serialize, Deserialize)]
870struct OwnerRecord {
871 pid: i32,
872 /// The port the recorded child bound, when it declared one. `default` so a
873 /// sidecar written before portless components existed still parses — those
874 /// records always carry a port, and a missing one now means portless.
875 #[serde(default)]
876 port: Option<u16>,
877}
878
879/// Record the child we just spawned. Best-effort: failing to write the sidecar
880/// must not fail an otherwise-successful bring-up — the cost is a manual kill
881/// on the next re-run, not a broken mirror.
882async fn write_owner(path: &std::path::Path, pid: i32, port: Option<u16>) {
883 if let Some(dir) = path.parent() {
884 if tokio::fs::create_dir_all(dir).await.is_err() {
885 return;
886 }
887 }
888 if let Ok(json) = serde_json::to_vec(&OwnerRecord { pid, port }) {
889 if let Err(e) = tokio::fs::write(path, json).await {
890 warn!(path = %path.display(), error = %e, "could not record local-process owner");
891 }
892 }
893}
894
895/// Stop the child a previous `up()` left behind, if it is still alive.
896///
897/// SIGTERM, a short grace, then SIGKILL — the same ladder kamaji's own teardown
898/// uses. The sidecar is removed either way, including when the pid is already
899/// gone, so a stale record can't linger and make the next run think it has a
900/// predecessor to wait on.
901async fn reap_predecessor(owner_path: &std::path::Path) {
902 let Ok(bytes) = tokio::fs::read(owner_path).await else {
903 return;
904 };
905 let _ = tokio::fs::remove_file(owner_path).await;
906 let Ok(owner) = serde_json::from_slice::<OwnerRecord>(&bytes) else {
907 return;
908 };
909 if !pid_alive(owner.pid) {
910 return;
911 }
912
913 info!(
914 pid = owner.pid,
915 port = ?owner.port,
916 "replacing predecessor local-process"
917 );
918 signal_pid(owner.pid, libc::SIGTERM);
919 for _ in 0..50 {
920 if !pid_alive(owner.pid) {
921 return;
922 }
923 tokio::time::sleep(Duration::from_millis(100)).await;
924 }
925 warn!(
926 pid = owner.pid,
927 "predecessor ignored SIGTERM; sending SIGKILL"
928 );
929 signal_pid(owner.pid, libc::SIGKILL);
930 // Give the kernel a moment to release the port before we probe it.
931 tokio::time::sleep(Duration::from_millis(200)).await;
932}
933
934/// `kill(pid, 0)` — true when a process with this pid exists and we may signal
935/// it. Cannot prove the pid is still *our* child (pids are reused), which is
936/// why the sidecar is written next to this workload's capture dir and removed
937/// on every read: the window where a recycled pid could be signalled is one
938/// reconcile wide, and the alternative (never reaping) is a guaranteed
939/// collision rather than a theoretical one.
940fn pid_alive(pid: i32) -> bool {
941 // SAFETY: `kill` with signal 0 performs error checking only and never
942 // delivers a signal; any pid value is a defined input.
943 unsafe { libc::kill(pid, 0) == 0 }
944}
945
946fn signal_pid(pid: i32, sig: i32) {
947 // SAFETY: same contract as above — `kill` is defined for any pid/signal
948 // pair and reports failure through its return value, which we ignore
949 // because a vanished process is the outcome we wanted anyway.
950 unsafe {
951 libc::kill(pid, sig);
952 }
953}
954
955/// Last few lines of the capture files, formatted for an error message. A bind
956/// timeout with no output is nearly impossible to act on; the process almost
957/// always said why on the way down.
958async fn read_capture_tail(stdout_path: &std::path::Path, stderr_path: &std::path::Path) -> String {
959 let mut lines: Vec<String> = Vec::new();
960 for path in [stderr_path, stdout_path] {
961 if let Ok(s) = tokio::fs::read_to_string(path).await {
962 lines.extend(s.lines().rev().take(10).map(str::to_string));
963 }
964 }
965 if lines.is_empty() {
966 return String::new();
967 }
968 lines.reverse();
969 format!("\nlast output:\n{}", lines.join("\n"))
970}
971
972#[cfg(test)]
973mod tests {
974 use super::*;
975
976 /// `run_streaming` interleaves stdout/stderr into `log_buf` as the child
977 /// produces them (not buffered until exit), reports success/failure by
978 /// exit status, and keeps a bounded stderr tail for the caller's error
979 /// message — the shape `cargo_build` builds on, exercised here without
980 /// depending on an actual `cargo` invocation.
981 #[tokio::test]
982 async fn run_streaming_captures_both_streams_and_reports_failure() {
983 let log_buf = LogBuffer::new();
984 let mut cmd = tokio::process::Command::new("sh");
985 cmd.arg("-c")
986 .arg("echo out-line; echo err-line >&2; exit 3");
987
988 let (ok, tail) = run_streaming(cmd, &log_buf).await.unwrap();
989 assert!(!ok, "exit 3 must be reported as failure");
990 assert_eq!(tail, vec!["err-line".to_string()]);
991
992 let (lines, _) = log_buf.since(0).await;
993 assert!(lines.contains(&"out-line".to_string()), "{lines:?}");
994 assert!(lines.contains(&"err-line".to_string()), "{lines:?}");
995 }
996
997 /// The tail exists so a failure's error message doesn't have to re-read
998 /// `log_buf` — but it must stay bounded, or a build that fails after
999 /// paging through thousands of warnings dumps all of them into the error.
1000 #[tokio::test]
1001 async fn run_streaming_bounds_the_stderr_tail() {
1002 let log_buf = LogBuffer::new();
1003 let mut cmd = tokio::process::Command::new("sh");
1004 cmd.arg("-c").arg("for i in $(seq 1 50); do echo \"e$i\" >&2; done; exit 1");
1005
1006 let (ok, tail) = run_streaming(cmd, &log_buf).await.unwrap();
1007 assert!(!ok);
1008 assert_eq!(tail.len(), STDERR_TAIL_CAP);
1009 assert_eq!(tail.first(), Some(&"e21".to_string()));
1010 assert_eq!(tail.last(), Some(&"e50".to_string()));
1011
1012 // Every line still reached the log buffer, unbounded — only the
1013 // in-memory tail kept for the error message is capped.
1014 let (lines, _) = log_buf.since(0).await;
1015 assert_eq!(lines.len(), 50);
1016 }
1017
1018 fn spec(bin: Option<&str>, pkg: Option<&str>) -> ProcessSpec {
1019 ProcessSpec {
1020 pre_build: None,
1021 cargo_package: pkg.map(str::to_string),
1022 bin: bin.map(str::to_string),
1023 args: vec![],
1024 port: Some(4325),
1025 env: BTreeMap::new(),
1026 profile: "debug".to_string(),
1027 control: None,
1028 }
1029 }
1030
1031 #[test]
1032 fn parses_a_process_section_alongside_container_sections() {
1033 // One workload.toml describes both tiers; each reconciler reads its own
1034 // section and ignores the other's.
1035 let src = r#"
1036schema_version = 1
1037kind = "container"
1038
1039[build]
1040image = "yah-local/x:dev"
1041
1042[run]
1043port = 4325
1044
1045[process]
1046cargo_package = "yah-cloud-admin"
1047port = 4325
1048args = ["--verbose"]
1049
1050[process.env]
1051YAH_CLOUD_ADMIN_ADDR = "127.0.0.1:4325"
1052"#;
1053 let c: ProcessComponent = toml::from_str(src).unwrap();
1054 let p = c.process.unwrap();
1055 assert_eq!(p.cargo_package.as_deref(), Some("yah-cloud-admin"));
1056 assert_eq!(p.port, Some(4325));
1057 assert_eq!(p.args, vec!["--verbose".to_string()]);
1058 assert_eq!(p.profile, "debug");
1059 assert_eq!(
1060 p.env.get("YAH_CLOUD_ADMIN_ADDR").map(String::as_str),
1061 Some("127.0.0.1:4325")
1062 );
1063 }
1064
1065 /// R715-T2: the noisetable shape — a native GUI with no network surface.
1066 /// `port` must be *absent*, not zero: a zero would be a real port number
1067 /// to every layer downstream that reads one.
1068 #[test]
1069 fn a_process_section_without_a_port_is_portless() {
1070 let src = r#"
1071[process]
1072cargo_package = "dev"
1073profile = "release"
1074args = ["--window"]
1075"#;
1076 let p: ProcessComponent = toml::from_str(src).unwrap();
1077 let p = p.process.unwrap();
1078 assert_eq!(p.port, None, "an omitted port must stay absent");
1079 assert_eq!(p.cargo_package.as_deref(), Some("dev"));
1080 assert_eq!(p.profile, "release");
1081 }
1082
1083 /// The macOS/iOS shape: no `cargo_package` (there is no runnable
1084 /// top-level binary from a plain `cargo build -p pkg` — Rust only
1085 /// supplies a static lib for Xcode), the entire build is `pre_build`.
1086 #[test]
1087 fn parses_a_pre_build_argv() {
1088 let src = r#"
1089[process]
1090pre_build = ["./build-dist.sh", "arm64", "--sign"]
1091bin = "app/macos/dist/NoiseTable.app/Contents/MacOS/NoiseTable"
1092"#;
1093 let p: ProcessComponent = toml::from_str(src).unwrap();
1094 let p = p.process.unwrap();
1095 assert_eq!(
1096 p.pre_build,
1097 Some(vec![
1098 "./build-dist.sh".to_string(),
1099 "arm64".to_string(),
1100 "--sign".to_string(),
1101 ])
1102 );
1103 assert_eq!(p.cargo_package, None);
1104 }
1105
1106 /// The house default: a portless component opting into the control
1107 /// channel with an empty `[process.control]` and nothing else. The socket
1108 /// path is the supervisor's to choose — the process reads it from
1109 /// `$YAH_CONTROL_SOCK`.
1110 #[test]
1111 fn an_empty_control_section_yields_the_supervisor_chosen_socket() {
1112 let src = r#"
1113[process]
1114cargo_package = "dev"
1115
1116[process.control]
1117"#;
1118 let c: ProcessComponent = toml::from_str(src).unwrap();
1119 let spec = c.process.unwrap();
1120 let got = control_endpoint(&spec, std::path::Path::new("/s"), "svc-dev-app");
1121 assert_eq!(
1122 got,
1123 Some(ControlEndpoint::Socket(PathBuf::from(
1124 "/s/svc-dev-app/control.sock"
1125 ))),
1126 );
1127 }
1128
1129 #[test]
1130 fn no_control_section_means_no_channel() {
1131 assert_eq!(
1132 control_endpoint(&spec(Some("bin/x"), None), std::path::Path::new("/s"), "id"),
1133 None,
1134 );
1135 }
1136
1137 #[test]
1138 fn an_http_path_binds_the_channel_to_the_declared_port() {
1139 let src = r#"
1140[process]
1141cargo_package = "svc"
1142port = 4325
1143
1144[process.control]
1145http_path = "/_yah/status"
1146"#;
1147 let spec = toml::from_str::<ProcessComponent>(src).unwrap().process.unwrap();
1148 assert_eq!(
1149 control_endpoint(&spec, std::path::Path::new("/s"), "id"),
1150 Some(ControlEndpoint::Http(
1151 "http://127.0.0.1:4325/_yah/status".into()
1152 )),
1153 );
1154 }
1155
1156 /// An empty `http_path` means "the conventional one" rather than a URL
1157 /// ending in the port — the shape most likely to be written by hand.
1158 #[test]
1159 fn an_empty_http_path_falls_back_to_the_conventional_one() {
1160 let src = r#"
1161[process]
1162cargo_package = "svc"
1163port = 4325
1164
1165[process.control]
1166http_path = ""
1167"#;
1168 let spec = toml::from_str::<ProcessComponent>(src).unwrap().process.unwrap();
1169 assert_eq!(
1170 control_endpoint(&spec, std::path::Path::new("/s"), "id"),
1171 Some(ControlEndpoint::Http(format!(
1172 "http://127.0.0.1:4325{}",
1173 crate::proc_control::DEFAULT_HTTP_PATH
1174 ))),
1175 );
1176 }
1177
1178 /// `http_path` with no port is a contradiction. Silently falling back to a
1179 /// socket would give the component a channel it never agreed to serve, and
1180 /// then fail readiness twenty seconds later with a message about a socket
1181 /// nobody mentioned.
1182 #[test]
1183 fn an_http_path_without_a_port_yields_no_endpoint() {
1184 let src = r#"
1185[process]
1186cargo_package = "svc"
1187
1188[process.control]
1189http_path = "/_yah/status"
1190"#;
1191 let spec = toml::from_str::<ProcessComponent>(src).unwrap().process.unwrap();
1192 assert_eq!(control_endpoint(&spec, std::path::Path::new("/s"), "id"), None);
1193 }
1194
1195 #[test]
1196 fn an_explicit_socket_path_overrides_the_default() {
1197 let src = r#"
1198[process]
1199cargo_package = "svc"
1200
1201[process.control]
1202socket = "/tmp/mine.sock"
1203"#;
1204 let spec = toml::from_str::<ProcessComponent>(src).unwrap().process.unwrap();
1205 assert_eq!(
1206 control_endpoint(&spec, std::path::Path::new("/s"), "id"),
1207 Some(ControlEndpoint::Socket(PathBuf::from("/tmp/mine.sock"))),
1208 );
1209 }
1210
1211 /// The sidecar gained an optional `port` when portless components landed.
1212 /// Records written before that carry a bare `u16` and must still parse —
1213 /// otherwise the first reconcile after an upgrade silently fails to reap
1214 /// its predecessor, which is the exact collision the sidecar exists for.
1215 #[test]
1216 fn an_owner_record_written_before_portless_components_still_parses() {
1217 let old: OwnerRecord = serde_json::from_str(r#"{"pid":54869,"port":4325}"#).unwrap();
1218 assert_eq!(old.pid, 54869);
1219 assert_eq!(old.port, Some(4325));
1220
1221 let portless: OwnerRecord = serde_json::from_str(r#"{"pid":71455}"#).unwrap();
1222 assert_eq!(portless.port, None);
1223 }
1224
1225 #[test]
1226 fn a_workload_without_a_process_section_parses_as_none() {
1227 let c: ProcessComponent = toml::from_str("[run]\nport = 1\n").unwrap();
1228 assert!(c.process.is_none());
1229 }
1230
1231 #[test]
1232 fn binary_defaults_to_the_cargo_convention() {
1233 let tmp = tempfile::tempdir().unwrap();
1234 std::fs::create_dir_all(tmp.path().join("target/debug")).unwrap();
1235 std::fs::write(tmp.path().join("target/debug/yah-cloud-admin"), b"").unwrap();
1236 let got = resolve_binary(&spec(None, Some("yah-cloud-admin")), tmp.path()).unwrap();
1237 assert_eq!(got, tmp.path().join("target/debug/yah-cloud-admin"));
1238 }
1239
1240 #[test]
1241 fn explicit_bin_wins_over_the_cargo_convention() {
1242 let tmp = tempfile::tempdir().unwrap();
1243 std::fs::create_dir_all(tmp.path().join("bin")).unwrap();
1244 std::fs::write(tmp.path().join("bin/custom"), b"").unwrap();
1245 let got = resolve_binary(&spec(Some("bin/custom"), Some("pkg")), tmp.path()).unwrap();
1246 assert_eq!(got, tmp.path().join("bin/custom"));
1247 }
1248
1249 /// Spawning a path that isn't there fails with an exec error several
1250 /// layers down; naming the missing file here is the actionable version.
1251 #[test]
1252 fn a_missing_binary_is_named_before_we_try_to_exec_it() {
1253 let tmp = tempfile::tempdir().unwrap();
1254 let err = resolve_binary(&spec(None, Some("nope")), tmp.path()).unwrap_err();
1255 assert!(err.to_string().contains("does not exist"), "{err}");
1256 }
1257
1258 #[test]
1259 fn neither_bin_nor_package_is_an_error() {
1260 let tmp = tempfile::tempdir().unwrap();
1261 let err = resolve_binary(&spec(None, None), tmp.path()).unwrap_err();
1262 assert!(err.to_string().contains("neither"), "{err}");
1263 }
1264
1265 /// The bug this whole path exists to prevent: a second `up()` in a fresh
1266 /// process must stop the first one's child. NativeRuntime's table is
1267 /// in-memory, so the sidecar is the only link between the two runs.
1268 ///
1269 /// The assertion is on the child's exit status, not on [`pid_alive`],
1270 /// because this test *is* the child's parent: a signalled child it has not
1271 /// waited on stays a zombie, and `kill(pid, 0)` succeeds against a zombie.
1272 /// In production the spawning process is either gone (CLI — init reaps) or
1273 /// still holding kamaji's supervisor task (desktop — that reaps), so
1274 /// neither leaves one behind.
1275 #[tokio::test]
1276 async fn reap_stops_a_live_predecessor_and_clears_the_record() {
1277 let tmp = tempfile::tempdir().unwrap();
1278 let owner_path = tmp.path().join("owner.json");
1279
1280 let mut child = tokio::process::Command::new("sleep")
1281 .arg("120")
1282 .spawn()
1283 .unwrap();
1284 let pid = child.id().unwrap() as i32;
1285 assert!(pid_alive(pid));
1286
1287 write_owner(&owner_path, pid, Some(4325)).await;
1288 reap_predecessor(&owner_path).await;
1289
1290 let status = tokio::time::timeout(Duration::from_secs(5), child.wait())
1291 .await
1292 .expect("a signalled `sleep 120` must have exited well inside 5s")
1293 .unwrap();
1294 assert!(!status.success(), "predecessor should have been signalled");
1295 assert!(!owner_path.exists(), "sidecar should be cleared");
1296 }
1297
1298 /// A record left behind by a crash names a pid that is gone. Reaping it
1299 /// must be a no-op that still clears the file — a stale record that
1300 /// survives would make every later run wait on a corpse.
1301 #[tokio::test]
1302 async fn reap_clears_a_stale_record_without_signalling_anything() {
1303 let tmp = tempfile::tempdir().unwrap();
1304 let owner_path = tmp.path().join("owner.json");
1305
1306 // Exited process: spawn and wait, so the pid is definitely dead.
1307 let mut child = tokio::process::Command::new("true").spawn().unwrap();
1308 let pid = child.id().unwrap() as i32;
1309 child.wait().await.unwrap();
1310
1311 write_owner(&owner_path, pid, Some(4325)).await;
1312 reap_predecessor(&owner_path).await;
1313 assert!(!owner_path.exists());
1314 }
1315
1316 #[tokio::test]
1317 async fn reap_with_no_record_is_a_no_op() {
1318 let tmp = tempfile::tempdir().unwrap();
1319 reap_predecessor(&tmp.path().join("owner.json")).await;
1320 }
1321
1322 // ── End-to-end: a portless component through the real reconciler ────────
1323 //
1324 // The unit tests above pin parsing and endpoint resolution. This one runs
1325 // `up()` itself — kamaji native backend, real child process, real sidecar
1326 // — because the claim R715-T2 makes is not "the struct has an Option", it
1327 // is "a component with no port comes up and reports no dev_url", and only
1328 // the whole path can say that.
1329
1330 fn portless_service() -> crate::ServiceConfig {
1331 crate::ServiceConfig {
1332 schema_version: 1,
1333 name: "noisy".into(),
1334 domain: "noisy.example".into(),
1335 components: vec![crate::ServiceComponent {
1336 mount: None,
1337 id: "gui".into(),
1338 kind: "container".into(),
1339 path: "gui".into(),
1340 role: "compute".into(),
1341 publishes: None,
1342 wave: 0,
1343 git: None,
1344 }],
1345 db: crate::DbCatalog::default(),
1346 }
1347 }
1348
1349 fn local_process_mirror() -> crate::MirrorConfig {
1350 let mut providers = BTreeMap::new();
1351 providers.insert(
1352 SLOT.to_string(),
1353 MirrorProviderSlot::Inline {
1354 kind: Provider::LocalProcess,
1355 fields: Default::default(),
1356 },
1357 );
1358 crate::MirrorConfig {
1359 schema_version: 1,
1360 shape: MirrorShape::Local,
1361 providers,
1362 ingress: Default::default(),
1363 ingress_machines: Vec::new(),
1364 drivers: Default::default(),
1365 asset_aliases: Default::default(),
1366 }
1367 }
1368
1369 /// The noisetable shape end to end: no `port`, no control channel. Comes
1370 /// up, reports no `dev_url`, and says in its notes that readiness here is
1371 /// liveness only — so nobody reads a green row as a health claim.
1372 #[tokio::test]
1373 async fn a_portless_component_comes_up_with_no_dev_url() {
1374 let ws = tempfile::tempdir().unwrap();
1375 std::fs::create_dir_all(ws.path().join("gui")).unwrap();
1376 std::fs::write(
1377 ws.path().join("gui/workload.toml"),
1378 "schema_version = 1\nkind = \"container\"\n\n[process]\nbin = \"/bin/sleep\"\nargs = [\"30\"]\n",
1379 )
1380 .unwrap();
1381
1382 let svc = portless_service();
1383 let mirror = local_process_mirror();
1384 let ctx = ReconcileCtx {
1385 workspace_root: ws.path(),
1386 service: &svc,
1387 component: &svc.components[0],
1388 mirror: &mirror,
1389 env: "dev",
1390 scope: crate::ProviderScope::singleton(),
1391 };
1392
1393 let mut running = LocalProcessReconciler::new().up(ctx).await.unwrap();
1394 assert_eq!(running.dev_url, None, "a portless component has no URL");
1395 assert_eq!(running.slot, SLOT);
1396 assert_eq!(
1397 running.build_log_end, None,
1398 "no cargo_package was declared, so nothing was built"
1399 );
1400 assert!(
1401 running.notes.iter().any(|n| n.contains("portless")),
1402 "the liveness-only caveat must be visible to an operator: {:?}",
1403 running.notes,
1404 );
1405
1406 // The sidecar is what lets a later reconcile in another process reap
1407 // this child. Portless or not, it must be written — and its `port`
1408 // must be absent rather than a placeholder zero.
1409 let owner: OwnerRecord = serde_json::from_slice(
1410 &std::fs::read(
1411 ws.path()
1412 .join(".yah/jit/native")
1413 .join(sanitize_ident("local-process-noisy-dev-gui"))
1414 .join("owner.json"),
1415 )
1416 .expect("owner sidecar must exist"),
1417 )
1418 .unwrap();
1419 assert_eq!(owner.port, None);
1420 assert!(pid_alive(owner.pid), "the child should still be running");
1421
1422 if let Some(tx) = running.shutdown.take() {
1423 tx.send(()).ok();
1424 }
1425 if let Some(sup) = running.supervisor.take() {
1426 let _ = tokio::time::timeout(Duration::from_secs(5), sup).await;
1427 }
1428 }
1429
1430 /// The house default, end to end: a portless component that declares
1431 /// `[process.control]` is held at "not ready" until something answers
1432 /// `status` with `running`.
1433 ///
1434 /// The child here is `/bin/sleep` and the socket is served by the test,
1435 /// which is the point — the reconciler must not care *who* answers, only
1436 /// that the declared endpoint does. A real workload binds the same path
1437 /// out of `$YAH_CONTROL_SOCK`.
1438 #[tokio::test]
1439 async fn a_control_channel_decides_readiness_when_declared() {
1440 let ws = tempfile::tempdir().unwrap();
1441 let sock = ws.path().join("control.sock");
1442 std::fs::create_dir_all(ws.path().join("gui")).unwrap();
1443 std::fs::write(
1444 ws.path().join("gui/workload.toml"),
1445 format!(
1446 "schema_version = 1\nkind = \"container\"\n\n[process]\nbin = \"/bin/sleep\"\n\
1447 args = [\"30\"]\n\n[process.control]\nsocket = \"{}\"\n",
1448 sock.display()
1449 ),
1450 )
1451 .unwrap();
1452
1453 // Stand-in producer: answers `starting` once, then `running`.
1454 //
1455 // It binds *after* a delay on purpose. `up()` unlinks a predecessor's
1456 // socket file before spawning (a leftover file makes `bind` fail with
1457 // EADDRINUSE even with nobody listening), so a producer that bound
1458 // first would have its socket deleted out from under it — which is
1459 // exactly the order a real child sees: supervisor unlinks, child
1460 // starts, child binds.
1461 let server = {
1462 let sock = sock.clone();
1463 tokio::spawn(async move {
1464 tokio::time::sleep(Duration::from_millis(400)).await;
1465 let listener = tokio::net::UnixListener::bind(&sock).unwrap();
1466 for doc in [r#"{"state":"starting","detail":"loading"}"#, r#"{"state":"running","detail":"1 window"}"#] {
1467 let Ok((stream, _)) = listener.accept().await else {
1468 return;
1469 };
1470 let (rd, mut wr) = stream.into_split();
1471 let mut line = String::new();
1472 tokio::io::AsyncBufReadExt::read_line(
1473 &mut tokio::io::BufReader::new(rd),
1474 &mut line,
1475 )
1476 .await
1477 .ok();
1478 tokio::io::AsyncWriteExt::write_all(&mut wr, format!("{doc}\n").as_bytes())
1479 .await
1480 .ok();
1481 }
1482 })
1483 };
1484
1485 let svc = portless_service();
1486 let mirror = local_process_mirror();
1487 let ctx = ReconcileCtx {
1488 workspace_root: ws.path(),
1489 service: &svc,
1490 component: &svc.components[0],
1491 mirror: &mirror,
1492 env: "dev",
1493 scope: crate::ProviderScope::singleton(),
1494 };
1495
1496 let mut running = LocalProcessReconciler::new().up(ctx).await.unwrap();
1497 assert_eq!(running.dev_url, None);
1498 assert!(
1499 running
1500 .notes
1501 .iter()
1502 .any(|n| n.contains("control:") && n.contains("1 window")),
1503 "the process's own words should reach the operator: {:?}",
1504 running.notes,
1505 );
1506 assert!(
1507 !running.notes.iter().any(|n| n.contains("liveness only")),
1508 "a component WITH a channel must not be labelled liveness-only: {:?}",
1509 running.notes,
1510 );
1511
1512 server.abort();
1513 if let Some(tx) = running.shutdown.take() {
1514 tx.send(()).ok();
1515 }
1516 if let Some(sup) = running.supervisor.take() {
1517 let _ = tokio::time::timeout(Duration::from_secs(5), sup).await;
1518 }
1519 }
1520
1521 /// A portless component that dies on exec must fail the reconcile, not
1522 /// register a healthy row over a corpse. `/usr/bin/false` is the smallest
1523 /// honest stand-in for "binary exits immediately".
1524 #[tokio::test]
1525 async fn a_portless_component_that_exits_immediately_fails_the_reconcile() {
1526 let ws = tempfile::tempdir().unwrap();
1527 std::fs::create_dir_all(ws.path().join("gui")).unwrap();
1528 std::fs::write(
1529 ws.path().join("gui/workload.toml"),
1530 "schema_version = 1\nkind = \"container\"\n\n[process]\nbin = \"/usr/bin/false\"\n",
1531 )
1532 .unwrap();
1533
1534 let svc = portless_service();
1535 let mirror = local_process_mirror();
1536 let ctx = ReconcileCtx {
1537 workspace_root: ws.path(),
1538 service: &svc,
1539 component: &svc.components[0],
1540 mirror: &mirror,
1541 env: "dev",
1542 scope: crate::ProviderScope::singleton(),
1543 };
1544
1545 let err = LocalProcessReconciler::new()
1546 .up(ctx)
1547 .await
1548 .expect_err("a process that exits immediately is not a successful bring-up");
1549 assert!(
1550 err.to_string().contains("portless"),
1551 "the error should name why it was judged this way: {err}"
1552 );
1553 }
1554
1555 /// A failing `[process.pre_build]` must fail the reconcile before ever
1556 /// touching `cargo_package`/spawn — a broken xcodebuild/codesign step
1557 /// should surface as its own error, not as a confusing "binary not
1558 /// found" from a later stage that never should have run.
1559 #[tokio::test]
1560 async fn a_failing_pre_build_fails_the_reconcile_before_spawn() {
1561 let ws = tempfile::tempdir().unwrap();
1562 std::fs::create_dir_all(ws.path().join("gui")).unwrap();
1563 std::fs::write(
1564 ws.path().join("gui/workload.toml"),
1565 "schema_version = 1\nkind = \"container\"\n\n[process]\npre_build = [\"sh\", \"-c\", \"exit 1\"]\nbin = \"/bin/sleep\"\nargs = [\"30\"]\n",
1566 )
1567 .unwrap();
1568
1569 let svc = portless_service();
1570 let mirror = local_process_mirror();
1571 let ctx = ReconcileCtx {
1572 workspace_root: ws.path(),
1573 service: &svc,
1574 component: &svc.components[0],
1575 mirror: &mirror,
1576 env: "dev",
1577 scope: crate::ProviderScope::singleton(),
1578 };
1579
1580 let err = LocalProcessReconciler::new()
1581 .up(ctx)
1582 .await
1583 .expect_err("a failing pre_build must not be treated as a successful bring-up");
1584 assert!(
1585 err.to_string().contains("pre_build"),
1586 "the error should name the stage that failed: {err}"
1587 );
1588 }
1589
1590 #[test]
1591 fn mirror_profile_override_reads_the_inline_extra_field() {
1592 let mut mirror = local_process_mirror();
1593 if let Some(MirrorProviderSlot::Inline { fields, .. }) = mirror.providers.get_mut(SLOT) {
1594 fields.insert("profile".to_string(), toml::Value::String("release".to_string()));
1595 }
1596 assert_eq!(
1597 mirror_profile_override(&mirror),
1598 Some("release".to_string())
1599 );
1600 }
1601
1602 #[test]
1603 fn mirror_profile_override_is_absent_by_default() {
1604 // No `profile` key declared on the mirror's compute slot — falls back
1605 // to whatever workload.toml itself declares.
1606 assert_eq!(mirror_profile_override(&local_process_mirror()), None);
1607 }
1608
1609 #[test]
1610 fn slot_declared_only_matches_the_local_process_compute_slot() {
1611 let mut m = crate::MirrorConfig {
1612 schema_version: 1,
1613 shape: MirrorShape::Local,
1614 ingress: Default::default(),
1615 ingress_machines: Vec::new(),
1616 providers: Default::default(),
1617 drivers: Default::default(),
1618 asset_aliases: Default::default(),
1619 };
1620 assert!(!slot_declared(&m));
1621 m.providers.insert(
1622 SLOT.to_string(),
1623 MirrorProviderSlot::Inline {
1624 kind: Provider::LocalContainer,
1625 fields: Default::default(),
1626 },
1627 );
1628 assert!(!slot_declared(&m), "a container slot is not a process slot");
1629 m.providers.insert(
1630 SLOT.to_string(),
1631 MirrorProviderSlot::Inline {
1632 kind: Provider::LocalProcess,
1633 fields: Default::default(),
1634 },
1635 );
1636 assert!(slot_declared(&m));
1637 }
1638}