fleche 6.26.0

Remote job runner for Slurm clusters
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
//! Job status operations - viewing status, notes, and tags.

use crate::error::{FlecheError, Result};
use crate::local;
use crate::output::OutputFormat;
use crate::registry::{
    ArchivedFilter, JobRecord, JobStatus, LiveStatus, Registry, build_job_filter_pattern,
};
use crate::runtime::RuntimeCtx;
use crate::slurm::{get_job_resource_usage, get_job_status};
use console::style;
use regex::Regex;
use serde::Serialize;
use std::io::{self, Write};
use std::path::PathBuf;
use std::time::Duration;

use super::display::{print_indexed_job_table, print_job_details, print_job_table};
use super::get_remote_direct_job_status;
use super::job_path_from_workspace;

/// Default number of jobs to show when no limit is specified and no config is available.
const DEFAULT_LIST_LIMIT: usize = 20;

/// Filtering and display options for job listings.
///
/// All fields default to their permissive/empty value, so callers can set only
/// the fields they care about via struct update syntax:
///
/// ```ignore
/// show_status(None, StatusOptions { last: Some(5), ..Default::default() }, ctx).await?;
/// ```
#[derive(Default)]
pub struct StatusOptions<'a> {
    /// Status strings (e.g. `"failed"`, `"running"`) to restrict results.
    pub filters: &'a [String],
    /// Regex pattern matched against job IDs.
    pub name: Option<&'a str>,
    /// Key-value pairs that must all match for a job to be included.
    pub tags: &'a [(String, String)],
    /// Maximum number of jobs to display. Falls back to `default_limit`,
    /// then to [`DEFAULT_LIST_LIMIT`].
    pub last: Option<usize>,
    /// Caller-supplied default (typically from config) used when `last` is `None`.
    pub default_limit: Option<usize>,
    /// Controls visibility of archived jobs. The default
    /// [`ExcludeArchived`](ArchivedFilter::ExcludeArchived) variant displays
    /// numeric indices; other variants omit them.
    pub archived: ArchivedFilter,
    /// Hide the subtitle line (job name, tags, note) below each row.
    pub compact: bool,
    /// Output format (human-readable or JSON).
    pub format: OutputFormat,
}

/// Queries the live status of a job from its execution environment.
///
/// Dispatches to the appropriate backend (local process, Slurm, or remote exec)
/// based on the job record. Does not update the registry — callers handle that.
async fn query_live_status(job: &JobRecord, ctx: &RuntimeCtx) -> Result<LiveStatus> {
    if job.remote_host == "local" {
        let project_path = PathBuf::from(&job.project_path);
        return local::get_local_job_status(&project_path, &job.id);
    }

    let ssh = ctx.ssh(&job.remote_host);
    if let Some(ref slurm_id) = job.slurm_id {
        get_job_status(&ssh, slurm_id).await
    } else {
        let job_dir = job_path_from_workspace(&job.remote_path, &job.id);
        get_remote_direct_job_status(&ssh, &job_dir).await
    }
}

/// Shows the status of a specific job or lists recent jobs.
///
/// When `job_id` is provided, queries the job's live status from its execution
/// environment (local process, Slurm, or remote exec), updates the registry,
/// and prints detailed information. The `opts` fields are ignored.
///
/// When `job_id` is `None`, refreshes all active jobs and lists recent ones
/// filtered according to `opts`.
pub async fn show_status(
    job_id: Option<&str>,
    opts: StatusOptions<'_>,
    ctx: RuntimeCtx,
) -> Result<()> {
    let registry = Registry::open()?;

    if let Some(id) = job_id {
        show_job_detail(&registry, id, &ctx, opts.format).await?;
    } else {
        refresh_active_job_statuses(&registry, &ctx).await?;
        list_recent_jobs(&registry, &opts)?;
    }

    Ok(())
}

/// Converts a refresh interval given in seconds into a [`Duration`].
///
/// Rejects non-finite values and anything `<= 0`, since a zero or negative
/// interval would make the watch loop spin without pausing.
pub fn parse_interval_secs(secs: f64) -> Result<Duration> {
    if !secs.is_finite() || secs <= 0.0 {
        return Err(FlecheError::InvalidArgument(format!(
            "--interval must be a positive number of seconds, got {secs}"
        )));
    }
    Ok(Duration::from_secs_f64(secs))
}

/// Begins a synchronized-output frame (terminal mode 2026).
///
/// Terminals that understand this hold rendering until [`SYNC_END`], then swap
/// the whole frame in atomically — so the screen never shows a half-cleared
/// state. Terminals that don't understand it ignore the sequence.
const SYNC_BEGIN: &str = "\x1b[?2026h";
/// Ends a synchronized-output frame (see [`SYNC_BEGIN`]).
const SYNC_END: &str = "\x1b[?2026l";
/// Erase the entire screen and move the cursor home.
const CLEAR_HOME: &str = "\x1b[2J\x1b[H";

