Repository navigation
Expand file tree
/
Copy pathorchestrate.py
More file actions
executable file
·1990 lines (1844 loc) · 75.6 KB
/
Copy pathorchestrate.py
File metadata and controls
executable file
·1990 lines (1844 loc) · 75.6 KB
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
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""Read-only inventory and non-privileged UMSH test orchestration.
The orchestrator never invokes sudo or changes kernel/module state. Commands
which require such setup must remain explicit unsupported/external_setup rows
in the manifest and be prepared outside this program.
"""
from __future__ import annotations
import argparse
import csv
import dataclasses
import datetime as dt
import hashlib
import io
import itertools
import json
import math
import os
import posixpath
import re
import shlex
import subprocess
import sys
import time
from collections import Counter
from pathlib import Path
from typing import Any, Iterable, Mapping, Sequence
SCHEMA_VERSION = 2
HARNESS_VERSION = "2"
SAFE_ID = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_.-]*$")
CASE_STATES = frozenset(("ready", "unsupported", "external_setup"))
SUITES = frozenset(("correctness", "performance"))
PERFORMANCE_DIRECTIONS = frozenset(
(
"bind",
"cpu_read",
"cpu_write",
"gpu_read",
"gpu_write",
"gpu_contention_read",
"io_to_gpu",
)
)
CLASSIFICATION_SOURCES = frozenset(("csv", "sidecar", "csv+sidecar", "not_applicable"))
FORBIDDEN_EXECUTABLES = frozenset(("sudo", "su", "insmod", "rmmod", "modprobe"))
DEFAULT_MANIFEST = Path(__file__).with_name("platforms.json")
REPO_ROOT = Path(__file__).resolve().parents[2]
DIRTY_HASH_PROGRAM = r"""
import hashlib
import os
import stat
import subprocess
h = hashlib.sha256()
h.update(b"tracked-diff\0")
h.update(subprocess.check_output(["git", "diff", "--binary", "HEAD"]))
untracked = subprocess.check_output(
["git", "ls-files", "--others", "--exclude-standard", "-z"]
).split(b"\0")
for raw_path in sorted(path for path in untracked if path):
path = os.fsdecode(raw_path)
h.update(b"untracked\0")
h.update(len(raw_path).to_bytes(8, "big"))
h.update(raw_path)
metadata = os.lstat(path)
h.update(stat.S_IFMT(metadata.st_mode).to_bytes(8, "big"))
if stat.S_ISLNK(metadata.st_mode):
h.update(os.fsencode(os.readlink(path)))
elif stat.S_ISREG(metadata.st_mode):
with open(path, "rb") as stream:
while True:
chunk = stream.read(1024 * 1024)
if not chunk:
break
h.update(chunk)
print(h.hexdigest())
""".strip()
HUGEPAGE_PROGRAM = r"""
from pathlib import Path
roots = [Path("/sys/kernel/mm/hugepages"), Path("/sys/kernel/mm/transparent_hugepage")]
for root in roots:
if not root.exists():
print(f"MISSING {root}")
continue
for path in sorted(item for item in root.rglob("*") if item.is_file()):
try:
value = path.read_text(encoding="utf-8", errors="replace").strip()
except OSError as error:
value = f"ERROR {error}"
print(f"{path}={value}")
""".strip()
MODULE_PARAMETER_PROGRAM = r"""
from pathlib import Path
for module in ("i915", "xe", "nvidia", "nvidia_uvm", "uc_mem", "wbinvd_mod", "arm64_attr_mmap"):
root = Path("/sys/module") / module
if not root.exists():
continue
print(f"MODULE {module}")
for relative in ("version", "srcversion", "taint"):
path = root / relative
if path.is_file():
try:
print(f"{path}={path.read_text(errors='replace').strip()}")
except OSError as error:
print(f"{path}=ERROR {error}")
parameters = root / "parameters"
if parameters.is_dir():
for path in sorted(item for item in parameters.iterdir() if item.is_file()):
try:
value = path.read_text(errors="replace")[:4096].strip()
except OSError as error:
value = f"ERROR {error}"
print(f"{path}={value}")
""".strip()
MODULE_FILE_HASH_PROGRAM = r"""
import hashlib
import subprocess
from pathlib import Path
for module in ("i915", "xe", "nvidia", "nvidia_uvm", "uc_mem", "wbinvd_mod", "arm64_attr_mmap"):
result = subprocess.run(["modinfo", "-n", module], capture_output=True, text=True)
if result.returncode != 0:
continue
path = Path(result.stdout.strip())
if not path.is_file():
print(f"{module}\t{path}\tMISSING")
continue
digest = hashlib.sha256()
with path.open("rb") as stream:
while True:
chunk = stream.read(1024 * 1024)
if not chunk:
break
digest.update(chunk)
print(f"{module}\t{path}\t{digest.hexdigest()}")
""".strip()
@dataclasses.dataclass
class CommandResult:
returncode: int
stdout: bytes
stderr: bytes
duration_seconds: float
timed_out: bool = False
class ManifestError(ValueError):
pass
class Transport:
def __init__(self, platform: Mapping[str, Any]):
self.kind = str(platform["transport"])
self.host = platform.get("host")
self.ssh_options = [str(value) for value in platform.get("ssh_options", [])]
def describe(self) -> str:
return "local" if self.kind == "local" else f"ssh:{self.host}"
def run(
self,
command: Sequence[str],
*,
cwd: str | None = None,
timeout: float | None = None,
) -> CommandResult:
logical = [str(item) for item in command]
if self.kind == "local":
actual = logical
local_cwd = cwd
else:
remote = shlex.join(logical)
if cwd:
remote = f"cd -- {shlex.quote(cwd)} && exec {remote}"
else:
remote = f"exec {remote}"
actual = ["ssh", *self.ssh_options, str(self.host), remote]
local_cwd = None
started = time.monotonic()
try:
completed = subprocess.run(
actual,
cwd=local_cwd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
timeout=timeout,
check=False,
)
return CommandResult(
returncode=completed.returncode,
stdout=completed.stdout,
stderr=completed.stderr,
duration_seconds=time.monotonic() - started,
)
except subprocess.TimeoutExpired as error:
return CommandResult(
returncode=124,
stdout=error.stdout or b"",
stderr=(error.stderr or b"") + b"\nORCHESTRATOR_TIMEOUT\n",
duration_seconds=time.monotonic() - started,
timed_out=True,
)
except (FileNotFoundError, NotADirectoryError) as error:
return CommandResult(
returncode=127,
stdout=b"",
stderr=f"{type(error).__name__}: {error}\n".encode(),
duration_seconds=time.monotonic() - started,
)
def read_file(self, path: str, *, timeout: float = 60.0) -> CommandResult:
if self.kind == "local":
started = time.monotonic()
try:
payload = Path(path).read_bytes()
return CommandResult(0, payload, b"", time.monotonic() - started)
except OSError as error:
return CommandResult(
1,
b"",
f"{type(error).__name__}: {error}\n".encode(),
time.monotonic() - started,
)
return self.run(["cat", "--", path], timeout=timeout)
def archive_directory(self, path: str, *, timeout: float = 120.0) -> CommandResult:
parent = posixpath.dirname(path.rstrip("/")) or "."
name = posixpath.basename(path.rstrip("/"))
return self.run(
["tar", "-C", parent, "-cf", "-", "--", name], timeout=timeout
)
def utc_now() -> str:
return dt.datetime.now(dt.timezone.utc).isoformat().replace("+00:00", "Z")
def default_run_id() -> str:
stamp = dt.datetime.now(dt.timezone.utc).strftime("%Y%m%dT%H%M%SZ")
nonce = hashlib.sha256(os.urandom(16)).hexdigest()[:8]
return f"{stamp}-{nonce}"
def decode(payload: bytes) -> str:
return payload.decode("utf-8", errors="replace")
def sha256_bytes(payload: bytes) -> str:
return hashlib.sha256(payload).hexdigest()
def sha256_file(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as stream:
while True:
chunk = stream.read(1024 * 1024)
if not chunk:
break
digest.update(chunk)
return digest.hexdigest()
def write_bytes(path: Path, payload: bytes) -> dict[str, Any]:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(payload)
return {"path": str(path), "bytes": len(payload), "sha256": sha256_bytes(payload)}
def write_json(path: Path, value: Any) -> None:
payload = (json.dumps(value, indent=2, sort_keys=True) + "\n").encode()
write_bytes(path, payload)
def safe_id(value: str, description: str) -> None:
if not SAFE_ID.fullmatch(value):
raise ManifestError(f"invalid {description} {value!r}")
def load_manifest(path: Path) -> tuple[dict[str, Any], bytes]:
try:
payload = path.read_bytes()
manifest = json.loads(payload)
except (OSError, json.JSONDecodeError) as error:
raise ManifestError(f"cannot load manifest {path}: {error}") from error
if not isinstance(manifest, dict):
raise ManifestError("manifest root must be an object")
validate_manifest(manifest)
return manifest, payload
def resolve_platform_cases(
manifest: Mapping[str, Any], platform_id: str
) -> list[dict[str, Any]]:
platform = manifest["platforms"][platform_id]
catalog = manifest["case_catalog"]
resolved: list[dict[str, Any]] = []
for entry in platform["cases"]:
if isinstance(entry, str):
case = dict(catalog[entry])
else:
case = {}
reference = entry.get("ref")
if reference:
case.update(catalog[reference])
case.update({key: value for key, value in entry.items() if key != "ref"})
resolved.append(case)
return resolved
def validate_command(command: Sequence[Any], context: str) -> None:
if not command or not all(isinstance(item, str) and item for item in command):
raise ManifestError(f"{context}: ready command must be a non-empty string list")
for token in command:
executable = posixpath.basename(token)
if executable in FORBIDDEN_EXECUTABLES:
raise ManifestError(f"{context}: forbidden privileged executable {token!r}")
if "/sys/module/" in token or "/proc/sys/" in token:
raise ManifestError(f"{context}: mutable kernel path is forbidden in test command")
def validate_performance_metadata(
case: Mapping[str, Any], context: str, csv_columns: set[str]
) -> None:
metadata = case.get("performance_metadata")
if not isinstance(metadata, dict):
raise ManifestError(f"{context}: ready performance case requires performance_metadata")
direction = metadata.get("direction")
if direction not in PERFORMANCE_DIRECTIONS:
raise ManifestError(f"{context}: invalid performance direction {direction!r}")
result_scope = metadata.get("result_scope")
if not isinstance(result_scope, str) or not result_scope:
raise ManifestError(f"{context}: performance result_scope is required")
if result_scope != case.get("result_scope"):
raise ManifestError(
f"{context}: performance result_scope must match the case result_scope"
)
timing_boundary = metadata.get("timing_boundary")
if not isinstance(timing_boundary, str) or not timing_boundary:
raise ManifestError(f"{context}: performance timing_boundary is required")
units = metadata.get("units")
if not isinstance(units, dict) or not units:
raise ManifestError(f"{context}: performance units must be a non-empty object")
for metric, unit in units.items():
if not isinstance(metric, str) or metric not in csv_columns:
raise ManifestError(
f"{context}: unit metric {metric!r} is not a required CSV column"
)
if not isinstance(unit, str) or not unit:
raise ManifestError(f"{context}: unit for {metric!r} must be a string")
for field in ("binding_classification", "policy_classification"):
classification = metadata.get(field)
if not isinstance(classification, dict):
raise ManifestError(f"{context}: {field} must be an object")
source = classification.get("source")
if source not in CLASSIFICATION_SOURCES:
raise ManifestError(f"{context}: invalid {field} source {source!r}")
value = classification.get("value")
if not isinstance(value, str) or not value:
raise ManifestError(f"{context}: {field} value is required")
columns = classification.get("columns")
if not isinstance(columns, list) or not all(
isinstance(column, str) and column for column in columns
):
raise ManifestError(f"{context}: {field} columns must be a string list")
if len(columns) != len(set(columns)):
raise ManifestError(f"{context}: {field} columns must be unique")
if source in ("csv", "csv+sidecar") and not columns:
raise ManifestError(f"{context}: {field} CSV source requires columns")
if source in ("sidecar", "not_applicable") and columns:
raise ManifestError(
f"{context}: {field} source {source!r} cannot declare CSV columns"
)
missing = sorted(set(columns) - csv_columns)
if missing:
raise ManifestError(
f"{context}: {field} columns are not required by CSV artifacts: "
f"{', '.join(missing)}"
)
def validate_csv_contract(
artifact: Mapping[str, Any],
context: str,
required_columns: Sequence[str],
*,
performance: bool,
) -> None:
required = set(required_columns)
expected_rows = artifact.get("expected_rows")
if expected_rows is not None:
if not isinstance(expected_rows, dict) or not expected_rows:
raise ManifestError(f"{context}: CSV expected_rows must be a non-empty object")
unknown = sorted(set(expected_rows) - {"exact", "minimum", "maximum"})
if unknown:
raise ManifestError(
f"{context}: CSV expected_rows has unknown keys: {', '.join(unknown)}"
)
for key, value in expected_rows.items():
if isinstance(value, bool) or not isinstance(value, int) or value < 0:
raise ManifestError(
f"{context}: CSV expected_rows {key!r} must be a non-negative integer"
)
if "exact" in expected_rows and len(expected_rows) != 1:
raise ManifestError(
f"{context}: CSV expected_rows exact cannot be combined with a range"
)
if expected_rows.get("minimum", 0) > expected_rows.get("maximum", sys.maxsize):
raise ManifestError(f"{context}: CSV expected_rows minimum exceeds maximum")
unique_coordinates = artifact.get("unique_coordinates")
if unique_coordinates is not None:
if not isinstance(unique_coordinates, list) or not unique_coordinates or not all(
isinstance(column, str) and column for column in unique_coordinates
):
raise ManifestError(
f"{context}: CSV unique_coordinates must be a non-empty string list"
)
if len(unique_coordinates) != len(set(unique_coordinates)):
raise ManifestError(f"{context}: CSV unique_coordinates must be unique")
missing = sorted(set(unique_coordinates) - required)
if missing:
raise ManifestError(
f"{context}: CSV unique_coordinates are not required columns: "
f"{', '.join(missing)}"
)
numeric_columns = artifact.get("numeric_columns")
if numeric_columns is not None:
if not isinstance(numeric_columns, dict) or not numeric_columns:
raise ManifestError(f"{context}: CSV numeric_columns must be a non-empty object")
for column, constraints in numeric_columns.items():
if column not in required:
raise ManifestError(f"{context}: numeric column {column!r} is not required")
if not isinstance(constraints, dict) or not constraints:
raise ManifestError(
f"{context}: numeric column {column!r} needs constraints"
)
unknown = sorted(set(constraints) - {"finite", "positive"})
if unknown:
raise ManifestError(
f"{context}: numeric column {column!r} has unknown constraints: "
f"{', '.join(unknown)}"
)
if not all(isinstance(value, bool) for value in constraints.values()):
raise ManifestError(
f"{context}: numeric constraints for {column!r} must be booleans"
)
if not any(constraints.values()):
raise ManifestError(
f"{context}: numeric column {column!r} has no enabled constraint"
)
expected_matrix = artifact.get("expected_matrix")
if expected_matrix is not None:
if not isinstance(expected_matrix, dict) or not expected_matrix:
raise ManifestError(
f"{context}: CSV expected_matrix must be a non-empty object"
)
for column, values in expected_matrix.items():
if column not in required:
raise ManifestError(
f"{context}: expected_matrix column {column!r} is not required"
)
if not isinstance(values, list) or not values or not all(
isinstance(value, str) for value in values
):
raise ManifestError(
f"{context}: expected_matrix values for {column!r} must be "
"a non-empty string list"
)
if len(values) != len(set(values)):
raise ManifestError(
f"{context}: expected_matrix values for {column!r} must be unique"
)
if unique_coordinates != list(expected_matrix):
raise ManifestError(
f"{context}: unique_coordinates must exactly match expected_matrix keys"
)
matrix_rows = math.prod(len(values) for values in expected_matrix.values())
if expected_rows is not None and expected_rows.get("exact") != matrix_rows:
raise ManifestError(
f"{context}: expected_rows.exact must equal expected_matrix size "
f"{matrix_rows}"
)
row_rules = artifact.get("row_rules")
if row_rules is not None:
if not isinstance(row_rules, list) or not row_rules:
raise ManifestError(f"{context}: CSV row_rules must be a non-empty list")
for index, rule in enumerate(row_rules):
if not isinstance(rule, dict) or set(rule) != {"when", "require"}:
raise ManifestError(
f"{context}: row_rules[{index}] needs only when and require"
)
for field in ("when", "require"):
values = rule[field]
if not isinstance(values, dict) or not values:
raise ManifestError(
f"{context}: row_rules[{index}].{field} must be an object"
)
for column, accepted in values.items():
if column not in required:
raise ManifestError(
f"{context}: row_rules[{index}] column {column!r} "
"is not required"
)
if isinstance(accepted, str):
accepted = [accepted]
if not isinstance(accepted, list) or not accepted or not all(
isinstance(value, str) for value in accepted
):
raise ManifestError(
f"{context}: row_rules[{index}] values for {column!r} "
"must be a string or non-empty string list"
)
invalid_values = artifact.get("evidence_invalid_values")
if invalid_values is not None:
if not isinstance(invalid_values, dict) or not invalid_values:
raise ManifestError(
f"{context}: CSV evidence_invalid_values must be a non-empty object"
)
for column, values in invalid_values.items():
if column not in required:
raise ManifestError(
f"{context}: evidence-invalid column {column!r} is not required"
)
if not isinstance(values, list) or not values or not all(
isinstance(value, str) for value in values
):
raise ManifestError(
f"{context}: evidence-invalid values for {column!r} must be "
"a non-empty string list"
)
if len(values) != len(set(values)):
raise ManifestError(
f"{context}: evidence-invalid values for {column!r} must be unique"
)
if performance:
if expected_rows is None and unique_coordinates is None:
raise ManifestError(
f"{context}: required performance CSV needs expected_rows or "
"unique_coordinates"
)
if numeric_columns is None:
raise ManifestError(f"{context}: required performance CSV needs numeric_columns")
if not isinstance(invalid_values, dict) or "Failure" not in invalid_values.get(
"status", []
):
raise ManifestError(
f"{context}: required performance CSV must mark status=Failure "
"as evidence-invalid"
)
def validate_case_artifacts(
case: Mapping[str, Any], context: str
) -> tuple[set[str], bool]:
outputs = case.get("artifacts", [])
if not isinstance(outputs, list):
raise ManifestError(f"{context}: artifacts must be a list")
artifact_ids: set[str] = set()
performance_csv_columns: set[str] = set()
required_performance_csv = False
for artifact in outputs:
if not isinstance(artifact, dict):
raise ManifestError(f"{context}: artifact must be an object")
artifact_id = artifact.get("id")
if not isinstance(artifact_id, str):
raise ManifestError(f"{context}: artifact id is required")
safe_id(artifact_id, "artifact id")
if artifact_id in artifact_ids:
raise ManifestError(f"{context}: duplicate artifact id {artifact_id!r}")
artifact_ids.add(artifact_id)
if artifact.get("kind", "file") not in ("file", "directory"):
raise ManifestError(f"{context}: invalid artifact kind")
if not isinstance(artifact.get("path"), str):
raise ManifestError(f"{context}: artifact path is required")
if artifact.get("format") not in (None, "csv", "json"):
raise ManifestError(f"{context}: unsupported artifact format")
if artifact.get("format") == "json":
required_values = artifact.get("required_values", {})
if not isinstance(required_values, dict) or not all(
isinstance(path, str) and path for path in required_values
):
raise ManifestError(
f"{context}: JSON required_values must be an object with "
"non-empty path keys"
)
required_nonempty = artifact.get("required_nonempty", [])
if not isinstance(required_nonempty, list) or not all(
isinstance(path, str) and path for path in required_nonempty
):
raise ManifestError(
f"{context}: JSON required_nonempty must be a string list"
)
if len(required_nonempty) != len(set(required_nonempty)):
raise ManifestError(
f"{context}: JSON required_nonempty paths must be unique"
)
required_types = artifact.get("required_types", {})
valid_types = {
"array", "boolean", "integer", "null", "number", "object", "string"
}
if not isinstance(required_types, dict) or not all(
isinstance(path, str) and path and isinstance(value, str) and
value in valid_types
for path, value in required_types.items()
):
raise ManifestError(
f"{context}: JSON required_types must map paths to valid type names"
)
continue
if artifact.get("format") != "csv":
continue
required_columns = artifact.get("required_columns", [])
if not isinstance(required_columns, list) or not all(
isinstance(column, str) and column for column in required_columns
):
raise ManifestError(f"{context}: CSV required_columns must be a string list")
if len(required_columns) != len(set(required_columns)):
raise ManifestError(f"{context}: CSV required_columns must be unique")
allowed_values = artifact.get("allowed_values", {})
if not isinstance(allowed_values, dict):
raise ManifestError(f"{context}: CSV allowed_values must be an object")
for column, values in allowed_values.items():
if column not in required_columns:
raise ManifestError(
f"{context}: allowed_values column {column!r} is not required"
)
if not isinstance(values, list) or not values or not all(
isinstance(value, str) for value in values
):
raise ManifestError(
f"{context}: allowed_values for {column!r} must be a "
"non-empty string list"
)
if len(values) != len(set(values)):
raise ManifestError(
f"{context}: allowed_values for {column!r} must be unique"
)
performance_contract = (
case.get("suite") == "performance" and artifact.get("required", False)
)
if performance_contract:
if not required_columns:
raise ManifestError(
f"{context}: required performance CSV needs required_columns"
)
required_performance_csv = True
performance_csv_columns.update(required_columns)
validate_csv_contract(
artifact,
context,
required_columns,
performance=performance_contract,
)
return performance_csv_columns, required_performance_csv
def validate_case(case: Mapping[str, Any], context: str) -> None:
case_id = case.get("id")
if not isinstance(case_id, str):
raise ManifestError(f"{context}: case id is required")
safe_id(case_id, "case id")
if case.get("suite") not in SUITES:
raise ManifestError(f"{context}: suite must be correctness or performance")
state = case.get("state")
if state not in CASE_STATES:
raise ManifestError(f"{context}: invalid state {state!r}")
profiles = case.get("profiles")
if not isinstance(profiles, list) or not profiles or not all(
isinstance(item, str) and item for item in profiles
):
raise ManifestError(f"{context}: profiles must be a non-empty string list")
command = case.get("command")
if state == "ready":
validate_command(command, context)
else:
if command != []:
raise ManifestError(
f"{context}: {state} case must have an explicitly empty command"
)
if not case.get("reason"):
raise ManifestError(f"{context}: {state} case requires a reason")
has_declared_evidence = "artifacts" in case or "performance_metadata" in case
if state == "ready" or has_declared_evidence:
performance_csv_columns, required_performance_csv = validate_case_artifacts(
case, context
)
if case.get("suite") == "performance":
if not required_performance_csv:
raise ManifestError(
f"{context}: performance case with evidence metadata requires a "
"required CSV artifact"
)
validate_performance_metadata(case, context, performance_csv_columns)
def validate_manifest(manifest: Mapping[str, Any]) -> None:
if manifest.get("schema_version") != SCHEMA_VERSION:
raise ManifestError(
f"schema_version must be {SCHEMA_VERSION}, got {manifest.get('schema_version')!r}"
)
catalog = manifest.get("case_catalog")
platforms = manifest.get("platforms")
if not isinstance(catalog, dict) or not isinstance(platforms, dict):
raise ManifestError("case_catalog and platforms must be objects")
for name, case in catalog.items():
safe_id(name, "catalog key")
if not isinstance(case, dict):
raise ManifestError(f"catalog case {name!r} must be an object")
validate_case(case, f"catalog case {name}")
if not platforms:
raise ManifestError("at least one platform is required")
for platform_id, platform in platforms.items():
safe_id(platform_id, "platform id")
if not isinstance(platform, dict):
raise ManifestError(f"platform {platform_id!r} must be an object")
transport = platform.get("transport")
if transport not in ("local", "ssh"):
raise ManifestError(f"platform {platform_id}: invalid transport")
if transport == "ssh" and not platform.get("host"):
raise ManifestError(f"platform {platform_id}: ssh host is required")
if not isinstance(platform.get("repo_root"), str):
raise ManifestError(f"platform {platform_id}: repo_root is required")
if not isinstance(platform.get("build_root"), str):
raise ManifestError(f"platform {platform_id}: build_root is required")
entries = platform.get("cases")
if not isinstance(entries, list) or not entries:
raise ManifestError(f"platform {platform_id}: cases must be non-empty")
for entry in entries:
if isinstance(entry, str):
if entry not in catalog:
raise ManifestError(
f"platform {platform_id}: unknown catalog case {entry!r}"
)
elif isinstance(entry, dict):
reference = entry.get("ref")
if reference and reference not in catalog:
raise ManifestError(
f"platform {platform_id}: unknown catalog case {reference!r}"
)
else:
raise ManifestError(f"platform {platform_id}: invalid case entry")
case_ids: set[str] = set()
for case in resolve_platform_cases(manifest, platform_id):
validate_case(case, f"platform {platform_id} case")
if case["id"] in case_ids:
raise ManifestError(
f"platform {platform_id}: duplicate case id {case['id']!r}"
)
case_ids.add(case["id"])
if case["state"] == "ready":
context = platform_context(
platform_id,
platform,
run_id="VALIDATE",
case_id=case["id"],
)
format_values(case["command"], context)
for artifact in case.get("artifacts", []):
try:
str(artifact["path"]).format_map(context)
except KeyError as error:
raise ManifestError(
f"platform {platform_id} case {case['id']}: "
f"unknown artifact placeholder {error.args[0]!r}"
) from error
def platform_context(
platform_id: str,
platform: Mapping[str, Any],
*,
run_id: str,
case_id: str,
) -> dict[str, str]:
repo = str(platform["repo_root"])
build_root = str(platform["build_root"])
build = build_root if posixpath.isabs(build_root) else posixpath.join(repo, build_root)
remote_root = str(platform.get("remote_work_root", "/tmp/umsh-cross-platform"))
work = posixpath.join(remote_root, run_id, platform_id, case_id)
return {
"platform": platform_id,
"repo": repo,
"build": build,
"work": work,
"run_id": run_id,
"python": str(platform.get("python", "python3")),
}
def format_values(values: Sequence[str], context: Mapping[str, str]) -> list[str]:
try:
return [value.format_map(context) for value in values]
except KeyError as error:
raise ManifestError(f"unknown command placeholder {error.args[0]!r}") from error
def select_platforms(
manifest: Mapping[str, Any], requested: Sequence[str] | None
) -> list[str]:
available = list(manifest["platforms"])
if not requested:
return available
unknown = sorted(set(requested) - set(available))
if unknown:
raise ManifestError(f"unknown platform(s): {', '.join(unknown)}")
requested_set = set(requested)
return [name for name in available if name in requested_set]
def select_cases(
manifest: Mapping[str, Any],
platform_id: str,
*,
suites: Sequence[str] | None,
profile: str,
) -> list[dict[str, Any]]:
suite_set = set(suites or SUITES)
cases = resolve_platform_cases(manifest, platform_id)
return [
case
for case in cases
if case["suite"] in suite_set
and (profile == "all" or profile in case["profiles"])
]
def plan_rows(
manifest: Mapping[str, Any],
platform_ids: Sequence[str],
*,
suites: Sequence[str] | None,
profile: str,
) -> list[dict[str, Any]]:
rows: list[dict[str, Any]] = []
for platform_id in platform_ids:
platform = manifest["platforms"][platform_id]
for case in select_cases(
manifest, platform_id, suites=suites, profile=profile
):
context = platform_context(
platform_id, platform, run_id="DRY_RUN", case_id=case["id"]
)
command = (
format_values(case["command"], context)
if case["state"] == "ready"
else []
)
rows.append(
{
"platform": platform_id,
"backend": platform["backend"],
"suite": case["suite"],
"case": case["id"],
"state": case["state"],
"result_scope": case.get("result_scope", "UNSPECIFIED"),
"paper_claim": case.get("paper_claim", "none"),
"performance_metadata": case.get("performance_metadata"),
"reason": case.get("reason", ""),
"command": command,
}
)
return rows
def print_plan(rows: Sequence[Mapping[str, Any]], *, as_json: bool) -> None:
if as_json:
print(json.dumps(list(rows), indent=2, sort_keys=True))
return
for row in rows:
prefix = (
f"{row['platform']:<10} {row['suite']:<11} "
f"{row['state']:<14} {row['case']}"
)
print(prefix)
if row["command"]:
print(f" {shlex.join(row['command'])}")
else:
print(f" reason={row['reason']}")
counts = Counter(str(row["state"]) for row in rows)
print(
"plan_summary "
+ " ".join(f"{state}={counts[state]}" for state in sorted(counts))
)
def probe_definitions() -> list[tuple[str, list[str], bool]]:
return [
("hostname", ["hostname", "--fqdn"], True),
("uname", ["uname", "-a"], True),
("os_release", ["cat", "/etc/os-release"], False),
("kernel_cmdline", ["cat", "/proc/cmdline"], False),
("lscpu", ["lscpu"], True),
("lspci", ["lspci", "-nnk"], False),
("dri_devices", ["ls", "-l", "/dev/dri"], False),
("opencl", ["clinfo", "--list"], False),
("nvidia_smi", ["nvidia-smi"], False),
("cc", ["cc", "--version"], False),
("cxx", ["c++", "--version"], False),
("clangxx", ["clang++", "--version"], False),
("nvcc", ["nvcc", "--version"], False),
("cmake", ["cmake", "--version"], False),
("ninja", ["ninja", "--version"], False),
("loaded_modules", ["cat", "/proc/modules"], True),
("module_parameters", ["python3", "-c", MODULE_PARAMETER_PROGRAM], False),
("module_file_hashes", ["python3", "-c", MODULE_FILE_HASH_PROGRAM], False),
("meminfo", ["cat", "/proc/meminfo"], True),
("base_page_size", ["getconf", "PAGESIZE"], False),
("hugepages", ["python3", "-c", HUGEPAGE_PROGRAM], False),
]
def archive_probe(
transport: Transport,
destination: Path,
name: str,
command: Sequence[str],
*,
cwd: str | None = None,
timeout: float = 60.0,
required: bool = False,
) -> tuple[dict[str, Any], CommandResult]:
result = transport.run(command, cwd=cwd, timeout=timeout)
stdout_path = destination / "raw" / f"{name}.stdout.txt"
stderr_path = destination / "raw" / f"{name}.stderr.txt"
stdout_info = write_bytes(stdout_path, result.stdout)
stderr_info = write_bytes(stderr_path, result.stderr)
record = {
"command": list(command),
"cwd": cwd,
"required": required,
"exit_code": result.returncode,
"timed_out": result.timed_out,
"duration_seconds": round(result.duration_seconds, 6),
"stdout": stdout_info,
"stderr": stderr_info,
}
return record, result
def parse_loaded_modules(payload: bytes) -> list[str]:
names: list[str] = []
for line in decode(payload).splitlines():
fields = line.split()
if fields:
names.append(fields[0])
return sorted(set(names))
def collect_repo_snapshot(
transport: Transport,
repo: str,
*,
destination: Path | None = None,
) -> dict[str, Any]:
commands = {
"inside_worktree": ["git", "rev-parse", "--is-inside-work-tree"],
"commit": ["git", "rev-parse", "HEAD"],
"branch": ["git", "rev-parse", "--abbrev-ref", "HEAD"],
"status": ["git", "status", "--porcelain=v1", "--untracked-files=all"],
"dirty_hash": ["python3", "-c", DIRTY_HASH_PROGRAM],
}
results: dict[str, CommandResult] = {}
records: dict[str, Any] = {}
for name, command in commands.items():
if destination is None:
result = transport.run(command, cwd=repo, timeout=120.0)
results[name] = result
else:
record, result = archive_probe(
transport,
destination,
f"repo_{name}",
command,
cwd=repo,
timeout=120.0,