1use 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
25pub const INVOCATION_ENV: [&str; 4] = [
30 "MAGI_WORKER_ID",
31 "MAGI_WORKER_GENERATION",
32 "MAGI_WORKER_HOME",
33 "MAGI_WORKER_EXE",
34];
35
36#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
38#[serde(rename_all = "snake_case")]
39pub enum Status {
40 Starting,
42 Running,
44 Finished,
46 Failed,
48}
49
50impl Status {
51 #[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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
71pub enum ActiveReason {
72 UnfencedStartup,
74 LiveLeaseHeld,
76 MissingLiveLease,
78}
79
80impl ActiveReason {
81 #[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#[derive(Clone, Debug)]
100pub struct ObservedActive {
101 pub job: Job,
103 pub reason: ActiveReason,
105}
106
107#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
109#[serde(rename_all = "snake_case")]
110pub enum Control {
111 Park,
113 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
136pub fn not_started(error: &anyhow::Error) -> bool {
142 error.downcast_ref::<NotStarted>().is_some()
143}
144
145#[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#[derive(Clone, Debug, Serialize, Deserialize)]
156pub struct Job {
157 pub id: String,
159 #[serde(default)]
161 pub sequence: u64,
162 pub kind: String,
164 pub key: String,
166 pub payload: serde_json::Value,
168 pub generation: String,
170 #[serde(default)]
172 pub version: Option<String>,
173 pub status: Status,
175 pub result: Option<String>,
177 pub pid: Option<u32>,
179 pub created_at: u64,
181 pub finished_at: Option<u64>,
183}
184
185#[derive(Clone, Debug)]
187pub struct Generation {
188 pub id: String,
190 pub executable: PathBuf,
192}
193
194#[derive(Debug)]
196pub struct Lease {
197 _file: File,
198}
199
200impl Drop for Lease {
201 fn drop(&mut self) {
202 #[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
269pub 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 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 crate::lock_file::Retry::new(None).run(|| std::fs::rename(from, to))?;
353 Ok(())
354}
355
356fn 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
369pub 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
409pub 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 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 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 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
542fn 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
575pub 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
587pub 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
595pub 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
635pub(crate) fn observe_job_active(home: &Path, job: &Job) -> Result<bool> {
637 Ok(observe_job_active_reason(home, job)?.is_some())
638}
639
640pub(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
693pub fn request(home: &Path, key: &str, control: Control) -> Result<()> {
695 let _store = store_lock(home)?;
696 save(&control_path(home, key), &control)
697}
698
699pub 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
720pub fn clear_control(home: &Path, key: &str) -> Result<()> {
722 let _store = store_lock(home)?;
723 clear_control_locked(home, key)
724}
725
726pub 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
741pub 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
755pub 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
769pub 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 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 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 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 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 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 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 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::win_job::detached_flags().context("prepare independent Windows worker")?,
1133 );
1134 }
1135 Ok(command)
1136}
1137
1138#[cfg(windows)]
1139fn detached_standard_handles() -> std::io::Result<()> {
1140 use std::ffi::c_void;
1141 #[link(name = "kernel32")]
1142 unsafe extern "system" {
1143 fn GetStdHandle(kind: u32) -> *mut c_void;
1144 fn SetHandleInformation(handle: *mut c_void, mask: u32, flags: u32) -> i32;
1145 }
1146 for kind in [-10_i32, -11, -12] {
1152 let handle = unsafe { GetStdHandle(kind as u32) };
1153 if handle.is_null() || handle as isize == -1 {
1154 continue;
1155 }
1156 if unsafe { SetHandleInformation(handle, 1, 0) } == 0 {
1157 let error = std::io::Error::last_os_error();
1158 if error.raw_os_error() != Some(6) {
1160 return Err(error);
1161 }
1162 }
1163 }
1164 Ok(())
1165}
1166
1167async fn spawn_generation(
1171 mut spawn: impl FnMut() -> std::io::Result<Child>,
1172) -> std::io::Result<Child> {
1173 for delay_ms in [10, 20, 40, 80] {
1174 match spawn() {
1175 Err(error) if error.kind() == std::io::ErrorKind::ExecutableFileBusy => {
1176 tokio::time::sleep(Duration::from_millis(delay_ms)).await;
1177 }
1178 result => return result,
1179 }
1180 }
1181 spawn()
1182}
1183
1184pub async fn spawn(home: &Path, kind: &str, key: &str, payload: serde_json::Value) -> Result<Job> {
1189 std::fs::create_dir_all(home).map_err(not_started_error)?;
1190 let home = home
1191 .canonicalize()
1192 .context("resolve worker home")
1193 .map_err(not_started_error)?;
1194 let pin_home = home.clone();
1195 let generation = tokio::task::spawn_blocking(move || pin_current(&pin_home))
1196 .await
1197 .map_err(not_started_error)?
1198 .map_err(not_started_error)?;
1199 let (job, fresh) = reserve(&home, &generation, kind, key, payload)?;
1200 if fresh {
1201 let child = match detached_command(&home, &job, &generation) {
1202 Ok(mut command) => spawn_generation(|| command.spawn())
1203 .await
1204 .map_err(Into::into),
1205 Err(error) => Err(error),
1206 };
1207 match child {
1208 Ok(mut child) => {
1209 std::thread::spawn(move || {
1212 let _ = child.wait();
1213 });
1214 }
1215 Err(error) => {
1216 let _store = store_lock(&home)?;
1217 let mut job = get(&home, &job.id)?;
1218 if job.status == Status::Starting {
1219 if let Some(_lease) = try_lock(&job_dir(&home, &job.id)?.join("live.lock"))? {
1220 terminal(
1221 &home,
1222 &mut job,
1223 Status::Failed,
1224 format!("worker spawn failed: {error}"),
1225 )?;
1226 return Err(not_started_error(error));
1227 }
1228 }
1229 return Err(error);
1230 }
1231 }
1232 }
1233 let deadline = tokio::time::Instant::now() + Duration::from_secs(10);
1234 loop {
1235 let current = get(&home, &job.id)?;
1236 match current.status {
1237 Status::Running | Status::Finished => return Ok(current),
1238 Status::Failed => bail!(
1239 "worker {} failed: {}",
1240 current.id,
1241 current.result.as_deref().unwrap_or("unknown failure")
1242 ),
1243 Status::Starting => {}
1244 }
1245 if tokio::time::Instant::now() >= deadline {
1246 return Err(StartupUnacknowledged { id: job.id }.into());
1247 }
1248 tokio::time::sleep(Duration::from_millis(20)).await;
1249 }
1250}
1251
1252pub async fn run(home: &Path, id: &str) -> Result<()> {
1256 let dir = job_dir(home, id)?;
1257 let (job, _lease) = {
1258 let _store = store_lock(home)?;
1259 let mut job = get(home, id)?;
1260 if job.status != Status::Starting {
1261 bail!("worker reservation is no longer startable");
1262 }
1263 let lease =
1264 try_lock(&dir.join("live.lock"))?.context("worker execution lease is already held")?;
1265 let current = std::env::current_exe()
1266 .context("locate running worker executable")?
1267 .canonicalize()
1268 .context("resolve running worker executable")?;
1269 let expected = executable(home, &job.generation)?
1270 .canonicalize()
1271 .with_context(|| {
1272 format!("resolve worker {id} reserved generation {}", job.generation)
1273 })?;
1274 if current != expected {
1275 bail!("worker must execute its reserved immutable generation");
1276 }
1277 job.pid = Some(std::process::id());
1278 job.version = Some(env!("CARGO_PKG_VERSION").to_owned());
1279 job.status = Status::Running;
1280 save(&dir.join("job.json"), &job)
1281 .with_context(|| format!("acknowledge worker {id} startup"))?;
1282 (job, lease)
1283 };
1284 let result = match job.kind.as_str() {
1285 "task" => crate::daemon::run_task_worker(home, job.payload.clone()).await,
1286 "scheduler" => crate::daemon::run_scheduler_worker(home, job.payload.clone()).await,
1287 "chat" => crate::chat_worker::run_turn_worker(home, job.payload.clone()).await,
1288 "service" => crate::consult::run_service_worker(home, job.payload.clone()).await,
1289 "daemon-service" => crate::daemon::run_service_worker(home, job.payload.clone()).await,
1290 "deputy" => crate::deputy::run_worker(home, job.payload.clone()).await,
1291 kind => Err(anyhow::anyhow!("unknown worker kind {kind}")),
1292 };
1293 let _store = store_lock(home)?;
1294 let mut current = get(home, id)?;
1295 match &result {
1296 Ok(()) => terminal(home, &mut current, Status::Finished, "completed".to_owned())?,
1297 Err(error) => terminal(home, &mut current, Status::Failed, format!("{error:#}"))?,
1298 }
1299 result
1300}
1301
1302fn hex_digest(hash: Sha256) -> String {
1303 hash.finalize()
1306 .iter()
1307 .map(|byte| format!("{byte:02x}"))
1308 .collect()
1309}
1310fn digest(bytes: &[u8]) -> String {
1311 let mut hash = Sha256::new();
1312 hash.update(bytes);
1313 hex_digest(hash)
1314}
1315
1316#[cfg(test)]
1317mod tests {
1318 use super::*;
1319
1320 #[test]
1321 fn observing_an_unused_store_requires_no_writes() {
1322 let home = tempfile::tempdir().unwrap();
1323 assert!(observe_active(home.path()).unwrap().is_empty());
1324 assert!(!home.path().join("workers").exists());
1325 }
1326
1327 #[test]
1328 fn observing_execution_probes_the_lease_without_rewriting_history() {
1329 let home = tempfile::tempdir().unwrap();
1330 let mut job = reservation(home.path(), "task:observer");
1331 let directory = job_dir(home.path(), &job.id).unwrap();
1332 let live_path = directory.join("live.lock");
1333 let lease = try_lock(&live_path).unwrap().unwrap();
1334 job.status = Status::Running;
1335 save(&directory.join("job.json"), &job).unwrap();
1336 #[cfg(unix)]
1337 {
1338 use std::os::unix::fs::PermissionsExt as _;
1339 std::fs::set_permissions(&live_path, std::fs::Permissions::from_mode(0o444)).unwrap();
1340 }
1341 let before = std::fs::read(directory.join("job.json")).unwrap();
1342 let observed = observe_active(home.path()).unwrap();
1343 assert_eq!(observed.len(), 1);
1344 assert_eq!(observed[0].id, job.id);
1345 drop(lease);
1346 assert!(observe_active(home.path()).unwrap().is_empty());
1347 assert_eq!(std::fs::read(directory.join("job.json")).unwrap(), before);
1348 assert_eq!(get(home.path(), &job.id).unwrap().status, Status::Running);
1349 }
1350 fn generation() -> Generation {
1351 Generation {
1352 id: "a".repeat(64),
1353 executable: PathBuf::from("unused"),
1354 }
1355 }
1356 fn reservation(home: &Path, key: &str) -> Job {
1357 reserve(
1358 home,
1359 &generation(),
1360 "task",
1361 key,
1362 serde_json::json!({"task":"example"}),
1363 )
1364 .unwrap()
1365 .0
1366 }
1367
1368 #[test]
1369 fn reservation_deduplicates_identical_keys_and_rejects_collision() {
1370 let home = tempfile::tempdir().unwrap();
1371 let first = reservation(home.path(), "task:one");
1372 assert_eq!(first.id, reservation(home.path(), "task:one").id);
1373 assert!(
1374 reserve(
1375 home.path(),
1376 &generation(),
1377 "chat",
1378 "task:one",
1379 serde_json::Value::Null
1380 )
1381 .is_err()
1382 );
1383 assert_ne!(first.id, reservation(home.path(), "task:two").id);
1384 }
1385
1386 #[test]
1387 fn reservation_order_is_durable_and_corruption_never_resets_it() {
1388 let home = tempfile::tempdir().unwrap();
1389 let first = reservation(home.path(), "chat:first");
1390 assert_eq!(
1391 first.sequence,
1392 reservation(home.path(), "chat:first").sequence
1393 );
1394 let second = reservation(home.path(), "chat:second");
1395 assert!(second.sequence > first.sequence);
1396 let encoded = serde_json::to_vec(&second).unwrap();
1397 assert_eq!(
1398 serde_json::from_slice::<Job>(&encoded).unwrap().sequence,
1399 second.sequence
1400 );
1401 let mut legacy = serde_json::to_value(&first).unwrap();
1402 legacy.as_object_mut().unwrap().remove("sequence");
1403 assert_eq!(serde_json::from_value::<Job>(legacy).unwrap().sequence, 0);
1404 std::fs::write(root(home.path()).join("sequence.json"), b"broken").unwrap();
1405 assert!(
1406 reserve(
1407 home.path(),
1408 &generation(),
1409 "chat",
1410 "chat:third",
1411 serde_json::Value::Null
1412 )
1413 .is_err()
1414 );
1415 }
1416
1417 #[tokio::test]
1418 async fn pre_reservation_failure_is_proven_without_history_absence_guesses() {
1419 let home = tempfile::tempdir().unwrap();
1420 let blocked = home.path().join("not-a-directory");
1421 std::fs::write(&blocked, b"file").unwrap();
1422 let error = spawn(&blocked, "chat", "fresh:chat", serde_json::Value::Null)
1423 .await
1424 .unwrap_err();
1425 assert!(not_started(&error));
1426 assert!(not_started(&error.context("publish recorded turn")));
1427 assert!(!not_started(&anyhow::anyhow!(
1428 "startup acknowledgement timed out"
1429 )));
1430 assert!(!blocked.join("workers").exists());
1431 }
1432
1433 #[test]
1434 fn failed_os_spawn_is_fenced_and_proven_not_started() {
1435 let home = tempfile::tempdir().unwrap();
1436 let executable = home.path().join("invalid-executable");
1437 std::fs::write(&executable, b"not an executable binary").unwrap();
1438 let output = Command::new(std::env::current_exe().unwrap())
1439 .args([
1440 "--exact",
1441 "worker::tests::unstarted_spawn_helper",
1442 "--ignored",
1443 "--nocapture",
1444 ])
1445 .env("MAGI_WORKER_EXE", &executable)
1446 .env("MAGI_SPAWN_FAILURE_HOME", home.path())
1447 .output()
1448 .unwrap();
1449 assert!(
1450 output.status.success(),
1451 "{}\n{}",
1452 String::from_utf8_lossy(&output.stdout),
1453 String::from_utf8_lossy(&output.stderr)
1454 );
1455 }
1456
1457 #[tokio::test]
1458 #[ignore = "isolated environment for the failed OS spawn test"]
1459 async fn unstarted_spawn_helper() {
1460 let home = PathBuf::from(std::env::var_os("MAGI_SPAWN_FAILURE_HOME").unwrap());
1461 let error = spawn(&home, "chat", "fresh:failed-exec", serde_json::Value::Null)
1462 .await
1463 .unwrap_err();
1464 assert!(not_started(&error));
1465 let entry = std::fs::read_dir(root(&home).join("jobs"))
1466 .unwrap()
1467 .next()
1468 .unwrap()
1469 .unwrap();
1470 let id = entry.file_name().to_str().unwrap().to_owned();
1471 let job = get(&home, &id).unwrap();
1472 assert_eq!(job.status, Status::Failed);
1473 assert_eq!(job.pid, None);
1474 assert!(active(&home).unwrap().is_empty());
1475 assert_eq!(get(&home, &id).unwrap().status, Status::Failed);
1476 }
1477
1478 #[test]
1479 fn unresolved_startup_remains_reserved_and_live_lease_never_expires() {
1480 let home = tempfile::tempdir().unwrap();
1481 let mut job = reservation(home.path(), "task:one");
1482 assert_eq!(active(home.path()).unwrap().len(), 1);
1483 job.created_at = 0;
1484 save(
1485 &job_dir(home.path(), &job.id).unwrap().join("job.json"),
1486 &job,
1487 )
1488 .unwrap();
1489 let lease = try_lock(&job_dir(home.path(), &job.id).unwrap().join("live.lock"))
1490 .unwrap()
1491 .unwrap();
1492 assert_eq!(active(home.path()).unwrap().len(), 1);
1493 drop(lease);
1494 assert!(active(home.path()).unwrap().is_empty());
1495 assert_eq!(get(home.path(), &job.id).unwrap().status, Status::Failed);
1496 }
1497
1498 #[tokio::test]
1499 async fn cancelled_startup_cannot_execute_late() {
1500 let home = tempfile::tempdir().unwrap();
1501 let mut job = reservation(home.path(), "task:one");
1502 job.created_at = 0;
1503 save(
1504 &job_dir(home.path(), &job.id).unwrap().join("job.json"),
1505 &job,
1506 )
1507 .unwrap();
1508 assert!(active(home.path()).unwrap().is_empty());
1509 assert!(
1510 run(home.path(), &job.id)
1511 .await
1512 .unwrap_err()
1513 .to_string()
1514 .contains("no longer startable")
1515 );
1516 }
1517
1518 #[test]
1519 fn running_without_lease_fails_regardless_of_pid() {
1520 let home = tempfile::tempdir().unwrap();
1521 let mut job = reservation(home.path(), "task:one");
1522 job.status = Status::Running;
1523 job.pid = Some(std::process::id());
1524 save(
1525 &job_dir(home.path(), &job.id).unwrap().join("job.json"),
1526 &job,
1527 )
1528 .unwrap();
1529 assert!(active(home.path()).unwrap().is_empty());
1530 assert_eq!(get(home.path(), &job.id).unwrap().status, Status::Failed);
1531 }
1532
1533 #[test]
1534 fn controls_survive_reopen_and_reset_at_new_invocation() {
1535 let home = tempfile::tempdir().unwrap();
1536 request(home.path(), "task:one", Control::Park).unwrap();
1537 assert_eq!(
1538 control(home.path(), "task:one").unwrap(),
1539 Some(Control::Park)
1540 );
1541 reservation(home.path(), "task:one");
1542 assert_eq!(control(home.path(), "task:one").unwrap(), None);
1543 request(home.path(), "task:one", Control::Stop).unwrap();
1544 assert_eq!(
1545 control(home.path(), "task:one").unwrap(),
1546 Some(Control::Stop)
1547 );
1548 assert_eq!(control(home.path(), "task:other").unwrap(), None);
1549 }
1550
1551 #[test]
1552 fn singleton_locks_release_without_pid_cleanup() {
1553 let home = tempfile::tempdir().unwrap();
1554 let lease = try_lease(home.path(), "scheduler").unwrap().unwrap();
1555 assert!(try_lease(home.path(), "scheduler").unwrap().is_none());
1556 assert!(try_lease(home.path(), "other").unwrap().is_some());
1557 drop(lease);
1558 assert!(try_lease(home.path(), "scheduler").unwrap().is_some());
1559 }
1560
1561 #[test]
1562 fn immutable_generation_keeps_old_content_after_source_replacement() {
1563 let home = tempfile::tempdir().unwrap();
1564 let source = home.path().join("source");
1565 std::fs::write(&source, b"old executable").unwrap();
1566 let old = pin_source(home.path(), &source).unwrap();
1567 std::fs::write(&source, b"new executable").unwrap();
1568 let new = pin_source(home.path(), &source).unwrap();
1569 assert_ne!(old.id, new.id);
1570 assert_eq!(
1571 std::fs::read(executable(home.path(), &old.id).unwrap()).unwrap(),
1572 b"old executable"
1573 );
1574 assert_eq!(std::fs::read(new.executable).unwrap(), b"new executable");
1575 }
1576
1577 #[tokio::test]
1578 async fn generation_spawn_does_not_retry_a_missing_executable() {
1579 let home = tempfile::tempdir().unwrap();
1580 let mut command = Command::new(home.path().join("missing-executable"));
1581 let mut attempts = 0;
1582 let error = spawn_generation(|| {
1583 attempts += 1;
1584 command.spawn()
1585 })
1586 .await
1587 .unwrap_err();
1588 assert_eq!(error.kind(), std::io::ErrorKind::NotFound);
1589 assert_eq!(attempts, 1);
1590 }
1591
1592 #[cfg(target_os = "linux")]
1593 fn busy_executable(dir: &Path) -> (Command, File) {
1594 use std::os::unix::fs::PermissionsExt;
1595
1596 let path = dir.join("busy-executable");
1597 std::fs::copy("/bin/sh", &path).unwrap();
1598 std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o700)).unwrap();
1599 let writer = OpenOptions::new().write(true).open(&path).unwrap();
1600 let mut command = Command::new(path);
1601 command.args(["-c", "exit 0"]);
1602 (command, writer)
1603 }
1604
1605 #[cfg(target_os = "linux")]
1606 #[tokio::test]
1607 async fn generation_spawn_retries_until_the_writer_closes() {
1608 let home = tempfile::tempdir().unwrap();
1609 let (mut command, writer) = busy_executable(home.path());
1610 let error = command.spawn().unwrap_err();
1611 assert_eq!(error.kind(), std::io::ErrorKind::ExecutableFileBusy);
1612
1613 let (release, requested) = std::sync::mpsc::channel();
1614 let closer = std::thread::spawn(move || {
1615 if requested.recv().is_ok() {
1616 std::thread::sleep(Duration::from_millis(20));
1617 }
1618 drop(writer);
1619 });
1620 let mut release = Some(release);
1621 let child = spawn_generation(|| {
1622 let result = command.spawn();
1623 if let Some(release) = release.take() {
1624 release.send(()).unwrap();
1625 }
1626 result
1627 })
1628 .await;
1629 closer.join().unwrap();
1630 assert!(child.unwrap().wait().unwrap().success());
1631 }
1632
1633 #[cfg(target_os = "linux")]
1634 #[tokio::test]
1635 async fn generation_spawn_stops_retrying_while_the_writer_remains_open() {
1636 let home = tempfile::tempdir().unwrap();
1637 let (mut command, _writer) = busy_executable(home.path());
1638 let mut attempts = 0;
1639 let error = spawn_generation(|| {
1640 attempts += 1;
1641 assert!(attempts <= 5, "busy generation exceeded its retry bound");
1642 command.spawn()
1643 })
1644 .await
1645 .unwrap_err();
1646 assert_eq!(error.kind(), std::io::ErrorKind::ExecutableFileBusy);
1647 }
1648
1649 #[tokio::test]
1650 async fn acknowledgement_records_own_version_and_handler_failure() {
1651 let home = tempfile::tempdir().unwrap();
1652 let generation = pin_source(home.path(), &std::env::current_exe().unwrap()).unwrap();
1653 let (job, _) = reserve(
1654 home.path(),
1655 &generation,
1656 "unknown-kind",
1657 "unknown:one",
1658 serde_json::Value::Null,
1659 )
1660 .unwrap();
1661 let invoke = || async {
1662 let mut command = Command::new(&generation.executable);
1663 command
1664 .args([
1665 "--exact",
1666 "worker::tests::pinned_entrypoint_helper",
1667 "--ignored",
1668 "--nocapture",
1669 ])
1670 .env("MAGI_WORKER_TEST_HOME", home.path())
1671 .env("MAGI_WORKER_TEST_ID", &job.id)
1672 .stdin(Stdio::null())
1673 .stdout(Stdio::piped())
1674 .stderr(Stdio::piped());
1675 let output = spawn_generation(|| command.spawn())
1676 .await
1677 .unwrap()
1678 .wait_with_output()
1679 .unwrap();
1680 assert!(
1681 output.status.success(),
1682 "{}",
1683 String::from_utf8_lossy(&output.stderr)
1684 );
1685 };
1686 invoke().await;
1687 let failed = get(home.path(), &job.id).unwrap();
1688 assert_eq!(failed.status, Status::Failed);
1689 assert_eq!(failed.version.as_deref(), Some(env!("CARGO_PKG_VERSION")));
1690 assert!(failed.result.unwrap().contains("unknown worker kind"));
1691 assert!(active(home.path()).unwrap().is_empty());
1692 assert!(!job_dir(home.path(), &job.id).unwrap().exists());
1693 invoke().await;
1694 assert!(!job_dir(home.path(), &job.id).unwrap().exists());
1695 }
1696
1697 #[tokio::test]
1698 #[ignore = "subprocess entrypoint for the immutable-generation startup test"]
1699 async fn pinned_entrypoint_helper() {
1700 let home = PathBuf::from(std::env::var_os("MAGI_WORKER_TEST_HOME").unwrap());
1701 let id = std::env::var("MAGI_WORKER_TEST_ID").unwrap();
1702 assert!(run(&home, &id).await.is_err());
1703 }
1704
1705 #[test]
1706 fn unfinished_staging_is_reclaimed_without_removing_generations() {
1707 let home = tempfile::tempdir().unwrap();
1708 let old = root(home.path()).join("generations").join(".new-abandoned");
1709 std::fs::create_dir_all(&old).unwrap();
1710 let partial = old.join("partial");
1711 std::fs::write(&partial, b"interrupted copy").unwrap();
1712 #[cfg(windows)]
1713 {
1714 let mut permissions = std::fs::metadata(&partial).unwrap().permissions();
1715 permissions.set_readonly(true);
1716 std::fs::set_permissions(&partial, permissions).unwrap();
1717 }
1718 let source = home.path().join("source");
1719 std::fs::write(&source, b"complete executable").unwrap();
1720 let generation = pin_source(home.path(), &source).unwrap();
1721 assert!(!old.exists());
1722 assert!(generation.executable.is_file());
1723 }
1724
1725 #[tokio::test]
1726 async fn unrelated_executable_cannot_acknowledge_or_consume_reservation() {
1727 let home = tempfile::tempdir().unwrap();
1728 let source = home.path().join("other-binary");
1729 std::fs::write(&source, b"different executable of the same Cargo version").unwrap();
1730 let generation = pin_source(home.path(), &source).unwrap();
1731 let (job, _) = reserve(
1732 home.path(),
1733 &generation,
1734 "task",
1735 "task:one",
1736 serde_json::Value::Null,
1737 )
1738 .unwrap();
1739 assert!(
1740 run(home.path(), &job.id)
1741 .await
1742 .unwrap_err()
1743 .to_string()
1744 .contains("immutable generation")
1745 );
1746 assert_eq!(get(home.path(), &job.id).unwrap().status, Status::Starting);
1747 assert_eq!(active(home.path()).unwrap().len(), 1);
1748 }
1749
1750 #[test]
1751 fn abandoned_record_staging_is_bounded_and_never_executes() {
1752 let home = tempfile::tempdir().unwrap();
1753 let staging = root(home.path()).join("jobs").join(".new-interrupted");
1754 std::fs::create_dir_all(&staging).unwrap();
1755 std::fs::write(staging.join("job.json"), b"partial json").unwrap();
1756 assert!(active(home.path()).unwrap().is_empty());
1757 assert!(!staging.exists());
1758 }
1759
1760 #[cfg(unix)]
1761 #[tokio::test]
1762 async fn detached_startup_preserves_stdout_and_stderr_in_record_log() {
1763 use std::os::unix::fs::PermissionsExt;
1764 let home = tempfile::tempdir().unwrap();
1765 let source = home.path().join("startup-diagnostic");
1766 std::fs::write(
1767 &source,
1768 b"#!/bin/sh\nprintf 'startup stdout\\n'\nprintf 'startup stderr\\n' >&2\nexit 7\n",
1769 )
1770 .unwrap();
1771 std::fs::set_permissions(&source, std::fs::Permissions::from_mode(0o755)).unwrap();
1772 let generation = pin_source(home.path(), &source).unwrap();
1773 let (mut job, _) = reserve(
1774 home.path(),
1775 &generation,
1776 "task",
1777 "task:log",
1778 serde_json::Value::Null,
1779 )
1780 .unwrap();
1781 let mut command = detached_command(home.path(), &job, &generation).unwrap();
1782 for key in ["MAGI_RUN", "MAGI_NODE", "MAGI_SEAT"]
1783 .into_iter()
1784 .chain(crate::chat_control::bridge::ENVIRONMENT.iter().copied())
1785 {
1786 assert!(
1787 command
1788 .get_envs()
1789 .any(|(name, value)| name == key && value.is_none())
1790 );
1791 }
1792 let mut child = spawn_generation(|| command.spawn()).await.unwrap();
1793 assert_eq!(child.wait().unwrap().code(), Some(7));
1794 let log = job_dir(home.path(), &job.id).unwrap().join("worker.log");
1795 let output = std::fs::read_to_string(log).unwrap();
1796 assert!(output.contains("startup stdout"));
1797 assert!(output.contains("startup stderr"));
1798 terminal(
1799 home.path(),
1800 &mut job,
1801 Status::Failed,
1802 "startup failed".into(),
1803 )
1804 .unwrap();
1805 assert!(active(home.path()).unwrap().is_empty());
1806 assert!(
1807 root(home.path())
1808 .join("results")
1809 .join(&job.id)
1810 .join("worker.log")
1811 .is_file()
1812 );
1813 }
1814
1815 #[cfg(windows)]
1816 #[test]
1817 fn record_publication_survives_readers_and_short_delete_sharing_handoffs() {
1818 use std::os::windows::fs::OpenOptionsExt as _;
1819
1820 let home = tempfile::tempdir().unwrap();
1821 let mut job = reservation(home.path(), "task:metadata-handoff");
1822 let directory = job_dir(home.path(), &job.id).unwrap();
1823 let path = directory.join("job.json");
1824 let lease = try_lock(&directory.join("live.lock")).unwrap().unwrap();
1825 let snapshot = File::open(&path).unwrap();
1826 let reader = OpenOptions::new()
1828 .read(true)
1829 .share_mode(1 | 2) .open(&path)
1831 .unwrap();
1832 std::thread::scope(|scope| {
1833 scope.spawn(move || {
1834 std::thread::sleep(Duration::from_millis(15));
1835 drop(reader);
1836 });
1837 job.status = Status::Running;
1838 save(&path, &job).unwrap();
1839 });
1840 let original: Job = serde_json::from_reader(snapshot).unwrap();
1841 assert_eq!(original.status, Status::Starting);
1842 assert_eq!(get(home.path(), &job.id).unwrap().status, Status::Running);
1843 let running_snapshot = File::open(&path).unwrap();
1844 terminal(home.path(), &mut job, Status::Finished, "completed".into()).unwrap();
1845 assert_eq!(get(home.path(), &job.id).unwrap().status, Status::Finished);
1846 let previous: Job = serde_json::from_reader(running_snapshot).unwrap();
1847 assert_eq!(previous.status, Status::Running);
1848 drop(lease);
1849 assert!(active(home.path()).unwrap().is_empty());
1850 }
1851
1852 #[cfg(windows)]
1853 #[test]
1854 fn denied_record_publication_preserves_reservation_and_original_os_error() {
1855 use std::os::windows::fs::OpenOptionsExt as _;
1856
1857 let home = tempfile::tempdir().unwrap();
1858 let job = reservation(home.path(), "task:metadata-denied");
1859 let directory = job_dir(home.path(), &job.id).unwrap();
1860 let path = directory.join("job.json");
1861 let reader = OpenOptions::new()
1862 .read(true)
1863 .share_mode(1 | 2) .open(&path)
1865 .unwrap();
1866 let mut acknowledged = job.clone();
1867 acknowledged.status = Status::Running;
1868 let error = save(&path, &acknowledged).unwrap_err();
1869 assert!(format!("{error:#}").contains("publish worker record"));
1870 let io = error.downcast_ref::<std::io::Error>().unwrap();
1871 assert!(matches!(io.raw_os_error(), Some(5 | 32)));
1872 assert_eq!(get(home.path(), &job.id).unwrap().status, Status::Starting);
1873 assert_eq!(reservation(home.path(), &job.key).id, job.id);
1874 assert!(std::fs::read_dir(&directory).unwrap().all(|entry| {
1875 !entry
1876 .unwrap()
1877 .file_name()
1878 .to_string_lossy()
1879 .starts_with(".pending-")
1880 }));
1881 drop(reader);
1882 save(&path, &acknowledged).unwrap();
1883 assert_eq!(get(home.path(), &job.id).unwrap().status, Status::Running);
1884 }
1885
1886 #[test]
1887 fn terminal_result_survives_open_execution_and_output_handles() {
1888 let home = tempfile::tempdir().unwrap();
1889 let mut job = reservation(home.path(), "task:open-handles");
1890 let directory = job_dir(home.path(), &job.id).unwrap();
1891 let lease = try_lock(&directory.join("live.lock")).unwrap().unwrap();
1892 let mut log = OpenOptions::new()
1893 .create(true)
1894 .append(true)
1895 .open(directory.join("worker.log"))
1896 .unwrap();
1897 writeln!(log, "before completion").unwrap();
1898 terminal(home.path(), &mut job, Status::Finished, "completed".into()).unwrap();
1899 assert_eq!(get(home.path(), &job.id).unwrap().status, Status::Finished);
1900 assert!(active(home.path()).unwrap().is_empty());
1901 assert!(
1902 directory.exists(),
1903 "a held execution lease must prevent retirement"
1904 );
1905 drop(lease);
1906 assert!(active(home.path()).unwrap().is_empty());
1909 assert_eq!(get(home.path(), &job.id).unwrap().status, Status::Finished);
1910 writeln!(log, "after completion").unwrap();
1911 drop(log);
1912 assert!(active(home.path()).unwrap().is_empty());
1913 assert!(
1914 root(home.path())
1915 .join("results")
1916 .join(&job.id)
1917 .join("worker.log")
1918 .is_file()
1919 );
1920 assert!(!directory.exists());
1921 }
1922
1923 #[test]
1924 fn terminal_records_are_bounded_without_pruning_live_reservations() {
1925 let home = tempfile::tempdir().unwrap();
1926 let live = reservation(home.path(), "task:live");
1927 let mut finished = reservation(home.path(), "task:finished");
1931 terminal(home.path(), &mut finished, Status::Finished, "done".into()).unwrap();
1932 let template_dir = job_dir(home.path(), &finished.id).unwrap();
1933 std::fs::remove_dir_all(template_dir).unwrap();
1934 for i in 0..RETAIN_FINISHED + 3 {
1935 let mut job = finished.clone();
1936 job.id = format!("{i:032x}");
1937 job.key = format!("task:{i}");
1938 job.sequence += i as u64;
1939 let directory = job_dir(home.path(), &job.id).unwrap();
1940 std::fs::create_dir_all(&directory).unwrap();
1941 std::fs::write(
1942 directory.join("job.json"),
1943 serde_json::to_vec(&job).unwrap(),
1944 )
1945 .unwrap();
1946 }
1947 assert_eq!(
1948 std::fs::read_dir(root(home.path()).join("jobs"))
1949 .unwrap()
1950 .count(),
1951 RETAIN_FINISHED + 4
1952 );
1953 let jobs = records(home.path()).unwrap();
1954 assert_eq!(jobs.len(), 1);
1955 assert_eq!(
1956 std::fs::read_dir(root(home.path()).join("results"))
1957 .unwrap()
1958 .count(),
1959 RETAIN_FINISHED
1960 );
1961 assert!(jobs.iter().any(|job| job.id == live.id));
1962 }
1963
1964 #[test]
1965 fn observe_active_excludes_unarchived_terminal_jobs_and_preserves_unfenced_startup() {
1966 let home = tempfile::tempdir().unwrap();
1967 let starting = reservation(home.path(), "task:starting");
1968 let mut finished = reservation(home.path(), "task:finished");
1969 let mut failed = reservation(home.path(), "task:failed");
1970 terminal(home.path(), &mut finished, Status::Finished, "done".into()).unwrap();
1971 terminal(home.path(), &mut failed, Status::Failed, "boom".into()).unwrap();
1972 assert!(job_dir(home.path(), &finished.id).unwrap().exists());
1974 assert!(job_dir(home.path(), &failed.id).unwrap().exists());
1975
1976 let observed = observe_active_detailed(home.path()).unwrap();
1977 assert_eq!(observed.len(), 1);
1978 assert_eq!(observed[0].job.id, starting.id);
1979 assert_eq!(observed[0].reason, ActiveReason::UnfencedStartup);
1980 assert!(job_dir(home.path(), &finished.id).unwrap().exists());
1982 assert!(job_dir(home.path(), &failed.id).unwrap().exists());
1983 }
1984
1985 #[test]
1986 fn observe_job_active_handles_archive_race_deterministically_and_protects_missing_live_lock() {
1987 let home = tempfile::tempdir().unwrap();
1988 let mut archived = reservation(home.path(), "task:archived-race");
1989 let running_snapshot = Job {
1990 status: Status::Running,
1991 pid: Some(std::process::id()),
1992 ..archived.clone()
1993 };
1994 terminal(home.path(), &mut archived, Status::Finished, "done".into()).unwrap();
1995 archive(home.path(), &archived).unwrap();
1996 assert!(!job_dir(home.path(), &archived.id).unwrap().exists());
1997 assert_eq!(
1999 observe_job_active_reason(home.path(), &running_snapshot).unwrap(),
2000 None
2001 );
2002
2003 let mut missing_lock = reservation(home.path(), "task:missing-lock");
2006 missing_lock.status = Status::Running;
2007 missing_lock.pid = Some(std::process::id());
2008 save(
2009 &job_dir(home.path(), &missing_lock.id)
2010 .unwrap()
2011 .join("job.json"),
2012 &missing_lock,
2013 )
2014 .unwrap();
2015 assert_eq!(
2016 observe_job_active_reason(home.path(), &missing_lock).unwrap(),
2017 Some(ActiveReason::MissingLiveLease)
2018 );
2019 }
2020}