-
Notifications
You must be signed in to change notification settings - Fork 81
Expand file tree
/
Copy pathconftest.py
More file actions
1828 lines (1593 loc) · 79.1 KB
/
Copy pathconftest.py
File metadata and controls
1828 lines (1593 loc) · 79.1 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
# Copyright (c) PyPTO Contributors.
# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
# CANN Open Software License Agreement Version 2.0 (the "License").
# Please refer to the License for details. You may not use this file except in compliance with the License.
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
# See LICENSE in the root of the software repository for the full text of the License.
# -----------------------------------------------------------------------------------------------------------
"""Root conftest — CLI options, markers, ST platform filtering, runtime isolation, and ST fixtures.
Runtime isolation: CANN's AICPU framework caches the user .so per device context.
Switching runtimes on the same device within one process causes hangs. When multiple
runtimes are collected and --runtime is not specified, pytest_runtestloop spawns a
subprocess per runtime so each gets a clean CANN context. See docs/testing.md.
"""
from __future__ import annotations
import faulthandler
import json
import logging
import os
import re
import signal
import subprocess
import sys
import tempfile
import time
import typing
# Make simpler's TIMING and NUL levels acceptable to pytest's `--log-level` validator.
# pytest does `int(getattr(logging, level.upper(), level))`, so the value must
# exist as a module attribute on `logging` (not just registered via
# `addLevelName`). Set both — the addLevelName side gives nice formatter output
# (`%(levelname)s` shows `TIMING` instead of `Level 25`); the setattr side is what
# pytest's CLI parser actually consumes.
logging.addLevelName(25, "TIMING")
setattr(logging, "TIMING", 25)
logging.addLevelName(60, "NUL")
setattr(logging, "NUL", 60)
# `pytest --log-level null` upcases to "NULL" before the getattr lookup, so
# expose both spellings.
setattr(logging, "NULL", 60)
# macOS libomp collision workaround — must run before any import that may
# transitively load numpy or torch (i.e. before pytest collects scene test
# goldens). See docs/troubleshooting/macos-libomp-collision.md.
if sys.platform == "darwin":
os.environ.setdefault("KMP_DUPLICATE_LIB_OK", "TRUE")
import pytest # noqa: E402
from simpler_setup import parallel_scheduler as _ps # noqa: E402
from simpler_setup.log_config import DEFAULT_LOG_LEVEL, configure_logging # noqa: E402
from simpler_setup.pto_isa import ensure_pto_isa_root # noqa: E402
from simpler_setup.scene_test import SceneTestLevel, clear_compile_cache, is_manual_for_platform # noqa: E402
# Exit code used when the session watchdog fires. Matches the GNU `timeout`
# convention so shell wrappers (e.g. CI) can distinguish timeout from other
# failures.
TIMEOUT_EXIT_CODE = 124
_SCENE_LEVEL_CHOICES = [int(level) for level in SceneTestLevel]
def _parse_device_range(s: str) -> list[int]:
"""Parse a --device spec into a sorted list of ints.
Delegates to :func:`simpler_setup.parallel_scheduler.device_range_to_list`
so both conftest and standalone share the same parser (supports ``0``,
``0-7``, ``0,2,5``, and mixed ``0,2-4,7``).
"""
return _ps.device_range_to_list(s)
def _normalize_cli_scene_level(level: int | None) -> SceneTestLevel | None:
if level is None:
return None
return SceneTestLevel(level)
def _item_scene_level(item) -> SceneTestLevel | None:
cls = getattr(item, "cls", None)
if cls is not None:
level = getattr(cls, "_st_level", None)
if level is not None:
return SceneTestLevel(level)
function = getattr(item, "function", None)
level = getattr(function, "_st_level", None)
if level is not None:
return SceneTestLevel(level)
return None
class DevicePool:
"""Device allocator for pytest fixtures.
Manages a fixed set of device IDs. Tests allocate IDs before use
and release them after. Works identically for sim and onboard.
"""
def __init__(self, device_ids: list[int]):
self._available = list(device_ids)
def allocate(self, n: int = 1) -> list[int]:
if n > len(self._available):
return []
allocated = self._available[:n]
self._available = self._available[n:]
return allocated
def release(self, ids: list[int]) -> None:
self._available.extend(ids)
_device_pool: DevicePool | None = None
class Network1Peer(typing.NamedTuple):
endpoint: str
remote_device_ids: tuple[int, ...]
session_timeout_s: float
session_listen_host: str
def pytest_addoption(parser):
"""Register CLI options."""
parser.addoption("--platform", action="store", default=None, help="Target platform (e.g., a2a3sim, a2a3)")
parser.addoption("--device", action="store", default="0", help="Device ID or range (e.g., 0, 4-7)")
parser.addoption(
"--case",
action="append",
default=None,
help="Case selector; repeatable. Forms: 'Foo' (any class), 'ClassA::Foo', 'ClassA::' (whole class).",
)
parser.addoption(
"--manual",
action="store",
choices=["exclude", "include", "only"],
default="exclude",
help="Manual test handling: exclude (default), include, only",
)
parser.addoption("--runtime", action="store", default=None, help="Only run tests for this runtime")
parser.addoption(
"--level",
action="store",
type=int,
default=None,
choices=_SCENE_LEVEL_CHOICES,
help="Only run tests for this scene-test level (2, 3, or 4); default: all levels",
)
parser.addoption(
"--exclude-level",
action="store",
type=int,
default=None,
choices=_SCENE_LEVEL_CHOICES,
help="Exclude tests carrying this scene-test level (2, 3, or 4)",
)
parser.addoption(
"--max-parallel",
action="store",
default="auto",
help=(
"Max in-flight subprocesses (make-style); decouples the device pool size "
"from parallelism. 'auto' = min(nproc, len(--device)) on sim, "
"len(--device) on hardware. Use '--max-parallel 2' to throttle sim on a "
"CPU-constrained CI runner without shrinking --device. pytest reserves "
"lowercase short options for itself, so no '-j' short is registered — "
"use the long form in both pytest and standalone."
),
)
parser.addoption("--rounds", type=int, default=1, help="Run each case N times (default: 1)")
parser.addoption(
"--skip-golden", action="store_true", default=False, help="Skip golden comparison (benchmark mode)"
)
parser.addoption(
"--enable-chip-swimlane",
nargs="?",
const=4,
default=0,
type=int,
metavar="PERF_LEVEL",
help="Enable chip swimlane. Bare flag=level 4 (full). "
"1=AICore timing, 2=+dispatch/fanout, 3=+sched phases, 4=+orch phases",
)
parser.addoption(
"--dump-args",
nargs="?",
const="partial",
default="off",
choices=("off", "partial", "hybrid", "full"),
help="Dump per-task args at runtime. Two independent choices, not a dial: "
"which tasks reach the JSON manifest, and which of those also write payload. "
"partial (default when given without a value) = only args selected via "
"Arg::dump(...), manifest and payload; hybrid = every task's manifest, payload "
"only for Arg::dump(...)-marked args (the mode "
"simpler_setup.tools.core_swimlane replays from); full = every task, every "
"arg, manifest and payload.",
)
parser.addoption(
"--enable-dep-gen",
action="store_true",
default=False,
help="Enable dep_gen capture (disabled when --rounds > 1)",
)
parser.addoption(
"--enable-pmu",
nargs="?",
const=2,
default=0,
type=int,
metavar="EVENT_TYPE",
help="Enable PMU collection. Bare flag = PIPE_UTILIZATION(2). "
"Pass event type to override (e.g. --enable-pmu 4)",
)
parser.addoption(
"--enable-scope-stats",
action="store_true",
default=False,
help="Enable per-scope peak collection and emit <output_prefix>/scope_stats/scope_stats.jsonl "
"(per-scope ring-fill peaks).",
)
parser.addoption(
"--enable-swimlane-overhead",
action="store_true",
default=False,
help="Add the 8 Overhead Analysis counter tracks (per-engine "
"idle/ready/overhead + system all/has overhead) to the swimlane JSON. "
"Requires --enable-chip-swimlane + deps.json (re-run with --enable-dep-gen if absent).",
)
parser.addoption(
"--sanitizer",
action="store",
default="none",
help=(
"Run against sanitizer-built binaries. Preset (asan/ubsan/tsan) or raw "
"-fsanitize tokens. Must match the SIMPLER_SANITIZER the runtime was "
"pip-installed with, and needs the matching runtime preloaded "
"(e.g. LD_PRELOAD=$(g++ -print-file-name=libasan.so))."
),
)
parser.addoption(
"--require-pto-isa",
action="store_true",
default=False,
help="Abort the session immediately if PTO-ISA can't be resolved/cloned, "
"instead of deferring to the per-test lazy path. CI scene-test jobs pass "
"this so a transient clone failure fails fast rather than fanning out into "
"device subprocesses that each re-clone into a poisoned directory.",
)
# Distinct from pytest-timeout's per-test --timeout (which `.[test]` pulls
# in on the a2a3 hardware runner); this is session-level.
parser.addoption(
"--pto-session-timeout",
action="store",
type=int,
default=0,
help=(f"Abort whole pytest session after N seconds (0 = disabled; exit code {TIMEOUT_EXIT_CODE} on timeout)"),
)
def _collect_descendant_pids(pid: int) -> list[int]:
"""Return all descendant pids of ``pid``, BFS via Linux ``/proc``.
L3 ``Worker`` forks ChipWorker / SubWorker / next-level children
(``python/simpler/worker.py::_start_hierarchical``). When a sim test
deadlocks inside one of those forked grandchildren, sending SIGUSR1 only
to the dispatched pytest pid is useless — that process is calmly waiting
in ``waitpid``; the real deadlock site sees no signal. Walking the tree
via ``/proc/<pid>/task/<tid>/children`` lets the timeout handler hit
every descendant so faulthandler (which is inherited across ``fork``)
fires in the one that's actually stuck.
Returns ``[]`` on platforms without ``/proc`` (macOS) or if the pid is
already gone. Best-effort: races with grandchild exit are silently
ignored.
"""
from collections import deque # noqa: PLC0415 — local import keeps the signal-handler import surface minimal
out: list[int] = []
visited: set[int] = {pid}
queue: deque[int] = deque([pid])
while queue:
cur = queue.popleft()
try:
task_dir = f"/proc/{cur}/task"
tids = os.listdir(task_dir)
except (FileNotFoundError, NotADirectoryError, PermissionError):
continue
for tid in tids:
try:
with open(f"{task_dir}/{tid}/children") as f:
raw = f.read()
except (FileNotFoundError, PermissionError):
continue
for tok in raw.split():
try:
child = int(tok)
except ValueError:
continue
if child not in visited:
visited.add(child)
out.append(child)
queue.append(child)
return out
def _drain_until_quiet(state: object, max_wait_s: float = 10.0) -> None:
"""Wait until the pump's output stops growing (bounded), so a signaled
process's faulthandler dump lands before the next signal or the SIGTERM.
A fixed sleep races slow signal delivery: a starved process can take
longer than a few seconds to run its dump, and the dump then dies with
the SIGTERM. Called from the session-timeout handler between signals."""
drain_deadline = time.monotonic() + max_wait_s
quiet_rounds = 0
prev_lines = -1
while time.monotonic() < drain_deadline:
cur_lines = sum(len(rj.output_lines) for rj in state.running.values())
if cur_lines == prev_lines:
quiet_rounds += 1
if quiet_rounds >= 5: # ~1 s of no new output
break
else:
quiet_rounds = 0
prev_lines = cur_lines
time.sleep(0.2)
def _install_session_timeout(timeout_s: int) -> None:
# Module-level `_ps` import is intentional (rather than a function-local
# one): doing `from simpler_setup import parallel_scheduler` inside a
# signal handler can deadlock on the import lock if the module hasn't
# been imported yet. Hoisting it to the top guarantees the handler only
# touches an already-loaded module.
def _handler(signum, frame):
print(
f"\n{'=' * 40}\n[pytest] TIMEOUT: session exceeded {timeout_s}s ({timeout_s // 60}min) limit\n{'=' * 40}",
flush=True,
)
# If the dispatcher is mid-flight, surface every stuck child:
# 1. SIGUSR1 each pid AND its descendants so faulthandler (inherited
# across fork in L3 Worker's ChipWorker/SubWorker children) dumps
# all-thread tracebacks (Python + C frames) into the child's
# stdout — pumped into output_lines.
# 2. Briefly let the pump thread drain those bytes (``join`` with a
# short timeout) before reading the tail buffer; otherwise bytes
# sit in the OS pipe and are dropped when SIGTERM closes it.
# 3. Print each in-flight job's tail buffer in a HUNG group so the log
# contains the actual cause, not just the timeout banner.
# 4. SIGTERM/SIGKILL the children so they don't outlive us as orphans
# holding NPU device state.
state = _ps._active_state
if state is not None and state.running:
descendants: dict[int, list[int]] = {}
for p in list(state.running):
kin = _collect_descendant_pids(p.pid) if hasattr(signal, "SIGUSR1") else []
descendants[p.pid] = kin
if not hasattr(signal, "SIGUSR1"):
continue
# Signal the dispatched pytest itself, then every descendant
# (in BFS order — closer kin first is fine, ordering doesn't
# affect the dump). Each signal is followed by a drain until
# the output settles: concurrent faulthandler dumps to the
# same pipe interleave at the byte level, splitting frame
# names, so a signaled process must finish dumping before the
# next one starts.
for target_pid in (p.pid, *kin):
try:
os.kill(target_pid, signal.SIGUSR1)
except (ProcessLookupError, OSError):
pass
_drain_until_quiet(state)
now = time.monotonic()
for p, rj in list(state.running.items()):
elapsed = now - rj.start_time
# ``join`` here only yields the GIL so the pump's pending
# ``output_lines.append`` lands before we read the list. Short
# timeout — pump will block on the next ``readline()`` since
# the child is still alive.
pump = getattr(rj, "pump_thread", None)
if pump is not None:
pump.join(timeout=0.05)
tail = "".join(rj.output_lines[-200:])
kin = descendants.get(p.pid, [])
kin_str = f" descendants={kin}" if kin else ""
print(
f"::group::HUNG {rj.job.label} pid={p.pid} devices={rj.device_ids} elapsed={elapsed:.1f}s{kin_str}",
flush=True,
)
if tail:
print(tail, end="" if tail.endswith("\n") else "\n", flush=True)
print("::endgroup::", flush=True)
print(
f"*** HUNG: {rj.job.label} (devices={rj.device_ids}) — expand group above ***",
flush=True,
)
try:
_ps._terminate_all(state)
except Exception: # noqa: BLE001
pass
os._exit(TIMEOUT_EXIT_CODE)
# signal.alarm / SIGALRM are Unix-only; skip silently on platforms without
# them so --pto-session-timeout is a no-op rather than a crash (e.g. Windows).
if hasattr(signal, "alarm") and hasattr(signal, "SIGALRM"):
signal.signal(signal.SIGALRM, _handler)
signal.alarm(timeout_s)
def _install_child_faulthandler() -> None:
"""In dispatched child pytest processes, let SIGUSR1 dump all-thread stacks.
The parent dispatcher's session-timeout handler sends SIGUSR1 to every
in-flight child before tearing the run down. ``faulthandler.register``
runs in the C signal handler, so it works even when the main thread is
blocked inside a native call that doesn't release the GIL (NPU runtime,
nanobind into C++) — exactly the case Python-level watchdogs miss.
Always-on ``faulthandler.enable()`` also gives us a stack on real crashes
(SIGSEGV/SIGABRT) instead of a silent exit.
"""
faulthandler.enable()
if hasattr(signal, "SIGUSR1"):
try:
faulthandler.register(signal.SIGUSR1, chain=False, all_threads=True)
except (ValueError, RuntimeError):
# Fails when stdout/stderr can't be duped (rare in child subprocs);
# leave faulthandler.enable() in place and continue.
pass
def _configure_sanitizer(config):
"""Wire the `--sanitizer` option: drive kernel compile + require the preload.
The runtime `.so` are sanitizer-built at install time
(`pip install --config-settings=cmake.define.SIMPLER_SANITIZER=...`); this
only has to (a) compile the per-test kernels/orchestration to match and
(b) fail early if the runtime isn't preloaded.
"""
from simpler_setup import sanitizers as san # noqa: PLC0415
from simpler_setup.kernel_compiler import KernelCompiler # noqa: PLC0415
selection = config.getoption("--sanitizer", default="none")
tokens = san.resolve(selection)
if not tokens:
return
try:
san.validate(tokens)
except ValueError as e:
raise pytest.UsageError(f"--sanitizer={selection}: {e}") from e
KernelCompiler._sanitizers = tokens
lib = san.preload_lib(tokens)
if lib and not san.is_runtime_loaded(lib):
platform = config.getoption("--platform", default="") or ""
raise pytest.UsageError(
f"--sanitizer={selection} needs the {lib} runtime preloaded "
f"(the instrumented .so are dlopen'd into this Python). Re-run with:\n"
f" {san.preload_command(tokens, platform)} pytest --sanitizer {selection} ..."
)
def _validate_diagnostic_flags(config) -> None:
# Imported by full path: `simpler_setup.scene_test` as an attribute is the
# @scene_test decorator, not this module.
from simpler_setup.scene_test import _validate_diagnostic_flags as validate # noqa: PLC0415
try:
validate(
chip_swimlane=config.getoption("--enable-chip-swimlane", default=0),
swimlane_overhead=config.getoption("--enable-swimlane-overhead", default=False),
)
except ValueError as e:
raise pytest.UsageError(str(e)) from e
def _validate_level_filters(config) -> None:
if config.getoption("--level", default=None) is not None and (
config.getoption("--exclude-level", default=None) is not None
):
raise pytest.UsageError("--level and --exclude-level cannot be used together")
def pytest_configure(config):
"""Register custom markers and apply global config."""
config.addinivalue_line("markers", "platforms(list): supported platforms for standalone ST functions")
config.addinivalue_line("markers", "requires_hardware: test needs Ascend toolchain and real device")
config.addinivalue_line("markers", "device_count(n): number of NPU devices needed")
config.addinivalue_line(
"markers", "manual(platforms=None): test runs only when --manual is include or only on selected platforms"
)
config.addinivalue_line(
"markers",
"network1_remote_device_count(n): number of remote NPU devices needed on the peer machine",
)
config.addinivalue_line(
"markers",
"sdma: the test exercises PTO-ISA async SDMA. SceneTestCase pytest "
"fixtures and standalone runners build its Worker with enable_sdma=True "
"unless worker_workspace=False selects a platform-provisioned "
"communication-domain workspace. "
"On onboard a2a3, worker-global provisioning creates 48 "
"device-only STARS streams that sit in the device fault domain, which "
"makes a later AICore fault on that device cost minutes instead of "
"~0.3 s (#1425). Two consequences follow from the one marker: such a "
"test never shares an L2 Worker (the pool key carries the flag) and it "
"sorts after every ordinary test, so fault-injection cases run on a "
"device that has never provisioned. The a2a3 CI additionally runs them "
"in a step of their own via -m sdma until #1425 is fixed. On sim platforms, "
"the workspace is inert scratch and no hardware streams are created.",
)
config.addinivalue_line(
"markers",
"runtime(name): runtime this standalone test targets; used by runtime-isolation subprocess "
"filtering so non-@scene_test tests only run under their matching runtime",
)
_validate_level_filters(config)
_validate_diagnostic_flags(config)
_configure_sanitizer(config)
# Configure logging unconditionally (not only when --log-level is passed) so
# simpler's own WARNINGs — e.g. the device-log-timing "no device log written"
# diagnostic — reach stderr by default under pytest, matching the standalone
# CLI path. Without this the root logger has no handler, so pytest's log
# capture swallows the message and a passing run shows nothing. An explicit
# --log-level still overrides the default threshold.
log_level = config.getoption("--log-level", default=None)
configure_logging(log_level or DEFAULT_LOG_LEVEL)
# Pre-clone / refresh PTO-ISA up front so scene-test children inherit the
# pinned managed checkout resolved from pto_isa.pin.
# Pre-clone is an optimization, not a requirement: jobs that don't actually
# need PTO-ISA (e.g. pytest tests/ut on a runner without SSH keys) must not
# be aborted when the eager clone fails. If an actual scene test later needs
# PTO-ISA, scene_test.py's lazy path will re-raise the original error.
#
# --require-pto-isa flips that: callers that know PTO-ISA is mandatory
# (CI scene-test jobs) want the session to die here rather than fan out
# into device subprocesses that each re-attempt the clone.
try:
# Eager clone only — do not export PTO_ISA_ROOT into the ambient env
# (#1403). Downstream host builds receive the path via -DPTO_ISA_ROOT=.
ensure_pto_isa_root(verbose=True)
except OSError as e:
if config.getoption("--require-pto-isa"):
pytest.exit(f"PTO-ISA required but unavailable: {e}", returncode=pytest.ExitCode.USAGE_ERROR)
print(f"[pytest] PTO-ISA pre-clone skipped: {e}", file=sys.stderr)
timeout = config.getoption("--pto-session-timeout")
if timeout and timeout > 0:
_install_session_timeout(timeout)
# Always register SIGUSR1 → faulthandler. In dispatched child pytest
# processes this is what the parent's session-timeout handler relies on
# to extract a stack from a hung run. In the parent dispatcher itself
# it's harmless and lets a developer query "what is this process doing?"
# interactively with `kill -USR1 <pid>`.
_install_child_faulthandler()
# xdist worker: bind this process to a single device id from the --device range.
# The dispatcher (or the user) supplies --device 0-7; xdist spawns N workers
# labelled gw0..gwN-1. We slice device_ids[worker_index] so each worker owns
# exactly one device. L2 Worker is session-scoped inside xdist children, so
# all tests on this worker share one ChipWorker init().
worker_id = os.environ.get("PYTEST_XDIST_WORKER")
if worker_id and worker_id.startswith("gw"):
try:
idx = int(worker_id[2:])
except ValueError:
idx = 0
device_spec = config.getoption("--device", default="0")
ids = _parse_device_range(device_spec)
if 0 <= idx < len(ids):
config.option.device = str(ids[idx])
# Profiling + parallelism is safe: each test case sets its own per-task
# `output_prefix` on CallConfig (see scene_test.py::_build_config), so
# diagnostic artifacts land in distinct directories with no shared
# filenames or rename dance.
def _manual_mode_matches(is_manual: bool, manual_mode: str) -> bool:
return manual_mode == "include" or is_manual == (manual_mode == "only")
def _manual_marker_applies(marker, platform: str | None) -> bool:
if marker is None:
return False
unknown_kwargs = set(marker.kwargs) - {"platforms"}
if unknown_kwargs:
names = ", ".join(sorted(unknown_kwargs))
raise pytest.UsageError(f"@pytest.mark.manual got unsupported keyword argument(s): {names}")
if marker.args and "platforms" in marker.kwargs:
raise pytest.UsageError(
"@pytest.mark.manual platforms must be passed either positionally or by keyword, not both"
)
if "platforms" in marker.kwargs:
platforms = marker.kwargs["platforms"]
elif marker.args:
platforms = marker.args[0] if len(marker.args) == 1 else marker.args
else:
return True
if platforms is None or platform is None:
return True
return is_manual_for_platform(platforms, platform)
def pytest_collection_modifyitems(session, config, items): # noqa: PLR0912
"""Filter ST tests by --platform / --runtime / level axes; order L3 before L2.
Static filter mismatches (wrong level, wrong runtime, wrong platform)
are **deselected** rather than marked ``pytest.skip`` so they don't
inflate the "N skipped" count in each subprocess's terminal summary —
the L2 subprocess alone re-collects ~50 items per runtime, and the
skipped variant produced one SKIPPED line per item under ``-v``.
Deselection goes through ``config.hook.pytest_deselected`` (the same
path pytest's ``-k`` / ``-m`` use), which reports "M deselected"
instead of per-item output.
User-actionable problems (``--platform required``) stay as real skips
so the reason still surfaces in the default pytest summary.
"""
platform = config.getoption("--platform")
runtime_filter = config.getoption("--runtime")
level_filter = _normalize_cli_scene_level(config.getoption("--level"))
exclude_level_filter = _normalize_cli_scene_level(config.getoption("--exclude-level"))
manual_mode = config.getoption("--manual", default="exclude")
keep: list = []
deselected: list = []
for item in items:
# Pre-existing skip markers (e.g. explicit ``@pytest.mark.skip``)
# stay put — the user asked for a visible skip, not a silent drop.
if any(m.name == "skip" for m in item.iter_markers()):
keep.append(item)
continue
cls = getattr(item, "cls", None)
item_level = _item_scene_level(item)
if cls is not None and hasattr(cls, "CASES") and isinstance(cls.CASES, list):
# SceneTestCase class item.
if not platform:
# User error: surface it as a real skip so the reason is visible.
item.add_marker(pytest.mark.skip(reason="--platform required"))
keep.append(item)
continue
if not any(
platform in case.get("platforms", [])
and _manual_mode_matches(is_manual_for_platform(case.get("manual"), platform), manual_mode)
for case in cls.CASES
):
deselected.append(item)
continue
if runtime_filter and getattr(cls, "_st_runtime", None) != runtime_filter:
deselected.append(item)
continue
if level_filter is not None and item_level != level_filter:
deselected.append(item)
continue
if exclude_level_filter is not None and item_level == exclude_level_filter:
deselected.append(item)
continue
keep.append(item)
continue
# Standalone pytest test (resource functions and ordinary tests).
is_manual = _manual_marker_applies(item.get_closest_marker("manual"), platform)
if not _manual_mode_matches(is_manual, manual_mode):
deselected.append(item)
continue
platforms_marker = item.get_closest_marker("platforms")
if platforms_marker:
if not platform:
item.add_marker(pytest.mark.skip(reason="--platform required"))
keep.append(item)
continue
if platform not in platforms_marker.args[0]:
deselected.append(item)
continue
# runtime-isolation filter for non-@scene_test tests: if the item
# declares ``@pytest.mark.runtime("X")`` and a --runtime filter is
# active, deselect when they don't match. Prevents
# test_explicit_fatal_reports and friends from running under every
# runtime's subprocess.
runtime_marker = item.get_closest_marker("runtime")
if runtime_marker and runtime_marker.args and runtime_filter and runtime_marker.args[0] != runtime_filter:
deselected.append(item)
continue
if level_filter is not None and item_level != level_filter:
deselected.append(item)
continue
if exclude_level_filter is not None and item_level == exclude_level_filter:
deselected.append(item)
continue
keep.append(item)
if deselected:
items[:] = keep
config.hook.pytest_deselected(items=deselected)
# Sort: L3 tests first (they fork child processes that inherit main process CANN state,
# so they must run before L2 tests pollute the CANN context).
def sort_key(item):
level = _item_scene_level(item) or 0
# SDMA last, for the same class of reason L3 goes first: provisioning
# the workspace leaves 48 STARS streams in the device's fault domain,
# so every fault-injection case must have already run on a device that
# never provisioned (#1425). Keyed off the marker, not the class, since
# the fault-injection tests are plain functions with no _st_level.
sdma_last = 1 if item.get_closest_marker("sdma") else 0
return (sdma_last, 0 if level >= 3 else 1, item.nodeid)
items.sort(key=sort_key)
# The automatic rankN/dN layout is scoped to one same-host L3 Worker. Every
# level above NODE owns several L3 Workers, each of which numbers its local
# chips from zero, so accepting one would reintroduce directory collisions.
if config.getoption("--enable-chip-swimlane", default=0) and config.getoption("--rounds", default=1) <= 1:
multi_node_items = [
item
for item in items
if (_item_scene_level(item) or SceneTestLevel.CHIP) > SceneTestLevel.NODE
and not any(marker.name == "skip" for marker in item.iter_markers())
]
if multi_node_items:
sample = ", ".join(sorted({item.nodeid for item in multi_node_items})[:3])
more = "" if len(multi_node_items) <= 3 else f" (+{len(multi_node_items) - 3} more)"
raise pytest.UsageError(
"--enable-chip-swimlane supports automatic multi-Rank merging only for same-host L3 tests; "
f"NETWORK1/L4 needs a node namespace before it is safe. Items: {sample}{more}."
)
# ---------------------------------------------------------------------------
# Test dispatcher: Resource phase (device-aware parallel subprocesses for L3
# classes *and* standalone resource-marked functions) + L2 phase (per-runtime
# subprocess). Activated only when neither --runtime nor --level is set by
# the caller. Dispatcher-spawned children set both, so they fall through to
# pytest's default runtestloop without recursing.
# ---------------------------------------------------------------------------
class _ResourceJob(typing.NamedTuple):
"""One device-allocating subprocess job fed into Resource phase.
``kind`` drives the ``--level 3`` filter added to the child command (for
L3 classes). The dispatch itself (bin-pack over ``--device`` pool,
``run_jobs`` scheduling, fail-fast semantics) is identical.
"""
kind: str # "l3" or "standalone"
nodeid: str
label: str # class name for "l3", function name for "standalone"
runtime: str
device_count: int
def _collect_st_runtimes(items, level=None):
"""Return sorted list of unique runtimes from items, optionally filtered by level."""
runtimes = set()
for item in items:
cls = getattr(item, "cls", None)
if not cls:
continue
rt = getattr(cls, "_st_runtime", None)
lvl = getattr(cls, "_st_level", None)
if rt and (level is None or lvl == level):
runtimes.add(rt)
return sorted(runtimes)
def _collect_resource_jobs(items, platform, manual_mode="exclude"):
"""Collect every item that needs a dedicated device-allocating subprocess.
Two job kinds share one phase:
- ``l3``: one per L3 ``SceneTestCase`` class.
``device_count`` is the max across the class's platform-matching
cases selected by ``manual_mode``.
- ``standalone``: one per non-class pytest function that declares its
resource needs via ``@pytest.mark.device_count(n)`` +
``@pytest.mark.runtime("...")`` (and optional
``@pytest.mark.platforms([...])``).
Both are dispatched through the same ``parallel_scheduler.run_jobs``
bin-pack, so merging them reduces the dispatcher to a single phase in
front of L2.
"""
jobs: list[_ResourceJob] = []
# L3 SceneTestCase classes (one job per class, keyed on nodeid).
l3_by_nodeid: dict[str, _ResourceJob] = {}
for item in items:
if any(m.name == "skip" for m in item.iter_markers()):
continue
cls = getattr(item, "cls", None)
if not cls or getattr(cls, "_st_level", None) != 3:
continue
rt = getattr(cls, "_st_runtime", None)
if not rt:
continue
max_dev = 1
saw_case = False
for case in getattr(cls, "CASES", []):
if platform and platform not in case.get("platforms", []):
continue
if not _manual_mode_matches(is_manual_for_platform(case.get("manual"), platform), manual_mode):
continue
saw_case = True
max_dev = max(max_dev, int(case.get("config", {}).get("device_count", 1)))
if saw_case:
l3_by_nodeid[item.nodeid] = _ResourceJob(
kind="l3", nodeid=item.nodeid, label=cls.__name__, runtime=rt, device_count=max_dev
)
jobs.extend(l3_by_nodeid.values())
# Standalone pytest functions with device_count + runtime markers.
standalone_by_nodeid: dict[str, _ResourceJob] = {}
for item in items:
if any(m.name == "skip" for m in item.iter_markers()):
continue
if getattr(item, "cls", None) is not None:
continue
dev_marker = item.get_closest_marker("device_count")
if dev_marker is None:
continue
rt_marker = item.get_closest_marker("runtime")
if rt_marker is None or not rt_marker.args:
continue
platforms_marker = item.get_closest_marker("platforms")
if platforms_marker and platform and platform not in platforms_marker.args[0]:
continue
dev_count = int(dev_marker.args[0]) if dev_marker.args else 1
standalone_by_nodeid[item.nodeid] = _ResourceJob(
kind="standalone",
nodeid=item.nodeid,
label=item.name,
runtime=rt_marker.args[0],
device_count=dev_count,
)
jobs.extend(standalone_by_nodeid.values())
return jobs
def _strip_value_options(args, options):
stripped = []
skip_next = False
for arg in args:
if skip_next:
skip_next = False
continue
text = str(arg)
if text in options:
skip_next = True
continue
if any(text.startswith(f"{option}=") for option in options):
continue
stripped.append(text)
return stripped
# Options that change what a case does rather than which case runs. The
# resource child's argv is built from scratch so it can be narrowed to one
# nodeid (see _build in the dispatcher), which means nothing reaches it that is
# not listed here — a diagnostic the parent asked for is silently dropped
# otherwise, and the run passes while producing no artifact at all.
#
# The options that select which case runs — --manual and --case — are forwarded
# by _resource_child_command alongside the nodeid they refine, because a nodeid
# names a whole SceneTestCase class: `--case` filters inside its single
# `test_run` item at run time, so a child that does not receive it runs every
# case of the class the parent narrowed to one.
_RESOURCE_CHILD_VALUE_OPTIONS = (
("--rounds", 1),
("--enable-chip-swimlane", 0),
("--dump-args", "off"),
("--enable-pmu", 0),
)
_RESOURCE_CHILD_FLAG_OPTIONS = (
"--skip-golden",
"--enable-dep-gen",
"--enable-scope-stats",
"--enable-swimlane-overhead",
)
def _resource_child_diagnostic_argv(cfg):
"""Forward the parent's diagnostic and round selection to a resource child."""
argv = []
for option, unset in _RESOURCE_CHILD_VALUE_OPTIONS:
value = cfg.getoption(option, default=unset)
if value != unset:
argv.extend([option, str(value)])
for option in _RESOURCE_CHILD_FLAG_OPTIONS:
if cfg.getoption(option, default=False):
argv.append(option)
return argv
def _resource_child_command(spec, device_ids, platform, manual_mode, cfg):
command = [
sys.executable,
"-m",
"pytest",
spec.nodeid,
"--runtime",
spec.runtime,
"--device",
_ps.format_device_range(device_ids),
]
if spec.kind == "l3":
command.extend(["--level", "3"])
if platform:
command.extend(["--platform", platform])
command.extend(["--manual", manual_mode])
for selector in cfg.getoption("--case", default=None) or []:
command.extend(["--case", str(selector)])
command.extend(_resource_child_diagnostic_argv(cfg))
return command
def _base_pytest_argv(session, *, strip_options=()):
"""Inherit the user's original pytest invocation args."""
base = [sys.executable, "-m", "pytest"]
args = _strip_value_options(session.config.invocation_params.args, set(strip_options))
for arg in args:
base.append(str(arg))
return base
def _resolve_max_parallel(cfg, platform: str, device_ids: list[int]) -> int:
"""Parse --max-parallel; 'auto' selects a platform-aware default."""
raw = cfg.getoption("--max-parallel", default="auto")
if raw in (None, "", "auto"):
return _ps.default_max_parallel(platform or "", device_ids)
try:
val = int(raw)
except (TypeError, ValueError) as e:
raise pytest.UsageError(f"--max-parallel must be 'auto' or an integer, got {raw!r}") from e
if val < 1:
raise pytest.UsageError(f"--max-parallel must be >= 1, got {val}")
return val
def _invocation_has_option(cfg, options):
"""Return whether the original command line contains one of ``options``."""
for arg in cfg.invocation_params.args:
text = str(arg)
if text in options or any(text.startswith(f"{option}=") for option in options):
return True
return False
def _l2_xdist_options(cfg, max_parallel: int):
"""Return whether L2 uses xdist, child defaults, and the worker label.
``numprocesses`` arrives here as ``None`` or ``0``. A top-level ``-n N``
with N > 0 puts xdist in distribution mode, and its ``pytest_runtestloop``
runs the whole session before this dispatcher's own hook is reached, so a
positive worker count is only ever seen from a direct caller.
``--pdb`` is serial whatever ``numprocesses`` says: xdist zeroes the worker
count only for ``-n auto`` / ``-n logical``, so a bare ``--pdb`` arrives
with it unset — and the L2 child inherits ``--pdb``, which xdist rejects
with a usage error as soon as ``-n`` puts the child in distribution mode.
"""
plugin_active = cfg.pluginmanager.hasplugin("xdist")
if not plugin_active or cfg.getoption("usepdb", default=False):
return False, [], None
requested_workers = cfg.getoption("numprocesses", default=None)
if requested_workers == 0:
return False, [], None
if requested_workers is None and max_parallel <= 1:
return False, [], None
options = []
if requested_workers is None:
options.extend(["-n", str(max_parallel)])
# xdist rewrites its effective default from ``no`` to ``load`` as soon as
# ``-n`` is active. Inspect the original command line so that derived
# ``load`` does not masquerade as an explicit user choice. ``-d`` is
# xdist's shortcut for ``--dist=load`` and overrides a ``--dist`` passed
# alongside it, so it is an explicit choice too. The scan sees the