Skip to main content

schedr_agent/
watchers.rs

1//! The watcher hosts: a worker's wait steps, as coroutines in one long-lived process per code
2//! set (decision 320; see archive/PROJECT.md, Sensors and triggers).
3//!
4//! A host is started for the first wait step of an interpreter and set of root copies, and
5//! stopped when its last one ends, so new code gets a new host while the old one finishes. All
6//! a host's watchers share its socket: one task reads it and passes each message to its
7//! attempt, one writes, so no attempt being dropped can leave half a message in it.
8
9use std::collections::{BTreeMap, BTreeSet, HashMap};
10use std::hash::{DefaultHasher, Hash as _, Hasher as _};
11use std::path::PathBuf;
12use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
13use std::sync::{Arc, Mutex as StdMutex, PoisonError};
14use std::time::{Duration, Instant};
15
16use schedr_model::runner::{
17    AgentMessage, ErrorSummary, OutputStream, RunnerMessage, RunnerMode, TaskRequest,
18    WatchersRequest,
19};
20use schedr_model::task::{SensorMode, TaskKind};
21use schedr_proto::pb;
22use tokio::io::AsyncWriteExt as _;
23use tokio::sync::{Mutex, Notify, mpsc, oneshot, watch};
24
25use crate::attempt::{Ran, WorkerSetup};
26use crate::channel::{read_message, write_message};
27use crate::handles::{AttemptHandles, HandleError};
28use crate::launch::{
29    LaunchError, PythonTask, connection_answer, secret_answer, start_runner, unless_stopped,
30};
31use crate::mask::{Mask, MaskSet, MaskStream};
32use crate::metrics::{CodeLabels, WatcherMetrics};
33use crate::process::{OsProcess, ProcessSpec};
34use crate::secrets::AttemptSecrets;
35use crate::status::{StopReason, Termination};
36use crate::supervise::{Limits, Process, Signal, Stops, Supervised};
37
38/// The exit code a failed watcher stands for: as a task's process that reports a failure.
39const FAILED_EXIT_CODE: i32 = 1;
40
41/// The signal number a cancelled watcher stands for: as a task's process that took it.
42const TERMINATED: i32 = 15;
43
44/// The signal number of a host that had to be killed.
45const KILLED: i32 = 9;
46
47#[cfg(test)]
48mod tests;
49
50/// What a trigger found, on its way to the master.
51#[derive(Debug, Clone, PartialEq, Eq)]
52pub struct FoundEvent {
53    /// Its key.
54    pub key: String,
55    /// Its data, encoded as an output is.
56    pub data: serde_json::Value,
57    /// When it happened, if it said.
58    pub at: Option<jiff::Timestamp>,
59}
60
61/// Takes what a trigger says.
62#[derive(Clone)]
63pub struct EventSink {
64    /// Whether it batches (`@trigger.poke(batch=...)`): its data is a list of events.
65    pub batched: bool,
66    /// What it found; the answer comes once the master has it.
67    pub found: Arc<dyn Fn(FoundEvent) -> oneshot::Receiver<()> + Send + Sync>,
68    /// How a poke's call ended: why it failed, if it did.
69    pub poked: Arc<dyn Fn(Option<String>) + Send + Sync>,
70}
71
72impl std::fmt::Debug for EventSink {
73    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
74        f.write_str("EventSink")
75    }
76}
77
78impl PartialEq for EventSink {
79    fn eq(&self, other: &Self) -> bool {
80        Arc::ptr_eq(&self.found, &other.found)
81    }
82}
83
84/// The hosts of a worker, by code set (cheap to clone; clones share them).
85#[derive(Debug, Clone, Default)]
86pub struct WatcherHosts {
87    hosts: Arc<Mutex<BTreeMap<Vec<String>, Arc<Host>>>>,
88    next_watcher: Arc<AtomicU64>,
89    /// The code sets hosts run, read by the agent's copy collection, which can't wait.
90    code_sets: Arc<StdMutex<BTreeSet<Vec<String>>>>,
91    /// The copy of each DAG root the worker runs now.
92    code: Arc<StdMutex<Option<watch::Sender<Copies>>>>,
93    /// Whether they are being looked at (their memory, and what the heartbeat tells).
94    watching: Arc<AtomicBool>,
95    metrics: WatcherMetrics,
96    /// Hosts lost, by code set, since the agent started (the code sets still current).
97    lost: Arc<StdMutex<BTreeMap<Vec<String>, u64>>>,
98    /// As last looked at, for the heartbeat, which can't wait.
99    reports: Arc<StdMutex<Vec<pb::WatcherHost>>>,
100}
101
102/// What a host last said of itself.
103#[derive(Debug, Default, Clone, Copy)]
104struct HostStats {
105    threads: u32,
106    tied_threads: u32,
107    thread_stops: u64,
108}
109
110impl HostStats {
111    fn heard(
112        stats: &StdMutex<Self>,
113        metrics: &WatcherMetrics,
114        (threads, tied_threads, thread_stops, loop_lag_ms): (u32, u32, u64, u64),
115    ) {
116        let mut stats = stats.lock().unwrap_or_else(PoisonError::into_inner);
117        metrics
118            .thread_stops
119            .inc_by(thread_stops.saturating_sub(stats.thread_stops));
120        *stats = Self {
121            threads,
122            // It is the host's word, and the count is of two moments.
123            tied_threads: tied_threads.min(threads),
124            thread_stops: thread_stops.max(stats.thread_stops),
125        };
126        #[allow(clippy::cast_precision_loss)] // A delay in milliseconds.
127        metrics.loop_lag.observe(loop_lag_ms as f64 / 1000.0);
128    }
129}
130
131/// The code a host runs: its folders' names, the copies' hashes.
132fn code_of(sys_path: &[String]) -> String {
133    let names: Vec<String> = sys_path
134        .iter()
135        .filter_map(|dir| {
136            let name = std::path::Path::new(dir).file_name()?;
137            Some(name.to_string_lossy().into_owned())
138        })
139        .collect();
140    names.join(",")
141}
142
143/// The wait step a host is killed for: the others on it start again.
144#[derive(Debug, Clone)]
145struct Blamed {
146    watcher: u64,
147    /// Where it held the event loop, if that is why.
148    stack: Option<String>,
149}
150
151/// Why a host has to go.
152#[derive(Debug, Default)]
153struct Going {
154    blamed: Option<Blamed>,
155    /// With no wait step to blame.
156    why: Option<String>,
157    /// Its process has ended: nothing done now can be why.
158    dead: bool,
159    /// Its last wait step left and the agent stopped it: its channel's end is expected (B253).
160    retired: bool,
161    /// The wait steps on it, by watcher: a lost attempt's error names them (decision 342).
162    names: BTreeMap<u64, String>,
163}
164
165type Copies = BTreeMap<String, PathBuf>;
166
167type Routes = Arc<StdMutex<HashMap<u64, mpsc::Sender<RunnerMessage>>>>;
168
169/// The messages of a watcher waiting for its attempt: past them its host's socket waits too, so a
170/// wait step printing faster than its log is written slows down, and the agent's memory holds at
171/// most this many (each up to `_LOG_CHUNK`, 4 MiB, for text).
172pub const ROUTE_MESSAGES: usize = 16;
173
174/// A running host.
175#[derive(Debug)]
176struct Host {
177    pid: i32,
178    outbox: mpsc::UnboundedSender<AgentMessage>,
179    routes: Routes,
180    stop: Arc<Notify>,
181    ended: watch::Receiver<Option<Termination>>,
182    /// What its own log masks: every value of every watcher it has had (decision 334: output
183    /// of a thread or C code can't be told apart, and may come after its watcher ended).
184    mask: Arc<MaskSet>,
185    going: Arc<StdMutex<Going>>,
186    stats: Arc<StdMutex<HostStats>>,
187}
188
189impl Host {
190    /// Starts one, ready for its watchers.
191    async fn start(
192        setup: &WorkerSetup,
193        sys_path: &[String],
194        hosts: &WatcherHosts,
195    ) -> Result<Self, LaunchError> {
196        // Each value was accepted by the attempt's own set, under its `min_mask_length`.
197        let mask = Arc::new(MaskSet::new(0));
198        let spec = host_spec(setup, sys_path, Mask(Some(Arc::clone(&mask))));
199        let runner = start_runner(&spec, RunnerMode::Watchers, |_| {}).await?;
200        let pid = runner.process.id();
201        let (reader, mut writer) = runner.stream.into_split();
202        let (outbox, mut outgoing) = mpsc::unbounded_channel::<AgentMessage>();
203        let _ = outbox.send(AgentMessage::Watchers(WatchersRequest {
204            sys_path: sys_path.to_vec(),
205            block_limit_ms: millis(setup.timeouts.watcher_block_limit),
206            import_limit_ms: millis(setup.timeouts.watcher_import_limit),
207            poke_overruns: setup.timeouts.watcher_poke_overruns,
208        }));
209        let stop = Arc::new(Notify::new());
210        let routes = Routes::default();
211        let writing = tokio::spawn(async move {
212            while let Some(message) = outgoing.recv().await {
213                if write_message(&mut writer, &message).await.is_err() {
214                    return;
215                }
216            }
217        });
218        let going = Arc::new(StdMutex::new(Going::default()));
219        let stats = Arc::new(StdMutex::new(HostStats::default()));
220        // Its watchdog says it is there; twice the limit, so that it can say whom to blame first.
221        let silence = setup
222            .timeouts
223            .watcher_block_limit
224            .max(setup.timeouts.watcher_import_limit)
225            * 2;
226        let reading = tokio::spawn(read_host(
227            reader,
228            Arc::clone(&routes),
229            Arc::clone(&stop),
230            Arc::clone(&going),
231            (silence, pid, Arc::clone(&mask)),
232            (Arc::clone(&stats), hosts.metrics.clone()),
233        ));
234        let (ended_sender, ended) = watch::channel(None);
235        let watch_over = HostEnd {
236            stopping: Arc::clone(&stop),
237            routes: Arc::clone(&routes),
238            ended: ended_sender,
239            drain: spec.output_drain,
240            going: Arc::clone(&going),
241            sys_path: sys_path.to_vec(),
242            hosts: hosts.clone(),
243        };
244        tokio::spawn(watch_over.run(runner.process, reading, writing));
245        Ok(Self {
246            pid,
247            outbox,
248            routes,
249            stop,
250            ended,
251            mask,
252            going,
253            stats,
254        })
255    }
256
257    fn alive(&self) -> bool {
258        self.ended.borrow().is_none()
259    }
260
261    /// Kills it for a wait step that wouldn't end.
262    fn kill_for(&self, watcher: u64) {
263        let dead = self
264            .going
265            .lock()
266            .unwrap_or_else(PoisonError::into_inner)
267            .dead;
268        if !dead {
269            blame(&self.going, watcher, None);
270        }
271        self.stop.notify_one();
272    }
273
274    /// Remembers what a watcher on it runs.
275    fn named(&self, watcher: u64, request: &TaskRequest) {
276        self.going
277            .lock()
278            .unwrap_or_else(PoisonError::into_inner)
279            .names
280            .insert(watcher, format!("{}.{}", request.dag_id, request.task.id));
281    }
282
283    /// Forgets one that ended; those on it when it ended stay, for the errors they are named in.
284    fn unnamed(&self, watcher: u64) {
285        if self.alive() {
286            self.going
287                .lock()
288                .unwrap_or_else(PoisonError::into_inner)
289                .names
290                .remove(&watcher);
291        }
292    }
293
294    /// Those on it, for a lost attempt's error.
295    fn names(&self) -> String {
296        let going = self.going.lock().unwrap_or_else(PoisonError::into_inner);
297        let names: BTreeSet<&str> = going.names.values().map(String::as_str).collect();
298        names.into_iter().collect::<Vec<_>>().join(", ")
299    }
300
301    fn going(&self) -> (Option<Blamed>, Option<String>) {
302        let going = self.going.lock().unwrap_or_else(PoisonError::into_inner);
303        (going.blamed.clone(), going.why.clone())
304    }
305}
306
307/// Reads a host's messages until it is to go: each watcher's goes to it, and what it says of
308/// itself is taken here.
309async fn read_host(
310    mut reader: tokio::net::unix::OwnedReadHalf,
311    routes: Routes,
312    stop: Arc<Notify>,
313    going: Arc<StdMutex<Going>>,
314    (silence, pid, mask): (Duration, i32, Arc<MaskSet>),
315    (stats, metrics): (Arc<StdMutex<HostStats>>, WatcherMetrics),
316) {
317    loop {
318        let read = read_message::<_, RunnerMessage>(&mut reader);
319        let Ok(read) = tokio::time::timeout(silence, read).await else {
320            tracing::warn!(pid, "a watcher host stopped answering: killing it");
321            set_why(&going, format!("its host didn't answer for {silence:?}"));
322            stop.notify_one();
323            return;
324        };
325        match read {
326            Ok(RunnerMessage::WatcherMessage { watcher, message }) => {
327                if matches!(*message, RunnerMessage::WatcherStuck) {
328                    if is_on_it(&routes, watcher) {
329                        blame(&going, watcher, None);
330                    }
331                    continue;
332                }
333                let route = routes
334                    .lock()
335                    .unwrap_or_else(PoisonError::into_inner)
336                    .get(&watcher)
337                    .cloned();
338                // Past it the host's own sends wait too, its watchdog's among them: this is
339                // what its silence would be.
340                if let Some(route) = route
341                    && tokio::time::timeout(silence, route.send(*message))
342                        .await
343                        .is_err()
344                {
345                    tracing::warn!(pid, watcher, "a wait step's log isn't being written");
346                    set_why(
347                        &going,
348                        format!("a log on its host wasn't written for {silence:?}"),
349                    );
350                    stop.notify_one();
351                    return;
352                }
353            }
354            Ok(RunnerMessage::HostAlive {
355                threads,
356                tied_threads,
357                thread_stops,
358                loop_lag_ms,
359            }) => HostStats::heard(
360                &stats,
361                &metrics,
362                (threads, tied_threads, thread_stops, loop_lag_ms),
363            ),
364            Ok(RunnerMessage::LoopBlocked { watcher, stack }) => {
365                tracing::warn!(pid, ?watcher, "a watcher blocked its host's loop");
366                // What every wait step on it read is in this process, and may be in its stack.
367                let stack = mask.mask_text(&stack);
368                // Only one on it can be blamed: anyone else would leave all to start again.
369                match watcher.filter(|watcher| is_on_it(&routes, *watcher)) {
370                    Some(watcher) => blame(&going, watcher, Some(stack)),
371                    None => set_why(
372                        &going,
373                        format!("its host's event loop was held by no wait step:\n{stack}"),
374                    ),
375                }
376                // What was sent before it is still read.
377                stop.notify_one();
378            }
379            Ok(other) => {
380                tracing::warn!(?other, "a watcher host sent something unexpected");
381            }
382            Err(error) => {
383                let retired = going.lock().unwrap_or_else(PoisonError::into_inner).retired;
384                if retired {
385                    // Stopped by `leave`, its last wait step gone (B253): not a failure.
386                    tracing::debug!(%error, pid, "a watcher host with no wait step left ended");
387                } else {
388                    tracing::warn!(%error, pid, "a watcher host's channel ended");
389                }
390                stop.notify_one();
391                return;
392            }
393        }
394    }
395}
396
397fn is_on_it(routes: &Routes, watcher: u64) -> bool {
398    routes
399        .lock()
400        .unwrap_or_else(PoisonError::into_inner)
401        .contains_key(&watcher)
402}
403
404/// Marks a host stopped for having no wait step left, so its channel's end is no warning
405/// (B253); only one nothing went wrong with: a blamed, failed or dead one's end stays a warning
406/// (Codex's review of B253).
407fn retire(going: &StdMutex<Going>) {
408    let mut going = going.lock().unwrap_or_else(PoisonError::into_inner);
409    going.retired = going.blamed.is_none() && going.why.is_none() && !going.dead;
410}
411
412/// The first to blame stays: what comes after is a result of it.
413fn blame(going: &StdMutex<Going>, watcher: u64, stack: Option<String>) {
414    going
415        .lock()
416        .unwrap_or_else(PoisonError::into_inner)
417        .blamed
418        .get_or_insert(Blamed { watcher, stack });
419}
420
421fn set_why(going: &StdMutex<Going>, why: String) {
422    going
423        .lock()
424        .unwrap_or_else(PoisonError::into_inner)
425        .why
426        .get_or_insert(why);
427}
428
429fn millis(duration: Duration) -> u64 {
430    u64::try_from(duration.as_millis()).unwrap_or(u64::MAX)
431}
432
433/// Waits for a host's end, or stops it, and tells its watchers.
434struct HostEnd {
435    stopping: Arc<Notify>,
436    routes: Routes,
437    ended: watch::Sender<Option<Termination>>,
438    drain: Duration,
439    going: Arc<StdMutex<Going>>,
440    sys_path: Vec<String>,
441    hosts: WatcherHosts,
442}
443
444impl HostEnd {
445    /// Counts how it ended: for one wait step, or with those on it and none to blame. One
446    /// without any was stopped for that.
447    fn count(&self) {
448        let blamed = self
449            .going
450            .lock()
451            .unwrap_or_else(PoisonError::into_inner)
452            .blamed
453            .is_some();
454        let on_it = !self
455            .routes
456            .lock()
457            .unwrap_or_else(PoisonError::into_inner)
458            .is_empty();
459        if blamed {
460            self.hosts.metrics.blocked_kills.inc();
461        } else if on_it {
462            self.hosts.host_lost(&self.sys_path);
463        }
464    }
465
466    async fn run(
467        self,
468        mut process: OsProcess,
469        reading: tokio::task::JoinHandle<()>,
470        writing: tokio::task::JoinHandle<()>,
471    ) {
472        let termination = tokio::select! {
473            biased;
474            () = self.stopping.notified() => {
475                let _ = process.signal(Signal::Kill);
476                process.wait().await
477            }
478            termination = process.wait() => termination,
479        };
480        self.going
481            .lock()
482            .unwrap_or_else(PoisonError::into_inner)
483            .dead = true;
484        // What it started goes with it.
485        let _ = process.signal(Signal::Kill);
486        let _ = tokio::time::timeout(self.drain, process.output()).await;
487        // What it sent before it ended counts: a result, and whom to blame.
488        let mut reading = reading;
489        if tokio::time::timeout(self.drain, &mut reading)
490            .await
491            .is_err()
492        {
493            reading.abort();
494        }
495        writing.abort();
496        self.count();
497        let _ = self
498            .ended
499            .send(Some(termination.unwrap_or(Termination::Unknown)));
500        self.routes
501            .lock()
502            .unwrap_or_else(PoisonError::into_inner)
503            .clear();
504    }
505}
506
507/// The host's process: its environment and folder are no run's, so they are the worker's; what
508/// threads and C code print goes to its own log.
509fn host_spec(setup: &WorkerSetup, sys_path: &[String], mask: Mask) -> ProcessSpec {
510    let mut hasher = DefaultHasher::new();
511    sys_path.hash(&mut hasher);
512    ProcessSpec {
513        program: setup.python.clone(),
514        args: vec![
515            // Not the working directory first: a root's file can't shadow what the runner imports (B178).
516            "-P".to_owned(),
517            // A thread a wait step starts stays its: what it prints goes to its log, and it can't
518            // start a process either (decision 336).
519            "-X".to_owned(),
520            "thread_inherit_context=1".to_owned(),
521            "-m".to_owned(),
522            "schedr.runner".to_owned(),
523            "watchers".to_owned(),
524        ],
525        env: setup
526            .agent_env
527            .iter()
528            .filter(|(name, _)| crate::env::is_allowed(name) || setup.pass_env.contains(name))
529            .map(|(k, v)| (k.clone(), v.clone()))
530            .collect(),
531        working_dir: setup.log_dir.clone(),
532        log_file: setup
533            .log_dir
534            .join(format!("watchers-{:016x}.log", hasher.finish())),
535        max_output_size: 64 * 1024,
536        mask,
537        start_timeout: setup.timeouts.runner_start,
538        output_drain: setup.timeouts.output_drain,
539    }
540}
541
542/// A watcher's place in its host, given up when dropped (a dropped attempt included).
543struct Entered {
544    hosts: WatcherHosts,
545    host: Arc<Host>,
546    watcher: u64,
547    messages: mpsc::Receiver<RunnerMessage>,
548    /// How long a cancel of it may take when no attempt waits for it any more.
549    grace: Duration,
550    left: bool,
551}
552
553impl WatcherHosts {
554    /// The hosts of a worker, counted in `metrics`.
555    #[must_use]
556    pub fn with_metrics(metrics: WatcherMetrics) -> Self {
557        Self {
558            metrics,
559            ..Self::default()
560        }
561    }
562
563    /// A place in the code set's host, started if it has none.
564    async fn enter(
565        &self,
566        setup: &WorkerSetup,
567        sys_path: &[String],
568        grace: Duration,
569    ) -> Result<Entered, LaunchError> {
570        self.watch_hosts(setup);
571        let mut hosts = self.hosts.lock().await;
572        let running = hosts.get(sys_path).filter(|host| host.alive()).cloned();
573        let host = if let Some(host) = running {
574            host
575        } else {
576            // Held from before it starts: nothing removes its copies under it.
577            self.code_set(sys_path, true);
578            let host = match Host::start(setup, sys_path, self).await {
579                Ok(host) => Arc::new(host),
580                Err(error) => {
581                    self.code_set(sys_path, false);
582                    return Err(error);
583                }
584            };
585            hosts.insert(sys_path.to_vec(), Arc::clone(&host));
586            host
587        };
588        let watcher = self.next_watcher.fetch_add(1, Ordering::Relaxed);
589        let (route, messages) = mpsc::channel(setup.timeouts.watcher_log_backlog.max(1));
590        host.routes
591            .lock()
592            .unwrap_or_else(PoisonError::into_inner)
593            .insert(watcher, route);
594        Ok(Entered {
595            hosts: self.clone(),
596            host,
597            watcher,
598            messages,
599            grace,
600            left: false,
601        })
602    }
603
604    /// From the first wait step on, looks at the hosts: what the heartbeat tells and the metrics
605    /// come from here, and all of them together are kept under `[watchers] memory_budget`. Past
606    /// it the largest is killed: no wait step can be blamed, as memory isn't told apart.
607    fn watch_hosts(&self, setup: &WorkerSetup) {
608        if self.watching.swap(true, Ordering::SeqCst) {
609            return;
610        }
611        let hosts = self.clone();
612        let watch = setup.memory.clone();
613        let budget = setup.timeouts.watcher_memory_budget;
614        tokio::spawn(async move {
615            let mut tick = tokio::time::interval(watch.interval);
616            tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
617            loop {
618                tick.tick().await;
619                let running: Vec<(Vec<String>, Arc<Host>)> = hosts
620                    .hosts
621                    .lock()
622                    .await
623                    .iter()
624                    .filter(|(_, host)| host.alive())
625                    .map(|(code, host)| (code.clone(), Arc::clone(host)))
626                    .collect();
627                let root = watch.proc_root.clone();
628                let pids: Vec<i32> = running.iter().map(|(_, host)| host.pid).collect();
629                let Ok(sizes) = tokio::task::spawn_blocking(move || {
630                    pids.iter()
631                        .map(|pid| crate::memory::group_memory(&root, *pid, true).unwrap_or(0))
632                        .collect::<Vec<u64>>()
633                })
634                .await
635                else {
636                    continue;
637                };
638                hosts.looked_at(&running, &sizes);
639                let used: u64 = sizes.iter().sum();
640                let largest = sizes.iter().enumerate().max_by_key(|(_, size)| **size);
641                if used > budget
642                    && let Some((index, _)) = largest
643                {
644                    let host = &running[index].1;
645                    tracing::warn!(pid = host.pid, used, budget, "killing a watcher host");
646                    set_why(
647                        &host.going,
648                        format!(
649                            "its host was killed: wait step hosts use {}, over `[watchers] \
650                             memory_budget` of {}",
651                            crate::memory::show_size(used),
652                            crate::memory::show_size(budget),
653                        ),
654                    );
655                    host.stop.notify_one();
656                }
657            }
658        });
659    }
660
661    /// Keeps what the hosts look like now, for the heartbeat and the metrics; code sets that
662    /// lost hosts stay after them, as what kills their hosts may kill them again.
663    fn looked_at(&self, running: &[(Vec<String>, Arc<Host>)], sizes: &[u64]) {
664        let mut lost = self
665            .lost
666            .lock()
667            .unwrap_or_else(PoisonError::into_inner)
668            .clone();
669        let (mut tied, mut untied) = (0_u64, 0_u64);
670        let mut reports = Vec::new();
671        for ((code, host), memory) in running.iter().zip(sizes) {
672            let stats = *host.stats.lock().unwrap_or_else(PoisonError::into_inner);
673            tied += u64::from(stats.tied_threads);
674            untied += u64::from(stats.threads - stats.tied_threads);
675            let wait_steps = host
676                .routes
677                .lock()
678                .unwrap_or_else(PoisonError::into_inner)
679                .len();
680            reports.push(pb::WatcherHost {
681                code: code_of(code),
682                wait_steps: u32::try_from(wait_steps).unwrap_or(u32::MAX),
683                threads: stats.threads,
684                tied_threads: stats.tied_threads,
685                memory_bytes: *memory,
686                hosts_lost: lost.remove(code).unwrap_or(0),
687            });
688        }
689        reports.extend(lost.iter().map(|(code, count)| pb::WatcherHost {
690            code: code_of(code),
691            hosts_lost: *count,
692            ..pb::WatcherHost::default()
693        }));
694        self.metrics.set_threads(tied, untied);
695        self.metrics
696            .hosts
697            .set(i64::try_from(running.len()).unwrap_or(i64::MAX));
698        self.metrics
699            .memory
700            .set(i64::try_from(sizes.iter().sum::<u64>()).unwrap_or(i64::MAX));
701        *self.reports.lock().unwrap_or_else(PoisonError::into_inner) = reports;
702    }
703
704    /// The hosts as last looked at, for the heartbeat.
705    #[must_use]
706    pub fn reports(&self) -> Vec<pb::WatcherHost> {
707        self.reports
708            .lock()
709            .unwrap_or_else(PoisonError::into_inner)
710            .clone()
711    }
712
713    fn host_lost(&self, sys_path: &[String]) {
714        self.metrics
715            .hosts_lost
716            .get_or_create(&CodeLabels {
717                code: code_of(sys_path),
718            })
719            .inc();
720        *self
721            .lost
722            .lock()
723            .unwrap_or_else(PoisonError::into_inner)
724            .entry(sys_path.to_vec())
725            .or_default() += 1;
726    }
727
728    /// Takes a watcher out; a host left without any stops.
729    async fn leave(&self, host: &Arc<Host>, watcher: u64) {
730        host.unnamed(watcher);
731        let mut hosts = self.hosts.lock().await;
732        let empty = {
733            let mut routes = host.routes.lock().unwrap_or_else(PoisonError::into_inner);
734            routes.remove(&watcher);
735            routes.is_empty()
736        };
737        if empty {
738            retire(&host.going);
739            host.stop.notify_one();
740            let mut gone = None;
741            hosts.retain(|key, known| {
742                let keep = !Arc::ptr_eq(known, host);
743                if !keep {
744                    gone = Some(key.clone());
745                }
746                keep
747            });
748            if let Some(key) = gone {
749                self.code_set(&key, false);
750            }
751        }
752    }
753
754    fn code_set(&self, sys_path: &[String], running: bool) {
755        let mut sets = self
756            .code_sets
757            .lock()
758            .unwrap_or_else(PoisonError::into_inner);
759        if running {
760            sets.insert(sys_path.to_vec());
761        } else {
762            sets.remove(sys_path);
763        }
764    }
765
766    /// The folders of the code copies hosts run: they outlive the attempt that started them,
767    /// when a poke moved.
768    #[must_use]
769    pub fn code_in_use(&self) -> Vec<String> {
770        let sets = self
771            .code_sets
772            .lock()
773            .unwrap_or_else(PoisonError::into_inner);
774        sets.iter()
775            .flatten()
776            .filter_map(|dir| {
777                let name = std::path::Path::new(dir).file_name()?;
778                Some(name.to_string_lossy().into_owned())
779            })
780            .collect()
781    }
782
783    /// The worker's newest copy of each DAG root: running pokes move to it (decision 335).
784    pub fn code_changed(&self, copies: &Copies) {
785        self.code_channel().send_if_modified(|now| {
786            let changed = now != copies;
787            if changed {
788                // Code no longer current has its lost hosts told by the metric from here on.
789                let old: Vec<&PathBuf> = now
790                    .values()
791                    .filter(|copy| !copies.values().any(|current| current == *copy))
792                    .collect();
793                self.lost
794                    .lock()
795                    .unwrap_or_else(PoisonError::into_inner)
796                    .retain(|code, _| {
797                        !code
798                            .iter()
799                            .any(|dir| old.iter().any(|copy| copy.as_os_str() == dir.as_str()))
800                    });
801                now.clone_from(copies);
802            }
803            changed
804        });
805    }
806
807    fn code_channel(&self) -> watch::Sender<Copies> {
808        self.code
809            .lock()
810            .unwrap_or_else(PoisonError::into_inner)
811            .get_or_insert_with(|| watch::channel(Copies::new()).0)
812            .clone()
813    }
814
815    /// How many hosts run, for tests and metrics.
816    pub async fn running(&self) -> usize {
817        self.hosts.lock().await.len()
818    }
819}
820
821impl Entered {
822    async fn leave(mut self) {
823        self.left = true;
824        self.hosts.leave(&self.host, self.watcher).await;
825    }
826}
827
828impl Drop for Entered {
829    fn drop(&mut self) {
830        if self.left {
831            return;
832        }
833        // No attempt waits for it any more (it ended first, or its agent is going away): it
834        // is still cancelled and held to its grace, as Python can't cancel what doesn't yield.
835        let _ = self.host.outbox.send(AgentMessage::CancelWatcher {
836            watcher: self.watcher,
837        });
838        let Ok(runtime) = tokio::runtime::Handle::try_current() else {
839            return;
840        };
841        let hosts = self.hosts.clone();
842        let host = Arc::clone(&self.host);
843        let watcher = self.watcher;
844        let grace = self.grace;
845        let mut messages = std::mem::replace(&mut self.messages, mpsc::channel(1).1);
846        runtime.spawn(async move {
847            let ended = async {
848                while let Some(message) = messages.recv().await {
849                    if ends_a_watcher(&message) {
850                        return;
851                    }
852                }
853            };
854            if tokio::time::timeout(grace, ended).await.is_err() {
855                host.kill_for(watcher);
856            }
857            hosts.leave(&host, watcher).await;
858        });
859    }
860}
861
862impl Entered {
863    /// Its grace, for its host to hold what it left running to.
864    fn cancel_grace_ms(&self) -> u64 {
865        millis(self.grace)
866    }
867}
868
869/// Whether a watcher says nothing after this.
870const fn ends_a_watcher(message: &RunnerMessage) -> bool {
871    matches!(
872        message,
873        RunnerMessage::TaskSucceeded { .. }
874            | RunnerMessage::TaskFailed { .. }
875            | RunnerMessage::WatcherCancelled
876            | RunnerMessage::WatcherMoved
877    )
878}
879
880/// What a watcher printed, masked, in its attempt's log.
881struct AttemptLog<'a> {
882    mask: &'a Mask,
883    file: tokio::fs::File,
884    stdout: Option<MaskStream<'a>>,
885    stderr: Option<MaskStream<'a>>,
886}
887
888impl<'a> AttemptLog<'a> {
889    async fn open(spec: &'a ProcessSpec) -> std::io::Result<Self> {
890        let file = crate::process::open_log_file(&spec.log_file).await?;
891        let stream = || spec.mask.0.as_deref().map(MaskSet::stream);
892        Ok(Self {
893            mask: &spec.mask,
894            file,
895            stdout: stream(),
896            stderr: stream(),
897        })
898    }
899
900    async fn write(&mut self, stream: OutputStream, text: &str) {
901        let masking = match stream {
902            OutputStream::Stdout => &mut self.stdout,
903            OutputStream::Stderr => &mut self.stderr,
904        };
905        let masked = match masking {
906            Some(masking) => masking.push(text.as_bytes()),
907            None => text.as_bytes().to_vec(),
908        };
909        let _ = self.file.write_all(&masked).await;
910    }
911
912    /// A line of the agent's, masked: it may quote what new code raised.
913    async fn note(&mut self, text: &str) {
914        let masked = match &self.mask.0 {
915            Some(mask) => mask.mask(text.as_bytes()),
916            None => text.as_bytes().to_vec(),
917        };
918        let _ = self.file.write_all(&masked).await;
919    }
920
921    async fn finish(mut self) {
922        for masking in [&mut self.stdout, &mut self.stderr].into_iter().flatten() {
923            let rest = masking.finish();
924            let _ = self.file.write_all(&rest).await;
925        }
926        let _ = self.file.flush().await;
927    }
928}
929
930/// Answers what watchers ask. Answers wait on a secret storage, so none holds up the rest, a
931/// cancel's end above all; they stop when it is dropped.
932struct Answers {
933    secrets: Option<Arc<AttemptSecrets>>,
934    handles: Option<Arc<AttemptHandles>>,
935    events: Option<EventSink>,
936    api: Option<crate::api::ApiCaller>,
937    pending: tokio::task::JoinSet<()>,
938    /// Whether the log says already that a key held a secret (B189).
939    told_masked_key: bool,
940}
941
942/// What answers a watcher's requests: its task's secrets, handles, event sink and API caller.
943type AnswerParts = (
944    Option<Arc<AttemptSecrets>>,
945    Option<Arc<AttemptHandles>>,
946    Option<EventSink>,
947    Option<crate::api::ApiCaller>,
948);
949
950impl Answers {
951    fn new((secrets, handles, events, api): AnswerParts) -> Self {
952        Self {
953            secrets,
954            handles,
955            events,
956            api,
957            pending: tokio::task::JoinSet::new(),
958            told_masked_key: false,
959        }
960    }
961
962    /// Whether an event's key, or a batch item's, holds a secret the trigger read: see
963    /// [`holds_secret`].
964    fn masks_a_key(&self, key: &str, data: &serde_json::Value, batched: bool) -> bool {
965        self.secrets
966            .as_ref()
967            .is_some_and(|secrets| holds_secret(&secrets.mask, key, data, batched))
968    }
969
970    /// Takes what a watcher sent; gives back what isn't for it, which is the caller's.
971    async fn serve(
972        &mut self,
973        message: RunnerMessage,
974        host: &Arc<Host>,
975        watcher: u64,
976        log: &mut AttemptLog<'_>,
977    ) -> Option<RunnerMessage> {
978        if let RunnerMessage::WatcherLog { stream, text } = &message {
979            log.write(*stream, text).await;
980            return None;
981        }
982        if let RunnerMessage::TriggerPoked { error } = message {
983            if let Some(events) = &self.events {
984                let error = match self.secrets.as_ref().map(|s| &s.mask) {
985                    Some(mask) if !mask.is_empty() => error.map(|why| mask.mask_text(&why)),
986                    _ => error,
987                };
988                (events.poked)(error);
989            }
990            return None;
991        }
992        if let RunnerMessage::TriggerEvent { key, data, at } = message {
993            let Some(events) = &self.events else {
994                return None;
995            };
996            // Stored masked: said once in the trigger's log (B189, the user's: no refusal).
997            if !self.told_masked_key && self.masks_a_key(&key, &data, events.batched) {
998                self.told_masked_key = true;
999                log.write(OutputStream::Stderr, MASKED_KEY).await;
1000            }
1001            // What a run reads of it, and people see, as they would of an output.
1002            let (key, data) = match self.secrets.as_ref().map(|s| &s.mask) {
1003                Some(mask) if !mask.is_empty() => (mask.mask_text(&key), mask.mask_json(&data)),
1004                _ => (key, data),
1005            };
1006            let stored = (events.found)(FoundEvent { key, data, at });
1007            let host = Arc::clone(host);
1008            self.pending.spawn(async move {
1009                // Dropped: it stopped, and nothing waits for this any more.
1010                if stored.await.is_ok() {
1011                    let _ = host.outbox.send(AgentMessage::ToWatcher {
1012                        watcher,
1013                        message: Box::new(AgentMessage::EventStored),
1014                    });
1015                }
1016            });
1017            return None;
1018        }
1019        if !matches!(
1020            message,
1021            RunnerMessage::SecretGet { .. }
1022                | RunnerMessage::HandleAdd { .. }
1023                | RunnerMessage::ConnectionGet { .. }
1024                | RunnerMessage::ApiCall { .. }
1025        ) {
1026            return Some(message);
1027        }
1028        let secrets = self.secrets.clone();
1029        let handles = self.handles.clone();
1030        let api = self.api.clone();
1031        let host = Arc::clone(host);
1032        self.pending.spawn(async move {
1033            let answer = answer_to(
1034                message,
1035                secrets.as_deref(),
1036                handles.as_deref(),
1037                api.as_ref(),
1038            )
1039            .await;
1040            let _ = host.outbox.send(AgentMessage::ToWatcher {
1041                watcher,
1042                message: Box::new(answer),
1043            });
1044        });
1045        None
1046    }
1047}
1048
1049async fn answer_to(
1050    message: RunnerMessage,
1051    secrets: Option<&AttemptSecrets>,
1052    handles: Option<&AttemptHandles>,
1053    api: Option<&crate::api::ApiCaller>,
1054) -> AgentMessage {
1055    match message {
1056        RunnerMessage::ApiCall {
1057            method,
1058            path,
1059            body,
1060            idempotency_key,
1061        } => {
1062            let request = crate::api::ApiRequest {
1063                method,
1064                path,
1065                body,
1066                idempotency_key,
1067                masked: false,
1068            }
1069            .masked_by(secrets);
1070            crate::api::runner_answer(api, request).await
1071        }
1072        RunnerMessage::SecretGet { secret } => secret_answer(secrets, &secret).await,
1073        RunnerMessage::ConnectionGet { name } => connection_answer(secrets, &name).await,
1074        RunnerMessage::HandleAdd { handle } => {
1075            let added = match handles {
1076                Some(handles) => handles.add(handle).await,
1077                None => Err(HandleError::NoCleanup),
1078            };
1079            added.map_or_else(
1080                |error| AgentMessage::HandleRefused {
1081                    message: error.to_string(),
1082                },
1083                |()| AgentMessage::HandleAdded,
1084            )
1085        }
1086        other => AgentMessage::Refused {
1087            reason: format!("not a question: {}", crate::channel::describe(&other)),
1088        },
1089    }
1090}
1091
1092/// A poke's move to new code (decision 335), under way.
1093enum Stage {
1094    /// Its new host is being found or started: nothing waits for that.
1095    Entering(tokio::task::JoinHandle<Result<Entered, LaunchError>>),
1096    /// Its place there, making no call until told; `stopping`: it could start, and the old
1097    /// one was told to stop.
1098    Entered { to: Entered, stopping: bool },
1099}
1100
1101struct Moving {
1102    stage: Stage,
1103    /// What it runs there.
1104    request: TaskRequest,
1105    /// The new code's hash.
1106    code_hash: Option<String>,
1107}
1108
1109/// A poke moving to new code when there is some; what never moves has none of these.
1110struct Poke<'a> {
1111    setup: &'a WorkerSetup,
1112    hosts: &'a WatcherHosts,
1113    mask: Mask,
1114    grace: Duration,
1115    /// As it runs now.
1116    request: TaskRequest,
1117    code: watch::Receiver<Copies>,
1118    /// The code last tried: new code that can't start it isn't tried again.
1119    tried: Vec<String>,
1120    max_wait: Option<Duration>,
1121    started: Instant,
1122    moving: Option<Moving>,
1123}
1124
1125impl Poke<'_> {
1126    /// Starts a move, if there is new code it hasn't tried.
1127    fn begin_move(&mut self) {
1128        if self.moving.is_some() {
1129            return;
1130        }
1131        let copies = self.code.borrow_and_update().clone();
1132        let Some(root_dir) = copies.get(&self.request.dag_file.root) else {
1133            return;
1134        };
1135        let sys_path = self.setup.sys_path_at(&copies);
1136        if sys_path == self.tried {
1137            return;
1138        }
1139        self.tried.clone_from(&sys_path);
1140        // A copy's folder is its hash (`crate::scan`).
1141        let code_hash = root_dir
1142            .file_name()
1143            .map(|name| name.to_string_lossy().replacen('-', ":", 1));
1144        let mut request = self.request.clone();
1145        request.dag_file.root_dir = root_dir.to_string_lossy().into_owned();
1146        request.sys_path.clone_from(&sys_path);
1147        let (hosts, setup, grace) = (self.hosts.clone(), self.setup.clone(), self.grace);
1148        let entering = tokio::spawn(async move { hosts.enter(&setup, &sys_path, grace).await });
1149        self.moving = Some(Moving {
1150            stage: Stage::Entering(entering),
1151            request,
1152            code_hash,
1153        });
1154    }
1155
1156    /// Its place in the new code's host came, or didn't: it starts there, not calling yet.
1157    async fn entered_new_host(
1158        &mut self,
1159        result: Result<Result<Entered, LaunchError>, tokio::task::JoinError>,
1160        log: &mut AttemptLog<'_>,
1161    ) {
1162        let Some(moving) = self.moving.as_mut() else {
1163            return;
1164        };
1165        match result {
1166            Ok(Ok(to)) => {
1167                // Before it can print anything there.
1168                if let Some(mask) = &self.mask.0 {
1169                    mask.also_in(Arc::clone(&to.host.mask));
1170                }
1171                let _ = to.host.outbox.send(AgentMessage::StartWatcher {
1172                    watcher: to.watcher,
1173                    task: Box::new(moving.request.clone()),
1174                    cancel_grace_ms: to.cancel_grace_ms(),
1175                    moved_in: true,
1176                });
1177                moving.stage = Stage::Entered {
1178                    to,
1179                    stopping: false,
1180                };
1181            }
1182            Ok(Err(error)) => self.stays(&error.to_string(), log).await,
1183            Err(error) => self.stays(&error.to_string(), log).await,
1184        }
1185    }
1186
1187    /// New code can't start it: it stays on its code.
1188    async fn stays(&mut self, why: &str, log: &mut AttemptLog<'_>) {
1189        log.note(&format!(
1190            "new code can't start this wait step, it stays on its code: {why}\n"
1191        ))
1192        .await;
1193        if let Some(Moving {
1194            stage: Stage::Entered { to, .. },
1195            ..
1196        }) = self.moving.take()
1197        {
1198            to.leave().await;
1199        }
1200    }
1201
1202    /// A message of the new code's host, about a move under way.
1203    async fn on_new_code_message(
1204        &mut self,
1205        message: Option<RunnerMessage>,
1206        old: &Entered,
1207        answers: &mut Answers,
1208        log: &mut AttemptLog<'_>,
1209    ) {
1210        let Some(Moving {
1211            stage: Stage::Entered { to, stopping },
1212            ..
1213        }) = self.moving.as_mut()
1214        else {
1215            return;
1216        };
1217        let why = match message {
1218            Some(RunnerMessage::TaskImported) if !*stopping => {
1219                *stopping = true;
1220                let _ = old.host.outbox.send(AgentMessage::MoveWatcher {
1221                    watcher: old.watcher,
1222                });
1223                return;
1224            }
1225            Some(RunnerMessage::TaskFailed { error, .. }) => {
1226                format!("{}: {}", error.exception, error.message)
1227            }
1228            None => "its host ended".to_owned(),
1229            Some(other) => {
1230                let (host, watcher) = (Arc::clone(&to.host), to.watcher);
1231                let _ = answers.serve(other, &host, watcher, log).await;
1232                return;
1233            }
1234        };
1235        self.stays(&why, log).await;
1236    }
1237
1238    fn left_of_max_wait(&self) -> Option<u64> {
1239        self.max_wait.map(|wait| {
1240            u64::try_from(wait.saturating_sub(self.started.elapsed()).as_millis())
1241                .unwrap_or(u64::MAX)
1242        })
1243    }
1244}
1245
1246/// Where a watcher is now, for what stops it from outside.
1247struct Place {
1248    host: StdMutex<Arc<Host>>,
1249    watcher: AtomicU64,
1250    /// It is being cancelled: it doesn't move any more.
1251    cancelling: AtomicBool,
1252    /// The hash of the code it moved to, if it moved.
1253    moved_to: StdMutex<Option<String>>,
1254    /// What it runs now: a move changes it.
1255    request: StdMutex<TaskRequest>,
1256    /// Started again: its first call waits to be told what is left of its time since this.
1257    going_when_imported: StdMutex<Option<Instant>>,
1258}
1259
1260impl Place {
1261    /// Its place, having told the host to start it; `running_since`: it started again, and its
1262    /// first call waits for its import, which takes none of its time left.
1263    fn started(entered: &Entered, request: &TaskRequest, running_since: Option<Instant>) -> Self {
1264        let _ = entered.host.outbox.send(AgentMessage::StartWatcher {
1265            watcher: entered.watcher,
1266            task: Box::new(request.clone()),
1267            cancel_grace_ms: entered.cancel_grace_ms(),
1268            moved_in: running_since.is_some(),
1269        });
1270        entered.host.named(entered.watcher, request);
1271        Self {
1272            host: StdMutex::new(Arc::clone(&entered.host)),
1273            watcher: AtomicU64::new(entered.watcher),
1274            cancelling: AtomicBool::new(false),
1275            moved_to: StdMutex::new(None),
1276            request: StdMutex::new(request.clone()),
1277            going_when_imported: StdMutex::new(running_since),
1278        }
1279    }
1280
1281    /// Lets one started again make its first call, with what is left of its time.
1282    fn go_when_imported(&self, entered: &Entered) {
1283        let since = self
1284            .going_when_imported
1285            .lock()
1286            .unwrap_or_else(PoisonError::into_inner)
1287            .take();
1288        let Some(since) = since else {
1289            return;
1290        };
1291        let request = self.request.lock().unwrap_or_else(PoisonError::into_inner);
1292        let max_wait_ms = match request.task.kind {
1293            TaskKind::Sensor { max_wait_ms, .. } => max_wait_ms,
1294            _ => None,
1295        };
1296        let _ = entered.host.outbox.send(AgentMessage::GoWatcher {
1297            watcher: entered.watcher,
1298            max_wait_ms: max_wait_ms.map(|max| max.saturating_sub(millis(since.elapsed()))),
1299        });
1300    }
1301
1302    fn host(&self) -> Arc<Host> {
1303        Arc::clone(&self.host.lock().unwrap_or_else(PoisonError::into_inner))
1304    }
1305
1306    fn moved_to(&self) -> Option<String> {
1307        self.moved_to
1308            .lock()
1309            .unwrap_or_else(PoisonError::into_inner)
1310            .take()
1311    }
1312
1313    fn cancel(&self) {
1314        self.cancelling.store(true, Ordering::SeqCst);
1315        let _ = self.host().outbox.send(AgentMessage::CancelWatcher {
1316            watcher: self.watcher.load(Ordering::SeqCst),
1317        });
1318    }
1319}
1320
1321/// Serves a watcher until its result, as a task's runner is served, moving a poke to new code
1322/// on the way; `None` if its host ended. Leaves its host on any end but being dropped.
1323async fn conversation(
1324    mut entered: Entered,
1325    mut poke: Option<Poke<'_>>,
1326    place: &Place,
1327    mut answers: Answers,
1328    log: &mut AttemptLog<'_>,
1329) -> Option<RunnerMessage> {
1330    let ended = loop {
1331        let still = !place.cancelling.load(Ordering::SeqCst);
1332        if let (Some(poke), true) = (&mut poke, still) {
1333            poke.begin_move();
1334        }
1335        let (code, moving) = match &mut poke {
1336            Some(poke) => (Some(&mut poke.code), poke.moving.as_mut()),
1337            None => (None, None),
1338        };
1339        let new_code = async {
1340            match code {
1341                Some(code) if still => {
1342                    if code.changed().await.is_err() {
1343                        std::future::pending::<()>().await;
1344                    }
1345                }
1346                _ => std::future::pending().await,
1347            }
1348        };
1349        let from_new = async {
1350            match moving.map(|moving| &mut moving.stage) {
1351                Some(Stage::Entering(entering)) => Happened::Entered(entering.await),
1352                Some(Stage::Entered { to, .. }) => Happened::New(to.messages.recv().await),
1353                None => std::future::pending().await,
1354            }
1355        };
1356        let happened = tokio::select! {
1357            biased;
1358            message = entered.messages.recv() => Happened::Old(message),
1359            happened = from_new => happened,
1360            () = new_code => Happened::NewCode,
1361            // A finished answer needs no one's attention.
1362            Some(_) = answers.pending.join_next() => Happened::NewCode,
1363        };
1364        match happened {
1365            Happened::NewCode => {}
1366            Happened::Old(Some(RunnerMessage::TaskImported)) => place.go_when_imported(&entered),
1367            Happened::Old(None) => break None,
1368            Happened::Old(Some(RunnerMessage::WatcherMoved)) => {
1369                if place.cancelling.load(Ordering::SeqCst) {
1370                    break Some(RunnerMessage::WatcherCancelled);
1371                }
1372                let Some(poke) = poke.as_mut() else {
1373                    break None;
1374                };
1375                match moved(poke, log).await {
1376                    Ok(to) => {
1377                        place
1378                            .request
1379                            .lock()
1380                            .unwrap_or_else(PoisonError::into_inner)
1381                            .clone_from(&poke.request);
1382                        *place.host.lock().unwrap_or_else(PoisonError::into_inner) =
1383                            Arc::clone(&to.0.host);
1384                        place.watcher.store(to.0.watcher, Ordering::SeqCst);
1385                        if to.1.is_some() {
1386                            *place
1387                                .moved_to
1388                                .lock()
1389                                .unwrap_or_else(PoisonError::into_inner) = to.1;
1390                        }
1391                        let old = std::mem::replace(&mut entered, to.0);
1392                        old.leave().await;
1393                    }
1394                    Err(why) => {
1395                        log.note(&format!("this wait step can't go on: {why}\n"))
1396                            .await;
1397                        break None;
1398                    }
1399                }
1400            }
1401            Happened::Old(Some(message)) => {
1402                let host = Arc::clone(&entered.host);
1403                if let Some(message) = answers.serve(message, &host, entered.watcher, log).await {
1404                    break Some(message);
1405                }
1406            }
1407            Happened::Entered(result) => {
1408                if let Some(poke) = poke.as_mut() {
1409                    poke.entered_new_host(result, log).await;
1410                }
1411            }
1412            Happened::New(message) => {
1413                if let Some(poke) = poke.as_mut() {
1414                    poke.on_new_code_message(message, &entered, &mut answers, log)
1415                        .await;
1416                }
1417            }
1418        }
1419    };
1420    drop(poke);
1421    entered.leave().await;
1422    ended
1423}
1424
1425/// The old host stopped its poke between calls: it goes on where it was to move to, or, the new
1426/// host gone by then, on its own code again; its deadline is kept either way. Gives its new
1427/// place, and the hash of the code it moved to.
1428async fn moved(
1429    poke: &mut Poke<'_>,
1430    log: &mut AttemptLog<'_>,
1431) -> Result<(Entered, Option<String>), String> {
1432    let left = poke.left_of_max_wait();
1433    if let Some(Moving {
1434        stage: Stage::Entered { to, .. },
1435        request,
1436        code_hash,
1437    }) = poke.moving.take()
1438    {
1439        to.host.named(to.watcher, &request);
1440        let _ = to.host.outbox.send(AgentMessage::GoWatcher {
1441            watcher: to.watcher,
1442            max_wait_ms: left,
1443        });
1444        log.note("moved to new code\n").await;
1445        poke.request = request;
1446        return Ok((to, code_hash));
1447    }
1448    let to = poke
1449        .hosts
1450        .enter(poke.setup, &poke.request.sys_path, poke.grace)
1451        .await
1452        .map_err(|error| error.to_string())?;
1453    let _ = to.host.outbox.send(AgentMessage::StartWatcher {
1454        watcher: to.watcher,
1455        task: Box::new(poke.request.clone()),
1456        cancel_grace_ms: to.cancel_grace_ms(),
1457        moved_in: true,
1458    });
1459    to.host.named(to.watcher, &poke.request);
1460    let _ = to.host.outbox.send(AgentMessage::GoWatcher {
1461        watcher: to.watcher,
1462        max_wait_ms: left,
1463    });
1464    Ok((to, None))
1465}
1466
1467enum Happened {
1468    Old(Option<RunnerMessage>),
1469    New(Option<RunnerMessage>),
1470    Entered(Result<Result<Entered, LaunchError>, tokio::task::JoinError>),
1471    NewCode,
1472}
1473
1474/// Runs a wait step in its code set's host: `spawned` gets the host's process ID. Cancelling,
1475/// a timeout and a drain cancel its coroutine; one that doesn't end in its grace time has its
1476/// whole host killed, as Python can't cancel what doesn't yield.
1477///
1478/// # Errors
1479///
1480/// [`LaunchError`] if the host can't be started or its log can't be opened.
1481pub async fn run_watcher(
1482    hosts: &WatcherHosts,
1483    setup: &WorkerSetup,
1484    process: &ProcessSpec,
1485    task: PythonTask,
1486    limits: Limits,
1487    mut stop: Stops,
1488    spawned: impl FnOnce(i32),
1489) -> Result<Ran, LaunchError> {
1490    let PythonTask {
1491        mut request,
1492        secrets,
1493        handles,
1494        events,
1495        api,
1496    } = task;
1497    let parts = (secrets, handles, events, api);
1498    let started = Instant::now();
1499    let deadline = limits
1500        .timeout
1501        .map(|timeout| tokio::time::Instant::from_std(started) + timeout);
1502    let ran = |supervised, runner_result| {
1503        Ran::with_no_process(supervised, runner_result, started.elapsed())
1504    };
1505    let mut log = AttemptLog::open(process)
1506        .await
1507        .map_err(|source| LaunchError::Start {
1508            what: process.log_file.display().to_string(),
1509            source,
1510        })?;
1511    let mut spawned = Some(spawned);
1512    let mut moved_to = None;
1513    let mut again = false;
1514    loop {
1515        let sys_path = request.sys_path.clone();
1516        let entering = hosts.enter(setup, &sys_path, limits.grace);
1517        let entered = match unless_stopped(entering, Some((&mut stop, deadline))).await {
1518            Ok(entered) => entered?,
1519            Err(reason) => {
1520                let supervised = Supervised {
1521                    termination: Termination::Unknown,
1522                    stopped: Some(reason),
1523                    killed: false,
1524                };
1525                return Ok(ran(supervised, None));
1526            }
1527        };
1528        if let Some(spawned) = spawned.take() {
1529            spawned(entered.host.pid);
1530        }
1531        if let Some(mask) = &process.mask.0 {
1532            mask.also_in(Arc::clone(&entered.host.mask));
1533        }
1534        let poke = poke_of(
1535            hosts,
1536            setup,
1537            &request,
1538            started,
1539            (&process.mask, limits.grace),
1540        );
1541        // Its time starts when it does; starting again, it runs on.
1542        let starts = again.then_some(started);
1543        let place = Place::started(&entered, &request, starts);
1544        let (message, reason, killed) = {
1545            let answers = Answers::new(parts.clone());
1546            let talking = conversation(entered, poke, &place, answers, &mut log);
1547            let talking = Box::pin(talking);
1548            until_ended(talking, &mut stop, deadline, &place, limits).await
1549        };
1550        moved_to = place.moved_to().or(moved_to);
1551        let (message, host_lost) = if message.is_none() && reason.is_none() {
1552            let trigger = place_is_trigger(&place);
1553            match after_host_ended(&place, setup, trigger).await {
1554                AfterHost::Fails(message) => (Some(message), None),
1555                AfterHost::Lost(why) => (None, Some(why)),
1556                AfterHost::StartsAgain => {
1557                    // Not its doing: its time runs on, and it uses no retry.
1558                    log.note(STARTS_AGAIN).await;
1559                    hosts.metrics.restarts.inc();
1560                    request = place
1561                        .request
1562                        .into_inner()
1563                        .unwrap_or_else(PoisonError::into_inner);
1564                    again = true;
1565                    continue;
1566                }
1567            }
1568        } else {
1569            (message, None)
1570        };
1571        log.finish().await;
1572        let struck = place
1573            .host()
1574            .going()
1575            .0
1576            .is_some_and(|blamed| blamed.watcher == place.watcher.load(Ordering::SeqCst));
1577        let supervised = Supervised {
1578            termination: termination_of(message.as_ref(), killed, &place).await,
1579            stopped: reason,
1580            killed,
1581        };
1582        let result = message.filter(|message| !matches!(message, RunnerMessage::WatcherCancelled));
1583        return Ok(Ran {
1584            moved_to,
1585            host_lost,
1586            struck,
1587            ..ran(supervised, result)
1588        });
1589    }
1590}
1591
1592const STARTS_AGAIN: &str =
1593    "another wait step had its host killed: this one starts again on a new host\n";
1594
1595/// What a wait step's host's end, with no result from it, means for it.
1596enum AfterHost {
1597    /// It is to blame.
1598    Fails(RunnerMessage),
1599    /// Another was.
1600    StartsAgain,
1601    /// None was: why it ended.
1602    Lost(String),
1603}
1604
1605async fn after_host_ended(place: &Place, setup: &WorkerSetup, trigger: bool) -> AfterHost {
1606    let host = place.host();
1607    let termination = ended_host(&host).await;
1608    match host.going() {
1609        (Some(blamed), _) if blamed.watcher == place.watcher.load(Ordering::SeqCst) => {
1610            AfterHost::Fails(blocked(setup, blamed.stack))
1611        }
1612        // The master knows its bookmark: from there, rather than from what it started with.
1613        (Some(_), _) if trigger => {
1614            AfterHost::Lost("its host was killed for another watcher on it".to_owned())
1615        }
1616        (Some(_), _) => AfterHost::StartsAgain,
1617        (None, why) => {
1618            let why = why.unwrap_or_else(|| format!("its host ended: {termination:?}"));
1619            let names = host.names();
1620            AfterHost::Lost(format!(
1621                "{why}\nNo wait step can be blamed. On its host: {names}"
1622            ))
1623        }
1624    }
1625}
1626
1627fn place_is_trigger(place: &Place) -> bool {
1628    place
1629        .request
1630        .lock()
1631        .unwrap_or_else(PoisonError::into_inner)
1632        .trigger
1633        .is_some()
1634}
1635
1636/// The end of a wait step that held its host's event loop.
1637fn blocked(setup: &WorkerSetup, stack: Option<String>) -> RunnerMessage {
1638    let limit = setup.timeouts.watcher_block_limit;
1639    RunnerMessage::TaskFailed {
1640        error: ErrorSummary {
1641            exception: "BlockedEventLoop".to_owned(),
1642            message: stack.as_ref().map_or_else(
1643                || "it wouldn't end in its grace time, so its host was killed".to_owned(),
1644                |_| {
1645                    format!(
1646                        "it didn't reach an `await` within `[watchers] block_limit` ({} s), \
1647                         holding up every wait step on its host. Use an async client or \
1648                         `asyncio.to_thread`",
1649                        limit.as_secs_f64()
1650                    )
1651                },
1652            ),
1653            traceback: stack.unwrap_or_default(),
1654        },
1655        kind: Some(schedr_model::runner::BLOCKED_EVENT_LOOP.to_owned()),
1656    }
1657}
1658
1659/// Waits for a watcher's end, cancelling it at the first reason to stop. Gives its last message,
1660/// the reason, and whether its host had to be killed.
1661async fn until_ended(
1662    mut talking: impl Future<Output = Option<RunnerMessage>> + Unpin,
1663    stop: &mut Stops,
1664    deadline: Option<tokio::time::Instant>,
1665    place: &Place,
1666    limits: Limits,
1667) -> (Option<RunnerMessage>, Option<StopReason>, bool) {
1668    let until = async {
1669        match deadline {
1670            Some(deadline) => tokio::time::sleep_until(deadline).await,
1671            None => std::future::pending().await,
1672        }
1673    };
1674    let reason = tokio::select! {
1675        biased;
1676        reason = stop.next_reason() => reason,
1677        () = until => StopReason::TimedOut,
1678        message = &mut talking => return (message, None, false),
1679    };
1680    place.cancel();
1681    let (message, killed) = cancelled(place, &mut talking, stop, limits, reason).await;
1682    (message, Some(reason), killed)
1683}
1684
1685/// What a watcher's end stands for, as a process's would.
1686async fn termination_of(
1687    message: Option<&RunnerMessage>,
1688    killed: bool,
1689    place: &Place,
1690) -> Termination {
1691    match message {
1692        Some(RunnerMessage::TaskSucceeded { .. }) => Termination::Exited(0),
1693        Some(RunnerMessage::TaskFailed { .. }) => Termination::Exited(FAILED_EXIT_CODE),
1694        Some(RunnerMessage::WatcherCancelled) => Termination::Signaled(TERMINATED),
1695        Some(_) => Termination::Unknown,
1696        None if killed => Termination::Signaled(KILLED),
1697        None => ended_host(&place.host()).await,
1698    }
1699}
1700
1701/// What moves a `@sensor.poke` to new code; a `@sensor` holds its progress, and never moves.
1702fn poke_of<'a>(
1703    hosts: &'a WatcherHosts,
1704    setup: &'a WorkerSetup,
1705    request: &TaskRequest,
1706    started: Instant,
1707    (mask, grace): (&Mask, Duration),
1708) -> Option<Poke<'a>> {
1709    // New code starts a trigger again from its bookmark, as the master tells it.
1710    if request.trigger.is_some() {
1711        return None;
1712    }
1713    let TaskKind::Sensor {
1714        mode: SensorMode::Poke,
1715        max_wait_ms,
1716        ..
1717    } = request.task.kind
1718    else {
1719        return None;
1720    };
1721    Some(Poke {
1722        setup,
1723        hosts,
1724        mask: mask.clone(),
1725        grace,
1726        request: request.clone(),
1727        code: hosts.code_channel().subscribe(),
1728        tried: request.sys_path.clone(),
1729        max_wait: max_wait_ms.map(Duration::from_millis),
1730        started,
1731        moving: None,
1732    })
1733}
1734
1735/// How the host's end was told; its watchers are told after it.
1736async fn ended_host(host: &Host) -> Termination {
1737    let mut ended = host.ended.clone();
1738    match ended.wait_for(Option::is_some).await {
1739        Ok(termination) => (*termination).unwrap_or(Termination::Unknown),
1740        Err(_) => Termination::Unknown,
1741    }
1742}
1743
1744/// Waits for a cancelled watcher to end, for its grace time: a later reason can only hurry it,
1745/// as for a process. Past it the host is killed. Returns its last message and whether it was.
1746async fn cancelled(
1747    place: &Place,
1748    talking: &mut (impl Future<Output = Option<RunnerMessage>> + Unpin),
1749    stop: &mut Stops,
1750    limits: Limits,
1751    reason: StopReason,
1752) -> (Option<RunnerMessage>, bool) {
1753    let grace = if reason == StopReason::Interrupted {
1754        limits.interrupt_grace
1755    } else {
1756        limits.grace
1757    };
1758    let mut kill_at = tokio::time::Instant::now() + grace;
1759    loop {
1760        tokio::select! {
1761            biased;
1762            later = stop.next_reason() => {
1763                if later == StopReason::Interrupted {
1764                    kill_at = kill_at.min(tokio::time::Instant::now() + limits.interrupt_grace);
1765                }
1766            }
1767            message = &mut *talking => return (message, false),
1768            () = tokio::time::sleep_until(kill_at) => {
1769                place.host().kill_for(place.watcher.load(Ordering::SeqCst));
1770                return (None, true);
1771            }
1772        }
1773    }
1774}
1775
1776/// What the trigger's log says, once, when a key held a secret it read (B189).
1777const MASKED_KEY: &str = "schedr: an event's key held a secret this trigger read: it is stored \
1778    and shown masked, so keys differing only in secrets count as one key (a key seen before \
1779    starts no run); keep secrets out of keys\n";
1780
1781/// Whether an event's key, or a batch item's, holds a secret the trigger read: keys are stored
1782/// and shown masked, so two differing only in secrets would be one (Grok's review of M4.11f).
1783fn holds_secret(mask: &MaskSet, key: &str, data: &serde_json::Value, batched: bool) -> bool {
1784    if mask.is_empty() {
1785        return false;
1786    }
1787    let items = data.as_array().filter(|_| batched).into_iter().flatten();
1788    let mut keys = std::iter::once(key).chain(items.filter_map(|item| item["key"].as_str()));
1789    keys.any(|key| mask.mask_text(key) != key)
1790}