Skip to main content

smix_lease/
lib.rs

1//! Who holds a device, what they opened on it, and how to close it after
2//! they die.
3//!
4//! smix could always tear down what it started, as long as it was the one
5//! doing the tearing. Everything else — Ctrl-C on `xcodebuild`, closing
6//! Simulator.app, an IDE restart, a CI timeout, another agent's `pkill` —
7//! killed the process holding a runner, a recording and a booted simulator,
8//! and nothing anywhere remembered that those three things existed. The
9//! runner died by SIGKILL rather than the SIGINT that lets testmanagerd
10//! end the session cleanly, so macOS put up a crash-report dialog; the
11//! recording lost its mp4 trailer; the simulator stayed booted. Teardown
12//! then went looking for survivors by matching process command lines,
13//! which fails in both directions: it kills another project's runner, and
14//! it misses the one whose command line reads differently.
15//!
16//! A ledger fixes the direction of that question. Instead of "what looks
17//! like mine", the next smix command asks "what did the last holder write
18//! down", and closes exactly those things by the graceful path the holder
19//! never got to take. That is the whole idea: **a kill that had no
20//! graceful path gets one at the next startup.**
21//!
22//! Looking is separated from judging, in the shape [`crate::Facts`] shares
23//! with `smix-cli`'s readiness module: the caller probes the world, and
24//! everything after that is a pure function. It is what lets the ordering
25//! of a teardown be tested without a device.
26
27mod carry;
28mod guards;
29pub mod held;
30pub mod owners;
31pub mod store;
32pub mod vanish;
33pub use guards::*;
34
35use serde::{Deserialize, Serialize};
36
37/// How long a holder may go without a heartbeat before its lease is
38/// considered abandoned.
39///
40/// Holders beat every 30 s, so this tolerates two missed beats. The
41/// tolerance is not politeness: a machine under load — or one that just
42/// came back from sleep — can starve a healthy holder past a single
43/// interval, and declaring that holder dead would have a second process
44/// tear down a session that is still running.
45pub const STALE_AFTER_SECS: i64 = 90;
46
47/// Enough to recognise a process later, or refuse to signal it.
48///
49/// A pid alone is not an identity: it outlives the process that owned it
50/// and the kernel hands the number to somebody else, so a ledger written
51/// an hour ago may point at a stranger. The command line is not an
52/// identity either — every concurrent `smix run` has the same one. What
53/// does pin it is the pair (pid, start time): the kernel will not reissue
54/// a pid to a process that started at the same second, and `ps` reports
55/// both. The command line rides along because a person reading a refusal
56/// needs to know who holds the device, and a pid does not tell them.
57#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
58#[serde(rename_all = "camelCase")]
59pub struct ProcIdentity {
60    /// Process id.
61    pub pid: u32,
62    /// Start time as `ps -o lstart=` reports it. Compared verbatim; it is
63    /// an opaque token here, not a date to do arithmetic on.
64    pub started_at: String,
65    /// Command line, for the human reading a refusal.
66    pub cmd: String,
67}
68
69/// A resource a holder opened on a device, and therefore owes a close.
70///
71/// Every variant carries what the graceful close needs, and every variant
72/// that names a process carries its [`ProcIdentity`] so the executor can
73/// confirm the pid is still that process before signalling it.
74/// [`CleanupAction`] carries the identity onward — the executor cannot
75/// forget what it was never given.
76///
77/// `#[non_exhaustive]` because this list has grown five times and will
78/// grow again: a runner, a recording, a supervisor, an Android runner, a
79/// forward, a boot row, and now a claim. Adding the claim cost a major
80/// version on its own — the one thing an exhaustive public enum charges
81/// for — so the charge is paid once here rather than again at the next
82/// kind of thing a holder can open.
83#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
84#[serde(tag = "kind", rename_all = "camelCase")]
85#[non_exhaustive]
86pub enum Resource {
87    /// An XCUITest runner session: the host-side `xcodebuild` process and
88    /// the port its HTTP face answers on.
89    #[serde(rename_all = "camelCase")]
90    Runner {
91        /// Port the runner's HTTP face answers on.
92        port: u16,
93        /// The host-side `xcodebuild` process.
94        proc: ProcIdentity,
95        /// The app the runner is bound to. `None` on a row written before
96        /// this field existed, and on a runner started without `--bundle`.
97        ///
98        /// It is here because this row is the only record of the runner:
99        /// the checkout used to hold a second one with the bundle in it,
100        /// under one key per platform, and two runners in one checkout
101        /// overwrote each other there.
102        #[serde(default, skip_serializing_if = "Option::is_none")]
103        bundle: Option<String>,
104        /// Where `xcodebuild`'s output is going. The supervisor tails it.
105        #[serde(default, skip_serializing_if = "Option::is_none")]
106        log: Option<String>,
107    },
108    /// A `simctl io … recordVideo` child writing to `path`.
109    #[serde(rename_all = "camelCase")]
110    Recording {
111        /// Where the video is being written.
112        path: String,
113        /// The `simctl io … recordVideo` child.
114        proc: ProcIdentity,
115    },
116    /// The supervisor sidecar watching an iOS runner.
117    ///
118    /// Ordered ahead of the runner in a cleanup plan, and that is not a
119    /// style choice: a live supervisor exists to bring a dead runner
120    /// back, so stopping the runner first accomplishes nothing except
121    /// giving the supervisor something to do.
122    #[serde(rename_all = "camelCase")]
123    Supervisor {
124        /// The sidecar process.
125        proc: ProcIdentity,
126    },
127    /// An Android instrumentation runner: the host-side process, the
128    /// forwarded port, and the device it is bound to.
129    #[serde(rename_all = "camelCase")]
130    AndroidRunner {
131        /// Forwarded port.
132        port: u16,
133        /// Device serial. Carried because every host-side call in the
134        /// teardown must name it — an unpinned one reaches whatever is
135        /// attached, which on a developer machine is often a phone.
136        serial: String,
137        /// Host-side process.
138        proc: ProcIdentity,
139        /// The app it was brought up for, so that a command finding it
140        /// gone can say how to bring it back. `None` on a row written
141        /// before this field existed.
142        #[serde(default, skip_serializing_if = "Option::is_none")]
143        bundle: Option<String>,
144    },
145    /// A local port forwarded to a port on a physical device.
146    ///
147    /// Closed *after* the runner it serves, which is the opposite of the
148    /// general reverse-of-opened rule: the runner's last few requests
149    /// still need the pipe, and pulling it first turns an orderly
150    /// teardown into a connection error.
151    #[serde(rename_all = "camelCase")]
152    PortForward {
153        /// Port on the host.
154        local_port: u16,
155        /// Port on the device.
156        device_port: u16,
157        /// The process holding the listener open. A forwarder lives
158        /// inside a process; when that process goes, so does it.
159        proc: ProcIdentity,
160    },
161    /// A port on the device routed back to a port on this machine, so
162    /// the app under test can reach a service running here.
163    ///
164    /// The mirror of [`Resource::PortForward`] in direction, and its
165    /// opposite in shape: a forward lives inside a process, this lives
166    /// in the adb server. `smix sim reverse` writes the row and exits,
167    /// and the route stays open — which is why there is no
168    /// [`ProcIdentity`] here to probe or signal. It is closed by naming
169    /// it, or when the device goes away.
170    ///
171    /// Closed *after* the runner it serves, for the same reason the
172    /// forward is: the app's last requests are still travelling
173    /// through it while the runner comes down.
174    #[serde(rename_all = "camelCase")]
175    ReversePort {
176        /// Port the app dials on the device. This identifies the route:
177        /// it is what `adb reverse --remove` takes, and a device may
178        /// have several open at once.
179        device_port: u16,
180        /// Port on this machine the route lands on.
181        host_port: u16,
182        /// Device serial. Carried for the same reason `AndroidRunner`
183        /// carries it: every host-side call in the teardown must name
184        /// the device, and an unpinned one reaches whatever is
185        /// attached — on a developer machine, often a phone.
186        serial: String,
187    },
188    /// The device is booted. `by_us` records whether this holder is the
189    /// one that booted it.
190    #[serde(rename_all = "camelCase")]
191    Booted {
192        /// True when this holder ran the boot. False when it found the
193        /// device already up.
194        by_us: bool,
195    },
196    /// This holder took responsibility for a device it did not boot.
197    ///
198    /// The ledger could already say "I booted it" and "I found it up".
199    /// Both are observations. The decision that sits between them had
200    /// nowhere to go: a machine's own dedicated emulator, running,
201    /// started by a hand that wrote no ledger is drivable by nobody,
202    /// because the only row that made a device drivable was the one that
203    /// also made it shut-downable — and nothing may claim to have booted
204    /// what it did not.
205    ///
206    /// So this row grants exactly one of the two. The device is this
207    /// holder's to drive; it is not its to switch off. [`may_shut_down`]
208    /// does not read it, which is the whole point of it being a separate
209    /// row rather than a cheaper `by_us: true`.
210    #[serde(rename_all = "camelCase")]
211    Claimed {
212        /// RFC3339. When the claim was made — later than the lease's own
213        /// `acquired_at` whenever a holder claims a device mid-session.
214        at: String,
215    },
216    /// Which AVD this emulator ledger is about, and where its console
217    /// is being written.
218    ///
219    /// An emulator's ledger is keyed by its serial, and the serial is a
220    /// port: whichever AVD boots next into that port answers to it. With
221    /// nothing but the serial, a ledger cannot tell "my device is gone"
222    /// from "my device is still here" once somebody else's has taken the
223    /// slot — which is the state a consumer's emulator and ours were in
224    /// on 2026-09-23. The AVD name is the device's identity; this row is
225    /// where the ledger keeps it.
226    ///
227    /// `console_log` is where the emulator's own stdout and stderr go when
228    /// smix started it. They used to go to `/dev/null`, so an emulator
229    /// that died left nothing behind — no crash report, an empty crash
230    /// database, and no way to say afterwards whose it was or why.
231    ///
232    /// Nothing to close: it names a device, it opens nothing.
233    #[serde(rename_all = "camelCase")]
234    Emulator {
235        /// The AVD name, as `adb emu avd name` reports it.
236        avd: String,
237        /// The file the emulator's console output was sent to, when smix
238        /// started it. `None` when smix found it already running.
239        #[serde(default, skip_serializing_if = "Option::is_none")]
240        console_log: Option<String>,
241    },
242}
243
244/// One ledger row: something this binary can name, or something it cannot.
245///
246/// The second case is not a defect to be tolerated, it is the normal
247/// state of a machine with two versions of smix on it. `Resource` is
248/// internally tagged and serde rejects a tag it has never heard of, so
249/// before this existed a newer smix's row stopped an older one dead —
250/// which is exactly what 7.0's claim row did to every 6.x on the same
251/// machine.
252///
253/// Nothing 7.0 could write would have helped: 6.x's parser had already
254/// shipped. The only place forward-compatibility can live is the
255/// reader, and the only time it can be added is before the writer needs
256/// it. That is what this is.
257///
258/// `Unnamed` keeps the row's whole object rather than just its tag,
259/// because a reader that remembers the name and forgets the contents
260/// has turned "I cannot read this" into "I destroyed this" the next
261/// time it writes the file back.
262#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
263#[serde(untagged)]
264pub enum Row {
265    /// A row this binary understands.
266    Known(Resource),
267    /// A row written by a smix that knows a kind this one does not.
268    Unnamed(serde_json::Value),
269}
270
271impl From<Resource> for Row {
272    fn from(r: Resource) -> Self {
273        Row::Known(r)
274    }
275}
276
277impl Row {
278    /// The resource, when this binary can name it.
279    #[must_use]
280    pub fn known(&self) -> Option<&Resource> {
281        match self {
282            Row::Known(r) => Some(r),
283            Row::Unnamed(_) => None,
284        }
285    }
286
287    /// The row's `kind` when this binary cannot name it.
288    #[must_use]
289    pub fn unnamed_kind(&self) -> Option<&str> {
290        match self {
291            Row::Known(_) => None,
292            Row::Unnamed(v) => Some(
293                v.get("kind")
294                    .and_then(serde_json::Value::as_str)
295                    .unwrap_or(""),
296            ),
297        }
298    }
299}
300
301/// One device's ledger: a holder, and what it opened.
302#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
303#[serde(rename_all = "camelCase")]
304pub struct Lease {
305    /// UDID (iOS) or serial (Android).
306    pub device_id: String,
307    /// The process holding the lease, pinned well enough to recognise.
308    pub holder: ProcIdentity,
309    /// RFC3339. When the lease was taken.
310    pub acquired_at: String,
311    /// RFC3339. Last heartbeat.
312    pub heartbeat_at: String,
313    /// What the holder opened on the device, in the order it opened them.
314    pub resources: Vec<Row>,
315}
316
317impl Lease {
318    /// The rows this binary can name.
319    ///
320    /// Spelled out at every call site on purpose: a caller that means
321    /// "all of them" and a caller that means "the ones I understand"
322    /// were the same expression before, and that is how a teardown came
323    /// to look complete while skipping what it could not read.
324    pub fn known_resources(&self) -> impl Iterator<Item = &Resource> {
325        self.resources.iter().filter_map(Row::known)
326    }
327}
328
329/// What a probe found at the holder's pid.
330///
331/// Two booleans rather than one `alive`, because the third case is real
332/// and dangerous: the pid exists but belongs to something else now. A
333/// single flag would collapse "holder is running" and "holder is gone,
334/// its pid was reused" into the same answer, and the correct response to
335/// them differs — the first means back off, the second means clean up
336/// while never signalling that pid.
337#[derive(Debug, Clone, Copy, PartialEq, Eq)]
338pub struct HolderProbe {
339    /// A process exists at the holder's pid.
340    pub pid_exists: bool,
341    /// Its start time matches the one recorded in the ledger.
342    pub identity_matches: bool,
343}
344
345/// A ledger found on disk, together with what its holder's pid looks like
346/// right now.
347///
348/// The two travel as one because a lease without a probe is not a state
349/// the caller may be in: it would leave `assess` to decide what an
350/// unprobed holder means, and the only answers available there are a
351/// guess.
352#[derive(Debug, Clone)]
353pub struct Held {
354    /// The ledger.
355    pub lease: Lease,
356    /// What the caller found at the holder's pid.
357    pub holder: HolderProbe,
358    /// Whether any process the ledger records is still running.
359    ///
360    /// The holder is usually a short-lived command: `smix runner up`
361    /// spawns an `xcodebuild` in its own process group and exits, so the
362    /// holder is gone within seconds while the runner it started keeps
363    /// the device occupied for hours. Judging occupancy by the holder
364    /// alone would let the next command treat that live runner as an
365    /// orphan and tear it down — the mechanism meant to protect sessions
366    /// killing the healthiest one on the machine.
367    pub any_resource_alive: bool,
368}
369
370/// Whether a ledger still describes anything, and the sentence for it.
371#[derive(Debug, Clone, PartialEq, Eq)]
372pub enum PruneVerdict {
373    /// Keep it, for the stated reason.
374    Keep(&'static str),
375    /// Nothing here describes the machine any more.
376    Remove,
377}
378
379/// Does this ledger still describe something?
380///
381/// Pure, and fed `device_is_on` rather than asking, for the reason
382/// `is_running` is pure: judging and doing I/O in the same breath makes a
383/// rule testable only against whatever this machine happens to be doing.
384///
385/// `device_is_on` is `None` when the machine cannot tell — an Android
386/// serial and a physical iPhone are not in `simctl`'s list at all.
387/// Not-listed must never collapse into off: that would delete the record
388/// of a device whose state nobody here can see.
389///
390/// The boot row is the reason this exists. `any_resource_alive` reads
391/// `Booted` as false by construction, which is correct for what that
392/// field means — a boot is not a process and cannot be probed — and
393/// wrong as the last word on whether a ledger is empty. A device that is
394/// on, with a row saying smix turned it on, is a ledger holding the only
395/// answer to a question `lease owner` is asked and `pick-dev-sim` acts
396/// on.
397pub fn prune_verdict(held: &Held, device_is_on: Option<bool>) -> PruneVerdict {
398    if held.holder.pid_exists && held.holder.identity_matches {
399        return PruneVerdict::Keep("held by a live holder");
400    }
401    if held.any_resource_alive {
402        return PruneVerdict::Keep("holder gone but something it started is still running");
403    }
404    let booted_by_us = held
405        .lease
406        .known_resources()
407        .any(|r| matches!(r, Resource::Booted { by_us: true }));
408    if booted_by_us {
409        return match device_is_on {
410            Some(true) => PruneVerdict::Keep(
411                "still switched on and this ledger is the only record of who turned it on",
412            ),
413            None => PruneVerdict::Keep(
414                "says smix booted it and this machine cannot tell whether it is still on",
415            ),
416            Some(false) => PruneVerdict::Remove,
417        };
418    }
419    // A claim is kept on exactly the same terms as a boot row, and for
420    // the same reason: while the device is on, this ledger is the only
421    // record that anybody answered for it. The terms matter more here
422    // than for a boot, because a claim that outlived its device would be
423    // an escape hatch nobody checks the far side of — the device going
424    // off is what ends it, with `lease release` for ending it sooner.
425    let claimed = held
426        .lease
427        .known_resources()
428        .any(|r| matches!(r, Resource::Claimed { .. }));
429    if claimed {
430        return match device_is_on {
431            Some(true) => PruneVerdict::Keep(
432                "still switched on and this ledger is the only record of who answered for it",
433            ),
434            None => {
435                PruneVerdict::Keep("claimed, and this machine cannot tell whether it is still on")
436            }
437            Some(false) => PruneVerdict::Remove,
438        };
439    }
440    PruneVerdict::Remove
441}
442
443/// What the world looks like. Gathered by the caller; never read from the
444/// world in here.
445#[derive(Debug, Clone)]
446pub struct Facts {
447    /// The ledger on disk with its holder probed, if any.
448    pub existing: Option<Held>,
449    /// Now, RFC3339.
450    pub now: String,
451    /// This process's pid — a holder re-entering its own lease is not
452    /// contention.
453    pub self_pid: u32,
454}
455
456/// A close this process owes the device, on behalf of a holder that died.
457///
458/// Ordered by [`plan_cleanup`], carrying the pid *and* the command line
459/// that pid must still be running for the signal to be sent.
460#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
461#[serde(tag = "action", rename_all = "camelCase")]
462pub enum CleanupAction {
463    /// A ledger row this binary has no name for.
464    ///
465    /// It carries no action because there is none to take: closing
466    /// something requires knowing what it is. It is in the plan so that
467    /// a teardown cannot report itself complete while a row it could
468    /// not read goes unmentioned — a plan that silently drops what it
469    /// did not understand reads exactly like a plan that had nothing
470    /// left to do.
471    #[serde(rename_all = "camelCase")]
472    CannotClose {
473        /// The `kind` the row gave, verbatim.
474        kind: String,
475    },
476    /// SIGINT the `simctl` child and wait, so the mp4 keeps its trailer.
477    #[serde(rename_all = "camelCase")]
478    StopRecording {
479        /// Where the video was being written.
480        path: String,
481        /// Must be re-verified at the pid before any signal is sent.
482        proc: ProcIdentity,
483    },
484    /// SIGINT-first teardown of the runner, so testmanagerd ends the
485    /// XCUITest session rather than the process dying by SIGABRT.
486    #[serde(rename_all = "camelCase")]
487    StopRunner {
488        /// Runner HTTP port.
489        port: u16,
490        /// Must be re-verified at the pid before any signal is sent.
491        proc: ProcIdentity,
492    },
493    /// Stop the supervisor sidecar. Emitted before the runner it watches.
494    #[serde(rename_all = "camelCase")]
495    StopSupervisor {
496        /// Must be re-verified at the pid before any signal is sent.
497        proc: ProcIdentity,
498    },
499    /// Stop an Android instrumentation runner.
500    #[serde(rename_all = "camelCase")]
501    StopAndroidRunner {
502        /// Forwarded port.
503        port: u16,
504        /// Device serial — every host-side call in the teardown names it.
505        serial: String,
506        /// Must be re-verified at the pid before any signal is sent.
507        proc: ProcIdentity,
508    },
509    /// Stop a port forwarder. Emitted after the runner it serves.
510    #[serde(rename_all = "camelCase")]
511    StopPortForward {
512        /// Port on the host, for the report.
513        local_port: u16,
514        /// Must be re-verified at the pid before any signal is sent.
515        proc: ProcIdentity,
516    },
517    /// `adb reverse --remove` the route the device was dialling.
518    /// Emitted after the runner, like the forward next door.
519    #[serde(rename_all = "camelCase")]
520    RemoveReversePort {
521        /// Device serial — every host-side call in the teardown names it.
522        serial: String,
523        /// The port on the device, which is what identifies the route.
524        device_port: u16,
525    },
526    /// `simctl shutdown` — only ever emitted for a device this holder
527    /// booted.
528    #[serde(rename_all = "camelCase")]
529    ShutdownSim {
530        /// Device to shut down.
531        udid: String,
532    },
533}
534
535/// Why a lease could not be taken, said with the facts the holder needs.
536#[derive(Debug, Clone, PartialEq, Eq)]
537pub struct Contention {
538    /// The process that took the lease.
539    pub holder: ProcIdentity,
540    /// When it took the lease (RFC3339).
541    pub acquired_at: String,
542    /// Whether that process is still running. False means the holder
543    /// command finished but what it started is still on the device —
544    /// the ordinary state after `smix runner up` returns.
545    pub holder_alive: bool,
546}
547
548/// The verdict.
549#[derive(Debug, Clone, PartialEq, Eq)]
550pub enum Admission {
551    /// The holder is gone and everything it left running is a service —
552    /// a runner, its forwarder, its supervisor. The caller takes over
553    /// the lease as-is: resources kept, holder replaced. Tearing this
554    /// down would destroy the thing the caller came to use.
555    Adoptable,
556    /// Nothing holds this device, or this process already does.
557    Granted,
558    /// Someone else holds it and is alive. Ambiguity is an error, not a
559    /// choice: the caller is told who, not made to wait.
560    Denied(Contention),
561    /// The holder is gone. The lease can be taken *after* these closes
562    /// are performed — never before, or the next holder inherits an
563    /// orphaned recording and a runner still occupying the device's
564    /// automation slot.
565    Reclaimable {
566        /// Closes owed, in the order they must happen.
567        cleanup: Vec<CleanupAction>,
568        /// Why the holder was judged gone — carried so the report can
569        /// say it rather than assert a bare "stale".
570        reason: StaleReason,
571    },
572}
573
574/// Why a holder was judged gone.
575#[derive(Debug, Clone, Copy, PartialEq, Eq)]
576pub enum StaleReason {
577    /// No process at the recorded pid.
578    HolderExited,
579    /// A process exists at the pid, but it is not the holder — the number
580    /// was recycled. Nothing may be signalled at that pid.
581    PidRecycled,
582    /// The process is there and is the holder, but it stopped beating.
583    ///
584    /// No longer produced. `assess` returned this until 2026-08-11,
585    /// when the ledgers moved from each checkout to the machine and
586    /// every tree could act on it. The heartbeat is written when the
587    /// ledger is touched, so a holder that takes a device and then
588    /// serves for hours is silent by design — `smix-mcp` had held a
589    /// simulator for two days with an eighty-three-minute-old heartbeat
590    /// while serving — and treating that silence as wedged would have
591    /// any `lease reconcile` tear down a live session. Kept as a name so
592    /// a ledger or a caller written against it still resolves.
593    HeartbeatExpired,
594}
595
596/// Something that can perform the closes a plan names.
597///
598/// The plan says *what* is owed; performing it needs knowledge this crate
599/// does not have and should not acquire — how an XCUITest session ends
600/// without a crash dialog, what a `simctl` recording needs in order to
601/// keep its trailer. Callers that hold that knowledge implement this;
602/// callers that only need to gate access take one as an argument.
603///
604/// The indirection buys one concrete thing beyond tidiness: admission can
605/// be tested against a recording double, so "did it clean up before
606/// handing the device over" is a question answerable without a device.
607pub trait CleanupExecutor {
608    /// Perform the closes, in the order given, and report each.
609    fn execute(&self, actions: &[CleanupAction]) -> Vec<CleanupReport>;
610}
611
612/// What became of one owed close, as the gate needs to hear it.
613#[derive(Debug, Clone, PartialEq, Eq)]
614pub struct CleanupReport {
615    /// One line, for the person reading.
616    pub line: String,
617    /// Did this leave the device in a state the next holder can trust?
618    pub clean: bool,
619}
620
621/// Judge the facts.
622pub fn assess(facts: &Facts) -> Admission {
623    let Some(held) = &facts.existing else {
624        return Admission::Granted;
625    };
626    let lease = &held.lease;
627
628    // Re-entering our own lease is not contention. Without this, a
629    // holder's second command against its own device would report itself
630    // as the obstacle.
631    if lease.holder.pid == facts.self_pid {
632        return Admission::Granted;
633    }
634
635    let reclaim = |reason| Admission::Reclaimable {
636        cleanup: plan_cleanup(lease),
637        reason,
638    };
639
640    let deny = |holder_alive| {
641        Admission::Denied(Contention {
642            holder: lease.holder.clone(),
643            acquired_at: lease.acquired_at.clone(),
644            holder_alive,
645        })
646    };
647
648    let holder_gone = !held.holder.pid_exists || !held.holder.identity_matches;
649    if holder_gone {
650        // What it started may well outlive it — and what outlives it is
651        // usually the point. `smix runner up` exits by design; the
652        // runner it leaves behind is a service the next command drives
653        // *through*, not a squatter it must wait out. So a dead holder
654        // whose surviving resources are all services hands the lease to
655        // whoever asks next, resources intact. This used to deny, which
656        // barred the quickstart's own `runner up` → `run` pairing on
657        // every device — found the first time a full flow ran against a
658        // physical phone.
659        //
660        // A live recording is different: it is an exclusive activity,
661        // not a service, and adopting past it would let a second
662        // session run over whatever the first was capturing.
663        if held.any_resource_alive {
664            // A row nobody can read is not a service: "service" is a
665            // claim about what the thing is for, and this one has not
666            // said. Adopting past it would hand the device to a second
667            // session over the top of whatever the first opened.
668            if lease
669                .resources
670                .iter()
671                .all(|row| row.known().is_some_and(is_service))
672            {
673                return Admission::Adoptable;
674            }
675            return deny(false);
676        }
677        // A ledger holding nothing but a boot is not an abandoned
678        // session — it is a device somebody turned on and has not
679        // finished with. `smix sim boot` exits the moment the device is
680        // up, so treating its ledger as abandoned would have the very
681        // next command shut the device down again, which is what the
682        // person just asked for the opposite of. The boot row exists to
683        // record who may shut it down later, not to claim the device.
684        // Same asymmetry the other way up: an unreadable row counts as
685        // something that could still be running, so it withholds the
686        // cheap "this device is free" and sends the question down the
687        // reclaim path where a person can see it.
688        if !lease
689            .resources
690            .iter()
691            .any(|row| row.known().is_none_or(is_process_backed))
692        {
693            return Admission::Granted;
694        }
695        return reclaim(if held.holder.pid_exists {
696            // A process is there, but it is not the holder — the number
697            // was recycled. Nothing may be signalled at that pid.
698            StaleReason::PidRecycled
699        } else {
700            StaleReason::HolderExited
701        });
702    }
703
704    // The holder itself is alive.
705    //
706    // A stopped heartbeat used to make it reclaimable, on the reading
707    // that a live holder which went quiet is wedged rather than
708    // working. Nothing here can tell those apart, and the heartbeat is
709    // written when the ledger is touched — so a holder that takes a
710    // device and then serves for hours is silent by design. `smix-mcp`
711    // is exactly that shape: one had held a simulator since 9 August
712    // with a heartbeat eighty-three minutes old, and it was serving.
713    //
714    // While each tree kept its own ledgers, only that tree could act on
715    // the mistake. They are the machine's now, so any `lease reconcile`
716    // from any checkout would settle it. Refusing costs a wait;
717    // reclaiming costs somebody their session — and the way out of a
718    // genuinely wedged holder is to end the process, which a person can
719    // establish and this cannot.
720    if heartbeat_expired(&lease.heartbeat_at, &facts.now) {
721        return deny(true);
722    }
723
724    deny(true)
725}
726
727/// Is this workspace entitled to shut this device down?
728///
729/// Being in the registry means "smix knows how to address it", not "smix
730/// may turn it off". A teardown that shut down every registered device
731/// took away sessions nobody here started — someone running a dev server
732/// against a registered simulator lost it to a sweep of somebody else's
733/// work. The boot row is the record of entitlement, and `None` (no ledger
734/// at all) means no.
735/// The `kind` of every row this binary could not name, in ledger order.
736///
737/// A refusal that cannot say WHAT it failed to read is a refusal nobody
738/// can act on, so this is what the messages quote.
739#[must_use]
740pub fn unnamed_kinds(lease: &Lease) -> Vec<String> {
741    lease
742        .resources
743        .iter()
744        .filter_map(|r| r.unnamed_kind().map(str::to_string))
745        .collect()
746}
747
748#[must_use]
749pub fn may_shut_down(lease: Option<&Lease>) -> bool {
750    lease.is_some_and(|l| {
751        // Entitlement is necessary and no longer sufficient. A row this
752        // binary cannot read is something open on the device that
753        // nothing here can close, and switching the device off would
754        // strand it — so having booted it does not settle the question
755        // on its own.
756        unnamed_kinds(l).is_empty()
757            && l.known_resources()
758                .any(|r| matches!(r, Resource::Booted { by_us: true }))
759    })
760}
761
762/// Is this resource a service — a thing that exists to be used by the
763/// next command, rather than an activity that excludes it?
764///
765/// The runner and its plumbing are services: a client driving through
766/// them is their purpose. A recording is an activity: two sessions
767/// writing over one capture is a collision, not a hand-off. `Booted` is
768/// neither a process nor an activity and never blocks adoption.
769///
770/// Exhaustive on purpose. This was a `matches!` with a default of "not a
771/// service", and the `Emulator` row, added later, fell to it without
772/// a word: every emulator smix booted then refused the `runner up` → `run`
773/// pairing on it. A new kind of row has to be classified here to compile.
774pub fn is_service(r: &Resource) -> bool {
775    match r {
776        Resource::Runner { .. }
777        | Resource::AndroidRunner { .. }
778        | Resource::PortForward { .. }
779        | Resource::Supervisor { .. }
780        | Resource::Booted { .. }
781        | Resource::Claimed { .. }
782        | Resource::ReversePort { .. }
783        // Names which AVD this is and where its console went. Like
784        // `Booted`, a fact about the device, not something a second
785        // session could collide with.
786        | Resource::Emulator { .. } => true,
787        Resource::Recording { .. } => false,
788    }
789}
790
791/// Does this resource stand for a process that can die?
792///
793/// `Booted` does not: it is a device state, and nothing about it can be
794/// probed for liveness. That difference decides whether a ledger without
795/// a live holder is an abandoned session or merely a device left on.
796pub fn is_process_backed(r: &Resource) -> bool {
797    // Exhaustive for the same reason as `is_service`.
798    match r {
799        Resource::Runner { .. }
800        | Resource::Recording { .. }
801        | Resource::Supervisor { .. }
802        | Resource::AndroidRunner { .. }
803        | Resource::PortForward { .. } => true,
804        Resource::ReversePort { .. }
805        | Resource::Booted { .. }
806        | Resource::Claimed { .. }
807        | Resource::Emulator { .. } => false,
808    }
809}
810
811/// Has the holder stopped beating for longer than [`STALE_AFTER_SECS`]?
812///
813/// An unparseable timestamp answers `false` — refuse to preempt rather
814/// than preempt on a reading we could not take. This branch is only ever
815/// reached with the holder's process alive and matching, so `false` keeps
816/// a running session running and reports a named holder the operator can
817/// act on; `true` would tear down a live session on the strength of a
818/// corrupt string. Not a fallback for a missing value — a decision about
819/// which way to be wrong.
820fn heartbeat_expired(heartbeat_at: &str, now: &str) -> bool {
821    let parse = |s: &str| chrono::DateTime::parse_from_rfc3339(s).ok();
822    match (parse(heartbeat_at), parse(now)) {
823        (Some(hb), Some(n)) => (n - hb).num_seconds() > STALE_AFTER_SECS,
824        _ => false,
825    }
826}
827
828/// The closes a dead holder's lease owes, in the order they must happen.
829///
830/// Reverse of the order they were opened: the recording is stopped before
831/// the runner that was driving what it recorded, and the device is shut
832/// down last, after nothing is left talking to it.
833pub fn plan_cleanup(lease: &Lease) -> Vec<CleanupAction> {
834    // Reverse-of-opened, with one exception that is not a preference.
835    //
836    // A supervisor's whole job is to bring a dead runner back. Stop the
837    // runner while its supervisor is alive and the teardown undoes
838    // itself — so the supervisor goes first regardless of when it was
839    // recorded. `runner::down` already cascades in this order; putting
840    // it in the plan means a reconcile running hours later, from a
841    // different process, does not have to rediscover it.
842    let mut plan: Vec<CleanupAction> = lease
843        .known_resources()
844        .filter_map(|r| match r {
845            Resource::Supervisor { proc } => {
846                Some(CleanupAction::StopSupervisor { proc: proc.clone() })
847            }
848            _ => None,
849        })
850        .collect();
851    plan.extend(plan_rest(lease));
852    // Forwarders last, for the mirror-image of the supervisor reason:
853    // the runner's closing requests still travel through the pipe, and
854    // pulling it early turns a clean teardown into a connection error
855    // that reads like the runner misbehaved.
856    plan.extend(lease.known_resources().filter_map(|r| match r {
857        Resource::PortForward {
858            local_port, proc, ..
859        } => Some(CleanupAction::StopPortForward {
860            local_port: *local_port,
861            proc: proc.clone(),
862        }),
863        // Same position, same reason, opposite direction: the app's
864        // last requests are still travelling this way out.
865        Resource::ReversePort {
866            device_port,
867            serial,
868            ..
869        } => Some(CleanupAction::RemoveReversePort {
870            serial: serial.clone(),
871            device_port: *device_port,
872        }),
873        _ => None,
874    }));
875    plan
876}
877
878/// Everything except supervisors, reverse-of-opened.
879fn plan_rest(lease: &Lease) -> Vec<CleanupAction> {
880    lease
881        .resources
882        .iter()
883        .rev()
884        .filter_map(|row| {
885            // In the plan, in position, carrying no action — because
886            // there is none. A teardown that quietly omitted the row it
887            // could not read would report itself complete, which is the
888            // one thing it must not be able to do here.
889            let r = match row {
890                Row::Unnamed(_) => {
891                    return Some(CleanupAction::CannotClose {
892                        kind: row.unnamed_kind().unwrap_or_default().to_string(),
893                    });
894                }
895                Row::Known(r) => r,
896            };
897            match r {
898                // Handled ahead of everything else by `plan_cleanup`.
899                Resource::Supervisor { .. } => None,
900                // Handled after everything else by `plan_cleanup`.
901                Resource::PortForward { .. } | Resource::ReversePort { .. } => None,
902                Resource::Recording { path, proc } => Some(CleanupAction::StopRecording {
903                    path: path.clone(),
904                    proc: proc.clone(),
905                }),
906                Resource::Runner { port, proc, .. } => Some(CleanupAction::StopRunner {
907                    port: *port,
908                    proc: proc.clone(),
909                }),
910                Resource::AndroidRunner {
911                    port, serial, proc, ..
912                } => Some(CleanupAction::StopAndroidRunner {
913                    port: *port,
914                    serial: serial.clone(),
915                    proc: proc.clone(),
916                }),
917                // Not ours to shut down. Finding the device already up and
918                // then turning it off would take away someone else's session
919                // as the price of cleaning up our own.
920                Resource::Booted { by_us: false } => None,
921                // A claim is the statement that this holder did NOT boot it.
922                // Closing it by switching the device off would be the one
923                // thing the claim promised not to do.
924                Resource::Claimed { .. } => None,
925                // Names the device; nothing was opened, so nothing closes.
926                Resource::Emulator { .. } => None,
927                Resource::Booted { by_us: true } => Some(CleanupAction::ShutdownSim {
928                    udid: lease.device_id.clone(),
929                }),
930            }
931        })
932        .collect()
933}
934
935#[cfg(test)]
936mod tests {
937    use super::*;
938
939    fn holder() -> ProcIdentity {
940        ProcIdentity {
941            pid: 4242,
942            started_at: "Thu Aug  6 10:00:00 2026".into(),
943            cmd: "smix run examples/hello.yaml".into(),
944        }
945    }
946
947    // A ledger row this binary has no name for.
948    //
949    // 7.0 taught 6.x machines what this costs: `Resource` is internally
950    // tagged, serde rejects a tag it does not know, and a 6.x smix
951    // meeting a claimed device stopped dead. Nothing 7.0 wrote could
952    // have prevented that — 6.x's parser had already shipped. What can
953    // be prevented is the next one, and only by the reader, and only if
954    // the reader is ready before the writer needs it.
955    const FUTURE_ROW: &str = r#"{"kind":"somethingFromTheFuture","port":9,"note":"x"}"#;
956
957    fn ledger_json(rows: &str) -> String {
958        format!(
959            r#"{{"deviceId":"D1","holder":{{"pid":4242,"startedAt":"Thu Aug  6 10:00:00 2026",
960               "cmd":"smix run examples/hello.yaml"}},"acquiredAt":"2026-08-25T00:00:00Z",
961               "heartbeatAt":"2026-08-25T00:00:00Z","resources":[{rows}]}}"#
962        )
963    }
964
965    #[test]
966    fn a_row_this_binary_cannot_name_still_parses() {
967        let json = ledger_json(&format!(r#"{{"kind":"booted","byUs":true}},{FUTURE_ROW}"#));
968        let lease: Lease = serde_json::from_str(&json)
969            .expect("an unknown row must be readable — refusing to parse is the 6.x failure");
970        assert_eq!(lease.resources.len(), 2);
971    }
972
973    #[test]
974    fn a_row_this_binary_cannot_name_survives_a_rewrite() {
975        let json = ledger_json(&format!(r#"{{"kind":"booted","byUs":true}},{FUTURE_ROW}"#));
976        let lease: Lease = serde_json::from_str(&json).unwrap();
977        let back = serde_json::to_string(&lease).unwrap();
978        let reread: serde_json::Value = serde_json::from_str(&back).unwrap();
979        let row = &reread["resources"][1];
980        // Every field, not just the tag: a reader that keeps the name
981        // and drops the contents has turned "I cannot read this" into
982        // "I destroyed this".
983        assert_eq!(row["kind"], "somethingFromTheFuture", "row: {row}");
984        assert_eq!(row["port"], 9, "row: {row}");
985        assert_eq!(row["note"], "x", "row: {row}");
986    }
987
988    #[test]
989    fn a_row_this_binary_cannot_name_withholds_shutdown() {
990        let json = ledger_json(&format!(r#"{{"kind":"booted","byUs":true}},{FUTURE_ROW}"#));
991        let lease: Lease = serde_json::from_str(&json).unwrap();
992        assert!(
993            !may_shut_down(Some(&lease)),
994            "we booted it, so the entitlement is there — but something is open on \
995             this device that nothing here can close, and switching it off would \
996             strand whatever that is"
997        );
998        assert!(
999            unnamed_kinds(&lease).contains(&"somethingFromTheFuture".to_string()),
1000            "a refusal that cannot say WHAT it could not name is a refusal nobody \
1001             can act on"
1002        );
1003    }
1004
1005    #[test]
1006    fn a_row_this_binary_cannot_name_appears_in_the_cleanup_plan() {
1007        let json = ledger_json(&format!(r#"{{"kind":"booted","byUs":true}},{FUTURE_ROW}"#));
1008        let lease: Lease = serde_json::from_str(&json).unwrap();
1009        assert!(
1010            plan_cleanup(&lease).iter().any(|a| matches!(
1011                a,
1012                CleanupAction::CannotClose { kind } if kind == "somethingFromTheFuture"
1013            )),
1014            "a plan that silently omits the row it could not read reads exactly \
1015             like a complete teardown"
1016        );
1017    }
1018
1019    fn lease_with(resources: Vec<Resource>) -> Lease {
1020        Lease {
1021            device_id: "UDID-1".into(),
1022            holder: holder(),
1023            acquired_at: "2026-08-06T10:00:00Z".into(),
1024            heartbeat_at: "2026-08-06T10:00:00Z".into(),
1025            resources: resources.into_iter().map(Row::Known).collect(),
1026        }
1027    }
1028
1029    fn runner_proc() -> ProcIdentity {
1030        ProcIdentity {
1031            pid: 5150,
1032            started_at: "Thu Aug  6 10:00:05 2026".into(),
1033            cmd: "xcodebuild test -project SmixRunner".into(),
1034        }
1035    }
1036
1037    fn recording_proc() -> ProcIdentity {
1038        ProcIdentity {
1039            pid: 5151,
1040            started_at: "Thu Aug  6 10:00:09 2026".into(),
1041            cmd: "xcrun simctl io UDID-1 recordVideo".into(),
1042        }
1043    }
1044
1045    fn runner() -> Resource {
1046        Resource::Runner {
1047            port: 22087,
1048            bundle: None,
1049            log: None,
1050            proc: runner_proc(),
1051        }
1052    }
1053
1054    fn recording() -> Resource {
1055        Resource::Recording {
1056            path: ".smix/trace/run.mov".into(),
1057            proc: recording_proc(),
1058        }
1059    }
1060
1061    fn reverse(device_port: u16, host_port: u16) -> Resource {
1062        Resource::ReversePort {
1063            device_port,
1064            host_port,
1065            serial: "emulator-5554".into(),
1066        }
1067    }
1068
1069    /// A route the device dials is there for whoever drives next.
1070    ///
1071    /// `smix sim reverse` exits the moment adb has the row, so its
1072    /// holder is dead seconds later. If this were not a service, the
1073    /// most ordinary order there is — open the route, bring the runner
1074    /// up, run a flow — would be denied at the third step by the first.
1075    #[test]
1076    fn a_reverse_route_is_a_service_and_not_a_process() {
1077        assert!(is_service(&reverse(8080, 8080)));
1078        assert!(
1079            !is_process_backed(&reverse(8080, 8080)),
1080            "it lives in the adb server; there is no pid here to probe or signal"
1081        );
1082    }
1083
1084    #[test]
1085    fn a_dead_holder_leaves_a_reverse_route_to_be_adopted() {
1086        let lease = lease_with(vec![
1087            reverse(8080, 8080),
1088            Resource::AndroidRunner {
1089                port: 22087,
1090                serial: "emulator-5554".into(),
1091                proc: runner_proc(),
1092                bundle: None,
1093            },
1094        ]);
1095        assert_eq!(
1096            assess(&facts_with_resources(lease, false, false, FRESH, true)),
1097            Admission::Adoptable
1098        );
1099    }
1100
1101    /// The ledger `smix sim boot <avd>` then `smix runner up` leaves: the
1102    /// boot row, the emulator's identity row (C4), and the live runner.
1103    /// `sim boot` exits by design, so its holder is dead — and the next
1104    /// command must drive through the runner, not be refused.
1105    ///
1106    /// It was refused: `is_service` was a non-exhaustive `matches!`, the
1107    /// `Emulator` row, added later, fell to its default, and a
1108    /// not-service row with a live neighbour reads as an abandoned
1109    /// activity. The refusal then said "a recording it started is still
1110    /// running" — about a device on which nothing was recording.
1111    #[test]
1112    fn a_boot_then_a_runner_is_adopted_with_the_emulator_row_in_it() {
1113        let lease = lease_with(vec![
1114            Resource::Booted { by_us: true },
1115            Resource::Emulator {
1116                avd: "sim-smix-android-01".into(),
1117                console_log: Some("/tmp/console.log".into()),
1118            },
1119            Resource::AndroidRunner {
1120                port: 22087,
1121                serial: "emulator-5554".into(),
1122                proc: runner_proc(),
1123                bundle: None,
1124            },
1125        ]);
1126        assert_eq!(
1127            assess(&facts_with_resources(lease, false, false, FRESH, true)),
1128            Admission::Adoptable
1129        );
1130    }
1131
1132    /// With nothing running, the next command takes the lease and the
1133    /// row stays — the route is still open on the device, and a ledger
1134    /// that forgot it would leave nothing able to close it.
1135    #[test]
1136    fn a_reverse_route_alone_does_not_make_a_ledger_abandoned() {
1137        let lease = lease_with(vec![reverse(8080, 3000)]);
1138        assert_eq!(
1139            assess(&facts(lease, false, false, FRESH)),
1140            Admission::Granted
1141        );
1142    }
1143
1144    /// Facts for a probed holder. `now` sits inside the heartbeat window
1145    /// unless a test is about staleness.
1146    fn facts(lease: Lease, pid_exists: bool, identity_matches: bool, now: &str) -> Facts {
1147        facts_with_resources(lease, pid_exists, identity_matches, now, false)
1148    }
1149
1150    fn facts_with_resources(
1151        lease: Lease,
1152        pid_exists: bool,
1153        identity_matches: bool,
1154        now: &str,
1155        any_resource_alive: bool,
1156    ) -> Facts {
1157        Facts {
1158            existing: Some(Held {
1159                lease,
1160                holder: HolderProbe {
1161                    pid_exists,
1162                    identity_matches,
1163                },
1164                any_resource_alive,
1165            }),
1166            now: now.into(),
1167            self_pid: 9000,
1168        }
1169    }
1170
1171    const FRESH: &str = "2026-08-06T10:00:30Z";
1172
1173    #[test]
1174    fn no_lease_is_granted() {
1175        let f = Facts {
1176            existing: None,
1177            now: FRESH.into(),
1178            self_pid: 9000,
1179        };
1180        assert_eq!(assess(&f), Admission::Granted);
1181    }
1182
1183    #[test]
1184    fn own_lease_is_granted() {
1185        let mut lease = lease_with(vec![runner()]);
1186        lease.holder.pid = 9000;
1187        assert_eq!(assess(&facts(lease, true, true, FRESH)), Admission::Granted);
1188    }
1189
1190    #[test]
1191    fn live_holder_denies_with_who_not_just_busy() {
1192        match assess(&facts(lease_with(vec![runner()]), true, true, FRESH)) {
1193            Admission::Denied(c) => {
1194                assert_eq!(c.holder.pid, 4242);
1195                assert_eq!(c.holder.cmd, "smix run examples/hello.yaml");
1196                assert_eq!(c.acquired_at, "2026-08-06T10:00:00Z");
1197            }
1198            other => panic!("expected Denied, got {other:?}"),
1199        }
1200    }
1201
1202    #[test]
1203    fn dead_holder_is_reclaimable_with_cleanup() {
1204        let lease = lease_with(vec![
1205            Resource::Booted { by_us: true },
1206            runner(),
1207            recording(),
1208        ]);
1209        match assess(&facts(lease, false, false, FRESH)) {
1210            Admission::Reclaimable { cleanup, reason } => {
1211                assert_eq!(reason, StaleReason::HolderExited);
1212                assert_eq!(cleanup.len(), 3);
1213            }
1214            other => panic!("expected Reclaimable, got {other:?}"),
1215        }
1216    }
1217
1218    #[test]
1219    fn recycled_pid_is_stale_and_says_so() {
1220        match assess(&facts(lease_with(vec![runner()]), true, false, FRESH)) {
1221            Admission::Reclaimable { reason, .. } => assert_eq!(reason, StaleReason::PidRecycled),
1222            other => panic!("expected Reclaimable, got {other:?}"),
1223        }
1224    }
1225
1226    #[test]
1227    fn live_holder_past_heartbeat_window_still_denies() {
1228        // 91 s after the recorded heartbeat — past the window, and the
1229        // holder is still there.
1230        //
1231        // This asserted `Reclaimable` until 2026-08-11. The heartbeat is
1232        // written when the ledger is touched, so a holder that takes a
1233        // device and then serves is silent by design, and nothing here
1234        // can separate silent-because-serving from wedged. Denying costs
1235        // a wait; reclaiming costs somebody their session.
1236        let f = facts(
1237            lease_with(vec![runner()]),
1238            true,
1239            true,
1240            "2026-08-06T10:01:31Z",
1241        );
1242        match assess(&f) {
1243            Admission::Denied(c) => assert!(c.holder_alive),
1244            other => panic!("expected Denied, got {other:?}"),
1245        }
1246    }
1247
1248    #[test]
1249    fn live_holder_within_heartbeat_window_still_denies() {
1250        let f = facts(
1251            lease_with(vec![runner()]),
1252            true,
1253            true,
1254            "2026-08-06T10:01:29Z",
1255        );
1256        assert!(matches!(assess(&f), Admission::Denied(_)));
1257    }
1258
1259    #[test]
1260    fn unreadable_timestamp_refuses_to_preempt_a_live_holder() {
1261        let mut lease = lease_with(vec![runner()]);
1262        lease.heartbeat_at = "not a timestamp".into();
1263        assert!(matches!(
1264            assess(&facts(lease, true, true, FRESH)),
1265            Admission::Denied(_)
1266        ));
1267    }
1268
1269    #[test]
1270    fn a_live_runner_after_its_launcher_exits_is_adopted_not_denied() {
1271        // `smix runner up` exits by design; the runner it leaves is a
1272        // service the next command drives *through*. This used to be
1273        // pinned as Denied, with a comment about not tearing down a
1274        // working runner — the right worry, wrong verdict: denial kept
1275        // the runner alive by making it unusable, which barred the
1276        // quickstart's own `runner up` → `run` pairing on every device.
1277        let f = facts_with_resources(lease_with(vec![runner()]), false, false, FRESH, true);
1278        assert_eq!(assess(&f), Admission::Adoptable);
1279    }
1280
1281    #[test]
1282    fn the_whole_physical_stack_is_adoptable_too() {
1283        // What `runner up <phone>` actually leaves: boot row, runner,
1284        // forwarder. All services; all kept by the adopter.
1285        let lease = lease_with(vec![
1286            Resource::Booted { by_us: true },
1287            runner(),
1288            Resource::PortForward {
1289                local_port: 22097,
1290                device_port: 22097,
1291                proc: runner_proc(),
1292            },
1293        ]);
1294        assert_eq!(
1295            assess(&facts_with_resources(lease, false, false, FRESH, true)),
1296            Admission::Adoptable
1297        );
1298    }
1299
1300    #[test]
1301    fn a_live_recording_is_not_adopted_past() {
1302        // A recording is an activity, not a service: adopting past it
1303        // would let a second session run over whatever the first was
1304        // capturing. Denied — and the denial must say the holder is
1305        // dead, so the message blames the recording rather than telling
1306        // someone to wait for a pid that no longer exists.
1307        let lease = lease_with(vec![runner(), recording()]);
1308        match assess(&facts_with_resources(lease, false, false, FRESH, true)) {
1309            Admission::Denied(c) => assert!(!c.holder_alive),
1310            other => panic!("expected Denied, got {other:?}"),
1311        }
1312    }
1313
1314    #[test]
1315    fn a_live_holder_still_denies_no_matter_the_resources() {
1316        // The real concurrency case, untouched: two commands at once is
1317        // contention whether or not the resources are services.
1318        let f = facts_with_resources(lease_with(vec![runner()]), true, true, FRESH, true);
1319        assert!(matches!(assess(&f), Admission::Denied(_)));
1320    }
1321
1322    #[test]
1323    fn cleanup_is_reverse_of_open_order() {
1324        let lease = lease_with(vec![
1325            Resource::Booted { by_us: true },
1326            runner(),
1327            recording(),
1328        ]);
1329        assert_eq!(
1330            plan_cleanup(&lease),
1331            vec![
1332                CleanupAction::StopRecording {
1333                    path: ".smix/trace/run.mov".into(),
1334                    proc: recording_proc(),
1335                },
1336                CleanupAction::StopRunner {
1337                    port: 22087,
1338                    proc: runner_proc(),
1339                },
1340                CleanupAction::ShutdownSim {
1341                    udid: "UDID-1".into(),
1342                },
1343            ]
1344        );
1345    }
1346
1347    #[test]
1348    fn device_we_did_not_boot_is_not_ours_to_shut_down() {
1349        let lease = lease_with(vec![Resource::Booted { by_us: false }, runner()]);
1350        assert_eq!(
1351            plan_cleanup(&lease),
1352            vec![CleanupAction::StopRunner {
1353                port: 22087,
1354                proc: runner_proc(),
1355            }]
1356        );
1357    }
1358
1359    #[test]
1360    fn every_signalling_action_carries_an_identity_to_verify() {
1361        // The executor must be able to confirm the pid is still that
1362        // process. An action that cannot be verified is one that signals
1363        // strangers.
1364        let lease = lease_with(vec![runner(), recording()]);
1365        for action in plan_cleanup(&lease) {
1366            match action {
1367                CleanupAction::StopRunner { proc, .. }
1368                | CleanupAction::StopRecording { proc, .. }
1369                | CleanupAction::StopSupervisor { proc, .. }
1370                | CleanupAction::StopAndroidRunner { proc, .. }
1371                | CleanupAction::StopPortForward { proc, .. } => {
1372                    assert!(
1373                        !proc.started_at.is_empty(),
1374                        "no start time to verify against"
1375                    );
1376                }
1377                // Carries no process by design: there is nothing to
1378                // signal for a row nobody can read, nothing to signal
1379                // for a device, and — for a reverse route — nothing to
1380                // signal at all, since it lives in the adb server.
1381                CleanupAction::ShutdownSim { .. }
1382                | CleanupAction::CannotClose { .. }
1383                | CleanupAction::RemoveReversePort { .. } => {}
1384            }
1385        }
1386    }
1387
1388    #[test]
1389    fn lease_json_roundtrips() {
1390        let lease = lease_with(vec![
1391            Resource::Booted { by_us: true },
1392            runner(),
1393            recording(),
1394        ]);
1395        let json = serde_json::to_string_pretty(&lease).expect("serialize");
1396        let back: Lease = serde_json::from_str(&json).expect("deserialize");
1397        assert_eq!(lease, back);
1398        // Another process reads this shape — pin the field spelling.
1399        assert!(json.contains("\"deviceId\""));
1400        assert!(json.contains("\"startedAt\""));
1401        assert!(json.contains("\"byUs\""));
1402    }
1403}
1404
1405#[cfg(test)]
1406mod boot_only_tests {
1407    use super::*;
1408
1409    #[test]
1410    fn a_ledger_holding_only_a_boot_is_a_free_device_not_an_orphan() {
1411        // Regression: `smix sim boot` exits as soon as the device is up.
1412        // Judging its ledger as abandoned made the next command shut the
1413        // device down — undoing what had just been asked for.
1414        let lease = Lease {
1415            device_id: "UDID-1".into(),
1416            holder: ProcIdentity {
1417                pid: 0,
1418                started_at: "Thu Aug  6 10:00:00 2026".into(),
1419                cmd: "smix sim boot UDID-1".into(),
1420            },
1421            acquired_at: "2026-08-06T10:00:00Z".into(),
1422            heartbeat_at: "2026-08-06T10:00:00Z".into(),
1423            resources: vec![Row::Known(Resource::Booted { by_us: true })],
1424        };
1425        let facts = Facts {
1426            existing: Some(Held {
1427                lease,
1428                holder: HolderProbe {
1429                    pid_exists: false,
1430                    identity_matches: false,
1431                },
1432                any_resource_alive: false,
1433            }),
1434            now: "2026-08-06T10:00:30Z".into(),
1435            self_pid: 9000,
1436        };
1437        assert_eq!(assess(&facts), Admission::Granted);
1438    }
1439
1440    #[test]
1441    fn a_boot_plus_a_dead_runner_is_still_an_orphan() {
1442        // The distinction is the process-backed row, not the boot.
1443        let lease = Lease {
1444            device_id: "UDID-1".into(),
1445            holder: ProcIdentity {
1446                pid: 0,
1447                started_at: "Thu Aug  6 10:00:00 2026".into(),
1448                cmd: "smix run x.yaml".into(),
1449            },
1450            acquired_at: "2026-08-06T10:00:00Z".into(),
1451            heartbeat_at: "2026-08-06T10:00:00Z".into(),
1452            resources: vec![
1453                Row::Known(Resource::Booted { by_us: true }),
1454                Row::Known(Resource::Runner {
1455                    port: 1,
1456                    bundle: None,
1457                    log: None,
1458                    proc: ProcIdentity {
1459                        pid: 0,
1460                        started_at: "Thu Aug  6 10:00:05 2026".into(),
1461                        cmd: "xcodebuild".into(),
1462                    },
1463                }),
1464            ],
1465        };
1466        let facts = Facts {
1467            existing: Some(Held {
1468                lease,
1469                holder: HolderProbe {
1470                    pid_exists: false,
1471                    identity_matches: false,
1472                },
1473                any_resource_alive: false,
1474            }),
1475            now: "2026-08-06T10:00:30Z".into(),
1476            self_pid: 9000,
1477        };
1478        match assess(&facts) {
1479            Admission::Reclaimable { cleanup, .. } => {
1480                assert_eq!(cleanup.len(), 2, "the runner and the boot are both owed");
1481            }
1482            other => panic!("expected Reclaimable, got {other:?}"),
1483        }
1484    }
1485}
1486
1487#[cfg(test)]
1488mod ordering_tests {
1489    use super::*;
1490
1491    fn proc(pid: u32, cmd: &str) -> ProcIdentity {
1492        ProcIdentity {
1493            pid,
1494            started_at: "Thu Aug  6 10:00:00 2026".into(),
1495            cmd: cmd.into(),
1496        }
1497    }
1498
1499    fn lease(resources: Vec<Resource>) -> Lease {
1500        Lease {
1501            device_id: "UDID-1".into(),
1502            holder: proc(4242, "smix runner up"),
1503            acquired_at: "2026-08-06T10:00:00Z".into(),
1504            heartbeat_at: "2026-08-06T10:00:00Z".into(),
1505            resources: resources.into_iter().map(Row::Known).collect(),
1506        }
1507    }
1508
1509    #[test]
1510    fn the_supervisor_is_stopped_before_the_runner_it_watches() {
1511        // Not a style preference. A supervisor exists to bring a dead
1512        // runner back, so a teardown that stops the runner first is one
1513        // that undoes itself — `runner::down` already cascades in this
1514        // order, and encoding it in the plan means a reconcile running
1515        // hours later does not have to rediscover it.
1516        let l = lease(vec![
1517            Resource::Supervisor {
1518                proc: proc(5000, "smix runner supervise"),
1519            },
1520            Resource::Runner {
1521                port: 22087,
1522                bundle: None,
1523                log: None,
1524                proc: proc(5150, "xcodebuild test"),
1525            },
1526        ]);
1527        let plan = plan_cleanup(&l);
1528        let sup = plan
1529            .iter()
1530            .position(|a| matches!(a, CleanupAction::StopSupervisor { .. }))
1531            .expect("supervisor in plan");
1532        let run = plan
1533            .iter()
1534            .position(|a| matches!(a, CleanupAction::StopRunner { .. }))
1535            .expect("runner in plan");
1536        assert!(
1537            sup < run,
1538            "supervisor must be stopped first, got plan: {plan:?}"
1539        );
1540    }
1541
1542    #[test]
1543    fn an_android_runner_is_process_backed_and_carries_its_serial() {
1544        let r = Resource::AndroidRunner {
1545            port: 28080,
1546            serial: "emulator-5554".into(),
1547            proc: proc(6000, "am instrument"),
1548            bundle: None,
1549        };
1550        assert!(is_process_backed(&r));
1551        let l = lease(vec![r]);
1552        match plan_cleanup(&l).as_slice() {
1553            [CleanupAction::StopAndroidRunner { serial, port, .. }] => {
1554                // Every host-side call in the teardown names the device.
1555                // Without it the command reaches whatever is attached,
1556                // which on a developer machine is often a phone.
1557                assert_eq!(serial, "emulator-5554");
1558                assert_eq!(*port, 28080);
1559            }
1560            other => panic!("expected one android action, got {other:?}"),
1561        }
1562    }
1563
1564    #[test]
1565    fn a_supervisor_alone_does_not_make_a_device_occupied() {
1566        // A sidecar watching nothing is not a session. Treating it as
1567        // occupancy would keep the device claimed after the session it
1568        // was watching has ended.
1569        let r = Resource::Supervisor {
1570            proc: proc(5000, "smix runner supervise"),
1571        };
1572        assert!(is_process_backed(&r), "it is still a process to clean up");
1573    }
1574
1575    #[test]
1576    fn the_new_rows_roundtrip_with_their_field_spelling_pinned() {
1577        let l = lease(vec![
1578            Resource::Supervisor {
1579                proc: proc(5000, "smix runner supervise"),
1580            },
1581            Resource::AndroidRunner {
1582                port: 28080,
1583                serial: "emulator-5554".into(),
1584                proc: proc(6000, "am instrument"),
1585                bundle: None,
1586            },
1587        ]);
1588        let json = serde_json::to_string_pretty(&l).expect("serialize");
1589        let back: Lease = serde_json::from_str(&json).expect("deserialize");
1590        assert_eq!(l, back);
1591        assert!(json.contains("\"supervisor\""));
1592        assert!(json.contains("\"androidRunner\""));
1593        assert!(json.contains("\"serial\""));
1594    }
1595}
1596
1597#[cfg(test)]
1598mod entitlement_tests {
1599    use super::*;
1600
1601    fn lease(resources: Vec<Resource>) -> Lease {
1602        Lease {
1603            device_id: "UDID-1".into(),
1604            holder: ProcIdentity {
1605                pid: 1,
1606                started_at: "Thu Aug  6 10:00:00 2026".into(),
1607                cmd: "smix".into(),
1608            },
1609            acquired_at: "2026-08-06T10:00:00Z".into(),
1610            heartbeat_at: "2026-08-06T10:00:00Z".into(),
1611            resources: resources.into_iter().map(Row::Known).collect(),
1612        }
1613    }
1614
1615    #[test]
1616    fn a_device_with_no_ledger_is_not_ours_to_shut_down() {
1617        // The case that took away somebody's dev server: registered,
1618        // booted by them, swept by us.
1619        assert!(!may_shut_down(None));
1620    }
1621
1622    #[test]
1623    fn a_device_we_found_already_up_is_not_ours_either() {
1624        let l = lease(vec![Resource::Booted { by_us: false }]);
1625        assert!(!may_shut_down(Some(&l)));
1626    }
1627
1628    #[test]
1629    fn a_device_we_booted_is_ours() {
1630        let l = lease(vec![Resource::Booted { by_us: true }]);
1631        assert!(may_shut_down(Some(&l)));
1632    }
1633
1634    #[test]
1635    fn a_ledger_without_a_boot_row_says_nothing_about_entitlement() {
1636        // We have a runner on it, but somebody else turned it on.
1637        let l = lease(vec![Resource::Runner {
1638            port: 22087,
1639            bundle: None,
1640            log: None,
1641            proc: ProcIdentity {
1642                pid: 2,
1643                started_at: "Thu Aug  6 10:00:05 2026".into(),
1644                cmd: "xcodebuild".into(),
1645            },
1646        }]);
1647        assert!(!may_shut_down(Some(&l)));
1648    }
1649}
1650
1651#[cfg(test)]
1652mod destructive_gate_tests {
1653    use super::*;
1654
1655    fn sim() -> DeviceClass {
1656        DeviceClass {
1657            physical: false,
1658            destructive_opt_in: false,
1659        }
1660    }
1661
1662    fn phone(opted_in: bool) -> DeviceClass {
1663        DeviceClass {
1664            physical: true,
1665            destructive_opt_in: opted_in,
1666        }
1667    }
1668
1669    #[test]
1670    fn a_simulator_is_never_gated() {
1671        // Gating it would add a step to the common case and buy nothing:
1672        // a simulator can be erased and rebuilt in a minute.
1673        assert!(may_destroy("sim-smix-02", sim()).is_ok());
1674    }
1675
1676    #[test]
1677    fn a_phone_without_opt_in_is_refused() {
1678        assert!(may_destroy("panda", phone(false)).is_err());
1679    }
1680
1681    #[test]
1682    fn a_phone_with_opt_in_is_allowed() {
1683        assert!(may_destroy("panda", phone(true)).is_ok());
1684    }
1685
1686    #[test]
1687    fn a_registered_device_is_addressable_whatever_it_is() {
1688        // Registration is the invitation. Whether the thing may then be
1689        // *harmed* is a separate question with a separate gate.
1690        assert!(may_address("panda", Known::Registered(phone(false))).is_ok());
1691        assert!(may_address("panda", Known::Registered(phone(true))).is_ok());
1692        assert!(may_address("sim-smix-02", Known::Registered(sim())).is_ok());
1693    }
1694
1695    #[test]
1696    fn an_unregistered_simulator_stays_addressable() {
1697        // `smix sim boot <a udid nobody registered>` is an ordinary thing
1698        // to do. The charter's protection is aimed at devices somebody
1699        // carries, not at ones that rebuild in a minute.
1700        assert!(
1701            may_address(
1702                "C0FFEE00-0000-4000-8000-000000000000",
1703                Known::UnregisteredVirtual
1704            )
1705            .is_ok()
1706        );
1707    }
1708
1709    #[test]
1710    fn a_device_nobody_registered_is_refused() {
1711        assert!(may_address("D51116A4-B2AD-5432-8A75-6FBB13F17B58", Known::Unknown).is_err());
1712    }
1713
1714    #[test]
1715    fn the_addressability_refusal_asks_for_a_decision_not_a_retry() {
1716        // An unregistered device is not a typo. Telling someone to check
1717        // the spelling would send them looking for a mistake they did not
1718        // make; what is missing is a decision nobody has taken yet, so
1719        // the message asks for that decision by name.
1720        let err =
1721            may_address("R5CT52DF07D", Known::Unknown).expect_err("an unknown device must refuse");
1722        let msg = err.to_string();
1723        assert!(msg.contains("R5CT52DF07D"), "got: {msg}");
1724        assert!(msg.contains("smix sim register"), "got: {msg}");
1725        for retry_flavoured in ["check the spelling", "try again", "did you mean"] {
1726            assert!(
1727                !msg.to_lowercase().contains(retry_flavoured),
1728                "the refusal must not read as a typo, got: {msg}"
1729            );
1730        }
1731    }
1732
1733    #[test]
1734    fn the_refusal_names_the_device_and_the_way_out() {
1735        // A guard that only says no gets worked around rather than
1736        // obeyed. Both halves are asserted because either alone is
1737        // useless: the device name without the remedy leaves someone
1738        // guessing, the remedy without the name leaves them unsure it
1739        // applies to what they just ran.
1740        let err = may_destroy("panda", phone(false)).expect_err("must refuse");
1741        let msg = err.to_string();
1742        assert!(msg.contains("panda"), "got: {msg}");
1743        assert!(
1744            msg.contains("smix sim allow-destructive panda"),
1745            "got: {msg}"
1746        );
1747        assert!(
1748            msg.contains("not undoable"),
1749            "the refusal should say why, got: {msg}"
1750        );
1751    }
1752}
1753
1754#[cfg(test)]
1755mod forward_ordering_tests {
1756    use super::*;
1757
1758    fn proc(pid: u32, cmd: &str) -> ProcIdentity {
1759        ProcIdentity {
1760            pid,
1761            started_at: "Thu Aug  6 10:00:00 2026".into(),
1762            cmd: cmd.into(),
1763        }
1764    }
1765
1766    fn lease(resources: Vec<Resource>) -> Lease {
1767        Lease {
1768            device_id: "00008120-001410C11A42201E".into(),
1769            holder: proc(4242, "smix runner up"),
1770            acquired_at: "2026-08-06T10:00:00Z".into(),
1771            heartbeat_at: "2026-08-06T10:00:00Z".into(),
1772            resources: resources.into_iter().map(Row::Known).collect(),
1773        }
1774    }
1775
1776    fn reverse_row(device_port: u16, host_port: u16) -> Resource {
1777        Resource::ReversePort {
1778            device_port,
1779            host_port,
1780            serial: "emulator-5554".into(),
1781        }
1782    }
1783
1784    /// Mirror of the forwarder's reason: the app's last requests are
1785    /// still travelling through this route while the runner shuts down.
1786    #[test]
1787    fn a_reverse_route_is_closed_after_the_runner_it_served() {
1788        let lease = lease(vec![
1789            reverse_row(8080, 8080),
1790            Resource::AndroidRunner {
1791                port: 22087,
1792                serial: "emulator-5554".into(),
1793                proc: proc(5150, "am instrument"),
1794                bundle: None,
1795            },
1796        ]);
1797        let plan = plan_cleanup(&lease);
1798        let runner_at = plan
1799            .iter()
1800            .position(|a| matches!(a, CleanupAction::StopAndroidRunner { .. }))
1801            .expect("the runner is in the plan");
1802        let route_at = plan
1803            .iter()
1804            .position(|a| matches!(a, CleanupAction::RemoveReversePort { .. }))
1805            .expect("the route is in the plan");
1806        assert!(
1807            runner_at < route_at,
1808            "pulling the route first turns a clean teardown into a connection error: {plan:?}"
1809        );
1810    }
1811
1812    /// The device port is what identifies a route, and a device may
1813    /// have several open at once — so the plan closes each one it was
1814    /// told about, by its own port.
1815    #[test]
1816    fn every_open_route_is_in_the_plan_by_its_device_port() {
1817        let lease = lease(vec![reverse_row(8080, 8080), reverse_row(3000, 3001)]);
1818        let ports: Vec<u16> = plan_cleanup(&lease)
1819            .iter()
1820            .filter_map(|a| match a {
1821                CleanupAction::RemoveReversePort { device_port, .. } => Some(*device_port),
1822                _ => None,
1823            })
1824            .collect();
1825        assert_eq!(ports.len(), 2, "both routes owe a close");
1826        assert!(ports.contains(&8080) && ports.contains(&3000), "{ports:?}");
1827    }
1828
1829    fn full_session() -> Lease {
1830        lease(vec![
1831            Resource::PortForward {
1832                local_port: 22087,
1833                device_port: 22087,
1834                proc: proc(7000, "smix forward"),
1835            },
1836            Resource::Supervisor {
1837                proc: proc(5000, "smix runner supervise"),
1838            },
1839            Resource::Runner {
1840                port: 22087,
1841                bundle: None,
1842                log: None,
1843                proc: proc(5150, "xcodebuild test"),
1844            },
1845        ])
1846    }
1847
1848    #[test]
1849    fn the_pipe_is_pulled_after_the_runner_it_serves() {
1850        // The mirror image of the supervisor rule. A runner's closing
1851        // requests still travel through the forwarder; pulling it first
1852        // turns an orderly teardown into a connection error that reads
1853        // like the runner misbehaved.
1854        let plan = plan_cleanup(&full_session());
1855        let fwd = plan
1856            .iter()
1857            .position(|a| matches!(a, CleanupAction::StopPortForward { .. }))
1858            .expect("forward in plan");
1859        let run = plan
1860            .iter()
1861            .position(|a| matches!(a, CleanupAction::StopRunner { .. }))
1862            .expect("runner in plan");
1863        assert!(fwd > run, "forward must go last, got plan: {plan:?}");
1864    }
1865
1866    #[test]
1867    fn a_full_session_tears_down_supervisor_then_runner_then_pipe() {
1868        // Three rules meeting in one plan, each for its own reason.
1869        let plan = plan_cleanup(&full_session());
1870        let kinds: Vec<&str> = plan
1871            .iter()
1872            .map(|a| match a {
1873                CleanupAction::StopSupervisor { .. } => "supervisor",
1874                CleanupAction::StopRunner { .. } => "runner",
1875                CleanupAction::StopPortForward { .. } => "forward",
1876                CleanupAction::StopRecording { .. } => "recording",
1877                CleanupAction::StopAndroidRunner { .. } => "android",
1878                CleanupAction::ShutdownSim { .. } => "shutdown",
1879                CleanupAction::CannotClose { .. } => "unnamed",
1880                CleanupAction::RemoveReversePort { .. } => "reverse",
1881            })
1882            .collect();
1883        assert_eq!(kinds, vec!["supervisor", "runner", "forward"]);
1884    }
1885
1886    #[test]
1887    fn a_forwarder_is_something_to_clean_up_but_not_occupancy() {
1888        // Same reasoning as a recording: a pipe nobody is talking
1889        // through does not make a device busy. Counting it would leave
1890        // an abandoned forwarder running forever, since nothing would
1891        // ever judge the ledger reclaimable.
1892        let r = Resource::PortForward {
1893            local_port: 22087,
1894            device_port: 22087,
1895            proc: proc(7000, "smix forward"),
1896        };
1897        assert!(is_process_backed(&r), "it is still a process to close");
1898    }
1899
1900    #[test]
1901    fn the_row_roundtrips_with_its_spelling_pinned() {
1902        let l = lease(vec![Resource::PortForward {
1903            local_port: 22087,
1904            device_port: 22087,
1905            proc: proc(7000, "smix forward"),
1906        }]);
1907        let json = serde_json::to_string(&l).expect("serialize");
1908        assert!(json.contains("\"portForward\""), "got: {json}");
1909        assert!(json.contains("\"localPort\""), "got: {json}");
1910        assert!(json.contains("\"devicePort\""), "got: {json}");
1911        assert_eq!(serde_json::from_str::<Lease>(&json).expect("parse"), l);
1912    }
1913}