/// Continuously refreshes and redraws the recent-jobs table until interrupted.
///
/// Clears the screen and reprints the table every `interval`, reusing the same
/// filtering/display configuration as [`show_status`]. A failed refresh tick is
/// reported in place and the loop continues; the loop only ends when the user
/// interrupts it (Ctrl+C). JSON output is unsupported because clearing the
/// screen each tick is meaningless for machine-readable output.
///
/// To avoid flicker, the (slow) remote refresh runs *before* the frame is
/// drawn, then the clear-and-redraw is wrapped in a synchronized-output frame
/// so it presents atomically. The refresh is kept outside that frame because
/// terminals time out synchronized output after ~150ms, which a slow SSH
/// refresh would otherwise blow through.
pub async fn watch_status(
    opts: StatusOptions<'_>,
    interval: Duration,
    ctx: RuntimeCtx,
) -> Result<()> {
    if !opts.format.is_human() {
        return Err(FlecheError::InvalidArgument(
            "fleche watch does not support --json; use `fleche status --json` instead".to_string(),
        ));
    }

    let registry = Registry::open()?;
    let header = style(format!(
        "fleche watch — every {}s — Ctrl+C to stop",
        interval.as_secs_f64()
    ))
    .dim();

    loop {
        // Slow remote work first, outside the synchronized frame.
        let refresh = refresh_active_job_statuses(&registry, &ctx).await;

        // Fast, atomic redraw: clear + render from the local registry.
        print!("{SYNC_BEGIN}{CLEAR_HOME}");
        println!("{header}");
        println!();
        match refresh.and_then(|()| list_recent_jobs(&registry, &opts)) {
            Ok(()) => {}
            Err(e) => println!("{} {e}", style("refresh error:").red()),
        }
        print!("{SYNC_END}");
        let _ = io::stdout().flush();

        tokio::time::sleep(interval).await;
    }
}

/// Shows detailed status for a single job, refreshing its live status first.
async fn show_job_detail(
    registry: &Registry,
    id: &str,
    ctx: &RuntimeCtx,
    format: OutputFormat,
) -> Result<()> {
    let mut job = registry.get_job(id)?;

    if let Ok(live) = query_live_status(&job, ctx).await {
        registry.update_status(&job.id, &live)?;
        job.status = live.status;
        job.exit_code = live.exit_code;
        job.slurm_state = live.slurm_state;
        job.sacct_exit_code = live.sacct_exit_code;
    }

    // Fetch resource usage for finished Slurm jobs
    let usage = if let Some(ref slurm_id) = job.slurm_id {
        if job.remote_host != "local"
            && matches!(
                job.status,
                JobStatus::Completed | JobStatus::Failed | JobStatus::Cancelled
            )
        {
            let ssh = ctx.ssh(&job.remote_host);
            get_job_resource_usage(&ssh, slurm_id).await.ok()
        } else {
            None
        }
    } else {
        None
    };

    format.print(&job, || {
        print_job_details(&job, usage.as_ref());
        Ok(())
    })
}

/// Lists recent jobs with optional filtering.
fn list_recent_jobs(registry: &Registry, opts: &StatusOptions<'_>) -> Result<()> {
    let status_filters: Vec<JobStatus> = opts
        .filters
        .iter()
        .map(|f| f.parse())
        .collect::<Result<Vec<_>>>()?;

    let limit = opts
        .last
        .unwrap_or_else(|| opts.default_limit.unwrap_or(DEFAULT_LIST_LIMIT));

    let jobs = if opts.archived == ArchivedFilter::ExcludeArchived {
        // Default view: filter in Rust to preserve global indices that
        // match get_job_by_index().
        let (indices, jobs) = list_indexed_jobs(registry, opts, &status_filters, limit)?;
        if opts.format.is_human() && !jobs.is_empty() {
            print_indexed_job_table(&jobs, &indices, !opts.compact);
        }
        jobs
    } else {
        // Archived or "show all" view: indices would not match
        // get_job_by_index(), so omit them.
        let jobs = registry.list_jobs(
            None,
            &status_filters,
            opts.name,
            None,
            opts.tags,
            opts.archived,
            limit,
        )?;
        if opts.format.is_human() && !jobs.is_empty() {
            print_job_table(&jobs, !opts.compact);
        }
        jobs
    };

    opts.format.print(&jobs, || {
        if jobs.is_empty() {
            println!("No jobs found. Run `fleche run` to submit a job.");
        }
        Ok(())
    })
}

