Skip to main content

sacct_parse/
lib.rs

1//! Parse Slurm `sacct --parsable2` rows into typed records.
2//!
3//! [`sacct`](https://slurm.schedmd.com/sacct.html) prints one pipe-separated
4//! line per accounting row. This crate reads one line at a time and turns it
5//! into a [`Record`]: timestamps as Unix seconds, runtimes as seconds, wall
6//! limits as [`Limit`], job states as a [`State`] enum, and allocated
7//! resources as a count per resource name. A row that cannot be read earns an
8//! [`Error`] that names the row and the field, never a quiet default.
9//!
10//! # The clock is the caller's
11//!
12//! `sacct` prints local clock readings with no zone on them. This crate does
13//! not carry a timezone database and does not guess one: every parsing
14//! function takes `utc_offset_seconds`, the zone's offset at the time of the
15//! export, and computes `unix = civil_interpreted_as_utc − utc_offset_seconds`.
16//! A site whose clock changes mid-export makes two calls with two offsets;
17//! the crate stays arithmetic.
18//!
19//! # Parsing, not deciding
20//!
21//! Every row parses. Job steps are still records — [`Record::is_step`] says
22//! which they are, and the caller decides what to do with them. An
23//! unfinished job parses like a finished one. Nothing here filters by GPU,
24//! renumbers ids, applies tiers, or writes a file.
25
26use std::collections::BTreeMap;
27
28/// The number of `--format` fields the documented `sacct` invocation has.
29const FORMAT_FIELDS: usize = 11;
30
31/// `TimelimitRaw` for a job with no wall-clock limit.
32const UNLIMITED_TOKEN: &str = "UNLIMITED";
33
34/// The `AllocTRES` key for a job's whole GPU allocation.
35const GPU_TOTAL_KEY: &str = "gres/gpu";
36
37/// The `AllocTRES` key prefix for one GPU type of an allocation.
38const GPU_TYPE_PREFIX: &str = "gres/gpu:";
39
40/// One parsed `sacct` row. **Data.**
41///
42/// Every field is the row's own, typed and unfiltered: a step, a running job
43/// and a finished job all parse, and what to keep is the caller's decision.
44#[derive(Debug, Clone, PartialEq, Eq)]
45pub struct Record {
46    /// `JobIDRaw` as printed: `1041`, or `1041.batch` for a job step.
47    pub job_id: String,
48    /// `Submit` as Unix seconds, from a civil reading and the caller's offset.
49    pub submit: i64,
50    /// `Start` as Unix seconds.
51    pub start: i64,
52    /// `End` as Unix seconds.
53    pub end: i64,
54    /// `ElapsedRaw` in seconds.
55    pub elapsed_seconds: u64,
56    /// `AllocTRES` as a count per resource name, in name order.
57    pub alloc_tres: BTreeMap<String, u64>,
58    /// `TimelimitRaw` in minutes, or no limit at all.
59    pub timelimit: Limit,
60    /// `QOS` as printed.
61    pub qos: String,
62    /// `Partition` as printed.
63    pub partition: String,
64    /// `State`, matched on its first whitespace-separated word.
65    pub state: State,
66    /// `User` as printed.
67    pub user: String,
68}
69
70impl Record {
71    /// Whether this row is a job step rather than a job. **Calculation.**
72    ///
73    /// Slurm writes a step's `JobIDRaw` with a dot — `1041.batch`, `1044.0` —
74    /// and the step is part of the job whose own row is in the same export.
75    #[must_use]
76    pub fn is_step(&self) -> bool {
77        self.job_id.contains('.')
78    }
79
80    /// The GPUs this record's `AllocTRES` allocates. **Calculation.**
81    ///
82    /// Slurm writes both a total and a per-type breakdown when a job asked
83    /// for a typed GPU — `gres/gpu=3,gres/gpu:a100=3` — so the total wins
84    /// where it is present, and the types are summed only where it is not.
85    /// Adding both would count the job twice.
86    #[must_use]
87    pub fn gpu_count(&self) -> u64 {
88        if let Some(total) = self.alloc_tres.get(GPU_TOTAL_KEY) {
89            return *total;
90        }
91        self.alloc_tres
92            .iter()
93            .filter(|(key, _)| key.starts_with(GPU_TYPE_PREFIX))
94            .map(|(_, count)| *count)
95            .sum()
96    }
97}
98
99/// `TimelimitRaw`: the minutes a job asked for, or no limit. **Data.**
100#[derive(Debug, Clone, Copy, PartialEq, Eq)]
101pub enum Limit {
102    /// A wall-clock limit, in minutes.
103    Minutes(u32),
104    /// The row printed `UNLIMITED`.
105    Unlimited,
106}
107
108/// `State`, matched on the first whitespace-separated word of the field.
109/// **Data.**
110///
111/// `sacct` appends a clause to some states — `CANCELLED by 1001` — and the
112/// clause is not part of the state.
113#[derive(Debug, Clone, PartialEq, Eq)]
114pub enum State {
115    /// The job ran and finished within its limit.
116    Completed,
117    /// The job hit its wall-clock limit.
118    Timeout,
119    /// The job ran and exited with a failure.
120    Failed,
121    /// The job was cancelled, by a user or the scheduler.
122    Cancelled,
123    /// The job is running now; its runtime is not final.
124    Running,
125    /// The job is queued and has not started.
126    Pending,
127    /// Any other state, carried as printed.
128    Other(String),
129}
130
131impl State {
132    /// The state one `State` field carries. **Calculation.**
133    fn parse(field: &str) -> Self {
134        match field.split_whitespace().next().unwrap_or_default() {
135            "COMPLETED" => Self::Completed,
136            "TIMEOUT" => Self::Timeout,
137            "FAILED" => Self::Failed,
138            "CANCELLED" => Self::Cancelled,
139            "RUNNING" => Self::Running,
140            "PENDING" => Self::Pending,
141            other => Self::Other(other.to_owned()),
142        }
143    }
144}
145
146/// Why a row could not be parsed. **Data.**
147///
148/// Every variant names the row, counted from 1, and the field that failed,
149/// because "row 12 is bad" sends a reader back to the file and "row 12,
150/// `ElapsedRaw`" sends them to the field.
151#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
152pub enum Error {
153    /// The row does not have the 11 documented `--format` fields.
154    #[error("row {row}: has {actual} fields, and the documented sacct format has {expected}")]
155    Arity {
156        /// The row's line number in the export, counted from 1.
157        row: usize,
158        /// The number of fields the documented format has.
159        expected: usize,
160        /// The number of fields the row has.
161        actual: usize,
162    },
163
164    /// A field holds a value this crate cannot read.
165    #[error("row {row}: field `{field}` holds `{value}`, which is not {expected}")]
166    Field {
167        /// The row's line number in the export, counted from 1.
168        row: usize,
169        /// The field that failed, named as the `--format` names it.
170        field: &'static str,
171        /// The value as printed.
172        value: String,
173        /// What the field was expected to hold.
174        expected: &'static str,
175    },
176}
177
178/// One `sacct` row, split into its fields. **Data.**
179struct Fields<'a> {
180    job_id: &'a str,
181    submit: &'a str,
182    start: &'a str,
183    end: &'a str,
184    elapsed: &'a str,
185    tres: &'a str,
186    timelimit: &'a str,
187    qos: &'a str,
188    partition: &'a str,
189    state: &'a str,
190    user: &'a str,
191}
192
193impl<'a> Fields<'a> {
194    /// One `|`-separated line, split into the documented fields.
195    /// **Calculation.**
196    fn parse(row: usize, line: &'a str) -> Result<Self, Error> {
197        let fields: Vec<&str> = line.split('|').map(str::trim).collect();
198        let actual = fields.len();
199        let [job_id, submit, start, end, elapsed, tres, timelimit, qos, partition, state, user] =
200            fields[..]
201        else {
202            return Err(Error::Arity {
203                row,
204                expected: FORMAT_FIELDS,
205                actual,
206            });
207        };
208
209        Ok(Self {
210            job_id,
211            submit,
212            start,
213            end,
214            elapsed,
215            tres,
216            timelimit,
217            qos,
218            partition,
219            state,
220            user,
221        })
222    }
223
224    /// A timestamp field, read as a civil clock reading and turned into Unix
225    /// seconds with the caller's offset. **Calculation.**
226    ///
227    /// `sacct` writes `Unknown` for a stamp the job has not earned yet; a
228    /// reading without the expected shape is a field error, not a zero.
229    fn timestamp(
230        &self,
231        row: usize,
232        field: &'static str,
233        text: &'a str,
234        utc_offset_seconds: i64,
235    ) -> Result<i64, Error> {
236        let bad = |value: &str, expected: &'static str| Error::Field {
237            row,
238            field,
239            value: value.to_owned(),
240            expected,
241        };
242
243        if text.is_empty() || text == "Unknown" {
244            return Err(bad(
245                text,
246                "a clock reading like 2026-03-02T08:15:00, not Unknown",
247            ));
248        }
249        let Some((date, time)) = text.split_once('T') else {
250            return Err(bad(text, "a clock reading like 2026-03-02T08:15:00"));
251        };
252        let days = civil_days(row, field, date)?;
253        let Some((hour, rest)) = time.split_once(':') else {
254            return Err(bad(text, "a clock reading like 2026-03-02T08:15:00"));
255        };
256        let (minute, second) = match rest.split_once(':') {
257            Some((minute, second)) => (minute, second),
258            None => (rest, "00"),
259        };
260        let hour: i64 = whole(row, field, hour, "an hour of the day")?;
261        let minute: i64 = whole(row, field, minute, "a minute of the hour")?;
262        let second: i64 = whole(row, field, second, "a second of the minute")?;
263        if !(0..24).contains(&hour) || !(0..60).contains(&minute) || !(0..60).contains(&second) {
264            return Err(bad(
265                text,
266                "a clock reading whose time is a real time of day",
267            ));
268        }
269        Ok(days * 86_400 + hour * 3_600 + minute * 60 + second - utc_offset_seconds)
270    }
271
272    /// `ElapsedRaw` as seconds. **Calculation.**
273    fn elapsed(&self, row: usize) -> Result<u64, Error> {
274        self.elapsed.parse().map_err(|_| Error::Field {
275            row,
276            field: "ElapsedRaw",
277            value: self.elapsed.to_owned(),
278            expected: "a count of seconds",
279        })
280    }
281
282    /// `AllocTRES` as a count per resource name. **Calculation.**
283    ///
284    /// An entry without `=` carries no count and is carried as `0`. A count
285    /// that carries a Slurm size suffix — `mem=256G` — is carried as the
286    /// number Slurm printed, with the suffix dropped; the suffix is not
287    /// converted, because a count of resources and a quantity of memory are
288    /// different things and this map holds counts.
289    fn tres(&self, row: usize) -> Result<BTreeMap<String, u64>, Error> {
290        let mut map = BTreeMap::new();
291        for entry in self.tres.split(',').filter(|entry| !entry.is_empty()) {
292            let (name, count) = match entry.split_once('=') {
293                Some((name, count)) => (name, count),
294                None => (entry, "0"),
295            };
296            let count: u64 = count_of(row, count)?;
297            map.insert(name.to_owned(), count);
298        }
299        Ok(map)
300    }
301
302    /// `TimelimitRaw` as a limit. **Calculation.**
303    fn timelimit(&self, row: usize) -> Result<Limit, Error> {
304        if self.timelimit == UNLIMITED_TOKEN {
305            return Ok(Limit::Unlimited);
306        }
307        self.timelimit
308            .parse()
309            .map(Limit::Minutes)
310            .map_err(|_| Error::Field {
311                row,
312                field: "TimelimitRaw",
313                value: self.timelimit.to_owned(),
314                expected: "a count of minutes, or UNLIMITED",
315            })
316    }
317}
318
319/// A whole number a timestamp part carries. **Calculation.**
320fn whole(
321    row: usize,
322    field: &'static str,
323    text: &str,
324    expected: &'static str,
325) -> Result<i64, Error> {
326    text.parse().map_err(|_| Error::Field {
327        row,
328        field,
329        value: text.to_owned(),
330        expected,
331    })
332}
333
334/// The days since the Unix epoch a `YYYY-MM-DD` date carries, as a civil
335/// calculation with no zone and no table. **Calculation.**
336///
337/// This is Howard Hinnant's `days_from_civil`, reduced to what a date needs:
338/// a month of 1–12, a day of 1–31 that the month and year must be able to
339/// hold, and arithmetic that treats year 0 like any other.
340fn civil_days(row: usize, field: &'static str, date: &str) -> Result<i64, Error> {
341    let bad = |value: &str, expected: &'static str| Error::Field {
342        row,
343        field,
344        value: value.to_owned(),
345        expected,
346    };
347
348    let parts: Vec<&str> = date.split('-').collect();
349    let [year, month, day] = parts[..] else {
350        return Err(bad(date, "a date like 2026-03-02"));
351    };
352    let year: i64 = whole(row, field, year, "a year")?;
353    let month: i64 = whole(row, field, month, "a month from 1 to 12")?;
354    let day: i64 = whole(row, field, day, "a day from 1 to 31")?;
355    if !(1..=12).contains(&month) || !(1..=31).contains(&day) {
356        return Err(bad(date, "a date whose month and day are real"));
357    }
358    let leap = month <= 2;
359    let era = if year >= 0 { year } else { year - 399 } / 400;
360    let year_of_era = year - era * 400;
361    let day_of_year = (153 * (month + if leap { 9 } else { -3 }) + 2) / 5 + day - 1;
362    let day_of_era = year_of_era * 365 + year_of_era / 4 - year_of_era / 100 + day_of_year;
363    Ok(era * 146_097 + day_of_era - 719_468)
364}
365
366/// The count one `AllocTRES` entry carries. **Calculation.**
367///
368/// A count may carry a Slurm size suffix — `256G` — and any such suffix is
369/// dropped without conversion: the map holds the number Slurm printed. A
370/// value with no number in it at all is a fault.
371fn count_of(row: usize, text: &str) -> Result<u64, Error> {
372    let bad = Error::Field {
373        row,
374        field: "AllocTRES",
375        value: text.to_owned(),
376        expected: "a count for a resource in the AllocTRES list",
377    };
378
379    let digits: &str = text
380        .split(|c: char| !c.is_ascii_digit() && c != '.')
381        .next()
382        .unwrap_or_default();
383    if let Ok(count) = digits.parse() {
384        return Ok(count);
385    }
386    digits
387        .parse::<f64>()
388        .ok()
389        .filter(|count| count.is_finite() && *count >= 0.0)
390        .map(|count| count as u64)
391        .ok_or(bad)
392}
393
394/// Parse one `sacct --parsable2 --noheader` row. **Calculation.**
395///
396/// The row's fields are, in order: `JobIDRaw, Submit, Start, End,
397/// ElapsedRaw, AllocTRES, TimelimitRaw, QOS, Partition, State, User`. The
398/// clock readings are civil time with no zone; `utc_offset_seconds` is the
399/// zone's offset, so `-21_600` for UTC-6, and the record's stamps are
400/// `civil_interpreted_as_utc − utc_offset_seconds`.
401///
402/// # Errors
403/// [`Error::Arity`] when the row has the wrong number of fields, and
404/// [`Error::Field`] naming the row and the field for any value that does not
405/// parse.
406pub fn parse_row(line: &str, utc_offset_seconds: i64) -> Result<Record, Error> {
407    parse_row_numbered(1, line, utc_offset_seconds)
408}
409
410/// [`parse_row`] with the row's own number, counted from 1. **Calculation.**
411fn parse_row_numbered(row: usize, line: &str, utc_offset_seconds: i64) -> Result<Record, Error> {
412    let fields = Fields::parse(row, line)?;
413    Ok(Record {
414        job_id: fields.job_id.to_owned(),
415        submit: fields.timestamp(row, "Submit", fields.submit, utc_offset_seconds)?,
416        start: fields.timestamp(row, "Start", fields.start, utc_offset_seconds)?,
417        end: fields.timestamp(row, "End", fields.end, utc_offset_seconds)?,
418        elapsed_seconds: fields.elapsed(row)?,
419        alloc_tres: fields.tres(row)?,
420        timelimit: fields.timelimit(row)?,
421        qos: fields.qos.to_owned(),
422        partition: fields.partition.to_owned(),
423        state: State::parse(fields.state),
424        user: fields.user.to_owned(),
425    })
426}
427
428/// Parse a whole `sacct --parsable2 --noheader` export. **Calculation.**
429///
430/// Blank lines are skipped. Every remaining line is parsed in order, and the
431/// first row that cannot be read fails the whole call with an error naming
432/// that row and field.
433///
434/// # Errors
435/// The first [`Error`] any row earns.
436pub fn parse_file(text: &str, utc_offset_seconds: i64) -> Result<Vec<Record>, Error> {
437    text.lines()
438        .enumerate()
439        .map(|(offset, line)| (offset + 1, line))
440        .filter(|(_, line)| !line.trim().is_empty())
441        .map(|(row, line)| parse_row_numbered(row, line, utc_offset_seconds))
442        .collect()
443}
444
445#[cfg(test)]
446mod tests {
447    use super::*;
448
449    const OFFSET: i64 = -21_600;
450
451    /// One row on the documented format, with every field a given test does
452    /// not care about already filled in: a finished one-GPU job.
453    ///
454    /// Synthetic data; nothing in these fixtures was measured.
455    fn row(job_id: &str, submit: &str, elapsed: &str, tres: &str, timelimit: &str) -> String {
456        [
457            job_id,
458            submit,
459            "2026-03-02T08:00:00",
460            "2026-03-02T09:00:00",
461            elapsed,
462            tres,
463            timelimit,
464            "normal",
465            "batch",
466            "COMPLETED",
467            "u01",
468        ]
469        .join("|")
470    }
471
472    fn parsed(line: &str) -> Record {
473        parse_row(line, OFFSET).expect("the row parses")
474    }
475
476    fn fault(line: &str) -> Error {
477        parse_row(line, OFFSET).expect_err("the row is rejected")
478    }
479
480    #[test]
481    fn a_finished_row_parses_into_a_record() {
482        let record = parsed(&row(
483            "101",
484            "2026-03-02T08:15:00",
485            "7200",
486            "cpu=8,gres/gpu=1",
487            "180",
488        ));
489
490        assert_eq!(record.job_id, "101");
491        assert!(!record.is_step());
492        assert_eq!(record.submit, 1_772_460_900);
493        assert_eq!(record.start, 1_772_460_000);
494        assert_eq!(record.end, 1_772_463_600);
495        assert_eq!(record.elapsed_seconds, 7_200);
496        assert_eq!(record.timelimit, Limit::Minutes(180));
497        assert_eq!(record.qos, "normal");
498        assert_eq!(record.partition, "batch");
499        assert_eq!(record.state, State::Completed);
500        assert_eq!(record.user, "u01");
501    }
502
503    #[test]
504    fn a_timestamp_is_the_civil_reading_minus_the_callers_offset() {
505        // `2026-03-02T08:15:00` read at UTC-6 is 14:15 UTC, so 1_772_460_900.
506        let record = parsed(&row("101", "2026-03-02T08:15:00", "7200", "cpu=8", "180"));
507        assert_eq!(record.submit, 1_772_460_900);
508
509        // The same reading at UTC+1 is 07:15 UTC, seven hours earlier.
510        let east = parse_row(
511            &row("101", "2026-03-02T08:15:00", "7200", "cpu=8", "180"),
512            3_600,
513        )
514        .expect("the row parses");
515        assert_eq!(east.submit, record.submit - 7 * 3_600);
516    }
517
518    #[test]
519    fn a_state_is_its_first_word_and_the_clause_is_not_part_of_it() {
520        let cancelled = State::parse("CANCELLED by 1001");
521        assert_eq!(cancelled, State::Cancelled);
522        assert_eq!(State::parse("RUNNING"), State::Running);
523        assert_eq!(State::parse("PENDING"), State::Pending);
524        assert_eq!(
525            State::parse("REQUEUED"),
526            State::Other("REQUEUED".to_owned())
527        );
528        assert_eq!(State::parse(""), State::Other(String::new()));
529    }
530
531    #[test]
532    fn a_row_with_the_wrong_field_count_names_the_row_and_the_counts() {
533        let short = "101|2026-03-02T08:15:00|7200|COMPLETED";
534
535        match fault(short) {
536            Error::Arity {
537                row,
538                expected,
539                actual,
540            } => {
541                assert_eq!(row, 1);
542                assert_eq!(expected, 11);
543                assert_eq!(actual, 4);
544            }
545            other => panic!("expected an arity error, got {other}"),
546        }
547    }
548
549    #[test]
550    fn an_unreadable_elapsed_names_the_row_and_elapsedraw() {
551        let line = row("101", "2026-03-02T08:15:00", "02:00:00", "cpu=8", "180");
552
553        match fault(&line) {
554            Error::Field {
555                row,
556                field,
557                value,
558                expected,
559            } => {
560                assert_eq!(row, 1);
561                assert_eq!(field, "ElapsedRaw");
562                assert_eq!(value, "02:00:00");
563                assert_eq!(expected, "a count of seconds");
564            }
565            other => panic!("expected a field error, got {other}"),
566        }
567    }
568
569    #[test]
570    fn an_unreadable_timelimit_names_the_row_and_timelimitraw() {
571        let line = row("101", "2026-03-02T08:15:00", "7200", "cpu=8", "3:00:00");
572
573        assert!(matches!(
574            fault(&line),
575            Error::Field {
576                field: "TimelimitRaw",
577                ..
578            }
579        ));
580    }
581
582    #[test]
583    fn unlimited_is_a_limit_and_not_a_fault() {
584        let line = row("101", "2026-03-02T08:15:00", "7200", "cpu=8", "UNLIMITED");
585
586        assert_eq!(parsed(&line).timelimit, Limit::Unlimited);
587    }
588
589    #[test]
590    fn an_unreadable_tres_count_names_the_row_and_alloctres() {
591        let line = row("101", "2026-03-02T08:15:00", "7200", "gres/gpu=many", "180");
592
593        assert!(matches!(
594            fault(&line),
595            Error::Field {
596                field: "AllocTRES",
597                ..
598            }
599        ));
600    }
601
602    #[test]
603    fn an_unknown_stamp_names_the_row_and_the_field() {
604        let line = [
605            "101",
606            "2026-03-02T08:15:00",
607            "Unknown",
608            "2026-03-02T09:00:00",
609            "7200",
610            "cpu=8",
611            "180",
612            "normal",
613            "batch",
614            "COMPLETED",
615            "u01",
616        ]
617        .join("|");
618
619        assert!(matches!(fault(&line), Error::Field { field: "Start", .. }));
620    }
621
622    #[test]
623    fn an_impossible_date_names_the_row_and_the_field() {
624        let line = row("101", "2026-13-02T08:15:00", "7200", "cpu=8", "180");
625
626        assert!(matches!(
627            fault(&line),
628            Error::Field {
629                field: "Submit",
630                ..
631            }
632        ));
633    }
634
635    #[test]
636    fn an_impossible_time_of_day_names_the_row_and_the_field() {
637        let line = row("101", "2026-03-02T25:15:00", "7200", "cpu=8", "180");
638
639        assert!(matches!(
640            fault(&line),
641            Error::Field {
642                field: "Submit",
643                ..
644            }
645        ));
646    }
647
648    #[test]
649    fn alloc_tres_carries_a_count_per_resource_and_drops_size_suffixes() {
650        let record = parsed(&row(
651            "101",
652            "2026-03-02T08:15:00",
653            "7200",
654            "billing=32,cpu=32,gres/gpu=4,mem=256G,node=2",
655            "180",
656        ));
657
658        let keys: Vec<&str> = record.alloc_tres.keys().map(String::as_str).collect();
659        assert_eq!(keys, vec!["billing", "cpu", "gres/gpu", "mem", "node"]);
660        assert_eq!(record.alloc_tres["mem"], 256);
661        assert_eq!(record.alloc_tres["node"], 2);
662    }
663
664    #[test]
665    fn the_gpu_total_wins_and_is_never_added_to_its_own_breakdown() {
666        let both = parsed(&row(
667            "101",
668            "2026-03-02T08:15:00",
669            "7200",
670            "cpu=8,gres/gpu=3,gres/gpu:a100=3",
671            "180",
672        ));
673        assert_eq!(both.gpu_count(), 3);
674    }
675
676    #[test]
677    fn typed_gpus_are_summed_when_the_total_is_absent() {
678        let typed = parsed(&row(
679            "101",
680            "2026-03-02T08:15:00",
681            "7200",
682            "cpu=8,gres/gpu:a100=2,gres/gpu:h100=1",
683            "180",
684        ));
685        assert_eq!(typed.gpu_count(), 3);
686    }
687
688    #[test]
689    fn a_job_step_is_a_step() {
690        for step in ["1041.batch", "1041.0"] {
691            let record = parsed(&row(step, "2026-03-02T08:15:00", "7200", "cpu=8", "180"));
692            assert!(record.is_step(), "{step} is a step");
693            assert_eq!(record.job_id, step);
694        }
695        let job = parsed(&row("1041", "2026-03-02T08:15:00", "7200", "cpu=8", "180"));
696        assert!(!job.is_step());
697    }
698
699    #[test]
700    fn parse_file_skips_blank_lines_and_names_the_rows_it_reads() {
701        let text = [
702            row("101", "2026-03-02T08:15:00", "7200", "cpu=8", "180"),
703            String::new(),
704            row("102", "2026-03-02T09:15:00", "600", "cpu=4", "60"),
705            row("103", "2026-03-02T10:15:00", "900", "cpu=4", "60"),
706        ]
707        .join("\n");
708
709        let records = parse_file(&text, OFFSET).expect("every row parses");
710        assert_eq!(records.len(), 3);
711        assert_eq!(records[0].job_id, "101");
712        assert_eq!(records[2].job_id, "103");
713    }
714
715    #[test]
716    fn parse_file_fails_on_the_first_rejection_and_names_its_row() {
717        let text = [
718            row("101", "2026-03-02T08:15:00", "7200", "cpu=8", "180"),
719            String::new(),
720            row("102", "2026-03-02T09:15:00", "600", "cpu=4", "60"),
721            row("103", "2026-03-02T10:15:00", "not-a-number", "cpu=4", "60"),
722        ]
723        .join("\n");
724
725        match parse_file(&text, OFFSET) {
726            Err(Error::Field { row, field, .. }) => {
727                assert_eq!(row, 4);
728                assert_eq!(field, "ElapsedRaw");
729            }
730            other => panic!("expected a field error on row 4, got {other:?}"),
731        }
732    }
733
734    #[test]
735    fn the_committed_sample_parses_with_zero_rejections_and_thirty_rows() {
736        let sample = include_str!("../testdata/sacct_sample.txt");
737        let records = parse_file(sample, OFFSET).expect("every row of the sample parses");
738
739        assert_eq!(records.len(), 30);
740
741        let steps = records.iter().filter(|record| record.is_step()).count();
742        assert_eq!(steps, 5);
743
744        let with_gpus = records
745            .iter()
746            .filter(|record| record.gpu_count() > 0)
747            .count();
748        assert_eq!(with_gpus, 28);
749
750        let unlimited = records
751            .iter()
752            .filter(|record| record.timelimit == Limit::Unlimited)
753            .count();
754        assert_eq!(unlimited, 1);
755
756        let states: Vec<&State> = records.iter().map(|record| &record.state).collect();
757        assert!(states.contains(&&State::Timeout));
758        assert!(states.contains(&&State::Failed));
759        assert!(states.contains(&&State::Cancelled));
760        assert!(states.contains(&&State::Running));
761    }
762}