hpc-core 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. hpc_core/__init__.py +1 -0
  2. hpc_core/contract/__init__.py +76 -0
  3. hpc_core/contract/fields.py +155 -0
  4. hpc_core/contract/identifiers.py +43 -0
  5. hpc_core/contract/metrics.py +92 -0
  6. hpc_core/contract/report.py +279 -0
  7. hpc_core/contract/resources.py +99 -0
  8. hpc_core/contract/sacct.py +122 -0
  9. hpc_core/contract/sinfo.py +44 -0
  10. hpc_core/contract/squeue.py +78 -0
  11. hpc_core/contract/sstat.py +46 -0
  12. hpc_core/contract/states.py +66 -0
  13. hpc_core/contract/times.py +85 -0
  14. hpc_core/py.typed +0 -0
  15. hpc_core/slurm/__init__.py +24 -0
  16. hpc_core/slurm/adapter.py +119 -0
  17. hpc_core/slurm/commands.py +84 -0
  18. hpc_core/testing/__init__.py +27 -0
  19. hpc_core/testing/contract.py +97 -0
  20. hpc_core/testing/fake_transport.py +51 -0
  21. hpc_core/testing/fixtures/reports/bad_row.csv +4 -0
  22. hpc_core/testing/fixtures/reports/bad_row.expected.json +54 -0
  23. hpc_core/testing/fixtures/reports/cancelled_before_start.csv +2 -0
  24. hpc_core/testing/fixtures/reports/cancelled_before_start.expected.json +30 -0
  25. hpc_core/testing/fixtures/reports/finished_run.csv +4 -0
  26. hpc_core/testing/fixtures/reports/finished_run.expected.json +78 -0
  27. hpc_core/testing/fixtures/reports/one_gpu_run.csv +2 -0
  28. hpc_core/testing/fixtures/reports/one_gpu_run.expected.json +30 -0
  29. hpc_core/testing/fixtures/reports/unavailable_metrics.csv +2 -0
  30. hpc_core/testing/fixtures/reports/unavailable_metrics.expected.json +30 -0
  31. hpc_core/testing/fixtures/reports/unknown_schema_version.csv +2 -0
  32. hpc_core/testing/fixtures/reports/unknown_schema_version.expected.json +4 -0
  33. hpc_core/testing/fixtures/reports/zero_beside_blank.csv +2 -0
  34. hpc_core/testing/fixtures/reports/zero_beside_blank.expected.json +30 -0
  35. hpc_core/testing/fixtures/scheduler/sacct-console.expected.json +83 -0
  36. hpc_core/testing/fixtures/scheduler/sacct-console.txt +7 -0
  37. hpc_core/testing/fixtures/scheduler/sacct-empty.expected.json +6 -0
  38. hpc_core/testing/fixtures/scheduler/sacct-empty.txt +3 -0
  39. hpc_core/testing/fixtures/scheduler/sacct-operator-recorded.expected.json +159 -0
  40. hpc_core/testing/fixtures/scheduler/sacct-operator-recorded.txt +11 -0
  41. hpc_core/testing/fixtures/scheduler/sacct-operator.expected.json +83 -0
  42. hpc_core/testing/fixtures/scheduler/sacct-operator.txt +7 -0
  43. hpc_core/testing/fixtures/scheduler/sinfo-capacity.expected.json +31 -0
  44. hpc_core/testing/fixtures/scheduler/sinfo-capacity.txt +6 -0
  45. hpc_core/testing/fixtures/scheduler/sinfo-empty.expected.json +6 -0
  46. hpc_core/testing/fixtures/scheduler/sinfo-empty.txt +3 -0
  47. hpc_core/testing/fixtures/scheduler/squeue-empty.expected.json +6 -0
  48. hpc_core/testing/fixtures/scheduler/squeue-empty.txt +3 -0
  49. hpc_core/testing/fixtures/scheduler/squeue-operator-recorded.expected.json +102 -0
  50. hpc_core/testing/fixtures/scheduler/squeue-operator-recorded.txt +8 -0
  51. hpc_core/testing/fixtures/scheduler/squeue-operator.expected.json +83 -0
  52. hpc_core/testing/fixtures/scheduler/squeue-operator.txt +8 -0
  53. hpc_core/testing/fixtures/scheduler/sstat-empty.expected.json +6 -0
  54. hpc_core/testing/fixtures/scheduler/sstat-empty.txt +3 -0
  55. hpc_core/testing/fixtures/scheduler/sstat-no-steps-empty.expected.json +6 -0
  56. hpc_core/testing/fixtures/scheduler/sstat-no-steps-empty.txt +4 -0
  57. hpc_core/testing/fixtures/scheduler/sstat-running.expected.json +31 -0
  58. hpc_core/testing/fixtures/scheduler/sstat-running.txt +7 -0
  59. hpc_core/testing/fixtures.py +123 -0
  60. hpc_core/transport/__init__.py +8 -0
  61. hpc_core/transport/protocol.py +39 -0
  62. hpc_core-0.1.0.dist-info/METADATA +90 -0
  63. hpc_core-0.1.0.dist-info/RECORD +67 -0
  64. hpc_core-0.1.0.dist-info/WHEEL +5 -0
  65. hpc_core-0.1.0.dist-info/licenses/LICENSE +201 -0
  66. hpc_core-0.1.0.dist-info/licenses/NOTICE +4 -0
  67. hpc_core-0.1.0.dist-info/top_level.txt +1 -0
