diff --git a/docs/NODE_RUNTIME.md b/docs/NODE_RUNTIME.md index fba8f595d..a82718cd7 100644 --- a/docs/NODE_RUNTIME.md +++ b/docs/NODE_RUNTIME.md @@ -277,12 +277,141 @@ One shell call reads, in this order: | GPUs | `nvidia-smi --query-gpu=index,pci.bus_id,name,memory.total,ecc.errors.uncorrected.volatile.total` | no GPU at all, fewer GPUs answer than the inventory's `cards_per_node` (a sampler: than the first check saw), a GPU nvidia-smi cannot open, a GPU's memory shrank, or nvidia-smi cannot talk to the driver | | ECC | the same query | the volatile uncorrectable ECC count grew since the previous check (a count that went down is the new baseline) | | NVLink fabric | the `Fabric` blocks of `nvidia-smi -q` | a GPU that has a fabric state is not `Completed/Success` (a PCIe card's `N/A` passes) | -| fabric manager | `systemctl is-active nvidia-fabricmanager` | it was active and is now `inactive` or `failed` (a node without NVSwitch, never active, passes) | +| fabric manager | `systemctl is-active nvidia-fabricmanager` and its `NRestarts`, what shows the node's own NVSwitch, the boot id | the node must run it (it was active in this boot, or the node has NVSwitch at the first check) and it is not `active`, or it restarted since the previous check; see below | | IB / RoCE ports | `ibstat` (`ibv_devinfo -v` only when ibstat fails) | a port named by `NCCL_IB_HCA` is missing, not `Active`, or slower than at the first check | The XIDs and the ECC count only count from the second check on. What the kernel log holds at the first check is history: the preflight judged the node then. +The fabric manager is judged by whether the node has NVSwitch of its own, and by +what it did in this boot (the boot id of the XID section). + +Whether the node has NVSwitch of its own, in this order: + +| finding | NVSwitch | +|---|---| +| a GPU name starts with `GB` | no (an NVL72-class compute tray: its NVSwitches sit in the switch trays), whatever else it shows | +| the driver lists NVSwitch devices in `/proc/driver/nvidia-nvswitch/devices`, or `/dev/nvidia-nvswitch` exist, or `lspci` shows an NVSwitch (class `0680`, `10de:1af1` A100 HGX or `10de:22a3` H100 / H200 HGX, from pci.ids) | yes (A100 / Hopper HGX) | +| no GPU has a real NVLink fabric state (`N/A`, or no `Fabric` block) | no (PCIe) | +| the VPD of a Mellanox (`15b3`) PCI function, any function, names the NVLink switch management port (`SMDL=SW_MNG`) | yes (HGX B200 / B300) | +| every GPU is a B200 / B300 (not GB, not PCIe) and has a real fabric state | yes (HGX B200 / B300, without root; a VPD without the port does not overrule it) | +| `lspci` shows another NVIDIA class `0680` bridge | yes (soft evidence) | +| the VPD of every Mellanox function read and none names it | no | +| anything else, or the fabric state did not read | not determined | + +On HGX B200 / B300 the NVSwitches are not PCIe devices of the host. They sit behind a +ConnectX bridge that the fabric manager reaches through NVLSM (NVIDIA Fabric Manager +User Guide). The host shows no procfs entry, no device file and no class `0680` +bridge; amazon-eks-ami PR 2840 reports the same on p6-b200. Hence the VPD rule, and +the GPU-name rule for a user that cannot read the VPD (it reads as root only). Each VPD +read is bounded to 1 s (`timeout 1`), all of them to 3 s; the rest are not read, and +without a `timeout` command none is. A node whose NVSwitch is not determined is never +taken for one without. A section cut off after the state line says `FM section timed +out after reading state`. Only a device, an NVSwitch PCI id or the VPD port is hard +evidence of NVSwitch on the node; the GPU names and another NVIDIA `0680` bridge are +not. A fabric manager that is not running on a node with soft evidence only is at most +unread at the first check, never bad. + +On a GB compute tray the fabric manager is not judged at all: the switch trays run it, +and the tray's own fabric state (`Completed`, or the fabric reason) judges the topology. + +The state of the fabric manager, its process first: + +| systemd | `nv-fabricmanager` process | state | +|---|---|---| +| unit `active` | not looked for | `active` | +| anything else | runs | `active` (a GPU Operator driver container runs it, maybe next to a stale host unit that is disabled, inactive or failed) | +| unit `loaded`, `inactive` / `failed` | none | `inactive` / `failed` (it stopped) | +| no unit (`not-found`), or `inactive` / `failed` of a unit that is not loaded (`masked`) | none | not running | +| unit `loaded`, `failed`, active earlier in this boot (`ActiveEnterTimestampMonotonic` > 0) | not seen | `failed` (it ran here and failed) | +| any other `inactive` / `failed`, or no unit | not seen | not read (a `node_health_degraded` event says so) | + +The processes are not seen when `/proc/1/comm` cannot be read (`hidepid`), or when the +check runs in a container (the output of `systemd-detect-virt -c`, where `none` means not +a container; without the tool, a non-empty `/run/systemd/container`, `/.dockerenv`, +`/run/.containerenv`, or `container=` in pid 1's environment; none of them readable means +not a container). A container run with `--pid=host` may read as one: its fabric manager +then reads unread, never bad. A system +container with its own pid 1 sees the host's NVSwitch devices but not the host's fabric +manager. A stale host unit that stopped, next to a fabric manager that runs in a driver +container, looks the same as one that is down when the processes are hidden, so it is not +judged: the event `processes hidden (hidepid): fabric manager not judged` (or `in a +container: ...`) says so, once per node. A fabric that is not `Completed` still makes the +node bad by its own reason. + +`systemctl is-active` prints `inactive` for a unit that does not exist, hence the +LoadState. The check reads `systemctl show -p LoadState` (and +`ActiveEnterTimestampMonotonic`) and cuts the prefix itself (`--value` needs systemd +230). It counts the processes by `/proc//comm`, which the kernel cuts to 15 +characters (`nv-fabricmanage`). + +A fabric manager that is not running, at the first check: + +- bad when the node has hard evidence of NVSwitch (the processes were seen: it is gone); +- ok when there is no such evidence and every GPU's fabric is `Completed/Success`: the + fabric is managed off-host (a shared NVSwitch guest VM, whose fabric manager runs on + the service VM; a guest whose NVSwitch cannot be determined); +- unread otherwise (the fabric state judges the node). + +A loaded unit that is `inactive` or `failed`, with no process, at the first check, on a +node with soft evidence of NVSwitch only (HGX B300 as a user without root) and every +fabric `Completed/Success`: + +- ok when the unit was never active in this boot (`ActiveEnterTimestampMonotonic` 0): the + fabric is managed off-host, and the guest image ships the unit; +- bad when it was (> 0): it ran here and stopped; +- unread when that time did not read. + +With hard evidence, or a fabric that is not `Completed`, any state but `active` is bad. + +The rules over the checks: + +- No NVSwitch of its own (PCIe, a GB tray, VPD without the switch port): the fabric + manager is never judged, even when it was active earlier in the boot. A tray may + have the unit installed, and it fails there. A fabric that is not `Completed` makes + the node bad by its own reason. +- Once the fabric manager was active in a boot (its unit, or its process), every later + check of that boot that does not read `active` (`inactive`, `failed`, `activating`, + `deactivating`, not running) is bad, + until it is active again. This also holds when NVSwitch was not determined: a fabric + manager that ran has a fabric to manage. One that stays down makes the node `lost` + after two checks, even while the fabric still reads `Completed`. +- The first check of a new launcher has no memory (it lives in the checker, not on + disk). On a node with NVSwitch, any state but `active` is bad at once, and that boot + is remembered. A check where the state did not read or NVSwitch was not determined + judges nothing and is not counted as the first one. The same rule, on one check + alone, is `yeto.hw.node_health.fabric_manager_absolute`: `ok`, `bad` or `unread`. +- On a node that must run it, an `NRestarts` that grew since the previous check of the + same boot is a restart. Every check that saw one writes a `node_health_fm_restarted` + event (its streak, `NRestarts` or the process ids). A restart is a reason only when + the fabric manager restarted at 3 checks in a row (`FM_RESTART_STREAK`): a unit in a + restart loop can read `active` at every check, and a loop that goes on makes the node + `lost` at the 4th (about 4 minutes, on purpose: one or two restarts that come back + lose no node). A check without a restart zeroes the streak; a read failure keeps it. + A fabric manager that is down after a restart is bad by its state, at once. + `NRestarts` counts only the restarts systemd makes itself, so this needs a `Restart=` + setting on the unit (a drop-in such as `Restart=on-failure`); restarts by hand do not + count. A fabric manager without its unit has no `NRestarts`: its process's pid and + start time (field 22 of `/proc//stat`) stand in. A restart is every process of + the previous check gone (one more process that comes and goes is none), counted in + the same streak. +- A new boot id forgets all of it. A fabric manager never active since the reboot is + judged as before: one bad check when it was active before the reboot (on a node with + NVSwitch), then the fabric state judges the node. A fabric manager that does not + start leaves the NVSwitch fabric unfinished on an HGX node. +- A systemctl that timed out says nothing. Without a boot id, a stop is bad once. + +Not yet seen on our own hardware: the VPD keyword on an HGX B300 node, and that a +GB300 tray's GPU names start with `GB`. The rules above follow the public sources. + +Known limit: on an HGX B300 bare-metal node checked as a user that cannot read the VPD, +there is no hard evidence of NVSwitch, only the GPU names. If its fabric manager has no +loaded unit (a GPU Operator driver container runs it) and dies after the fabric reads +`Completed`, a check that never saw its process takes the fabric for one managed +off-host. New CUDA launches then fail with `cudaErrorSystemNotReady`, so the trainer +reports the error itself. A check that saw the process earlier in the boot does catch +it (the per-boot memory), and so does a loaded unit that was active in this boot. + A kernel log without timestamps (dmesg's default has them) is followed by its last line, how often that line ends the log, and the line before it, so lines that rotate out of the log's head do not move the cursor. One limit is left: when the log holds diff --git a/tests/test_node_health.py b/tests/test_node_health.py index 09f0b2de9..2970e35d7 100644 --- a/tests/test_node_health.py +++ b/tests/test_node_health.py @@ -6,9 +6,12 @@ from __future__ import annotations +import os import shlex +import shutil import subprocess import sys +import time from pathlib import Path import pytest @@ -30,14 +33,14 @@ BOOT = "0b6f8c1e-2d4a-4f7e-9a51-3c2d1e0f9a88" -def gpus_text(n=8, mib=275040, ecc=None, gone=()) -> str: +def gpus_text(n=8, mib=275040, ecc=None, gone=(), name="NVIDIA B300 SXM6 AC") -> str: ecc = ecc or {} rows = [] for i in range(n): if i in gone: rows.append(f"Unable to determine the device handle for GPU0000:{BUSES[i].upper()}:00.0: Unknown Error") continue - rows.append(f"{i}, 00000000:{BUSES[i].upper()}:00.0, NVIDIA B300 SXM6 AC, {mib}, {ecc.get(i, 0)}") + rows.append(f"{i}, 00000000:{BUSES[i].upper()}:00.0, {name}, {mib}, {ecc.get(i, 0)}") return "\n".join(rows) @@ -119,7 +122,7 @@ def test_an_unfinished_nvlink_fabric_fails_the_node(): r = check(node_text(fabric=(0, FABRIC_IN_PROGRESS))) assert r.ok_single is False assert r.reasons == ["NVLink fabric In Progress/N/A on 8/8 GPUs (fabric manager: active)"] - stopped = check(node_text(fabricmanager=(3, "failed")), check(node_text()).facts) + stopped = check(node_text(fabricmanager=(3, fm_out("failed"))), check(node_text()).facts) assert stopped.reasons == ["nvidia-fabricmanager failed (was active)"] @@ -432,21 +435,727 @@ def two(*rows): def test_a_node_without_nvswitch_passes_with_its_fabric_manager_inactive_and_no_fabric(): - pcie = dict(fabricmanager=(3, "inactive"), fabric=(1, "")) + pcie = dict(fabricmanager=(3, fm_out("inactive")), fabric=(1, "")) first = check(node_text(**pcie)) second = check(node_text(**pcie), first.facts) assert first.ok_single and second.ok_single and second.facts["fm"] == "inactive" assert second.facts["fabric"] == "none" na = " Fabric\n State : N/A\n Status : N/A\n" * 8 # a PCIe card: no NVLink fabric - r = check(node_text(fabric=(0, na), fabricmanager=(3, "inactive")), first.facts) + r = check(node_text(fabric=(0, na), fabricmanager=(3, fm_out("inactive"))), first.facts) assert r.ok_single and r.facts["fabric"] == "none" - stopped = check(node_text(fabricmanager=(3, "inactive")), check(node_text()).facts) + stopped = check(node_text(fabricmanager=(3, fm_out("inactive"))), check(node_text()).facts) assert stopped.reasons == ["nvidia-fabricmanager inactive (was active)"] # one that ran and stopped # nvidia-smi -q cut off by its section's timeout: what it printed is not the fabric's state hung = check(node_text(fabric=(124, FABRIC_IN_PROGRESS)), first.facts) assert hung.ok_single and hung.reasons == [] +# -- the fabric manager over a boot (a fabric manager that stays down reaches lost) ---------- + +# What the fabricmanager section shows (FM_SCRIPT). The default is an HGX B300 node as the +# ssh user (not root) sees it: its NVSwitches sit behind a ConnectX bridge, so no procfs +# entry, no device file and no NVIDIA PCI bridge; ten Mellanox devices whose VPD does not +# read; GPUs "NVIDIA B300 SXM6 AC" with a Completed fabric. +B300_ROOT = dict(vpd=10, sw=1) # as root: the VPD of the switch management port names SW_MNG +B300_ROOT_NO_SW = dict(vpd=10, sw=0) # every VPD read, none names it: the GPUs still say NVSwitch +VPD_NO_SW = dict(name="NVIDIA H100 80GB HBM3", vpd=10, sw=0) # a fabric, every VPD read without the port +UNIT_GONE = dict(load="not-found", fm_proc=0) # no unit, no nv-fabricmanager process (a shared NVSwitch VM) +UNIT_IN_CONTAINER = dict(load="not-found", fm_proc=1) # no unit, its process from a driver container +HIDEPID = dict(load="not-found", proc1=0) # no unit, the processes not seen +HOPPER = dict(name="NVIDIA H100 80GB HBM3", proc=4, pci=4) # Hopper HGX: NVSwitch on the host's PCIe +HIDDEN = dict(name="NVIDIA H100 80GB HBM3") # a fabric, no NVSwitch shown, VPD unread: not determined +TRAY = dict(name="NVIDIA GB300") # an NVL72-class compute tray: a Completed fabric, switches elsewhere +PCIE = dict(name="NVIDIA L40S", mlx=2, fabric=(1, "")) # no Fabric block in nvidia-smi -q +PCIE_NA = dict(name="NVIDIA H100 PCIe", mlx=2, + fabric=(0, " Fabric\n State : N/A\n Status : N/A\n" * 8)) +NO_PROBE = HIDDEN + + +ENTERED = 41_000_000 # the unit's ActiveEnterTimestampMonotonic: it was active in this boot + + +def fm_out(state: str | None, *, load="loaded", entered=ENTERED, fm_proc=None, fm_ids=None, proc1=1, container=0, + proc=None, dev=0, pci=0, bridge=None, mlx=10, vpd=0, sw=0, restarts=0) -> str: + """The fabricmanager section's output; ``load`` the unit's LoadState, ``entered`` its + ActiveEnterTimestampMonotonic (0: not active in this boot; None: not printed; a unit + not found has 0); ``fm_proc`` the nv-fabricmanager processes (None: not counted), + ``fm_ids`` their pid:starttime; ``proc1`` 0: the processes not seen (hidepid); ``proc`` / + ``pci`` / ``vpd`` None: no procfs dir / no lspci / no timeout (the VPD not read); + ``bridge``: another NVIDIA class 0680 bridge (None: not printed).""" + entered = 0 if load == "not-found" and entered == ENTERED else entered + lines = ([state] if state else []) + [f"loadstate={load}"] + lines += [] if entered is None else [f"active_enter={entered}"] + lines += [f"container={container}", f"proc1={proc1}"] + if fm_proc is not None: + ids = fm_ids if fm_ids is not None else " ".join(f"{4242 + n}:777" for n in range(fm_proc)) + lines += [f"fm_proc={fm_proc}", f"fm_ids={ids}"] + lines += [f"nrestarts={'' if restarts is None else restarts}"] + lines += ([] if proc is None else [f"nvswitch_proc={proc}"]) + [f"nvswitch_dev={dev}"] + lines += ([] if pci is None else [f"nvswitch_pci={pci}"]) + ([] if bridge is None else [f"nvidia_bridge={bridge}"]) + lines += [f"mlx={mlx}"] + lines += [] if vpd is None else [f"mlx_vpd={vpd}", f"sw_mng={sw}"] + return "\n".join(lines) + + +def fm_text(state: str | None, boot=BOOT, *, name="NVIDIA B300 SXM6 AC", restarts=0, **over) -> str: + """A healthy 8-GPU node (default: HGX B300, as above) whose fabric manager reads + ``state`` in ``boot`` (None: the section timed out, nothing printed).""" + keys = ("load", "entered", "fm_proc", "fm_ids", "proc1", "container", "proc", "dev", "pci", "bridge", "mlx", + "vpd", "sw") + probe = {k: over.pop(k) for k in keys if k in over} + fm = (124, "") if state is None else (0 if state == "active" else 3, fm_out(state, restarts=restarts, **probe)) + over.setdefault("gpus", (0, gpus_text(name=name))) + return node_text(fabricmanager=fm, xid=(0, xid_text(boot=boot)), **over) + + +def watch_through(*texts, multi=False): + w = HealthWatch("cuda", hcas=hcas_of(HCA), multi=multi) + return w, [w.observe(t) for t in texts] + + +def test_a_fabric_manager_that_stays_failed_after_it_was_active_is_lost(): + w, rs = watch_through(fm_text("active"), fm_text("failed"), fm_text("failed"), fm_text("failed")) + assert [r.verdict for r in rs] == ["ok", "bad_once", "lost", "lost"] + assert [r.event for r in rs] == [None, None, "node_health", None] # the loss is said once + assert all(r.result.reasons == ["nvidia-fabricmanager failed (was active)"] for r in rs[1:]) + assert all(r.result.facts["fabric"] == "8/8 completed" for r in rs) # the fabric still reads Completed + assert rs[-1].result.facts["fm_boot"] == BOOT and "fm_why" not in rs[-1].result.facts + assert w.record()["reasons"] == ["nvidia-fabricmanager failed (was active)"] + + +@pytest.mark.parametrize("state", ["inactive", "activating", "deactivating"]) +def test_any_state_but_active_after_active_in_the_boot_stays_a_reason(state): + _, rs = watch_through(fm_text("active"), fm_text(state), fm_text(state)) + assert [r.verdict for r in rs] == ["ok", "bad_once", "lost"] + assert rs[2].result.reasons == [f"nvidia-fabricmanager {state} (was active)"] + + +def test_an_active_fabric_manager_clears_the_streak_and_an_unread_one_judges_nothing(): + _, rs = watch_through(fm_text("active"), fm_text("failed"), fm_text("active"), fm_text("failed"), + fm_text(None), fm_text("failed")) + # systemctl that timed out: that check passes (the streak goes), the memory stays + assert [r.verdict for r in rs] == ["ok", "bad_once", "ok", "bad_once", "ok", "bad_once"] + assert rs[4].result.reasons == [] and rs[4].result.facts["fm_boot"] == BOOT + assert rs[5].result.reasons == ["nvidia-fabricmanager failed (was active)"] + + +def test_a_read_failure_keeps_the_fabric_manager_memory(): + _, rs = watch_through(fm_text("active"), fm_text("failed"), node_text(gpus=(124, "")), fm_text("failed")) + assert [r.verdict for r in rs] == ["ok", "bad_once", "read_failed", "lost"] + assert rs[2].result.facts["fm_boot"] == BOOT + + +@pytest.mark.parametrize("node", [PCIE, PCIE_NA, TRAY, VPD_NO_SW], ids=["pcie", "pcie-na", "gb-tray", "vpd-no-sw"]) +@pytest.mark.parametrize("state", ["inactive", "failed", "activating"]) +def test_a_node_without_nvswitch_of_its_own_is_never_judged_on_its_fabric_manager(node, state): + _, rs = watch_through(*[fm_text(state, restarts=n, **node) for n in range(4)]) + assert [r.verdict for r in rs] == ["ok"] * 4 and all(r.result.reasons == [] for r in rs) + assert all("fm_boot" not in r.result.facts and r.result.facts["nvswitch"] == "no" for r in rs) + # REV-905 M1: not even after it was active in the boot (a GB tray's unit may run, then fail) + _, rs = watch_through(fm_text("active", **node), fm_text(state, **node), fm_text(state, restarts=3, **node)) + assert [r.verdict for r in rs] == ["ok"] * 3 + + +def test_whether_the_node_has_nvswitch_of_its_own(): + of = lambda **kw: (lambda f: (f["nvswitch"], f["nvswitch_by"]))(check(fm_text("active", **kw)).facts) # noqa: E731 + assert of() == ("yes", "B200/B300 GPU with an NVLink fabric") # HGX B300, not root + assert of(name="NVIDIA B200") == ("yes", "B200/B300 GPU with an NVLink fabric") + assert of(**B300_ROOT) == ("yes", "ConnectX VPD SW_MNG") + # REV-905c M: a VPD without the port does not overrule B200 / B300 GPUs with a fabric + assert of(**B300_ROOT_NO_SW) == ("yes", "B200/B300 GPU with an NVLink fabric") + assert of(**VPD_NO_SW) == ("no", "ConnectX VPD without SW_MNG") + assert of(name="NVIDIA H100 80GB HBM3", vpd=4, sw=0) == ("unread", "NVSwitch not determined") # some unread + assert of(name="NVIDIA H100 80GB HBM3", vpd=None) == ("unread", "NVSwitch not determined") # no timeout + assert of(name="NVIDIA H100 80GB HBM3", dev=1) == ("yes", "device files") # a single NVSwitch + assert of(name="NVIDIA B40") == ("unread", "NVSwitch not determined") # B-like, not B200 / B300 + assert of(**HOPPER) == ("yes", "procfs") + assert of(name="NVIDIA H100 80GB HBM3", dev=8) == ("yes", "device files") + assert of(name="NVIDIA H100 80GB HBM3", pci=4) == ("yes", "lspci") + assert of(**HIDDEN) == ("unread", "NVSwitch not determined") + assert of(**TRAY) == ("no", "compute tray (GB GPU)") + assert of(**TRAY, **B300_ROOT) == ("no", "compute tray (GB GPU)") + assert of(**PCIE) == ("no", "no NVLink fabric") and of(**PCIE_NA) == ("no", "no NVLink fabric") + assert of(sw=1, **PCIE) == ("no", "no NVLink fabric") # no fabric first: a PCIe node's ConnectX VPD + assert of(name="NVIDIA B300 PCIe") == ("unread", "NVSwitch not determined") + # the fabric unread (nvidia-smi -q timed out or failed): by the GPU names no more + assert of(fabric=(124, FABRIC_IN_PROGRESS)) == ("unread", "NVSwitch not determined") + assert of(fabric=(9, "")) == ("unread", "NVSwitch not determined") + assert of(fabric=(124, ""), **B300_ROOT) == ("yes", "ConnectX VPD SW_MNG") + assert of(fabric=(124, ""), **TRAY) == ("no", "compute tray (GB GPU)") + # mixed GPUs: all must be B200 / B300 + mixed = gpus_text().replace("NVIDIA B300 SXM6 AC", "NVIDIA H100 80GB HBM3", 1) + assert check(fm_text("active", gpus=(0, mixed))).facts["nvswitch"] == "unread" + assert node_health.nvswitch_of({}, [], True) == ("unread", "NVSwitch not determined") + # REV-905e: another NVIDIA class 0680 bridge is soft evidence (yes, not hard); an NVSwitch id is hard + h100 = dict(name="NVIDIA H100 80GB HBM3") + assert of(bridge=1, **h100) == ("yes", "lspci NVIDIA bridge (no known NVSwitch id)") + assert check(fm_text("active", bridge=1, **h100)).facts["nvswitch_hard"] is False + assert check(fm_text("active", pci=1, **h100)).facts["nvswitch_hard"] is True + assert of(bridge=1, **PCIE) == ("no", "no NVLink fabric") and of(bridge=1, **TRAY)[0] == "no" + assert of(bridge=1, vpd=10, sw=0, **h100)[0] == "yes" # before the VPD rule + assert of(bridge=0, **h100) == ("unread", "NVSwitch not determined") + + +def test_a_new_boot_forgets_the_fabric_manager_as_before(): + # active in the old boot, never in the new one: one reason when it stops (as before), then none + _, rs = watch_through(fm_text("active"), fm_text("failed", boot="boot-2"), fm_text("failed", boot="boot-2"), + fm_text("failed", boot="boot-2")) + assert [r.verdict for r in rs] == ["ok", "bad_once", "ok", "ok"] + assert "fm_boot" not in rs[1].result.facts and "fm_boot" not in rs[3].result.facts + # failed before the reboot and after it, never active since: nothing, as before + _, rs = watch_through(fm_text("active"), fm_text("failed"), fm_text("failed", boot="boot-2"), + fm_text("failed", boot="boot-2")) + assert [r.verdict for r in rs] == ["ok", "bad_once", "ok", "ok"] + # NVSwitch not determined: not even the stop across the reboot + _, rs = watch_through(fm_text("active", **HIDDEN), fm_text("failed", boot="boot-2", **HIDDEN)) + assert [r.verdict for r in rs] == ["ok", "ok"] + # active again in the new boot: that boot's memory + _, rs = watch_through(fm_text("active"), fm_text("active", boot="boot-2"), fm_text("failed", boot="boot-2"), + fm_text("failed", boot="boot-2")) + assert [r.verdict for r in rs] == ["ok", "ok", "bad_once", "lost"] + assert rs[3].result.facts["fm_boot"] == "boot-2" + + +@pytest.mark.parametrize("node", [{}, B300_ROOT, HOPPER], ids=["b300", "b300-root", "hopper"]) +@pytest.mark.parametrize("state", ["failed", "inactive", "activating", "deactivating"]) +def test_a_new_launcher_reports_a_down_fabric_manager_on_an_nvswitch_node_at_once(state, node): + _, rs = watch_through(fm_text(state, **node), fm_text(state, **node), fm_text(state, **node)) + assert [r.verdict for r in rs] == ["bad_once", "lost", "lost"] + assert all(r.result.reasons == [f"nvidia-fabricmanager {state} (NVSwitch present)"] for r in rs) + assert rs[0].result.facts["fm_boot"] == BOOT and rs[0].result.facts["fm_why"] == "nvswitch" + # it comes back: the reason goes; down again in the boot: the usual reason + back = check(fm_text("active", **node), rs[-1].result.facts) + assert back.ok_single and "fm_why" not in back.facts + assert check(fm_text("failed", **node), back.facts).reasons == ["nvidia-fabricmanager failed (was active)"] + # a new boot forgets it too + assert check(fm_text(state, boot="boot-2", **node), rs[-1].result.facts).ok_single + + +def test_a_first_read_that_cannot_judge_is_not_the_first_judged_one(): + # REV-905 M1: the first check cannot judge (the fabric timed out: NVSwitch not determined), + # the next three read: they are judged as the first read of a new launcher + unread = fm_text("failed", fabric=(124, FABRIC_IN_PROGRESS)) + _, rs = watch_through(unread, fm_text("failed"), fm_text("failed"), fm_text("failed")) + assert [r.verdict for r in rs] == ["ok", "bad_once", "lost", "lost"] + assert rs[0].result.facts["nvswitch"] == "unread" and rs[0].result.facts["fm_judged"] is False + # the fabric manager section timed out first: the same + _, rs = watch_through(fm_text(None), fm_text("failed"), fm_text("failed")) + assert [r.verdict for r in rs] == ["ok", "bad_once", "lost"] + # a whole read failure first: the same + _, rs = watch_through(node_text(gpus=(124, "")), fm_text("failed"), fm_text("failed")) + assert [r.verdict for r in rs] == ["read_failed", "bad_once", "lost"] + # an unjudged read, then a read failure (it carries "not judged yet"), then a judged one + _, rs = watch_through(fm_text("failed", **NO_PROBE), node_text(gpus=(124, "")), fm_text("failed")) + assert [r.verdict for r in rs] == ["ok", "read_failed", "bad_once"] + assert rs[1].result.facts["fm_judged"] is False + # NVSwitch never determined: never judged bad on a fabric manager never active + _, rs = watch_through(*[fm_text("failed", **NO_PROBE)] * 3) + assert [r.verdict for r in rs] == ["ok"] * 3 + # once active in the boot, the memory judges it while NVSwitch is not determined + _, rs = watch_through(fm_text("active", **NO_PROBE), fm_text("failed", **NO_PROBE), fm_text("failed", **NO_PROBE)) + assert [r.verdict for r in rs] == ["ok", "bad_once", "lost"] + + +def test_inactive_at_the_first_read_follows_nvswitch_and_the_fabric(): + _, rs = watch_through(*[fm_text("inactive")] * 2) # NVSwitch: the unit must run + assert [r.verdict for r in rs] == ["bad_once", "lost"] + _, rs = watch_through(*[fm_text("inactive", **TRAY)] * 3) # no NVSwitch, a Completed fabric: nothing + assert [r.verdict for r in rs] == ["ok"] * 3 + stuck = fm_text("inactive", fabric=(0, FABRIC_IN_PROGRESS), **TRAY) # a fabric not completed: its own reason + _, rs = watch_through(stuck, stuck) + assert [r.verdict for r in rs] == ["bad_once", "lost"] + assert all(r.result.reasons == ["NVLink fabric In Progress/N/A on 8/8 GPUs (fabric manager: inactive)"] + for r in rs) + + +def test_a_fabric_manager_that_restarts_is_bad_only_while_it_goes_on_restarting(): + # REV-905e: restarts that came back active are no reason: a node_health_fm_restarted event + # at every check of the streak (its count), never node_health_degraded + w, rs = watch_through(*[fm_text("active", restarts=n) for n in (0, 1, 2)]) + assert [r.verdict for r in rs] == ["ok"] * 3 and all(r.result.reasons == [] for r in rs) + assert all(r.degraded is None for r in rs) and "degraded" not in w.record() + assert rs[0].fm_restarted is None and rs[0].fm_restarted_fields() == {} + assert [r.fm_restarted_fields() for r in rs[1:]] == [ + {"streak": n, "nrestarts": n, "reasons": ["nvidia-fabricmanager restarted 1x since the previous check"]} + for n in (1, 2)] + assert w.record()["fm_restarted"] == rs[2].fm_restarted_fields() + assert rs[2].result.facts["fm_restart_streak"] == {"boot": BOOT, "n": 2} + assert "fm_restarted" not in w.observe(fm_text("active", restarts=2)).result.facts + assert "fm_restarted" not in w.record() # the record holds the last check's restarts only + # FM_RESTART_STREAK (3) checks in a row restarting: a reason, and lost at the next one + _, rs = watch_through(*[fm_text("active", restarts=n) for n in (0, 1, 2, 3, 4)]) + assert [r.verdict for r in rs] == ["ok", "ok", "ok", "bad_once", "lost"] + assert rs[3].result.reasons == ["nvidia-fabricmanager restarted 1x since the previous check"] + assert [r.fm_restarted["streak"] for r in rs[1:]] == [1, 2, 3, 4] # the event goes on with it + assert rs[4].result.facts["fm_restarts"] == {"boot": BOOT, "n": 4} + # a check without a restart ends the streak + _, rs = watch_through(*[fm_text("active", restarts=n) for n in (0, 1, 2, 2, 3, 4)]) + assert [r.verdict for r in rs] == ["ok"] * 6 + assert rs[3].result.facts["fm_restart_streak"]["n"] == 0 and rs[3].fm_restarted is None + assert rs[5].fm_restarted["streak"] == 2 + # down while restarting: bad by its state at once (the restart itself not counted yet) + _, rs = watch_through(fm_text("active", restarts=0), fm_text("activating", restarts=1)) + assert [r.verdict for r in rs] == ["ok", "bad_once"] + assert rs[1].result.reasons == ["nvidia-fabricmanager activating (was active)"] + # NRestarts unread: the baseline and the streak stay; a new boot: new ones + _, rs = watch_through(*[fm_text("active", restarts=n) for n in (0, 1, 2)], node_text(gpus=(124, "")), + fm_text("active", restarts=3)) + assert [r.verdict for r in rs] == ["ok", "ok", "ok", "read_failed", "bad_once"] # a read failure keeps it + assert rs[3].fm_restarted is None and rs[4].fm_restarted["streak"] == 3 + # NRestarts unread at a check: no growth there, the streak is zeroed (the baseline stays) + _, rs = watch_through(*[fm_text("active", restarts=n) for n in (0, 1, 2, None, 3, 4)]) + assert [r.verdict for r in rs] == ["ok"] * 6 + assert rs[3].result.facts["fm_restart_streak"]["n"] == 0 and rs[4].fm_restarted["streak"] == 1 + _, rs = watch_through(*[fm_text("active", restarts=n) for n in (0, 1, 2)], + fm_text("active", boot="boot-2", restarts=0), fm_text("active", boot="boot-2", restarts=1)) + assert [r.verdict for r in rs] == ["ok"] * 5 and rs[4].result.facts["fm_restart_streak"]["n"] == 1 + _, rs = watch_through(fm_text("active", restarts=1), fm_text("active", boot="boot-2", restarts=3)) + assert [r.verdict for r in rs] == ["ok", "ok"] # more than the old boot's count: still a new baseline + assert rs[1].fm_restarted is None and rs[1].result.facts["fm_restarts"] == {"boot": "boot-2", "n": 3} + # NVSwitch not determined, never active: nothing; once active, the memory counts the restarts + _, rs = watch_through(*[fm_text("activating", restarts=n, **HIDDEN) for n in range(4)]) + assert [r.verdict for r in rs] == ["ok"] * 4 and all(r.degraded is None for r in rs) + _, rs = watch_through(*[fm_text("active", restarts=n, **HIDDEN) for n in range(4)]) + assert [r.verdict for r in rs] == ["ok", "ok", "ok", "bad_once"] + + +def test_the_fabric_manager_absolute_rule_judges_one_check_alone(): + absolute = node_health.fabric_manager_absolute + assert absolute(check(fm_text("active")).facts) == ("ok", "nvidia-fabricmanager active") + assert absolute(check(fm_text("failed")).facts) == ("bad", "nvidia-fabricmanager failed (NVSwitch present)") + assert absolute(check(fm_text("inactive", **B300_ROOT)).facts)[0] == "bad" + assert absolute(check(fm_text("failed", **TRAY)).facts) == ("ok", "no NVSwitch on the node (compute tray (GB GPU))") + assert absolute(check(fm_text("failed", **PCIE)).facts) == ("ok", "no NVSwitch on the node (no NVLink fabric)") + # REV-905 H1: the HGX B300 sample (no NVSwitch device on the host) is never ok when down + b300 = check(fm_text("failed", fabric=(124, FABRIC_OK))) + assert absolute(b300.facts) == ("unread", "NVSwitch not determined") + assert absolute(check(fm_text("failed", **HIDDEN)).facts) == ("unread", "NVSwitch not determined") + assert absolute(check(fm_text(None)).facts) == ("unread", "nvidia-fabricmanager state unread") + assert absolute(check(fm_text(None, **HIDDEN)).facts) == ("unread", "FM section timed out") + # REV-905c L2: cut off after the state line (the VPD reads): not "state unread" + cut = node_text(fabricmanager=(124, "failed\nloadstate=loaded\nnrestarts=0\nnvswitch_dev=0"), + gpus=(0, gpus_text(name="NVIDIA H100 80GB HBM3"))) + assert absolute(check(cut).facts) == ("unread", "FM section timed out after reading state") + assert check(cut).facts["fm_state"] == "failed" + assert absolute(check(node_text(gpus=(124, ""))).facts)[0] == "unread" # nvidia-smi did not answer + assert absolute({})[0] == "unread" and absolute({"nvswitch": 4, "fm_state": "failed"})[0] == "unread" + # REV-905e H1: a loaded unit stopped, no NVSwitch device seen (B300 as the ssh user, another + # NVIDIA bridge), every fabric Completed: by whether it was active in this boot + for soft in ({}, dict(name="NVIDIA H100 80GB HBM3", bridge=1)): + for state in ("inactive", "failed"): + assert absolute(check(fm_text(state, entered=0, **soft)).facts) == ("ok", node_health.OFF_HOST) + assert absolute(check(fm_text(state, **soft)).facts) == ( + "bad", f"nvidia-fabricmanager {state} (NVSwitch present)") + assert absolute(check(fm_text(state, entered=None, **soft)).facts) == ( + "unread", f"nvidia-fabricmanager {state}, fabric Completed, its active time unread") + # the fabric not Completed (or unread): bad as before + assert absolute(check(fm_text(state, entered=0, fabric=(0, FABRIC_IN_PROGRESS), **soft)).facts)[0] == "bad" + assert absolute(check(fm_text("activating", entered=0, **soft)).facts)[0] == "bad" + for hard in (B300_ROOT, HOPPER, dict(name="NVIDIA H100 80GB HBM3", pci=1)): # a device of its own: bad + assert absolute(check(fm_text("inactive", entered=0, **hard)).facts)[0] == "bad" + # its own read, never carried: an unread check after a bad one is unread + bad = check(fm_text("failed")) + assert absolute(check(node_text(gpus=(124, "")), bad.facts).facts)[0] == "unread" + assert absolute(check(fm_text("failed", fabric=(124, "")), bad.facts).facts)[0] == "unread" + + +def test_the_fabric_manager_section_reads_systemctl_and_the_nvswitch_probe(tmp_path): + read = node_health.read_fabric_manager + every = dict(active_enter=ENTERED, nvswitch_dev=0, nvswitch_pci=2, nvidia_bridge=1, mlx=10, mlx_vpd=0, sw_mng=0) + assert read(host_probe.Section(3, fm_out("failed", pci=2, bridge=1, restarts=7))) == ("failed", 7, every) + assert read(host_probe.Section(0, fm_out("active", proc=4, pci=None, entered=None)))[2] == dict( + nvswitch_proc=4, nvswitch_dev=0, mlx=10, mlx_vpd=0, sw_mng=0) + assert read(host_probe.Section(3, fm_out("unknown")))[0] == "" # not a state + assert read(host_probe.Section(3, fm_out("failed", vpd=None, entered=0)))[2] == dict( + active_enter=0, nvswitch_dev=0, nvswitch_pci=0, mlx=10) + # REV-905e: hidden processes; a loaded unit that was active in this boot and failed stays failed + hid = dict(load="loaded", proc1=0) + assert read(host_probe.Section(3, fm_out("failed", **hid)))[0] == "failed" + assert "fm_hidden" not in read(host_probe.Section(3, fm_out("failed", **hid)))[2] + for state, entered in (("failed", 0), ("failed", None), ("inactive", ENTERED)): + got = read(host_probe.Section(3, fm_out(state, entered=entered, **hid))) + assert got[0] == "" and got[2]["fm_hidden"] == "hidepid", (state, entered) + assert read(host_probe.Section(3, fm_out("failed", load="masked", proc1=0)))[0] == "" + assert read(host_probe.Section(3, fm_out("activating", **hid)))[0] == "activating" + assert "fm_hidden" not in read(host_probe.Section(3, fm_out("activating", **hid)))[2] + assert "fm_hidden" not in read(host_probe.Section(124, "loadstate=not-found\nproc1=0"))[2] # no state: no note + assert read(host_probe.Section(127, "nrestarts=\nnvswitch_dev=0")) == ("", None, {"nvswitch_dev": 0}) + assert read(host_probe.Section(0, "active")) == ("active", None, {}) # an older script's output + assert read(host_probe.Section(3, "failed")) == ("", None, {}) # no LoadState: no unit known to have failed + assert read(host_probe.Section(127, "active")) == ("", None, {}) # systemctl not found: no state + assert read(None) == ("", None, {}) + # REV-905c H: the LoadState decides what inactive / failed mean + assert read(host_probe.Section(3, fm_out("inactive", load="not-found", fm_proc=0)))[0] == "not running" + assert read(host_probe.Section(3, fm_out("inactive", load="not-found", fm_proc=2)))[0] == "active" + assert read(host_probe.Section(3, fm_out("inactive", load="not-found")))[0] == "" # no process count + assert read(host_probe.Section(3, fm_out("inactive", load="masked")))[0] == "" + assert read(host_probe.Section(3, fm_out("activating", load="masked")))[0] == "activating" + assert read(host_probe.Section(124, fm_out("failed")))[2]["timed_out"] == 2 + assert read(host_probe.Section(124, ""))[2] == {"timed_out": 1} + # REV-905d L2: rc 137 (killed) is a timeout too; lines without the state line are "before" + assert read(host_probe.Section(137, fm_out("failed")))[2]["timed_out"] == 2 + assert read(host_probe.Section(124, "loadstate=loaded\nproc1=1"))[2]["timed_out"] == 1 + assert read(host_probe.Section(124, fm_out("unknown")))[2]["timed_out"] == 1 # no state: before + + def run(path, **env): # the section as the check runs it (its stderr merged), on a host of fakes + out = subprocess.run(["bash", "-c", probe_script([("fabricmanager", node_health.FM_SCRIPT)])], + capture_output=True, text=True, env={"PATH": path, **env}, check=False) + return host_probe.parse_sections(out.stdout)["fabricmanager"] + + fakes, tools, paths = _fm_host(tmp_path) + path = f"{fakes}:{tools}" + unit, entered, proc = fakes / "unit", fakes / "entered", Path(paths["__YETO_PROC"]) + sec = run(path, **paths) + # REV-905d: systemd < 230 has no --value (the fake refuses it): LoadState still reads + assert sec.text.splitlines()[:5] == ["failed", "loadstate=loaded", "active_enter=0", "container=0", + "proc1=1"] # the state first + base = dict(active_enter=0, nvswitch_dev=0, nvswitch_pci=2, nvidia_bridge=1, mlx=4, mlx_vpd=3, sw_mng=1) + assert sec.rc == 3 and read(sec) == ("failed", 5, dict(base, fm_proc=0)) + _fm_process(proc, 4242, 777) # a stale failed host unit, a driver container's fabric manager + assert read(run(path, **paths)) == ("active", 5, dict(base, fm_proc=1, fm_ids="4242:777")) + # in a container (REV-905e): by systemd-detect-virt -c's output (none: not one), else + # /run/systemd/container, /.dockerenv, /run/.containerenv, else pid 1's environ + virt = fakes / "systemd-detect-virt" + for out, rc, want in (("docker", 0, "1"), ("lxc", 0, "1"), ("none", 1, "0"), ("", 1, "0")): + virt.write_text(f'#!/bin/bash\n[ "$1" = -c ] && {{ [ -n "{out}" ] && echo {out}; exit {rc}; }}; exit 2\n') + virt.chmod(0o755) + sec = run(path, **paths) + assert f"container={want}" in sec.text, out + virt.write_text('#!/bin/bash\n[ "$1" = -c ] && { echo docker; exit 0; }; exit 2\n') + sec = run(path, **paths) + assert "proc1=0" in sec.text and read(sec)[0] == "" + assert read(sec)[2]["fm_hidden"] == "container" and "fm_proc" not in read(sec)[2] + virt.write_text('#!/bin/bash\necho none; exit 1\n') # there, says none: the fallbacks are not read + (Path(paths["__YETO_ROOT"]) / ".dockerenv").write_text("") + assert "container=0" in run(path, **paths).text + virt.unlink() + assert "container=1" in run(path, **paths).text # /.dockerenv + (Path(paths["__YETO_ROOT"]) / ".dockerenv").unlink() + (Path(paths["__YETO_RUN"]) / ".containerenv").write_text("") + assert "container=1" in run(path, **paths).text # podman + (Path(paths["__YETO_RUN"]) / ".containerenv").unlink() + (Path(paths["__YETO_RUN"]) / "systemd").mkdir() + (Path(paths["__YETO_RUN"]) / "systemd" / "container").write_text("") # empty: not one + assert "container=0" in run(path, **paths).text + (Path(paths["__YETO_RUN"]) / "systemd" / "container").write_text("lxc\n") + assert "container=1" in run(path, **paths).text + (Path(paths["__YETO_RUN"]) / "systemd" / "container").unlink() + (proc / "1" / "environ").write_bytes(b"PATH=/bin\x00container=lxc\x00") + assert "container=1" in run(path, **paths).text + (proc / "1" / "environ").write_bytes(b"PATH=/bin\x00") + assert "container=0" in run(path, **paths).text + (proc / "1" / "environ").chmod(0o000) # not readable: not a container, no error + sec = run(path, **paths) + assert "container=0" in sec.text and "environ" not in sec.text + (proc / "1" / "environ").chmod(0o600) + unit.write_text("not-found") # no unit: the process (comm cut at 15) says it runs + assert read(run(path, **paths))[0] == "active" + (proc / "4242" / "comm").write_text("bash\n") + assert read(run(path, **paths))[0] == "not running" + (proc / "1" / "comm").unlink() # the processes not seen (hidepid): nothing counted + sec = run(path, **paths) + assert "proc1=0" in sec.text and read(sec)[0] == "" and "fm_proc" not in read(sec)[2] + unit.write_text("loaded") + nvsw, dev = Path(paths["__YETO_NVSW_PROC"]), Path(paths["__YETO_DEV"]) + nvsw.mkdir() + for n in range(4): + (nvsw / f"0000:0{n}:00.0").write_text("") + (dev / f"nvidia-nvswitch{n}").write_text("") + (dev / "nvidia-nvswitchctl").write_text("") # the control device is not a switch + (fakes / "lspci").write_text("#!/bin/bash\nexit 1\n") # lspci there, failing: no count (L1) + assert read(run(path, **paths))[2] == dict(active_enter=0, nvswitch_proc=4, nvswitch_dev=4, mlx=4, mlx_vpd=3, + sw_mng=1, fm_hidden="hidepid") # /proc/1/comm still gone + entered.write_text("ActiveEnterTimestampMonotonic=41000000") # active in this boot: failed stays failed + assert read(run(path, **paths))[0] == "failed" and "fm_hidden" not in read(run(path, **paths))[2] + entered.write_text("ActiveEnterTimestampMonotonic=0") + (fakes / "timeout").unlink() # no timeout: no VPD read (it could hang the section) + assert read(run(path, **paths))[2] == dict(active_enter=0, nvswitch_proc=4, nvswitch_dev=4, mlx=4, + fm_hidden="hidepid") + (fakes / "systemctl").unlink() + (fakes / "lspci").unlink() + sec = run(path, **paths) # no systemctl, no lspci + assert sec.rc == 127 and read(sec)[:2] == ("", None) and "nvswitch_pci" not in read(sec)[2] + + +def _fm_process(proc, pid, start, comm="nv-fabricmanage"): + (proc / str(pid)).mkdir(parents=True, exist_ok=True) + (proc / str(pid) / "comm").write_text(comm + "\n") + (proc / str(pid) / "stat").write_text(f"{pid} ({comm}) S " + " ".join(["0"] * 18) + f" {start} 0 0\n") + + +def _fm_host(tmp_path, *, real_timeout=False): + """Fakes of a node for the fabricmanager section: systemctl (its LoadState in ``unit``; + it refuses --value, as systemd < 230), lspci, timeout (the real one with + ``real_timeout``), /proc, the NVSwitch procfs dir, /dev and the PCI sysfs.""" + fakes, tools = tmp_path / "bin", tmp_path / "tools" # tools: only what the section needs + fakes.mkdir() + tools.mkdir() + for tool in ("bash", "ls", "wc", "tr", "grep", "head", "printf", "sed", "awk", "sleep"): + if shutil.which(tool): + (tools / tool).symlink_to(shutil.which(tool)) + unit, entered = fakes / "unit", fakes / "entered" + unit.write_text("loaded") + entered.write_text("ActiveEnterTimestampMonotonic=0") + (fakes / "systemctl").write_text( + f'#!/bin/bash\nread -r load < {shlex.quote(str(unit))}\nread -r ae < {shlex.quote(str(entered))}\n' + 'for a in "$@"; do [ "$a" = --value ] && { echo "Unknown option --value" >&2; exit 1; }; done\n' + 'if [ "$1" = is-active ]; then if [ "$load" = loaded ]; then echo failed; else echo inactive; fi; exit 3; fi\n' + 'if [ "$1" = show ]; then case "$3" in LoadState) echo "LoadState=$load";; NRestarts) echo NRestarts=5;; ' + 'ActiveEnterTimestampMonotonic) echo "$ae";; esac; fi\n') + # two NVSwitches (GH100 ids), another NVIDIA 0680 bridge (soft), a GPU + (fakes / "lspci").write_text("#!/bin/bash\necho '05:00.0 0680: 10de:22a3 (rev a1)'\n" + "echo '06:00.0 0680: 10de:22a3 (rev a1)'\necho '07:00.0 0680: 10de:1111 (rev a1)'\n" + "echo '18:00.0 0302: 10de:2901 (rev a1)'\n") + if real_timeout: + (tools / "timeout").symlink_to(shutil.which("timeout")) + else: + (fakes / "timeout").write_text('#!/bin/bash\nshift\nexec "$@"\n') + for f in fakes.iterdir(): + f.chmod(0o755) + proc, dev, sys_pci = tmp_path / "proc", tmp_path / "dev", tmp_path / "pci" + dev.mkdir() + _fm_process(proc, 1, 1, comm="systemd") + _fm_process(proc, 4243, 5, comm="nv-fabricmanagerx") + # SW_MNG on a .1 function only (REV-905c M): every function is read + for name, vendor, vpd in (("0000:01:00.0", "0x15b3", b"PN\x00MCX75\x00"), + ("0000:01:00.1", "0x15b3", b"PN\x00MCX75\x00V3SMDL=SW_MNG\x00"), + ("0000:02:00.0", "0x15b3", b""), ("0000:03:00.0", "0x15b3", None), + ("0000:18:00.0", "0x10de", b"")): + (sys_pci / name).mkdir(parents=True) + (sys_pci / name / "vendor").write_text(vendor + "\n") + if vpd is not None: + (sys_pci / name / "vpd").write_bytes(vpd) + (tmp_path / "run").mkdir() + (tmp_path / "root").mkdir() + paths = dict(__YETO_PROC=str(proc), __YETO_NVSW_PROC=str(tmp_path / "proc-nvswitch"), __YETO_DEV=str(dev), + __YETO_SYS_PCI=str(sys_pci), __YETO_RUN=str(tmp_path / "run"), __YETO_ROOT=str(tmp_path / "root")) + return fakes, tools, paths + + +@pytest.mark.skipif(shutil.which("timeout") is None, reason="no timeout command here") +@pytest.mark.parametrize("fifos", [1, 8]) +def test_a_vpd_that_does_not_answer_does_not_hold_the_section(tmp_path, fifos): + # REV-905d L1: a VPD read is cut at 1 s, all of them at 3 s (the rest not read) + fakes, tools, paths = _fm_host(tmp_path, real_timeout=True) + for n in range(fifos): + d = Path(paths["__YETO_SYS_PCI"]) / f"0000:9{n}:00.0" + d.mkdir() + (d / "vendor").write_text("0x15b3\n") + os.mkfifo(d / "vpd") # opens, never answers + start = time.monotonic() + out = subprocess.run(["bash", "-c", probe_script([("fabricmanager", node_health.FM_SCRIPT)])], + capture_output=True, text=True, env={"PATH": f"{fakes}:{tools}", **paths}, check=False, + timeout=60) + took = time.monotonic() - start + probe = node_health.read_fabric_manager(host_probe.parse_sections(out.stdout)["fabricmanager"])[2] + assert probe["mlx"] == 4 + fifos and probe["mlx_vpd"] < probe["mlx"] + if fifos == 1: + assert took < 2.5 and probe["mlx_vpd"] == 3 # the others read + else: + assert took < fifos - 1 # unbounded, it takes one second per FIFO + + +def read_state(text, rc=3): + return node_health.read_fabric_manager(host_probe.Section(rc, text))[0] + + +def test_a_fabric_manager_without_its_unit_is_judged_by_its_process(): + # REV-905c H: no unit on the host (a GPU Operator driver container runs nv-fabricmanager; + # a shared NVSwitch VM runs it on its service VM): systemctl says inactive, nothing stopped + for node in (dict(HOPPER), {}, dict(B300_ROOT_NO_SW), dict(B300_ROOT)): + _, rs = watch_through(*[fm_text("inactive", **UNIT_IN_CONTAINER, **node)] * 3) + assert [r.verdict for r in rs] == ["ok"] * 3 and rs[0].result.facts["fm"] == "active" + # REV-905d: no unit and no process. Off-host (no NVSwitch device of its own, every + # fabric Completed: a shared NVSwitch guest, B300 seen only by its GPU names): ok + for node in ({}, dict(B300_ROOT_NO_SW), dict(HIDDEN)): + _, rs = watch_through(*[fm_text("inactive", **UNIT_GONE, **node)] * 3) + assert [r.verdict for r in rs] == ["ok"] * 3 and all(r.result.reasons == [] for r in rs) + assert node_health.fabric_manager_absolute(rs[0].result.facts) == ("ok", node_health.OFF_HOST) + assert rs[0].result.facts["fm"] == rs[0].result.facts["fm_state"] == "not running" + # an NVSwitch device on the node, its processes seen: the fabric manager is gone, at once + for node in (dict(HOPPER), dict(B300_ROOT), dict(name="NVIDIA H100 80GB HBM3", dev=1)): + _, rs = watch_through(*[fm_text("inactive", **UNIT_GONE, **node)] * 3) + assert [r.verdict for r in rs] == ["bad_once", "lost", "lost"] + assert rs[0].result.reasons == ["nv-fabricmanager not running (NVSwitch present)"] + # the processes not seen (hidepid): unread, never bad, never ok + _, rs = watch_through(*[fm_text("inactive", **HIDEPID, **HOPPER)] * 3) + assert [r.verdict for r in rs] == ["ok"] * 3 + assert node_health.fabric_manager_absolute(rs[0].result.facts) == ("unread", "nvidia-fabricmanager state unread") + assert read_state(fm_out("inactive", load="not-found", proc1=0, fm_proc=0)) == "" # a count not seen + # nvidia-smi -q failed (no fabric state): not off-host + failed_q = check(fm_text("inactive", fabric=(9, ""), **UNIT_GONE, **HIDDEN)) + assert node_health.fabric_manager_absolute(failed_q.facts)[0] == "unread" + # the fabric not completed: bad by its own reason, as before + stuck = fm_text("inactive", fabric=(0, FABRIC_IN_PROGRESS), **UNIT_GONE) + _, rs = watch_through(stuck, stuck) + assert [r.verdict for r in rs] == ["bad_once", "lost"] + assert rs[0].result.reasons == ["NVLink fabric In Progress/N/A on 8/8 GPUs (fabric manager: not running)"] + assert node_health.fabric_manager_absolute(rs[0].result.facts)[0] == "unread" + # its process seen in this boot counts as active: gone later, it must run (and reaches lost) + _, rs = watch_through(fm_text("inactive", **UNIT_IN_CONTAINER), fm_text("inactive", **UNIT_GONE), + fm_text("inactive", **UNIT_GONE)) + assert [r.verdict for r in rs] == ["ok", "bad_once", "lost"] + assert rs[1].result.reasons == ["nv-fabricmanager not running (was active)"] + # a new boot forgets it; a GB tray is never judged + _, rs = watch_through(fm_text("inactive", **UNIT_IN_CONTAINER), fm_text("inactive", boot="boot-2", **UNIT_GONE)) + assert [r.verdict for r in rs] == ["ok", "ok"] + _, rs = watch_through(fm_text("inactive", **UNIT_IN_CONTAINER, **TRAY), fm_text("inactive", **UNIT_GONE, **TRAY)) + assert [r.verdict for r in rs] == ["ok", "ok"] + # off-host is a judged read: the next one is not a first read + _, rs = watch_through(fm_text("inactive", **UNIT_GONE), fm_text("failed"), fm_text("failed")) + assert [r.verdict for r in rs] == ["ok", "ok", "ok"] + # an unjudged read (hidepid): the next judged read is still the first + _, rs = watch_through(fm_text("inactive", **HIDEPID), fm_text("failed"), fm_text("failed")) + assert [r.verdict for r in rs] == ["ok", "bad_once", "lost"] + + +# REV-905d scenarios: (LoadState, is-active, nv-fabricmanager processes) on an NVSwitch node +SCENARIOS = { + "18 masked unit, the fabric manager crashed": (dict(load="masked", fm_proc=0, **HOPPER), "inactive", "lost"), + "19 masked unit, its process runs": (dict(load="masked", fm_proc=1, **HOPPER), "inactive", "ok"), + "20 stale disabled host unit, a driver container runs it": (dict(load="loaded", fm_proc=1), "inactive", "ok"), + "20f stale failed host unit, a driver container runs it": (dict(load="loaded", fm_proc=1), "failed", "ok"), + "20b failed host unit, nothing runs it (Hopper)": (dict(load="loaded", fm_proc=0, **HOPPER), "failed", "lost"), + "21 failed host unit, nothing runs it (B300 as root)": (dict(load="loaded", fm_proc=0, **B300_ROOT), "failed", + "lost"), + # REV-905e H1: HGX B300 as the ssh user (no NVSwitch device seen, a Completed fabric): the + # unit's ActiveEnterTimestampMonotonic says whether it ran in this boot + "22 B300 non-root, loaded unit never active (off-host)": (dict(load="loaded", fm_proc=0, entered=0), "inactive", + "ok"), + "22f B300 non-root, loaded unit failed before it was active": (dict(load="loaded", fm_proc=0, entered=0), + "failed", "ok"), + "23 B300 non-root, loaded unit active before, failed": (dict(load="loaded", fm_proc=0), "failed", "lost"), + "23i B300 non-root, loaded unit active before, stopped": (dict(load="loaded", fm_proc=0), "inactive", "lost"), + "24 B300 non-root, its active time unread": (dict(load="loaded", fm_proc=0, entered=None), "failed", "unread"), + # REV-905e L1: lspci alone + "25 only lspci 10de:22a3, no unit, nothing runs it": (dict(UNIT_GONE, name="NVIDIA H100 80GB HBM3", pci=1), + "inactive", "lost"), + "26 only another 10de 0680 bridge, no unit, nothing runs it": (dict(UNIT_GONE, name="NVIDIA H100 80GB HBM3", + pci=0, bridge=1), "inactive", "ok"), + "26u only another 10de 0680 bridge, no unit, fabric not read": (dict(UNIT_GONE, name="NVIDIA H100 80GB HBM3", + pci=0, bridge=1, fabric=(124, "")), + "inactive", "unread"), +} + + +@pytest.mark.parametrize("name", sorted(SCENARIOS)) +def test_the_fabric_manager_scenarios(name): + node, state, want = SCENARIOS[name] + _, rs = watch_through(*[fm_text(state, **node)] * 3) + assert [r.verdict for r in rs] == (["bad_once", "lost", "lost"] if want == "lost" else ["ok"] * 3) + assert node_health.fabric_manager_absolute(rs[0].result.facts)[0] == {"lost": "bad"}.get(want, want) + if want == "ok" and name[:2] in ("19", "20"): + assert rs[0].result.facts["fm"] == "active" + + +def test_a_fabric_manager_without_its_unit_that_restarts_counts_its_processes(): + run = lambda ids, **kw: fm_text("inactive", **UNIT_IN_CONTAINER, fm_ids=ids, **kw) # noqa: E731 + _, rs = watch_through(run("4242:777"), run("4242:777"), run("5151:901"), run("5151:901"), run("6000:950")) + assert [r.verdict for r in rs] == ["ok"] * 5 and all(r.degraded is None for r in rs) + assert [r.fm_restarted is not None for r in rs] == [False, False, True, False, True] + assert rs[2].fm_restarted_fields() == {"streak": 1, "nrestarts": 0, "fm_ids": "5151:901", "reasons": [ + "nv-fabricmanager restarted (another process since the previous check)"]} # no unit: NRestarts stays 0 + assert rs[4].result.facts["fm_ids"] == {"boot": BOOT, "ids": "6000:950"} + # REV-905e M1: a process that comes and goes next to the one that stays is no restart + _, rs = watch_through(run("1:1"), run("1:1 9:9"), run("1:1"), run("1:1 9:9"), run("1:1")) + assert [r.verdict for r in rs] == ["ok"] * 5 and all(r.fm_restarted is None for r in rs) + assert rs[4].result.facts["fm_restart_streak"]["n"] == 0 + # every process of the previous check replaced: one restart + _, rs = watch_through(run("1:1 2:2"), run("3:3 4:4")) + assert rs[1].fm_restarted["streak"] == 1 + _, rs = watch_through(run("1:1 2:2"), run("2:2 3:3")) # one of them stays: none + assert rs[1].fm_restarted is None + # another process at every check: the same streak as NRestarts + _, rs = watch_through(*[run(f"{4242 + n}:777") for n in range(5)]) + assert [r.verdict for r in rs] == ["ok", "ok", "ok", "bad_once", "lost"] + assert rs[3].result.reasons == ["nv-fabricmanager restarted (another process since the previous check)"] + # the same pid with another start time is another process; a new boot is a new baseline + _, rs = watch_through(*[run(f"4242:{777 + n}") for n in range(4)], run("4242:1", boot="boot-2")) + assert [r.verdict for r in rs] == ["ok", "ok", "ok", "bad_once", "ok"] + # gone between two checks: bad by its state; back as the same process: ok + _, rs = watch_through(run("4242:777"), fm_text("inactive", **UNIT_GONE), run("4242:777")) + assert [r.verdict for r in rs] == ["ok", "bad_once", "ok"] + _, rs = watch_through(*[run(f"{4242 + n}:777", **TRAY) for n in range(5)]) + assert [r.verdict for r in rs] == ["ok"] * 5 # a GB tray is never judged + # the baseline and the streak are carried over a read failure; processes in another order are the same + _, rs = watch_through(run("1:7"), run("2:7"), node_text(gpus=(124, "")), run("3:7"), run("4:7")) + assert [r.verdict for r in rs] == ["ok", "ok", "read_failed", "ok", "bad_once"] + _, rs = watch_through(*[run("5151:901 4242:777"), run("4242:777 5151:901")] * 2) + assert [r.verdict for r in rs] == ["ok"] * 4 and all(r.fm_restarted is None for r in rs) + assert rs[0].result.facts["fm_ids"]["ids"] == "4242:777 5151:901" # sorted: the event's fm_ids are stable + + +def test_hidden_processes_leave_a_stopped_unit_unjudged(): + # REV-905e: hidepid on a GPU Operator host, its stale host unit inactive or failed (20 / 20f): + # the driver container's fabric manager would not show + for state, entered in (("inactive", ENTERED), ("inactive", 0), ("failed", 0), ("failed", None)): + w, rs = watch_through(*[fm_text(state, load="loaded", proc1=0, entered=entered, **HOPPER)] * 3) + assert [r.verdict for r in rs] == ["ok"] * 3, (state, entered) + assert rs[0].degraded == [node_health.FM_HIDDEN_NOTE] and rs[1].degraded is None + assert w.record()["degraded"] == [node_health.FM_HIDDEN_NOTE] # it stays in the record + assert node_health.fabric_manager_absolute(rs[0].result.facts) == ("unread", + "nvidia-fabricmanager state unread") + # REV-905e: its loaded unit was active in this boot and failed: bad, hidden or not, no note + for node in ({}, HOPPER): + _, rs = watch_through(*[fm_text("failed", load="loaded", proc1=0, **node)] * 3) + assert [r.verdict for r in rs] == ["bad_once", "lost", "lost"] + assert rs[0].result.reasons == ["nvidia-fabricmanager failed (NVSwitch present)"] and rs[0].degraded is None + # the fabric not completed: bad by its own reason + stuck = fm_text("failed", load="loaded", proc1=0, entered=0, fabric=(0, FABRIC_IN_PROGRESS)) + _, rs = watch_through(stuck, stuck) + assert [r.verdict for r in rs] == ["bad_once", "lost"] + # active stays active; once seen active, the memory judges a later visible stop + _, rs = watch_through(fm_text("active", proc1=0), fm_text("failed", load="loaded", proc1=0, entered=0), + fm_text("failed")) + assert [r.verdict for r in rs] == ["ok", "ok", "bad_once"] + # a system container (its own pid 1): the same, with its own note + _, rs = watch_through(*[fm_text("inactive", load="not-found", proc1=0, container=1, **HOPPER)] * 3) + assert [r.verdict for r in rs] == ["ok"] * 3 and rs[0].degraded == [node_health.FM_CONTAINER_NOTE] + + +def test_a_gb_tray_is_never_an_nvswitch_node_whatever_it_shows(): + # REV-905e: the GB rule comes before the devices + for probe in (dict(pci=4), dict(dev=2), dict(proc=2), dict(sw=1, vpd=10)): + _, rs = watch_through(*[fm_text("failed", **TRAY, **probe)] * 3) + assert [r.verdict for r in rs] == ["ok"] * 3 + assert rs[0].result.facts["nvswitch"] == "no" and rs[0].result.facts["nvswitch_by"] == "compute tray (GB GPU)" + + +def test_without_a_boot_id_the_fabric_manager_is_judged_as_before(): + no_boot = lambda state: node_text(fabricmanager=(0 if state == "active" else 3, fm_out(state)), # noqa: E731 + xid=(0, "source=dmesg")) + _, rs = watch_through(no_boot("active"), no_boot("failed"), no_boot("failed")) + assert [r.verdict for r in rs] == ["ok", "bad_once", "ok"] + # remembered in a boot, then the boot id stops reading: the memory stays and judges nothing + _, rs = watch_through(fm_text("active"), no_boot("failed"), no_boot("failed"), fm_text("failed")) + assert [r.verdict for r in rs] == ["ok", "bad_once", "ok", "bad_once"] + assert rs[2].result.facts["fm_boot"] == BOOT + first = check(no_boot("failed")) # a new launcher: the reason, no memory + assert first.reasons == ["nvidia-fabricmanager failed (NVSwitch present)"] and "fm_boot" not in first.facts + + +def test_an_older_prev_without_the_fabric_manager_memory_is_read(): + old = {k: v for k, v in check(fm_text("active")).facts.items() + if k not in ("fm_boot", "fm_why", "fm_judged", "fm_restarts", "fm_state", "nvswitch")} + assert old["fm"] == "active" and old["xid"]["boot"] == BOOT + a = check(fm_text("failed"), old) + b = check(fm_text("failed"), a.facts) + assert a.reasons == b.reasons == ["nvidia-fabricmanager failed (was active)"] and b.facts["fm_boot"] == BOOT + # its XID cursor names another boot: a reboot since (one reason, as before, then none) + rebooted = check(fm_text("failed", boot="boot-2"), old) + assert rebooted.reasons == ["nvidia-fabricmanager failed (was active)"] + assert check(fm_text("failed", boot="boot-2"), rebooted.facts).ok_single + # no XID cursor at all (no kernel log access): this boot + bare = {k: v for k, v in old.items() if k != "xid"} + c = check(fm_text("failed"), bare) + assert c.reasons == check(fm_text("failed"), c.facts).reasons == ["nvidia-fabricmanager failed (was active)"] + # an older prev whose fabric manager was not active: it was judged then, nothing remembered + assert check(fm_text("failed"), {**old, "fm": "failed"}).ok_single + # an older prev of a check without the fabric manager: the next read is the first judged one + assert check(fm_text("failed"), {k: v for k, v in old.items() if k != "fm"}).reasons == [ + "nvidia-fabricmanager failed (NVSwitch present)"] + + def _plain_xid(gpu: int, code: int) -> str: # a kernel log without timestamps (dmesg -t, a syslog copy) return f"NVRM: Xid (PCI:0000:{BUSES[gpu]}:00): {code}, pid=4242, name=python3, GPU has fallen off the bus." diff --git a/tests/test_node_health_wiring.py b/tests/test_node_health_wiring.py index 20ad66b9b..42df8a4a5 100644 --- a/tests/test_node_health_wiring.py +++ b/tests/test_node_health_wiring.py @@ -25,7 +25,7 @@ from test_cluster_preflight import ibstat_text # tests/ is on sys.path from test_nc_elastic import Clock as PoolClock from test_nc_elastic import Cloud, _names, _pool, _ready_member, _run -from test_node_health import HCA, node_text, xid_line, xid_text +from test_node_health import HCA, fm_text, node_text, xid_line, xid_text from test_rl_ssh_resident import NAMES, FakeCluster, _controller, b300, make_ops from test_rl_ssh_resident import _cards # noqa: F401 - autouse: no card tool, a resource ledger in tmp from test_rl_ssh_resident import Clock as IslandClock @@ -643,6 +643,26 @@ def test_a_multi_node_island_says_once_what_its_check_cannot_judge(tmp_path): "no NCCL_IB_HCA: the ports are not judged"] +def test_an_island_logs_every_check_of_a_fabric_manager_restart_streak(tmp_path): + # REV-905e: node_health_fm_restarted at each check that saw a restart (never degraded) + cluster = HealthCluster(NAMES) + clock = IslandClock() + ops = make_ops(tmp_path, cluster, clock=clock, health_every_s=60.0) + ops.add("isl", SshTrainerSpec(nodes=tuple(b300(i) for i in range(3)), run_id="run1", workdir="/opt/yeto", + run_script="echo island", env={"NCCL_IB_HCA": HCA})) + ops.start("isl") + cluster.health["b300-1"] = [fm_text("active", restarts=n) for n in (0, 1, 2, 2, 3)] + for _ in range(5): + assert _tick(ops, clock) == "RUNNING" + events = ops.take_health_events("isl") + fm = [e for e in events if e["event"] == node_health.EVENT_FM_RESTARTED] + assert [(e["node"], e["streak"], e["nrestarts"]) for e in fm] == [("b300-1", 1, 1), ("b300-1", 2, 2), + ("b300-1", 1, 3)] + assert fm[0]["reasons"] == ["nvidia-fabricmanager restarted 1x since the previous check"] + assert fm[0]["rank"] == 1 and "incarnation" in fm[0] + assert not any(e["event"] == node_health.EVENT_DEGRADED for e in events) + + def test_without_nccl_ib_hca_the_island_judges_the_ports_of_its_fabric_as_the_preflight(tmp_path): from test_cluster_preflight import ibstat_text as ib # noqa: PLC0415 @@ -749,6 +769,29 @@ def test_the_pool_logs_a_stale_check_and_what_a_node_cannot_judge_once(): assert stale["reasons"][0].startswith("health check stale: the last one ") +def test_the_pool_logs_each_check_of_a_fabric_manager_restart_streak_once(): + clock = PoolClock() + cloud = Cloud(clock) + pool = _pool(clock, cloud, accounts=(1, 4)) + m = _ready_member(pool, clock, cloud) + probe = cloud.probe + restarted = {"streak": 1, "nrestarts": 4, "reasons": ["nvidia-fabricmanager restarted 1x since the previous check"]} + health = {"verdict": "ok", "reasons": [], "at": clock.t, "every_s": 60, "fm_restarted": dict(restarted)} + cloud.probe = lambda member: replace(probe(member), health=dict(health)) if member.ticket == m.ticket \ + else probe(member) + _run(pool, clock, clock.t + 180) # the same check read at every probe: one event + health.update(at=clock.t, fm_restarted=dict(restarted, streak=2, nrestarts=5)) + _run(pool, clock, clock.t + 30) + del health["fm_restarted"] + health["at"] = clock.t + _run(pool, clock, clock.t + 30) + events = [e for e in pool.events.events if e["event"].endswith("node_health_fm_restarted")] + assert [(e["streak"], e["nrestarts"]) for e in events] == [(1, 4), (2, 5)] + assert events[0]["ticket"] == m.ticket and events[0]["reasons"] == restarted["reasons"] + assert sum(str(k).startswith("health_fm_restarted@") for k in m.alerted) == 1 + assert "node_health_degraded" not in _names(pool) + + def test_inventory_node_health_parses_at_the_top_and_per_node(): import pytest # noqa: PLC0415 diff --git a/yeto/hw/node_health.py b/yeto/hw/node_health.py index 323208fd2..4465e9cc4 100644 --- a/yeto/hw/node_health.py +++ b/yeto/hw/node_health.py @@ -15,8 +15,9 @@ * ``nvidia-smi --query-gpu``: the GPUs that answer, their memory and their volatile uncorrectable ECC count; a GPU ``nvidia-smi`` names but cannot open (``Unable to determine the device handle``) is a GPU gone; -* the NVSwitch ``Fabric`` state of ``nvidia-smi -q`` and ``systemctl is-active - nvidia-fabricmanager``; +* the NVSwitch ``Fabric`` state of ``nvidia-smi -q``, ``systemctl is-active + nvidia-fabricmanager`` with its unit's ``NRestarts``, and what shows the node's own + NVSwitch (:data:`FM_SCRIPT`, :func:`nvswitch_of`); * ``ibstat`` (``ibv_devinfo -v`` when ``ibstat`` fails): the state and rate of the IB / RoCE ports. @@ -41,7 +42,10 @@ * ``ok_single``: a single-node job: every GPU answers (as many as expected, or as the first check saw), none lost memory, no uncorrectable ECC error and no hardware XID (:data:`HARDWARE_XIDS`) since the previous check, the NVLink fabric is - ``Completed/Success`` on every GPU that has one, the fabric manager did not stop; + ``Completed/Success`` on every GPU that has one, the fabric manager is active (and did + not restart since the previous check) in a boot in which it was active, or on a node + with NVSwitch at the first read (:meth:`CudaChecker._fabric_manager`, + :func:`fabric_manager_absolute`); * ``ok_multi``: also every port the job's ``NCCL_IB_HCA`` names exists, is ``Active`` and runs at no less than its rate at the first check (or ``min_ib_gbps``). False whenever ``ok_single`` is; None when the GPUs pass but the job names HCAs and the IB @@ -123,6 +127,7 @@ EVENT_LOST = "node_health" EVENT_READ_FAILED = "node_health_read_failed" EVENT_DEGRADED = "node_health_degraded" +EVENT_FM_RESTARTED = "node_health_fm_restarted" # each check of a restart streak (:data:`FM_RESTART_STREAK`) GPU_QUERY = "index,pci.bus_id,name,memory.total,ecc.errors.uncorrected.volatile.total" _T = "__yeto_t" # the script's section wrapper: timeout -k 5 (timeout, no -k: without it) when the node has it @@ -141,11 +146,75 @@ f"journalctl -k -b -o short-monotonic --no-pager | grep -E 'NVRM: Xid' | tail -c {XID_TAIL_BYTES}; " "else echo source=none; fi; true" ) +# Restarts are a reason only when they go on: FM_RESTART_STREAK checks in a row whose fabric +# manager restarted; each such check is a node_health_fm_restarted event. Lost takes the +# streak plus one more bad check (BAD_CHECKS in a row): ~4 checks of restarts, ~4 min. On +# purpose: a fabric manager that restarts once or twice and stays up loses no node. +FM_RESTART_STREAK = 3 +FM_HIDDEN_NOTE = "processes hidden (hidepid): fabric manager not judged" +FM_CONTAINER_NOTE = "in a container: fabric manager not judged" +# The NVSwitch PCI device ids (vendor 10de, class 0680) taken as hard evidence, from pci.ids: +# 1af1 (GA100 NVSwitch, A100 HGX), 22a3 (GH100 NVSwitch, H100 / H200 HGX). Another NVIDIA 0680 +# bridge is soft evidence only. HGX B200 / B300 NVSwitches are no PCIe devices of the host: they +# sit behind a ConnectX-7 bridge (the VPD rule, :func:`nvswitch_of`). +NVSWITCH_PCI_IDS = ("1af1", "22a3") +VPD_READ_S = 1 # one VPD read (a VPD that does not answer must not hold the section) +VPD_BUDGET_S = 3 # every VPD read of a check: past it, the rest are not read +# The fabricmanager section. First, so that a section cut off later still has them: the +# fabric manager's state (the section's exit code is systemctl's), its unit's LoadState and +# ActiveEnterTimestampMonotonic (0: not active in this boot; ``systemctl show -p``, its prefix +# cut: no ``--value``, which systemd < 230 lacks); whether the processes of the node can be +# seen (``proc1``: /proc/1/comm readable; not under hidepid, nor in a container: +# systemd-detect-virt -c's output, else /run/systemd/container, /.dockerenv, /run/.containerenv +# or pid 1's container= variable) and, when the state is not active, the ``nv-fabricmanager`` +# processes (comm is cut at 15 characters) with their pid and start time (``fm_ids``): a +# fabric manager run by a GPU Operator driver container, or a stale host unit next to it. +# Then its unit's restarts, and what shows NVSwitch on the node (:func:`nvswitch_of`): the +# driver's NVSwitch devices (procfs, device files), NVIDIA PCI bridges (class 0680: the +# NVSwitch ids of NVSWITCH_PCI_IDS and the others apart; only when lspci runs), and every +# Mellanox (15b3) PCI function with how many of their VPD read (1 s each, 3 s in all; none +# without timeout) and name the NVLink switch management port (SMDL=SW_MNG: NVSwitch behind +# a ConnectX bridge, HGX B200 / B300; root only). The __YETO_* paths are for tests. +_IDS = "|".join(NVSWITCH_PCI_IDS) +FM_SCRIPT = START_TIME_FN + "\n".join(( + '__s=$(systemctl is-active nvidia-fabricmanager 2>/dev/null); __rc=$?; [ -n "$__s" ] && echo "$__s"', + '__ls=$(systemctl show -p LoadState nvidia-fabricmanager 2>/dev/null); echo "loadstate=${__ls#LoadState=}"', + '__ae=$(systemctl show -p ActiveEnterTimestampMonotonic nvidia-fabricmanager 2>/dev/null); ' + 'echo "active_enter=${__ae#ActiveEnterTimestampMonotonic=}"', + '__pr="${__YETO_PROC:-/proc}"; __rt="${__YETO_ROOT:-}"; __ct=0', + # in a container the node's processes are not ours to see (a system container's own pid 1) + 'if command -v systemd-detect-virt >/dev/null 2>&1; then __cv=$(systemd-detect-virt -c 2>/dev/null); ' + '[ -n "$__cv" ] && [ "$__cv" != none ] && __ct=1; ' + 'elif [ -s "${__YETO_RUN:-/run}/systemd/container" ] || [ -e "$__rt/.dockerenv" ] ' + '|| [ -e "${__YETO_RUN:-/run}/.containerenv" ]; then __ct=1; ' + "elif tr '\\000' '\\n' 2>/dev/null < \"$__pr/1/environ\" | grep -q '^container='; then __ct=1; fi", + '__pv=0; [ "$__ct" = 0 ] && [ -r "$__pr/1/comm" ] && __pv=1; echo "container=$__ct"; echo "proc1=$__pv"', + 'if [ "$__s" != active ] && [ "$__pv" = 1 ]; then', + ' __fp=$(grep -lsx nv-fabricmanage "$__pr"/[0-9]*/comm 2>/dev/null); __ids=', + ' for __c in $__fp; do __q=${__c%/comm}; __q=${__q##*/}; __ids="$__ids $__q:$(__yeto_st "$__q")"; done', + ' echo "fm_proc=$(printf \'%s\\n\' "$__fp" | grep -c .)"; echo "fm_ids=${__ids# }"', + 'fi', + '__nr=$(systemctl show -p NRestarts nvidia-fabricmanager 2>/dev/null); echo "nrestarts=${__nr#NRestarts=}"', + '__p="${__YETO_NVSW_PROC:-/proc/driver/nvidia-nvswitch/devices}"', + "[ -d \"$__p\" ] && echo \"nvswitch_proc=$(ls -A \"$__p\" 2>/dev/null | wc -l | tr -d ' ')\"", + "echo \"nvswitch_dev=$(ls -d \"${__YETO_DEV:-/dev}\"/nvidia-nvswitch[0-9]* 2>/dev/null | wc -l | tr -d ' ')\"", + "if command -v lspci >/dev/null 2>&1 && __l=$(lspci -n -d 10de: 2>/dev/null); then " + f"echo \"nvswitch_pci=$(printf '%s\\n' \"$__l\" | grep -cE ' 0680: 10de:({_IDS})')\"; " + f"echo \"nvidia_bridge=$(printf '%s\\n' \"$__l\" | grep ' 0680: ' | grep -cvE ' 0680: 10de:({_IDS})')\"; fi", + '__m=0; __r=0; __w=0; __t=; command -v timeout >/dev/null 2>&1 && __t=1; __v0=$SECONDS', + 'for __f in $(grep -lx 0x15b3 "${__YETO_SYS_PCI:-/sys/bus/pci/devices}"/*/vendor 2>/dev/null); do', + f' __m=$((__m + 1)); __d=${{__f%/vendor}}; [ $((SECONDS - __v0)) -lt {VPD_BUDGET_S} ] || continue', + f" if __v=$(set -o pipefail; timeout {VPD_READ_S} head -c 2048 \"$__d/vpd\" 2>/dev/null | tr -d '\\000'); then " + '__r=$((__r + 1)); case "$__v" in *SW_MNG*) __w=$((__w + 1));; esac; fi', + 'done', + 'echo "mlx=$__m"; [ -n "$__t" ] && { echo "mlx_vpd=$__r"; echo "sw_mng=$__w"; }', + 'exit $__rc', +)) _SECTIONS = ( ("xid", XID_SCRIPT), ("gpus", f"nvidia-smi --query-gpu={GPU_QUERY} --format=csv,noheader,nounits"), ("fabric", "set -o pipefail; nvidia-smi -q | grep -A3 -E '^ *Fabric *$'"), - ("fabricmanager", "systemctl is-active nvidia-fabricmanager"), + ("fabricmanager", FM_SCRIPT), ("ibstat", "ibstat"), ("ibv_devinfo", "ibstat >/dev/null 2>&1 && exit 3; ibv_devinfo -v"), # only when ibstat fails ) @@ -209,7 +278,11 @@ def bounded(script: str, limit_s: int = HEALTH_LIMIT_S, *, pid_file: str | None 'cat "$__yeto_hf" 2>/dev/null; rm -f "$__yeto_hf"\n' ) # the facts a check hands to the next one (baselines and the XID cursor); kept over a read failure -CARRIED = ("gpu_count", "bus", "mem", "ecc", "xid", "fm", "ib_rate") +CARRIED = ("gpu_count", "bus", "mem", "ecc", "xid", "fm", "fm_boot", "fm_why", "fm_judged", "fm_restarts", + "fm_ids", "fm_restart_streak", "ib_rate") +# the states of ``systemctl is-active nvidia-fabricmanager`` that are judged (anything else, +# an empty or timed-out answer, says nothing) +FM_STATES = ("active", "inactive", "failed", "activating", "deactivating") @dataclass @@ -289,6 +362,216 @@ def _port_label(port: IbPort) -> str: return port.ca if port.port == 1 else f"{port.ca}:{port.port}" +def _boot_of(sec: Any) -> str: + """The boot id the XID section printed first ('' when it did not).""" + if sec is None: + return "" + for line in sec.text.splitlines(): + if line.startswith("boot="): + return line[len("boot="):].strip() + return "" + + +def _prev_boot(prev: Mapping[str, Any]) -> str: + """The boot id of the previous check's XID cursor ('' when it has none).""" + cursor = prev.get("xid") + return str(cursor.get("boot") or "") if isinstance(cursor, Mapping) else "" + + +def read_fabric_manager(sec: Any) -> tuple[str, int | None, dict[str, Any]]: + """``(state, NRestarts, probe)`` of the ``fabricmanager`` section (:data:`FM_SCRIPT`). + + The state, its process first: a state that is not ``active`` while an + ``nv-fabricmanager`` process runs reads ``active`` (a GPU Operator driver container runs + it, maybe next to a stale host unit that is disabled, inactive or failed). Else a unit + that is ``not-found`` reads :data:`FM_ABSENT` (no unit, no process); ``inactive`` / + ``failed`` of a unit that is not ``loaded`` (``masked``, unknown) reads :data:`FM_ABSENT` + too when no process runs; of a ``loaded`` unit it stays (it stopped). The processes not + seen (``proc1`` 0: hidepid, or a container): ``inactive`` / ``failed`` and no unit read + '' (a driver container's fabric manager would not show; ``fm_hidden`` says why), but + ``failed`` of a ``loaded`` unit that was active in this boot + (``ActiveEnterTimestampMonotonic`` > 0) stays: it ran here and failed. '' too when the + state did not read (systemctl missing, no state printed). + + NRestarts is None when it did not read; ``probe`` holds the counts the section printed + (``nvswitch_proc``, ``nvswitch_dev``, ``nvswitch_pci``, ``nvidia_bridge``, ``mlx``, + ``mlx_vpd``, ``sw_mng``, ``active_enter`` (0: the unit was not active in this boot), + ``fm_proc``; a count it did not print is missing: not read), ``fm_ids`` (the + ``pid:starttime`` of each ``nv-fabricmanager`` process, when there is one), and + ``timed_out`` when the section was cut off by its timeout (2: after systemctl's state, + 1: before).""" + if sec is None: + return "", None, {} + kv: dict[str, str] = {} + state = "" + for line in sec.text.splitlines(): + line = line.strip() + if "=" in line: + key, _, value = line.partition("=") + kv.setdefault(key.strip(), value.strip()) + elif line and not state: + state = line.split()[0] + if sec.rc == 127 or state not in FM_STATES: + state = "" + printed = bool(state) # systemctl's state line came (the probe after it may not have) + load = kv.get("loadstate") + hidden = kv.get("proc1") == "0" + procs = None if hidden else _num(kv.get("fm_proc", "")) + entered = _num(kv.get("active_enter", "")) + if state != "active" and procs: # its process runs: the fabric manager is up + state = "active" + elif load == "not-found": + state = "" if procs is None else FM_ABSENT + elif hidden and state == "failed" and load == "loaded" and entered: + pass # the host unit ran in this boot and failed: down, whatever the processes not seen + elif hidden and state in ("inactive", "failed"): # a driver container's fabric manager would not show + state = "" + elif load != "loaded" and state in ("inactive", "failed"): # no loaded unit to have stopped + state = FM_ABSENT if procs == 0 else "" + probe: dict[str, Any] = {k: n for k in PROBE_KEYS if (n := _num(kv.get(k, ""))) is not None} + if hidden and not state and printed: + probe["fm_hidden"] = "container" if kv.get("container") == "1" else "hidepid" + if procs is not None: + probe["fm_proc"] = procs + if procs and kv.get("fm_ids"): + probe["fm_ids"] = " ".join(sorted(kv["fm_ids"].split())) + if sec.rc in (124, 137): + probe["timed_out"] = 2 if printed else 1 + return state, _num(kv.get("nrestarts", "")), probe + + +FM_ABSENT = "not running" # no unit and no nv-fabricmanager process + + +PROBE_KEYS = ("nvswitch_proc", "nvswitch_dev", "nvswitch_pci", "nvidia_bridge", "mlx", "mlx_vpd", "sw_mng", + "active_enter") +NVSWITCH_YES, NVSWITCH_NO, NVSWITCH_UNREAD = "yes", "no", "unread" +_B_SXM = re.compile(r"^B\d{3}\b") # B200 / B300 (HGX: SXM only) + + +def nvswitch_of(probe: Mapping[str, int], gpu_names: Sequence[str], fabric: bool | None) -> tuple[str, str]: + """Whether the node has NVSwitch of its own: ``(yes | no | unread, basis)``. + + ``probe``: :func:`read_fabric_manager`'s counts; ``gpu_names``: nvidia-smi's names of + the GPUs; ``fabric``: the GPUs have a real NVLink fabric state (``nvidia-smi -q``: not + ``N/A``), False when none has, None when it did not read. In order: + + * no: a GPU named ``GB...`` (an NVL72-class compute tray: its NVSwitches are in the + switch trays), whatever else it shows; + * yes: the NVIDIA driver shows NVSwitch devices (``/proc/driver/nvidia-nvswitch/devices``, + ``/dev/nvidia-nvswitch``) or lspci an NVSwitch (class 0680, an id of + :data:`NVSWITCH_PCI_IDS`): A100 / Hopper HGX; + * no: no real fabric state (PCIe); + * yes: a Mellanox function whose VPD names the NVLink switch management port + (``SW_MNG``): HGX B200 / B300, whose NVSwitches sit behind a ConnectX bridge, not on + the host's PCIe (no procfs entry, no device file, no class 0680); the VPD reads as + root only; + * yes: every GPU a B200 / B300 (not GB, not PCIe) with a real fabric state (the rule + without root; a VPD without the port does not overrule it); + * yes: lspci shows another NVIDIA class 0680 bridge (``nvidia_bridge``: soft, like the + GPU names: :func:`nvswitch_hard` does not count it); + * no: the VPD of every Mellanox function read, none names it; + * unread: anything else (the fabric unread, another GPU with a fabric and no NVSwitch + device shown): never taken for no.""" + names = [re.sub(r"^NVIDIA\s+", "", str(n).strip()).upper() for n in gpu_names if str(n).strip()] + if any(n.startswith("GB") for n in names): # first: a compute tray holds no NVSwitch, whatever it shows + return NVSWITCH_NO, "compute tray (GB GPU)" + for key, basis in (("nvswitch_proc", "procfs"), ("nvswitch_dev", "device files"), ("nvswitch_pci", "lspci")): + if probe.get(key, 0) > 0: + return NVSWITCH_YES, basis + if fabric is False: + return NVSWITCH_NO, "no NVLink fabric" + if probe.get("sw_mng", 0) > 0: + return NVSWITCH_YES, "ConnectX VPD SW_MNG" + if fabric and names and all(_B_SXM.match(n) and "PCIE" not in n for n in names): + return NVSWITCH_YES, "B200/B300 GPU with an NVLink fabric" + if probe.get("nvidia_bridge", 0) > 0: + return NVSWITCH_YES, "lspci NVIDIA bridge (no known NVSwitch id)" + mlx, vpd = probe.get("mlx"), probe.get("mlx_vpd") + if mlx and vpd == mlx and probe.get("sw_mng") == 0: + return NVSWITCH_NO, "ConnectX VPD without SW_MNG" + if probe.get("timed_out"): + return NVSWITCH_UNREAD, ("FM section timed out after reading state" if probe["timed_out"] == 2 + else "FM section timed out") + return NVSWITCH_UNREAD, "NVSwitch not determined" + + +FM_OK, FM_BAD, FM_UNREAD = "ok", "bad", "unread" + + +def nvswitch_hard(probe: Mapping[str, Any]) -> bool: + """The node shows NVSwitch of its own: a device (procfs, device file), an NVSwitch PCI id + (:data:`NVSWITCH_PCI_IDS`), or a VPD naming the switch management port. The GPU names + and another NVIDIA bridge (``nvidia_bridge``) alone are no such evidence.""" + return any(int(probe.get(k) or 0) > 0 for k in ("nvswitch_proc", "nvswitch_dev", "nvswitch_pci", "sw_mng")) + + +OFF_HOST = "fabric managed off-host (no local NVSwitch device, fabric Completed)" + + +def fabric_manager_absolute(facts: Mapping[str, Any]) -> tuple[str, str]: + """The fabric manager judged from one check alone (no earlier check): ``(verdict, + detail)``, the verdict :data:`FM_OK`, :data:`FM_BAD` or :data:`FM_UNREAD`. + + ``facts``: a check's facts (:meth:`CudaChecker.parse`; its own read, never carried: + ``nvswitch`` / ``nvswitch_by`` (:func:`nvswitch_of`), ``nvswitch_hard`` + (:func:`nvswitch_hard`), ``fabric_complete``, ``fm_state`` and ``fm_active_enter``). In order: + + * a node known to have no NVSwitch of its own (PCIe, a GB compute tray, ConnectX VPD + without the switch port): ok, whatever its state; + * no loaded unit and no ``nv-fabricmanager`` process (:data:`FM_ABSENT`): bad when the + node shows NVSwitch of its own (the processes are seen: the fabric manager is gone); + else ok when every GPU's fabric is ``Completed/Success`` (:data:`OFF_HOST`: a shared + NVSwitch guest VM, whose fabric manager runs on the service VM); else unread (the + fabric state judges the node); + * NVSwitch not determined, or the state not read (a check whose ``nvidia-smi`` did not + answer has neither): unread; + * a loaded unit ``inactive`` / ``failed`` (no process) on a node whose NVSwitch is soft + evidence only (not :func:`nvswitch_hard`: the GPU names, another NVIDIA bridge) with + every fabric ``Completed/Success``: by ``fm_active_enter`` (its + ``ActiveEnterTimestampMonotonic``): 0, never active in this boot, ok (:data:`OFF_HOST`: + the guest VM of a shared NVSwitch fabric, whose image ships the unit); > 0, it ran + here and stopped: bad; unread: unread; + * a node with NVSwitch: ``active`` ok, any other state bad (``detail``: the reason). + + Unread is never ok nor bad.""" + nvswitch, state = facts.get("nvswitch"), facts.get("fm_state") + if nvswitch == NVSWITCH_NO: + return FM_OK, f"no NVSwitch on the node ({facts.get('nvswitch_by') or '?'})" + if state == FM_ABSENT: + if facts.get("nvswitch_hard") is True: + return FM_BAD, f"nv-fabricmanager {FM_ABSENT} (NVSwitch present)" + if facts.get("fabric_complete") is True: + return FM_OK, OFF_HOST + return FM_UNREAD, f"nv-fabricmanager {FM_ABSENT}, the NVLink fabric not Completed" + if nvswitch != NVSWITCH_YES: + return FM_UNREAD, str(facts.get("nvswitch_by") or "NVSwitch not determined") + if state not in FM_STATES: + return FM_UNREAD, "nvidia-fabricmanager state unread" + if state == "active": + return FM_OK, "nvidia-fabricmanager active" + if state in ("inactive", "failed") and facts.get("nvswitch_hard") is not True \ + and facts.get("fabric_complete") is True: + entered = facts.get("fm_active_enter") + if entered is None: + return FM_UNREAD, f"nvidia-fabricmanager {state}, fabric Completed, its active time unread" + if not entered: + return FM_OK, OFF_HOST + return FM_BAD, f"nvidia-fabricmanager {state} (NVSwitch present)" + + +def _gpu_names(sec: Any) -> list[str]: + """nvidia-smi's GPU names (the gpus section's third column).""" + if sec is None or sec.rc in (124, 137, 127): + return [] + out = [] + for line in sec.text.splitlines(): + parts = [p.strip() for p in line.split(",")] + if len(parts) >= 5 and parts[0].isdigit(): + out.append(parts[2]) + return out + + def _read_error(sec: Any) -> str: if sec is None: return "nvidia-smi: no output (the check did not run)" @@ -438,22 +721,138 @@ def _gpu_rows(sec: Any) -> tuple[list[tuple[str, str | None, int | None, int | N @staticmethod def _fabric(sections: Mapping[str, Any], prev: Mapping[str, Any], facts: dict[str, Any]) -> list[str]: - out = [] - fm_sec = sections.get("fabricmanager") - fm = (fm_sec.text.strip().split() or [""])[0] if fm_sec is not None and fm_sec.rc != 127 else "" - if fm in ("active", "inactive", "failed", "activating", "deactivating"): - facts["fm"] = fm - if prev.get("fm") == "active" and fm in ("inactive", "failed"): - out.append(f"nvidia-fabricmanager {fm} (was active)") + fm, restarts, probe = read_fabric_manager(sections.get("fabricmanager")) sec = sections.get("fabric") - if sec is None or sec.rc in (124, 137): - return out - real = [(s, st) for s, st in parse_fabric(sec.text) if s.upper() != "N/A"] - bad = [(s, st) for s, st in real if s.lower() != "completed" or (st and st.lower() != "success")] - facts["fabric"] = f"{len(real) - len(bad)}/{len(real)} completed" if real else "none" - if bad: - state = "/".join(x for x in bad[0] if x) - out.append(f"NVLink fabric {state} on {len(bad)}/{len(real)} GPUs (fabric manager: {fm or '?'})") + out: list[str] = [] + real_fabric: bool | None = None # a real NVLink fabric state (None: unread) + facts["fabric_complete"] = False # every GPU's fabric Completed/Success + if sec is not None and sec.rc not in (124, 137): + real = [(s, st) for s, st in parse_fabric(sec.text) if s.upper() != "N/A"] + bad = [(s, st) for s, st in real if s.lower() != "completed" or (st and st.lower() != "success")] + facts["fabric"] = f"{len(real) - len(bad)}/{len(real)} completed" if real else "none" + if bad: + state = "/".join(x for x in bad[0] if x) + out.append(f"NVLink fabric {state} on {len(bad)}/{len(real)} GPUs (fabric manager: {fm or '?'})") + if real or sec.rc in (0, 1): # 1: no Fabric block (grep); another exit: nvidia-smi -q failed + real_fabric = bool(real) + facts["fabric_complete"] = bool(real) and not bad + nvswitch, basis = nvswitch_of(probe, _gpu_names(sections.get("gpus")), real_fabric) + facts["nvswitch"], facts["nvswitch_by"] = nvswitch, basis + facts["nvswitch_hard"] = nvswitch_hard(probe) + if "active_enter" in probe: + facts["fm_active_enter"] = probe["active_enter"] + if probe.get("fm_hidden"): + facts["fm_notes"] = [FM_CONTAINER_NOTE if probe["fm_hidden"] == "container" else FM_HIDDEN_NOTE] + return CudaChecker._fabric_manager(fm, restarts, nvswitch, _boot_of(sections.get("xid")), prev, facts, + ids=probe.get("fm_ids")) + out + + @staticmethod + def _fabric_manager(fm: str, restarts: int | None, nvswitch: str, boot: str, + prev: Mapping[str, Any], facts: dict[str, Any], *, ids: str | None = None) -> list[str]: + """The fabric manager's reasons over the checks of a watch. + + ``fm`` is this read's state ('' unread), ``restarts`` its unit's ``NRestarts`` (None + unread), ``nvswitch`` whether the node has NVSwitch of its own (:func:`nvswitch_of`: + yes, no, unread). A node with none (``no``: PCIe, a GB compute tray) is never judged + on its fabric manager. ``fm_boot`` (carried) is the boot in which the fabric manager + must be active: it was active in it (an active fabric manager means there is a + fabric to manage: it judges a node whose NVSwitch was not determined), or (``fm_why`` + ``nvswitch``) the first judged read of the watch found it down on a node with + NVSwitch (:func:`fabric_manager_absolute`). In that boot anything but ``active`` is a + reason at every check, so a fabric manager that stays down reaches ``lost``. A new + boot forgets it: a fabric manager not active since the reboot is judged as before + (one reason when it was active before the reboot, on a node with NVSwitch; then the + fabric state judges the node). + + The first judged read (``fm_judged`` not yet true: a new launcher) is the one where + the state read and NVSwitch was determined; a read where either did not leaves the + next read first. An older ``prev`` without ``fm_boot`` whose fabric manager was + active: the boot of its XID cursor (else this one); without ``fm_judged``: judged + when it has ``fm``. + + The state is the process's first (:func:`read_fabric_manager`): an + ``nv-fabricmanager`` process reads ``active`` (and is remembered so); none and no + loaded unit reads :data:`FM_ABSENT`, a reason in a boot in which it must run, and at + the first judged read when :func:`fabric_manager_absolute` says bad. + + On a node that must run it (``fm_boot`` this boot, or NVSwitch), ``NRestarts`` that + grew since the previous check of the same boot is a restart: a unit that restarts + between two checks (systemd's own ``Restart=``) reads ``active`` at both. Without a + unit, a restart is every process of the previous check gone (``fm_ids``: none of its + ``pid:starttime`` left; one more process that comes and goes is none). Each check + with a restart is in ``fm_restarted`` (the :data:`EVENT_FM_RESTARTED` event) and + grows ``fm_restart_streak``; a check without one zeroes it (a read failure keeps it: + :data:`CARRIED`). The restarts are reasons from the :data:`FM_RESTART_STREAK`-th check + of a streak on, so ``lost`` takes ~4 checks of restarts in a row (on purpose).""" + if "fm_boot" in prev: + need, why = prev.get("fm_boot") or None, prev.get("fm_why") or None + elif prev.get("fm") == "active": + need, why = _prev_boot(prev) or boot or None, None + else: + need = why = None + if need and boot and need != boot: # a new boot: forgotten + need = why = None + was_judged = bool(prev.get("fm_judged", "fm" in prev)) + facts["fm_state"] = fm if fm in FM_STATES or fm == FM_ABSENT else "" + absolute, detail = fabric_manager_absolute(facts) + judged = absolute != FM_UNREAD + if fm == "active" and boot: + need, why = boot, None + elif not was_judged and absolute == FM_BAD and boot and not need: + need, why = boot, "nvswitch" + facts["fm_judged"] = was_judged or judged + for key, value in (("fm_boot", need), ("fm_why", why)): + if value: + facts[key] = value + else: + facts.pop(key, None) + if fm in FM_STATES or fm == FM_ABSENT: + facts["fm"] = fm + if nvswitch == NVSWITCH_NO: # no NVSwitch of its own: nothing to manage here + if restarts is not None and boot: + facts["fm_restarts"] = {"boot": boot, "n": restarts} + if ids and boot: + facts["fm_ids"] = {"boot": boot, "ids": ids} + return [] + must = bool(need) and need == boot # it must be active in this boot + out = [] + if fm == FM_ABSENT and must: # no unit: its process ran in this boot and is gone + out.append(f"nv-fabricmanager {fm} ({'NVSwitch present' if why == 'nvswitch' else 'was active'})") + if fm in FM_STATES and fm != "active": + if must: + out.append(f"nvidia-fabricmanager {fm} ({'NVSwitch present' if why == 'nvswitch' else 'was active'})") + elif not was_judged and absolute == FM_BAD: # the first judged read, the boot unknown + out.append(detail) + elif prev.get("fm") == "active" and fm in ("inactive", "failed") and nvswitch == NVSWITCH_YES: + out.append(f"nvidia-fabricmanager {fm} (was active)") # it stopped across a reboot (or boot unknown) + restarted: list[str] = [] + base = prev.get("fm_restarts") + if restarts is not None and boot: + before = base.get("n") if isinstance(base, Mapping) and base.get("boot") == boot else None + if (must or nvswitch == NVSWITCH_YES) and before is not None and restarts > int(before): + restarted.append(f"nvidia-fabricmanager restarted {restarts - int(before)}x since the previous check") + facts["fm_restarts"] = {"boot": boot, "n": restarts} + # a fabric manager without its unit (no NRestarts): its process changed in the boot + base = prev.get("fm_ids") + if ids and boot: + before = base.get("ids") if isinstance(base, Mapping) and base.get("boot") == boot else None + # every process of the previous check gone (another one that came and went is none) + if (must or nvswitch == NVSWITCH_YES) and before and not set(str(before).split()) & set(ids.split()): + restarted.append("nv-fabricmanager restarted (another process since the previous check)") + facts["fm_ids"] = {"boot": boot, "ids": ids} + # restarts are a reason only when they go on (FM_RESTART_STREAK checks in a row); each + # check of the streak is a node_health_fm_restarted event (``fm_restarted``). One that + # did not come back is down by its state. + # (a new boot's first check counts no restart: the baselines are per boot, so it zeroes it) + base = prev.get("fm_restart_streak") + streak = int(base.get("n") or 0) if isinstance(base, Mapping) else 0 + if boot: + streak = streak + 1 if restarted else 0 + facts["fm_restart_streak"] = {"boot": boot, "n": streak} + if restarted: + facts["fm_restarted"] = {"streak": streak, "nrestarts": restarts, "fm_ids": ids, "reasons": restarted} + if streak >= FM_RESTART_STREAK: + out += restarted return out @staticmethod @@ -614,13 +1013,21 @@ def update(self, result: HealthResult) -> str: @dataclass class Reading: """One check through a :class:`HealthWatch`: the verdict, the result, the event it asks - for (``node_health`` / ``node_health_read_failed``; None: no event) and, once per node, - what the check cannot judge (``degraded``: the ``node_health_degraded`` event; None: nothing new).""" + for (``node_health`` / ``node_health_read_failed``; None: no event), once per node, + what the check cannot judge (``degraded``: the ``node_health_degraded`` event; None: + nothing new), and the fabric manager's restarts this check saw (``fm_restarted``: the + ``node_health_fm_restarted`` event, every check of a restart streak).""" verdict: str result: HealthResult event: str | None = None degraded: list[str] | None = None + fm_restarted: dict[str, Any] | None = None # the node_health_fm_restarted event's fields + + def fm_restarted_fields(self) -> dict[str, Any]: + """The :data:`EVENT_FM_RESTARTED` event's fields (``streak``, ``reasons``, and + ``nrestarts`` / ``fm_ids`` when read); {} when the check saw no restart.""" + return {k: v for k, v in (self.fm_restarted or {}).items() if v is not None} @property def lost(self) -> bool: @@ -667,6 +1074,7 @@ def __init__(self, family: str, *, hcas: Sequence[str] = (), multi: bool = False self.last: Reading | None = None self.at: float | None = None self.degraded: list[str] | None = None # set once (the node_health_degraded event) + self.fm_noted: set[str] = set() # the fabric manager notes said (each once) self.read_failed_in_row = 0 self.kept: dict[str, Any] | None = None # the record before a reset, until the next check @@ -700,12 +1108,19 @@ def observe(self, text: str) -> Reading: found = degraded_of(result, multi=self.multi, hcas=self.hcas, fabric=self.fabric) if found: self.degraded = degraded = found + notes = [x for x in (result.facts.get("fm_notes") or []) if x not in self.fm_noted] + if notes: # what the fabric manager check could not count, once per node each + self.fm_noted.update(notes) + self.degraded = [*(self.degraded or []), *notes] + degraded = [*(degraded or []), *notes] self.read_failed_in_row = self.read_failed_in_row + 1 if verdict == "read_failed" else 0 if self.read_failed_in_row == READ_FAILED_DEGRADE: # once per streak: it says so, it loses nothing why = "; ".join(result.job_reasons(self.multi)) or "unread" degraded = (degraded or []) + [f"read failed {READ_FAILED_DEGRADE} checks in a row: {why}"] self.prev = dict(result.facts) - self.last, self.kept = Reading(verdict, result, event, degraded), None + restarted = result.facts.get("fm_restarted") if result.checked else None + self.last, self.kept = Reading(verdict, result, event, degraded, + dict(restarted) if isinstance(restarted, Mapping) else None), None self.at = float(self.clock()) return self.last @@ -725,6 +1140,8 @@ def record(self) -> dict[str, Any] | None: doc["degraded"] = list(self.degraded) if self.read_failed_in_row: doc["read_failed_in_row"] = self.read_failed_in_row + if self.last.fm_restarted: # this check's fabric manager restarts (a pool reads its event here) + doc["fm_restarted"] = self.last.fm_restarted_fields() facts = {k: r.facts[k] for k in ("gpus", "gpu_count", "fabric", "fm", "ports", "xid_source", "xid_other") if k in r.facts} if "ports" in facts: diff --git a/yeto/launch/pool/island_pool.py b/yeto/launch/pool/island_pool.py index 1280c3b1d..fd0577f18 100644 --- a/yeto/launch/pool/island_pool.py +++ b/yeto/launch/pool/island_pool.py @@ -2608,8 +2608,10 @@ def _health_seen(self, m: Member, probe: el.Probe, now: float) -> None: """A node health check that could not read (``yeto.hw.node_health``; a check older than three periods is one): one ``node_health_read_failed`` event until a check reads again. What the check cannot judge on the node (``degraded``): one - ``node_health_degraded`` event. A check that reads ``lost`` makes the verdict - ``LOST`` (:func:`yeto.launch.pool.status.classify`).""" + ``node_health_degraded`` event. A check whose fabric manager restarted + (``fm_restarted``): one ``node_health_fm_restarted`` event per check (by its ``at``; + a check between two probes is seen in the next one's streak). A check that reads + ``lost`` makes the verdict ``LOST`` (:func:`yeto.launch.pool.status.classify`).""" from ...hw import node_health # noqa: PLC0415 health = node_health.fresh(getattr(probe, "health", None), now) @@ -2617,6 +2619,12 @@ def _health_seen(self, m: Member, probe: el.Probe, now: float) -> None: return if health.get("degraded"): self._once(m, "health_degraded", node_health.EVENT_DEGRADED, reasons=list(health["degraded"])[:5]) + restarted = health.get("fm_restarted") + if isinstance(restarted, Mapping) and not health.get("stale"): + key = f"health_fm_restarted@{health.get('at')}" + if key not in m.alerted: + m.alerted[:] = [k for k in m.alerted if not str(k).startswith("health_fm_restarted@")] + self._once(m, key, node_health.EVENT_FM_RESTARTED, **dict(restarted)) if health.get("verdict") == "read_failed": self._once(m, "health_read", "node_health_read_failed", reasons=list(health.get("reasons") or [])[:5]) elif "health_read" in m.alerted: diff --git a/yeto/launch/ssh_resident.py b/yeto/launch/ssh_resident.py index ad9696a3b..f305d6248 100644 --- a/yeto/launch/ssh_resident.py +++ b/yeto/launch/ssh_resident.py @@ -703,13 +703,19 @@ def _node_event(self, rec: _Island, rank: int, state: NodeState | None, *, strea # -- node health ------------------------------------------------------------------ def _health_reading(self, rec: _Island, rank: int, reading: Any) -> None: """One node's health check: its event (``node_health`` when it turns lost, - ``node_health_read_failed`` when reads start failing), and a lost node's handling.""" + ``node_health_read_failed`` when reads start failing, ``node_health_fm_restarted`` at + each check of a fabric manager restart streak), and a lost node's handling.""" node = rec.spec.nodes[rank].name base = {"node": node, "rank": rank, "incarnation": rec.incarnation} if reading.degraded: # once per node: what its check cannot judge rec.health_events.append({"event": node_health.EVENT_DEGRADED, **base, "reasons": list(reading.degraded)}) self.log(f"[launcher] {rec.name}: {node_health.EVENT_DEGRADED}: rank {rank} ({node}): " f"{'; '.join(reading.degraded)}") + if reading.fm_restarted: # every check of a fabric manager restart streak + fields = reading.fm_restarted_fields() + rec.health_events.append({"event": node_health.EVENT_FM_RESTARTED, **base, **fields}) + self.log(f"[launcher] {rec.name}: {node_health.EVENT_FM_RESTARTED}: rank {rank} ({node}) " + f"streak {fields.get('streak')}: {'; '.join(fields.get('reasons') or [])}") if reading.event is not None: rec.health_events.append({"event": reading.event, **base, **node_health.event_fields(reading)}) self.log(f"[launcher] {rec.name}: {reading.event}: rank {rank} ({node}) {reading.verdict}: " diff --git a/yeto/node/runtime.py b/yeto/node/runtime.py index 866a5f204..c3afd3c65 100644 --- a/yeto/node/runtime.py +++ b/yeto/node/runtime.py @@ -264,6 +264,10 @@ def check_health(self, path: str) -> node_health.Reading: self.log(f"{self.assignment.ticket}: health record not written: {error}") if reading.degraded: self.log(f"{self.assignment.ticket}: {node_health.EVENT_DEGRADED}: {'; '.join(reading.degraded)}") + if reading.fm_restarted: + fields = reading.fm_restarted_fields() + self.log(f"{self.assignment.ticket}: {node_health.EVENT_FM_RESTARTED}: streak {fields.get('streak')}: " + f"{'; '.join(fields.get('reasons') or [])}") if reading.event is not None: self.log(f"{self.assignment.ticket}: {reading.event}: {reading.verdict} " f"{'; '.join(reading.result.reasons) or '-'}")