/// Fetches and filters non-archived jobs, returning 1-based global indices
/// alongside the matched records.
fn list_indexed_jobs(
    registry: &Registry,
    opts: &StatusOptions<'_>,
    status_filters: &[JobStatus],
    limit: usize,
) -> Result<(Vec<usize>, Vec<JobRecord>)> {
    let has_filters = !status_filters.is_empty() || opts.name.is_some() || !opts.tags.is_empty();
    let fetch_limit = if has_filters {
        limit.saturating_mul(10).max(1000)
    } else {
        limit
    };

    let all_jobs = registry.list_all_jobs(fetch_limit)?;

    let name_re = opts
        .name
        .map(|p| {
            let pattern = build_job_filter_pattern(p);
            Regex::new(&pattern)
                .map_err(|e| FlecheError::InvalidRegexPattern(format!("--name '{p}': {e}")))
        })
        .transpose()?;

    Ok(all_jobs
        .into_iter()
        .enumerate()
        .filter(|(_, job)| {
            (status_filters.is_empty() || status_filters.contains(&job.status))
                && name_re.as_ref().is_none_or(|re| re.is_match(&job.id))
                && opts
                    .tags
                    .iter()
                    .all(|(k, v)| job.tags.get(k).is_some_and(|tv| tv == v))
        })
        .take(limit)
        .map(|(i, job)| (i + 1, job))
        .unzip())
}

/// Adds or displays a note on a job.
///
/// If `note` is provided, sets or updates the job's note.
/// If `note` is `None`, displays the existing note (if any).
pub fn note_job(job_id: &str, note: Option<&str>) -> Result<()> {
    let registry = Registry::open()?;
    let job = registry.get_job(job_id)?;

    if let Some(note_text) = note {
        registry.set_note(&job.id, Some(note_text))?;
        println!(
            "{} Note set for job {}",
            style("").green(),
            style(&job.id).bold()
        );
    } else {
        // Display existing note
        match job.note {
            Some(ref note_text) => {
                println!("{} {}", style("Note:").bold(), note_text);
            }
            None => {
                println!("No note set for job {}.", job.id);
            }
        }
    }

    Ok(())
}

/// A unique tag key-value pair for JSON output.
#[derive(Serialize)]
struct TagEntry {
    key: String,
    value: String,
}

/// Converts raw tag tuples into structured entries for JSON output.
fn to_tag_entries(tags: Vec<(String, String)>) -> Vec<TagEntry> {
    tags.into_iter()
        .map(|(key, value)| TagEntry { key, value })
        .collect()
}

/// Lists all unique tags across jobs.
pub fn list_tags(format: OutputFormat) -> Result<()> {
    let registry = Registry::open()?;
    let tags = registry.list_unique_tags()?;
    let entries = to_tag_entries(tags);

    format.print(&entries, || {
        if entries.is_empty() {
            println!("No tags found. Use --tag when running jobs to add tags.");
            return Ok(());
        }

        // Group by key
        let mut current_key = "";
        for entry in &entries {
            if entry.key != current_key {
                if !current_key.is_empty() {
                    println!();
                }
                println!("{}", style(&entry.key).bold());
                current_key = &entry.key;
            }
            println!("  {}", entry.value);
        }

        Ok(())
    })
}

/// Refreshes the status of all pending/running jobs from Slurm or local process status.
pub async fn refresh_active_job_statuses(registry: &Registry, ctx: &RuntimeCtx) -> Result<()> {
    let active_jobs = registry.list_active_jobs()?;

    for job in active_jobs {
        if let Ok(live) = query_live_status(&job, ctx).await {
            if live.status != job.status {
                registry.update_status(&job.id, &live)?;
            }
        }
    }

    Ok(())
}

/// Resolves a job ID or gets the most recent job matching criteria.
pub fn resolve_job(
    registry: &Registry,
    job_id: Option<&str>,
    tags: &[(String, String)],
    note_filter: Option<&str>,
) -> Result<JobRecord> {
    if let Some(id) = job_id {
        registry.get_job(id)
    } else {
        registry
            .list_jobs(
                None,
                &[],
                None,
                note_filter,
                tags,
                ArchivedFilter::ExcludeArchived,
                1,
            )?
            .into_iter()
            .next()
            .ok_or(FlecheError::NoRecentJob)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parse_interval_accepts_positive_values() {
        assert_eq!(parse_interval_secs(1.0).unwrap(), Duration::from_secs(1));
        assert_eq!(
            parse_interval_secs(0.5).unwrap(),
            Duration::from_millis(500)
        );
    }

    #[test]
    fn parse_interval_rejects_zero_and_negative() {
        assert!(parse_interval_secs(0.0).is_err());
        assert!(parse_interval_secs(-1.0).is_err());
    }

    #[test]
    fn parse_interval_rejects_non_finite() {
        assert!(parse_interval_secs(f64::NAN).is_err());
        assert!(parse_interval_secs(f64::INFINITY).is_err());
    }
}