hpc_core/__init__.py ADDED
@@ -0,0 +1 @@
1
+ """Shared, dependency-free HPC scheduler contract, transport interface and Slurm adapter."""
@@ -0,0 +1,76 @@
1
+ """Contract layer: standard library only, no I/O.
2
+
3
+ Scheduler output parsing, identifiers, the run-report CSV schema and its reader, and metrics.
4
+ """
5
+
6
+ from .fields import (
7
+ Field,
8
+ FieldProfile,
9
+ JobRecord,
10
+ NodeRecord,
11
+ ParseResult,
12
+ ProfileError,
13
+ SstatRecord,
14
+ )
15
+ from .identifiers import ValidationError, is_job_id, is_step_id, validate_account, validate_job_id
16
+ from .metrics import (
17
+ cpu_hours,
18
+ cpu_seconds_used,
19
+ elapsed_seconds,
20
+ gpu_hours,
21
+ mean,
22
+ peak,
23
+ running_cpu_seconds,
24
+ wait_seconds,
25
+ )
26
+ from .report import (
27
+ COLUMNS,
28
+ SCHEMA_VERSION,
29
+ SUPPORTED_VERSIONS,
30
+ ReadResult,
31
+ ReportError,
32
+ ReportRow,
33
+ format_report,
34
+ format_row,
35
+ read_report,
36
+ )
37
+ from .states import classify_state, state_word
38
+ from .times import format_time, parse_duration, parse_report_time, parse_time
39
+
40
+ __all__ = [
41
+ "COLUMNS",
42
+ "SCHEMA_VERSION",
43
+ "SUPPORTED_VERSIONS",
44
+ "Field",
45
+ "FieldProfile",
46
+ "JobRecord",
47
+ "NodeRecord",
48
+ "ParseResult",
49
+ "ProfileError",
50
+ "ReadResult",
51
+ "ReportError",
52
+ "ReportRow",
53
+ "SstatRecord",
54
+ "ValidationError",
55
+ "classify_state",
56
+ "cpu_hours",
57
+ "cpu_seconds_used",
58
+ "elapsed_seconds",
59
+ "format_report",
60
+ "format_row",
61
+ "format_time",
62
+ "gpu_hours",
63
+ "is_job_id",
64
+ "is_step_id",
65
+ "mean",
66
+ "parse_duration",
67
+ "parse_report_time",
68
+ "parse_time",
69
+ "peak",
70
+ "read_report",
71
+ "running_cpu_seconds",
72
+ "state_word",
73
+ "validate_account",
74
+ "validate_job_id",
75
+ "wait_seconds",
76
+ ]
@@ -0,0 +1,155 @@
1
+ """Named field profiles, the records parsers return, and the row splitter.
2
+
3
+ A profile names the columns a command was asked for, in order. Cells are read by name, so a field
4
+ the profile does not name is unset on the record. A free-text field (a job name) may only be the
5
+ last field, so a separator inside it cannot shift the others.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from dataclasses import dataclass
11
+ from datetime import datetime
12
+ from typing import Generic, TypeVar
13
+
14
+ from .states import StateClass
15
+
16
+ SUPPORTED_COMMANDS: frozenset[str] = frozenset({"squeue", "sacct", "sinfo", "sstat"})
17
+
18
+
19
+ class ProfileError(ValueError):
20
+ """A field profile that breaks the rules. The message names the offending field."""
21
+
22
+
23
+ @dataclass(frozen=True)
24
+ class Field:
25
+ name: str
26
+ token: str
27
+ free_text: bool = False
28
+
29
+
30
+ @dataclass(frozen=True)
31
+ class FieldProfile:
32
+ name: str
33
+ command: str
34
+ fields: tuple[Field, ...]
35
+ separator: str = "|"
36
+
37
+ def __post_init__(self) -> None:
38
+ if self.command not in SUPPORTED_COMMANDS:
39
+ raise ProfileError(f"profile '{self.name}': unsupported command '{self.command}'")
40
+ if len(self.separator) != 1 or self.separator.isspace() or self.separator in ",%":
41
+ raise ProfileError(f"profile '{self.name}': separator must be one plain character")
42
+ if not self.fields:
43
+ raise ProfileError(f"profile '{self.name}': no fields")
44
+ names = [item.name for item in self.fields]
45
+ duplicates = sorted({name for name in names if names.count(name) > 1})
46
+ if duplicates:
47
+ raise ProfileError(f"profile '{self.name}': duplicate field '{duplicates[0]}'")
48
+ for item in self.fields:
49
+ if not item.token or any(ch in item.token for ch in ", \t\n"):
50
+ raise ProfileError(f"profile '{self.name}': bad token for field '{item.name}'")
51
+ for item in self.fields[:-1]:
52
+ if item.free_text:
53
+ raise ProfileError(
54
+ f"profile '{self.name}': free-text field '{item.name}' must be the last field"
55
+ )
56
+
57
+ @property
58
+ def names(self) -> tuple[str, ...]:
59
+ return tuple(item.name for item in self.fields)
60
+
61
+
62
+ T = TypeVar("T")
63
+
64
+
65
+ @dataclass(frozen=True)
66
+ class ParseResult(Generic[T]):
67
+ records: tuple[T, ...]
68
+ skipped: int
69
+
70
+
71
+ def check_known_names(profile: FieldProfile, known: frozenset[str]) -> None:
72
+ for name in profile.names:
73
+ if name not in known:
74
+ raise ProfileError(
75
+ f"profile '{profile.name}': field '{name}' is not read by {profile.command}"
76
+ )
77
+
78
+
79
+ def iter_rows(text: str, profile: FieldProfile) -> tuple[list[dict[str, str]], int]:
80
+ """Split command output into rows keyed by field name. Returns (good rows, skipped count).
81
+
82
+ Blank lines are not rows and are not counted. A row with too few cells is skipped; so is a row
83
+ with extra cells unless the last field is free text, which keeps any extra separators.
84
+ """
85
+ width = len(profile.fields)
86
+ last = profile.fields[-1]
87
+ good: list[dict[str, str]] = []
88
+ skipped = 0
89
+ for raw_line in text.splitlines():
90
+ line = raw_line.rstrip("\r")
91
+ if not line.strip():
92
+ continue
93
+ cells = line.split(profile.separator)
94
+ if last.free_text:
95
+ if len(cells) < width:
96
+ skipped += 1
97
+ continue
98
+ cells = cells[: width - 1] + [profile.separator.join(cells[width - 1 :])]
99
+ elif len(cells) != width:
100
+ skipped += 1
101
+ continue
102
+ row = {
103
+ item.name: (cell if item.free_text else cell.strip())
104
+ for item, cell in zip(profile.fields, cells, strict=True)
105
+ }
106
+ good.append(row)
107
+ return good, skipped
108
+
109
+
110
+ @dataclass(frozen=True)
111
+ class JobRecord:
112
+ """One job row from squeue or sacct. Every field is unset unless the profile named it and
113
+
114
+ the cell was readable.
115
+ """
116
+
117
+ job_id: str
118
+ job_name: str | None = None
119
+ partition: str | None = None
120
+ state: str | None = None
121
+ state_class: StateClass | None = None
122
+ reason: str | None = None
123
+ submit_time: datetime | None = None
124
+ start_time: datetime | None = None
125
+ end_time: datetime | None = None
126
+ cpus_requested: int | None = None
127
+ cpus_allocated: int | None = None
128
+ gpus_requested: int | None = None
129
+ gpus_allocated: int | None = None
130
+ gpu_type: str | None = None
131
+ total_cpu_seconds: float | None = None
132
+ max_rss_mib: float | None = None
133
+ time_limit_seconds: float | None = None
134
+
135
+
136
+ @dataclass(frozen=True)
137
+ class SstatRecord:
138
+ """One job step row from sstat."""
139
+
140
+ step_id: str
141
+ ave_cpu_seconds: float | None = None
142
+ ntasks: int | None = None
143
+ max_rss_mib: float | None = None
144
+
145
+
146
+ @dataclass(frozen=True)
147
+ class NodeRecord:
148
+ """One partition row from sinfo."""
149
+
150
+ partition: str | None = None
151
+ gres: str | None = None
152
+ state: str | None = None
153
+ node_count: int | None = None
154
+ gpus_per_node: int | None = None
155
+ gpu_type: str | None = None
@@ -0,0 +1,43 @@
1
+ """Identifiers that may be placed in a Slurm command: a job id and an account name.
2
+
3
+ Nothing else is inserted into a command. The rules are strict on purpose: an identifier that
4
+ fails them raises ``ValidationError`` before any command exists.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import re
10
+
11
+ # A plain job id, or an array task id such as 4812201_3.
12
+ JOB_ID_PATTERN = re.compile(r"[0-9]+(?:_[0-9]+)?")
13
+ # A job step id as printed by sstat, such as 4812201.0 or 4812201_3.batch.
14
+ STEP_ID_PATTERN = re.compile(r"[0-9]+(?:_[0-9]+)?\.[A-Za-z0-9]+")
15
+ # Letters, digits, underscore, dot and hyphen; must not start with a hyphen.
16
+ ACCOUNT_PATTERN = re.compile(r"[A-Za-z0-9_.][A-Za-z0-9_.-]*")
17
+
18
+
19
+ class ValidationError(ValueError):
20
+ """A value that may not be used in a command. The message names the rule, not the value."""
21
+
22
+
23
+ def is_job_id(text: str) -> bool:
24
+ return JOB_ID_PATTERN.fullmatch(text) is not None
25
+
26
+
27
+ def is_step_id(text: str) -> bool:
28
+ return STEP_ID_PATTERN.fullmatch(text) is not None
29
+
30
+
31
+ def validate_job_id(text: str) -> str:
32
+ if not is_job_id(text):
33
+ raise ValidationError("job id must be digits with an optional _<index> suffix")
34
+ return text
35
+
36
+
37
+ def validate_account(text: str) -> str:
38
+ if ACCOUNT_PATTERN.fullmatch(text) is None:
39
+ raise ValidationError(
40
+ "account name may hold only letters, digits, '_', '.' and '-', "
41
+ "and must not start with '-'"
42
+ )
43
+ return text
@@ -0,0 +1,92 @@
1
+ """Wait, elapsed, CPU-hours, GPU-hours and peak use. Unset inputs give unset results, never zero."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Iterable
6
+ from datetime import datetime
7
+
8
+
9
+ def wait_seconds(
10
+ submit: datetime | None,
11
+ start: datetime | None = None,
12
+ *,
13
+ end: datetime | None = None,
14
+ as_of: datetime | None = None,
15
+ ) -> int | None:
16
+ """Seconds from submit to start. A job that has not started counts to its end (if it was
17
+ cancelled before starting) or to ``as_of``. Returns None when no reference time is known or
18
+ the reference is before the submit time."""
19
+ if submit is None:
20
+ return None
21
+ reference = start if start is not None else (end if end is not None else as_of)
22
+ if reference is None:
23
+ return None
24
+ seconds = (reference - submit).total_seconds()
25
+ return None if seconds < 0 else int(seconds)
26
+
27
+
28
+ def elapsed_seconds(
29
+ start: datetime | None,
30
+ *,
31
+ end: datetime | None = None,
32
+ as_of: datetime | None = None,
33
+ ) -> int | None:
34
+ """Seconds from start to the end time, or to ``as_of`` while running. Unset before a start."""
35
+ if start is None:
36
+ return None
37
+ reference = end if end is not None else as_of
38
+ if reference is None:
39
+ return None
40
+ seconds = (reference - start).total_seconds()
41
+ return None if seconds < 0 else int(seconds)
42
+
43
+
44
+ def cpu_hours(cpus: int | None, elapsed: int | None) -> float | None:
45
+ if cpus is None or elapsed is None:
46
+ return None
47
+ return cpus * elapsed / 3600
48
+
49
+
50
+ def gpu_hours(gpus: int | None, elapsed: int | None) -> float | None:
51
+ if gpus is None or elapsed is None:
52
+ return None
53
+ return gpus * elapsed / 3600
54
+
55
+
56
+ def peak(values: Iterable[float | None]) -> float | None:
57
+ """The largest value that was read. Gaps are ignored; no reading gives None."""
58
+ readings = [value for value in values if value is not None]
59
+ return max(readings) if readings else None
60
+
61
+
62
+ def mean(values: Iterable[float | None]) -> float | None:
63
+ readings = [value for value in values if value is not None]
64
+ return sum(readings) / len(readings) if readings else None
65
+
66
+
67
+ def running_cpu_seconds(steps: Iterable[tuple[float | None, int | None]]) -> float | None:
68
+ """CPU seconds used so far: over steps, average CPU time per task times the task count.
69
+
70
+ Returns None when there is no step, or when any step lacks its average or its task count: a
71
+ partial sum would understate the job's usage.
72
+ """
73
+ total = 0.0
74
+ seen = False
75
+ for average, tasks in steps:
76
+ seen = True
77
+ if average is None or tasks is None:
78
+ return None
79
+ total += average * tasks
80
+ return total if seen else None
81
+
82
+
83
+ def cpu_seconds_used(
84
+ *,
85
+ final: bool,
86
+ total_cpu_seconds: float | None,
87
+ steps: Iterable[tuple[float | None, int | None]],
88
+ ) -> float | None:
89
+ """The accounting TotalCPU for a finished job; the step sum for a running one."""
90
+ if final:
91
+ return total_cpu_seconds
92
+ return running_cpu_seconds(steps)
@@ -0,0 +1,279 @@
1
+ """The run-report CSV contract: columns, schema version, a formatter and a strict reader.
2
+
3
+ The writer and the reader here are the reference. A consumer that writes or reads reports runs
4
+ the contract checks in ``hpc_core.testing`` against its own code.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import csv
10
+ import io
11
+ import math
12
+ from collections.abc import Iterable
13
+ from dataclasses import dataclass
14
+ from datetime import datetime
15
+
16
+ from .identifiers import is_job_id
17
+ from .times import format_time, parse_report_time
18
+
19
+ COLUMNS: tuple[str, ...] = (
20
+ "schema_version",
21
+ "job_id",
22
+ "job_name",
23
+ "partition",
24
+ "stage",
25
+ "sample_time",
26
+ "scheduler_state",
27
+ "submit_time",
28
+ "start_time",
29
+ "end_time",
30
+ "wait_seconds",
31
+ "elapsed_seconds",
32
+ "cpus_alloc",
33
+ "cpu_seconds_used",
34
+ "mem_peak_mb",
35
+ "gpus_alloc",
36
+ "gpu_type",
37
+ "gpu_util_pct",
38
+ "gpu_mem_mb",
39
+ "source",
40
+ "unavailable",
41
+ "report_status",
42
+ )
43
+ SCHEMA_VERSION = 1
44
+ SUPPORTED_VERSIONS: frozenset[int] = frozenset({1})
45
+ STAGES: frozenset[str] = frozenset({"pre", "running", "post"})
46
+ REPORT_STATUSES: frozenset[str] = frozenset({"in_progress", "complete", "samples_only"})
47
+ SOURCE_PARTS: frozenset[str] = frozenset({"squeue", "sstat", "nvidia-smi", "sacct", "samples"})
48
+
49
+ _INT_COLUMNS = frozenset(
50
+ {"schema_version", "wait_seconds", "elapsed_seconds", "cpus_alloc", "gpus_alloc"}
51
+ )
52
+ _FLOAT_COLUMNS = frozenset({"cpu_seconds_used", "mem_peak_mb", "gpu_util_pct", "gpu_mem_mb"})
53
+ _TIME_COLUMNS = frozenset({"sample_time", "submit_time", "start_time", "end_time"})
54
+ _REQUIRED_READ = frozenset({"schema_version", "job_id", "stage", "sample_time"})
55
+
56
+
57
+ class ReportError(ValueError):
58
+ """The whole report is refused. The message names what was wrong."""
59
+
60
+
61
+ class RowError(ValueError):
62
+ """One row cannot be read. The reader skips it and counts it."""
63
+
64
+
65
+ def is_valid_source(source: str) -> bool:
66
+ parts = source.split("+")
67
+ return all(part in SOURCE_PARTS for part in parts)
68
+
69
+
70
+ @dataclass(frozen=True)
71
+ class ReportRow:
72
+ """One report row. Blank in the CSV reads as None; a real zero stays 0."""
73
+
74
+ schema_version: int = SCHEMA_VERSION
75
+ job_id: str = ""
76
+ job_name: str | None = None
77
+ partition: str | None = None
78
+ stage: str = ""
79
+ sample_time: datetime | None = None
80
+ scheduler_state: str | None = None
81
+ submit_time: datetime | None = None
82
+ start_time: datetime | None = None
83
+ end_time: datetime | None = None
84
+ wait_seconds: int | None = None
85
+ elapsed_seconds: int | None = None
86
+ cpus_alloc: int | None = None
87
+ cpu_seconds_used: float | None = None
88
+ mem_peak_mb: float | None = None
89
+ gpus_alloc: int | None = None
90
+ gpu_type: str | None = None
91
+ gpu_util_pct: float | None = None
92
+ gpu_mem_mb: float | None = None
93
+ source: str = ""
94
+ unavailable: str | None = None
95
+ report_status: str = ""
96
+
97
+ def __post_init__(self) -> None:
98
+ if self.schema_version not in SUPPORTED_VERSIONS:
99
+ raise ValueError(f"unsupported schema_version {self.schema_version}")
100
+ if not is_job_id(self.job_id):
101
+ raise ValueError("job_id is not a valid job id")
102
+ if self.stage not in STAGES:
103
+ raise ValueError("stage is outside pre, running, post")
104
+ if self.report_status not in REPORT_STATUSES:
105
+ raise ValueError("report_status is outside in_progress, complete, samples_only")
106
+ if not is_valid_source(self.source):
107
+ raise ValueError("source is outside the known sources")
108
+ if self.sample_time is None:
109
+ raise ValueError("sample_time is required")
110
+
111
+
112
+ def _format_float(value: float) -> str:
113
+ if value.is_integer():
114
+ return str(int(value))
115
+ return repr(value)
116
+
117
+
118
+ def _format_cell(column: str, value: object) -> str:
119
+ if value is None:
120
+ return ""
121
+ if column in _TIME_COLUMNS:
122
+ if not isinstance(value, datetime):
123
+ raise ValueError(f"{column} must be a datetime")
124
+ return format_time(value)
125
+ if column in _INT_COLUMNS:
126
+ if isinstance(value, bool) or not isinstance(value, int):
127
+ raise ValueError(f"{column} must be a whole number")
128
+ return str(value)
129
+ if column in _FLOAT_COLUMNS:
130
+ if isinstance(value, bool) or not isinstance(value, int | float):
131
+ raise ValueError(f"{column} must be a number")
132
+ return _format_float(float(value))
133
+ return str(value)
134
+
135
+
136
+ def format_row(row: ReportRow) -> list[str]:
137
+ """One row in COLUMNS order. Whole numbers have no decimal point; unset values are empty."""
138
+ return [_format_cell(column, getattr(row, column)) for column in COLUMNS]
139
+
140
+
141
+ def format_report(rows: Iterable[ReportRow]) -> str:
142
+ """The header and the rows as CSV text with ``\\n`` line endings."""
143
+ buffer = io.StringIO()
144
+ writer = csv.writer(buffer, lineterminator="\n")
145
+ writer.writerow(COLUMNS)
146
+ for row in rows:
147
+ writer.writerow(format_row(row))
148
+ return buffer.getvalue()
149
+
150
+
151
+ @dataclass(frozen=True)
152
+ class ReadResult:
153
+ rows: tuple[ReportRow, ...]
154
+ skipped: int
155
+
156
+
157
+ def _cell_int(cells: dict[str, str], column: str, *, required: bool = False) -> int | None:
158
+ text = cells.get(column, "").strip()
159
+ if not text:
160
+ if required:
161
+ raise RowError(column)
162
+ return None
163
+ if not text.isdigit():
164
+ raise RowError(column)
165
+ return int(text)
166
+
167
+
168
+ def _cell_float(cells: dict[str, str], column: str) -> float | None:
169
+ text = cells.get(column, "").strip()
170
+ if not text:
171
+ return None
172
+ try:
173
+ value = float(text)
174
+ except ValueError as error:
175
+ raise RowError(column) from error
176
+ if not math.isfinite(value) or value < 0:
177
+ raise RowError(column)
178
+ return value
179
+
180
+
181
+ def _cell_time(cells: dict[str, str], column: str, *, required: bool = False) -> datetime | None:
182
+ text = cells.get(column, "").strip()
183
+ if not text:
184
+ if required:
185
+ raise RowError(column)
186
+ return None
187
+ try:
188
+ return parse_report_time(text)
189
+ except ValueError as error:
190
+ raise RowError(column) from error
191
+
192
+
193
+ def _cell_text(cells: dict[str, str], column: str) -> str | None:
194
+ text = cells.get(column, "")
195
+ return text if text else None
196
+
197
+
198
+ def _cell_closed(cells: dict[str, str], column: str, allowed: frozenset[str]) -> str:
199
+ text = cells.get(column, "")
200
+ if text not in allowed:
201
+ raise RowError(column)
202
+ return text
203
+
204
+
205
+ def _row_from_cells(cells: dict[str, str]) -> ReportRow:
206
+ job_id = cells.get("job_id", "")
207
+ if not is_job_id(job_id):
208
+ raise RowError("job_id")
209
+ source = cells.get("source", "")
210
+ if not source or not is_valid_source(source):
211
+ raise RowError("source")
212
+ sample_time = _cell_time(cells, "sample_time", required=True)
213
+ try:
214
+ return ReportRow(
215
+ schema_version=_cell_int(cells, "schema_version", required=True) or 0,
216
+ job_id=job_id,
217
+ job_name=_cell_text(cells, "job_name"),
218
+ partition=_cell_text(cells, "partition"),
219
+ stage=_cell_closed(cells, "stage", STAGES),
220
+ sample_time=sample_time,
221
+ scheduler_state=_cell_text(cells, "scheduler_state"),
222
+ submit_time=_cell_time(cells, "submit_time"),
223
+ start_time=_cell_time(cells, "start_time"),
224
+ end_time=_cell_time(cells, "end_time"),
225
+ wait_seconds=_cell_int(cells, "wait_seconds"),
226
+ elapsed_seconds=_cell_int(cells, "elapsed_seconds"),
227
+ cpus_alloc=_cell_int(cells, "cpus_alloc"),
228
+ cpu_seconds_used=_cell_float(cells, "cpu_seconds_used"),
229
+ mem_peak_mb=_cell_float(cells, "mem_peak_mb"),
230
+ gpus_alloc=_cell_int(cells, "gpus_alloc"),
231
+ gpu_type=_cell_text(cells, "gpu_type"),
232
+ gpu_util_pct=_cell_float(cells, "gpu_util_pct"),
233
+ gpu_mem_mb=_cell_float(cells, "gpu_mem_mb"),
234
+ source=source,
235
+ unavailable=_cell_text(cells, "unavailable"),
236
+ report_status=_cell_closed(cells, "report_status", REPORT_STATUSES),
237
+ )
238
+ except (ValueError, RowError) as error:
239
+ raise RowError(str(error)) from error
240
+
241
+
242
+ def read_report(text: str) -> ReadResult:
243
+ """Read a run report by column name.
244
+
245
+ Refuses the whole report, with no rows, when the header lacks a required column or a row's
246
+ ``schema_version`` is not supported; the message names the version. Otherwise rows that cannot
247
+ be read are skipped and counted, and the rest are returned.
248
+ """
249
+ reader = csv.reader(io.StringIO(text))
250
+ try:
251
+ header = [name.strip() for name in next(reader)]
252
+ except StopIteration as error:
253
+ raise ReportError("report is empty: no header") from error
254
+ if len(set(header)) != len(header):
255
+ raise ReportError("report header repeats a column name")
256
+ index = {name: position for position, name in enumerate(header)}
257
+ for column in sorted(_REQUIRED_READ):
258
+ if column not in index:
259
+ raise ReportError(f"report has no '{column}' column")
260
+
261
+ rows: list[ReportRow] = []
262
+ skipped = 0
263
+ for raw in reader:
264
+ if not any(cell.strip() for cell in raw):
265
+ continue
266
+ cells = {
267
+ name: (raw[position] if position < len(raw) else "") for name, position in index.items()
268
+ }
269
+ version_text = cells.get("schema_version", "").strip()
270
+ if version_text.isdigit() and int(version_text) not in SUPPORTED_VERSIONS:
271
+ raise ReportError(
272
+ f"unsupported schema_version {int(version_text)}; this package reads "
273
+ + ", ".join(str(v) for v in sorted(SUPPORTED_VERSIONS))
274
+ )
275
+ try:
276
+ rows.append(_row_from_cells(cells))
277
+ except RowError:
278
+ skipped += 1
279
+ return ReadResult(tuple(rows), skipped)