Skip to main content

schedr_bin/
local.rs

1//! The DAG author's local commands: `schedr dags check` and `schedr dags test`
2//! (see archive/PROJECT.md, Testing DAGs).
3//!
4//! - **`dags check <path>`** imports the DAG files with the real runner (parse mode, the
5//!   per-file timeout) and applies the master's checks, so whatever the master would refuse is
6//!   reported here; exit 1 on any error. **`--against <url>`** then reads that server's active
7//!   workers and fails when this schedr is newer (by minor version) than any of them. A pass
8//!   prints one `ok:` line. A version the master cannot parse does not fail the check.
9//! - **`dags test <dag> [--for]`** runs one real run in an in-process standalone with a
10//!   temporary SQLite database: every task its own process, exactly as in production. It prints
11//!   each task's state as it changes, then the logs (prefixed with the task) and the outputs;
12//!   exit 0 if the run succeeded, 1 otherwise.
13
14use std::collections::BTreeMap;
15use std::fmt::Write as _;
16use std::io::Write;
17use std::path::{Path, PathBuf};
18use std::time::{Duration, Instant};
19
20use schedr_agent::launch::ProcessParseRunner;
21use schedr_agent::parse::{ParseLimits, parse_files_with};
22use schedr_agent::process::ProcessSpec;
23use schedr_agent::scan::scan;
24use schedr_api::views::{AttemptList, LocationView, RunDetail, WorkerView};
25use schedr_api::views::{TriggerRequest, TriggerState};
26use schedr_config::{Config, Root};
27use schedr_db::Database;
28use schedr_master::validate::{Checks, validate_files};
29use schedr_model::runner::{ParseRequest, ParsedFile};
30use schedr_model::{SchedrVersion, WorkerState};
31use serde::Serialize;
32use serde_json::{Value, json};
33
34use crate::app::{AppError, connect_to};
35use crate::cli::{ClientArgs, DagsCommand};
36use crate::client::{Auth, Client, ClientError, HttpTransport};
37use crate::standalone::{plan, run};
38
39#[cfg(test)]
40mod tests;
41
42/// How long `dags test` waits for its run (a hanging task is stopped by its own timeout).
43pub const TEST_RUN_TIMEOUT: Duration = Duration::from_hours(1);
44
45/// The files of one root to check or test: a directory, or one file in its directory.
46#[derive(Debug, Clone, PartialEq, Eq)]
47pub struct LocalRoot {
48    /// The root's name: the directory's name.
49    pub name: String,
50    /// The directory.
51    pub dir: PathBuf,
52    /// The `.py` files to parse, relative to `dir`.
53    pub files: Vec<String>,
54    /// The `.py` files a parse skips: they don't mention `schedr` (decision 305).
55    pub skipped: Vec<String>,
56    /// The root's other `.py` files, when a file or folder of it was named.
57    pub unselected: Vec<String>,
58}
59
60impl LocalRoot {
61    /// The same files, read from a copy of the root.
62    fn clone_at(&self, dir: &Path) -> Self {
63        Self {
64            dir: dir.to_path_buf(),
65            ..self.clone()
66        }
67    }
68
69    /// The root for `path` within a configured root, if it is in one: the file or folder is
70    /// selected, the root's boundary and names kept, so package imports work as on a worker
71    /// (decision 331).
72    ///
73    /// # Errors
74    ///
75    /// [`AppError::BadArgument`] for an unreadable path, one in several roots, or one a
76    /// worker doesn't get (`.schedrignore`).
77    pub fn at_in(path: &Path, config: &Config) -> Result<Self, AppError> {
78        let bad = |e: std::io::Error| AppError::BadArgument(format!("{}: {e}", path.display()));
79        let given = std::path::absolute(path).map_err(bad)?;
80        let resolved = path.canonicalize().map_err(bad)?;
81        let matches: Vec<_> = config
82            .dag_roots
83            .iter()
84            .filter_map(|configured| {
85                let base = configured.path.canonicalize().ok()?;
86                let given_base = std::path::absolute(&configured.path).ok()?;
87                let relative = given
88                    .strip_prefix(given_base)
89                    .ok()
90                    .filter(|relative| {
91                        !relative
92                            .components()
93                            .any(|c| matches!(c, std::path::Component::ParentDir))
94                    })
95                    .or_else(|| resolved.strip_prefix(&base).ok())?;
96                let selected = base.join(relative);
97                Some((configured, base, selected))
98            })
99            .collect();
100        if matches.len() > 1 {
101            return Err(AppError::BadArgument(format!(
102                "{} is inside several DAG roots; configure one root that holds it",
103                path.display()
104            )));
105        }
106        let Some((configured, base, selected)) = matches.first() else {
107            return Self::at(path);
108        };
109        let mut root = Self::at(base)?;
110        root.name.clone_from(&configured.name);
111        let (files, unselected) = std::mem::take(&mut root.files)
112            .into_iter()
113            .partition(|relative| base.join(relative).starts_with(selected));
114        root.files = files;
115        root.unselected = unselected;
116        root.skipped
117            .retain(|relative| base.join(relative).starts_with(selected));
118        if selected.is_file() && root.files.is_empty() && root.skipped.is_empty() {
119            return Err(AppError::BadArgument(format!(
120                "{} is left out of DAG root `{}` (`.schedrignore`), so workers don't get it",
121                path.display(),
122                configured.name
123            )));
124        }
125        Ok(root)
126    }
127
128    /// The root for `path`: a directory scanned like a DAG root (`.schedrignore` honoured), or
129    /// a single file.
130    ///
131    /// # Errors
132    ///
133    /// [`AppError::BadArgument`] if the path doesn't exist or can't be scanned.
134    pub fn at(path: &Path) -> Result<Self, AppError> {
135        let resolved = path
136            .canonicalize()
137            .map_err(|e| AppError::BadArgument(format!("{}: {e}", path.display())))?;
138        let (dir, files) = if resolved.is_dir() {
139            let snapshot = scan(&resolved).map_err(|e| AppError::BadArgument(e.to_string()))?;
140            (resolved, snapshot.python_files())
141        } else if !resolved.is_file() {
142            return Err(AppError::BadArgument(format!(
143                "{}: not a file or a directory",
144                path.display()
145            )));
146        } else {
147            let dir = resolved
148                .parent()
149                .map_or_else(|| PathBuf::from("/"), Path::to_path_buf);
150            let name = resolved
151                .file_name()
152                .map(|n| n.to_string_lossy().into_owned())
153                .unwrap_or_default();
154            (dir, vec![name])
155        };
156        let (files, skipped) = schedr_agent::scan::split_dag_files(&dir, files);
157        let name = dir
158            .file_name()
159            .map_or_else(|| "root".to_owned(), |n| n.to_string_lossy().into_owned());
160        Ok(Self {
161            name,
162            dir,
163            files,
164            skipped,
165            unselected: Vec::new(),
166        })
167    }
168}
169
170/// Runs `schedr dags check` or `schedr dags test`.
171///
172/// # Errors
173///
174/// [`AppError`] for bad arguments, a failure to run the runner, errors found by `check`, a
175/// worker version older than this schedr, a server `--against` cannot read, or a run of
176/// `test` that didn't succeed.
177pub async fn run_local(
178    command: &DagsCommand,
179    config: &Config,
180    env: &BTreeMap<String, String>,
181    client: &ClientArgs,
182    out: &mut impl Write,
183) -> Result<(), AppError> {
184    match command {
185        // Interrupted, the check is dropped: its parser killed, its copies removed.
186        DagsCommand::Check { path, against } => tokio::select! {
187            checked = check_path(path, against.as_deref(), client, config, env, out) => checked,
188            () = interrupted() => Err(interrupted_error()),
189        },
190        DagsCommand::Test {
191            dag,
192            planned_for,
193            params,
194            params_json,
195            event_key,
196            event_data,
197            event_at,
198            secrets,
199            connections,
200            task,
201            path,
202        } => {
203            let params = crate::user::given_params(params, params_json.as_deref())?;
204            let secrets = secrets
205                .iter()
206                .map(|spec| schedr_agent::secrets::MemoryStorage::parse(spec))
207                .collect::<Result<Vec<_>, _>>()
208                .map_err(|e| AppError::BadArgument(format!("--secret: {e}")))?;
209            let connections = connections
210                .iter()
211                .map(|spec| given_connection(spec))
212                .collect::<Result<BTreeMap<_, _>, _>>()
213                .map_err(|e| AppError::BadArgument(format!("--connection: {e}")))?;
214            if task.is_some() {
215                return Err(not_yet("dags test --task", "M4"));
216            }
217            // Its warnings shown, as `runs trigger`'s are (B214).
218            let at = crate::user::for_time(planned_for.as_deref(), &mut std::io::stderr())?;
219            let event = event_key.clone().map(|key| (key, event_data.as_deref()));
220            let event = event
221                .map(|(key, data)| {
222                    let data =
223                        crate::user::given_event_data(data).map_err(AppError::BadArgument)?;
224                    Ok::<_, AppError>((key, data))
225                })
226                .transpose()?;
227            let event_at = crate::user::for_time(event_at.as_deref(), &mut std::io::stderr())?;
228            let run = TestRun {
229                planned_for: at,
230                params,
231                event,
232                event_at,
233                secrets,
234                connections,
235            };
236            Box::pin(test_dag(
237                dag,
238                &run,
239                path.as_deref(),
240                config,
241                env,
242                client.json,
243                out,
244            ))
245            .await
246        }
247        _ => Err(AppError::BadArgument("not a local command".to_owned())),
248    }
249}
250
251/// Parses `path`, reports it, and when `against` is set compares this schedr with that
252/// server's active workers.
253///
254/// # Errors
255///
256/// As [`run_local`] for `dags check`.
257async fn check_path(
258    path: &Path,
259    against: Option<&str>,
260    client: &ClientArgs,
261    config: &Config,
262    env: &BTreeMap<String, String>,
263    out: &mut impl Write,
264) -> Result<(), AppError> {
265    if let Some(files) = check_scripts(path, config)? {
266        let version = match against {
267            Some(url) => Some(worker_versions(url, client, env).await),
268            None => None,
269        };
270        return finish_check(&files, version, client.json, out);
271    }
272    let root = LocalRoot::at_in(path, config)?;
273    // A folder's connections can be defined anywhere in its root: all is parsed, as a worker
274    // does, and what was named is reported.
275    let mut whole = root.clone();
276    if path.is_dir() {
277        whole.files.extend(whole.unselected.iter().cloned());
278        whole.files.sort();
279    }
280    let mut files = check_root(&whole, config, env).await?;
281    // Not in `--json`'s output: it stays what a parse reports.
282    if !client.json {
283        for file in &root.skipped {
284            writeln!(
285                out,
286                "skipped {file}: it doesn't mention `schedr`, so it is never parsed (a file \
287                 defining DAGs needs at least `import schedr`)"
288            )?;
289        }
290    }
291    if path.is_dir() {
292        // A whole root: what its tasks declare in `connections=` is checked against its own.
293        files = schedr_master::validate::connection_problems(files);
294        files = schedr_master::validate::target_problems(files);
295        files.retain(|file| !root.unselected.contains(&file.path));
296    }
297    let version = match against {
298        Some(url) => Some(worker_versions(url, client, env).await),
299        None => None,
300    };
301    finish_check(&files, version, client.json, out)
302}
303
304/// A script root's `schedr.toml` files read and checked, as a worker reads them (M4.9): for a
305/// path in a configured script root (its scripts never imported, as a DAG check would), or
306/// outside the configured roots a `schedr.toml` or a directory holding one. The root is the
307/// configured script root, else the directory (the file's own for a file). `None` for a DAG
308/// check: a path in a configured DAG root, or anything else.
309///
310/// # Errors
311///
312/// [`AppError::BadArgument`] if the path doesn't exist or can't be scanned, or is a file in a
313/// script root that isn't a `schedr.toml` (no DAG file there), or a `schedr.toml` in a DAG
314/// root (read only in script roots).
315pub fn check_scripts(path: &Path, config: &Config) -> Result<Option<Vec<ParsedFile>>, AppError> {
316    let bad = |e: std::io::Error| AppError::BadArgument(format!("{}: {e}", path.display()));
317    let is_file = path.metadata().map_err(bad)?.is_file();
318    // A file by its own name (a `schedr.toml` may link elsewhere) in its resolved directory.
319    let named_config =
320        is_file && path.file_name().and_then(|n| n.to_str()) == Some(schedr_agent::jobs::FILE_NAME);
321    let resolved = if is_file {
322        let parent = path
323            .parent()
324            .filter(|p| !p.as_os_str().is_empty())
325            .unwrap_or_else(|| Path::new("."));
326        parent
327            .canonicalize()
328            .map_err(bad)?
329            .join(path.file_name().unwrap_or_default())
330    } else {
331        path.canonicalize().map_err(bad)?
332    };
333    let inside = |roots: &[schedr_config::roots::Root]| {
334        roots.iter().find_map(|root| {
335            let dir = root.path.canonicalize().ok()?;
336            resolved.starts_with(&dir).then(|| (root.name.clone(), dir))
337        })
338    };
339    let (name, dir) = if let Some(configured) = inside(&config.script_roots) {
340        if is_file && !named_config {
341            return Err(AppError::BadArgument(format!(
342                "{}: in script root `{}`, whose files aren't DAG files: check its `{}` files",
343                path.display(),
344                configured.0,
345                schedr_agent::jobs::FILE_NAME
346            )));
347        }
348        configured
349    } else if let Some((root, _)) = inside(&config.dag_roots) {
350        if named_config {
351            return Err(AppError::BadArgument(format!(
352                "{}: in DAG root `{root}`: `{}` files are read only in script roots \
353                 (`SCHEDR_SCRIPT_PATH`)",
354                path.display(),
355                schedr_agent::jobs::FILE_NAME
356            )));
357        }
358        return Ok(None);
359    } else if is_file {
360        if !named_config {
361            return Ok(None);
362        }
363        let dir = resolved
364            .parent()
365            .map_or_else(|| PathBuf::from("/"), Path::to_path_buf);
366        (directory_name(&dir), dir)
367    } else {
368        (directory_name(&resolved), resolved.clone())
369    };
370    let snapshot = scan(&dir).map_err(|e| AppError::BadArgument(e.to_string()))?;
371    let mut files: Vec<String> = snapshot.files().keys().cloned().collect();
372    let wanted: Vec<String> = if is_file {
373        // Asked for by name: read even if `.schedrignore` leaves it out.
374        let relative = resolved
375            .strip_prefix(&dir)
376            .map_err(|e| AppError::BadArgument(format!("{}: {e}", path.display())))?
377            .to_string_lossy()
378            .replace('\\', "/");
379        if !files.contains(&relative) {
380            files.push(relative.clone());
381        }
382        vec![relative]
383    } else {
384        files
385            .iter()
386            .filter(|file| {
387                schedr_agent::jobs::is_config(file) && dir.join(file).starts_with(&resolved)
388            })
389            .cloned()
390            .collect()
391    };
392    if wanted.is_empty() && inside(&config.script_roots).is_none() {
393        // Outside the configured roots, a directory without one is a DAG directory.
394        return Ok(None);
395    }
396    let interpreters: Vec<String> = config.interpreters.keys().cloned().collect();
397    let parsed = schedr_agent::jobs::read_root(&name, &dir, (&files, &wanted), Some(&interpreters));
398    let limit = usize::try_from(config.grpc.max_message_size).unwrap_or(usize::MAX);
399    Ok(Some(validate_files(
400        &name,
401        parsed,
402        &Checks::new(SchedrVersion::current(), limit),
403    )))
404}
405
406/// A directory's last component, as a root's default name.
407fn directory_name(dir: &Path) -> String {
408    dir.file_name()
409        .map_or_else(|| "root".to_owned(), |n| n.to_string_lossy().into_owned())
410}
411
412/// Parses a root's files with the real runner and applies the master's checks.
413///
414/// # Errors
415///
416/// [`AppError::BadArgument`] if the DAG interpreter isn't defined or the runner can't be run.
417pub async fn check_root(
418    root: &LocalRoot,
419    config: &Config,
420    env: &BTreeMap<String, String>,
421) -> Result<Vec<ParsedFile>, AppError> {
422    // What a worker gets: `.schedrignore`'s files aren't there to import (decision 330, B179).
423    let mut copies = BTreeMap::from([(root.name.clone(), CheckCopy::new(&root.name, &root.dir)?)]);
424    let configured = |path: &Path| path.canonicalize().ok().as_deref() == Some(root.dir.as_path());
425    if config.dag_roots.iter().any(|other| configured(&other.path)) {
426        for other in config
427            .dag_roots
428            .iter()
429            .filter(|other| !configured(&other.path))
430        {
431            copies.insert(
432                other.name.clone(),
433                CheckCopy::new(&other.name, &other.path)?,
434            );
435        }
436    }
437    let sys_path: Vec<String> = copies
438        .values()
439        .map(|copy| copy.dir.to_string_lossy().into_owned())
440        .collect();
441    let in_copy = root.clone_at(&copies[&root.name].dir);
442    let root = &in_copy;
443    let python = config
444        .interpreters
445        .get(&config.dags.interpreter)
446        .map(|i| i.path.clone())
447        .ok_or_else(|| {
448            AppError::BadArgument(format!(
449                "the DAG interpreter `{}` isn't defined in [interpreters]",
450                config.dags.interpreter
451            ))
452        })?;
453    let log_file = check_log_file()?;
454    let check_forks = CheckForks::start(config, env).await?;
455    let runner = ProcessParseRunner {
456        process: ProcessSpec {
457            program: python,
458            args: vec![
459                // Not the working directory first: a root's file can't shadow what the runner imports (B178).
460                "-P".to_owned(),
461                "-m".to_owned(),
462                "schedr.runner".to_owned(),
463                "parse".to_owned(),
464            ],
465            env: env
466                .iter()
467                // As a task's (`PYTHONPATH` changes what imports find).
468                .filter(|(name, _)| {
469                    schedr_agent::env::is_allowed(name) || config.worker.pass_env.contains(name)
470                })
471                .map(|(k, v)| (k.clone(), v.clone()))
472                .collect(),
473            working_dir: root.dir.clone(),
474            log_file: log_file.clone(),
475            max_output_size: 64 * 1024,
476            mask: schedr_agent::mask::Mask::default(),
477            start_timeout: config.worker.runner_start_timeout,
478            output_drain: config.timings.output_drain_timeout,
479        },
480        memory: schedr_agent::memory::MemoryWatch::default(),
481        kills: prometheus_client::metrics::counter::Counter::default(),
482        // As tasks will run (decision 326): forked from the configured fork server.
483        forks: check_forks.as_ref().map(|started| started.servers.clone()),
484    };
485    let request = ParseRequest {
486        root: root.name.clone(),
487        root_dir: root.dir.to_string_lossy().into_owned(),
488        files: root.files.clone(),
489        sys_path,
490    };
491    // A `ScriptOperator` is looked up in the configured script roots, read in place.
492    let scripts = config
493        .script_roots
494        .iter()
495        .map(|script| {
496            let at = schedr_agent::jobs::ScriptRoot {
497                configured: script.path.clone(),
498                copy: script.path.clone(),
499            };
500            (script.name.clone(), at)
501        })
502        .collect();
503    let limits = ParseLimits::configured(
504        config.dags.parse_file_timeout,
505        config.dags.parse_concurrency,
506    );
507    let parsed = parse_files_with(&runner, request, limits, &scripts).await;
508    drop(check_forks);
509    let output = std::fs::read_to_string(&log_file).unwrap_or_default();
510    let _ = std::fs::remove_file(&log_file);
511    let parsed = parsed.map_err(|e| {
512        AppError::BadArgument(runner_failed(
513            &e.to_string(),
514            config,
515            &runner.process.program,
516            &output,
517        ))
518    })?;
519    let limit = usize::try_from(config.grpc.max_message_size).unwrap_or(usize::MAX);
520    Ok(validate_files(
521        &root.name,
522        parsed,
523        &Checks::new(SchedrVersion::current(), limit),
524    ))
525}
526
527/// How many of the runner's last output lines a failed parse shows.
528const RUNNER_OUTPUT_LINES: usize = 20;
529
530/// Why parsing failed, with what helps fixing it: the interpreter, how it was chosen, the
531/// runner's last output lines, and what the interpreter needs.
532fn runner_failed(error: &str, config: &Config, python: &Path, output: &str) -> String {
533    let builtin = config
534        .builtin_python
535        .as_deref()
536        .filter(|_| config.dags.interpreter == "python");
537    let how = builtin.unwrap_or("configured in [interpreters]");
538    let mut message = format!(
539        "parsing failed: {error}\n  interpreter `{}`: {} ({how})",
540        config.dags.interpreter,
541        python.display()
542    );
543    let lines: Vec<&str> = output.lines().collect();
544    if !lines.is_empty() {
545        message.push_str("\n  its output:");
546        for line in &lines[lines.len().saturating_sub(RUNNER_OUTPUT_LINES)..] {
547            message.push_str("\n    ");
548            message.push_str(line);
549        }
550    }
551    let choose = if config.dags.interpreter == "python" {
552        "[interpreters] python (SCHEDR_CONFIG__INTERPRETERS__PYTHON)".to_owned()
553    } else {
554        format!(
555            "[interpreters] {}, or [dags] interpreter",
556            config.dags.interpreter
557        )
558    };
559    let _ = write!(
560        message,
561        "\n  it needs Python 3.14+ with schedr {} installed; choose another with {choose}",
562        crate::VERSION
563    );
564    message
565}
566
567/// An active worker compared with the local schedr (`dags check --against`).
568#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
569pub(crate) struct ComparedWorker {
570    /// Its ID.
571    pub worker_id: String,
572    /// The version it reported (`major.minor` or `major.minor.patch`).
573    pub schedr_version: String,
574}
575
576/// What `--against` found. `ok` is false when an active worker is older than `local`, or
577/// none is active. A version that does not parse is unknown, as the master stores it, and
578/// does not by itself make `ok` false.
579#[derive(Debug, Clone, PartialEq, Eq)]
580pub(crate) struct VersionCheck {
581    /// This schedr, as `major.minor`.
582    pub local: SchedrVersion,
583    /// Whether every active worker is eligible: at least `local`, or an unknown version.
584    pub ok: bool,
585    /// Set when `ok` is false. The CLI prints it as `error: {message}`.
586    pub message: Option<String>,
587    /// Every active worker, in the order the server listed them.
588    pub workers: Vec<ComparedWorker>,
589    /// The server URL the lines name, without a trailing slash.
590    server: String,
591}
592
593impl VersionCheck {
594    /// The line a person sees: `ok: ...` when the check passes, `error: ...` when it fails.
595    #[must_use]
596    pub(crate) fn line(&self) -> String {
597        match &self.message {
598            Some(body) => format!("error: {body}"),
599            None => passing_line(self.local, &self.server, &self.workers),
600        }
601    }
602}
603
604/// Reads `GET /api/v1/workers` at `url` with the CLI's client ([`connect_to`]) and compares
605/// the active workers with this build of schedr.
606///
607/// # Errors
608///
609/// [`ClientError`] when the server cannot be reached or the answer is not the worker list.
610pub(crate) async fn worker_versions(
611    url: &str,
612    client: &ClientArgs,
613    env: &BTreeMap<String, String>,
614) -> Result<VersionCheck, ClientError> {
615    let api = connect_to(url, client, env);
616    let server = api.transport().server().to_owned();
617    let listed = api.workers().await?;
618    Ok(compare_active_workers(
619        SchedrVersion::current(),
620        &server,
621        &listed.workers,
622    ))
623}
624
625/// Compares `local` with the active workers at `server`.
626///
627/// Active includes a worker drained for maintenance. Draining, disconnected, offline and lost
628/// workers are left out. The patch level is ignored. A version that does not parse is unknown:
629/// the master stores `None` and still assigns tasks, so the check does not fail for that worker.
630#[must_use]
631pub(crate) fn compare_active_workers(
632    local: SchedrVersion,
633    server: &str,
634    workers: &[WorkerView],
635) -> VersionCheck {
636    let active_name = WorkerState::Active.to_string();
637    let mut compared = Vec::new();
638    for worker in workers {
639        if worker.state == active_name {
640            compared.push(ComparedWorker {
641                worker_id: worker.worker_id.clone(),
642                schedr_version: worker.schedr_version.clone(),
643            });
644        }
645    }
646    if compared.is_empty() {
647        return VersionCheck {
648            local,
649            ok: false,
650            message: Some(no_active_message(server, local)),
651            workers: compared,
652            server: server.to_owned(),
653        };
654    }
655    let message = older_workers(local, server, &compared);
656    VersionCheck {
657        local,
658        ok: message.is_none(),
659        message,
660        workers: compared,
661        server: server.to_owned(),
662    }
663}
664
665/// No counted worker. A master restart records workers disconnected until they register.
666fn no_active_message(server: &str, local: SchedrVersion) -> String {
667    format!(
668        "no active worker at {server} to compare with this schedr ({local}): \
669         workers are recorded disconnected right after a master restart until they \
670         register again, so retry in a minute"
671    )
672}
673
674/// The failure when any of `active` is older than `local`, naming those workers.
675///
676/// An unreadable version is left out: the master treats it as unknown and still assigns tasks.
677fn older_workers(local: SchedrVersion, server: &str, active: &[ComparedWorker]) -> Option<String> {
678    let mut by_version: BTreeMap<SchedrVersion, Vec<&str>> = BTreeMap::new();
679    for worker in active {
680        if let Ok(version) = worker.schedr_version.parse::<SchedrVersion>()
681            && local > version
682        {
683            by_version
684                .entry(version)
685                .or_default()
686                .push(worker.worker_id.as_str());
687        }
688    }
689    if by_version.is_empty() {
690        return None;
691    }
692    let mut groups = Vec::new();
693    for (version, ids) in &by_version {
694        groups.push(format!("{version}: {}", ids.join(", ")));
695    }
696    Some(format!(
697        "this schedr is {local}; older active workers at {server}: {}",
698        groups.join("; ")
699    ))
700}
701
702/// The passing line, for example `ok: this schedr is 0.3; 2 active workers at the server run 0.3 (w1, w2)`.
703fn passing_line(local: SchedrVersion, server: &str, active: &[ComparedWorker]) -> String {
704    let n = active.len();
705    let (noun, verb) = if n == 1 {
706        ("worker", "runs")
707    } else {
708        ("workers", "run")
709    };
710    format!(
711        "ok: this schedr is {local}; {n} active {noun} at {server} {verb} {}",
712        run_groups(active)
713    )
714}
715
716/// Versions oldest first, then unknown texts, each with its worker ids.
717fn run_groups(active: &[ComparedWorker]) -> String {
718    let mut by_version: BTreeMap<SchedrVersion, Vec<&str>> = BTreeMap::new();
719    let mut unknown: BTreeMap<&str, Vec<&str>> = BTreeMap::new();
720    for worker in active {
721        match worker.schedr_version.parse::<SchedrVersion>() {
722            Ok(version) => by_version
723                .entry(version)
724                .or_default()
725                .push(worker.worker_id.as_str()),
726            Err(_) => unknown
727                .entry(worker.schedr_version.as_str())
728                .or_default()
729                .push(worker.worker_id.as_str()),
730        }
731    }
732    let mut groups = Vec::new();
733    for (version, ids) in &by_version {
734        groups.push(format!("{version} ({})", ids.join(", ")));
735    }
736    for (text, ids) in &unknown {
737        groups.push(format!("unknown version `{text}` ({})", ids.join(", ")));
738    }
739    groups.join(", ")
740}
741
742/// One file in `dags check --json`.
743#[derive(Debug, Serialize)]
744struct CheckedFile<'a> {
745    path: &'a str,
746    dags: Vec<&'a str>,
747    error: Option<&'a schedr_model::runner::ErrorSummary>,
748    #[serde(skip_serializing_if = "<[String]>::is_empty")]
749    warnings: &'a [String],
750}
751
752/// `dags check --json`, with `version_check` when `--against` read the worker list.
753#[derive(Serialize)]
754struct CheckJson<'a> {
755    files: Vec<CheckedFile<'a>>,
756    #[serde(skip_serializing_if = "Option::is_none")]
757    version_check: Option<VersionJson<'a>>,
758}
759
760/// The `version_check` object. `message` is the line a person sees.
761#[derive(Serialize)]
762struct VersionJson<'a> {
763    local: SchedrVersion,
764    ok: bool,
765    message: String,
766    workers: &'a [ComparedWorker],
767}
768
769/// Prints the file report and returns the version failure, the file failure, or both.
770///
771/// # Errors
772///
773/// [`AppError::Failed`] when a file has an error or an active worker is older (both, when
774/// both happened), [`AppError::Client`] when the server could not be read and the files were
775/// fine, or [`AppError::Output`] when writing fails.
776pub(crate) fn finish_check(
777    files: &[ParsedFile],
778    version: Option<Result<VersionCheck, ClientError>>,
779    json: bool,
780    out: &mut impl Write,
781) -> Result<(), AppError> {
782    let shown = version.as_ref().and_then(|result| result.as_ref().ok());
783    let errors = write_report(files, shown, json, out)?;
784    combine(file_failure(errors), version_failure(version))
785}
786
787/// The file-report half of a failure, when any file has an error.
788fn file_failure(errors: usize) -> Option<String> {
789    (errors > 0).then(|| format!("{errors} file(s) with errors"))
790}
791
792/// The `--against` half of a failure.
793fn version_failure(version: Option<Result<VersionCheck, ClientError>>) -> Option<AppError> {
794    match version {
795        Some(Err(error)) => Some(AppError::Client(error)),
796        Some(Ok(check)) => check.message.map(AppError::Failed),
797        None => None,
798    }
799}
800
801/// One error, or both with a second `error:` line.
802fn combine(files: Option<String>, version: Option<AppError>) -> Result<(), AppError> {
803    match (files, version) {
804        (None, None) => Ok(()),
805        (Some(files), None) => Err(AppError::Failed(files)),
806        (None, Some(error)) => Err(error),
807        (Some(files), Some(error)) => Err(AppError::Failed(format!("{files}\nerror: {error}"))),
808    }
809}
810
811/// Writes the file report and returns how many files have an error.
812///
813/// # Errors
814///
815/// [`AppError::Output`] when writing fails.
816fn write_report(
817    files: &[ParsedFile],
818    version: Option<&VersionCheck>,
819    json: bool,
820    out: &mut impl Write,
821) -> Result<usize, AppError> {
822    let errors = files.iter().filter(|f| f.error.is_some()).count();
823    if json {
824        write_json(files, version, out)?;
825    } else {
826        write_text(files, errors, version, out)?;
827    }
828    Ok(errors)
829}
830
831/// `--json`: the files, and `version_check` when the worker list was read.
832fn write_json(
833    files: &[ParsedFile],
834    version: Option<&VersionCheck>,
835    out: &mut impl Write,
836) -> Result<(), AppError> {
837    let report = CheckJson {
838        files: files
839            .iter()
840            .map(|file| CheckedFile {
841                path: &file.path,
842                dags: file.dags.iter().map(|dag| dag.id.as_str()).collect(),
843                error: file.error.as_ref(),
844                warnings: &file.warnings,
845            })
846            .collect(),
847        version_check: version.map(|check| VersionJson {
848            local: check.local,
849            ok: check.ok,
850            message: check.line(),
851            workers: &check.workers,
852        }),
853    };
854    writeln!(
855        out,
856        "{}",
857        serde_json::to_string_pretty(&report).unwrap_or_default()
858    )?;
859    Ok(())
860}
861
862/// One line per file and one per warning it raised, then the summary, then the passing
863/// `--against` line.
864fn write_text(
865    files: &[ParsedFile],
866    errors: usize,
867    version: Option<&VersionCheck>,
868    out: &mut impl Write,
869) -> Result<(), AppError> {
870    for file in files {
871        match &file.error {
872            None if file.dags.is_empty() => writeln!(out, "ok     {}: no DAGs", file.path)?,
873            None => {
874                let dags: Vec<String> = file
875                    .dags
876                    .iter()
877                    .map(|dag| format!("{} ({} tasks)", dag.id, dag.tasks.len()))
878                    .collect();
879                writeln!(out, "ok     {}: {}", file.path, dags.join(", "))?;
880            }
881            Some(error) => {
882                writeln!(
883                    out,
884                    "error  {}: {}: {}",
885                    file.path, error.exception, error.message
886                )?;
887                for line in error.traceback.lines() {
888                    writeln!(out, "         {line}")?;
889                }
890            }
891        }
892        // Warnings don't fail the check: the DAG runs as written (e.g. a `TypingHint`).
893        for warning in &file.warnings {
894            writeln!(out, "warn   {}: {warning}", file.path)?;
895        }
896    }
897    let dags: usize = files.iter().map(|file| file.dags.len()).sum();
898    writeln!(
899        out,
900        "{} file(s), {dags} DAG(s), {errors} error(s)",
901        files.len()
902    )?;
903    if let Some(check) = version.filter(|check| check.ok) {
904        writeln!(out, "{}", check.line())?;
905    }
906    Ok(())
907}
908
909/// Runs one real run of `dag` locally and reports it.
910/// The run `dags test` makes: when for, and its parameters.
911struct TestRun {
912    planned_for: Option<jiff::Timestamp>,
913    params: Option<serde_json::Map<String, serde_json::Value>>,
914    /// `--event-key` and `--event-data`.
915    event: Option<(String, Option<Value>)>,
916    /// `--event-at`.
917    event_at: Option<jiff::Timestamp>,
918    /// `--secret` values: in memory, standing for every storage the DAG reads.
919    secrets: Vec<(schedr_model::SecretName, String)>,
920    /// `--connection` values, by connection and parameter.
921    connections: BTreeMap<String, BTreeMap<String, Value>>,
922}
923
924/// A `--connection` value: `name={"param": value, ...}`.
925///
926/// # Errors
927///
928/// What is wrong with it.
929pub(crate) fn given_connection(spec: &str) -> Result<(String, BTreeMap<String, Value>), String> {
930    // The value is never quoted back: it may hold a secret (B210).
931    let Some((name, json)) = spec.split_once('=') else {
932        return Err("expected `name={\"param\": value}`".to_owned());
933    };
934    // Nor its name: a value alone may hold `=` (base64's padding).
935    schedr_model::TaskId::new(name)
936        .map_err(|_| "a connection's name is letters, digits and `_`".to_owned())?;
937    let values = serde_json::from_str(json).map_err(|e| {
938        format!(
939            "its values must be a JSON object (line {}, column {})",
940            e.line(),
941            e.column()
942        )
943    })?;
944    Ok((name.to_owned(), values))
945}
946
947/// Once Ctrl-C or SIGTERM comes: the test then ends as a run's end does, its tasks stopped and
948/// its folder removed (B211, B209), not the CLI alone, its tasks going on.
949async fn interrupted() {
950    let _ = crate::roles::stop_on_signal().changed().await;
951}
952
953/// A check's parse log: a new private file in the temp folder, named afresh each time.
954///
955/// # Errors
956///
957/// [`AppError::BadArgument`] when it can't be made.
958fn check_log_file() -> Result<PathBuf, AppError> {
959    let name = format!("schedr-check-{}.log", uuid::Uuid::now_v7());
960    private_file(&std::env::temp_dir(), &name)
961}
962
963/// A new empty file `name` in `dir` (the temp folder), its user's only (0600), made before a runner
964/// writes it: an import may print a secret (B209's review). Made new: a file or a link
965/// already there (planted in a shared temp folder) is refused, never followed or truncated.
966///
967/// # Errors
968///
969/// [`AppError::BadArgument`] when it can't be made.
970fn private_file(dir: &Path, name: &str) -> Result<PathBuf, AppError> {
971    use std::os::unix::fs::OpenOptionsExt;
972    let path = dir.join(name);
973    std::fs::OpenOptions::new()
974        .write(true)
975        .create_new(true)
976        .mode(0o600)
977        .open(&path)
978        .map_err(|e| AppError::BadArgument(format!("{}: {e}", path.display())))?;
979    Ok(path)
980}
981
982/// Why a test or a check ended on Ctrl-C or SIGTERM.
983fn interrupted_error() -> AppError {
984    AppError::Failed("interrupted: what it started was stopped".to_owned())
985}
986
987/// A test run's folder, in the temp folder, its user's only: its database holds the run's
988/// parameters in plain text (B209).
989///
990/// # Errors
991///
992/// [`AppError::BadArgument`] when it can't be made.
993fn private_folder() -> Result<PathBuf, AppError> {
994    private_temp(&format!(
995        "schedr-test-{}-{}",
996        std::process::id(),
997        jiff::Timestamp::now().as_nanosecond()
998    ))
999}
1000
1001/// A new folder `name` in the temp folder, its user's only (0700): what a check or a test
1002/// copies or writes there (DAG files, a database, logs) may hold secrets, and the temp
1003/// folder is shared (B209 and its review).
1004///
1005/// # Errors
1006///
1007/// [`AppError::BadArgument`] when it can't be made.
1008fn private_temp(name: &str) -> Result<PathBuf, AppError> {
1009    use std::os::unix::fs::DirBuilderExt;
1010    let path = std::env::temp_dir().join(name);
1011    std::fs::DirBuilder::new()
1012        .mode(0o700)
1013        .create(&path)
1014        .map_err(|e| AppError::BadArgument(format!("can't make `{}`: {e}", path.display())))?;
1015    Ok(path)
1016}
1017
1018/// A test run's secrets: only its `--secret` values and `--connection` values, masked as
1019/// the configured deployment masks (B208).
1020fn test_stores(test: &TestRun, config: &Config) -> schedr_agent::secrets::SecretStores {
1021    let values = schedr_agent::secrets::MemoryStorage::new(test.secrets.clone());
1022    let mut stores = schedr_agent::secrets::SecretStores::for_test(values)
1023        .with_test_connections(test.connections.clone());
1024    stores.min_mask_length = config.secret_storage.min_mask_length;
1025    stores
1026}
1027
1028/// The configuration of `dags test`'s own standalone: `config` with `roots`, its data in
1029/// `data`, every port chosen by the system.
1030fn test_config(config: &Config, roots: Vec<Root>, data: &Path) -> Config {
1031    let mut local = config.clone();
1032    local.dag_roots = roots;
1033    local.database.url = Some(format!("sqlite://{}", data.join("schedr.db").display()));
1034    local.worker.data_dir = Some(data.to_path_buf());
1035    local.master.grpc_port = 0;
1036    local.webserver.port = 0;
1037    local.worker.log_port = 0;
1038    local.ops.port = 0;
1039    // Its own server, for this command alone: on this machine only, and with no sign-in, as
1040    // its own client calls it without one (B212; `--user` never reached it).
1041    let loopback = std::net::IpAddr::from(std::net::Ipv4Addr::LOCALHOST);
1042    local.master.bind = loopback;
1043    local.webserver.bind = loopback;
1044    local.ops.bind = loopback;
1045    local.worker.log_bind = loopback;
1046    local.webserver.auth = schedr_config::config::AuthSection::default();
1047    // Nor the deployment's UI token, which its own UI doesn't need (Grok's review of B212).
1048    local.webserver.ui_token_file = None;
1049    // Nor its folder of connection files: one set there is swept at start, a live worker's
1050    // with it on the same host (Grok's review); unset, it is the test's own, from its data.
1051    local.worker.connection_dir = None;
1052    // Its notifications are kept, not sent (the user, 2026-11-10): the channels stay known by
1053    // name, so a DAG naming one loads, but none of their secrets is read.
1054    local.notifications.ca_file = None;
1055    for channel in local.notifications.channels.values_mut() {
1056        channel.headers_env.clear();
1057    }
1058    local.timings.tick_interval = Duration::from_millis(100);
1059    local.dags.poll_interval = Duration::from_millis(200);
1060    local.dags.settle_time = Duration::ZERO;
1061    local
1062}
1063
1064async fn test_dag(
1065    dag: &str,
1066    test: &TestRun,
1067    path: Option<&Path>,
1068    config: &Config,
1069    env: &BTreeMap<String, String>,
1070    json: bool,
1071    out: &mut impl Write,
1072) -> Result<(), AppError> {
1073    let roots: Vec<Root> = match path {
1074        Some(path) => {
1075            // A named file alone is parsed, with the root it is in (B118, decision 331); a
1076            // folder, all of its root, whose connections it can use, as on a worker. The other
1077            // configured roots are importable.
1078            let root = LocalRoot::at_in(path, config)?;
1079            let name = root.name.clone();
1080            let mut roots = vec![Root {
1081                only: path.is_file().then_some(root.files),
1082                name: root.name,
1083                path: root.dir.clone(),
1084            }];
1085            if config
1086                .dag_roots
1087                .iter()
1088                .any(|known| known.path.canonicalize().ok().as_ref() == Some(&root.dir))
1089            {
1090                for known in config.dag_roots.iter().filter(|known| known.name != name) {
1091                    let mut library = known.clone();
1092                    library.only = Some(Vec::new());
1093                    roots.push(library);
1094                }
1095            }
1096            roots
1097        }
1098        None if !config.dag_roots.is_empty() => config.dag_roots.clone(),
1099        None => {
1100            let root = LocalRoot::at(Path::new("."))?;
1101            vec![Root {
1102                name: root.name,
1103                path: root.dir,
1104                only: None,
1105            }]
1106        }
1107    };
1108    // Interrupted while the files are parsed: dropped, the parser is killed and its copy
1109    // removed (B211's review).
1110    tokio::select! {
1111        defined = ensure_defined(dag, &roots, config, env) => defined?,
1112        () = interrupted() => return Err(interrupted_error()),
1113    }
1114    let data = private_folder()?;
1115    if let Err(error) = scannable(&roots, &data.join("preflight")) {
1116        let _ = std::fs::remove_dir_all(&data);
1117        return Err(error);
1118    }
1119    let local = test_config(config, roots, &data);
1120    let mut setup = plan(&local, env)?;
1121    setup.outbox.deliver = false;
1122    // A database of its own, created here.
1123    setup.migrate = true;
1124    // A test run's secrets are only its `--secret` values (none: every read is "not found"),
1125    // never the configured storages standalone would otherwise put in their place.
1126    let stores = test_stores(test, config);
1127    setup.secret_storage = setup.secret_storage.clone().given(stores);
1128    let logs = setup.agent.setup.log_dir.clone();
1129    let (stop, stopped) = tokio::sync::watch::channel(0);
1130    let (bound, addresses) = tokio::sync::oneshot::channel();
1131    let server = tokio::spawn(run(
1132        setup,
1133        move |listening| {
1134            let _ = bound.send(listening);
1135        },
1136        stopped,
1137    ));
1138    let result = tokio::select! {
1139        result = async {
1140            match addresses.await {
1141                Ok(listening) => {
1142                    drive(
1143                        dag,
1144                        test,
1145                        &format!("http://{}", listening.http),
1146                        (&data, &logs),
1147                        (json, config.timings.dags_test_run_timeout),
1148                        crate::roles::client_timeouts(config),
1149                        out,
1150                    )
1151                    .await
1152                }
1153                Err(_) => Err(AppError::BadArgument(
1154                    "the local schedr didn't start".to_owned(),
1155                )),
1156            }
1157        } => result,
1158        () = interrupted() => Err(interrupted_error()),
1159    };
1160    // Two requests: whatever still runs (a run that timed out) is interrupted at once.
1161    let _ = stop.send(2);
1162    if let Ok(Err(error)) = server.await {
1163        tracing::warn!(%error, "local schedr stopped with an error");
1164    }
1165    // The master's background tasks aren't waited for, and one may be writing to the database:
1166    // its journal appears while the folder is being removed. Once it is gone they can't bring it back.
1167    for _ in 0..50 {
1168        if schedr_agent::scan::remove_tree(&data).is_ok() || !data.exists() {
1169            break;
1170        }
1171        tokio::time::sleep(Duration::from_millis(100)).await;
1172    }
1173    result
1174}
1175
1176/// The DAG interpreter's fork servers for one check, when it has `fork_server = true`: their logs
1177/// go to a folder removed when dropped.
1178struct CheckForks {
1179    servers: schedr_agent::fork::ForkServers,
1180    logs: PathBuf,
1181}
1182
1183impl CheckForks {
1184    /// Started and settled: a check runs as tasks will, so it doesn't spawn because the server
1185    /// is still starting. What is wrong with one (a preload failing) is logged as a warning.
1186    async fn start(
1187        config: &Config,
1188        env: &BTreeMap<String, String>,
1189    ) -> Result<Option<Self>, AppError> {
1190        if crate::roles::fork_config(config).is_none() {
1191            return Ok(None);
1192        }
1193        let logs = private_temp(&format!("schedr-check-{}", uuid::Uuid::now_v7()))?;
1194        let settings = crate::roles::agent_settings(
1195            config,
1196            env,
1197            &logs,
1198            schedr_agent::memory::STANDALONE_RESERVE,
1199        )?;
1200        std::fs::create_dir_all(&settings.setup.log_dir)
1201            .map_err(|e| AppError::BadArgument(format!("{}: {e}", logs.display())))?;
1202        let metrics = schedr_agent::fork::ForkMetrics::default();
1203        let Some(servers) = schedr_agent::fork::ForkServers::for_worker(&settings.setup, &metrics)
1204        else {
1205            return Ok(None);
1206        };
1207        for warning in servers
1208            .settled(config.worker.fork_server_preload_timeout)
1209            .await
1210        {
1211            tracing::warn!(%warning, "fork server");
1212        }
1213        Ok(Some(Self { servers, logs }))
1214    }
1215}
1216
1217impl Drop for CheckForks {
1218    fn drop(&mut self) {
1219        let _ = schedr_agent::scan::remove_tree(&self.logs);
1220    }
1221}
1222
1223/// A root's read-only copy for one check, as a worker's: removed when dropped.
1224struct CheckCopy {
1225    store: PathBuf,
1226    dir: PathBuf,
1227}
1228
1229impl CheckCopy {
1230    fn new(name: &str, root: &Path) -> Result<Self, AppError> {
1231        let bad = |e: schedr_agent::scan::ScanError| {
1232            AppError::BadArgument(format!("can't scan DAG root `{name}`: {e}"))
1233        };
1234        let store = private_temp(&format!("schedr-check-{}", uuid::Uuid::now_v7()))?;
1235        let before = scan(root).map_err(bad)?;
1236        let captured = schedr_agent::scan::capture(&before, &store).map_err(bad)?;
1237        let copy = Self {
1238            store,
1239            dir: captured.dir,
1240        };
1241        if scan(root).map_err(bad)? != before {
1242            return Err(AppError::BadArgument(
1243                "the DAG files changed while being copied; run the check again".to_owned(),
1244            ));
1245        }
1246        Ok(copy)
1247    }
1248}
1249
1250impl Drop for CheckCopy {
1251    fn drop(&mut self) {
1252        let _ = schedr_agent::scan::remove_tree(&self.store);
1253    }
1254}
1255
1256/// Fails at once if a root can't be scanned and copied as its agent will (B103): the agent
1257/// would retry for ever, its worker never registering. Each is copied into `store`, then
1258/// removed.
1259fn scannable(roots: &[Root], store: &Path) -> Result<(), AppError> {
1260    for root in roots {
1261        let failed = |error: schedr_agent::scan::ScanError| {
1262            AppError::Failed(format!("can't scan DAG root `{}`: {error}", root.name))
1263        };
1264        let snapshot = schedr_agent::scan::scan(&root.path).map_err(failed)?;
1265        let captured =
1266            schedr_agent::scan::capture(&snapshot, &store.join(&root.name)).map_err(failed)?;
1267        if let Err(error) = schedr_agent::scan::remove_capture(&captured.dir) {
1268            tracing::warn!(dir = %captured.dir.display(), %error, "can't remove a copy of DAG code");
1269        }
1270    }
1271    Ok(())
1272}
1273
1274/// Fails fast if no file in the roots defines `dag`, naming the files that didn't import.
1275async fn ensure_defined(
1276    dag: &str,
1277    roots: &[Root],
1278    config: &Config,
1279    env: &BTreeMap<String, String>,
1280) -> Result<(), AppError> {
1281    let mut broken = Vec::new();
1282    for root in roots {
1283        let mut local = LocalRoot::at(&root.path)?;
1284        local.name.clone_from(&root.name);
1285        if let Some(only) = &root.only {
1286            local.files.clone_from(only);
1287        }
1288        for file in check_root(&local, config, env).await? {
1289            if file.dags.iter().any(|d| d.id.as_str() == dag) {
1290                return Ok(());
1291            }
1292            if file.error.is_some() {
1293                broken.push(format!("{}:{}", root.name, file.path));
1294            }
1295        }
1296    }
1297    let message = if broken.is_empty() {
1298        format!("no DAG `{dag}` in the DAG files (`schedr dags check` shows what they define)")
1299    } else {
1300        format!(
1301            "no DAG `{dag}` in the DAG files; these files have errors \
1302             (`schedr dags check` shows them): {}",
1303            broken.join(", ")
1304        )
1305    };
1306    Err(AppError::Failed(message))
1307}
1308
1309/// Triggers the run, follows it, and prints the report.
1310async fn drive(
1311    dag: &str,
1312    test: &TestRun,
1313    api: &str,
1314    (data, logs): (&Path, &Path),
1315    (json, run_timeout): (bool, Duration),
1316    timeouts: schedr_client::Timeouts,
1317    out: &mut impl Write,
1318) -> Result<(), AppError> {
1319    // The configured client timeouts (Codex's review of M5.1p: `dags test` kept its own).
1320    let client = Client::new(
1321        HttpTransport::new(api, Auth::None).with_timeouts(timeouts),
1322        Duration::from_millis(100),
1323        timeouts.command_wait,
1324    );
1325    let location = wait_for_dag(&client, dag).await?;
1326    unpause_chained(&client).await?;
1327    let request = TriggerRequest {
1328        planned_for: test.planned_for,
1329        params: test.params.clone(),
1330        event_key: test.event.as_ref().map(|(key, _)| key.clone()),
1331        event_data: test.event.as_ref().and_then(|(_, data)| data.clone()),
1332        event_at: test.event_at,
1333        event: None,
1334    };
1335    let command = client
1336        .wait(
1337            client
1338                .send_command(|| client.trigger_with(dag, &request))
1339                .await?,
1340        )
1341        .await?;
1342    let run_id = command
1343        .result
1344        .as_ref()
1345        .and_then(|r| r["run_id"].as_str())
1346        .unwrap_or_default()
1347        .to_owned();
1348    let started = Instant::now();
1349    let mut shown: BTreeMap<String, String> = BTreeMap::new();
1350    let detail = loop {
1351        let detail = client.run(&run_id).await?;
1352        if !json {
1353            for task in &detail.tasks {
1354                let worth_showing = !["scheduled", "queued"].contains(&task.state.as_str());
1355                let name = shown_name(task);
1356                if worth_showing && shown.get(&name) != Some(&task.state) {
1357                    writeln!(out, "{:<10} {name}", task.state)?;
1358                    shown.insert(name, task.state.clone());
1359                }
1360            }
1361        }
1362        if ["success", "failed", "cancelled"].contains(&detail.run.state.as_str()) {
1363            break detail;
1364        }
1365        if started.elapsed() > run_timeout {
1366            return Err(AppError::Failed(format!(
1367                "run {run_id} didn't finish in time"
1368            )));
1369        }
1370        tokio::time::sleep(Duration::from_millis(100)).await;
1371    };
1372    let report = report(&client, &detail, location.as_ref(), (data, logs)).await?;
1373    if json {
1374        writeln!(
1375            out,
1376            "{}",
1377            serde_json::to_string_pretty(&report).unwrap_or_default()
1378        )?;
1379    } else {
1380        print_report(&report, out)?;
1381    }
1382    if detail.run.state == "success" {
1383        Ok(())
1384    } else {
1385        Err(AppError::Failed(format!(
1386            "run {run_id} ended {}",
1387            detail.run.state
1388        )))
1389    }
1390}
1391
1392/// Waits until the local master has stored `dag`; returns the file that defines it.
1393/// Unpauses the `trigger=Chained()` DAGs of the path tested (a new trigger is stored paused), so a
1394/// `TriggerDagOperator` starts a real run of a target there (decisions 378, 398); only other
1395/// DAGs start them, so nothing else runs. The others stay paused: their triggers don't fire.
1396async fn unpause_chained(client: &Client<HttpTransport>) -> Result<(), AppError> {
1397    for found in client.dags().await?.dags {
1398        let chained = found
1399            .trigger
1400            .as_ref()
1401            .is_some_and(|t| t["kind"].as_str() == Some("chained"));
1402        if chained && found.trigger_state == Some(TriggerState::Paused) {
1403            client
1404                .wait(
1405                    client
1406                        .send_command(|| client.set_paused(&found.dag_id, false, false))
1407                        .await?,
1408                )
1409                .await?;
1410        }
1411    }
1412    Ok(())
1413}
1414
1415async fn wait_for_dag(
1416    client: &Client<HttpTransport>,
1417    dag: &str,
1418) -> Result<Option<LocationView>, AppError> {
1419    let deadline = Instant::now() + Duration::from_secs(60);
1420    loop {
1421        let dags = client.dags().await?;
1422        if let Some(found) = dags.dags.iter().find(|d| d.dag_id == dag) {
1423            if let Some(places) = &found.conflict {
1424                let places: Vec<String> = places
1425                    .iter()
1426                    .map(|p| format!("{}:{}", p.root, p.path))
1427                    .collect();
1428                return Err(AppError::Failed(format!(
1429                    "DAG `{dag}` is defined in more than one place: {}",
1430                    places.join(", ")
1431                )));
1432            }
1433            return Ok(found.location.clone());
1434        }
1435        if Instant::now() > deadline {
1436            return Err(AppError::Failed(format!(
1437                "no DAG `{dag}` in the DAG files (`schedr dags check` shows what they define)"
1438            )));
1439        }
1440        tokio::time::sleep(Duration::from_millis(100)).await;
1441    }
1442}
1443
1444/// The run's report: the run, the file defining the DAG, and each task's state, output,
1445/// attempts and log.
1446async fn report(
1447    client: &Client<HttpTransport>,
1448    detail: &RunDetail,
1449    location: Option<&LocationView>,
1450    (data, logs): (&Path, &Path),
1451) -> Result<Value, AppError> {
1452    let db = Database::connect(&format!("sqlite://{}", data.join("schedr.db").display())).await?;
1453    let run_id = &detail.run.run_id;
1454    let mut tasks = Vec::new();
1455    for task in &detail.tasks {
1456        let instance = u32::try_from(task.map_index).ok();
1457        // A mapped task as a whole has no attempts; its output is the gathered list.
1458        let attempts: AttemptList = if task.instances.is_some() {
1459            AttemptList {
1460                attempts: Vec::new(),
1461            }
1462        } else {
1463            client
1464                .instance_attempts(run_id, &task.task_id, instance)
1465                .await?
1466        };
1467        let mut log = String::new();
1468        for attempt in &attempts.attempts {
1469            let file = logs.join(format!("{}.log", attempt.attempt_id));
1470            log.push_str(&std::fs::read_to_string(file).unwrap_or_default());
1471        }
1472        // Read from its files, not the API: masked as the API masks a log (B207).
1473        let log = schedr_config::masked::mask_text(&log);
1474        let output =
1475            if task.instances.is_some() {
1476                client
1477                    .instance_output(run_id, &task.task_id, None)
1478                    .await
1479                    .ok()
1480                    .map(|o| o.value)
1481            } else {
1482                match schedr_model::TaskId::new(task.task_id.clone()) {
1483                    // From the database, not the API: masked as the API masks an output (B207).
1484                    Ok(id) => db.instance_output(run_id, &id, task.map_index).await?.map(
1485                        |(_, mut value)| {
1486                            schedr_config::masked::mask_data(&mut value);
1487                            value
1488                        },
1489                    ),
1490                    Err(_) => None,
1491                }
1492            };
1493        tasks.push(json!({
1494            "task_id": task.task_id,
1495            "map_index": task.map_index,
1496            "instances": task.instances,
1497            "state": task.state,
1498            "outcome": task.outcome,
1499            "try_number": task.try_number,
1500            "cleanup": task.cleanup,
1501            "output": output,
1502            "attempts": attempts.attempts,
1503            "log": log,
1504        }));
1505    }
1506    // What the run would have notified: kept in the outbox, never sent (masked, as a log is).
1507    let notifications: Vec<Value> = db
1508        .due_notifications(jiff::Timestamp::MAX, u32::MAX)
1509        .await?
1510        .into_iter()
1511        .map(reported_notification)
1512        .collect();
1513    Ok(json!({
1514        "run": detail.run,
1515        "location": location,
1516        "tasks": tasks,
1517        "resources": detail.resources,
1518        "notifications": notifications,
1519    }))
1520}
1521
1522/// A notification the run would have sent, as the report shows it: its body masked as data,
1523/// as a task's output is (as text, after JSON escaped it, a secret in an email's text or a
1524/// nested object would show: Grok's review).
1525fn reported_notification(notification: schedr_db::notifications::Notification) -> Value {
1526    let mut body = notification.body;
1527    schedr_config::masked::mask_data(&mut body);
1528    json!({
1529        "channel": notification.channel,
1530        "kind": notification.kind,
1531        "event": notification.event,
1532        "body": body,
1533    })
1534}
1535
1536/// A task as the report shows it: `fetch`, or `fetch[2]` for an instance (decision 86).
1537fn shown_name(task: &schedr_api::views::TaskView) -> String {
1538    if task.map_index >= 0 {
1539        format!("{}[{}]", task.task_id, task.map_index)
1540    } else {
1541        task.task_id.clone()
1542    }
1543}
1544
1545/// [`shown_name`] of a task in the report's JSON.
1546fn reported_name(task: &Value) -> String {
1547    let id = task["task_id"].as_str().unwrap_or_default();
1548    match task["map_index"].as_i64() {
1549        Some(index) if index >= 0 => format!("{id}[{index}]"),
1550        _ => id.to_owned(),
1551    }
1552}
1553
1554fn print_report(report: &Value, out: &mut impl Write) -> Result<(), AppError> {
1555    let empty = Vec::new();
1556    let tasks = report["tasks"].as_array().unwrap_or(&empty);
1557    for task in tasks {
1558        let name = reported_name(task);
1559        let id = name.as_str();
1560        for line in task["log"].as_str().unwrap_or_default().lines() {
1561            writeln!(out, "{id} | {line}")?;
1562        }
1563        for attempt in task["attempts"].as_array().unwrap_or(&empty) {
1564            let error = &attempt["error_summary"];
1565            if error.is_null() {
1566                continue;
1567            }
1568            writeln!(
1569                out,
1570                "{id} | try {} failed ({}):",
1571                attempt["try_number"],
1572                attempt["error_kind"].as_str().unwrap_or("error")
1573            )?;
1574            match error["traceback"].as_str().filter(|t| !t.is_empty()) {
1575                Some(traceback) => {
1576                    for line in traceback.lines() {
1577                        writeln!(out, "{id} | {line}")?;
1578                    }
1579                }
1580                None => writeln!(
1581                    out,
1582                    "{id} | {}: {}",
1583                    error["exception"].as_str().unwrap_or_default(),
1584                    error["message"].as_str().unwrap_or_default()
1585                )?,
1586            }
1587        }
1588    }
1589    let rows: Vec<Vec<String>> = tasks
1590        .iter()
1591        .map(|task| {
1592            vec![
1593                reported_name(task),
1594                task["state"].as_str().unwrap_or_default().to_owned(),
1595                task["outcome"].as_str().unwrap_or("-").to_owned(),
1596                task["try_number"].to_string(),
1597                duration(task),
1598            ]
1599        })
1600        .collect();
1601    crate::user::write_table(
1602        out,
1603        &["TASK", "STATE", "OUTCOME", "TRIES", "DURATION"],
1604        &rows,
1605    )?;
1606    writeln!(out, "outputs:")?;
1607    for task in tasks {
1608        if !task["output"].is_null() {
1609            // Named as in the table: `fetch` the gathered list, `fetch[0]` an instance's.
1610            writeln!(out, "  {}: {}", reported_name(task), task["output"])?;
1611        }
1612    }
1613    let notifications = report["notifications"].as_array().unwrap_or(&empty);
1614    if !notifications.is_empty() {
1615        writeln!(out, "notifications (not sent):")?;
1616        for notification in notifications {
1617            writeln!(
1618                out,
1619                "  {}: {}",
1620                notification["channel"].as_str().unwrap_or_default(),
1621                notification["event"].as_str().unwrap_or_default()
1622            )?;
1623        }
1624    }
1625    writeln!(
1626        out,
1627        "run {}: {}",
1628        report["run"]["run_id"].as_str().unwrap_or_default(),
1629        report["run"]["state"].as_str().unwrap_or_default()
1630    )?;
1631    Ok(())
1632}
1633
1634/// How long the task's last attempt ran, e.g. `1.2s`; `-` if it never started.
1635/// The last attempt's duration as the worker measured it (the start and end timestamps come
1636/// from the master's wall clock, which can step, so they aren't subtracted).
1637fn duration(task: &Value) -> String {
1638    task["attempts"]
1639        .as_array()
1640        .and_then(|a| a.last())
1641        .and_then(|last| last["duration_ms"].as_u64())
1642        .map_or_else(|| "-".to_owned(), crate::user::seconds)
1643}
1644
1645const fn not_yet(command: &'static str, milestone: &'static str) -> AppError {
1646    AppError::NotImplemented { command, milestone }
1647}