Skip to main content

magi/
worker.rs

1//! Durable detached execution, independent of the scheduler and web lifetimes.
2//!
3//! A reservation is published before spawn, and the child must take its execution
4//! lease and acknowledge that reservation before dispatch. Reconciliation cancels
5//! an unacknowledged startup under the same store lock the child needs: a late
6//! child can never execute a cancelled operation. Process IDs are diagnostic only.
7//! Metadata publication closes its staging handle before atomic replacement.
8//! Windows replacement/delete-pending handoffs use the short, bounded lock-file
9//! retry policy; failed publication never releases an uncertain reservation.
10
11use std::fs::{File, OpenOptions};
12use std::io::{Read, Write};
13use std::path::{Path, PathBuf};
14use std::process::{Child, Command, Stdio};
15use std::sync::{LazyLock, Mutex, OnceLock};
16use std::time::{Duration, SystemTime, UNIX_EPOCH};
17
18use anyhow::{Context, Result, bail};
19use serde::{Deserialize, Serialize};
20use sha2::{Digest, Sha256};
21
22const STARTUP_SECONDS: u64 = 30;
23const RETAIN_FINISHED: usize = 256;
24
25/// Identity and executable selection inherited by descendants of a worker.
26/// Verification commands and standalone test fixtures remove these overrides:
27/// they test the checkout, rather than act on behalf of the enclosing worker.
28/// Keep runtime storage, seat metadata and process containment context intact.
29pub const INVOCATION_ENV: [&str; 4] = [
30    "MAGI_WORKER_ID",
31    "MAGI_WORKER_GENERATION",
32    "MAGI_WORKER_HOME",
33    "MAGI_WORKER_EXE",
34];
35
36/// Durable execution state. Starting reservations count as occupied slots.
37#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
38#[serde(rename_all = "snake_case")]
39pub enum Status {
40    /// Published but not yet acknowledged by the detached child.
41    Starting,
42    /// The child acknowledged startup and owns the execution lease.
43    Running,
44    /// The handler returned successfully.
45    Finished,
46    /// Startup, handler execution, or the owning process failed.
47    Failed,
48}
49
50impl Status {
51    /// Stable lowercase label matching the on-disk representation.
52    #[must_use]
53    pub const fn as_str(self) -> &'static str {
54        match self {
55            Self::Starting => "starting",
56            Self::Running => "running",
57            Self::Finished => "finished",
58            Self::Failed => "failed",
59        }
60    }
61}
62
63impl std::fmt::Display for Status {
64    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
65        formatter.write_str(self.as_str())
66    }
67}
68
69/// Why an observed worker reservation counts as active.
70#[derive(Clone, Copy, Debug, PartialEq, Eq)]
71pub enum ActiveReason {
72    /// Reservation is still `starting` and has not been fenced by a writer.
73    UnfencedStartup,
74    /// Worker holds its OS execution lease (`live.lock`).
75    LiveLeaseHeld,
76    /// Worker is recorded `running`, but `live.lock` is missing (protected conservatively).
77    MissingLiveLease,
78}
79
80impl ActiveReason {
81    /// Short diagnostic description of why the worker counts as active.
82    #[must_use]
83    pub const fn as_str(self) -> &'static str {
84        match self {
85            Self::UnfencedStartup => "unfenced starting reservation",
86            Self::LiveLeaseHeld => "live.lock held",
87            Self::MissingLiveLease => "running job missing live.lock",
88        }
89    }
90}
91
92impl std::fmt::Display for ActiveReason {
93    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
94        formatter.write_str(self.as_str())
95    }
96}
97
98/// One active worker reservation paired with the reason it counts as active.
99#[derive(Clone, Debug)]
100pub struct ObservedActive {
101    /// Observed worker job record.
102    pub job: Job,
103    /// Why this job was judged active.
104    pub reason: ActiveReason,
105}
106
107/// An explicit owner control; upgrades do not send these to task workers.
108#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
109#[serde(rename_all = "snake_case")]
110pub enum Control {
111    /// Park at the handler's existing safe cancellation boundary.
112    Park,
113    /// Stop the operation through its handler's cancellation path.
114    Stop,
115}
116
117#[derive(Debug)]
118struct NotStarted(anyhow::Error);
119
120impl std::fmt::Display for NotStarted {
121    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
122        write!(formatter, "{:#}", self.0)
123    }
124}
125
126impl std::error::Error for NotStarted {
127    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
128        Some(self.0.as_ref())
129    }
130}
131
132fn not_started_error(error: impl Into<anyhow::Error>) -> anyhow::Error {
133    anyhow::Error::new(NotStarted(error.into()))
134}
135
136/// Whether this spawn invocation provably did not execute its handler. This
137/// covers preparation failures and a failed OS spawn whose fresh reservation
138/// was exclusively leased and durably fenced before this error was returned.
139/// Only a fresh operation key makes this proof sufficient to restore a caller's
140/// publication. Unknown startup, existing work, or a failed fence is never tagged.
141pub fn not_started(error: &anyhow::Error) -> bool {
142    error.downcast_ref::<NotStarted>().is_some()
143}
144
145/// The wait timed out, but this reservation is still eligible to start.
146#[derive(Debug, thiserror::Error)]
147#[error(
148    "worker {id} startup is unacknowledged; its reservation remains occupied; inspect or retry the same operation key"
149)]
150pub(crate) struct StartupUnacknowledged {
151    pub(crate) id: String,
152}
153
154/// A durable operation record. Its payload belongs to the started generation.
155#[derive(Clone, Debug, Serialize, Deserialize)]
156pub struct Job {
157    /// Unique invocation identity.
158    pub id: String,
159    /// Durable total reservation order, independent of wall clock resolution.
160    #[serde(default)]
161    pub sequence: u64,
162    /// Dispatch handler, such as task, chat, scheduler, or service.
163    pub kind: String,
164    /// Exclusive logical operation identity, independent of executable generation.
165    pub key: String,
166    /// Handler-owned request.
167    pub payload: serde_json::Value,
168    /// SHA-256 identity of the immutable executable.
169    pub generation: String,
170    /// Version reported by the started executable, unknown before acknowledgement.
171    #[serde(default)]
172    pub version: Option<String>,
173    /// Last durable execution state.
174    pub status: Status,
175    /// Successful completion note or failure diagnostic.
176    pub result: Option<String>,
177    /// Diagnostic process ID, never used as an execution witness.
178    pub pid: Option<u32>,
179    /// Reservation publication time, seconds since the Unix epoch.
180    pub created_at: u64,
181    /// Terminal state publication time.
182    pub finished_at: Option<u64>,
183}
184
185/// An immutable, content-addressed executable.
186#[derive(Clone, Debug)]
187pub struct Generation {
188    /// SHA-256 digest of the executable bytes.
189    pub id: String,
190    /// Absolute path to the retained executable.
191    pub executable: PathBuf,
192}
193
194/// OS-held lock. Closing it, including on a crash, releases ownership.
195#[derive(Debug)]
196pub struct Lease {
197    _file: File,
198}
199
200impl Drop for Lease {
201    fn drop(&mut self) {
202        // flock's lock belongs to the open-file description; explicitly unlock
203        // so a temporarily inherited descriptor cannot prolong ownership.
204        #[cfg(unix)]
205        {
206            use std::os::fd::AsRawFd;
207            unsafe { libc::flock(self._file.as_raw_fd(), libc::LOCK_UN) };
208        }
209    }
210}
211
212fn root(home: &Path) -> PathBuf {
213    home.join("workers")
214}
215fn now() -> u64 {
216    SystemTime::now()
217        .duration_since(UNIX_EPOCH)
218        .unwrap_or_default()
219        .as_secs()
220}
221fn nonce() -> String {
222    crate::rng::SplitMix64::new(crate::rng::entropy()).uuid_v4()
223}
224fn valid_id(id: &str) -> bool {
225    !id.is_empty() && id.bytes().all(|b| b.is_ascii_hexdigit() || b == b'-')
226}
227fn job_dir(home: &Path, id: &str) -> Result<PathBuf> {
228    if !valid_id(id) {
229        bail!("invalid worker id");
230    }
231    Ok(root(home).join("jobs").join(id))
232}
233
234fn open_lock(path: &Path) -> Result<File> {
235    if let Some(parent) = path.parent() {
236        std::fs::create_dir_all(parent)
237            .with_context(|| format!("create worker lock directory {}", parent.display()))?;
238    }
239    OpenOptions::new()
240        .create(true)
241        .truncate(false)
242        .read(true)
243        .write(true)
244        .open(path)
245        .with_context(|| format!("open worker lock {}", path.display()))
246}
247
248fn try_lock(path: &Path) -> Result<Option<Lease>> {
249    let file = open_lock(path)?;
250    match crate::pr_head::try_lock_file(&file) {
251        Ok(()) => Ok(Some(Lease { _file: file })),
252        Err(e)
253            if e.kind() == std::io::ErrorKind::WouldBlock
254                || matches!(e.raw_os_error(), Some(33)) =>
255        {
256            Ok(None)
257        }
258        Err(e) => Err(e).with_context(|| format!("acquire worker lock {}", path.display())),
259    }
260}
261
262#[doc(hidden)]
263pub fn execution_lease_for_test(path: &Path) -> Lease {
264    try_lock(path)
265        .expect("execution lease")
266        .expect("free execution lease")
267}
268
269/// Try to own a named cross-process singleton, without PID-based stale handling.
270/// Names are hashed, so callers may use logical keys containing paths or colons.
271pub fn try_lease(home: &Path, name: &str) -> Result<Option<Lease>> {
272    try_lock(
273        &root(home)
274            .join("leases")
275            .join(format!("{}.lock", digest(name.as_bytes()))),
276    )
277}
278
279fn store_lock(home: &Path) -> Result<Lease> {
280    let deadline = std::time::Instant::now() + Duration::from_secs(10);
281    loop {
282        if let Some(lease) = try_lock(&root(home).join("store.lock"))? {
283            return Ok(lease);
284        }
285        if std::time::Instant::now() >= deadline {
286            bail!("worker store is busy; retry later");
287        }
288        std::thread::sleep(Duration::from_millis(5));
289    }
290}
291
292#[cfg(unix)]
293fn sync_dir(path: &Path) -> Result<()> {
294    File::open(path)
295        .with_context(|| format!("open worker directory for sync {}", path.display()))?
296        .sync_all()
297        .with_context(|| format!("sync worker directory {}", path.display()))?;
298    Ok(())
299}
300
301#[cfg(not(unix))]
302fn sync_dir(_path: &Path) -> Result<()> {
303    Ok(())
304}
305
306fn save(path: &Path, value: &impl Serialize) -> Result<()> {
307    let parent = path.parent().context("worker record has no parent")?;
308    std::fs::create_dir_all(parent)
309        .with_context(|| format!("create worker record directory {}", parent.display()))?;
310    let temp = parent.join(format!(".pending-{}", nonce()));
311    let result = (|| -> Result<()> {
312        let mut file = OpenOptions::new()
313            .create_new(true)
314            .write(true)
315            .open(&temp)
316            .with_context(|| format!("create staged worker record {}", temp.display()))?;
317        serde_json::to_writer(&mut file, value)
318            .with_context(|| format!("serialize worker record {}", path.display()))?;
319        file.flush()
320            .with_context(|| format!("flush staged worker record {}", temp.display()))?;
321        file.sync_all()
322            .with_context(|| format!("sync staged worker record {}", temp.display()))?;
323        // Publication must not retain our own writable staging handle. Windows
324        // readers may briefly deny deletion; only the atomic handoff retries.
325        drop(file);
326        replace(&temp, path).with_context(|| {
327            format!(
328                "publish worker record {} -> {}",
329                temp.display(),
330                path.display()
331            )
332        })?;
333        sync_dir(parent)
334    })();
335    if result.is_err() {
336        let _ = std::fs::remove_file(&temp);
337    }
338    result
339}
340
341#[cfg(not(windows))]
342fn replace(from: &Path, to: &Path) -> Result<()> {
343    Ok(std::fs::rename(from, to)?)
344}
345
346#[cfg(windows)]
347fn replace(from: &Path, to: &Path) -> Result<()> {
348    // std uses FileRenameInfoEx/POSIX semantics where supported, unlike
349    // MoveFileExW: a FILE_SHARE_DELETE reader may retain the previous record
350    // while the replacement becomes visible atomically. Readers that briefly
351    // deny deletion still get only the existing short Windows handoff budget.
352    crate::lock_file::Retry::new(None).run(|| std::fs::rename(from, to))?;
353    Ok(())
354}
355
356// Atomic replacement can leave the old Windows name briefly delete-pending.
357// Keep that handoff bounded; malformed records and permanent IO errors propagate.
358fn open_record(path: &Path) -> std::io::Result<File> {
359    #[cfg(windows)]
360    {
361        crate::lock_file::Retry::new(None).run(|| File::open(path))
362    }
363    #[cfg(not(windows))]
364    {
365        File::open(path)
366    }
367}
368
369/// Load a specific invocation, including a retained terminal result.
370pub fn get(home: &Path, id: &str) -> Result<Job> {
371    let path = job_dir(home, id)?.join("job.json");
372    let file = match open_record(&path) {
373        Ok(file) => file,
374        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
375            let retained = root(home).join("results").join(id).join("job.json");
376            open_record(&retained)
377                .with_context(|| format!("open retained worker record {}", retained.display()))?
378        }
379        Err(error) => {
380            let retained = root(home).join("results").join(id).join("job.json");
381            if let Ok(file) = open_record(&retained) {
382                file
383            } else {
384                return Err(error)
385                    .with_context(|| format!("open worker record {}", path.display()));
386            }
387        }
388    };
389    serde_json::from_reader(file).with_context(|| format!("decode worker record {id}"))
390}
391
392fn confirmed_terminal_retained(home: &Path, id: &str) -> bool {
393    if !valid_id(id) {
394        return false;
395    }
396    let retained = root(home).join("results").join(id).join("job.json");
397    open_record(&retained)
398        .ok()
399        .and_then(|file| serde_json::from_reader::<_, Job>(file).ok())
400        .is_some_and(|job| matches!(job.status, Status::Finished | Status::Failed))
401}
402
403fn confirmed_terminal(home: &Path, id: &str) -> bool {
404    get(home, id)
405        .ok()
406        .is_some_and(|job| matches!(job.status, Status::Finished | Status::Failed))
407}
408
409/// Identify this detached invocation. Helpers inherit its identity, while a
410/// newly spawned worker receives its own id before exec; no global environment
411/// mutation is required inside the asynchronous handler runtime.
412pub fn current_job(home: &Path) -> Result<Option<Job>> {
413    match std::env::var("MAGI_WORKER_ID") {
414        Ok(id) => Ok(Some(get(home, &id)?)),
415        Err(std::env::VarError::NotPresent) => Ok(None),
416        Err(error) => Err(error.into()),
417    }
418}
419
420fn next_sequence(home: &Path) -> Result<u64> {
421    let path = root(home).join("sequence.json");
422    let previous: u64 = match open_record(&path) {
423        Ok(file) => serde_json::from_reader(file)
424            .with_context(|| format!("decode worker sequence {}", path.display()))?,
425        Err(error) if error.kind() == std::io::ErrorKind::NotFound => 0,
426        Err(error) => {
427            return Err(error).with_context(|| format!("open worker sequence {}", path.display()));
428        }
429    };
430    let sequence = previous
431        .checked_add(1)
432        .context("worker reservation sequence exhausted")?;
433    save(&path, &sequence)?;
434    Ok(sequence)
435}
436
437fn records(home: &Path) -> Result<Vec<Job>> {
438    let directory = root(home).join("jobs");
439    std::fs::create_dir_all(&directory)?;
440    let mut jobs = Vec::new();
441    let mut retired = false;
442    for entry in std::fs::read_dir(directory)? {
443        let entry = entry?;
444        if !entry.file_type()?.is_dir() {
445            continue;
446        }
447        let name = entry.file_name();
448        let Some(id) = name.to_str() else {
449            continue;
450        };
451        if id.starts_with(".new-") {
452            // Reservations are staged only while holding the store lock. Any
453            // staging directory visible to the next owner was left by a crash.
454            std::fs::remove_dir_all(entry.path())?;
455            continue;
456        }
457        if id.starts_with('.') {
458            continue;
459        }
460        for pending in std::fs::read_dir(entry.path())? {
461            let pending = pending?;
462            if pending.file_type()?.is_file()
463                && pending
464                    .file_name()
465                    .to_string_lossy()
466                    .starts_with(".pending-")
467            {
468                std::fs::remove_file(pending.path())?;
469            }
470        }
471        let job = get(home, id).with_context(|| format!("read worker {id}"))?;
472        if matches!(job.status, Status::Starting | Status::Running) {
473            jobs.push(job);
474        } else {
475            retired |= retire(home, &job);
476        }
477    }
478    if retired {
479        if let Err(error) = prune_results(home) {
480            tracing::warn!(%error, "worker result retention deferred");
481        }
482    }
483    Ok(jobs)
484}
485
486fn terminal(home: &Path, job: &mut Job, status: Status, result: String) -> Result<()> {
487    job.status = status;
488    job.result = Some(result);
489    job.finished_at = Some(now());
490    save(&job_dir(home, &job.id)?.join("job.json"), job)
491        .with_context(|| format!("publish worker {} terminal status {status:?}", job.id))?;
492    // The result is authoritative now. Keep the directory in place while this
493    // process owns live.lock and its stdout/stderr handles. Another store owner
494    // retires it opportunistically after execution ownership is released.
495    clear_control_locked(home, &job.key)
496}
497
498fn retire(home: &Path, job: &Job) -> bool {
499    let attempt = || -> Result<bool> {
500        let dir = job_dir(home, &job.id)?;
501        let Some(lease) = try_lock(&dir.join("live.lock"))? else {
502            return Ok(false);
503        };
504        drop(lease);
505        archive(home, job)?;
506        Ok(true)
507    };
508    // Windows can still deny the directory rename in the short interval after
509    // lease release but before process stdout/stderr are closed. Retry on the
510    // next store read; archival failure must never turn completion into failure
511    // or terminate an otherwise healthy scheduler.
512    match attempt() {
513        Ok(retired) => retired,
514        Err(error) => {
515            tracing::warn!(
516                worker = %job.id,
517                error = %format_args!("{error:#}"),
518                "worker result retirement deferred"
519            );
520            false
521        }
522    }
523}
524
525fn archive(home: &Path, job: &Job) -> Result<()> {
526    let results = root(home).join("results");
527    std::fs::create_dir_all(&results)
528        .with_context(|| format!("create worker results directory {}", results.display()))?;
529    let from = job_dir(home, &job.id)?;
530    let to = results.join(&job.id);
531    std::fs::rename(&from, &to).with_context(|| {
532        format!(
533            "archive worker result {} -> {}",
534            from.display(),
535            to.display()
536        )
537    })?;
538    sync_dir(&root(home).join("jobs"))?;
539    sync_dir(&results)
540}
541
542// Caller owns the store lock. Acquiring the execution lease and then marking a
543// dead startup terminal fences a late child: it must recheck state under store.
544fn reconcile(home: &Path, jobs: &mut [Job]) -> Result<()> {
545    let mut retired = false;
546    for job in jobs {
547        if !matches!(job.status, Status::Starting | Status::Running) {
548            continue;
549        }
550        let lease = try_lock(&job_dir(home, &job.id)?.join("live.lock"))?;
551        if lease.is_none() {
552            continue;
553        }
554        if job.status == Status::Starting && now().saturating_sub(job.created_at) < STARTUP_SECONDS
555        {
556            continue;
557        }
558        let reason = if job.status == Status::Starting {
559            "worker startup reservation expired before acknowledgement"
560        } else {
561            "worker exited without recording a result"
562        };
563        terminal(home, job, Status::Failed, reason.to_owned())?;
564        drop(lease);
565        retired |= retire(home, job);
566    }
567    if retired {
568        if let Err(error) = prune_results(home) {
569            tracing::warn!(%error, "worker result retention deferred");
570        }
571    }
572    Ok(())
573}
574
575/// List live operations and unresolved startups. A missing lease only frees a
576/// startup after its deadline and an atomic cancellation fence; PID is irrelevant.
577pub fn active(home: &Path) -> Result<Vec<Job>> {
578    let _store = store_lock(home)?;
579    let mut jobs = records(home)?;
580    reconcile(home, &mut jobs)?;
581    Ok(jobs
582        .into_iter()
583        .filter(|job| matches!(job.status, Status::Starting | Status::Running))
584        .collect())
585}
586
587/// Observe execution without creating, repairing, archiving, or locking the
588/// writable store. Sandboxed diagnostics need only file reads and a read-only
589/// handle for the OS lease probe. Starting reservations remain protected until
590/// an authorized writer fences them; a missing running lease is unknown.
591pub fn observe_active(home: &Path) -> Result<Vec<Job>> {
592    observe_active_detailed(home).map(|jobs| jobs.into_iter().map(|entry| entry.job).collect())
593}
594
595/// Same passive observation as [`observe_active`], retaining why each observed
596/// worker counts as active.
597pub fn observe_active_detailed(home: &Path) -> Result<Vec<ObservedActive>> {
598    let entries = match std::fs::read_dir(root(home).join("jobs")) {
599        Ok(entries) => entries,
600        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
601        Err(error) => return Err(error.into()),
602    };
603    let mut active = Vec::new();
604    for entry in entries {
605        let entry = entry?;
606        let name = entry.file_name();
607        if name.to_str().is_some_and(|id| id.starts_with('.')) {
608            continue;
609        }
610        let is_dir = match entry.file_type() {
611            Ok(file_type) => file_type.is_dir(),
612            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
613                if name
614                    .to_str()
615                    .is_some_and(|id| confirmed_terminal_retained(home, id))
616                {
617                    continue;
618                }
619                return Err(error.into());
620            }
621            Err(error) => return Err(error.into()),
622        };
623        if !is_dir {
624            continue;
625        }
626        let id = name.to_str().context("invalid worker reservation name")?;
627        let job = get(home, id)?;
628        if let Some(reason) = observe_job_active_reason(home, &job)? {
629            active.push(ObservedActive { job, reason });
630        }
631    }
632    Ok(active)
633}
634
635/// Passive lease observation for a single reservation already read by the caller.
636pub(crate) fn observe_job_active(home: &Path, job: &Job) -> Result<bool> {
637    Ok(observe_job_active_reason(home, job)?.is_some())
638}
639
640/// Same passive observation as [`observe_job_active`], naming why the job was
641/// judged active when it is.
642pub(crate) fn observe_job_active_reason(home: &Path, job: &Job) -> Result<Option<ActiveReason>> {
643    match job.status {
644        Status::Starting => Ok(Some(ActiveReason::UnfencedStartup)),
645        Status::Running => {
646            let lock_path = job_dir(home, &job.id)?.join("live.lock");
647            let file = match open_record(&lock_path) {
648                Ok(file) => file,
649                Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
650                    if confirmed_terminal(home, &job.id) {
651                        return Ok(None);
652                    }
653                    return Ok(Some(ActiveReason::MissingLiveLease));
654                }
655                Err(error) => {
656                    if confirmed_terminal_retained(home, &job.id) {
657                        return Ok(None);
658                    }
659                    return Err(error)
660                        .with_context(|| format!("open worker lease {}", lock_path.display()));
661                }
662            };
663            match crate::pr_head::try_lock_file(&file) {
664                Ok(()) => {
665                    drop(Lease { _file: file });
666                    Ok(None)
667                }
668                Err(error)
669                    if error.kind() == std::io::ErrorKind::WouldBlock
670                        || cfg!(windows) && error.raw_os_error() == Some(33) =>
671                {
672                    Ok(Some(ActiveReason::LiveLeaseHeld))
673                }
674                Err(error) => {
675                    if confirmed_terminal_retained(home, &job.id) {
676                        return Ok(None);
677                    }
678                    Err(error)
679                        .with_context(|| format!("probe worker lease {}", lock_path.display()))
680                }
681            }
682        }
683        Status::Finished | Status::Failed => Ok(None),
684    }
685}
686
687fn control_path(home: &Path, key: &str) -> PathBuf {
688    root(home)
689        .join("controls")
690        .join(format!("{}.json", digest(key.as_bytes())))
691}
692
693/// Persist a stop or park request; the operation's handler consumes it safely.
694pub fn request(home: &Path, key: &str, control: Control) -> Result<()> {
695    let _store = store_lock(home)?;
696    save(&control_path(home, key), &control)
697}
698
699/// Read the latest durable owner request for a logical operation.
700pub fn control(home: &Path, key: &str) -> Result<Option<Control>> {
701    let path = control_path(home, key);
702    match open_record(&path) {
703        Ok(file) => serde_json::from_reader(file)
704            .map(Some)
705            .with_context(|| format!("decode worker control {}", path.display())),
706        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
707        Err(e) => Err(e).with_context(|| format!("open worker control {}", path.display())),
708    }
709}
710
711fn clear_control_locked(home: &Path, key: &str) -> Result<()> {
712    let path = control_path(home, key);
713    match std::fs::remove_file(&path) {
714        Ok(()) => sync_dir(&root(home).join("controls")),
715        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
716        Err(e) => Err(e).with_context(|| format!("remove worker control {}", path.display())),
717    }
718}
719
720/// Clear controls at an explicitly owned new singleton invocation boundary.
721pub fn clear_control(home: &Path, key: &str) -> Result<()> {
722    let _store = store_lock(home)?;
723    clear_control_locked(home, key)
724}
725
726/// Resolve a retained executable strictly by its content identity.
727pub fn executable(home: &Path, generation: &str) -> Result<PathBuf> {
728    if generation.len() != 64 || !generation.bytes().all(|b| b.is_ascii_hexdigit()) {
729        bail!("invalid worker generation");
730    }
731    let path = root(home)
732        .join("generations")
733        .join(generation)
734        .join(if cfg!(windows) { "magi.exe" } else { "magi" });
735    if !path.is_file() {
736        bail!("worker generation {generation} is unavailable");
737    }
738    Ok(path)
739}
740
741/// Resolve helper invocations to this worker's started executable, not a newly
742/// installed binary. Outside a worker, pin the caller's current executable.
743pub fn helper_executable(home: &Path) -> Result<PathBuf> {
744    if let Some(generation) = std::env::var_os("MAGI_WORKER_GENERATION") {
745        return executable(
746            home,
747            generation
748                .to_str()
749                .context("invalid generation environment")?,
750        );
751    }
752    Ok(pin_current(home)?.executable)
753}
754
755/// Remember the installed executable pathname before an updater replaces it.
756/// A web process calls this at startup so Linux's deleted-executable marker or
757/// Windows's backup rename cannot redirect successor workers to the old binary.
758pub fn remember_current_executable() -> Result<()> {
759    if INSTALLED_EXECUTABLE.get().is_some() {
760        return Ok(());
761    }
762    let path = std::env::current_exe()?.canonicalize()?;
763    let _ = INSTALLED_EXECUTABLE.set(path);
764    Ok(())
765}
766
767static INSTALLED_EXECUTABLE: OnceLock<PathBuf> = OnceLock::new();
768
769/// Copy and SHA-256 address the executable. MAGI_WORKER_EXE is an explicit
770/// embedding/test override; it is never an in-process execution fallback.
771pub fn pin_current(home: &Path) -> Result<Generation> {
772    let source = match std::env::var_os("MAGI_WORKER_EXE") {
773        Some(path) => PathBuf::from(path),
774        None => match INSTALLED_EXECUTABLE.get() {
775            Some(path) => path.clone(),
776            None => std::env::current_exe()?,
777        },
778    };
779    let source = source.canonicalize().context("resolve worker executable")?;
780    // A worker already runs the immutable copy. Do not copy/hash a large binary
781    // again for every finite maintenance invocation in the same generation.
782    if let Some(directory) = source.parent() {
783        if directory.parent() == Some(root(home).join("generations").as_path()) {
784            if let Some(id) = directory.file_name().and_then(|name| name.to_str()) {
785                if id.len() == 64
786                    && id.bytes().all(|b| b.is_ascii_hexdigit())
787                    && executable(home, id)?.canonicalize()? == source
788                {
789                    return Ok(Generation {
790                        id: id.to_owned(),
791                        executable: source,
792                    });
793                }
794            }
795        }
796    }
797    let stamp = source_stamp(&source)?;
798    let mut cache = PIN_CACHE
799        .lock()
800        .map_err(|_| anyhow::anyhow!("worker generation cache poisoned"))?;
801    if let Some(entry) = cache.iter().find(|entry| {
802        entry.home == home
803            && entry.source == source
804            && entry.stamp == stamp
805            && entry.generation.executable.is_file()
806    }) {
807        return Ok(entry.generation.clone());
808    }
809    let generation = pin_source(home, &source)?;
810    if source_stamp(&source)? != stamp {
811        bail!("worker executable changed while being pinned; retry");
812    }
813    if cache.len() >= 8 {
814        cache.remove(0);
815    }
816    cache.push(CachedGeneration {
817        home: home.to_path_buf(),
818        source,
819        stamp,
820        generation: generation.clone(),
821    });
822    Ok(generation)
823}
824
825type SourceStamp = (u64, Option<SystemTime>, Option<SystemTime>, u64, u64);
826struct CachedGeneration {
827    home: PathBuf,
828    source: PathBuf,
829    stamp: SourceStamp,
830    generation: Generation,
831}
832static PIN_CACHE: LazyLock<Mutex<Vec<CachedGeneration>>> = LazyLock::new(|| Mutex::new(Vec::new()));
833
834fn source_stamp(path: &Path) -> Result<SourceStamp> {
835    let metadata = std::fs::metadata(path)?;
836    #[cfg(unix)]
837    let identity = {
838        use std::os::unix::fs::MetadataExt;
839        (metadata.dev(), metadata.ino())
840    };
841    #[cfg(not(unix))]
842    let identity = (0, 0);
843    Ok((
844        metadata.len(),
845        metadata.modified().ok(),
846        metadata.created().ok(),
847        identity.0,
848        identity.1,
849    ))
850}
851
852fn pin_source(home: &Path, source: &Path) -> Result<Generation> {
853    let generations = root(home).join("generations");
854    std::fs::create_dir_all(&generations)?;
855    let staging = generations.join(format!(".new-{}", nonce()));
856    let mut staging_lease = {
857        let _store = store_lock(home)?;
858        // Only unpublished copies are reclaimed, never executable generations.
859        for entry in std::fs::read_dir(&generations)? {
860            let entry = entry?;
861            if entry.file_type()?.is_dir()
862                && entry.file_name().to_string_lossy().starts_with(".new-")
863            {
864                if let Some(lease) = try_lock(&entry.path().join("pin.lock"))? {
865                    drop(lease);
866                    remove_staging(&entry.path())?;
867                }
868            }
869        }
870        std::fs::create_dir(&staging)?;
871        Some(try_lock(&staging.join("pin.lock"))?.context("generation staging lease unavailable")?)
872    };
873    let temp = staging.join(if cfg!(windows) { "magi.exe" } else { "magi" });
874    let result = (|| -> Result<Generation> {
875        let mut input = File::open(source)?;
876        let mut output = OpenOptions::new()
877            .create_new(true)
878            .write(true)
879            .open(&temp)?;
880        let mut hash = Sha256::new();
881        let mut buffer = [0u8; 65536];
882        loop {
883            let n = input.read(&mut buffer)?;
884            if n == 0 {
885                break;
886            }
887            hash.update(&buffer[..n]);
888            output.write_all(&buffer[..n])?;
889        }
890        let id = hex_digest(hash);
891        let mut permissions = input.metadata()?.permissions();
892        permissions.set_readonly(true);
893        output.set_permissions(permissions)?;
894        output.sync_all()?;
895        drop(output);
896        sync_dir(&staging)?;
897        let target = generations.join(&id);
898        // The store lock serializes publication with retention and other pins.
899        let _store = store_lock(home)?;
900        drop(staging_lease.take());
901        std::fs::remove_file(staging.join("pin.lock"))?;
902        if target.exists() {
903            let existing = target.join(temp.file_name().context("binary filename")?);
904            if hash_file(&existing)? != id {
905                bail!("immutable worker generation is corrupt: {id}");
906            }
907        } else {
908            std::fs::rename(&staging, &target)?;
909            sync_dir(&generations)?;
910        }
911        Ok(Generation {
912            executable: target.join(temp.file_name().context("binary filename")?),
913            id,
914        })
915    })();
916    let _store = store_lock(home)?;
917    drop(staging_lease);
918    if staging.exists() {
919        remove_staging(&staging)?;
920    }
921    result
922}
923
924fn remove_staging(staging: &Path) -> Result<()> {
925    #[cfg(windows)]
926    {
927        use std::os::windows::{ffi::OsStrExt, fs::MetadataExt};
928        #[link(name = "kernel32")]
929        unsafe extern "system" {
930            fn SetFileAttributesW(path: *const u16, attributes: u32) -> i32;
931        }
932        const READONLY: u32 = 0x1;
933        for entry in std::fs::read_dir(staging)? {
934            let entry = entry?;
935            let attributes = entry.metadata()?.file_attributes();
936            if attributes & READONLY != 0 {
937                let path: Vec<u16> = entry.path().as_os_str().encode_wide().chain([0]).collect();
938                // SAFETY: path is a live, NUL-terminated UTF-16 buffer. Clear
939                // only the Windows readonly attribute, preserving other bits.
940                if unsafe { SetFileAttributesW(path.as_ptr(), attributes & !READONLY) } == 0 {
941                    return Err(std::io::Error::last_os_error())
942                        .context("clear staging readonly attribute");
943                }
944            }
945        }
946    }
947    Ok(std::fs::remove_dir_all(staging)?)
948}
949
950fn hash_file(path: &Path) -> Result<String> {
951    let mut file = File::open(path)?;
952    let mut hash = Sha256::new();
953    let mut buffer = [0u8; 65536];
954    loop {
955        let n = file.read(&mut buffer)?;
956        if n == 0 {
957            break;
958        }
959        hash.update(&buffer[..n]);
960    }
961    Ok(hex_digest(hash))
962}
963
964fn reserve(
965    home: &Path,
966    generation: &Generation,
967    kind: &str,
968    key: &str,
969    payload: serde_json::Value,
970) -> Result<(Job, bool)> {
971    if kind.is_empty() || key.is_empty() {
972        bail!("worker kind and operation key must be nonempty");
973    }
974    let _store = store_lock(home)?;
975    let mut jobs = records(home)?;
976    reconcile(home, &mut jobs)?;
977    if let Some(job) = jobs
978        .iter()
979        .find(|job| job.key == key && matches!(job.status, Status::Starting | Status::Running))
980    {
981        if job.kind != kind || job.payload != payload {
982            bail!("worker operation key {key} is already reserved for a different request");
983        }
984        return Ok((job.clone(), false));
985    }
986    let id = nonce();
987    let job = Job {
988        id: id.clone(),
989        sequence: next_sequence(home)?,
990        kind: kind.to_owned(),
991        key: key.to_owned(),
992        payload,
993        generation: generation.id.clone(),
994        version: None,
995        status: Status::Starting,
996        result: None,
997        pid: None,
998        created_at: now(),
999        finished_at: None,
1000    };
1001    let jobs_dir = root(home).join("jobs");
1002    let staging = jobs_dir.join(format!(".new-{id}"));
1003    std::fs::create_dir(&staging)
1004        .with_context(|| format!("create worker reservation staging {}", staging.display()))?;
1005    save(&staging.join("job.json"), &job)?;
1006    clear_control_locked(home, key)?;
1007    std::fs::rename(&staging, job_dir(home, &id)?)
1008        .with_context(|| format!("publish worker {id} reservation from {}", staging.display()))?;
1009    sync_dir(&jobs_dir)?;
1010    Ok((job, true))
1011}
1012
1013pub(crate) fn running_fixture(
1014    home: &Path,
1015    key: &str,
1016    payload: serde_json::Value,
1017) -> Result<(Job, Lease)> {
1018    let _store = store_lock(home)?;
1019    let id = nonce();
1020    let dir = job_dir(home, &id)?;
1021    std::fs::create_dir_all(&dir)?;
1022    let result = (|| {
1023        let lease = try_lock(&dir.join("live.lock"))?.context("fixture lease unavailable")?;
1024        let job = Job {
1025            id,
1026            sequence: next_sequence(home)?,
1027            kind: "task".into(),
1028            key: key.into(),
1029            payload,
1030            generation: "a".repeat(64),
1031            version: None,
1032            status: Status::Running,
1033            result: None,
1034            pid: Some(std::process::id()),
1035            created_at: now(),
1036            finished_at: None,
1037        };
1038        save(&dir.join("job.json"), &job)?;
1039        Ok((job, lease))
1040    })();
1041    if result.is_err() {
1042        let _ = std::fs::remove_dir_all(&dir);
1043    }
1044    result
1045}
1046
1047fn prune_results(home: &Path) -> Result<()> {
1048    let results = root(home).join("results");
1049    std::fs::create_dir_all(&results)?;
1050    let mut entries = Vec::new();
1051    for entry in std::fs::read_dir(&results)? {
1052        let entry = entry?;
1053        if entry.file_type()?.is_dir() {
1054            // Directory mtime changes when the terminal job.json is published.
1055            // Retention needs no deserialization of old handler/config payloads.
1056            entries.push((entry.metadata()?.modified()?, entry.path()));
1057        }
1058    }
1059    entries.sort_unstable_by_key(|(modified, _)| std::cmp::Reverse(*modified));
1060    for (_, dir) in entries.into_iter().skip(RETAIN_FINISHED) {
1061        if let Some(lease) = try_lock(&dir.join("live.lock"))? {
1062            drop(lease);
1063            std::fs::remove_dir_all(dir)?;
1064        }
1065    }
1066    sync_dir(&results)
1067}
1068
1069fn detached_command(home: &Path, job: &Job, generation: &Generation) -> Result<Command> {
1070    // Open before exec so argument parsing, startup panics, and task progress
1071    // remain diagnosable even before the child can publish its acknowledgement.
1072    // Archiving/pruning the reservation also archives/prunes its log.
1073    let log_path = job_dir(home, &job.id)?.join("worker.log");
1074    let log = OpenOptions::new()
1075        .create(true)
1076        .append(true)
1077        .open(&log_path)
1078        .with_context(|| format!("open worker startup log {}", log_path.display()))?;
1079    let stderr = log
1080        .try_clone()
1081        .with_context(|| format!("clone worker startup log {}", log_path.display()))?;
1082    let mut command = Command::new(&generation.executable);
1083    command
1084        .arg("__worker")
1085        .arg("--home")
1086        .arg(home)
1087        .arg(&job.id)
1088        .env("MAGI_HOME", home)
1089        .env("MAGI_WORKER_HOME", home)
1090        .env("MAGI_WORKER_ID", &job.id)
1091        .env("MAGI_WORKER_GENERATION", &generation.id)
1092        .env("MAGI_WORKER_EXE", &generation.executable)
1093        .env_remove("MAGI_RUN")
1094        .env_remove("MAGI_NODE")
1095        .env_remove("MAGI_SEAT")
1096        .stdin(Stdio::null())
1097        .stdout(Stdio::from(log))
1098        .stderr(Stdio::from(stderr));
1099    crate::chat_control::bridge::clear_std_environment(&mut command);
1100    let mut paths = vec![
1101        generation
1102            .executable
1103            .parent()
1104            .context("generation directory")?
1105            .to_path_buf(),
1106    ];
1107    if let Some(path) = std::env::var_os("PATH") {
1108        paths.extend(std::env::split_paths(&path));
1109    }
1110    command.env("PATH", std::env::join_paths(paths)?);
1111    #[cfg(unix)]
1112    {
1113        use std::os::unix::process::CommandExt;
1114        unsafe {
1115            command.pre_exec(|| {
1116                if libc::setsid() < 0 {
1117                    return Err(std::io::Error::last_os_error());
1118                }
1119                // A scheduler's Ctrl-C handling must not be inherited as an
1120                // ignored shutdown signal by its independent worker session.
1121                libc::signal(libc::SIGINT, libc::SIG_DFL);
1122                libc::signal(libc::SIGTERM, libc::SIG_DFL);
1123                Ok(())
1124            });
1125        }
1126    }
1127    #[cfg(windows)]
1128    {
1129        use std::os::windows::process::CommandExt;
1130        detached_standard_handles().context("exclude caller pipes from detached worker")?;
1131        command.creation_flags(
1132            crate::chat_watch::windows::detached_flags()
1133                .context("prepare independent Windows worker")?,
1134        );
1135    }
1136    Ok(command)
1137}
1138
1139#[cfg(windows)]
1140fn detached_standard_handles() -> std::io::Result<()> {
1141    use std::ffi::c_void;
1142    #[link(name = "kernel32")]
1143    unsafe extern "system" {
1144        fn GetStdHandle(kind: u32) -> *mut c_void;
1145        fn SetHandleInformation(handle: *mut c_void, mask: u32, flags: u32) -> i32;
1146    }
1147    // Explicit Stdio entries are duplicated by Command for the child. The
1148    // caller's original inherited handles must not also leak into a detached
1149    // process: that keeps an external caller's stdout pipe open after exit.
1150    // Leave them non-inheritable; subsequent ordinary Command launches still
1151    // inherit their explicitly selected standard streams.
1152    for kind in [-10_i32, -11, -12] {
1153        let handle = unsafe { GetStdHandle(kind as u32) };
1154        if handle.is_null() || handle as isize == -1 {
1155            continue;
1156        }
1157        if unsafe { SetHandleInformation(handle, 1, 0) } == 0 {
1158            let error = std::io::Error::last_os_error();
1159            // Console pseudo handles have no inheritable kernel handle flag.
1160            if error.raw_os_error() != Some(6) {
1161                return Err(error);
1162            }
1163        }
1164    }
1165    Ok(())
1166}
1167
1168/// A concurrent fork can inherit the generation's writable file descriptor.
1169/// Even after pinning closes its copy, Unix exec can return ETXTBSY until the
1170/// other child closes its copy on exec or exit. Retry only that spawn error.
1171async fn spawn_generation(
1172    mut spawn: impl FnMut() -> std::io::Result<Child>,
1173) -> std::io::Result<Child> {
1174    for delay_ms in [10, 20, 40, 80] {
1175        match spawn() {
1176            Err(error) if error.kind() == std::io::ErrorKind::ExecutableFileBusy => {
1177                tokio::time::sleep(Duration::from_millis(delay_ms)).await;
1178            }
1179            result => return result,
1180        }
1181    }
1182    spawn()
1183}
1184
1185/// Reserve an exclusive operation and detach its immutable executable. Returns
1186/// after acknowledgement; a timeout preserves the reservation and never kills
1187/// the child or silently executes in the caller. Repeated identical requests
1188/// attach to the existing reservation rather than dispatching twice.
1189pub async fn spawn(home: &Path, kind: &str, key: &str, payload: serde_json::Value) -> Result<Job> {
1190    std::fs::create_dir_all(home).map_err(not_started_error)?;
1191    let home = home
1192        .canonicalize()
1193        .context("resolve worker home")
1194        .map_err(not_started_error)?;
1195    let pin_home = home.clone();
1196    let generation = tokio::task::spawn_blocking(move || pin_current(&pin_home))
1197        .await
1198        .map_err(not_started_error)?
1199        .map_err(not_started_error)?;
1200    let (job, fresh) = reserve(&home, &generation, kind, key, payload)?;
1201    if fresh {
1202        let child = match detached_command(&home, &job, &generation) {
1203            Ok(mut command) => spawn_generation(|| command.spawn())
1204                .await
1205                .map_err(Into::into),
1206            Err(error) => Err(error),
1207        };
1208        match child {
1209            Ok(mut child) => {
1210                // std::process::Child has no kill-on-drop. The reaper is only
1211                // bookkeeping; runtime or parent exit cannot terminate a worker.
1212                std::thread::spawn(move || {
1213                    let _ = child.wait();
1214                });
1215            }
1216            Err(error) => {
1217                let _store = store_lock(&home)?;
1218                let mut job = get(&home, &job.id)?;
1219                if job.status == Status::Starting {
1220                    if let Some(_lease) = try_lock(&job_dir(&home, &job.id)?.join("live.lock"))? {
1221                        terminal(
1222                            &home,
1223                            &mut job,
1224                            Status::Failed,
1225                            format!("worker spawn failed: {error}"),
1226                        )?;
1227                        return Err(not_started_error(error));
1228                    }
1229                }
1230                return Err(error);
1231            }
1232        }
1233    }
1234    let deadline = tokio::time::Instant::now() + Duration::from_secs(10);
1235    loop {
1236        let current = get(&home, &job.id)?;
1237        match current.status {
1238            Status::Running | Status::Finished => return Ok(current),
1239            Status::Failed => bail!(
1240                "worker {} failed: {}",
1241                current.id,
1242                current.result.as_deref().unwrap_or("unknown failure")
1243            ),
1244            Status::Starting => {}
1245        }
1246        if tokio::time::Instant::now() >= deadline {
1247            return Err(StartupUnacknowledged { id: job.id }.into());
1248        }
1249        tokio::time::sleep(Duration::from_millis(20)).await;
1250    }
1251}
1252
1253/// Hidden detached entrypoint. The lease is acquired before acknowledgement and
1254/// is retained through handler result persistence. Only the recorded generation
1255/// can acknowledge a reservation, even if a newer CLI is accidentally invoked.
1256pub async fn run(home: &Path, id: &str) -> Result<()> {
1257    let dir = job_dir(home, id)?;
1258    let (job, _lease) = {
1259        let _store = store_lock(home)?;
1260        let mut job = get(home, id)?;
1261        if job.status != Status::Starting {
1262            bail!("worker reservation is no longer startable");
1263        }
1264        let lease =
1265            try_lock(&dir.join("live.lock"))?.context("worker execution lease is already held")?;
1266        let current = std::env::current_exe()
1267            .context("locate running worker executable")?
1268            .canonicalize()
1269            .context("resolve running worker executable")?;
1270        let expected = executable(home, &job.generation)?
1271            .canonicalize()
1272            .with_context(|| {
1273                format!("resolve worker {id} reserved generation {}", job.generation)
1274            })?;
1275        if current != expected {
1276            bail!("worker must execute its reserved immutable generation");
1277        }
1278        job.pid = Some(std::process::id());
1279        job.version = Some(env!("CARGO_PKG_VERSION").to_owned());
1280        job.status = Status::Running;
1281        save(&dir.join("job.json"), &job)
1282            .with_context(|| format!("acknowledge worker {id} startup"))?;
1283        (job, lease)
1284    };
1285    let result = match job.kind.as_str() {
1286        "task" => crate::daemon::run_task_worker(home, job.payload.clone()).await,
1287        "scheduler" => crate::daemon::run_scheduler_worker(home, job.payload.clone()).await,
1288        "chat" => crate::chat_worker::run_turn_worker(home, job.payload.clone()).await,
1289        "service" => crate::consult::run_service_worker(home, job.payload.clone()).await,
1290        "daemon-service" => crate::daemon::run_service_worker(home, job.payload.clone()).await,
1291        "deputy" => crate::deputy::run_worker(home, job.payload.clone()).await,
1292        kind => Err(anyhow::anyhow!("unknown worker kind {kind}")),
1293    };
1294    let _store = store_lock(home)?;
1295    let mut current = get(home, id)?;
1296    match &result {
1297        Ok(()) => terminal(home, &mut current, Status::Finished, "completed".to_owned())?,
1298        Err(error) => terminal(home, &mut current, Status::Failed, format!("{error:#}"))?,
1299    }
1300    result
1301}
1302
1303fn hex_digest(hash: Sha256) -> String {
1304    // sha2 0.11's `finalize` returns a `hybrid_array::Array`, which no
1305    // longer implements `LowerHex`, so format the bytes individually.
1306    hash.finalize()
1307        .iter()
1308        .map(|byte| format!("{byte:02x}"))
1309        .collect()
1310}
1311fn digest(bytes: &[u8]) -> String {
1312    let mut hash = Sha256::new();
1313    hash.update(bytes);
1314    hex_digest(hash)
1315}
1316
1317#[cfg(test)]
1318mod tests {
1319    use super::*;
1320
1321    #[test]
1322    fn observing_an_unused_store_requires_no_writes() {
1323        let home = tempfile::tempdir().unwrap();
1324        assert!(observe_active(home.path()).unwrap().is_empty());
1325        assert!(!home.path().join("workers").exists());
1326    }
1327
1328    #[test]
1329    fn observing_execution_probes_the_lease_without_rewriting_history() {
1330        let home = tempfile::tempdir().unwrap();
1331        let mut job = reservation(home.path(), "task:observer");
1332        let directory = job_dir(home.path(), &job.id).unwrap();
1333        let live_path = directory.join("live.lock");
1334        let lease = try_lock(&live_path).unwrap().unwrap();
1335        job.status = Status::Running;
1336        save(&directory.join("job.json"), &job).unwrap();
1337        #[cfg(unix)]
1338        {
1339            use std::os::unix::fs::PermissionsExt as _;
1340            std::fs::set_permissions(&live_path, std::fs::Permissions::from_mode(0o444)).unwrap();
1341        }
1342        let before = std::fs::read(directory.join("job.json")).unwrap();
1343        let observed = observe_active(home.path()).unwrap();
1344        assert_eq!(observed.len(), 1);
1345        assert_eq!(observed[0].id, job.id);
1346        drop(lease);
1347        assert!(observe_active(home.path()).unwrap().is_empty());
1348        assert_eq!(std::fs::read(directory.join("job.json")).unwrap(), before);
1349        assert_eq!(get(home.path(), &job.id).unwrap().status, Status::Running);
1350    }
1351    fn generation() -> Generation {
1352        Generation {
1353            id: "a".repeat(64),
1354            executable: PathBuf::from("unused"),
1355        }
1356    }
1357    fn reservation(home: &Path, key: &str) -> Job {
1358        reserve(
1359            home,
1360            &generation(),
1361            "task",
1362            key,
1363            serde_json::json!({"task":"example"}),
1364        )
1365        .unwrap()
1366        .0
1367    }
1368
1369    #[test]
1370    fn reservation_deduplicates_identical_keys_and_rejects_collision() {
1371        let home = tempfile::tempdir().unwrap();
1372        let first = reservation(home.path(), "task:one");
1373        assert_eq!(first.id, reservation(home.path(), "task:one").id);
1374        assert!(
1375            reserve(
1376                home.path(),
1377                &generation(),
1378                "chat",
1379                "task:one",
1380                serde_json::Value::Null
1381            )
1382            .is_err()
1383        );
1384        assert_ne!(first.id, reservation(home.path(), "task:two").id);
1385    }
1386
1387    #[test]
1388    fn reservation_order_is_durable_and_corruption_never_resets_it() {
1389        let home = tempfile::tempdir().unwrap();
1390        let first = reservation(home.path(), "chat:first");
1391        assert_eq!(
1392            first.sequence,
1393            reservation(home.path(), "chat:first").sequence
1394        );
1395        let second = reservation(home.path(), "chat:second");
1396        assert!(second.sequence > first.sequence);
1397        let encoded = serde_json::to_vec(&second).unwrap();
1398        assert_eq!(
1399            serde_json::from_slice::<Job>(&encoded).unwrap().sequence,
1400            second.sequence
1401        );
1402        let mut legacy = serde_json::to_value(&first).unwrap();
1403        legacy.as_object_mut().unwrap().remove("sequence");
1404        assert_eq!(serde_json::from_value::<Job>(legacy).unwrap().sequence, 0);
1405        std::fs::write(root(home.path()).join("sequence.json"), b"broken").unwrap();
1406        assert!(
1407            reserve(
1408                home.path(),
1409                &generation(),
1410                "chat",
1411                "chat:third",
1412                serde_json::Value::Null
1413            )
1414            .is_err()
1415        );
1416    }
1417
1418    #[tokio::test]
1419    async fn pre_reservation_failure_is_proven_without_history_absence_guesses() {
1420        let home = tempfile::tempdir().unwrap();
1421        let blocked = home.path().join("not-a-directory");
1422        std::fs::write(&blocked, b"file").unwrap();
1423        let error = spawn(&blocked, "chat", "fresh:chat", serde_json::Value::Null)
1424            .await
1425            .unwrap_err();
1426        assert!(not_started(&error));
1427        assert!(not_started(&error.context("publish recorded turn")));
1428        assert!(!not_started(&anyhow::anyhow!(
1429            "startup acknowledgement timed out"
1430        )));
1431        assert!(!blocked.join("workers").exists());
1432    }
1433
1434    #[test]
1435    fn failed_os_spawn_is_fenced_and_proven_not_started() {
1436        let home = tempfile::tempdir().unwrap();
1437        let executable = home.path().join("invalid-executable");
1438        std::fs::write(&executable, b"not an executable binary").unwrap();
1439        let output = Command::new(std::env::current_exe().unwrap())
1440            .args([
1441                "--exact",
1442                "worker::tests::unstarted_spawn_helper",
1443                "--ignored",
1444                "--nocapture",
1445            ])
1446            .env("MAGI_WORKER_EXE", &executable)
1447            .env("MAGI_SPAWN_FAILURE_HOME", home.path())
1448            .output()
1449            .unwrap();
1450        assert!(
1451            output.status.success(),
1452            "{}\n{}",
1453            String::from_utf8_lossy(&output.stdout),
1454            String::from_utf8_lossy(&output.stderr)
1455        );
1456    }
1457
1458    #[tokio::test]
1459    #[ignore = "isolated environment for the failed OS spawn test"]
1460    async fn unstarted_spawn_helper() {
1461        let home = PathBuf::from(std::env::var_os("MAGI_SPAWN_FAILURE_HOME").unwrap());
1462        let error = spawn(&home, "chat", "fresh:failed-exec", serde_json::Value::Null)
1463            .await
1464            .unwrap_err();
1465        assert!(not_started(&error));
1466        let entry = std::fs::read_dir(root(&home).join("jobs"))
1467            .unwrap()
1468            .next()
1469            .unwrap()
1470            .unwrap();
1471        let id = entry.file_name().to_str().unwrap().to_owned();
1472        let job = get(&home, &id).unwrap();
1473        assert_eq!(job.status, Status::Failed);
1474        assert_eq!(job.pid, None);
1475        assert!(active(&home).unwrap().is_empty());
1476        assert_eq!(get(&home, &id).unwrap().status, Status::Failed);
1477    }
1478
1479    #[test]
1480    fn unresolved_startup_remains_reserved_and_live_lease_never_expires() {
1481        let home = tempfile::tempdir().unwrap();
1482        let mut job = reservation(home.path(), "task:one");
1483        assert_eq!(active(home.path()).unwrap().len(), 1);
1484        job.created_at = 0;
1485        save(
1486            &job_dir(home.path(), &job.id).unwrap().join("job.json"),
1487            &job,
1488        )
1489        .unwrap();
1490        let lease = try_lock(&job_dir(home.path(), &job.id).unwrap().join("live.lock"))
1491            .unwrap()
1492            .unwrap();
1493        assert_eq!(active(home.path()).unwrap().len(), 1);
1494        drop(lease);
1495        assert!(active(home.path()).unwrap().is_empty());
1496        assert_eq!(get(home.path(), &job.id).unwrap().status, Status::Failed);
1497    }
1498
1499    #[tokio::test]
1500    async fn cancelled_startup_cannot_execute_late() {
1501        let home = tempfile::tempdir().unwrap();
1502        let mut job = reservation(home.path(), "task:one");
1503        job.created_at = 0;
1504        save(
1505            &job_dir(home.path(), &job.id).unwrap().join("job.json"),
1506            &job,
1507        )
1508        .unwrap();
1509        assert!(active(home.path()).unwrap().is_empty());
1510        assert!(
1511            run(home.path(), &job.id)
1512                .await
1513                .unwrap_err()
1514                .to_string()
1515                .contains("no longer startable")
1516        );
1517    }
1518
1519    #[test]
1520    fn running_without_lease_fails_regardless_of_pid() {
1521        let home = tempfile::tempdir().unwrap();
1522        let mut job = reservation(home.path(), "task:one");
1523        job.status = Status::Running;
1524        job.pid = Some(std::process::id());
1525        save(
1526            &job_dir(home.path(), &job.id).unwrap().join("job.json"),
1527            &job,
1528        )
1529        .unwrap();
1530        assert!(active(home.path()).unwrap().is_empty());
1531        assert_eq!(get(home.path(), &job.id).unwrap().status, Status::Failed);
1532    }
1533
1534    #[test]
1535    fn controls_survive_reopen_and_reset_at_new_invocation() {
1536        let home = tempfile::tempdir().unwrap();
1537        request(home.path(), "task:one", Control::Park).unwrap();
1538        assert_eq!(
1539            control(home.path(), "task:one").unwrap(),
1540            Some(Control::Park)
1541        );
1542        reservation(home.path(), "task:one");
1543        assert_eq!(control(home.path(), "task:one").unwrap(), None);
1544        request(home.path(), "task:one", Control::Stop).unwrap();
1545        assert_eq!(
1546            control(home.path(), "task:one").unwrap(),
1547            Some(Control::Stop)
1548        );
1549        assert_eq!(control(home.path(), "task:other").unwrap(), None);
1550    }
1551
1552    #[test]
1553    fn singleton_locks_release_without_pid_cleanup() {
1554        let home = tempfile::tempdir().unwrap();
1555        let lease = try_lease(home.path(), "scheduler").unwrap().unwrap();
1556        assert!(try_lease(home.path(), "scheduler").unwrap().is_none());
1557        assert!(try_lease(home.path(), "other").unwrap().is_some());
1558        drop(lease);
1559        assert!(try_lease(home.path(), "scheduler").unwrap().is_some());
1560    }
1561
1562    #[test]
1563    fn immutable_generation_keeps_old_content_after_source_replacement() {
1564        let home = tempfile::tempdir().unwrap();
1565        let source = home.path().join("source");
1566        std::fs::write(&source, b"old executable").unwrap();
1567        let old = pin_source(home.path(), &source).unwrap();
1568        std::fs::write(&source, b"new executable").unwrap();
1569        let new = pin_source(home.path(), &source).unwrap();
1570        assert_ne!(old.id, new.id);
1571        assert_eq!(
1572            std::fs::read(executable(home.path(), &old.id).unwrap()).unwrap(),
1573            b"old executable"
1574        );
1575        assert_eq!(std::fs::read(new.executable).unwrap(), b"new executable");
1576    }
1577
1578    #[tokio::test]
1579    async fn generation_spawn_does_not_retry_a_missing_executable() {
1580        let home = tempfile::tempdir().unwrap();
1581        let mut command = Command::new(home.path().join("missing-executable"));
1582        let mut attempts = 0;
1583        let error = spawn_generation(|| {
1584            attempts += 1;
1585            command.spawn()
1586        })
1587        .await
1588        .unwrap_err();
1589        assert_eq!(error.kind(), std::io::ErrorKind::NotFound);
1590        assert_eq!(attempts, 1);
1591    }
1592
1593    #[cfg(target_os = "linux")]
1594    fn busy_executable(dir: &Path) -> (Command, File) {
1595        use std::os::unix::fs::PermissionsExt;
1596
1597        let path = dir.join("busy-executable");
1598        std::fs::copy("/bin/sh", &path).unwrap();
1599        std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o700)).unwrap();
1600        let writer = OpenOptions::new().write(true).open(&path).unwrap();
1601        let mut command = Command::new(path);
1602        command.args(["-c", "exit 0"]);
1603        (command, writer)
1604    }
1605
1606    #[cfg(target_os = "linux")]
1607    #[tokio::test]
1608    async fn generation_spawn_retries_until_the_writer_closes() {
1609        let home = tempfile::tempdir().unwrap();
1610        let (mut command, writer) = busy_executable(home.path());
1611        let error = command.spawn().unwrap_err();
1612        assert_eq!(error.kind(), std::io::ErrorKind::ExecutableFileBusy);
1613
1614        let (release, requested) = std::sync::mpsc::channel();
1615        let closer = std::thread::spawn(move || {
1616            if requested.recv().is_ok() {
1617                std::thread::sleep(Duration::from_millis(20));
1618            }
1619            drop(writer);
1620        });
1621        let mut release = Some(release);
1622        let child = spawn_generation(|| {
1623            let result = command.spawn();
1624            if let Some(release) = release.take() {
1625                release.send(()).unwrap();
1626            }
1627            result
1628        })
1629        .await;
1630        closer.join().unwrap();
1631        assert!(child.unwrap().wait().unwrap().success());
1632    }
1633
1634    #[cfg(target_os = "linux")]
1635    #[tokio::test]
1636    async fn generation_spawn_stops_retrying_while_the_writer_remains_open() {
1637        let home = tempfile::tempdir().unwrap();
1638        let (mut command, _writer) = busy_executable(home.path());
1639        let mut attempts = 0;
1640        let error = spawn_generation(|| {
1641            attempts += 1;
1642            assert!(attempts <= 5, "busy generation exceeded its retry bound");
1643            command.spawn()
1644        })
1645        .await
1646        .unwrap_err();
1647        assert_eq!(error.kind(), std::io::ErrorKind::ExecutableFileBusy);
1648    }
1649
1650    #[tokio::test]
1651    async fn acknowledgement_records_own_version_and_handler_failure() {
1652        let home = tempfile::tempdir().unwrap();
1653        let generation = pin_source(home.path(), &std::env::current_exe().unwrap()).unwrap();
1654        let (job, _) = reserve(
1655            home.path(),
1656            &generation,
1657            "unknown-kind",
1658            "unknown:one",
1659            serde_json::Value::Null,
1660        )
1661        .unwrap();
1662        let invoke = || async {
1663            let mut command = Command::new(&generation.executable);
1664            command
1665                .args([
1666                    "--exact",
1667                    "worker::tests::pinned_entrypoint_helper",
1668                    "--ignored",
1669                    "--nocapture",
1670                ])
1671                .env("MAGI_WORKER_TEST_HOME", home.path())
1672                .env("MAGI_WORKER_TEST_ID", &job.id)
1673                .stdin(Stdio::null())
1674                .stdout(Stdio::piped())
1675                .stderr(Stdio::piped());
1676            let output = spawn_generation(|| command.spawn())
1677                .await
1678                .unwrap()
1679                .wait_with_output()
1680                .unwrap();
1681            assert!(
1682                output.status.success(),
1683                "{}",
1684                String::from_utf8_lossy(&output.stderr)
1685            );
1686        };
1687        invoke().await;
1688        let failed = get(home.path(), &job.id).unwrap();
1689        assert_eq!(failed.status, Status::Failed);
1690        assert_eq!(failed.version.as_deref(), Some(env!("CARGO_PKG_VERSION")));
1691        assert!(failed.result.unwrap().contains("unknown worker kind"));
1692        assert!(active(home.path()).unwrap().is_empty());
1693        assert!(!job_dir(home.path(), &job.id).unwrap().exists());
1694        invoke().await;
1695        assert!(!job_dir(home.path(), &job.id).unwrap().exists());
1696    }
1697
1698    #[tokio::test]
1699    #[ignore = "subprocess entrypoint for the immutable-generation startup test"]
1700    async fn pinned_entrypoint_helper() {
1701        let home = PathBuf::from(std::env::var_os("MAGI_WORKER_TEST_HOME").unwrap());
1702        let id = std::env::var("MAGI_WORKER_TEST_ID").unwrap();
1703        assert!(run(&home, &id).await.is_err());
1704    }
1705
1706    #[test]
1707    fn unfinished_staging_is_reclaimed_without_removing_generations() {
1708        let home = tempfile::tempdir().unwrap();
1709        let old = root(home.path()).join("generations").join(".new-abandoned");
1710        std::fs::create_dir_all(&old).unwrap();
1711        let partial = old.join("partial");
1712        std::fs::write(&partial, b"interrupted copy").unwrap();
1713        #[cfg(windows)]
1714        {
1715            let mut permissions = std::fs::metadata(&partial).unwrap().permissions();
1716            permissions.set_readonly(true);
1717            std::fs::set_permissions(&partial, permissions).unwrap();
1718        }
1719        let source = home.path().join("source");
1720        std::fs::write(&source, b"complete executable").unwrap();
1721        let generation = pin_source(home.path(), &source).unwrap();
1722        assert!(!old.exists());
1723        assert!(generation.executable.is_file());
1724    }
1725
1726    #[tokio::test]
1727    async fn unrelated_executable_cannot_acknowledge_or_consume_reservation() {
1728        let home = tempfile::tempdir().unwrap();
1729        let source = home.path().join("other-binary");
1730        std::fs::write(&source, b"different executable of the same Cargo version").unwrap();
1731        let generation = pin_source(home.path(), &source).unwrap();
1732        let (job, _) = reserve(
1733            home.path(),
1734            &generation,
1735            "task",
1736            "task:one",
1737            serde_json::Value::Null,
1738        )
1739        .unwrap();
1740        assert!(
1741            run(home.path(), &job.id)
1742                .await
1743                .unwrap_err()
1744                .to_string()
1745                .contains("immutable generation")
1746        );
1747        assert_eq!(get(home.path(), &job.id).unwrap().status, Status::Starting);
1748        assert_eq!(active(home.path()).unwrap().len(), 1);
1749    }
1750
1751    #[test]
1752    fn abandoned_record_staging_is_bounded_and_never_executes() {
1753        let home = tempfile::tempdir().unwrap();
1754        let staging = root(home.path()).join("jobs").join(".new-interrupted");
1755        std::fs::create_dir_all(&staging).unwrap();
1756        std::fs::write(staging.join("job.json"), b"partial json").unwrap();
1757        assert!(active(home.path()).unwrap().is_empty());
1758        assert!(!staging.exists());
1759    }
1760
1761    #[cfg(unix)]
1762    #[tokio::test]
1763    async fn detached_startup_preserves_stdout_and_stderr_in_record_log() {
1764        use std::os::unix::fs::PermissionsExt;
1765        let home = tempfile::tempdir().unwrap();
1766        let source = home.path().join("startup-diagnostic");
1767        std::fs::write(
1768            &source,
1769            b"#!/bin/sh\nprintf 'startup stdout\\n'\nprintf 'startup stderr\\n' >&2\nexit 7\n",
1770        )
1771        .unwrap();
1772        std::fs::set_permissions(&source, std::fs::Permissions::from_mode(0o755)).unwrap();
1773        let generation = pin_source(home.path(), &source).unwrap();
1774        let (mut job, _) = reserve(
1775            home.path(),
1776            &generation,
1777            "task",
1778            "task:log",
1779            serde_json::Value::Null,
1780        )
1781        .unwrap();
1782        let mut command = detached_command(home.path(), &job, &generation).unwrap();
1783        for key in ["MAGI_RUN", "MAGI_NODE", "MAGI_SEAT"]
1784            .into_iter()
1785            .chain(crate::chat_control::bridge::ENVIRONMENT.iter().copied())
1786        {
1787            assert!(
1788                command
1789                    .get_envs()
1790                    .any(|(name, value)| name == key && value.is_none())
1791            );
1792        }
1793        let mut child = spawn_generation(|| command.spawn()).await.unwrap();
1794        assert_eq!(child.wait().unwrap().code(), Some(7));
1795        let log = job_dir(home.path(), &job.id).unwrap().join("worker.log");
1796        let output = std::fs::read_to_string(log).unwrap();
1797        assert!(output.contains("startup stdout"));
1798        assert!(output.contains("startup stderr"));
1799        terminal(
1800            home.path(),
1801            &mut job,
1802            Status::Failed,
1803            "startup failed".into(),
1804        )
1805        .unwrap();
1806        assert!(active(home.path()).unwrap().is_empty());
1807        assert!(
1808            root(home.path())
1809                .join("results")
1810                .join(&job.id)
1811                .join("worker.log")
1812                .is_file()
1813        );
1814    }
1815
1816    #[cfg(windows)]
1817    #[test]
1818    fn record_publication_survives_readers_and_short_delete_sharing_handoffs() {
1819        use std::os::windows::fs::OpenOptionsExt as _;
1820
1821        let home = tempfile::tempdir().unwrap();
1822        let mut job = reservation(home.path(), "task:metadata-handoff");
1823        let directory = job_dir(home.path(), &job.id).unwrap();
1824        let path = directory.join("job.json");
1825        let lease = try_lock(&directory.join("live.lock")).unwrap().unwrap();
1826        let snapshot = File::open(&path).unwrap();
1827        // This reader allows ordinary IO but temporarily denies replacement.
1828        let reader = OpenOptions::new()
1829            .read(true)
1830            .share_mode(1 | 2) // FILE_SHARE_READ | FILE_SHARE_WRITE
1831            .open(&path)
1832            .unwrap();
1833        std::thread::scope(|scope| {
1834            scope.spawn(move || {
1835                std::thread::sleep(Duration::from_millis(15));
1836                drop(reader);
1837            });
1838            job.status = Status::Running;
1839            save(&path, &job).unwrap();
1840        });
1841        let original: Job = serde_json::from_reader(snapshot).unwrap();
1842        assert_eq!(original.status, Status::Starting);
1843        assert_eq!(get(home.path(), &job.id).unwrap().status, Status::Running);
1844        let running_snapshot = File::open(&path).unwrap();
1845        terminal(home.path(), &mut job, Status::Finished, "completed".into()).unwrap();
1846        assert_eq!(get(home.path(), &job.id).unwrap().status, Status::Finished);
1847        let previous: Job = serde_json::from_reader(running_snapshot).unwrap();
1848        assert_eq!(previous.status, Status::Running);
1849        drop(lease);
1850        assert!(active(home.path()).unwrap().is_empty());
1851    }
1852
1853    #[cfg(windows)]
1854    #[test]
1855    fn denied_record_publication_preserves_reservation_and_original_os_error() {
1856        use std::os::windows::fs::OpenOptionsExt as _;
1857
1858        let home = tempfile::tempdir().unwrap();
1859        let job = reservation(home.path(), "task:metadata-denied");
1860        let directory = job_dir(home.path(), &job.id).unwrap();
1861        let path = directory.join("job.json");
1862        let reader = OpenOptions::new()
1863            .read(true)
1864            .share_mode(1 | 2) // Deny deletion for the entire handoff budget.
1865            .open(&path)
1866            .unwrap();
1867        let mut acknowledged = job.clone();
1868        acknowledged.status = Status::Running;
1869        let error = save(&path, &acknowledged).unwrap_err();
1870        assert!(format!("{error:#}").contains("publish worker record"));
1871        let io = error.downcast_ref::<std::io::Error>().unwrap();
1872        assert!(matches!(io.raw_os_error(), Some(5 | 32)));
1873        assert_eq!(get(home.path(), &job.id).unwrap().status, Status::Starting);
1874        assert_eq!(reservation(home.path(), &job.key).id, job.id);
1875        assert!(std::fs::read_dir(&directory).unwrap().all(|entry| {
1876            !entry
1877                .unwrap()
1878                .file_name()
1879                .to_string_lossy()
1880                .starts_with(".pending-")
1881        }));
1882        drop(reader);
1883        save(&path, &acknowledged).unwrap();
1884        assert_eq!(get(home.path(), &job.id).unwrap().status, Status::Running);
1885    }
1886
1887    #[test]
1888    fn terminal_result_survives_open_execution_and_output_handles() {
1889        let home = tempfile::tempdir().unwrap();
1890        let mut job = reservation(home.path(), "task:open-handles");
1891        let directory = job_dir(home.path(), &job.id).unwrap();
1892        let lease = try_lock(&directory.join("live.lock")).unwrap().unwrap();
1893        let mut log = OpenOptions::new()
1894            .create(true)
1895            .append(true)
1896            .open(directory.join("worker.log"))
1897            .unwrap();
1898        writeln!(log, "before completion").unwrap();
1899        terminal(home.path(), &mut job, Status::Finished, "completed".into()).unwrap();
1900        assert_eq!(get(home.path(), &job.id).unwrap().status, Status::Finished);
1901        assert!(active(home.path()).unwrap().is_empty());
1902        assert!(
1903            directory.exists(),
1904            "a held execution lease must prevent retirement"
1905        );
1906        drop(lease);
1907        // Retirement may still be denied by the output handle on Windows.
1908        // Either way, querying active work and the durable result must succeed.
1909        assert!(active(home.path()).unwrap().is_empty());
1910        assert_eq!(get(home.path(), &job.id).unwrap().status, Status::Finished);
1911        writeln!(log, "after completion").unwrap();
1912        drop(log);
1913        assert!(active(home.path()).unwrap().is_empty());
1914        assert!(
1915            root(home.path())
1916                .join("results")
1917                .join(&job.id)
1918                .join("worker.log")
1919                .is_file()
1920        );
1921        assert!(!directory.exists());
1922    }
1923
1924    #[test]
1925    fn terminal_records_are_bounded_without_pruning_live_reservations() {
1926        let home = tempfile::tempdir().unwrap();
1927        let live = reservation(home.path(), "task:live");
1928        // Exercise retention, not hundreds of durable reservation publications.
1929        // Use a real terminal record as the on-disk template; reservation and
1930        // terminal publication have their own tests above.
1931        let mut finished = reservation(home.path(), "task:finished");
1932        terminal(home.path(), &mut finished, Status::Finished, "done".into()).unwrap();
1933        let template_dir = job_dir(home.path(), &finished.id).unwrap();
1934        std::fs::remove_dir_all(template_dir).unwrap();
1935        for i in 0..RETAIN_FINISHED + 3 {
1936            let mut job = finished.clone();
1937            job.id = format!("{i:032x}");
1938            job.key = format!("task:{i}");
1939            job.sequence += i as u64;
1940            let directory = job_dir(home.path(), &job.id).unwrap();
1941            std::fs::create_dir_all(&directory).unwrap();
1942            std::fs::write(
1943                directory.join("job.json"),
1944                serde_json::to_vec(&job).unwrap(),
1945            )
1946            .unwrap();
1947        }
1948        assert_eq!(
1949            std::fs::read_dir(root(home.path()).join("jobs"))
1950                .unwrap()
1951                .count(),
1952            RETAIN_FINISHED + 4
1953        );
1954        let jobs = records(home.path()).unwrap();
1955        assert_eq!(jobs.len(), 1);
1956        assert_eq!(
1957            std::fs::read_dir(root(home.path()).join("results"))
1958                .unwrap()
1959                .count(),
1960            RETAIN_FINISHED
1961        );
1962        assert!(jobs.iter().any(|job| job.id == live.id));
1963    }
1964
1965    #[test]
1966    fn observe_active_excludes_unarchived_terminal_jobs_and_preserves_unfenced_startup() {
1967        let home = tempfile::tempdir().unwrap();
1968        let starting = reservation(home.path(), "task:starting");
1969        let mut finished = reservation(home.path(), "task:finished");
1970        let mut failed = reservation(home.path(), "task:failed");
1971        terminal(home.path(), &mut finished, Status::Finished, "done".into()).unwrap();
1972        terminal(home.path(), &mut failed, Status::Failed, "boom".into()).unwrap();
1973        // Both terminal directories are still in jobs/ (unarchived).
1974        assert!(job_dir(home.path(), &finished.id).unwrap().exists());
1975        assert!(job_dir(home.path(), &failed.id).unwrap().exists());
1976
1977        let observed = observe_active_detailed(home.path()).unwrap();
1978        assert_eq!(observed.len(), 1);
1979        assert_eq!(observed[0].job.id, starting.id);
1980        assert_eq!(observed[0].reason, ActiveReason::UnfencedStartup);
1981        // Passive observation must never archive or mutate terminal records.
1982        assert!(job_dir(home.path(), &finished.id).unwrap().exists());
1983        assert!(job_dir(home.path(), &failed.id).unwrap().exists());
1984    }
1985
1986    #[test]
1987    fn observe_job_active_handles_archive_race_deterministically_and_protects_missing_live_lock() {
1988        let home = tempfile::tempdir().unwrap();
1989        let mut archived = reservation(home.path(), "task:archived-race");
1990        let running_snapshot = Job {
1991            status: Status::Running,
1992            pid: Some(std::process::id()),
1993            ..archived.clone()
1994        };
1995        terminal(home.path(), &mut archived, Status::Finished, "done".into()).unwrap();
1996        archive(home.path(), &archived).unwrap();
1997        assert!(!job_dir(home.path(), &archived.id).unwrap().exists());
1998        // Caller read Running right before archive moved the directory to results/.
1999        assert_eq!(
2000            observe_job_active_reason(home.path(), &running_snapshot).unwrap(),
2001            None
2002        );
2003
2004        // Contrast: a still-Running job in jobs/ whose live.lock is missing
2005        // must remain conservatively protected.
2006        let mut missing_lock = reservation(home.path(), "task:missing-lock");
2007        missing_lock.status = Status::Running;
2008        missing_lock.pid = Some(std::process::id());
2009        save(
2010            &job_dir(home.path(), &missing_lock.id)
2011                .unwrap()
2012                .join("job.json"),
2013            &missing_lock,
2014        )
2015        .unwrap();
2016        assert_eq!(
2017            observe_job_active_reason(home.path(), &missing_lock).unwrap(),
2018            Some(ActiveReason::MissingLiveLease)
2019        );
2020    }
2021}