From 9438f001d4b2bc3fe2b36f368c25d4b1cc212fdf Mon Sep 17 00:00:00 2001 From: Cody Cessna <87842395+FujitsuPolycom@users.noreply.github.com> Date: Mon, 9 Nov 2026 18:45:47 -0600 Subject: [PATCH 1/2] Fix review findings that need no hardware: deadlines, parsing, fabric-tool Plugin - Wait for a late peer as NCCL does: NET_SIRCL_REQUEST_TIMEOUT_MS now bounds only this host's transport progress; NET_SIRCL_PEER_WAIT_TIMEOUT_MS adds an optional bound on the peer application. A failed comm shuts its socket down so the peer fails promptly. - Bind the listener to the advertised address and drop connections that never send valid metadata instead of failing the accept. - Validate every numeric setting and NET_SIRCL_OOB_ADDR; warn when falling back to loopback; log a connect toward a position without a route. - Release the one-plugin-per-host claim in forked children; keep payload writes of an explicit direct window below the send queue depth. Topology - Make the C parser strict (required cabling, exact word counts, name and host limits, every host cabled, one connected fabric) and share the grammar with fabric-tool; a two-host ring is one cable in both. - Follow the cables for equally short lanes at the higher position, so both ends of a lane stay on one path under explicit cabling. - Add a conformance corpus both parsers must read alike. fabric-tool - Count only root's processes as markers; treat a failed read or missing tool as a blocking problem; derive the record's layout name from content. - Plan explicit cabling by tracing the real cables; keep unplanned markers in boot mode; start the reconcile timer after a failed install-boot apply; make remove-boot idempotent; keep qdisc ownership across a failed apply. Build and release - Prefer the bundled transport-core; fail the release scanner on an empty tree and scan files containing NUL bytes; regenerate SOURCE.json. - Document the changes in docs/configuration.md, docs/testing.md and RELEASE_NOTES-unreleased.md. CPU-tested only (transport-core, plugin, root and fabric-tool suites pass under Linux); not run on DGX Sparks, so the 0.1.2 hardware qualification does not cover this tree. Co-Authored-By: Claude Fable 5.2 --- RELEASE_NOTES-unreleased.md | 89 ++++ SOURCE.json | 16 +- docs/configuration.md | 108 ++-- docs/fabric.md | 23 +- docs/testing.md | 18 +- fabric-tool/DESIGN.md | 30 +- fabric-tool/HARDWARE-TEST-PLAN.md | 4 +- fabric-tool/README.md | 33 +- fabric-tool/fabric_tool/boot.py | 12 +- fabric-tool/fabric_tool/cli.py | 31 +- fabric-tool/fabric_tool/commands.py | 58 ++- fabric-tool/fabric_tool/diff.py | 119 ++++- fabric-tool/fabric_tool/ops.py | 24 +- fabric-tool/fabric_tool/plan.py | 30 +- fabric-tool/fabric_tool/report.py | 2 + fabric-tool/fabric_tool/state.py | 79 ++- fabric-tool/fabric_tool/topology.py | 59 ++- fabric-tool/tests/test_review_fixes.py | 656 +++++++++++++++++++++++++ fabric-tool/tests/test_topology.py | 48 +- net-sircl/Makefile | 4 +- net-sircl/net_sircl.c | 142 ++++-- net-sircl/net_sircl.h | 41 +- net-sircl/net_sircl_config.h | 30 +- net-sircl/net_sircl_connection.h | 49 +- net-sircl/tests/failure_test.c | 76 ++- net-sircl/tests/layer_test.c | 99 +++- net-sircl/tests/settings_test.c | 84 ++++ net-sircl/tests/test_net_sircl.py | 39 +- scripts/check_release_safety.py | 17 +- tests/test_release_safety.py | 17 + tests/test_topology_conformance.py | 250 ++++++++++ transport-core/src/topology.c | 223 ++++++--- transport-core/tests/test_planning.py | 60 +++ 33 files changed, 2285 insertions(+), 285 deletions(-) create mode 100644 RELEASE_NOTES-unreleased.md create mode 100644 fabric-tool/tests/test_review_fixes.py create mode 100644 tests/test_topology_conformance.py diff --git a/RELEASE_NOTES-unreleased.md b/RELEASE_NOTES-unreleased.md new file mode 100644 index 0000000..2db0763 --- /dev/null +++ b/RELEASE_NOTES-unreleased.md @@ -0,0 +1,89 @@ +# net-sircl: changes after 0.1.2 (unreleased) + +Status: **CPU-tested only.** Nothing here has run on DGX Sparks. The plugin, +transport-core and fabric-tool sources on this branch differ from the `v0.1.2` +tag (they already did after the merge of the resource-ownership work), so the +0.1.2 hardware qualification does not cover this tree; see +[qualification](docs/qualification.md). The `VERSION` files still read 0.1.2 +and 0.1.1 until a release is cut. Wire version remains **6** and the wire +structures are unchanged; every host of a job must run the same build. + +## Behaviour that changes for users + +- **A rank that is late is waited for.** `NET_SIRCL_REQUEST_TIMEOUT_MS` now + bounds only this host's own transport progress (a send from its + clear-to-send to completion, and a receive's clear-to-send post). Waiting + for the peer application to post its matching request has no deadline by + default, as with NCCL's own transports; before, a rank more than 60 seconds + late to a collective failed the job. `NET_SIRCL_PEER_WAIT_TIMEOUT_MS` adds + an optional bound. A failed connection now shuts its socket down, so the + peer's requests on it fail promptly. + See [deadlines](docs/configuration.md#deadlines). +- **Settings fail closed.** `NET_SIRCL_CHUNK`, `NET_SIRCL_SPEED_MBPS`, + `NET_SIRCL_TC`, `NET_SIRCL_RELAXED_ORDERING`, `NET_SIRCL_ROUTE_CHECK` and + `NET_SIRCL_GID_INDEX` are validated like the other settings: an empty, + malformed or out-of-range value fails initialization instead of selecting + the default or being truncated. `NET_SIRCL_OOB_ADDR` must be an IPv4 address + when set; when no address is found the plugin warns that it advertises + 127.0.0.1. +- **Topology files are read strictly, and identically by the plugin and + fabric-tool.** A `cabling` line is required; extra words, a `port0`/`port1` + line without exactly two names, over-long names, more than 64 hosts, a host + without a cable and cables that do not join every host are refused with a + message, where the plugin used to guess, truncate or continue without + routes. A two-host `cabling ring` is one cable for both tools (fabric-tool + used to read two); write a double-cabled pair with `cabling explicit`. +- **Stray connections no longer fail communicator setup.** The listener binds + the advertised address and drops a connection that never sends valid + metadata. +- **fabric-tool** + - Only processes run by root count as markers (`pgrep -U 0 -u 0`), so a + process that merely carries the marker's name cannot stand in for one. + - A missing tool or a failed read on a host is a problem that blocks + `apply`/`remove` and fails `verify`, instead of reading as "nothing + installed". + - The ownership record's layout name is derived from the topology's content, + not its file name, so a workstation and the boot unit agree. Each host + shows one pending record write the first time. + - `cabling explicit` in any order or port pairing can be planned. + - `apply --boot` no longer stops marker processes the plan does not name. + - `install-boot` starts the reconcile timer even when its immediate apply + fails; `remove-boot` can be run twice; ingress qdiscs added by a run that + failed later stay recorded as owned. + - `remove` refuses a host whose interfaces have other names unless `--facts` + is given, and a host whose record names a different marker executable + unless `--marker` names it. `verify --adopt` is rejected (it never did + anything). + +## Fixes without a change in normal use + +- Equally short lanes on an even ring cabled with `explicit` now follow the + cables at the higher position; they were assumed to arrive on port 1, which + put the two ends of a lane on different paths when a host was turned round. + Ring and path cabling are unaffected. +- A direct peer capped with `NET_SIRCL_WINDOWS` above about 64 MiB could + overflow the queue pair's send queue on a large send; payload writes now + stop short of it and resume as completions arrive. +- A forked child (a data-loader worker) no longer keeps the one-plugin-per-host + claim alive after its parent finalizes or exits. +- A connect toward a position the topology gives no route to logs why. +- The plugin build uses the bundled `transport-core` before a directory of + that name next to the checkout. +- The release scanner fails on an empty or missing tree and scans files that + contain NUL bytes. + +## Tests added + +Peers that are late rather than lost, stray connections, a window deeper than +the send queue, strict settings, fork handling, what the topology parser +refuses and accepts, lane reciprocity on turned rings, a conformance corpus +that both topology parsers must read alike, and 57 fabric-tool cases. + +## Not changed here + +- Version numbers, tags and the hardware-claim wording in README, + `docs/release-0.1.0.md`, `docs/measurements.md` and `docs/qualification.md`, + which disagree with each other in places and need the people who ran the + hardware to settle. +- `transport-core/src/fabric.c` and the `sircl_protocol_*` declarations in + `sircl_fabric.h`, which nothing in this repository calls or defines. diff --git a/SOURCE.json b/SOURCE.json index 391ee9c..dd0e45b 100644 --- a/SOURCE.json +++ b/SOURCE.json @@ -138,12 +138,12 @@ "net-sircl/nccl/tuner.h": "8450583204696fe008b01ab92cfc86d5e8e5bfe1b722b02360be58d599f00148", "net-sircl/nccl/tuner_v4.h": "1164e13f7096c21c3c02fda1ddcb13d52a9d74e89a42cbf287ac74710861c9cd", "net-sircl/nccl/types.h": "204015ef7865117da6d643307d81df8f16736ccde3762e5110de516b34983890", - "net-sircl/net_sircl.c": "8c1fb7ea5d6930946a9689a6810a1b282e3d5fe25a4da56776e846a3be37fca6", - "net-sircl/net_sircl.h": "edf9ea26f9c3efd22a514233004b9a0771da16dc55a627ae5ed5e834cd3fe746", + "net-sircl/net_sircl.c": "831c257c6f029e0fbfae31988d3230969d5fd732fb5ef4f3f0c4f6fccc723135", + "net-sircl/net_sircl.h": "de03b0ae808c101c2a3acc1dc7361b78eaf3d6baefa94f21af97723cb4a978d1", "net-sircl/net_sircl_admission.h": "6e92a7e07863fc7667f1db549ac89761a34a4a372388497915fb6c362fea1409", "net-sircl/net_sircl_compat.h": "0053800750c2f061a1254d1db95e65e4317de000c1b52873c0fe2cec9afafdf9", - "net-sircl/net_sircl_config.h": "6d6a3e6eeb697ec652177bea148e3ba9ce80e1ecc11e17820768c19b72c1ed85", - "net-sircl/net_sircl_connection.h": "4e323cb1900aea927febf0f20f68dbb2e2eef05f0d99107febc6cf78ad5ebd96", + "net-sircl/net_sircl_config.h": "af52fb32b73d7ed3a60e08bad0a5c5567cbf2614f86a27d12e200000ab2265de", + "net-sircl/net_sircl_connection.h": "901f799e6964445294f2a5fbca0413419d601f8a0cd5bde59f948a8650cff067", "net-sircl/net_sircl_plan.c": "6fc1f03374562864b5b5898a54f4b2cf471e6d11003af83839e0f5a1f777e856", "net-sircl/net_sircl_plan.h": "dcb857dce8247ff61756e216e90cfd40c6ce3a2b24f5e990b39ec561d2169526", "net-sircl/net_sircl_profile.h": "58b2d994f86fbc88fba4b4d90f332142c52610fcb069dbb2990356734ac076fe", @@ -151,13 +151,13 @@ "net-sircl/tests/abi_test.c": "6bc4f44a4cec8f95253ccdf3e3980ced419f01b6be5e41f7e7d1718714e4d91a", "net-sircl/tests/ack_test.c": "ba53451731662b8398c7e4dfd6ccab2008004e0343b1fd25f5fa8884599c6430", "net-sircl/tests/emulation/nccl_compat_e2e.cc": "87217f46e6b83c65e9630b1df1b8f54ac4595e27cb3086e95c12ddc1765568d5", - "net-sircl/tests/failure_test.c": "6c7c79f4e689b037ea74c6a2cb685794d624fffb515d2e3c5ec764958b155c42", - "net-sircl/tests/layer_test.c": "7c677708799add8eba5d06187c1987054015e5b05252e47b010c592b25583f35", + "net-sircl/tests/failure_test.c": "040d98cb2803723a56b3f2534d5a228e3b51fdc19f59e4f526a75829d7208a82", + "net-sircl/tests/layer_test.c": "1d31ac5e27aaddbaeffab39d057665474c8e875f167c3ffe2752edbaa315c5c7", "net-sircl/tests/progress_cost_test.c": "b3d26360da2c4df8a5d63ad4e62672462c6ebff15b06d1c79e7887cc128f5fa0", "net-sircl/tests/relay_test.c": "651da26961b317e7189c27204f99c06cd7319b4d051cbe4677d69d95dfc7c13a", "net-sircl/tests/request_contract_test.c": "3881b1f0ca107b600fb29a2b43478b687571a20b0495255cc3c635233d69c500", "net-sircl/tests/route_model.c": "b365917435b11477b0e722e6df1bdcc2ddba427a847b02073b91eaa3f3bd76d2", - "net-sircl/tests/settings_test.c": "81ab5d5b8b62223ff533f8d1d4680b734962649176c97fb731b46733761115cf", + "net-sircl/tests/settings_test.c": "07b5ff68bc0919c456d56281c49af18c4f2bacf974846b77ca18c7044c1159a2", "net-sircl/tests/standin/fake_verbs/infiniband/verbs.h": "8c2173547a2169bb455d103b7842463168e75d4350f4434d92ab5dabc353c64c", "net-sircl/tests/standin/proxy_names.h": "962f0623b88648d1f8bc683168d0befd25dfe5dd7fe4c48a6f69b1e168b1964a", "net-sircl/tests/standin/shm_verbs.c": "3921790d413212dee23f906a2abc897ff2367c27ac910d521174cf8c077b66a2", @@ -178,7 +178,7 @@ "transport-core/src/shm_memory.h": "defe5e56c0162f2c2ce3d7484693b2771bf0afb953f8a9994ba8ebe5e4f1e01b", "transport-core/src/shm_verbs.c": "2bc7a33b4e492c1ab0ee25de3527695420ce7ddde4bd4b9b5128874093a1686b", "transport-core/src/sysfs.c": "747062778a2cab1744d43e602c724b1887ad6ba66428d62ee892b351f7f5b7c2", - "transport-core/src/topology.c": "a3f7c625832f95816d8cac09d625aada86b4fe29f30923acbc9c126af73a9d0a", + "transport-core/src/topology.c": "0719f36aa7b5a3b4754c180166ed3d8620a67bf9d285aed3faf92d4fbc9852f4", "transport-core/src/verbs_dl.c": "ea38fd0ef71bc215f8d97c4f836179aa9190dc87a34125a4a24a96e23bbc4d84", "transport-core/tests/fake_verbs/infiniband/verbs.h": "8c2173547a2169bb455d103b7842463168e75d4350f4434d92ab5dabc353c64c", "transport-core/tests/test_core.c": "af1228e52b14a1da826573e8eb604ca27ffaf603d3aa7f464b00a4b729f0c2c0", diff --git a/docs/configuration.md b/docs/configuration.md index 2e9646f..177de05 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -1,5 +1,6 @@ # Configuration +## Topology file A text file, the same on every host, `#` for comments: @@ -11,16 +12,27 @@ cabling ring | Key | Meaning | |---|---| -| `hosts ...` | host names in position order; a host finds its own position by its host name (`NET_SIRCL_POSITION` overrides) | -| `cabling ring` / `path` / `explicit` | `ring`: host i's port 0 is cabled to host i+1's port 1, and the last host to the first; `path`: the same without the closing cable; `explicit`: only `cable` lines | -| `cable .port

.port` | one cable (repeatable) | -| `port0 `, `port1 ` | the RDMA functions of each port, lane order (default the DGX OS names above) | +| `hosts ...` | host names in position order, 2 to 64 of them, each at most 63 characters; several `hosts` lines append; a host finds its own position by its host name (`NET_SIRCL_POSITION` overrides) | +| `cabling ring` / `path` / `explicit` | required. `ring`: host i's port 0 is cabled to host i+1's port 1, and the last host to the first; `path`: the same without the closing cable; `explicit`: only `cable` lines. With two hosts `ring` and `path` both mean the one cable `0.port0`–`1.port1` | +| `cable .port

.port` | one cable (repeatable); positions are plain decimal numbers and ports are 0 or 1 | +| `port0 `, `port1 ` | the two RDMA functions of each port, lane order (default `rocep1s0f0 roceP2p1s0f0` and `rocep1s0f1 roceP2p1s0f1`, the DGX OS names); letters, digits and `_.:-`, at most 63 characters | | `relay_budget ` | directional budget ceiling, 65536–393216 bytes; default ceiling 393216, further limited by `NET_SIRCL_RELAY_BUDGET` | A topology file is required, including for a direct pair. The plugin derives the shortest cabled path, the local functions of its two lanes, the relays on the way and the source allowance. Each physical port must have at most one cable; host names must be unique. Expose both functions required by each route. Where two directions are equally short (the opposite host of an -even ring), lane 0 takes one direction and lane 1 the other, as verified by the standalone route and queue-model tests. +even ring, or a pair joined by two cables), lane 0 takes the direction that leaves the lower position through +its port 0 and lane 1 the other, at both ends, whichever way round `explicit` cabling connects the hosts +between; the standalone route and queue-model tests verify it. A pair joined by two cables is written with +`cabling explicit` and two `cable` lines. + +The file is refused, with the line and the rule, rather than interpreted loosely: an unknown key, a missing +`cabling` line, extra words after a key, a `port0`/`port1` line without exactly two names, a name that is too +long, a line over 1022 characters, a host that no cable reaches, or cables that do not join every host into +one path or one cycle. `fabric-tool` reads the same file by the same rules, and a shared test holds the two +parsers to the same cables and lanes. One difference is deliberate: the plugin accepts the same function name +for both ports (the emulation tests use it, and relay admission then keeps the aggregate model), while +`fabric-tool` requires four distinct functions. The NCCL ranks may be a subset of the hosts: a path of three Sparks inside a ring of four lists all four hosts, and the fourth relays. @@ -34,37 +46,62 @@ and the fourth relays. | `NET_SIRCL_ROUTES` | unset | optional `=/,...`; must exactly match topology lanes | | `NET_SIRCL_WINDOWS` | unset | `=,...`; direct peers: optional per-function payload cap; relayed peers: can only lower the shared source allowance; 0 is rejected for relayed peers | | `NET_SIRCL_HCA` | every active RoCE function | comma list of functions to expose | -| `NET_SIRCL_GID_INDEX` | the function's RoCE v2 IPv4 GID | GID index | +| `NET_SIRCL_GID_INDEX` | the function's RoCE v2 IPv4 GID | GID index, 0–255 | | `NET_SIRCL_RELAY_BUDGET` | 327680 | base budget B (split limits: 6B/5 forward, B/5 ACK) per direction/function; decimal 65536–327680, limited by topology `relay_budget` | -| `NET_SIRCL_CHUNK` | 65536 | maximum payload bytes per independently completed chunk; adapts to available credit | -| `NET_SIRCL_OOB_ADDR` | first IPv4 of `NCCL_SOCKET_IFNAME` | address for the connection exchange | +| `NET_SIRCL_CHUNK` | 65536 | maximum payload bytes per independently completed chunk, 1–1073741824 (values below 4096 use 4096); adapts to available credit | +| `NET_SIRCL_OOB_ADDR` | first IPv4 of `NCCL_SOCKET_IFNAME`, else 127.0.0.1 | this host's IPv4 address for the connection exchange; the listener binds it | | `NET_SIRCL_CONNECT_TIMEOUT_MS` | 60000 | connect/accept deadline | -| `NET_SIRCL_REQUEST_TIMEOUT_MS` | 60000 | deadline for a pending send/receive, including waiting for clear-to-send | +| `NET_SIRCL_REQUEST_TIMEOUT_MS` | 60000 | deadline for this host's own transport progress on a request: a send from its clear-to-send to its completion, and a receive's clear-to-send post | +| `NET_SIRCL_PEER_WAIT_TIMEOUT_MS` | 0 (no limit) | optional deadline for the peer application to post its matching request: a send waiting for clear-to-send, and a receive waiting for its payload | | `NET_SIRCL_CHANNELS` | 8 on topologies with more than two hosts; otherwise 0 | tuner collective limit, 1–64; 0 leaves selection to NCCL; explicit NCCL channel settings take precedence | | `NET_SIRCL_IB_TIMEOUT` | 20 | RC ACK timeout exponent, decimal 1-31; one timeout is 4.096 microseconds times 2^value | | `NET_SIRCL_IB_RETRY_CNT` | 7 | RC transport retry count, decimal 0-7 (0 disables retries); RNR retries remain 7 | -| `NET_SIRCL_RELAXED_ORDERING` | 1 | register memory with relaxed ordering | -| `NET_SIRCL_ROUTE_CHECK` | 1 | refuse a peer the function's interface has no route to | -| `NET_SIRCL_SPEED_MBPS` | 100000 | speed reported to NCCL's tuner, per function | -| `NET_SIRCL_TC` | 0 | RoCE traffic class | +| `NET_SIRCL_RELAXED_ORDERING` | 1 | 1 registers memory with relaxed ordering, 0 does not | +| `NET_SIRCL_ROUTE_CHECK` | 1 | 1 refuses a peer the function's interface has no route to, 0 skips the check | +| `NET_SIRCL_SPEED_MBPS` | 100000 | speed reported to NCCL's tuner, per function; at least 1 | +| `NET_SIRCL_TC` | 0 | RoCE traffic class, 0–255 | `NET_SIRCL_ROUTES` may confirm topology lanes, but cannot change them. Unknown peers fail connection admission. Invalid window maps fail initialization; a relayed peer's override cannot remove or raise the directional cap. A smaller override lowers every function's source allowance on that host. -Direct peers have window 0 unless explicitly capped. The directional budget accepts decimal digits only; -empty, signed, malformed, overflowing and out-of-range values fail initialization. - -Both timeout settings accept decimal integers in 1–2147483647 milliseconds. -Invalid settings fail initialization. Request deadlines start at receive submission -or the sender's first wait for clear-to-send; after admission, the send gets its -own completion deadline. They are total request bounds, not idle timers, so choose -a value larger than the slowest expected individual transfer. Health is checked -on the first and every 4096th waiting progress call; detection requires NCCL to -continue polling. Peer loss or deadline expiry returns `ncclRemoteError` and stays -failed on subsequent calls. Relayed connections also poison their shared allowance, -so abandoned credits cannot fund another transfer. Close abandons QPs without -waiting for remote recovery. Use an outer application timeout too: the plugin cannot -time out CUDA or a process that no longer calls it. +Direct peers have window 0 unless explicitly capped. A capped direct peer keeps its payload writes below +the queue pair's send queue, whatever the cap. + +Every numeric setting above accepts decimal digits only. Unset values use the defaults; empty, signed, +malformed, overflowing and out-of-range values fail initialization and name the setting, instead of +silently selecting the default or being truncated. `NET_SIRCL_OOB_ADDR` must be an IPv4 address when set. + +### Deadlines + +The plugin separates two kinds of waiting. + +- **This host's transport.** Once a send has its peer's clear-to-send, only this host's RDMA writes and + their completions are outstanding; the same holds for the clear-to-send a receive posts. Nothing but + the fabric delays those, so `NET_SIRCL_REQUEST_TIMEOUT_MS` bounds them (1–2147483647 ms). It is a total + bound for that part of a request, not an idle timer: choose a value larger than the slowest expected + individual transfer. +- **The peer application.** NCCL posts a receive as soon as the local collective starts and retries a + send until its receive exists, with no time limit of its own. A rank that is merely late, because it is + checkpointing, evaluating or compiling while the others have entered the next collective, is therefore + waited for, exactly as with NCCL's own transports. `NET_SIRCL_PEER_WAIT_TIMEOUT_MS` (0–2147483647 ms, + 0 or unset: no limit) adds a bound for sites that want one; it must exceed the longest time any rank may + spend outside a collective that the others have entered. + +Before this distinction the request deadline covered both, so a rank more than 60 seconds late to a +collective failed the job. + +Health is checked on the first and every 4096th waiting progress call; detection requires NCCL to +continue polling. A peer that closes its connection (its process ended, or it closed or failed the +connection) ends every wait on it at the next check, whichever kind. Peer loss or deadline expiry +returns `ncclRemoteError` and stays failed on subsequent calls. A failed connection also shuts its side +of the connection socket down, so the peer's requests on it fail at their next check instead of waiting +for work that will not come. Relayed connections also poison their shared allowance, so abandoned +credits cannot fund another transfer. Close abandons QPs without waiting for remote recovery. + +What remains unbounded by default is what NCCL also leaves unbounded: a peer whose process is alive but +no longer calls NCCL, and a peer host that vanishes without closing its sockets while this host only +waits to receive from it. Use an outer application timeout: the plugin cannot time out CUDA or a process +that no longer calls it. If a relay loses a rule, `fabric-tool verify` reports the missing filter and returns nonzero. A filter with no `in_hw` flag also fails verification, even if its actions @@ -104,7 +141,22 @@ NCCL_DEBUG_SUBSYS=INIT,NET` for diagnostics. Use one interface name or prefix in `NCCL_SOCKET_IFNAME`. The plugin does not parse NCCL's list/exclusion/exact-match syntax; configure `NET_SIRCL_OOB_ADDR` -explicitly if using that syntax. Loopback is only suitable for local tests. +explicitly if using that syntax. A `NET_SIRCL_OOB_ADDR` that is not an IPv4 address +fails initialization. When neither setting yields an address the plugin advertises +127.0.0.1 and warns that peers on other hosts cannot reach it: loopback is only +suitable for local tests. + +The listener for the connection exchange binds the advertised address (every +interface only if this host does not own that address). A connection that never +identifies itself as a net-sircl peer, such as a port scan, a health probe or a +connector that ended early, is dropped with a warning and the listener keeps +accepting; it no longer fails communicator setup. A peer that did identify itself +and then fails still fails the accept. + +One plugin process per host owns the relay allowance (an abstract socket in the +host network namespace). A forked child, such as a data-loader worker, releases +its inherited copy, so the owner can finalize and initialize again, and the next +job can start, while such children are still alive. ## PyTorch and CUDA graphs diff --git a/docs/fabric.md b/docs/fabric.md index a6f20e5..920ed67 100644 --- a/docs/fabric.md +++ b/docs/fabric.md @@ -5,6 +5,10 @@ relays. A ring needs them when communicating peers are not direct neighbours. A path needs them because NCCL's ring algorithm connects the two end hosts, which share no cable. A *layout* is the cabling and ordered hosts; a *group* in the tool's output is the set of hosts described by one topology file. +With two hosts, `cabling ring` and `cabling path` both mean the one cable +`0.port0-1.port1`; write a pair joined by two cables with `cabling explicit` +and two `cable` lines. `cabling explicit` may join the hosts in any order and +through either port, as long as the cables form one path or one cycle. ## How relays work @@ -71,7 +75,10 @@ An executing apply rereads and verifies changed hosts. Always run `verify` afterward, even if apply reports nothing to change. Identity mismatches, contradictory facts, cabling mismatches and foreign ownership block changes. A failure during execution can leave partial state: inspect `status` and -resolve the cause before using the relays. Read sections end with a newline +resolve the cause before using the relays. A host whose read failed (a tool +missing from the SSH account's `PATH`, or a failed `ip`, `tc` or `pgrep` read) +is a blocker for `apply` and `remove` and fails `verify`; it is never treated +as a host that holds nothing. Read sections end with a newline so digest records cannot hide following ownership observations. Marker starts use util-linux `setsid -f` with stdin from `/dev/null` and stdout and stderr on the root-created log, allowing the SSH command to finish while markers run. @@ -104,9 +111,12 @@ See [marker security](../fabric-tool/README.md#marker-security) for custom paths and refusal handling. fabric-tool marks installed IP routes and neighbour entries with protocol 82, -and forwarding filters with `tc` ingress preferences 11–17. Its ownership +and forwarding filters with `tc` ingress preferences 11–17. Its ownership record is `/run/fabric-table/relay-state.json`. `remove` targets marked objects, -owned ingress qdiscs, marker processes and that record. +owned ingress qdiscs, marker processes and that record. Only root's processes +count as markers. Pass `remove` the `--marker` and, where the hosts do not use +the default interface names, the `--facts` that `apply` was given: it refuses +a host whose record or interfaces say otherwise. It refuses hosts with `/run/sparkring-fabric/relay-state.json`, written by the SparkRing project's relay installer. Remove those relays with that installer's @@ -131,12 +141,13 @@ sudo /opt/net-sircl/bin/fabric-tool install-boot \ This writes topology and facts under `/etc/fabric-table/`, copies the tool to `/usr/local/lib/fabric-tool` and `/usr/local/bin/fabric-tool` (separate from the `/opt/net-sircl` install), enables `fabric-table.service` and applies the relays. -It also installs and starts `fabric-table-reconcile.timer`. Every 15 seconds +It also installs and starts `fabric-table-reconcile.timer`; the timer is +started even when the immediate apply fails, and the command says so. Every 15 seconds after the preceding check finishes, the timer starts `fabric-table-reconcile.service`, which requests a reload of the retained fabric service, or starts it if inactive. Startup and reload both run -`apply --boot --execute`, adding missing objects and markers without removing -healthy state. Reload preserves existing marker processes. Failed checks are +`apply --boot --execute`, adding missing objects and markers, replacing planned +ones that differ and removing nothing the plan does not name. Reload preserves existing marker processes. Failed checks are retried; inspect both services' journals when restoration is blocked. Addresses must be ready at `network-online.target`. If a separate service configures them later, order `fabric-table.service` after that service and diff --git a/docs/testing.md b/docs/testing.md index 2990e80..4c864cb 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -16,9 +16,11 @@ test plugin. `make check` runs: - transport-core: three C test executables for concurrent window arithmetic, abort/progress callbacks, emulated verbs and barrier-controlled executor/mapping lifetimes, - plus five Python discovery/topology tests. + plus seven Python discovery/topology tests, including what the topology parser + refuses and accepts. - net-sircl: Python tests, including multiprocess transfer, window, lane, - teardown, peer-loss and deadline tests, fixed topology expectations and + teardown, peer-loss, deadline, stray-connection and deep-window tests, peers that + are late rather than lost, strict settings, fixed topology expectations and the real-NIC library's v7–v12 export check, ABI layout calls, route/ACK capacity oracle, oldest-first credit, partial completions and profiling checks. That export check needs rdma-core headers and `nm`; CI installs both. @@ -28,6 +30,9 @@ test plugin. `make check` runs: and local Bash checks without privileged host changes. No external checkout or full-network simulator is used. These do not exercise real apply/verify/remove across hosts or restoration after an actual reboot. +- Topology conformance: the plugin's C parser and fabric-tool's Python parser + read one corpus of topology files and must agree on which are valid, on the + cables and on every lane. - Release contracts: shipped C/C++/header hashes, example routes, embedded core identity, and archive reproducibility/completeness, extracted-source privacy scanning and complete distributed C/C++/header inventory. The archive test creates @@ -120,7 +125,9 @@ credential-like strings. It reports locations and rule names without matched values. `--site-values FILE` adds literal host names or addresses, one per line; keep the file untracked (`scripts/config/site-values.txt` is ignored and excluded). The scanner checks Git-tracked text by default. `--tree` enumerates confined -regular files without Git metadata and refuses symbolic links. CI scans the +regular files without Git metadata and refuses symbolic links. A tree with no +files to inspect is an error, not a clean result, and a file containing NUL +bytes is scanned like any other. CI scans the extracted archive before building it, using the same rules. ## Source identity @@ -143,8 +150,9 @@ limits, the direct-pair stock-tuner control, overrides and tuner disablement. Use the site's GPU reservation for these commands. [Compatibility](compatibility.md) documents the native runtime matrix and its -reproducer. CPU fault injection covers silent peers, lost completion delivery, -sticky errors and bounded close. Fabric tests cover missing forwarding rules, +reproducer. CPU fault injection covers silent peers (waited for by default, +failed at the optional peer-wait bound), lost completion delivery, sticky errors +that hang the connection up, and bounded close. Fabric tests cover missing forwarding rules, lost `in_hw`, unreachable relays and verify blockers without contacting a host. The distributed source inventory is regenerated with diff --git a/fabric-tool/DESIGN.md b/fabric-tool/DESIGN.md index eb8c2ec..05c14d4 100644 --- a/fabric-tool/DESIGN.md +++ b/fabric-tool/DESIGN.md @@ -6,8 +6,13 @@ reads host state and computes the changes needed to match the plan. ## Inputs and planning `fabric_tool/topology.py` reads hosts, cables and function names using the -same conventions as `transport-core/src/topology.c`. `model.py` derives -shortest paths and lanes. A layout means ordered hosts and cables; a group is +same conventions as `transport-core/src/topology.c`: at most 64 hosts, names +of 1 to 63 bytes, a decimal `relay_budget`, and one cable for two hosts under +`cabling ring` as under `cabling path` (a pair joined by two cables is written +with `cabling explicit`). `model.py` derives +shortest paths and lanes. Routes, filters and the delivery trace follow the +topology's cables, so `cabling explicit` may join the hosts in any order and +through either port as long as the cables form one path or one cycle. A layout means ordered hosts and cables; a group is the hosts managed by one topology file. `plan.py` carries every shortest path on both function classes. It derives @@ -22,17 +27,29 @@ subnet prefixes. Contradictions and incomplete host coverage block apply. `diff.py` compares them with the plan; `ops.py` runs the selected operations; `report.py` formats the result. +The read script never lets a failed read pass for an empty host. It names the +tools missing from the read account's `PATH` and records the exit status of +the address, route, neighbour, qdisc, filter and marker-process reads; +`state.py` turns a missing tool, a failed `ip` read, a `tc` that could not be +executed (exit 126 or 127; other `tc` failures are not judged) and a failed +`pgrep` (exit 1 means no match) into parse problems, which block apply and +remove and fail verify. Only the first block of a section name is used, and a +repeated header is a parse problem. Marker processes are read with +`pgrep -U 0 -u 0`: only root's count. + ## Execution and ownership OFFLINE commands compute from files without host reads. READ-ONLY REMOTE commands inspect hosts through SSH. MUTATES HOST commands preview changes unless `--execute` is supplied. No command assigns interface addresses. -Ownership marks are routing protocol 82, ingress preferences 11–17, marker +Ownership marks are routing protocol 82, ingress preferences 11–17, marker process identities and `/run/fabric-table/relay-state.json`. The tool refuses a foreign ownership record and unrelated routes to planned destinations. Apply can leave partial state on a command failure; inspect and reconcile it. -Boot apply restores missing objects without removing any. The systemd unit +Boot apply restores missing objects and replaces a planned object that +differs; it removes nothing the plan does not name, including marker +processes of a device without planned rules. The systemd unit is a oneshot operation rather than marker supervision. See the installed guide `share/doc/net-sircl/docs/fabric.md` for the relay @@ -84,6 +101,11 @@ stale-object removal and adoption requirements. Restoration retains stale objects; apply reconciles them. Qdisc ownership records contain only interfaces where the tool added a qdisc, plus previously recorded ownership. Removal leaves a pre-existing unowned qdisc intact and preserves qdiscs with unrelated filters. +A script that adds qdiscs writes the record before it adds them, so a run that +fails afterwards still owns them. The record's layout name is a digest of the +topology's hosts, cables and functions, never the file's path: the workstation +and the boot unit, which read different copies, agree on it. Objects that carry +the ownership mark on a device outside the fabric's four are noted and left. `RestoreInvocation` retains execution intent, facts, topology, marker location, relay limit and optional host selection. The systemd unit serializes its argument diff --git a/fabric-tool/HARDWARE-TEST-PLAN.md b/fabric-tool/HARDWARE-TEST-PLAN.md index 3ea788a..544a220 100644 --- a/fabric-tool/HARDWARE-TEST-PLAN.md +++ b/fabric-tool/HARDWARE-TEST-PLAN.md @@ -8,7 +8,7 @@ CPU tests establish software contracts, not real forwarding or boot restoration. Use placeholders `node-0` through `node-3` for one ring and `node-4` through `node-7` for the other. Substitute actual host names and SSH targets privately. -Each ring cables position i's port 0 to position i+1's port 1, closing at 3→0. +Each ring cables position i's port 0 to position i+1's port 1, closing at 3→0. For its path test, describe the same ordered hosts with `cabling path`. ## Prepare and record (about 15 minutes) @@ -65,7 +65,7 @@ Use unpatched NCCL 2.32.3, nccl-tests v2.21.1 and one GPU/rank per host. Select `NCCL_NET=sircl`, the stamped plugin and `NCCL_ALGO=Ring`. Record actual library selection and version/core identity from INIT logs. Run a stock pair control, then all-reduce, all-gather and broadcast on the path of four at -8–256 MiB, bfloat16, eager and 20 graph replays. Run the repository's PyTorch +8–256 MiB, bfloat16, eager and 20 graph replays. Run the repository's PyTorch example; release captured graphs before process-group teardown. Require exit zero on every rank, exact results, no out-of-bounds errors and diff --git a/fabric-tool/README.md b/fabric-tool/README.md index 8b57bcd..de4b370 100644 --- a/fabric-tool/README.md +++ b/fabric-tool/README.md @@ -45,12 +45,12 @@ The installed copy of that guide is under `share/doc/net-sircl/`. |---|---| | `plan` (default) | Offline relay plan; `--commands` needs complete `--facts`; `--json` emits machine-readable output | | `facts` | Read local host, or every topology host with repeated `--ssh NAME=TARGET`; `--output FILE` saves facts | -| `apply` | Preview reconciliation; `--execute` applies; `--boot` restores without removing objects | +| `apply` | Preview reconciliation; `--execute` applies; `--boot` restores: adds missing objects, replaces planned objects that differ, removes nothing the plan does not name | | `verify` | Read and compare objects and resolve lane destinations with `ip route get`; zero means success | | `status` | Show owned and unowned objects | | `install-marker` | Preview/build `mesh_marker.c` on hosts, install root-owned at `/usr/local/libexec/fabric-tool/fabric-tool-marker` and record its SHA-256 | | `remove` | Preview/remove owned relay objects | -| `install-boot` | Install the retained fabric service, periodic reconciliation service/timer, tool and inputs; apply now and start checks | +| `install-boot` | Install the retained fabric service, periodic reconciliation service/timer, tool and inputs; apply now and start checks (the timer starts even when that apply fails, so it is retried) | | `remove-boot` | Stop reconciliation and remove units/inputs; leave live table, markers and tool copy | `apply`, `verify`, `remove`, `status` and `install-marker` act locally by default. @@ -64,8 +64,37 @@ Exit codes: 0 success; 1 failed reads or remaining changes; 2 invalid input; mismatch and non-relay routes to planned destinations. A failure during execution may leave partial state; inspect and reconcile before using the table. +A read that could not be made is a blocker, not an empty host: the read script +reports a tool missing from the read account's `PATH` (`ip`, `tc`, `pgrep`, +`sha256sum`, `stat`, `head`), a failed read of addresses, routes or permanent +neighbours, a `tc` that could not be executed and a failed `pgrep`. `apply` and +`remove` refuse such a host and `verify` fails. Facts whose addresses lack +prefix lengths cannot be checked against the cabling; the comparison says so +in a `NOTE` line instead of passing silently. + +Restore (`apply --boot`, the boot unit's mode) keeps what the plan does not +name: stale routes, neighbours, filters and qdiscs, marker processes of a +device without planned rules and marker-named processes without a device. It +still replaces a planned filter, route, neighbour or marker that differs. + +The ownership record names the layout by a digest of the topology's hosts, +cables and functions, so copies of one topology under different file names +(for example the boot unit's `/etc/fabric-table/topology`) agree. A host with +a record written by an earlier version shows one pending record write, which +one apply converges. A script that adds ingress qdiscs writes the record +first, so a run that fails later keeps their ownership and `remove` deletes +them. `remove` must be given the `--marker` the table was applied with: it +refuses a host whose record names a marker with another process name. +`verify` does not take `--adopt`; it reports unowned objects as blockers. + ## Marker security +Only processes whose real and effective user are root count as running +markers (`pgrep -U 0 -u 0`); a process of another user that carries the +marker's name and arguments is not read, so it can neither stand in for a +marker nor cause one to be restarted. A read whose output repeats a section +header is refused. + The marker runs as root. Before every start, the tool requires its executable, its adjacent `.sha256` file and every parent directory through `/` to be owned by root and not writable by group or others. It also requires the executable diff --git a/fabric-tool/fabric_tool/boot.py b/fabric-tool/fabric_tool/boot.py index ce1597a..050b3c7 100644 --- a/fabric-tool/fabric_tool/boot.py +++ b/fabric-tool/fabric_tool/boot.py @@ -5,8 +5,11 @@ installs the table now; ``remove-boot`` disables and removes both. The unit runs ``apply --boot --execute`` at startup and reload. A timer requests reload every 15 seconds after the preceding check finishes. Restore semantics add -missing objects and remove nothing. Reload retains the service's marker +missing objects, replace a planned object that differs and remove nothing the +plan does not name. Reload retains the service's marker processes; restarting the service on each check would kill healthy markers. +``install-boot`` starts the timer whenever it installed the units, also when +its own immediate apply failed, so that failure is retried. """ from __future__ import annotations @@ -175,9 +178,10 @@ def remove(*, root: str = "/", execute: bool) -> list[str]: removed = [] if root == "/" and execute: stop_reconciliation() - if Path(f"/etc/systemd/system/{RECOVERY_TIMER}").exists(): - subprocess.run(["systemctl", "disable", RECOVERY_TIMER], check=True) - subprocess.run(["systemctl", "disable", UNIT_NAME], check=True) + # `systemctl disable` fails for a unit file that does not exist; a second removal must not. + for unit in (RECOVERY_TIMER, UNIT_NAME): + if Path(f"/etc/systemd/system/{unit}").exists(): + subprocess.run(["systemctl", "disable", unit], check=True) for destination in (f"/etc/systemd/system/{UNIT_NAME}", f"/etc/systemd/system/{RECOVERY_SERVICE}", f"/etc/systemd/system/{RECOVERY_TIMER}", TOPOLOGY_INPUT, FACTS_INPUT): path = Path(root) / destination.lstrip("/") diff --git a/fabric-tool/fabric_tool/cli.py b/fabric-tool/fabric_tool/cli.py index 822f917..c2e673b 100644 --- a/fabric-tool/fabric_tool/cli.py +++ b/fabric-tool/fabric_tool/cli.py @@ -7,8 +7,9 @@ - ``facts`` (READ-ONLY REMOTE): read hosts and print the facts document; - ``status`` (READ-ONLY REMOTE): the relay objects every host holds; - ``apply`` (READ-ONLY REMOTE; MUTATES HOST with ``--execute``): compare each - host with its part of the plan and reconcile it; ``--boot`` installs missing - parts only (boot restore, never removes); + host with its part of the plan and reconcile it; ``--boot`` (boot restore) + installs missing parts, replaces a planned part that differs and removes + nothing the plan does not name; - ``verify`` (READ-ONLY REMOTE): compare every host with the plan and resolve every lane destination with ``ip route get``; - ``remove`` (READ-ONLY REMOTE; MUTATES HOST with ``--execute``): delete @@ -321,8 +322,8 @@ def _command_install_boot(args: argparse.Namespace, topology: topology_mod.Topol for destination, _ in spec.files[:2]: print(f"input: {destination}") if not args.execute: - print("dry run: --execute copies this tool to /usr/local/lib, writes the files, enables the unit " - "and installs the table now") + print("dry run: --execute copies this tool to /usr/local/lib, writes the files, enables the unit, " + "installs the table now and starts the reconcile timer") return 0 # Reject identity/ownership/facts blockers before persisting a boot service. hosts = _resolve_hosts(topology, args) @@ -348,9 +349,18 @@ def _command_install_boot(args: argparse.Namespace, topology: topology_mod.Topol print(f"wrote {wrapper}") boot.install(spec, root=args.root, execute=True) print(f"enabled {boot.UNIT_NAME} and {boot.RECOVERY_TIMER}") - code = _apply_flow(args, topology, "boot", executor) - if code == 0 and args.root == "/": - subprocess.run(["systemctl", "start", boot.RECOVERY_TIMER], check=True) + # The units are installed: the timer runs whatever the apply below returns, so a failed check is retried. + code = None + try: + code = _apply_flow(args, topology, "boot", executor) + finally: + if args.root == "/": + subprocess.run(["systemctl", "start", boot.RECOVERY_TIMER], check=True) + print(f"started {boot.RECOVERY_TIMER}" + + ("" if code == 0 else ": the apply above did not succeed" + + (f" (exit {code})" if code is not None else "") + + "; the timer retries it every 15 seconds, see the journals of " + f"{boot.UNIT_NAME} and {boot.RECOVERY_SERVICE}")) return code @@ -417,12 +427,15 @@ def relay_options(sub: argparse.ArgumentParser) -> None: if name in ("apply", "verify", "remove"): plan_facts(sub) relay_options(sub) + sub.add_argument("--verbose", action="store_true", help="also list unchanged objects") + if name in ("apply", "remove"): + # `verify` changes nothing, so it has nothing to adopt: it reports unowned objects as blockers. sub.add_argument("--adopt", action="store_true", help="take over relay routes and neighbours that lack the ownership mark") - sub.add_argument("--verbose", action="store_true", help="also list unchanged objects") if name == "apply": sub.add_argument("--boot", action="store_true", - help="restore semantics: install missing parts, never remove (the boot unit's mode)") + help="restore semantics: install missing parts, replace planned parts that differ, " + "remove nothing the plan does not name (the boot unit's mode)") sub.add_argument("--execute", action="store_true", help="change the hosts (MUTATES HOST)") sub.add_argument("--no-scripts", action="store_true", help="omit the per-host scripts") elif name == "verify": diff --git a/fabric-tool/fabric_tool/commands.py b/fabric-tool/fabric_tool/commands.py index b0e55d2..edb1df7 100644 --- a/fabric-tool/fabric_tool/commands.py +++ b/fabric-tool/fabric_tool/commands.py @@ -16,8 +16,8 @@ - relay filters occupy the reserved preferences 11 to 17 of chain 0 on the ingress of the four fabric network devices (preference ``10 + k``, handle ``k``, protocol ``TAG(k)``); -- marker processes run the marker executable, whose first 15 characters are - the process name ``pgrep -x`` matches; +- marker processes run the marker executable as root (real and effective + user), and its first 15 characters are the process name ``pgrep -x`` matches; - the record ``/run/fabric-table/relay-state.json`` names the host's group, layout, relay egress, plan digest and the ingress qdiscs the tool added. ``/run`` is cleared at boot, like every object of the plan. @@ -74,6 +74,11 @@ # Ends every section of a read script with a newline, so the next ``@@`` header starts its own # line even after output without one (``head -c 64`` of the digest record prints none). SECTION_END = "echo" +# Tools the read script needs on the read account's PATH. One that is missing is reported in the +# ``tools`` section, so its empty output is never taken for "nothing there". +READ_TOOLS = ("ip", "tc", "pgrep", "sha256sum", "stat", "head") +# ``@@exit:

`` holds the exit status of the read command of ``
``. +STATUS_PREFIX = "exit:" HEADER = "set -euo pipefail" SETTLE = "sleep 1.5" _PATH = re.compile(r"^/[A-Za-z0-9_./+-]+$") @@ -94,7 +99,7 @@ class MarkerConfig: def __post_init__(self) -> None: for label, value in (("marker path", self.path), ("marker log directory", self.log_dir)): - if not _PATH.match(value) or "/../" in f"{value}/": + if not _PATH.fullmatch(value) or "/../" in f"{value}/": raise FabricError(f"{label} {value!r} must be an absolute path of letters, digits and _./+-") # Root runs the executable and opens the logs, so neither may live where every user can write. for label, value, default in (("marker path", self.path, DEFAULT_MARKER), @@ -165,7 +170,7 @@ def _ipv4(value: str) -> str: def _mac(value: str) -> str: - if not _MAC.match(value.lower()): + if not _MAC.fullmatch(value.lower()): raise FabricError(f"{value!r} is not a MAC address; apply needs the hosts' facts, not placeholders") return value.lower() @@ -186,25 +191,41 @@ def _device(value: str, *, bindings: model.FabricBindings = model.DEFAULT_BINDIN def read_script(marker: MarkerConfig, *, bindings: model.FabricBindings = model.DEFAULT_BINDINGS) -> str: - """Read-only facts and relay objects of one host, as ``@@
`` blocks.""" + """Read-only facts and relay objects of one host, as ``@@
`` blocks. + + A read that fails must not look like a host that holds nothing. The + ``tools`` section names every tool of :data:`READ_TOOLS` that the read + account cannot run, and the reads of addresses, routes, neighbours, qdiscs, + filters and marker processes are each followed by an ``@@exit:
`` + block with the command's exit status (:func:`.state.parse` decides which + statuses are failures). Only processes whose real and effective user are + root count as markers: no other user can start one, so a process that + merely carries the marker's name and arguments is not listed. + """ lines = ["set -u"] - def section(name: str, *commands: str) -> None: + def section(name: str, *commands: str, status: bool = False) -> None: lines.append(f"echo {q(SECTION + name)}") lines.extend(commands) + if status: + lines.append("status=$?") lines.append(SECTION_END) + if status: + lines.extend([f"echo {q(SECTION + STATUS_PREFIX + name)}", 'echo "$status"', SECTION_END]) section("hostname", "hostname") + section("tools", f"for tool in {' '.join(READ_TOOLS)}; do command -v \"$tool\" >/dev/null 2>&1 || " + "echo \"$tool\"; done") section("versions", "ip -V 2>&1 || true", "tc -V 2>&1 || true") - section("links", "ip -j addr show") + section("links", "ip -j addr show", status=True) for device in bindings.devices: section(f"rdma:{device}", f"ls /sys/class/infiniband/{q(device)}/device/net 2>/dev/null || true") - section("routes", "ip -j -d route show table main") - section("neighbours", "ip -j neigh show nud permanent") + section("routes", "ip -j -d route show table main", status=True) + section("neighbours", "ip -j neigh show nud permanent", status=True) for netdev in bindings.netdevs: - section(f"qdisc:{netdev}", f"tc -j qdisc show dev {q(netdev)} 2>/dev/null || true") - section(f"filters:{netdev}", f"tc -j filter show dev {netdev} ingress 2>/dev/null || true") - section("markers", f"pgrep -a -x {q(marker.comm)} || true") + section(f"qdisc:{netdev}", f"tc -j qdisc show dev {q(netdev)} 2>/dev/null", status=True) + section(f"filters:{netdev}", f"tc -j filter show dev {q(netdev)} ingress 2>/dev/null", status=True) + section("markers", f"pgrep -a -x -U 0 -u 0 {q(marker.comm)}", status=True) section("marker-binary", f"sha256sum {q(marker.path)} 2>/dev/null || true") section("marker-record", f"head -c 64 {q(marker.record)} 2>/dev/null || true") section("marker-owners", f"stat -c '%U %a %n' -- {' '.join(q(p) for p in marker.checked_paths)} " @@ -236,7 +257,7 @@ def route_get_script(destinations: Iterable[str]) -> str: def guard(hostname: str) -> str: """Stop the script unless it runs on ``hostname``.""" - if not _HOSTNAME.match(hostname): + if not _HOSTNAME.fullmatch(hostname): raise FabricError(f"host name {hostname!r} cannot be checked safely") return (f'test "$(hostname)" = {q(hostname)} || ' f'{{ echo {q("refusing: this host is not " + hostname)} >&2; exit 3; }}') @@ -280,9 +301,14 @@ def route_replace(destination: str, netdev: str, source: str, *, bindings: model f"scope link proto {ROUTE_PROTOCOL}") -def route_del(destination: str, netdev: str, *, protocol: int | None, metric: int = 0, bindings: model.FabricBindings = model.DEFAULT_BINDINGS) -> str: - """Delete one /32 route; naming its protocol makes the kernel refuse any other route.""" - command = f"sudo -n ip route del {_ipv4(destination)}/32 dev {_netdev(netdev, bindings=bindings)}" +def route_del(destination: str, netdev: str, *, protocol: int | None, metric: int = 0, prefixlen: int = 32, + bindings: model.FabricBindings = model.DEFAULT_BINDINGS) -> str: + """Delete one route (a /32 unless ``prefixlen`` says otherwise); naming its protocol makes the kernel + refuse any other route.""" + length = int(prefixlen) + if not 0 <= length <= 32: + raise FabricError(f"{length} is not an IPv4 prefix length") + command = f"sudo -n ip route del {_ipv4(destination)}/{length} dev {_netdev(netdev, bindings=bindings)}" if protocol is not None: command += f" proto {int(protocol)}" if metric: diff --git a/fabric-tool/fabric_tool/diff.py b/fabric-tool/fabric_tool/diff.py index b47edf6..e0429ca 100644 --- a/fabric-tool/fabric_tool/diff.py +++ b/fabric-tool/fabric_tool/diff.py @@ -28,12 +28,24 @@ Script order: qdiscs, relay filters, neighbours, routes, marker restarts, removal of stale routes and neighbours, qdisc removal, record. A changed filter or marker is deleted and re-created, which interrupts the lanes that -use it for well under a second; an unchanged object is not touched. +use it for well under a second; an unchanged object is not touched. A script +that adds ingress qdiscs first writes the record with every qdisc it is about +to own, so a run that fails later still leaves their ownership recorded and +``remove`` deletes them. + +Restore (``apply --boot``) adds what is missing and replaces a planned object +that differs; it removes nothing the plan does not name: stale routes, +neighbours, filters and qdiscs stay, and so do marker processes of a device +without planned rules and marker-named processes without a device. + +An object that carries the ownership mark on a device outside the fabric's +four is reported in a note and never touched. """ from __future__ import annotations import dataclasses +import posixpath from collections.abc import Sequence from . import commands, model @@ -98,6 +110,7 @@ def script(self) -> str | None: @dataclasses.dataclass class _Script: + record_first: list[str] = dataclasses.field(default_factory=list) qdisc_add: list[str] = dataclasses.field(default_factory=list) filter_del: list[str] = dataclasses.field(default_factory=list) filter_add: list[str] = dataclasses.field(default_factory=list) @@ -111,7 +124,7 @@ class _Script: record: list[str] = dataclasses.field(default_factory=list) def lines(self, hostname: str, *, check_hostname: bool = True) -> list[str]: - body = (self.qdisc_add + self.filter_del + self.filter_add + self.neigh_set + self.route_set + body = (self.record_first + self.qdisc_add + self.filter_del + self.filter_add + self.neigh_set + self.route_set + self.marker_stop + self.marker_start + self.route_del + self.neigh_del + self.qdisc_del + self.record) if not body: @@ -127,7 +140,8 @@ def _route_equal(entry: RouteEntry, destination: str, netdev: str, source: str) def _route_removal(entry: RouteEntry, bindings: model.FabricBindings) -> str: - return commands.route_del(entry.destination, entry.dev, protocol=entry.protocol, metric=entry.metric, bindings=bindings) + return commands.route_del(entry.destination, entry.dev, protocol=entry.protocol, metric=entry.metric, + prefixlen=entry.prefixlen, bindings=bindings) def _filter_removal(entries: Sequence[FilterEntry], bindings: model.FabricBindings) -> list[str]: @@ -156,6 +170,13 @@ def _common_blockers(diff: HostDiff, state: HostState, *, check_hostname: bool) if state.record is not None and state.record.get("group") != diff.group: diff.blockers.append(f"the host belongs to group {state.record.get('group')} (layout " f"{state.record.get('layout')}); remove that group with `remove` first") + # The comparison reads and changes the bound network devices only. Where the host binds a function to + # another one, the tool's objects are on interfaces this run did not read. + for device, netdev in zip(state.bindings.devices, state.bindings.netdevs): + found = state.rdma.get(device) + if found and found != netdev: + diff.blockers.append(f"RDMA device {device} is network device {found} on this host, not {netdev}; " + "pass the facts file that names the host's interfaces (--facts)") return False @@ -202,7 +223,14 @@ def _marker_blockers(state: HostState, marker: commands.MarkerConfig) -> list[st def _marker_changes(diff: HostDiff, script: _Script, state: HostState, host: HostPlan | None, - marker: commands.MarkerConfig) -> None: + marker: commands.MarkerConfig, *, remove_stale: bool = True) -> None: + """Marker processes to keep, start, replace or stop. + + A device with planned rules gets exactly one marker with those rules from + the checked executable; processes there that differ are replaced. Marker + processes the plan has no rules for (their device has none, or they name + no device) are stopped only with ``remove_stale``; restore retains them. + """ handled = set() for device in state.bindings.devices: planned = host.marker(device) if host is not None else None @@ -215,24 +243,53 @@ def _marker_changes(diff: HostDiff, script: _Script, state: HostState, host: Hos and present[0].problem is None and present[0].argv[:1] == (marker.path,): diff.changes.append(Change("marker", "keep", device, f"pid {present[0].pid}, {len(wanted)} rules")) continue - for process in present: - script.marker_stop.extend(commands.marker_stop(marker, process.pid)) if wanted: + for process in present: + script.marker_stop.extend(commands.marker_stop(marker, process.pid)) script.marker_start.extend(commands.marker_start(marker, device, planned.rules if planned else (), bindings=state.bindings)) before = "; ".join(process.text() + ("" if process.argv[:1] == (marker.path,) else f" (executable {process.argv[0]})") for process in present) diff.changes.append(Change("marker", "replace" if present else "add", device, f"{before} -> {rules_text}" if present else rules_text)) - elif present: + elif present and remove_stale: + for process in present: + script.marker_stop.extend(commands.marker_stop(marker, process.pid)) diff.changes.append(Change("marker", "remove", device, "; ".join(p.text() for p in present))) + elif present: + diff.notes.append(f"marker process(es) on {device}, which has no planned rules, are retained: " + + "; ".join(p.text() for p in present)) for process in state.markers: - if process.pid not in handled: + if process.pid in handled: + continue + if remove_stale: script.marker_stop.extend(commands.marker_stop(marker, process.pid)) diff.changes.append(Change("marker", "remove", f"pid {process.pid}", process.text())) + else: + diff.notes.append(f"a marker process without a fabric RDMA device is retained: {process.text()}") if script.marker_start: diff.blockers.extend(_marker_blockers(state, marker)) +def _recorded_marker_blocker(diff: HostDiff, state: HostState, marker: commands.MarkerConfig) -> None: + """Stop a removal that would not find the host's marker processes. + + Marker processes are found by the process name of ``--marker``. When the + record names an executable with another process name, ``remove`` would + leave its markers running as root and still report the host as clean. + """ + recorded = state.record.get("marker") if state.record else None + if not isinstance(recorded, str) or posixpath.basename(recorded)[:15] == marker.comm: + return + try: + commands.MarkerConfig(recorded) + except model.FabricError: + diff.notes.append(f"the record names the marker executable {recorded!r}, which --marker cannot name; " + "its marker processes, if any, are not found by this run") + return + diff.blockers.append(f"the record names the marker executable {recorded}; this run looks for processes " + f"named {marker.comm} and would leave that marker's running; pass --marker {recorded}") + + def _record(host: HostPlan, plan: GroupPlan, layout_name: str, marker: commands.MarkerConfig, qdiscs: Sequence[str]) -> dict[str, object]: return {"schema": commands.RECORD_SCHEMA, "host": host.name, "position": host.position, @@ -270,6 +327,14 @@ def _reconcile(state: HostState, host: HostPlan, plan: GroupPlan | None, *, layo script = _Script() removed_filters = {netdev: 0 for netdev in state.bindings.netdevs} + def off_fabric(what: str, dev: str) -> bool: + """Whether a marked object sits on a device outside the fabric's four (noted, never touched).""" + if dev in state.bindings.netdevs: + return False + diff.notes.append(f"{what} carries the ownership mark on {dev or 'no device'}, which is not a fabric " + "network device; it is not touched") + return True + # Relay filters (reserved preferences) and the ingress qdiscs they need. added_qdiscs = [] for netdev in state.bindings.netdevs: @@ -323,7 +388,7 @@ def _reconcile(state: HostState, host: HostPlan, plan: GroupPlan | None, *, layo if _route_equal(entry, destination, route.netdev, route.source)), None) in_place = equal or next((entry for entry in candidates if entry.metric == 0), None) for entry in candidates if policy.remove_stale else (): - if entry is not in_place: + if entry is not in_place and not off_fabric(f"route {entry.text()}", entry.dev): script.route_del.append(_route_removal(entry, state.bindings)) diff.changes.append(Change("route", "remove", f"{destination}/32", entry.text(), not entry.owned)) if equal is not None: @@ -337,9 +402,14 @@ def _reconcile(state: HostState, host: HostPlan, plan: GroupPlan | None, *, layo f"{in_place.text()} -> {want}" if in_place else want, bool(in_place and not in_place.owned))) for entry in state.relay_routes(): - if policy.remove_stale and entry.destination not in planned_routes: - script.route_del.append(_route_removal(entry, state.bindings)) - diff.changes.append(Change("route", "remove", f"{entry.destination}/32", entry.text(), not entry.owned)) + # A planned destination's /32 routes were handled above; every other owned or relay route is stale. + if not policy.remove_stale or (entry.prefixlen == 32 and entry.destination in planned_routes): + continue + if off_fabric(f"route {entry.text()}", entry.dev): + continue + script.route_del.append(_route_removal(entry, state.bindings)) + diff.changes.append(Change("route", "remove", f"{entry.destination}/{entry.prefixlen}", entry.text(), + not entry.owned)) planned_neighbours = {(route.destination, route.netdev): route.next_mac for route in host.routes} present_neighbours: dict[tuple[str, str], NeighbourEntry] = {} @@ -357,32 +427,49 @@ def _reconcile(state: HostState, host: HostPlan, plan: GroupPlan | None, *, layo diff.changes.append(Change("neighbour", "replace" if entry else "add", f"{destination} dev {netdev}", f"{entry.mac} -> {mac}" if entry else mac, bool(entry and not entry.owned))) for (destination, netdev), entry in sorted(present_neighbours.items()) if policy.remove_stale else (): + if off_fabric(f"neighbour {entry.text()}", netdev): + continue script.neigh_del.append(commands.neigh_del(destination, netdev, bindings=state.bindings)) diff.changes.append(Change("neighbour", "remove", f"{destination} dev {netdev}", entry.text(), not entry.owned)) - _marker_changes(diff, script, state, host, marker) + _marker_changes(diff, script, state, host, marker, remove_stale=policy.remove_stale) + if not policy.persist_record: + _recorded_marker_blocker(diff, state, marker) # Qdiscs the record lists as added by the tool and that no filter needs any more. record = state.record if state.record and state.record.get("group") == group else None - recorded = set(record.get("qdiscs", [])) if record else set() - kept = set(added_qdiscs) | recorded + listed = record.get("qdiscs", []) if record else [] + recorded = {netdev for netdev in listed if isinstance(netdev, str)} if isinstance(listed, list) else set() + owned = set(added_qdiscs) | recorded # every ingress qdisc the tool owns while the script runs + kept = set(owned) for netdev in sorted(recorded) if policy.remove_stale else (): + if netdev not in state.bindings.netdevs: + diff.notes.append(f"the record lists an ingress qdisc on {netdev}, which is not a fabric network " + "device of this run; it is not touched") + continue remaining = len(state.filters.get(netdev, [])) - removed_filters[netdev] if netdev not in host.filter_netdevs and remaining <= 0 and state.ingress_qdisc.get(netdev) == "ingress": script.qdisc_del.append(commands.qdisc_del(netdev, bindings=state.bindings)) kept.discard(netdev) diff.changes.append(Change("qdisc", "remove", netdev, "ingress qdisc added by the tool")) wanted_record = None + written_first = None if policy.persist_record: assert plan is not None wanted_record = _record(host, plan, layout_name, marker, sorted(kept)) + if added_qdiscs: + # Write-ahead: the script stops at its first failing command and the record is its last step, so + # a qdisc added by a run that failed later would belong to nobody and `remove` would leave it. + written_first = _record(host, plan, layout_name, marker, sorted(owned)) + script.record_first.extend(commands.record_write(written_first)) if state.record != wanted_record: if wanted_record is None: script.record.append(commands.record_remove()) diff.changes.append(Change("record", "remove", commands.RECORD_PATH, f"group {group}")) else: - script.record.extend(commands.record_write(wanted_record)) + if written_first != wanted_record: + script.record.extend(commands.record_write(wanted_record)) before = f"group {state.record.get('group')}" if state.record else "none" diff.changes.append(Change("record", "write", commands.RECORD_PATH, f"{before} -> group {group}, layout {layout_name}, plan {plan.digest}")) diff --git a/fabric-tool/fabric_tool/ops.py b/fabric-tool/fabric_tool/ops.py index 7c830dd..e731568 100644 --- a/fabric-tool/fabric_tool/ops.py +++ b/fabric-tool/fabric_tool/ops.py @@ -2,7 +2,7 @@ Derived from the SparkRing relay installer; see NOTICE. Every host is reached through an *executor*: a function that runs one ``bash -s`` -script and returns its exit code and output — over SSH +script and returns its exit code and output — over SSH (:func:`ssh_executor`, batch mode) or on this machine (:func:`local_executor`, the per-host run). The hosts of an operation are contacted in parallel. @@ -58,7 +58,8 @@ class HostTarget: def ssh_executor(target: str, script: str, timeout: float) -> Result: """Run ``script`` with ``bash -s`` on ``target`` (batch-mode SSH, deadline ``timeout``).""" - argv = ["ssh", *SSH_OPTIONS, target, "bash -s"] + # ``--`` ends ssh's options: a target that starts with ``-`` is a host name, never an option. + argv = ["ssh", *SSH_OPTIONS, "--", target, "bash -s"] try: process = subprocess.run(argv, input=script.encode(), capture_output=True, timeout=timeout) except subprocess.TimeoutExpired: @@ -140,6 +141,23 @@ def cable_problems(group: GroupSpec, facts: Facts) -> list[str]: return problems +def unchecked_cables(group: GroupSpec, facts: Facts) -> list[str]: + """Links :func:`cable_problems` could not check: an end's facts give its address without a prefix + length, so its subnet is unknown. Reported, so a skipped cabling check is never a silent pass.""" + skipped = [] + for cable in group.layout.fabric.cables: + for secondary in (False, True): + here = facts.port(cable.a, facts.bindings.role_at(cable.a_port, secondary).netdev) + there = facts.port(cable.b, facts.bindings.role_at(cable.b_port, secondary).netdev) + if here.network() is None or there.network() is None: + skipped.append(f"{cable.text} ({model.class_name(secondary)})") + if not skipped: + return [] + return [f"the cabling check was skipped for {len(skipped)} link(s) ({', '.join(skipped)}): the facts give " + "their addresses without prefix lengths, so the topology's host order was not compared with the " + "cabling (`facts` writes addresses with prefix lengths)"] + + @dataclasses.dataclass class Outcome: """A comparison of the topology's hosts with the plan (``up``/``boot``) or their removal (``down``).""" @@ -151,6 +169,7 @@ class Outcome: diffs: list[diff_mod.HostDiff] = dataclasses.field(default_factory=list) problems: list[str] = dataclasses.field(default_factory=list) facts: Facts | None = None + notes: list[str] = dataclasses.field(default_factory=list) @property def blocked(self) -> bool: @@ -206,6 +225,7 @@ def evaluate(topology: Topology, states: dict[int, HostState], file_facts: Facts if not problems: try: problems += cable_problems(group, facts) + outcome.notes.extend(unchecked_cables(group, facts)) if not problems: plan = build_plan(group, facts, max_relays=max_relays) except FabricError as error: diff --git a/fabric-tool/fabric_tool/plan.py b/fabric-tool/fabric_tool/plan.py index ddccf6f..ceacb7c 100644 --- a/fabric-tool/fabric_tool/plan.py +++ b/fabric-tool/fabric_tool/plan.py @@ -205,7 +205,7 @@ def port_from_text(netdev: str, mac: str, address: str, *, owner: str) -> Port: """A validated :class:`Port` from a MAC and ``a.b.c.d`` or ``a.b.c.d/len``.""" model.device_name(netdev) mac = mac.strip().lower() - if not _MAC.match(mac): + if not _MAC.fullmatch(mac): raise FabricError(f"{owner} {netdev}: {mac!r} is not a MAC address") try: if "/" in address: @@ -499,7 +499,8 @@ def build_group_plan(group: GroupSpec, facts: Facts, *, relay_egress: str, by_position = {host.position: host for host in hosts} for host in hosts: for route in host.routes: - result = trace(by_position, facts, group.ring_size, host.position, route.destination) + result = trace(by_position, facts, group.ring_size, host.position, route.destination, + fabric=layout.fabric) if result.outcome != "delivered" or result.hops[-1] != (route.peer, route.peer_netdev): raise FabricError(f"group {group.label}: the route from {host.name} to {route.destination} does " f"not deliver through the plan's relays ({result.outcome}: {result.detail})") @@ -544,12 +545,16 @@ class Trace: def trace(hosts: Mapping[int, HostPlan], facts: Facts, ring_size: int, origin: int, destination: str, - *, limit: int = 2 * MAX_TAG) -> Trace: + *, limit: int = 2 * MAX_TAG, fabric: model.Fabric | None = None) -> Trace: """Follow a frame from ``origin`` to ``destination`` through the plan's objects on the cabling. - Port 0 of position ``i`` is cabled to port 1 of position ``i + 1``. A frame - is received by the function whose MAC it carries on the far end of the - cable; a tagged frame continues only through a relay filter for its tag. + With ``fabric`` the frame crosses that fabric's cables, whatever ports + they join (the cables of the topology, including ``cabling explicit``); + a frame that leaves through a port without a cable is dropped. Without it + the cabling is a ring of ``ring_size``: port 0 of position ``i`` is cabled + to port 1 of position ``i + 1``. A frame is received by the function whose + MAC it carries on the far end of the cable; a tagged frame continues only + through a relay filter for its tag. """ host = hosts.get(origin) route = host.route_to(destination) if host is not None else None @@ -559,11 +564,18 @@ def trace(hosts: Mapping[int, HostPlan], facts: Facts, ring_size: int, origin: i hops: list[tuple[int, str]] = [] for _ in range(limit): port = facts.bindings.role_of_netdev(out_netdev).port - there = (here + 1) % ring_size if port == 0 else (here - 1) % ring_size + if fabric is None: + there, far_port = ((here + 1) % ring_size if port == 0 else (here - 1) % ring_size), 1 - port + else: + step = fabric.cross(here, port) + if step is None: + return Trace("dropped", tuple(hops), f"a frame for {mac} leaves position {here} port {port}, " + "which has no cable") + there, far_port = step.dst, step.dst_port receiver = facts.find_mac(mac) - if receiver is None or receiver[0] != there or facts.bindings.role_of_netdev(receiver[1]).port != 1 - port: + if receiver is None or receiver[0] != there or facts.bindings.role_of_netdev(receiver[1]).port != far_port: return Trace("misdelivered", tuple(hops), f"a frame for {mac} leaves position {here} port {port}; " - f"the cable ends at position {there} port {1 - port}") + f"the cable ends at position {there} port {far_port}") hops.append(receiver) netdev = receiver[1] k = relays_left(ethertype) diff --git a/fabric-tool/fabric_tool/report.py b/fabric-tool/fabric_tool/report.py index e209b1d..5d99697 100644 --- a/fabric-tool/fabric_tool/report.py +++ b/fabric-tool/fabric_tool/report.py @@ -142,6 +142,8 @@ def render_outcome(outcome: Outcome, *, verbose: bool = False, scripts: bool = F lines = [f"group {group.label} ({group.name}, relay egress {group.relay_egress}); {outcome.mode}"] for problem in outcome.problems: lines.append(f"PROBLEM: {problem}") + for note in outcome.notes: + lines.append(f"NOTE: {note}") if outcome.plan is not None: plan = outcome.plan bound = (f"per-peer op sizes at or below {plan.per_peer_bytes} bytes (busiest relay queue " diff --git a/fabric-tool/fabric_tool/state.py b/fabric-tool/fabric_tool/state.py index 91fbd9d..f5b9547 100644 --- a/fabric-tool/fabric_tool/state.py +++ b/fabric-tool/fabric_tool/state.py @@ -6,12 +6,13 @@ the host name, the iproute2 versions, ``ip -j addr show``, the network device of each RDMA device, ``ip -j -d route show table main``, ``ip -j neigh show nud permanent``, ``tc -j qdisc show`` and -``tc -j filter show ... ingress`` of the four fabric network devices, the -marker processes (``pgrep -a -x``), the marker executable's SHA-256, the +``tc -j filter show ... ingress`` of the four fabric network devices, root's +marker processes (``pgrep -a -x -U 0 -u 0``), the marker executable's SHA-256, the digest its install recorded, the owner and mode of the executable, that record and every directory above them, the head of every marker log, the tool's record and SparkRing's installer record. -:func:`parse` turns them into a :class:`HostState`. +:func:`parse` turns them into a :class:`HostState`. A missing tool or a failed +read is a parse problem (:func:`read_failures`), never an empty section. Classification of what the host holds: @@ -265,13 +266,15 @@ def parse_routes(text: str, problems: list[str]) -> list[RouteEntry]: address, length = "0.0.0.0", 0 elif "/" in destination: address, _, length_text = destination.partition("/") - length = int(length_text) if length_text.isdigit() else -1 + length = int(length_text) if length_text.isascii() and length_text.isdigit() else -1 else: address, length = destination, 32 try: ipaddress.IPv4Address(address) except ValueError: continue + if not 0 <= length <= 32: + continue protocol_text = str(entry.get("protocol", "boot")) found.append(RouteEntry(address, length, str(entry.get("dev", "")), entry.get("prefsrc"), str(entry.get("scope", "global")), protocol_number(protocol_text), protocol_text, @@ -283,6 +286,11 @@ def parse_routes(text: str, problems: list[str]) -> list[RouteEntry]: def parse_neighbours(text: str, problems: list[str]) -> list[NeighbourEntry]: found = [] for entry in _json_list(text, "ip -j neigh show", problems): + # The read lists every address family; like the routes, only IPv4 entries can be relay objects. + try: + ipaddress.IPv4Address(str(entry.get("dst", ""))) + except ValueError: + continue states = entry.get("state", []) states = tuple(states) if isinstance(states, list) else (str(states),) protocol_text = str(entry.get("protocol", "")) if entry.get("protocol") is not None else "" @@ -520,19 +528,67 @@ def unowned_relay_objects(self) -> tuple[list[RouteEntry], list[NeighbourEntry]] [neighbour for neighbour in self.relay_neighbours() if not neighbour.owned]) -def parse_sections(stdout: str) -> dict[str, str]: - """``@@`` blocks of a script's output, by name.""" +def parse_sections(stdout: str, repeated: list[str] | None = None) -> dict[str, str]: + """``@@`` blocks of a script's output, by name. + + The first block of a name is the section. A later header of the same name + never replaces it: the lines under it are dropped and the name is appended + to ``repeated``, so output printed inside a later section cannot rewrite + an earlier one. + """ sections: dict[str, list[str]] = {} current = None for line in stdout.splitlines(): if line.startswith(commands.SECTION): - current = line[len(commands.SECTION):].strip() - sections[current] = [] + name = line[len(commands.SECTION):].strip() + if name in sections: + current = None + if repeated is not None and name not in repeated: + repeated.append(name) + else: + current = name + sections[current] = [] elif current is not None: sections[current].append(line) return {key: "\n".join(value) for key, value in sections.items()} +def _exit_status(raw: Mapping[str, str], section: str) -> int | None: + """The exit status the read script recorded for ``section``; None when it recorded none.""" + words = raw.get(commands.STATUS_PREFIX + section, "").split() + return int(words[0]) if len(words) == 1 and words[0].isascii() and words[0].isdigit() else None + + +def read_failures(raw: Mapping[str, str], bindings: model.FabricBindings) -> list[str]: + """Reads whose empty output must not be taken for a host that holds nothing. + + A tool the read account cannot run; a failed read of the addresses, the + routes or the permanent neighbours; a ``tc`` that could not be executed + (exit 126 or 127; any other failure of ``tc`` is how a device without an + ingress qdisc may answer, so it is not judged); and a ``pgrep`` that + failed (exit 1 only says that no process matched). + """ + found = [f"the read account cannot run {tool}: it is not on its PATH, so nothing {tool} reports was read" + for tool in commands.READ_TOOLS if tool in raw.get("tools", "").split()] + for section, command in (("links", "ip -j addr show"), ("routes", "ip -j -d route show table main"), + ("neighbours", "ip -j neigh show nud permanent")): + status = _exit_status(raw, section) + if status != 0: + found.append(f"{command} " + (f"failed with exit status {status}" if status is not None + else "reported no exit status") + "; its output was not read") + for netdev in bindings.netdevs: + for section, command in ((f"qdisc:{netdev}", f"tc -j qdisc show dev {netdev}"), + (f"filters:{netdev}", f"tc -j filter show dev {netdev} ingress")): + status = _exit_status(raw, section) + if status in (126, 127): + found.append(f"{command} could not be executed (exit status {status}); its output was not read") + status = _exit_status(raw, "markers") + if status not in (0, 1): + found.append("pgrep " + (f"failed with exit status {status}" if status is not None + else "reported no exit status") + "; the marker processes were not read") + return found + + def _parse_record(text: str, schema: str, problems: list[str], what: str) -> dict | None: record_text = text.strip() if not record_text: @@ -550,7 +606,8 @@ def _parse_record(text: str, schema: str, problems: list[str], what: str) -> dic def parse(position: int, name: str, ssh: str, *, returncode: int, stdout: str, stderr: str, bindings: model.FabricBindings = model.DEFAULT_BINDINGS) -> HostState: """The :class:`HostState` of one host from its read script's output.""" state = HostState(position, name, ssh, reachable=True, bindings=bindings) - sections = parse_sections(stdout) + repeated: list[str] = [] + sections = parse_sections(stdout, repeated) if "end" not in sections: state.reachable = bool(sections) detail = (stderr.strip().splitlines() or [f"exit code {returncode}"])[-1] @@ -561,6 +618,10 @@ def parse(position: int, name: str, ssh: str, *, returncode: int, stdout: str, s state.raw = sections raw = state.raw problems = state.parse_problems + # No read prints a section header twice: a repeated one is output that imitates the script. + problems.extend(f"the read printed the section {section!r} more than once; only the first was used" + for section in repeated) + problems.extend(read_failures(raw, bindings)) state.hostname = raw.get("hostname", "").strip() state.versions = " | ".join(line.strip() for line in raw.get("versions", "").splitlines() if line.strip()) state.links = parse_links(raw.get("links", ""), problems) diff --git a/fabric-tool/fabric_tool/topology.py b/fabric-tool/fabric_tool/topology.py index bf4dd3d..f4852f0 100644 --- a/fabric-tool/fabric_tool/topology.py +++ b/fabric-tool/fabric_tool/topology.py @@ -4,29 +4,40 @@ (``transport-core/src/topology.c``); this parser accepts the same keys and defaults: -- ``hosts ...``: host names in position order; +- ``hosts ...``: host names in position order, at most 64, each of 1 to + 63 bytes; - ``cabling ring`` / ``path`` / ``explicit``: ``ring`` cables host ``i``'s port 0 to host ``i+1``'s port 1 and the last host to the first; ``path`` - leaves the closing cable out; ``explicit`` takes only ``cable`` lines; + leaves the closing cable out; ``explicit`` takes only ``cable`` lines. Two + hosts have one cable, ``0.port0-1.port1``, under ``ring`` as under ``path``; + a pair joined by two cables is written with ``explicit`` and two ``cable`` + lines; - ``cable .port

.port``: one cable (repeatable, ``explicit``); + the cables may join the hosts in any order and through either port, as + long as they form one path or one cycle; - ``port0 `` / ``port1 ``: the RDMA functions of each port in lane order (lane 0 first). The defaults are the DGX OS names ``rocep1s0f0 roceP2p1s0f0`` and ``rocep1s0f1 roceP2p1s0f1``; -- ``relay_budget ``: the plugin's window toward a relayed peer; the - tool carries it for reference (its own queue bound is the measured - 512 KiB hairpin queue); +- ``relay_budget ``: the plugin's window toward a relayed peer, in + ASCII decimal digits; the tool carries it for reference (its own queue + bound is the measured 512 KiB hairpin queue); - ``net-sircl-topology``: the file's optional first key, as the plugin reads it. :func:`load` returns a validated :class:`Topology` with immutable device bindings. Its :attr:`Topology.group` is the one group the tool plans: the fabric of the topology's cables over positions 0..N-1, whole cycle or path, with the relay-egress default (``same`` for a whole cycle, -``sibling`` otherwise). +``sibling`` otherwise). The group's layout name (:attr:`Topology.layout_name`) +is derived from the hosts, cables and functions, not from the file's path, so +the same topology read from two files names the same layout. """ from __future__ import annotations import dataclasses +import hashlib +import json +import re from pathlib import Path from . import model @@ -36,17 +47,21 @@ DEFAULT_FUNCTIONS = ("rocep1s0f0", "roceP2p1s0f0", "rocep1s0f1", "roceP2p1s0f1") DEFAULT_NETDEVS = ("enp1s0f0np0", "enP2p1s0f0np0", "enp1s0f1np1", "enP2p1s0f1np1") CABLING_KINDS = ("ring", "path", "explicit") +MAX_HOSTS = 64 # the plugin's position limit +MAX_HOST_NAME_BYTES = 63 # the plugin stores a host name in 64 bytes +_DECIMAL = re.compile(r"[0-9]+") @dataclasses.dataclass(frozen=True) class GroupSpec: """The one group a topology file describes. - ``ring_size`` bounds the forwarding trace: the + ``ring_size`` bounds a forwarding trace that is not given the fabric: the whole cycle is a ring of its own size, a path sits on a ring one Spark longer (the wrap position has no facts, so a frame that left the path's - end could never be delivered). The attribute names match the plan - derivation's group interface. + end could never be delivered). The plan's own trace follows the fabric's + cables instead. The attribute names match the plan derivation's group + interface. """ layout: Layout @@ -127,6 +142,20 @@ def bindings(self) -> model.FabricBindings: def size(self) -> int: return len(self.hosts) + @property + def layout_name(self) -> str: + """The layout's name in reports and in the hosts' ownership record: a digest of the hosts, the + cables and the function names. + + It does not depend on the file's path, on the order or spelling of the + ``cable`` lines or on the relay budget, so a workstation and a boot + unit that read copies of one topology write the same record. + """ + cables = sorted(sorted([[cable.a, cable.a_port], [cable.b, cable.b_port]]) for cable in self.cables) + content = json.dumps({"hosts": list(self.hosts), "cables": cables, "functions": list(self.functions)}, + sort_keys=True, separators=(",", ":")) + return "topology:" + hashlib.sha256(content.encode("utf-8")).hexdigest()[:12] + def position_of(self, name: str) -> int: """The position of a host name, or -1 when the topology does not name it.""" try: @@ -187,7 +216,7 @@ def parse(text: str, *, path: str = "") -> Topology: for lane, name in enumerate(rest[:2]): functions[2 * port + lane] = name elif key == "relay_budget": - if len(rest) != 1 or not rest[0].isdigit() or int(rest[0]) == 0: + if len(rest) != 1 or not _DECIMAL.fullmatch(rest[0]) or int(rest[0]) == 0: raise FabricError(f"{path}:{lineno}: relay_budget is a positive byte count") budget = int(rest[0]) elif key == "net-sircl-topology": @@ -197,12 +226,18 @@ def parse(text: str, *, path: str = "") -> Topology: raise FabricError(f"{path}:{lineno}: unknown key {key}") if len(hosts) < 2: raise FabricError(f"{path}: `hosts` names fewer than two hosts") + if len(hosts) > MAX_HOSTS: + raise FabricError(f"{path}: `hosts` names {len(hosts)} hosts; at most {MAX_HOSTS} are supported") + for name in hosts: + if len(name.encode("utf-8")) > MAX_HOST_NAME_BYTES: + raise FabricError(f"{path}: host name {name!r} is longer than {MAX_HOST_NAME_BYTES} bytes") if len(set(hosts)) != len(hosts): raise FabricError(f"{path}: `hosts` names a host twice") if cabling not in CABLING_KINDS: raise FabricError(f"{path}: cabling is {', '.join(CABLING_KINDS)}") if cabling in ("ring", "path"): - last = len(hosts) if cabling == "ring" else len(hosts) - 1 + # A pair has one cable between its two hosts: a two-host ring is a two-host path. + last = len(hosts) if cabling == "ring" and len(hosts) > 2 else len(hosts) - 1 for i in range(last): cables.append(Cable(i, 0, (i + 1) % len(hosts), 1)) if len(set(functions)) != 4: @@ -242,7 +277,7 @@ def _group_of(topology: Topology) -> GroupSpec: fabric = Fabric(topology.cables) layout = Layout(fabric, tuple(range(topology.size))) egress = "same" if fabric.kind == "cycle" else "sibling" - return GroupSpec(layout, egress, f"topology:{Path(topology.path).name}", topology.bindings) + return GroupSpec(layout, egress, topology.layout_name, topology.bindings) def load(path: str | Path) -> Topology: diff --git a/fabric-tool/tests/test_review_fixes.py b/fabric-tool/tests/test_review_fixes.py new file mode 100644 index 0000000..381af81 --- /dev/null +++ b/fabric-tool/tests/test_review_fixes.py @@ -0,0 +1,656 @@ +"""Regressions for the review findings: spoofed or failed reads, record identity, explicit cabling, +restore policy, objects the command builders refuse, boot unit handling and qdisc ownership. + +Hosts are synthetic. Bash tests run the read script against shell functions only; no host command, +SSH, sudo or systemctl runs. +""" +from __future__ import annotations + +import dataclasses +import ipaddress +import json +import shlex +import shutil +import subprocess +from pathlib import Path + +import pytest + +from fabric_tool import boot, cli, commands, diff, facts as facts_mod, model, ops, plan, report, state, topology +from fabric_tool.model import FabricError +from test_commands import READ_STUBS +from test_facts import RING4, _document +from test_marker_security import environment # noqa: F401 (fixture) + +MARKER = commands.MarkerConfig() +PATH4 = "hosts node-0 node-1 node-2 node-3\ncabling path\n" +NETDEVS = model.FABRIC_NETDEVS + + +def healthy(text: str = RING4, path: str = "/srv/site/ring4.topology"): + """Hosts that hold exactly their part of the plan, as a read would report them.""" + topo = topology.parse(text, path=path) + document = _document() + bound = facts_mod.bind(document, topo) + built = plan.build_plan(topo.group, bound) + states = {} + for host in built.hosts: + s = state.HostState(host.position, host.name, host.name, True, hostname=host.name) + for device, function in document["hosts"][host.position]["functions"].items(): + address = ipaddress.ip_interface(function["address"]) + s.rdma[device] = function["netdev"] + s.links[function["netdev"]] = state.Link(function["netdev"], function["mac"], + ((str(address.ip), address.network.prefixlen),), "UP") + for f in host.filters: + s.ingress_qdisc[f.in_netdev] = "ingress" + s.filters.setdefault(f.in_netdev, []).append(state.FilterEntry( + f.in_netdev, f.pref, 0, "flower", f.protocol, f.handle, True, True, f.next_mac, f.new_type, + f.out_netdev, None)) + for r in host.routes: + s.routes.append(state.RouteEntry(r.destination, 32, r.netdev, r.source, "link", 82, "82", 0, None, + "unicast")) + s.neighbours.append(state.NeighbourEntry(r.destination, r.netdev, r.next_mac, ("PERMANENT",), 82, "82")) + for device in model.RDMA_DEVICES: + rules = host.marker(device) + if rules: + s.markers.append(state.MarkerProcess(100 + len(s.markers), (MARKER.path,), device, + frozenset(rules.rules), True, None)) + s.marker_binary = s.marker_recorded = "a" * 64 + s.marker_owners = {p: ("root", 0o755) for p in (*MARKER.checked_paths, *MARKER.log_dirs)} + s.record = diff._record(host, built, topo.group.name, MARKER, []) + states[host.position] = s + return topo, bound, built, states + + +def evaluate(topo, states, bound, mode): + return ops.evaluate(topo, states, bound, mode=mode, marker=MARKER, adopt=False) + + +def read_output(name: str = "node-0", **sections: str) -> str: + """A complete read of a host that holds nothing; keyword ``exit_links="2"`` or ``tools="tc"`` overrides + a section (``_`` stands for ``:``).""" + blocks = {"hostname": name, "tools": "", "links": "[]", "exit:links": "0", "routes": "[]", "exit:routes": "0", + "neighbours": "[]", "exit:neighbours": "0"} + for netdev in NETDEVS: + blocks.update({f"qdisc:{netdev}": "[]", f"exit:qdisc:{netdev}": "0", + f"filters:{netdev}": "", f"exit:filters:{netdev}": "0"}) + blocks.update({"markers": "", "exit:markers": "1"}) + for key, value in sections.items(): + blocks[key.replace("_", ":")] = value + return "".join(f"@@{key}\n{value}\n" for key, value in blocks.items()) + "@@end\n" + + +def parsed(**sections: str) -> state.HostState: + return state.parse(0, "node-0", "node-0", returncode=0, stdout=read_output(**sections), stderr="") + + +# -- 1. marker liveness and section headers ---------------------------------------------------------------- + + +def test_only_processes_of_root_are_read_as_markers(): + script = commands.read_script(MARKER) + assert "pgrep -a -x -U 0 -u 0 fabric-tool-mar" in script.splitlines() + assert not any(line.startswith("pgrep") and "-U 0 -u 0" not in line for line in script.splitlines()) + + +def test_a_repeated_section_header_never_replaces_the_first(): + spoofed_route = json.dumps([{"dst": "203.0.113.9", "dev": NETDEVS[0], "protocol": "82", "scope": "link"}]) + # Output inside the markers section imitates the script: an earlier section and its own section. + host = parsed(markers=f"31337 x\n@@routes\n{spoofed_route}\n@@markers\n") + assert host.routes == [] + assert [process.pid for process in host.markers] == [31337] + assert any("'routes' more than once" in problem for problem in host.parse_problems) + assert any("'markers' more than once" in problem for problem in host.parse_problems) + repeated: list[str] = [] + sections = state.parse_sections("@@a\n1\n@@b\n2\n@@a\n3\n4\n@@c\n5\n", repeated) + assert sections == {"a": "1", "b": "2", "c": "5"} and repeated == ["a"] + # The repeated header blocks the host instead of passing as a clean read. + blocked = diff.compare_down(host, group="cycle:0-1-2-3", marker=MARKER, adopt=False) + assert any("more than once" in blocker for blocker in blocked.blockers) + assert parsed().parse_problems == [] + + +# -- 2. the record does not depend on the topology file's path ------------------------------------------- + + +def test_workstation_and_boot_unit_agree_on_the_record(): + topo, bound, _, states = healthy(RING4, "/srv/site/ring4.topology") + assert not evaluate(topo, states, bound, "up").pending + unit = topology.parse(RING4, path=boot.TOPOLOGY_INPUT) + for mode in ("up", "boot"): + outcome = evaluate(unit, states, facts_mod.bind(_document(), unit), mode) + assert not outcome.pending and not outcome.blocked + assert states[0].record["layout"] == topo.layout_name == unit.layout_name + + +def test_a_record_of_the_old_file_name_layout_converges_in_one_apply(): + topo, bound, _, states = healthy() + for host in states.values(): + host.record = dict(host.record, layout="topology:ring4.topology") + outcome = evaluate(topo, states, bound, "up") + assert not outcome.blocked and outcome.host_changes == 0 + for host_diff in outcome.diffs: + assert [(c.kind, c.action) for c in host_diff.pending] == [("record", "write")] + line = next(line for line in host_diff.commands if "tee " + commands.RECORD_PATH in line) + states[host_diff.position].record = json.loads(shlex.split(line)[2]) + assert not evaluate(topo, states, bound, "up").pending + + +# -- 3. explicit cabling --------------------------------------------------------------------------------- + +PERMUTED = "hosts a b c d\ncabling explicit\ncable 0.port0 2.port1\ncable 2.port0 1.port1\ncable 1.port0 3.port1\n" +MIRRORED = "hosts a b c\ncabling explicit\ncable 0.port1 1.port0\ncable 1.port1 2.port0\n" +WRAPPED = "hosts a b c d\ncabling explicit\ncable 1.port0 2.port1\ncable 2.port0 3.port1\ncable 3.port0 0.port1\n" +EXPLICIT_RING = ("hosts a b c d\ncabling explicit\ncable 0.port0 2.port1\ncable 2.port0 1.port0\n" + "cable 1.port1 3.port1\ncable 3.port0 0.port1\n") + + +def cable_facts(topo: topology.Topology): + """One /30 per cable and function class; functions without a cable get subnets of their own.""" + addresses = {} + for index, cable in enumerate(topo.cables): + for secondary in (False, True): + subnet = 4 * (2 * index + int(secondary)) + addresses[(cable.a, model.role_at(cable.a_port, secondary).netdev)] = f"192.0.2.{subnet + 1}/30" + addresses[(cable.b, model.role_at(cable.b_port, secondary).netdev)] = f"192.0.2.{subnet + 2}/30" + hosts, spare = [], 0 + for position, name in enumerate(topo.hosts): + functions = {} + for role in model.ROLES: + address = addresses.get((position, role.netdev)) + if address is None: + address, spare = f"198.51.100.{4 * spare + 1}/30", spare + 1 + functions[role.device] = {"netdev": role.netdev, "address": address, + "mac": f"02:00:{position:02x}:{role.port:02x}:{int(role.secondary):02x}:01"} + hosts.append({"name": name, "functions": functions}) + return facts_mod.bind({"schema": facts_mod.FACTS_SCHEMA, "hosts": hosts}, topo) + + +@pytest.mark.parametrize("text,label", [(PERMUTED, "path:0-2-1-3"), (MIRRORED, "path:0-1-2"), + (WRAPPED, "path:0-3-2-1"), (EXPLICIT_RING, "cycle:0-2-1-3")]) +def test_explicit_cabling_is_planned_and_every_route_is_delivered(text, label): + topo = topology.parse(text) + assert topo.group.label == label + bound = cable_facts(topo) + assert ops.cable_problems(topo.group, bound) == [] + built = plan.build_plan(topo.group, bound) + hosts = {host.position: host for host in built.hosts} + fabric = topo.group.layout.fabric + routes = [(host, route) for host in built.hosts for route in host.routes] + assert routes and any(host.filters for host in built.hosts) + for host, route in routes: + result = plan.trace(hosts, bound, topo.group.ring_size, host.position, route.destination, fabric=fabric) + assert result.outcome == "delivered", (host.name, route.destination, result) + assert result.hops[-1] == (route.peer, route.peer_netdev) + assert [position for position, _ in result.hops[:-1]] == list(route.relays) + assert bound.port(route.peer, route.peer_netdev).address == route.destination + # Every pair of hosts without a common cable is reachable on both function classes. + for origin in range(topo.size): + for target in range(topo.size): + if origin != target and len(fabric.shortest_paths(origin, target)[0]) > 1: + reached = {(r.peer, r.peer_netdev) for r in hosts[origin].routes if r.peer == target} + assert {model.role_of_netdev(netdev).secondary for _, netdev in reached} == {False, True} + + +def test_trace_follows_the_cables_it_is_given(): + topo = topology.parse(PERMUTED) + bound = cable_facts(topo) + built = plan.build_plan(topo.group, bound) + hosts = {host.position: host for host in built.hosts} + route = built.host(0).routes[0] + # Without the fabric the trace assumes ring order, which these cables do not have. + assert plan.trace(hosts, bound, topo.group.ring_size, 0, route.destination).outcome == "misdelivered" + # A relay filter that sends the frame out of a port without a cable is found by the trace. + end = built.host(3) + stray = plan.RelayFilter(model.role_at(1, False).netdev, 1, model.role_at(0, False).netdev, + "02:00:00:00:00:01", 0, model.role_at(1, False).netdev, "cw", "primary") + lost = dict(hosts) + lost[3] = dataclasses.replace(end, filters=(stray,)) + sender = dataclasses.replace(built.host(1), routes=(dataclasses.replace( + built.host(1).routes[0], destination="192.0.2.250", netdev=model.role_at(0, False).netdev, + next_mac=bound.port(3, model.role_at(1, False).netdev).mac, tag=plan.tag(1)),)) + lost[1] = sender + result = plan.trace(lost, bound, topo.group.ring_size, 1, "192.0.2.250", fabric=topo.group.layout.fabric) + assert result.outcome == "dropped" and "no cable" in result.detail + + +# -- 4. failed reads are not empty hosts ----------------------------------------------------------------- + + +def test_read_script_reports_missing_tools_and_exit_statuses(): + lines = commands.read_script(MARKER).splitlines() + assert ('for tool in ip tc pgrep sha256sum stat head; do command -v "$tool" >/dev/null 2>&1 || ' + 'echo "$tool"; done') in lines + for command, section in (("ip -j addr show", "links"), ("ip -j -d route show table main", "routes"), + ("ip -j neigh show nud permanent", "neighbours"), + (f"tc -j qdisc show dev {NETDEVS[0]} 2>/dev/null", f"qdisc:{NETDEVS[0]}"), + (f"tc -j filter show dev {NETDEVS[3]} ingress 2>/dev/null", f"filters:{NETDEVS[3]}"), + ("pgrep -a -x -U 0 -u 0 fabric-tool-mar", "markers")): + at = lines.index(command) + assert lines[at + 1:at + 6] == ["status=$?", "echo", f"echo @@exit:{section}", 'echo "$status"', "echo"] + assert "sudo" not in "\n".join(lines) + + +@pytest.mark.parametrize("sections,expected", [ + ({"tools": "tc"}, "cannot run tc"), + ({"tools": "pgrep\nsha256sum"}, "cannot run pgrep"), + ({"exit_links": "1"}, "ip -j addr show failed with exit status 1"), + ({"exit_routes": "2"}, "ip -j -d route show table main failed with exit status 2"), + ({"exit_neighbours": "127"}, "ip -j neigh show nud permanent failed with exit status 127"), + ({"exit_routes": ""}, "ip -j -d route show table main reported no exit status"), + ({f"exit_qdisc_{NETDEVS[1]}": "127"}, f"tc -j qdisc show dev {NETDEVS[1]} could not be executed"), + ({f"exit_filters_{NETDEVS[2]}": "126"}, f"tc -j filter show dev {NETDEVS[2]} ingress could not be executed"), + ({"exit_markers": "2"}, "pgrep failed with exit status 2"), + ({"exit_markers": "127"}, "pgrep failed with exit status 127"), +]) +def test_a_failed_read_is_a_problem_that_blocks_the_host(sections, expected): + host = parsed(**sections) + assert any(expected in problem for problem in host.parse_problems), host.parse_problems + removal = diff.compare_down(host, group="cycle:0-1-2-3", marker=MARKER, adopt=False) + assert removal.blocked and any(expected in blocker for blocker in removal.blockers) + assert any(expected in problem for problem in host.fact_problems(check_hostname=False)) + + +@pytest.mark.parametrize("sections", [ + {}, + {"exit_markers": "0", "markers": f"4100 {MARKER.path} --device rocep1s0f0 --rule 192.0.2.10=0x88b5 --managed"}, + {f"exit_qdisc_{NETDEVS[0]}": "1", f"exit_filters_{NETDEVS[0]}": "2"}, # tc's own failures are not judged + {f"exit_qdisc_{NETDEVS[0]}": "255"}, +]) +def test_reads_that_legitimately_find_nothing_are_not_problems(sections): + assert parsed(**sections).parse_problems == [] + + +@pytest.mark.parametrize("command", ["remove", "verify", "apply"]) +def test_cli_refuses_hosts_whose_tc_cannot_run(tmp_path, capsys, command): + path = tmp_path / "ring.topology" + path.write_text(RING4) + facts = tmp_path / "facts.json" + facts.write_text(json.dumps(_document())) + argv = [command, "--topology", str(path), "--facts", str(facts)] + for position in range(4): + argv += ["--ssh", f"node-{position}=node-{position}"] + + def executor(target, script, timeout): + assert script.startswith("set -u\n"), "a host whose read failed was changed" + if "@@hostname" not in script: + return ops.Result(0, "@@end\n", "") + return ops.Result(0, read_output(target, tools="tc", **{f"exit_qdisc_{n}": "127" for n in NETDEVS}), "") + + assert cli.main(argv + ([] if command == "verify" else ["--execute"]), executor=executor) == 3 + output = capsys.readouterr().out + assert "the read account cannot run tc" in output + assert "verified" not in output and "nothing to apply" not in output + + +def run_read_script(extra_stubs: str) -> state.HostState: + bash = shutil.which("bash") + if bash is None: + pytest.skip("no bash on this host") + script = READ_STUBS + extra_stubs + commands.read_script(MARKER) + result = subprocess.run([bash, "-s"], input=script.encode("utf-8"), capture_output=True, timeout=30) + return state.parse(0, "node-0", "node-0", returncode=result.returncode, stdout=result.stdout.decode("utf-8"), + stderr="") + + +def test_the_read_script_under_bash_reports_a_clean_read_without_problems(): + host = run_read_script("") + assert host.parse_problems == [] and host.reachable and host.hostname == "node-0" + assert host.raw["exit:links"].strip() == "0" and host.raw["exit:markers"].strip() == "1" + + +@pytest.mark.parametrize("stub,expected", [ + ('command() { if [ "$1" = -v ] && [ "$2" = tc ]; then return 1; fi; builtin command "$@"; }\n' + "tc() { return 127; }\n", ["the read account cannot run tc", "tc -j qdisc show dev enp1s0f0np0 could not"]), + ('ip() { case "$*" in *route*) echo "RTNETLINK answers: failure" >&2; return 2;; esac; echo "[]"; }\n', + ["ip -j -d route show table main failed with exit status 2"]), + ('ip() { case "$*" in *neigh*) return 1;; esac; echo "[]"; }\n', + ["ip -j neigh show nud permanent failed with exit status 1"]), + ("pgrep() { return 3; }\n", ["pgrep failed with exit status 3"]), +]) +def test_the_read_script_under_bash_reports_failed_reads(stub, expected): + host = run_read_script(stub) + for text in expected: + assert any(text in problem for problem in host.parse_problems), host.parse_problems + + +def test_the_read_script_under_bash_does_not_judge_other_tc_failures(): + assert run_read_script("tc() { return 2; }\n").parse_problems == [] + + +# -- 5. restore keeps marker processes the plan does not name ------------------------------------------ + + +def stray_markers(states, position, unplanned_device): + rule = frozenset({("192.0.2.200", 0x88b5)}) + states[position].markers += [ + state.MarkerProcess(4242, (MARKER.path, "--device", unplanned_device), unplanned_device, rule, True, None), + state.MarkerProcess(4343, ("/tmp/fabric-tool-marker", "sleep"), None, frozenset(), False, None)] + + +def test_restore_retains_stray_marker_processes_and_apply_stops_them(): + topo, bound, built, states = healthy(PATH4, "/srv/site/path4.topology") + unplanned = next(device for device in model.RDMA_DEVICES if built.host(0).marker(device) is None) + stray_markers(states, 0, unplanned) + restored = evaluate(topo, states, bound, "boot").diffs[0] + assert not restored.pending and restored.commands == [] and not restored.blocked + assert any("pid 4242" in note and "retained" in note for note in restored.notes) + assert any("pid 4343" in note and "retained" in note for note in restored.notes) + applied = evaluate(topo, states, bound, "up").diffs[0] + assert sorted(c.key for c in applied.changes if c.kind == "marker" and c.action == "remove") == [ + "pid 4343", unplanned] + assert commands.marker_stop(MARKER, 4242)[0] in applied.commands + assert commands.marker_stop(MARKER, 4343)[0] in applied.commands + removed = evaluate(topo, states, bound, "down").diffs[0] + assert commands.marker_stop(MARKER, 4242)[0] in removed.commands + + +def test_restore_still_replaces_a_wrong_marker_of_a_planned_device(): + topo, bound, built, states = healthy(PATH4, "/srv/site/path4.topology") + planned = built.host(0).markers[0] + states[0].markers = [m if m.device != planned.device else dataclasses.replace( + m, rules=frozenset({("192.0.2.200", 0x88b5)})) for m in states[0].markers] + wrong = next(m for m in states[0].markers if m.device == planned.device) + restored = evaluate(topo, states, bound, "boot").diffs[0] + assert [(c.kind, c.action, c.key) for c in restored.pending] == [("marker", "replace", planned.device)] + assert commands.marker_stop(MARKER, wrong.pid)[0] in restored.commands + assert any(line.startswith("sudo -n setsid -f ") and f"--device {planned.device} " in line + for line in restored.commands) + + +# -- 6. observed objects the command builders refuse --------------------------------------------------- + + +def test_permanent_ipv6_neighbours_are_not_relay_neighbours(): + text = json.dumps([ + {"dst": "fe80::1", "dev": NETDEVS[0], "lladdr": "02:aa:bb:cc:dd:ee", "state": ["PERMANENT"]}, + {"dst": "2001:db8::7", "dev": NETDEVS[1], "lladdr": "02:aa:bb:cc:dd:ef", "state": ["PERMANENT"], + "protocol": "82"}, + {"dst": "198.51.100.77", "dev": NETDEVS[0], "lladdr": "02:aa:bb:cc:dd:f0", "state": ["PERMANENT"]}]) + problems: list[str] = [] + assert [n.destination for n in state.parse_neighbours(text, problems)] == ["198.51.100.77"] and not problems + topo, _, _, _ = healthy() + host = state.parse(0, "node-0", "node-0", returncode=0, stderr="", stdout=read_output(neighbours=json.dumps( + [{"dst": "fe80::1", "dev": NETDEVS[0], "lladdr": "02:aa:bb:cc:dd:ee", "state": ["PERMANENT"]}]))) + assert host.parse_problems == [] and host.relay_neighbours() == [] + removed = diff.compare_down(host, group=topo.group.label, marker=MARKER, adopt=False) + assert not removed.blocked and not removed.pending + + +@pytest.mark.parametrize("mode", ["up", "down", "boot"]) +def test_marked_objects_on_other_devices_are_noted_and_left(mode): + topo, bound, _, states = healthy() + states[0].routes.append(state.RouteEntry("203.0.113.9", 32, "eth0", None, "link", 82, "82", 0, None, "unicast")) + states[0].routes.append(state.RouteEntry("203.0.113.128", 16, "", None, "global", 82, "82", 0, None, "blackhole")) + states[0].neighbours.append(state.NeighbourEntry("203.0.113.9", "eth0", "02:aa:bb:cc:dd:ee", ("PERMANENT",), + 82, "82")) + result = evaluate(topo, states, bound, mode).diffs[0] + assert not result.blocked + assert not any("eth0" in line or "203.0.113.128" in line for line in result.commands) + assert not any(c.key.startswith(("203.0.113.9", "203.0.113.128")) for c in result.changes) + noted = [note for note in result.notes if "not a fabric network device" in note] + assert len(noted) == (0 if mode == "boot" else 3) + + +def test_an_owned_route_is_deleted_with_its_own_prefix_length(): + topo, bound, _, states = healthy() + states[0].routes.append(state.RouteEntry("203.0.113.0", 24, NETDEVS[0], None, "link", 82, "82", 0, None, "unicast")) + states[0].routes.append(state.RouteEntry("0.0.0.0", 0, NETDEVS[1], None, "link", 82, "82", 50, None, "unicast")) + result = evaluate(topo, states, bound, "up").diffs[0] + assert f"sudo -n ip route del 203.0.113.0/24 dev {NETDEVS[0]} proto 82" in result.commands + assert f"sudo -n ip route del 0.0.0.0/0 dev {NETDEVS[1]} proto 82 metric 50" in result.commands + assert sorted(c.key for c in result.changes if c.kind == "route" and c.action == "remove") == [ + "0.0.0.0/0", "203.0.113.0/24"] + assert commands.route_del("192.0.2.17", NETDEVS[0], protocol=82) == ( + f"sudo -n ip route del 192.0.2.17/32 dev {NETDEVS[0]} proto 82") + with pytest.raises(FabricError, match="prefix length"): + commands.route_del("192.0.2.17", NETDEVS[0], protocol=82, prefixlen=33) + problems: list[str] = [] + routes = state.parse_routes(json.dumps([{"dst": "203.0.113.16/24", "dev": "x"}, {"dst": "203.0.113.32/99", "dev": "x"}, + {"dst": "203.0.113.48/x", "dev": "x"}]), problems) + assert [(r.destination, r.prefixlen) for r in routes] == [("203.0.113.16", 24)] + + +# -- 7. install-boot starts the timer whatever the immediate apply returns -------------------------------- + + +@pytest.fixture +def boot_install(environment, tmp_path, monkeypatch): # noqa: F811 + _, _, _, arguments = environment + facts = tmp_path / "facts.json" + facts.write_text(json.dumps(_document())) + calls = [] + monkeypatch.setattr(cli.subprocess, "run", lambda argv, **kwargs: calls.append((argv, kwargs))) + monkeypatch.setattr(cli.shutil, "copytree", lambda *args, **kwargs: None) + monkeypatch.setattr(boot, "install", lambda spec, root, execute: []) + monkeypatch.setattr(boot, "stop_reconciliation", lambda: None) + monkeypatch.setattr(boot, "LIB_DIR", str(Path(cli.__file__).resolve().parents[1])) + monkeypatch.setattr(boot, "BIN_PATH", str(tmp_path / "fabric-tool")) + argv = ["install-boot", "--topology", arguments[arguments.index("--topology") + 1], "--facts", str(facts), + "--host", "node-0", "--execute"] + + def forbid(target, script, timeout): + raise AssertionError("the apply flow is replaced in this test") + + return calls, lambda: cli.main(argv, executor=forbid) + + +@pytest.mark.parametrize("code", [0, 1, 3]) +def test_install_boot_starts_the_timer_whatever_the_apply_returns(boot_install, monkeypatch, capsys, code): + calls, install = boot_install + monkeypatch.setattr(cli, "_apply_flow", lambda *args, **kwargs: code) + assert install() == code + assert [argv for argv, _ in calls] == [["systemctl", "start", boot.RECOVERY_TIMER]] + assert calls[0][1] == {"check": True} + output = capsys.readouterr().out + assert f"started {boot.RECOVERY_TIMER}" in output + assert ("did not succeed" in output and f"(exit {code})" in output) == (code != 0) + + +def test_install_boot_starts_the_timer_when_the_apply_raises(boot_install, monkeypatch, capsys): + calls, install = boot_install + + def fail(*args, **kwargs): + raise FabricError("synthetic failure") + + monkeypatch.setattr(cli, "_apply_flow", fail) + assert install() == 2 + assert [argv for argv, _ in calls] == [["systemctl", "start", boot.RECOVERY_TIMER]] + assert "did not succeed" in capsys.readouterr().out + + +# -- 8. remove-boot is idempotent ------------------------------------------------------------------------ + + +def test_remove_boot_twice_does_not_disable_units_that_are_gone(tmp_path, monkeypatch): + calls = [] + + def systemctl(argv, **kwargs): + calls.append(argv) + if argv[1] == "disable" and not (tmp_path / "etc/systemd/system" / argv[2]).exists(): + raise subprocess.CalledProcessError(1, argv) + return subprocess.CompletedProcess(argv, 0, stdout="ActiveState=inactive\nJob=\n") + + spec = boot.plan("topology", "facts", topology_text="hosts a b\n", facts_text="{}") + boot.install(spec, root=str(tmp_path), execute=False) + monkeypatch.setattr(boot, "Path", lambda value: tmp_path / str(value).lstrip("/") + if str(value).startswith("/") else Path(value)) + monkeypatch.setattr(boot.subprocess, "run", systemctl) + assert len(boot.remove(execute=True)) == 5 + assert [argv for argv in calls if argv[1] == "disable"] == [ + ["systemctl", "disable", boot.RECOVERY_TIMER], ["systemctl", "disable", boot.UNIT_NAME]] + calls.clear() + assert boot.remove(execute=True) == [] + assert not [argv for argv in calls if argv[1] == "disable"] + assert ["systemctl", "daemon-reload"] in calls + + +# -- 9. qdisc ownership survives a failed apply ------------------------------------------------------------ + + +def record_writes(lines): + return [(index, json.loads(shlex.split(line)[2])) for index, line in enumerate(lines) + if "tee " + commands.RECORD_PATH in line] + + +def test_a_failed_apply_keeps_the_ownership_of_the_qdiscs_it_added(): + topo, _, built, _ = healthy() + host = built.host(1) + arguments = dict(layout_name=topo.group.name, marker=MARKER, adopt=False) + fresh = state.HostState(1, host.name, "", True, hostname=host.name) + first = diff.compare_up(fresh, host, built, **arguments) + writes = record_writes(first.commands) + adds = [index for index, line in enumerate(first.commands) if " tc qdisc add " in line] + assert len(adds) == 4 and len(writes) == 1 + assert writes[0][0] < min(adds), "the record must be written before the first qdisc is added" + assert writes[0][1]["qdiscs"] == sorted(host.filter_netdevs) + assert first.commands[writes[0][0] - 1].startswith("sudo -n mkdir -p ") + assert first.commands[1] == commands.guard(host.name) + # The script stopped after the qdiscs: the rerun still owns them, and so does a removal. + stopped = state.HostState(1, host.name, "", True, hostname=host.name, record=writes[0][1]) + for netdev in host.filter_netdevs: + stopped.ingress_qdisc[netdev] = "ingress" + rerun = diff.compare_up(stopped, host, built, **arguments) + assert not any(c.kind in ("qdisc", "record") for c in rerun.pending) + assert not record_writes(rerun.commands) + removed = diff.compare_down(stopped, group=topo.group.label, marker=MARKER, adopt=False) + assert sorted(c.key for c in removed.changes if c.kind == "qdisc" and c.action == "remove") == sorted( + host.filter_netdevs) + for boot_first in (diff.compare_boot(fresh, host, built, **arguments),): + assert record_writes(boot_first.commands)[0][0] < min( + index for index, line in enumerate(boot_first.commands) if " tc qdisc add " in line) + + +def test_write_ahead_record_keeps_a_qdisc_until_it_is_deleted(): + topo, _, built, _ = healthy() + full = built.host(1) + needed, stale = full.filter_netdevs[0], full.filter_netdevs[1] + host = dataclasses.replace(full, filters=tuple(f for f in full.filters if f.in_netdev == needed)) + observed = state.HostState(1, host.name, "", True, hostname=host.name) + observed.ingress_qdisc[stale] = "ingress" + observed.record = diff._record(host, built, topo.group.name, MARKER, [stale]) + result = diff.compare_up(observed, host, built, layout_name=topo.group.name, marker=MARKER, adopt=False) + (first_at, first), (last_at, last) = record_writes(result.commands) + assert first["qdiscs"] == sorted([needed, stale]) and last["qdiscs"] == [needed] + delete_at = result.commands.index(commands.qdisc_del(stale)) + assert first_at < result.commands.index(commands.qdisc_add(needed)) < delete_at < last_at + # Without a qdisc to add, the record stays the script's last step. + present = dataclasses.replace(observed, ingress_qdisc={needed: "ingress", stale: "ingress"}) + later = diff.compare_up(present, host, built, layout_name=topo.group.name, marker=MARKER, adopt=False) + ((only_at, only),) = record_writes(later.commands) + assert only["qdiscs"] == [] and only_at > later.commands.index(commands.qdisc_del(stale)) + + +# -- 11. hosts whose interfaces are not the bound ones ---------------------------------------------------- + + +def test_a_recorded_qdisc_outside_the_bindings_is_noted_not_a_crash(): + topo, bound, _, states = healthy() + states[0].record = dict(states[0].record, qdiscs=["fabric0", 7]) + for mode in ("up", "down"): + result = evaluate(topo, states, bound, mode).diffs[0] + assert any("ingress qdisc on fabric0" in note for note in result.notes) + assert not any("fabric0" in line and "qdisc" in line and "tee" not in line for line in result.commands) + + +def test_remove_without_facts_refuses_hosts_with_other_interface_names(tmp_path, monkeypatch, capsys): + topo, _, _, states = healthy() + for host in states.values(): + host.rdma = {device: f"fabric{index}" for index, device in enumerate(model.RDMA_DEVICES)} + host.record = dict(host.record, qdiscs=["fabric0"]) + host.routes = [dataclasses.replace(route, dev="fabric0") for route in host.routes] + monkeypatch.setattr(ops, "gather", lambda *args, **kwargs: states) + path = tmp_path / "ring.topology" + path.write_text(RING4) + argv = ["remove", "--topology", str(path), "--execute"] + for name in topo.hosts: + argv += ["--ssh", f"{name}={name}"] + + def forbid(target, script, timeout): + raise AssertionError("a refused removal ran a script") + + assert cli.main(argv, executor=forbid) == 3 + output = capsys.readouterr().out + assert "RDMA device rocep1s0f0 is network device fabric0 on this host, not enp1s0f0np0" in output + assert "--facts" in output + # An RDMA device the host does not report (driver gone) does not stop a removal. + topo, bound, _, states = healthy() + states[0].rdma = {} + assert not evaluate(topo, states, bound, "down").blocked + + +# -- 12. facts without prefix lengths ---------------------------------------------------------------------- + + +def test_a_skipped_cabling_check_is_reported(): + topo, bound, _, states = healthy() + assert evaluate(topo, states, bound, "up").notes == [] + document = _document() + for host in document["hosts"]: + for function in host["functions"].values(): + function["address"] = function["address"].split("/")[0] + bare = facts_mod.bind(document, topo) + outcome = evaluate(topo, states, bare, "up") + assert not outcome.blocked and outcome.plan is not None + assert len(outcome.notes) == 1 and "the cabling check was skipped for 8 link(s)" in outcome.notes[0] + assert "NOTE: the cabling check was skipped" in report.render_outcome(outcome) + assert ops.unchecked_cables(topo.group, bound) == [] + + +# -- 13. remove and the marker the record names ----------------------------------------------------------- + + +def test_remove_refuses_a_host_whose_record_names_another_marker(): + topo, bound, _, states = healthy() + states[0].record = dict(states[0].record, marker="/opt/relay/bin/tagger") + removed = evaluate(topo, states, bound, "down").diffs[0] + assert any("--marker /opt/relay/bin/tagger" in blocker for blocker in removed.blockers) + named = diff.compare_down(states[0], group=topo.group.label, marker=commands.MarkerConfig("/opt/relay/bin/tagger"), + adopt=False) + assert not named.blockers + # The same process name from another directory is found by pgrep and needs no refusal. + states[0].record = dict(states[0].record, marker="/opt/other/fabric-tool-marker") + assert not evaluate(topo, states, bound, "down").diffs[0].blockers + # A recorded path that --marker could not name is reported without blocking the removal. + states[0].record = dict(states[0].record, marker="/tmp/tagger") + unnamed = evaluate(topo, states, bound, "down").diffs[0] + assert not unnamed.blockers and any("/tmp/tagger" in note for note in unnamed.notes) + # Apply and restore are not affected. + states[0].record = dict(states[0].record, marker="/opt/relay/bin/tagger") + assert not evaluate(topo, states, bound, "boot").blocked + + +# -- nits ------------------------------------------------------------------------------------------------- + + +def test_validators_reject_a_trailing_newline(): + with pytest.raises(FabricError, match="cannot be checked safely"): + commands.guard("node-0\n") + with pytest.raises(FabricError, match="marker path"): + commands.MarkerConfig("/opt/marker\n") + with pytest.raises(FabricError, match="marker log directory"): + commands.MarkerConfig(log_dir="/var/lib/logs\n") + with pytest.raises(FabricError, match="not a MAC address"): + commands.neigh_replace("192.0.2.10", "02:00:00:00:00:03\n", NETDEVS[0]) + assert commands.guard("node-0").startswith('test "$(hostname)" = node-0 ') + + +def test_ssh_target_cannot_be_read_as_an_option(monkeypatch): + seen = [] + + def run(argv, **kwargs): + seen.append(argv) + return subprocess.CompletedProcess(argv, 0, stdout=b"", stderr=b"") + + monkeypatch.setattr(ops.subprocess, "run", run) + assert ops.ssh_executor("-oProxyCommand=id", "true\n", 5).ok + assert seen[0][-3:] == ["--", "-oProxyCommand=id", "bash -s"] + assert seen[0][0] == "ssh" and all(word != "-oProxyCommand=id" for word in seen[0][:-3]) + + +def test_verify_rejects_adopt(capsys): + with pytest.raises(SystemExit) as stopped: + cli.main(["verify", "--adopt"]) + assert stopped.value.code == 2 and "--adopt" in capsys.readouterr().err + for command in ("apply", "remove"): + assert cli._parser().parse_args([command, "--adopt"]).adopt diff --git a/fabric-tool/tests/test_topology.py b/fabric-tool/tests/test_topology.py index be3991a..a6560a4 100644 --- a/fabric-tool/tests/test_topology.py +++ b/fabric-tool/tests/test_topology.py @@ -43,7 +43,53 @@ def test_defaults_and_overrides(): def test_plugin_key_and_comments(): text = "net-sircl-topology\n# a comment\nhosts a b\ncabling ring # trailing\n" ring = topology.parse(text) - assert ring.hosts == ("a", "b") and ring.group.label == "cycle:0-1" + assert ring.hosts == ("a", "b") and ring.group.label == "pair:0-1" + + +def test_two_host_ring_is_one_cable_like_the_plugin_reads_it(): + """`transport-core/src/topology.c` gives a pair one cable under `ring`; two cables are `explicit`.""" + ring = topology.parse("hosts a b\ncabling ring\n") + path = topology.parse("hosts a b\ncabling path\n") + assert ring.group.cables == path.group.cables == ("0.port0-1.port1",) + assert ring.group.label == "pair:0-1" and ring.group.relay_egress == "sibling" + assert ring.layout_name == path.layout_name + # Both lanes of a pair use the one cable's port, as the plugin derives them. + routes = model.derive_routes(ring.group.layout, 2) + assert routes.route_text(0) == "1=rocep1s0f0/roceP2p1s0f0" + assert routes.route_text(1) == "0=rocep1s0f1/roceP2p1s0f1" + double = topology.parse("hosts a b\ncabling explicit\ncable 0.port0 1.port1\ncable 1.port0 0.port1\n") + assert double.group.label == "cycle:0-1" and len(double.group.cables) == 2 + assert topology.parse("hosts a b c\ncabling ring\n").group.label == "cycle:0-1-2" + + +def test_host_count_name_length_and_budget_limits_match_the_plugin(): + names = [f"h{i}" for i in range(65)] + assert topology.parse("hosts " + " ".join(names[:64]) + "\ncabling path\n").size == 64 + with pytest.raises(FabricError, match="at most 64"): + topology.parse("hosts " + " ".join(names) + "\ncabling path\n") + assert topology.parse(f"hosts {'a' * 63} b\ncabling path\n").hosts[0] == "a" * 63 + with pytest.raises(FabricError, match="longer than 63 bytes"): + topology.parse(f"hosts {'a' * 64} b\ncabling path\n") + with pytest.raises(FabricError, match="longer than 63 bytes"): + topology.parse(f"hosts {'é' * 32} b\ncabling path\n") # 32 characters, 64 bytes + assert topology.parse("hosts a b\ncabling path\nrelay_budget 0123\n").budget == 123 + for budget in ("١٢٣", "²", "+5", "1_0", "0x10"): # digits to Python, not to the plugin + with pytest.raises(FabricError, match="positive byte count"): + topology.parse(f"hosts a b\ncabling path\nrelay_budget {budget}\n") + + +def test_layout_name_follows_the_content_not_the_file(): + ring = topology.parse(RING4, path="/srv/site/ring4.topology") + assert ring.group.name == ring.layout_name and ring.layout_name.startswith("topology:") + assert "ring4" not in ring.layout_name + assert topology.parse(RING4, path="/etc/fabric-table/topology").layout_name == ring.layout_name + spelled = topology.parse("hosts node-0 node-1 node-2 node-3\ncabling explicit\n# the same cables\n" + "cable 0.port1 3.port0\ncable 2.port0 3.port1\n" + "cable 1.port0 2.port1\ncable 0.port0 1.port1\nrelay_budget 4096\n") + assert spelled.layout_name == ring.layout_name + assert topology.parse(PATH4).layout_name != topology.parse(RING4.replace("node-3", "node-9")).layout_name + assert topology.parse(RING4 + "port0 mlx5_0 mlx5_2\n").layout_name != ring.layout_name + assert topology.parse("hosts node-0 node-1 node-2 node-3\ncabling path\n").layout_name != ring.layout_name def test_refusals(): diff --git a/net-sircl/Makefile b/net-sircl/Makefile index 3532158..55ebb4b 100644 --- a/net-sircl/Makefile +++ b/net-sircl/Makefile @@ -15,7 +15,9 @@ PYTHON ?= python3 PREFIX ?= /usr/local CFLAGS ?= -std=gnu11 -O2 -g -Wall -Wextra -Werror -pthread STANDIN := tests/standin -CORE ?= $(firstword $(wildcard ../../transport-core ../transport-core)) +# The bundled core beside this directory comes first: a directory that merely happens to be called +# transport-core next to the checkout must not be compiled in instead. CORE= selects another. +CORE ?= $(firstword $(wildcard ../transport-core ../../transport-core)) CORE_SOURCES := $(CORE)/src/core.c $(CORE)/src/topology.c $(CORE)/src/sysfs.c net_sircl_plan.c CORE_HEADERS := $(wildcard $(CORE)/include/sircl_core/*.h) CPPFLAGS += -I$(CORE)/include -include .core-build/core_identity.h diff --git a/net-sircl/net_sircl.c b/net-sircl/net_sircl.c index 812e309..966a6f7 100644 --- a/net-sircl/net_sircl.c +++ b/net-sircl/net_sircl.c @@ -61,6 +61,15 @@ __attribute__((visibility("default"))) const char net_sircl_core_source[] = SIRC #define RELAY_BUDGET_DEFAULT (RELAY_QUEUE_BYTES * 5u / 8u) #include "net_sircl_plan.h" #define PEER_CHECK_EVERY 4096u /* test()/isend() calls between peer-loss checks of a waiting comm */ +/* A windowed comm signals every payload write. Its queue pair also holds at most two control writes + * per request slot, so payload writes stop short of the send queue: a window larger than + * SEND_DEPTH chunks then waits for completions instead of overflowing the queue. */ +#define DATA_WR_LIMIT (SEND_DEPTH - 2 * NET_SIRCL_SLOTS - 8) +#ifdef NET_SIRCL_STANDIN +#define GID_INDEX_DEFAULT 0 +#else +#define GID_INDEX_DEFAULT (-1) /* find the function's RoCE v2 IPv4 GID in sysfs */ +#endif /* wr_id: kind in 56-63, ACK units (128 bytes) in 40-55, charge in 8-39, * slot in 0-7. A windowed WR's charge fits 32 bits; direct writes are <=1 GiB. */ @@ -132,7 +141,8 @@ static struct { int speed_mbps; int traffic_class; int relaxed_ordering; - int connect_timeout_ms, request_timeout_ms; + int connect_timeout_ms, request_timeout_ms, peer_wait_timeout_ms; + int route_check, gid_index_setting; /* gid_index_setting < 0: find the RoCE v2 IPv4 GID in sysfs */ int ib_timeout, ib_retry_cnt; int relay_budget, nhosts, owner_fd, route_derived; uint64_t policy; @@ -186,6 +196,8 @@ struct comm { uint64_t inflight; /* this comm's share of win->inflight */ uint64_t chunks; int peer_position, lane; + int hung_up; /* this side failed and shut its connection socket down, once */ + unsigned data_out; /* signaled payload writes of a windowed comm not yet completed */ unsigned waits; /* calls since the last peer-loss check */ int64_t cts_wait_ms; ncclResult_t error; @@ -242,9 +254,25 @@ static void shared_free(void *p) { #include "net_sircl_config.h" +/* A forked child inherits the owner socket, and the name stays bound while any descriptor refers to + * it: without this a later initialization in the parent, or the next job on the host, would be refused + * for as long as such a child (a data-loader worker, say) lives. The child never owns the allowance. */ +static void release_host_in_child(void) { + if (g.owner_fd >= 0) { + close(g.owner_fd); + g.owner_fd = -1; + } +} + +static void register_fork_handler(void) { + pthread_atfork(NULL, NULL, release_host_in_child); +} + /* Abstract socket ownership has no stale file after a crash. Production containers must use * the host network namespace, as RDMA deployments do; separate namespaces cannot share this guard. */ static int claim_host(void) { + static pthread_once_t fork_handler = PTHREAD_ONCE_INIT; + pthread_once(&fork_handler, register_fork_handler); struct sockaddr_un addr = {.sun_family = AF_UNIX}; #ifdef NET_SIRCL_STANDIN const char *fabric = getenv("SIRCL_EMU_FABRIC"); @@ -254,7 +282,15 @@ static int claim_host(void) { #endif g.owner_fd = socket(AF_UNIX, SOCK_DGRAM | SOCK_CLOEXEC, 0); if (g.owner_fd < 0) return -1; - if (bind(g.owner_fd, (struct sockaddr *)&addr, sizeof addr)) { + /* A child forked a moment ago may not have run its handler yet. Give it a short time to close its + * inherited copy before concluding that another plugin process owns the name. */ + int bound = -1; + for (int attempt = 0; attempt < 50; ++attempt) { + bound = bind(g.owner_fd, (struct sockaddr *)&addr, sizeof addr); + if (!bound || errno != EADDRINUSE) break; + nanosleep(&(struct timespec){0, 2000000}, NULL); + } + if (bound) { close(g.owner_fd); g.owner_fd = -1; WARN("net-sircl: one plugin process per host is required for relay accounting"); @@ -324,10 +360,8 @@ static ncclResult_t open_devices(void) { d->ctx = ctx; d->port = 1; d->mtu = pa.active_mtu; -#ifdef NET_SIRCL_STANDIN - d->gid_index = (int)env_long("NET_SIRCL_GID_INDEX", 0); -#else - d->gid_index = (int)env_long("NET_SIRCL_GID_INDEX", -1); + d->gid_index = g.gid_index_setting; +#ifndef NET_SIRCL_STANDIN if (d->gid_index < 0) d->gid_index = sircl_core_gid_index("/sys/class/infiniband", name, d->port); if (d->gid_index < 0) { WARN("net-sircl: %s has no RoCE v2 IPv4 GID; set NET_SIRCL_GID_INDEX", name); @@ -372,30 +406,35 @@ static ncclResult_t sircl_init(void **ctx, uint64_t commId, ncclNetCommConfig_v1 if (g.refs++ == 0) { profile_init(); /* Defaults follow NVIDIA NCCL v2.32.3-1, src/transport/net_ib/connect.cc (see NOTICE). - * Plugin settings are independent of NCCL_IB_*; all peers use this local QP policy. */ - r = env_range("NET_SIRCL_IB_TIMEOUT", 20, 1, 31, &g.ib_timeout); - if (r == ncclSuccess) - r = env_range("NET_SIRCL_IB_RETRY_CNT", 7, 0, 7, &g.ib_retry_cnt); - if (r == ncclSuccess) - r = env_range("NET_SIRCL_RELAY_BUDGET", RELAY_BUDGET_DEFAULT, 65536, RELAY_BUDGET_DEFAULT, &g.relay_budget); - if (r == ncclSuccess) - r = env_range("NET_SIRCL_POSITION", -1, 0, MAX_POSITIONS - 1, &g.position); - if (r == ncclSuccess) - r = env_range("NET_SIRCL_CONNECT_TIMEOUT_MS", 60000, 1, INT_MAX, &g.connect_timeout_ms); - if (r == ncclSuccess) - r = env_range("NET_SIRCL_REQUEST_TIMEOUT_MS", 60000, 1, INT_MAX, &g.request_timeout_ms); + * Plugin settings are independent of NCCL_IB_*; all peers use this local QP policy. + * Every setting is validated before a device is opened: a malformed value fails initialization + * instead of silently selecting the default or being truncated. */ + int chunk = 0; + const struct { const char *name; int fallback, min, max, *out; } settings[] = { + {"NET_SIRCL_IB_TIMEOUT", 20, 1, 31, &g.ib_timeout}, + {"NET_SIRCL_IB_RETRY_CNT", 7, 0, 7, &g.ib_retry_cnt}, + {"NET_SIRCL_RELAY_BUDGET", RELAY_BUDGET_DEFAULT, 65536, RELAY_BUDGET_DEFAULT, &g.relay_budget}, + {"NET_SIRCL_POSITION", -1, 0, MAX_POSITIONS - 1, &g.position}, + {"NET_SIRCL_CONNECT_TIMEOUT_MS", 60000, 1, INT_MAX, &g.connect_timeout_ms}, + {"NET_SIRCL_REQUEST_TIMEOUT_MS", 60000, 1, INT_MAX, &g.request_timeout_ms}, + {"NET_SIRCL_PEER_WAIT_TIMEOUT_MS", 0, 0, INT_MAX, &g.peer_wait_timeout_ms}, + {"NET_SIRCL_CHUNK", 65536, 1, MAX_NET_BYTES, &chunk}, + {"NET_SIRCL_SPEED_MBPS", 100000, 1, INT_MAX, &g.speed_mbps}, + {"NET_SIRCL_TC", 0, 0, 255, &g.traffic_class}, + {"NET_SIRCL_RELAXED_ORDERING", 1, 0, 1, &g.relaxed_ordering}, + {"NET_SIRCL_ROUTE_CHECK", 1, 0, 1, &g.route_check}, + {"NET_SIRCL_GID_INDEX", GID_INDEX_DEFAULT, 0, 255, &g.gid_index_setting}, + }; + for (unsigned i = 0; i < sizeof settings / sizeof settings[0] && r == ncclSuccess; ++i) + r = env_range(settings[i].name, settings[i].fallback, settings[i].min, settings[i].max, settings[i].out); + if (r == ncclSuccess) r = oob_address(&g.oob_addr); if (r != ncclSuccess) goto init_done; g.owner_fd = -1; g.nhosts = 0; memset(g.relay_windows, 0, sizeof g.relay_windows); for (int d = 0; d < NET_SIRCL_MAX_DEVS; ++d) pthread_mutex_init(&g.relay_windows[d].lock, NULL); - g.chunk = (uint32_t)env_long("NET_SIRCL_CHUNK", 65536); - g.speed_mbps = (int)env_long("NET_SIRCL_SPEED_MBPS", 100000); - g.traffic_class = (int)env_long("NET_SIRCL_TC", 0); - g.relaxed_ordering = (int)env_long("NET_SIRCL_RELAXED_ORDERING", 1); - g.oob_addr = oob_address(); - if (g.chunk < 4096) g.chunk = 4096; + g.chunk = chunk < 4096 ? 4096u : (uint32_t)chunk; memset(g.routes, 0, sizeof g.routes); g.nwindows = 0; r = open_devices(); @@ -435,6 +474,7 @@ static ncclResult_t sircl_init(void **ctx, uint64_t commId, ncclNetCommConfig_v1 } g.ndevs = 0; if (g.owner_fd >= 0) close(g.owner_fd); + g.owner_fd = -1; for (int d = 0; d < NET_SIRCL_MAX_DEVS; ++d) pthread_mutex_destroy(&g.relay_windows[d].lock); } init_done: @@ -576,7 +616,7 @@ static int post_write(struct comm *c, uint64_t laddr, uint32_t lkey, uint32_t le static ncclResult_t send_progress(struct comm *c, struct req *q) { while (q->posted < q->total) { uint32_t left = q->total - q->posted; - uint32_t piece = c->win ? chunk_bytes(c, left) : left; + uint32_t piece = !c->win ? left : c->data_out < DATA_WR_LIMIT ? chunk_bytes(c, left) : 0; if (profile_enabled) profile_wait(c, q, !piece); if (!piece) return ncclSuccess; uint64_t charge = write_charge(c, piece); @@ -590,6 +630,7 @@ static ncclResult_t send_progress(struct comm *c, struct req *q) { } q->posted += piece; c->chunks++; + if (c->win) c->data_out++; } if (!q->final_posted) { uint64_t charge = c->win && c->win->relay ? 2 * write_charge(c, 4) : 0; @@ -612,20 +653,48 @@ static ncclResult_t send_progress(struct comm *c, struct req *q) { return ncclSuccess; } -static ncclResult_t check_wait(struct comm *c, int64_t started_ms) { +/* A waiting request checks its peer and its deadline on the first and every PEER_CHECK_EVERY-th call. + * + * WAIT_TRANSPORT: the request waits only for this host's own RC completions (a send whose + * clear-to-send has arrived, or a receive's clear-to-send post). Nothing but the fabric can delay + * those, so NET_SIRCL_REQUEST_TIMEOUT_MS bounds them. + * + * WAIT_PEER: the request waits for the peer application to post its matching receive or send. NCCL + * posts a receive when the local collective starts and retries a send for as long as it takes, so a + * rank that is merely late (checkpointing, evaluating, compiling) is not a failure. These waits have no + * deadline unless NET_SIRCL_PEER_WAIT_TIMEOUT_MS sets one; a peer that closes its connection, as a + * process that exits or a comm that fails does, still ends them. */ +enum { WAIT_PEER = 0, WAIT_TRANSPORT = 1 }; + +static ncclResult_t check_wait(struct comm *c, int64_t started_ms, int kind) { if (c->error) return c->error; if (c->waits++ % PEER_CHECK_EVERY) return ncclSuccess; + int limit_ms = kind == WAIT_TRANSPORT ? g.request_timeout_ms : g.peer_wait_timeout_ms; if (peer_gone(c)) { WARN("net-sircl: the peer at position %d closed its connection with requests outstanding", c->peer_position); - } else if (now_ms() - started_ms >= g.request_timeout_ms) { - WARN("net-sircl: request to position %d timed out after %d ms; check peer progress and fabric-tool verify", - c->peer_position, g.request_timeout_ms); + } else if (limit_ms > 0 && now_ms() - started_ms >= limit_ms) { + if (kind == WAIT_TRANSPORT) + WARN("net-sircl: request to position %d made no transport progress for %d ms " + "(NET_SIRCL_REQUEST_TIMEOUT_MS); check the fabric and fabric-tool verify", + c->peer_position, limit_ms); + else + WARN("net-sircl: position %d did not post its matching request within %d ms " + "(NET_SIRCL_PEER_WAIT_TIMEOUT_MS); check that rank's progress", c->peer_position, limit_ms); } else return ncclSuccess; c->error = ncclRemoteError; if (c->win) c->win->error = ncclRemoteError; return ncclRemoteError; } +/* A failed comm stays failed. Shutting its connection socket down tells the peer, whose waiting + * requests then end with ncclRemoteError at their next peer check instead of waiting for work this + * side will never do. The descriptor itself stays open until the comm is closed. */ +static void comm_hang_up(struct comm *c) { + if (c->fd < 0 || c->hung_up) return; + c->hung_up = 1; + shutdown(c->fd, SHUT_RDWR); +} + static ncclResult_t submit_progress(struct comm *c, struct req *q); static ncclResult_t isend_locked(void *sendComm, void *data, size_t size, int tag, void *mhandle, void *phandle, @@ -637,8 +706,9 @@ static ncclResult_t isend_locked(void *sendComm, void *data, size_t size, int ta struct req *q = &c->reqs[slot]; if (q->used) return ncclSuccess; if (__atomic_load_n(&c->ctrl->cts_seq[slot], __ATOMIC_ACQUIRE) != c->seq + 1) { + /* The peer has not posted this receive yet. */ if (!c->cts_wait_ms) c->cts_wait_ms = now_ms(); - return check_wait(c, c->cts_wait_ms); + return check_wait(c, c->cts_wait_ms, WAIT_PEER); } c->cts_wait_ms = 0; struct net_sircl_cts e = c->ctrl->cts[slot]; @@ -681,6 +751,7 @@ static ncclResult_t sircl_isend(void *sendComm, void *data, size_t size, int tag ncclResult_t r = c->error ? c->error : (c->win ? poll_cq(c) : ncclSuccess); if (r == ncclSuccess) r = isend_locked(sendComm, data, size, tag, mhandle, phandle, request); if (r == ncclRemoteError || r == ncclSystemError) c->error = r; + if (c->error) comm_hang_up(c); if (c->win) pthread_mutex_unlock(&c->win->lock); return r; } @@ -746,6 +817,7 @@ static ncclResult_t sircl_irecv(void *recvComm, int n, void **data, size_t *size ncclResult_t r = c && c->error ? c->error : (c && c->win ? poll_cq(c) : ncclSuccess); if (r == ncclSuccess) r = irecv_locked(recvComm, n, data, sizes, tags, mhandles, phandles, request); if (c && (r == ncclRemoteError || r == ncclSystemError)) c->error = r; + if (c && c->error) comm_hang_up(c); if (c && c->win) pthread_mutex_unlock(&c->win->lock); return r; } @@ -778,6 +850,7 @@ static ncclResult_t drain(struct comm *c) { uint32_t slot = (uint32_t)(id & 0xff); admission_complete(c, id); if (profile_enabled) profile_complete(c, id); + if (kind == WR_DATA && c->data_out) c->data_out--; if (kind == WR_FINAL && slot < NET_SIRCL_SLOTS) c->reqs[slot].done = 1; if (kind == WR_CTS && slot < NET_SIRCL_SLOTS) c->reqs[slot].cts_done = 1; } @@ -792,12 +865,14 @@ static ncclResult_t test_locked(void *request, int *done, int *sizes) { ncclResult_t r = poll_cq(c); if (r != ncclSuccess) return r; if (q->is_send) { - if (!q->done) return check_wait(c, q->started_ms); + /* Clear-to-send arrived before this request existed: only this host's writes are outstanding. */ + if (!q->done) return check_wait(c, q->started_ms, WAIT_TRANSPORT); if (sizes) *sizes = (int)q->total; } else { - if (!q->cts_done) return check_wait(c, q->started_ms); + if (!q->cts_done) return check_wait(c, q->started_ms, WAIT_TRANSPORT); + /* Clear-to-send is with the peer; the payload comes when that rank sends. */ if (__atomic_load_n(&c->ctrl->done_seq[q->slot], __ATOMIC_ACQUIRE) != q->seq + 1) - return check_wait(c, q->started_ms); + return check_wait(c, q->started_ms, WAIT_PEER); uint32_t got = __atomic_load_n(&c->ctrl->done_size[q->slot], __ATOMIC_ACQUIRE); if (got > q->total) { WARN("net-sircl: receive completion length %u exceeds capacity %u", got, q->total); @@ -820,6 +895,7 @@ static ncclResult_t sircl_test(void *request, int *done, int *sizes) { if (c->win) pthread_mutex_lock(&c->win->lock); ncclResult_t r = test_locked(request, done, sizes); if (r != ncclSuccess) c->error = r; + if (c->error) comm_hang_up(c); if (c->win) pthread_mutex_unlock(&c->win->lock); return r; } diff --git a/net-sircl/net_sircl.h b/net-sircl/net_sircl.h index e8e0ef0..bc77497 100644 --- a/net-sircl/net_sircl.h +++ b/net-sircl/net_sircl.h @@ -16,44 +16,55 @@ * with separate ACK debt when both resources permit control-pair progress; * otherwise the base route or B/(N-2) aggregate policy remains. Shares round down. * Forward traffic plus reverse ACKs stays below 7/8 of an assumed 512 KiB queue at default B. - * Direct peers keep unwindowed sends. See README "Relay window" for the capacity assumptions. + * Direct peers keep unwindowed sends. See ROUTE-ALLOWANCE.md for the capacity assumptions. * * Routes. A peer position's route lists the local functions of its lanes (up to two, lane order). The * connector keeps NCCL's device when it is one of them (NCCL spreads channels over its devices, which keeps * both PCI functions of a cable busy), else takes the lanes in turn; it sends its lane, and the acceptor uses * the same lane of its own route, so both ends are the same function class on the same path. * - * Settings (environment, read at init): + * Settings (environment, read at init; docs/configuration.md is the reference). Numeric settings take + * decimal digits only; a malformed or out-of-range value fails initialization and names the setting. * NET_SIRCL_TOPOLOGY required topology file (below): routes for every peer, this host's position * from its host name * NET_SIRCL_POSITION this process's position (overrides the topology file's host-name match) - * NET_SIRCL_ROUTES =[/],... lanes per peer (SIRCL_PEER_ROUTES format); - * must match the topology lanes + * NET_SIRCL_ROUTES =/,... both lanes per peer (SIRCL_PEER_ROUTES + * format); must match the topology lanes exactly * NET_SIRCL_WINDOWS =,... optional direct-peer payload cap per function; * relayed entries can only lower every function's source allowance * NET_SIRCL_RELAY_BUDGET directional charged-byte budget, default 327680, range 65536..327680 * NET_SIRCL_IB_TIMEOUT RC ACK timeout exponent, default 20, decimal 1..31 (direct and relayed) * NET_SIRCL_IB_RETRY_CNT RC retry count, default 7, decimal 0..7 * NET_SIRCL_HCA comma list of RDMA functions to expose (default: every active RoCE function) - * NET_SIRCL_GID_INDEX GID index (default: the function's RoCE v2 IPv4 GID, found in sysfs) - * NET_SIRCL_CHUNK maximum payload bytes per signaled windowed chunk (default 65536); - * shrinks to available credit and half the allowance when two 4 KiB pieces fit - * NET_SIRCL_OOB_ADDR IPv4 address for the connection exchange (default: NCCL_SOCKET_IFNAME's first - * IPv4 address, else 127.0.0.1) - * NET_SIRCL_CONNECT_TIMEOUT_MS connect/accept deadline (default 60000) + * NET_SIRCL_GID_INDEX GID index 0..255 (default: the function's RoCE v2 IPv4 GID, found in sysfs) + * NET_SIRCL_CHUNK maximum payload bytes per signaled windowed chunk (default 65536, at least + * 4096); shrinks to available credit and half the allowance when two 4 KiB + * pieces fit + * NET_SIRCL_OOB_ADDR this host's IPv4 address for the connection exchange (default: + * NCCL_SOCKET_IFNAME's first IPv4 address, else 127.0.0.1 with a warning) + * NET_SIRCL_CONNECT_TIMEOUT_MS connect/accept deadline (default 60000) + * NET_SIRCL_REQUEST_TIMEOUT_MS deadline for this host's own transport progress on a request: a send + * from its clear-to-send to completion, a receive's clear-to-send post + * (default 60000) + * NET_SIRCL_PEER_WAIT_TIMEOUT_MS optional deadline for the peer application to post its matching + * request (default 0: wait, as NCCL does) + * NET_SIRCL_CHANNELS the bundled tuner's collective channel limit (net_sircl_tuner.h, docs/channels.md) + * NET_SIRCL_PROFILE output prefix that enables cumulative profiling (PROFILING.md) * NET_SIRCL_RELAXED_ORDERING 1 (default) registers memory with IBV_ACCESS_RELAXED_ORDERING * NET_SIRCL_ROUTE_CHECK 1 (default) refuses a peer this function's interface has no route to * NET_SIRCL_SPEED_MBPS the speed each device reports to NCCL's tuner (default 100000) - * NET_SIRCL_TC RoCE traffic class (default 0) + * NET_SIRCL_TC RoCE traffic class 0..255 (default 0) * - * Topology file (text; `#` starts a comment): - * hosts ... host names in position order (positions 0, 1, ...) - * cabling ring|path|explicit ring/path: host i's port 0 is cabled to host i+1's port 1 (path: no - * cable from the last host back to the first) + * Topology file (text; `#` starts a comment; anything not listed here is refused): + * hosts ... host names in position order (positions 0, 1, ...), 2 to 64 of them + * cabling ring|path|explicit required. ring/path: host i's port 0 is cabled to host i+1's port 1 + * (path: no cable from the last host back to the first; two hosts: the + * one cable 0.port0-1.port1 either way) * cable .port

.port one cable (repeatable; with `cabling explicit`, or added to ring/path) * port0 the functions of port 0, lane order (default rocep1s0f0 roceP2p1s0f0) * port1 the functions of port 1 (default rocep1s0f1 roceP2p1s0f1) * relay_budget directional budget ceiling (default 393216), limited by the environment + * Every host must be cabled, and the cables must join the hosts into one path or one cycle. * * NVIDIA NCCL's plugin headers (nccl/, Apache-2.0) are vendored unchanged from tag v2.32.3-1, * plugins/net/example/nccl/; see NOTICE. */ diff --git a/net-sircl/net_sircl_config.h b/net-sircl/net_sircl_config.h index b0a41c0..4da200e 100644 --- a/net-sircl/net_sircl_config.h +++ b/net-sircl/net_sircl_config.h @@ -26,10 +26,21 @@ static ncclResult_t env_range(const char *name, int fallback, int min, int max, return ncclInvalidArgument; } -static uint32_t oob_address(void) { +/* The IPv4 address peers connect to for the connection exchange (network order). An explicit + * NET_SIRCL_OOB_ADDR that is not a usable IPv4 address fails initialization: falling back would + * advertise an address the user did not ask for. Without one, the first IPv4 address of the + * NCCL_SOCKET_IFNAME interface or prefix; without that, loopback, which only local tests can use. */ +static ncclResult_t oob_address(uint32_t *out) { const char *a = getenv("NET_SIRCL_OOB_ADDR"); - struct in_addr in; - if (a && *a && inet_pton(AF_INET, a, &in) == 1) return in.s_addr; + if (a && *a) { + struct in_addr in; + if (inet_pton(AF_INET, a, &in) != 1 || in.s_addr == htonl(INADDR_ANY)) { + WARN("net-sircl: NET_SIRCL_OOB_ADDR must be this host's IPv4 address (got '%s')", a); + return ncclInvalidArgument; + } + *out = in.s_addr; + return ncclSuccess; + } const char *ifname = getenv("NCCL_SOCKET_IFNAME"); if (ifname && *ifname && *ifname != '^' && *ifname != '=') { struct ifaddrs *list, *i; @@ -39,10 +50,19 @@ static uint32_t oob_address(void) { if (i->ifa_addr && i->ifa_addr->sa_family == AF_INET && !strncmp(i->ifa_name, ifname, strlen(ifname))) found = ((struct sockaddr_in *)i->ifa_addr)->sin_addr.s_addr; freeifaddrs(list); - if (found) return found; + if (found) { + *out = found; + return ncclSuccess; + } } } - return htonl(INADDR_LOOPBACK); +#ifndef NET_SIRCL_STANDIN + /* The stand-in runs every rank on one host, where loopback is the right address. */ + WARN("net-sircl: no IPv4 address from NET_SIRCL_OOB_ADDR or NCCL_SOCKET_IFNAME (%s); advertising 127.0.0.1, " + "which peers on other hosts cannot reach", ifname && *ifname ? ifname : "unset"); +#endif + *out = htonl(INADDR_LOOPBACK); + return ncclSuccess; } static int in_list(const char *list, const char *name) { diff --git a/net-sircl/net_sircl_connection.h b/net-sircl/net_sircl_connection.h index 416e6ca..4e4d461 100644 --- a/net-sircl/net_sircl_connection.h +++ b/net-sircl/net_sircl_connection.h @@ -133,8 +133,8 @@ static ncclResult_t route_check(struct comm *c, const struct net_sircl_meta *r) #else struct dev *dv = &g.devs[c->dev]; static const uint8_t mapped[12] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff}; - if (!dv->netdev[0] || memcmp(r->gid, mapped, 12) || !env_long("NET_SIRCL_ROUTE_CHECK", 1)) return ncclSuccess; - int fd = socket(AF_INET, SOCK_DGRAM, 0); + if (!dv->netdev[0] || memcmp(r->gid, mapped, 12) || !g.route_check) return ncclSuccess; + int fd = socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0); if (fd < 0) return ncclSuccess; ncclResult_t result = ncclSuccess; if (setsockopt(fd, SOL_SOCKET, SO_BINDTODEVICE, dv->netdev, (socklen_t)strlen(dv->netdev)) == 0) { @@ -237,15 +237,22 @@ static ncclResult_t sircl_listen(void *ctx, int d, void *handle, void **listenCo if (d < 0 || d >= g.ndevs) return ncclInvalidArgument; struct net_sircl_handle *h = handle; memset(handle, 0, NCCL_NET_HANDLE_MAXSIZE); - int fd = socket(AF_INET, SOCK_STREAM, 0); + int fd = socket(AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0); if (fd < 0) return ncclSystemError; struct sockaddr_in sa; memset(&sa, 0, sizeof sa); sa.sin_family = AF_INET; - sa.sin_addr.s_addr = htonl(INADDR_ANY); + /* Listen only on the address peers are told to connect to. An advertised address this host does not + * own (address translation in front of it) still needs every interface. */ + sa.sin_addr.s_addr = g.oob_addr; socklen_t len = sizeof sa; - if (bind(fd, (struct sockaddr *)&sa, sizeof sa) || listen(fd, 128) || - getsockname(fd, (struct sockaddr *)&sa, &len) || set_nonblocking(fd)) { + int bound = bind(fd, (struct sockaddr *)&sa, sizeof sa); + if (bound && errno == EADDRNOTAVAIL) { + sa.sin_addr.s_addr = htonl(INADDR_ANY); + bound = bind(fd, (struct sockaddr *)&sa, sizeof sa); + } + if (bound || listen(fd, 128) || getsockname(fd, (struct sockaddr *)&sa, &len) || set_nonblocking(fd)) { + WARN("net-sircl: listening for the connection exchange: %s", strerror(errno)); close(fd); return ncclSystemError; } @@ -289,7 +296,10 @@ static ncclResult_t sircl_connect(void *ctx, int d, void *handle, void **sendCom WARN("net-sircl: handle magic %08x version %u", h->magic, h->version); return ncclInvalidArgument; } - if (!route_of(h->position)) return ncclInvalidArgument; + if (!route_of(h->position)) { + WARN("net-sircl: NET_SIRCL_TOPOLOGY gives position %d no route to position %d", g.position, h->position); + return ncclInvalidArgument; + } struct pending *p = (struct pending *)(uintptr_t)h->pending; if (!p) { p = calloc(1, sizeof *p); @@ -297,7 +307,7 @@ static ncclResult_t sircl_connect(void *ctx, int d, void *handle, void **sendCom p->deadline_ms = now_ms() + g.connect_timeout_ms; int lane = -1; p->dev = connect_dev(h->position, d, &lane); - p->fd = socket(AF_INET, SOCK_STREAM, 0); + p->fd = socket(AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0); if (p->fd < 0 || set_nonblocking(p->fd)) return connect_fail(h, p, ncclSystemError); int one = 1; setsockopt(p->fd, IPPROTO_TCP, TCP_NODELAY, &one, sizeof one); @@ -363,14 +373,28 @@ static ncclResult_t accept_fail(struct listen_comm *l, ncclResult_t r) { return r; } +/* A connection that never identifies itself as a net-sircl peer (a port scan, a health probe, a + * connector that ended before its metadata) is dropped and the listener keeps accepting. Only a peer + * that sent valid metadata can fail the accept; a connector that gave up reports its own error. */ +static ncclResult_t accept_drop(struct listen_comm *l, const char *why) { + WARN("net-sircl: dropped a connection to the listener of %s: %s", g.devs[l->dev].name, why); + pending_drop(l->accepting); + l->accepting = NULL; + return ncclSuccess; +} + static ncclResult_t sircl_accept(void *listenComm, void **recvComm, ncclNetDeviceHandle_v12_t **recvDevComm) { (void)recvDevComm; *recvComm = NULL; struct listen_comm *l = listenComm; struct pending *p = l->accepting; if (!p) { - int fd = accept(l->fd, NULL, NULL); - if (fd < 0) return (errno == EAGAIN || errno == EWOULDBLOCK) ? ncclSuccess : ncclSystemError; + int fd = accept4(l->fd, NULL, NULL, SOCK_CLOEXEC); + if (fd < 0) { + /* The connection ended while it was queued: not this listener's failure. */ + return (errno == EAGAIN || errno == EWOULDBLOCK || errno == ECONNABORTED || errno == EINTR) ? ncclSuccess + : ncclSystemError; + } p = calloc(1, sizeof *p); if (!p) { close(fd); @@ -383,14 +407,17 @@ static ncclResult_t sircl_accept(void *listenComm, void **recvComm, ncclNetDevic l->accepting = p; } if (now_ms() > p->deadline_ms) { + if (p->state == P_WAIT_META) return accept_drop(l, "no metadata before the connect deadline"); WARN("net-sircl: accepting a connection timed out after %d ms (NET_SIRCL_CONNECT_TIMEOUT_MS)", g.connect_timeout_ms); return accept_fail(l, ncclSystemError); } if (p->state == P_WAIT_META) { int r = recv_some(p->fd, &p->theirs, sizeof p->theirs, &p->got); - if (r < 0) return accept_fail(l, ncclRemoteError); + if (r < 0) return accept_drop(l, "closed before sending its metadata"); if (r == 0) return ncclSuccess; + /* Checked before any queue pair is created for it. */ + if (p->theirs.magic != NET_SIRCL_MAGIC) return accept_drop(l, "not a net-sircl peer"); p->c = comm_create(accept_dev(p->theirs.position, p->theirs.lane, l->dev), 0); if (!p->c) return accept_fail(l, ncclSystemError); p->c->lane = p->theirs.lane; diff --git a/net-sircl/tests/failure_test.c b/net-sircl/tests/failure_test.c index d774796..c0d963f 100644 --- a/net-sircl/tests/failure_test.c +++ b/net-sircl/tests/failure_test.c @@ -1,22 +1,53 @@ -/* Exercise the public submit/test/close seam with a live but silent peer, - * vanished peers, and a provider that loses all forwarded writes/CQEs. */ +/* Exercise the public submit/test/close seam with a live but silent peer, vanished peers, and a + * provider that loses all forwarded writes/CQEs. + * + * failure_test + * + * send the peer never posts its receive and NET_SIRCL_PEER_WAIT_TIMEOUT_MS is set: the send + * fails at that bound + * recv the clear-to-send post never completes: the receive fails at + * NET_SIRCL_REQUEST_TIMEOUT_MS + * flight clear-to-send arrived and the payload writes never complete: the send fails at + * NET_SIRCL_REQUEST_TIMEOUT_MS + * lost the peer closed its connection: the request fails at once + * patient-send the peer never posts its receive and no peer-wait bound is set: the send keeps + * waiting well past NET_SIRCL_REQUEST_TIMEOUT_MS, as NCCL itself would, and fails only + * when the peer closes its connection + * patient-recv the clear-to-send post completes and the peer never sends: the receive keeps + * waiting likewise + * + * Every failure is sticky, shuts this side of the connection down so the peer learns of it, and + * leaves a comm that closes promptly. */ #include "../net_sircl.c" #include +static int swallow = 1; + +int __real_sccl_emu_ibv_post_send(struct ibv_qp *qp, struct ibv_send_wr *wr, struct ibv_send_wr **bad); int __wrap_sccl_emu_ibv_post_send(struct ibv_qp *qp, struct ibv_send_wr *wr, struct ibv_send_wr **bad) { - (void)qp; (void)wr; (void)bad; + if (!swallow) return __real_sccl_emu_ibv_post_send(qp, wr, bad); return 0; /* Accepted by provider, no delivery or completion: lost relay path. */ } +#define TRANSPORT_MS 100 +#define PATIENCE_MS (6 * TRANSPORT_MS) + int main(int argc, char **argv) { assert(argc == 4); + const char *mode = argv[2]; + int patient = !strncmp(mode, "patient-", 8); setenv("NET_SIRCL_TOPOLOGY", argv[1], 1); setenv("NET_SIRCL_POSITION", "0", 1); setenv("NET_SIRCL_REQUEST_TIMEOUT_MS", "100", 1); - int sending = strcmp(argv[2], "recv") != 0; + /* Only `send` bounds the wait for the peer application; the other modes keep the default (none). */ + if (!strcmp(mode, "send")) setenv("NET_SIRCL_PEER_WAIT_TIMEOUT_MS", "100", 1); + int sending = !strcmp(mode, "send") || !strcmp(mode, "flight") || !strcmp(mode, "lost") || + !strcmp(mode, "patient-send"); int peer = atoi(argv[3]); void *ctx = NULL; assert(sircl_init(&ctx, 0, NULL, NULL, NULL) == ncclSuccess); + assert(g.request_timeout_ms == TRANSPORT_MS); + assert(g.peer_wait_timeout_ms == (!strcmp(mode, "send") ? 100 : 0)); struct comm *c = comm_create(0, sending); assert(c); struct net_sircl_meta remote; @@ -26,36 +57,59 @@ int main(int argc, char **argv) { assert(!socketpair(AF_UNIX, SOCK_STREAM, 0, pair)); c->fd = pair[0]; assert(!set_nonblocking(c->fd)); - if (!strcmp(argv[2], "lost")) { close(pair[1]); pair[1] = -1; } + if (!strcmp(mode, "lost")) { close(pair[1]); pair[1] = -1; } + /* The receive's clear-to-send is delivered (the comm is connected to itself) and completes. */ + if (!strcmp(mode, "patient-recv")) swallow = 0; char data[1024] = {0}; void *request = NULL, *buf = data, *mr = NULL; size_t size = sizeof data; int tag = 0; - if (!strcmp(argv[2], "flight")) { + if (!strcmp(mode, "flight")) { c->ctrl->cts_seq[0] = 1; c->ctrl->cts[0].size = sizeof data; } int64_t start = now_ms(); ncclResult_t result = ncclSuccess; - int done = 0; + int done = 0, closed_at_peer = 0; + int64_t limit = patient ? PATIENCE_MS + 2000 : 2000; do { if (request) result = sircl_test(request, &done, NULL); else if (sending) result = sircl_isend(c, data, sizeof data, 0, NULL, NULL, &request); else result = sircl_irecv(c, 1, &buf, &size, &tag, &mr, NULL, &request); assert(!done); - } while (result == ncclSuccess && now_ms() - start < 2000); + if (patient && !closed_at_peer && now_ms() - start >= PATIENCE_MS) { + /* Six transport deadlines have passed with the peer alive and silent: still waiting. */ + assert(result == ncclSuccess && !c->error); + if (sending) assert(!request); + else assert(request && ((struct req *)request)->cts_done); + close(pair[1]); pair[1] = -1; closed_at_peer = 1; + } + } while (result == ncclSuccess && now_ms() - start < limit); assert(result == ncclRemoteError); - assert(now_ms() - start < 1500); - if (strcmp(argv[2], "lost")) assert(now_ms() - start >= 100); + if (patient) { + assert(closed_at_peer); + assert(now_ms() - start < PATIENCE_MS + 1500); + } else { + assert(now_ms() - start < 1500); + if (strcmp(mode, "lost")) assert(now_ms() - start >= TRANSPORT_MS); + } /* Failure is sticky even on a direct comm with no shared window. */ void *again = (void *)1; assert(sircl_isend(c, data, 1, 0, NULL, NULL, &again) == ncclRemoteError && !again); if (c->win) assert(c->win->error == ncclRemoteError); + /* The failed comm hung up: a peer still holding the connection reads end of stream. */ + assert(c->hung_up); + if (pair[1] >= 0) { + char b; + assert(recv(pair[1], &b, 1, MSG_DONTWAIT) == 0); + } int64_t closing = now_ms(); comm_destroy(c); if (pair[1] >= 0) close(pair[1]); assert(sircl_finalize(ctx) == ncclSuccess); assert(now_ms() - closing < 500); - printf("failure %s peer %d: bounded error and close\n", argv[2], peer); + printf("failure %s peer %d: %s\n", mode, peer, + patient ? "waited for the silent peer past the transport deadline, failed when it left" + : "bounded error and close"); return 0; } diff --git a/net-sircl/tests/layer_test.c b/net-sircl/tests/layer_test.c index 6e66a6b..cba5293 100644 --- a/net-sircl/tests/layer_test.c +++ b/net-sircl/tests/layer_test.c @@ -16,9 +16,18 @@ * returns within 2 s * peerloss the sender's process ends after connecting: the receiver's waiting request fails with * ncclRemoteError within 5 s instead of waiting forever - * timeout a listener that never accepts: connect fails within NET_SIRCL_CONNECT_TIMEOUT_MS (1.5 s) */ + * timeout a listener that never accepts: connect fails within NET_SIRCL_CONNECT_TIMEOUT_MS (1.5 s) + * stray three connections that are not a peer reach the listener first (closed at once, 56 bytes that + * are not metadata, silent until the deadline): each is dropped, and the peer's connection + * behind them is accepted and carries a message + * deepwindow a direct peer with a 64 MiB window and 4 KiB chunks sends 8 MiB (2048 chunks) while the + * provider is slow: payload writes stop short of the 1024-entry send queue and resume as + * completions arrive */ #define _GNU_SOURCE +#include +#include #include +#include #include #include #include @@ -270,6 +279,43 @@ static void windowed_send(void *comms[2]) { } } +/* -- deepwindow: more chunks than the send queue holds -- */ +#define DEEP_WINDOW (64u << 20) +#define DEEP_CHUNK 4096u +#define DEEP_MSG (8u << 20) +#define DEEP_QUEUE 1024u /* the plugin's send queue depth */ + +static void deep_recv(void *comm) { + uint8_t *buf = region(); + void *mr = NULL; + if (NET.regMr(comm, buf, REGION, NCCL_PTR_HOST, &mr) != ncclSuccess) die("regMr"); + int got = -1; + wait_done(post_recv(comm, buf, DEEP_MSG, 7, mr), &got); + if (got != (int)DEEP_MSG) die("the deep-window receive reported the wrong size"); + for (size_t j = 0; j < DEEP_MSG; ++j) + if (buf[j] != pattern(7, j)) die("a deep-window byte differs"); + NET.deregMr(comm, mr); + free(buf); +} + +static void deep_send(void *comm) { + uint8_t *buf = region(); + void *mr = NULL; + if (NET.regMr(comm, buf, REGION, NCCL_PTR_HOST, &mr) != ncclSuccess) die("regMr"); + for (size_t j = 0; j < DEEP_MSG; ++j) buf[j] = pattern(7, j); + wait_done(post_send(comm, buf, DEEP_MSG, 7, mr), NULL); + uint64_t max_inflight = 0, chunks = 0; + net_sircl_stats(comm, &max_inflight, &chunks); + if (chunks < DEEP_MSG / DEEP_CHUNK) die("the deep-window send was not chunked"); + if (!max_inflight || max_inflight >= (uint64_t)DEEP_QUEUE * DEEP_CHUNK) + die("payload writes were not held below the send queue depth"); + printf("net-sircl layer test deepwindow: %u MiB in %llu chunks exact; at most %llu chunks in flight below " + "a send queue of %u\n", DEEP_MSG >> 20, (unsigned long long)chunks, + (unsigned long long)(max_inflight / DEEP_CHUNK), DEEP_QUEUE); + NET.deregMr(comm, mr); + free(buf); +} + /* -- one message per comm, to show a connection carries data -- */ static void one_recv(void *comm, int tag) { uint8_t *buf = malloc(4096); @@ -306,11 +352,37 @@ static int receiver(int to_child, int from_child) { setenv("NET_SIRCL_ROUTES", "5=emu0/emu1", 1); } if (!strcmp(mode, "directlanes")) setenv("NET_SIRCL_STANDIN_DEVICES", "3", 1); + if (!strcmp(mode, "stray")) setenv("NET_SIRCL_CONNECT_TIMEOUT_MS", "1000", 1); /* the silent stray's wait */ void *ctx = init(); char handles[3][H]; void *listen[3], *comms[3] = {NULL, NULL, NULL}; for (int i = 0; i < listens; ++i) if (NET.listen(ctx, 0, handles[i], &listen[i]) != ncclSuccess) die("listen"); + int strays[2] = {-1, -1}; + if (!strcmp(mode, "stray")) { + /* Queued ahead of the peer, which has not been told the port yet. */ + struct net_sircl_handle h; + memcpy(&h, handles[0], sizeof h); + struct sockaddr_in sa; + memset(&sa, 0, sizeof sa); + sa.sin_family = AF_INET; + sa.sin_port = h.port; + sa.sin_addr.s_addr = h.addr; + for (int k = 0; k < 3; ++k) { + int fd = socket(AF_INET, SOCK_STREAM, 0); + if (fd < 0 || connect(fd, (struct sockaddr *)&sa, sizeof sa)) die("a stray connection"); + if (k == 0) { + close(fd); /* a probe: connects and leaves */ + continue; + } + if (k == 1) { /* bytes that are not net-sircl metadata */ + char junk[sizeof(struct net_sircl_meta)]; + memset(junk, 0x5a, sizeof junk); + if (write(fd, junk, sizeof junk) != (ssize_t)sizeof junk) die("stray bytes"); + } + strays[k - 1] = fd; /* k == 2 stays silent until the listener's deadline */ + } + } send_handles(to_child, handles, listens); if (!strcmp(mode, "timeout")) { int status = 0; @@ -324,6 +396,13 @@ static int receiver(int to_child, int from_child) { plain_recv(comms[0]); } else if (!strcmp(mode, "windowed")) { windowed_recv(comms); + } else if (!strcmp(mode, "stray")) { + one_recv(comms[0], 40); + for (int k = 0; k < 2; ++k) close(strays[k]); + printf("net-sircl layer test stray: 3 stray connections dropped; the peer behind them was accepted and " + "its message is exact\n"); + } else if (!strcmp(mode, "deepwindow")) { + deep_recv(comms[0]); } else if (!strcmp(mode, "lanes") || !strcmp(mode, "directlanes")) { for (int i = 0; i < 3; ++i) { char name[64]; @@ -401,6 +480,14 @@ static int sender(int from_parent, int to_parent) { } if (!strcmp(mode, "directlanes")) setenv("NET_SIRCL_STANDIN_DEVICES", "3", 1); if (!strcmp(mode, "timeout")) setenv("NET_SIRCL_CONNECT_TIMEOUT_MS", "1500", 1); + if (!strcmp(mode, "deepwindow")) { + char w[32]; + snprintf(w, sizeof w, "0=%u", DEEP_WINDOW); + setenv("NET_SIRCL_WINDOWS", w, 1); /* a direct peer, explicitly windowed */ + snprintf(w, sizeof w, "%u", DEEP_CHUNK); + setenv("NET_SIRCL_CHUNK", w, 1); + setenv("SIRCL_EMU_LATENCY_NS", "2000000", 1); /* every chunk is posted before the first one completes */ + } void *ctx = init(); char handles[3][H]; read_handles(from_parent, handles, listens); @@ -438,6 +525,10 @@ static int sender(int from_parent, int to_parent) { plain_send(comms[0]); } else if (!strcmp(mode, "windowed")) { windowed_send(comms); + } else if (!strcmp(mode, "stray")) { + one_send(comms[0], 40); + } else if (!strcmp(mode, "deepwindow")) { + deep_send(comms[0]); } else if (!strcmp(mode, "teardown")) { uint8_t *buf = region(); void *mr = NULL; @@ -465,11 +556,13 @@ static int sender(int from_parent, int to_parent) { } int main(int argc, char **argv) { - static const char *const modes[] = {"plain", "windowed", "lanes", "directlanes", "teardown", "peerloss", "timeout"}; + static const char *const modes[] = {"plain", "windowed", "lanes", "directlanes", "teardown", "peerloss", "timeout", + "stray", "deepwindow"}; int known = 0; for (size_t i = 0; argc == 2 && i < sizeof modes / sizeof modes[0]; ++i) known |= !strcmp(argv[1], modes[i]); if (!known) { - fprintf(stderr, "usage: %s plain|windowed|lanes|directlanes|teardown|peerloss|timeout\n", argv[0]); + fprintf(stderr, "usage: %s plain|windowed|lanes|directlanes|teardown|peerloss|timeout|stray|deepwindow\n", + argv[0]); return 2; } mode = argv[1]; diff --git a/net-sircl/tests/settings_test.c b/net-sircl/tests/settings_test.c index 799f852..40f3912 100644 --- a/net-sircl/tests/settings_test.c +++ b/net-sircl/tests/settings_test.c @@ -2,6 +2,7 @@ * Link wrappers observe the provider boundary without changing the shared emulator. */ #include "../net_sircl.c" #include +#include static struct ibv_qp_attr observed; static int rts_calls, injected_status; @@ -151,6 +152,89 @@ int main(void) { } setting(deadlines[d], NULL); } + /* The peer-wait bound is optional: unset or 0 waits for the peer application as NCCL does. */ + const char *invalid_peer_waits[] = {"", "-1", "+1", " 100", "1x", "2147483648"}; + for (unsigned i = 0; i < sizeof invalid_peer_waits / sizeof invalid_peer_waits[0]; ++i) { + setting("NET_SIRCL_PEER_WAIT_TIMEOUT_MS", invalid_peer_waits[i]); + void *badctx = NULL; + assert(sircl_init(&badctx, 0, NULL, capture, NULL) == ncclInvalidArgument); + assert(!badctx && !g.refs && !g.ndevs); + assert(strstr(last_log, "NET_SIRCL_PEER_WAIT_TIMEOUT_MS")); + } + const char *peer_waits[] = {NULL, "0", "250"}; + for (unsigned i = 0; i < 3; ++i) { + setting("NET_SIRCL_PEER_WAIT_TIMEOUT_MS", peer_waits[i]); + void *okctx = NULL; + assert(sircl_init(&okctx, 0, NULL, capture, NULL) == ncclSuccess); + assert(g.peer_wait_timeout_ms == (i == 2 ? 250 : 0) && g.request_timeout_ms == 60000); + assert(sircl_finalize(okctx) == ncclSuccess); + } + setting("NET_SIRCL_PEER_WAIT_TIMEOUT_MS", NULL); + /* Settings that used to fall back to their default, or be truncated, fail initialization by name. */ + const char *rejected[][2] = { + {"NET_SIRCL_CHUNK", "0"}, {"NET_SIRCL_CHUNK", "-1"}, {"NET_SIRCL_CHUNK", "64k"}, + {"NET_SIRCL_CHUNK", "1073741825"}, {"NET_SIRCL_SPEED_MBPS", "0"}, {"NET_SIRCL_SPEED_MBPS", "fast"}, + {"NET_SIRCL_TC", "256"}, {"NET_SIRCL_TC", "-1"}, {"NET_SIRCL_RELAXED_ORDERING", "2"}, + {"NET_SIRCL_RELAXED_ORDERING", "yes"}, {"NET_SIRCL_ROUTE_CHECK", "2"}, {"NET_SIRCL_GID_INDEX", "256"}, + {"NET_SIRCL_GID_INDEX", "-1"}, {"NET_SIRCL_GID_INDEX", ""}, {"NET_SIRCL_OOB_ADDR", "not-an-address"}, + {"NET_SIRCL_OOB_ADDR", "10.0.0.300"}, {"NET_SIRCL_OOB_ADDR", "0.0.0.0"}, + }; + for (unsigned i = 0; i < sizeof rejected / sizeof rejected[0]; ++i) { + int oob = !strcmp(rejected[i][0], "NET_SIRCL_OOB_ADDR"); + setting(rejected[i][0], rejected[i][1]); + void *badctx = NULL; + assert(sircl_init(&badctx, 0, NULL, capture, NULL) == ncclInvalidArgument); + assert(!badctx && !g.refs && !g.ndevs); + assert(strstr(last_log, rejected[i][0])); + setting(rejected[i][0], oob ? "127.0.0.1" : NULL); + } + { + /* Accepted edges: the chunk floor and ceiling, and both ends of the small ranges. */ + setting("NET_SIRCL_CHUNK", "1"); + setting("NET_SIRCL_TC", "255"); + setting("NET_SIRCL_GID_INDEX", "0"); + setting("NET_SIRCL_ROUTE_CHECK", "0"); + setting("NET_SIRCL_RELAXED_ORDERING", "0"); + void *okctx = NULL; + assert(sircl_init(&okctx, 0, NULL, capture, NULL) == ncclSuccess); + assert(g.chunk == 4096 && g.traffic_class == 255 && !g.route_check && !g.relaxed_ordering); + assert(sircl_finalize(okctx) == ncclSuccess); + setting("NET_SIRCL_CHUNK", "1073741824"); + setting("NET_SIRCL_TC", NULL); + setting("NET_SIRCL_GID_INDEX", NULL); + setting("NET_SIRCL_ROUTE_CHECK", NULL); + setting("NET_SIRCL_RELAXED_ORDERING", NULL); + assert(sircl_init(&okctx, 0, NULL, capture, NULL) == ncclSuccess); + assert(g.chunk == 1u << 30 && g.traffic_class == 0 && g.route_check == 1 && g.relaxed_ordering == 1); + assert(sircl_finalize(okctx) == ncclSuccess); + setting("NET_SIRCL_CHUNK", NULL); + } + { + /* A forked child (a data-loader worker) inherits the host claim's descriptor. It must not keep the + * claim: the parent can finalize and initialize again while the child still lives. */ + void *owner = NULL; + assert(sircl_init(&owner, 0, NULL, capture, NULL) == ncclSuccess); + assert(g.owner_fd >= 0); + int hold[2]; + assert(!pipe(hold)); + pid_t child = fork(); + assert(child >= 0); + if (!child) { + char b; + close(hold[1]); + _exit(g.owner_fd < 0 && read(hold[0], &b, 1) == 0 ? 0 : 1); /* lives until the parent is done */ + } + close(hold[0]); + assert(sircl_finalize(owner) == ncclSuccess); + owner = NULL; + ncclResult_t again = sircl_init(&owner, 0, NULL, capture, NULL); + if (again != ncclSuccess) fprintf(stderr, "re-init after fork: %d: %s\n", (int)again, last_log); + assert(again == ncclSuccess); /* refused for as long as the child lives if it kept the claim */ + assert(sircl_finalize(owner) == ncclSuccess); + close(hold[1]); + int status = 0; + assert(waitpid(child, &status, 0) == child && WIFEXITED(status) && !WEXITSTATUS(status)); + } setting("NCCL_IB_TIMEOUT", "13"); setting("NCCL_IB_RETRY_CNT", "2"); valid(NULL, NULL, 20, 7); /* NCCL's environment does not override plugin settings. */ diff --git a/net-sircl/tests/test_net_sircl.py b/net-sircl/tests/test_net_sircl.py index 072f1e3..292f006 100644 --- a/net-sircl/tests/test_net_sircl.py +++ b/net-sircl/tests/test_net_sircl.py @@ -20,7 +20,8 @@ HERE = Path(__file__).resolve().parents[1] STANDIN = HERE / "tests" / "standin" -CORE = next(p for p in (HERE.parents[1] / "transport-core", HERE.parent / "transport-core") if (p / "VERSION").is_file()) +# The bundled core first, as net-sircl/Makefile chooses it. +CORE = next(p for p in (HERE.parent / "transport-core", HERE.parents[1] / "transport-core") if (p / "VERSION").is_file()) CORE_SOURCES = [str(CORE / "src" / f) for f in ("core.c", "topology.c", "sysfs.c")] CORE_SOURCES += [str(HERE / "net_sircl_plan.c")] FLAGS = ["-std=gnu11", "-O2", "-Wall", "-Wextra", "-Werror", "-pthread"] @@ -67,7 +68,8 @@ def test_silent_and_lost_peers_fail_and_close(self): str(HERE / "tests/failure_test.c"), str(STANDIN / "shm_verbs.c"), *CORE_SOURCES, "-Wl,--wrap=sccl_emu_ibv_post_send", "-o", str(exe)], check=True) for peer in (1, 3): - for mode in ("send", "recv", "flight", "lost"): + # The patient modes show that a peer which is merely late is waited for, as NCCL does. + for mode in ("send", "recv", "flight", "lost", "patient-send", "patient-recv"): with self.subTest(peer=peer, mode=mode): fabric = f"/sircl-failure-{os.getpid()}-{peer}-{mode}" env = {k: v for k, v in os.environ.items() if not k.startswith("NET_SIRCL_")} @@ -284,6 +286,15 @@ def test_a_vanished_peer_fails_the_waiting_request(self): def test_connect_gives_up_at_its_deadline(self): self.assertIn("connect failed after", self.run_layer("timeout")) + def test_stray_connections_do_not_fail_the_listener(self): + self.assertIn("3 stray connections dropped", self.run_layer("stray")) + + def test_direct_window_deeper_than_the_send_queue(self): + out = self.run_layer("deepwindow") + self.assertIn("8 MiB in 2048 chunks exact", out) + in_flight = int(out.split("at most ")[1].split(" chunks")[0]) + self.assertLess(in_flight, 1024) + # -- topology files -- def routes(self, text, position): with tempfile.NamedTemporaryFile("w", suffix=".topo", delete=False) as f: @@ -333,6 +344,24 @@ def test_topology_errors_are_named(self): self.assertIn("unknown key", self.routes("hosts a b\nflavour x\n", 0)) self.assertIn("a cable is", self.routes("hosts a b\ncabling explicit\ncable 0.port2 1.port0\n", 0)) self.assertIn("fewer than two hosts", self.routes("hosts a\n", 0)) + # A file without `cabling` used to parse into a topology with no cables and no routes. + self.assertIn("cabling is ring, path or explicit", self.routes("hosts a b\n", 0)) + self.assertIn("without a cable", self.routes("hosts a b c\ncabling explicit\ncable 0.port0 1.port1\n", 0)) + + def test_equally_short_lanes_follow_the_cables_on_a_turned_ring(self): + # A ring of four with hosts 2 and 3 turned around: 0.port0-1.port1, 1.port0-2.port0, 2.port1-3.port1, + # 3.port0-0.port1. Path A from 0 (out of its port 0) reaches 2 on port 0, so lane 0 leaves 2 by port 0 + # and lane 1 by port 1; assuming ring cabling would put them the other way round, on the wrong paths. + # Path A from 1 reaches 3 on port 1, as in ring cabling. + turned = ("hosts a b c d\ncabling explicit\ncable 0.port0 1.port1\ncable 1.port0 2.port0\n" + "cable 2.port1 3.port1\ncable 3.port0 0.port1\n") + self.assertEqual(self.routes(turned, 0)["2"].split(":")[0], "rocep1s0f0/roceP2p1s0f1") + self.assertEqual(self.routes(turned, 2)["0"].split(":")[0], "rocep1s0f0/roceP2p1s0f1") + self.assertEqual(self.routes(turned, 1)["3"].split(":")[0], "rocep1s0f0/roceP2p1s0f1") + self.assertEqual(self.routes(turned, 3)["1"].split(":")[0], "rocep1s0f1/roceP2p1s0f0") + # Ordinary ring cabling is unchanged: the higher position sends lane 0 out of port 1. + self.assertEqual(self.routes("hosts a b c d\ncabling ring\n", 3)["1"].split(":")[0], + "rocep1s0f1/roceP2p1s0f0") def test_source_shares_bound_all_path_and_ring_layouts(self): for n in (16, 64): # Larger route sets retain the aggregate fallback. @@ -439,11 +468,13 @@ def paths(prefix, target): for prev, relay, nxt in zip(p, p[1:], p[2:]): q = (relay, adj[relay][nxt], f % 2) queues.setdefault(q, {}).setdefault((s, f), set()).add(d) + # Both ends of every lane are on one path, including equally short directions on a ring whose + # hosts are cabled port 0 to port 0 (the higher position follows the cables, not port 1). + self.assertTrue(reverse_ok, (n, layout)) for budget in (65536, 262144, 327680): caps = (ctypes.c_uint32 * (n * 4))() derived = lib.test_route_caps(os.fsencode(path), budget, caps) - self.assertEqual(derived, int(reverse_ok), (n, layout)) - # Non-reciprocal tie routes deliberately keep the aggregate fallback. + self.assertEqual(derived, 1, (n, layout)) if not derived: self.assertEqual(set(caps), {budget // max(1, n - 2) // 64 * 64}) continue diff --git a/scripts/check_release_safety.py b/scripts/check_release_safety.py index 9c83e91..d6d9e39 100644 --- a/scripts/check_release_safety.py +++ b/scripts/check_release_safety.py @@ -70,17 +70,24 @@ def main(): site = [line.split("#", 1)[0].strip() for line in args.site_values.read_text().splitlines()] site = [value for value in site if value] try: - count = 0 + count = scanned = 0 for name in source_paths(args.root, args.tree): if name == "scripts/check_release_safety.py": continue data = (args.root / name).read_bytes() - if b"\0" in data: - continue - for line, rule in findings(data.decode("utf-8"), site): + scanned += 1 + # A NUL byte must not hide the rest of a file: scan binary content too, split at the NULs. + text = (data.replace(b"\0", b"\n").decode("utf-8", errors="replace") if b"\0" in data + else data.decode("utf-8")) + for line, rule in findings(text, site): print(json.dumps({"path": name, "line": line, "rule": rule})) count += 1 - print(f"Release-safety findings: {count}; matched content withheld; site values: {len(site)}") + if not scanned: + # A missing or empty tree is not a clean one. + print("Release-safety scan found no source files to inspect") + return 2 + print(f"Release-safety findings: {count}; matched content withheld; site values: {len(site)}; " + f"files scanned: {scanned}") return int(count > 0) except (OSError, ValueError, subprocess.SubprocessError): print("Release-safety scan could not inspect all source files") diff --git a/tests/test_release_safety.py b/tests/test_release_safety.py index fb894ad..9c48734 100644 --- a/tests/test_release_safety.py +++ b/tests/test_release_safety.py @@ -29,6 +29,23 @@ def test_documentation_address_is_accepted_without_git(self): (path / "guide.txt").write_text("Example address: 192.0.2.1") self.assertEqual(self.scan(path).returncode, 0) + def test_an_empty_or_missing_tree_is_not_a_clean_one(self): + with tempfile.TemporaryDirectory() as directory: + self.assertEqual(self.scan(directory).returncode, 2) + result = self.scan(Path(directory) / "absent") + self.assertEqual(result.returncode, 2) + self.assertNotIn("findings: 0", result.stdout) + + def test_a_nul_byte_does_not_hide_private_content(self): + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) + private = "spark-" + "abcd" + (path / "blob.bin").write_bytes(b"\x89PNG\0\0" + private.encode() + b"\0tail") + result = self.scan(path) + self.assertEqual(result.returncode, 1) + self.assertIn('"rule": "site-host"', result.stdout) + self.assertNotIn(private, result.stdout) + def test_symlinks_are_refused(self): with tempfile.TemporaryDirectory() as directory: path = Path(directory) diff --git a/tests/test_topology_conformance.py b/tests/test_topology_conformance.py new file mode 100644 index 0000000..f990c37 --- /dev/null +++ b/tests/test_topology_conformance.py @@ -0,0 +1,250 @@ +"""One topology file, two parsers: the plugin's (transport-core/src/topology.c) and fabric-tool's. + +Both read the file a site writes once and copies to every host. They must agree on which files are +valid, on the cables a valid file describes and on the lanes between every pair of hosts; otherwise the +relays fabric-tool installs and the routes the plugin uses describe different fabrics. CPU only. +""" +import ctypes +import itertools +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "fabric-tool")) + +from fabric_tool import model, topology # noqa: E402 + +MAX_POSITIONS = 64 +NAME = 64 + + +class CCable(ctypes.Structure): + _fields_ = [("a", ctypes.c_int), ("pa", ctypes.c_int), ("b", ctypes.c_int), ("pb", ctypes.c_int)] + + +class CTopology(ctypes.Structure): + """struct sircl_core_topology (transport-core/include/sircl_core/core.h).""" + + _fields_ = [("nhosts", ctypes.c_int), + ("host", (ctypes.c_char * NAME) * MAX_POSITIONS), + ("ncables", ctypes.c_int), + ("cable", CCable * (2 * MAX_POSITIONS)), + ("fn", ((ctypes.c_char * NAME) * 2) * 2), + ("budget", ctypes.c_uint32)] + + +def ring(n): + return [(i, 0, (i + 1) % n, 1) for i in range(n)] + + +def path(n): + return ring(n)[:-1] + + +def explicit(hosts, cables, extra=""): + names = " ".join(f"h{i}" for i in range(hosts)) + return f"hosts {names}\ncabling explicit\n" + "".join( + f"cable {a}.port{pa} {b}.port{pb}\n" for a, pa, b, pb in cables) + extra + + +def turned(cables, positions): + """The same cables with both ports of the given positions exchanged (those hosts turned around).""" + return [(a, pa ^ (a in positions), b, pb ^ (b in positions)) for a, pa, b, pb in cables] + + +def relabelled(cables, order): + """The same shape with the hosts in another order along it.""" + return [(order[a], pa, order[b], pb) for a, pa, b, pb in cables] + + +def valid_corpus(): + yield "pair, path", "hosts a b\ncabling path\n" + yield "pair, ring is one cable", "hosts a b\ncabling ring\n" + yield "pair, two cables", explicit(2, [(0, 0, 1, 1), (1, 0, 0, 1)]) + yield "pair, two cables port 0 to port 0", explicit(2, [(0, 0, 1, 0), (0, 1, 1, 1)]) + yield "pair, one cable port 1 to port 1", explicit(2, [(0, 1, 1, 1)]) + for n in range(3, 9): + names = " ".join(f"n{i}" for i in range(n)) + yield f"ring {n}", f"hosts {names}\ncabling ring\n" + yield f"path {n}", f"hosts {names}\ncabling path\n" + order = list(range(0, n, 2)) + list(range(1, n, 2)) + yield f"permuted path {n}", explicit(n, relabelled(path(n), order)) + yield f"permuted ring {n}", explicit(n, relabelled(ring(n), order)) + odd = set(range(1, n, 2)) + yield f"path {n}, odd hosts turned", explicit(n, turned(path(n), odd)) + yield f"ring {n}, odd hosts turned", explicit(n, turned(ring(n), odd)) + yield f"ring {n}, host 2 turned", explicit(n, turned(ring(n), {2})) + yield f"ring {n}, last host turned", explicit(n, turned(ring(n), {n - 1})) + yield "custom functions", "hosts a b c d\ncabling ring\nport0 mlx5_0 mlx5_1\nport1 mlx5_2 mlx5_3\n" + yield "one port renamed", "hosts a b c\ncabling path\nport1 left.a right-b\n" + yield "budget", "hosts a b c d\ncabling path\nrelay_budget 196608\n" + yield "comments and spacing", ("# leading comment\nnet-sircl-topology\n\n hosts a\tb c # trailing\n" + "\tcabling\tring\r\nrelay_budget 65536 # bytes\n") + yield "hosts on several lines", "hosts a b\nhosts c\nhosts d e\ncabling ring\n" + yield "ring plus nothing else", "cabling ring\nhosts z y x w\n" + yield "explicit cables in any order", explicit(4, [(2, 0, 3, 1), (0, 0, 1, 1), (1, 0, 2, 1)]) + yield "longest host name", f"hosts a {'h' * 63}\ncabling path\n" + yield "sixteen hosts", f"hosts {' '.join(f'h{i}' for i in range(16))}\ncabling ring\n" + + +def invalid_corpus(): + yield "no cabling", "hosts a b\n" + yield "unknown cabling", "hosts a b\ncabling mesh\n" + yield "two cabling words", "hosts a b\ncabling ring path\n" + yield "cabling without a word", "hosts a b\ncabling\n" + yield "one host", "hosts a\ncabling path\n" + yield "no hosts", "cabling path\n" + yield "a host twice", "hosts a b a\ncabling ring\n" + yield "unknown key", "hosts a b\ncabling path\nflavour x\n" + yield "explicit without cables", "hosts a b\ncabling explicit\n" + yield "a host without a cable", explicit(3, [(0, 0, 1, 1)]) + yield "two islands", explicit(4, [(0, 0, 1, 1), (2, 0, 3, 1)]) + yield "a port used twice", explicit(3, [(0, 0, 1, 1), (0, 0, 2, 1)]) + yield "a cable to itself", explicit(2, [(0, 0, 0, 1)]) + yield "a cable outside the hosts", explicit(2, [(0, 0, 5, 1)]) + yield "port 2", "hosts a b\ncabling explicit\ncable 0.port2 1.port0\n" + yield "cable with trailing text", "hosts a b\ncabling explicit\ncable 0.port0 1.port1x\n" + yield "cable with a sign", "hosts a b\ncabling explicit\ncable +0.port0 1.port1\n" + yield "cable with one end", "hosts a b\ncabling explicit\ncable 0.port0\n" + yield "cable with three ends", "hosts a b c\ncabling explicit\ncable 0.port0 1.port1 2.port0\n" + yield "cable joined by a dash", "hosts a b\ncabling explicit\ncable 0.port0-1.port1\n" + yield "ring plus a cable on a used port", "hosts a b c\ncabling ring\ncable 0.port0 2.port1\n" + yield "port line with one name", "hosts a b\ncabling path\nport0 only\n" + yield "port line with three names", "hosts a b\ncabling path\nport1 a b c\n" + yield "function with a slash", "hosts a b\ncabling path\nport0 ok bad/name\n" + yield "function too long", f"hosts a b\ncabling path\nport0 ok {'f' * 64}\n" + yield "budget with a sign", "hosts a b\ncabling path\nrelay_budget +65536\n" + yield "budget in hexadecimal", "hosts a b\ncabling path\nrelay_budget 0x10000\n" + yield "budget of zero", "hosts a b\ncabling path\nrelay_budget 0\n" + yield "budget with two words", "hosts a b\ncabling path\nrelay_budget 65536 65536\n" + yield "words after the header key", "hosts a b\ncabling path\nnet-sircl-topology 2\n" + yield "host name too long", f"hosts a {'h' * 64}\ncabling path\n" + yield "too many hosts", f"hosts {' '.join(f'h{i}' for i in range(65))}\ncabling ring\n" + + +class TopologyConformance(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.temp = tempfile.TemporaryDirectory(prefix="sircl-conformance-") + cls.root = Path(cls.temp.name) + library = cls.root / "topology.so" + subprocess.run(["cc", "-std=c11", "-O2", "-fPIC", "-shared", "-Wall", "-Wextra", "-Werror", + "-I", str(ROOT / "transport-core/include"), str(ROOT / "transport-core/src/topology.c"), + "-o", str(library)], check=True) + cls.lib = ctypes.CDLL(str(library)) + cls.lib.sircl_core_topology_parse.argtypes = [ctypes.c_char_p, ctypes.POINTER(CTopology), + ctypes.c_char_p, ctypes.c_size_t] + cls.lib.sircl_core_topology_route.argtypes = [ctypes.POINTER(CTopology), ctypes.c_int, ctypes.c_int, + ctypes.POINTER(ctypes.c_char_p), ctypes.POINTER(ctypes.c_int)] + + @classmethod + def tearDownClass(cls): + cls.temp.cleanup() + + def plugin(self, text): + """(struct, None) when the plugin's parser accepts the text, else (None, its message).""" + file = self.root / "case.topology" + file.write_bytes(text.encode()) + parsed = CTopology() + error = ctypes.create_string_buffer(512) + if self.lib.sircl_core_topology_parse(str(file).encode(), ctypes.byref(parsed), error, len(error)): + return None, error.value.decode() + return parsed, None + + @staticmethod + def tool(text): + """(Topology, None) when fabric-tool's parser accepts the text, else (None, its message).""" + try: + return topology.parse(text, path="case.topology"), None + except model.FabricError as error: + return None, str(error) + + def test_structure_layout_matches_the_header(self): + # nhosts, 64 names of 64 bytes, ncables, 128 cables of four ints, four names, budget. + self.assertEqual(ctypes.sizeof(CTopology), 4 + 64 * 64 + 4 + 128 * 16 + 4 * 64 + 4) + + def test_valid_files_mean_the_same_fabric_to_both(self): + count = 0 + for name, text in valid_corpus(): + with self.subTest(case=name): + c, c_error = self.plugin(text) + py, py_error = self.tool(text) + self.assertIsNotNone(c, f"the plugin refuses it: {c_error}") + self.assertIsNotNone(py, f"fabric-tool refuses it: {py_error}") + self.assertEqual([c.host[i].value.decode() for i in range(c.nhosts)], list(py.hosts)) + self.assertEqual([c.fn[p][lane].value.decode() for p in (0, 1) for lane in (0, 1)], + list(py.functions)) + self.assertEqual(c.budget, py.budget) + c_cables = {frozenset({(c.cable[i].a, c.cable[i].pa), (c.cable[i].b, c.cable[i].pb)}) + for i in range(c.ncables)} + py_cables = {frozenset({(cable.a, cable.a_port), (cable.b, cable.b_port)}) for cable in py.cables} + self.assertEqual(len(c_cables), c.ncables) + self.assertEqual(c_cables, py_cables) + fabric = py.group.layout.fabric + for a, b in itertools.permutations(range(c.nhosts), 2): + names = (ctypes.c_char_p * 2)() + relays = ctypes.c_int(-1) + self.assertEqual(self.lib.sircl_core_topology_route(ctypes.byref(c), a, b, names, + ctypes.byref(relays)), 2, (a, b)) + lanes = model.derive_lanes(fabric, a, b, 2, bindings=py.bindings) + self.assertEqual([names[0].decode(), names[1].decode()], + [lane.local.device for lane in lanes], (a, b)) + self.assertEqual({relays.value}, {lane.hops - 1 for lane in lanes}, (a, b)) + count += 1 + self.assertGreater(count, 50) + + def test_lanes_are_the_same_function_class_on_one_path_at_both_ends(self): + # The property the two derivations must share, checked on the plugin's side from the cables alone: + # following lane L from a, out of its port, arrives at b on the port of b's lane L toward a. + for name, text in valid_corpus(): + c, _ = self.plugin(text) + if c is None: + continue + port_of = {c.fn[p][lane].value: (p, lane) for p in (0, 1) for lane in (0, 1)} + far = {} + for i in range(c.ncables): + cable = c.cable[i] + far[(cable.a, cable.pa)] = (cable.b, cable.pb) + far[(cable.b, cable.pb)] = (cable.a, cable.pa) + + def lanes(a, b): + names = (ctypes.c_char_p * 2)() + relays = ctypes.c_int(-1) + self.lib.sircl_core_topology_route(ctypes.byref(c), a, b, names, ctypes.byref(relays)) + return [port_of[names[0]], port_of[names[1]]], relays.value + + with self.subTest(case=name): + for a, b in itertools.permutations(range(c.nhosts), 2): + forward, relays = lanes(a, b) + backward, _ = lanes(b, a) + for lane in (0, 1): + self.assertEqual(forward[lane][1], lane, (a, b)) + here, out = a, forward[lane][0] + for _ in range(relays + 1): + here, arrived = far[(here, out)] + out = 1 - arrived + self.assertEqual(here, b, (a, b, lane)) + self.assertEqual(backward[lane], (arrived, lane), (a, b, lane)) + + def test_invalid_files_are_refused_by_both(self): + for name, text in invalid_corpus(): + with self.subTest(case=name): + c, c_error = self.plugin(text) + py, py_error = self.tool(text) + self.assertIsNone(c, "the plugin accepts it") + self.assertIsNone(py, "fabric-tool accepts it") + self.assertTrue(c_error and py_error) + + def test_the_one_deliberate_difference(self): + # The emulation tests give both ports the same function names; relay admission then keeps the + # aggregate model. fabric-tool configures real devices and needs four distinct functions. + text = "hosts a b c\ncabling path\nport0 emu0 emu1\nport1 emu0 emu1\n" + self.assertIsNotNone(self.plugin(text)[0]) + self.assertIn("one function twice", self.tool(text)[1]) + + +if __name__ == "__main__": + unittest.main() diff --git a/transport-core/src/topology.c b/transport-core/src/topology.c index 3c40122..55c4734 100644 --- a/transport-core/src/topology.c +++ b/transport-core/src/topology.c @@ -1,46 +1,106 @@ #define _GNU_SOURCE #include +#include #include #include #include #include #define MAX_POSITIONS SIRCL_CORE_MAX_POSITIONS #define NET_SIRCL_MAX_LANES SIRCL_CORE_MAX_LANES +#define FIELD 64 /* bytes of a host or function name, terminator included */ +#define BLANK " \t\r\n" /* Extracted from net-sircl 7b81b968; see NOTICE. */ + +/* The grammar is shared with fabric-tool's parser (fabric_tool/topology.py): a file one of them accepts + * means the same cables to the other. tests/test_topology_conformance.py holds both to it. The parser + * refuses what it does not understand instead of guessing: an unknown key, a missing or misspelt + * `cabling`, extra words, a truncated name, a host without a cable. */ + +static int reject(char *err, size_t len, const char *fmt, ...) { + va_list ap; + va_start(ap, fmt); + if (err && len) vsnprintf(err, len, fmt, ap); + va_end(ap); + return -1; +} + +static void topo_distances(const struct sircl_core_topology *t, int from, int *dist); + +/* `.port<0|1>` and nothing else: decimal digits only, no sign, no trailing text. */ +static int cable_end(const char *text, int *host, int *port) { + const char *p = text; + long value = 0; + if (*p < '0' || *p > '9') return -1; + for (; *p >= '0' && *p <= '9'; ++p) + if (value < 1000000) value = value * 10 + (*p - '0'); /* any larger index is out of range anyway */ + if (strncmp(p, ".port", 5) || (p[5] != '0' && p[5] != '1') || p[6]) return -1; + *host = (int)value; + *port = p[5] - '0'; + return 0; +} + +/* A function name as fabric-tool accepts it: letters, digits and `_.:-`, starting with a letter, + * digit or `_`, at most 63 bytes. */ +static int function_name(const char *text) { + size_t n = strlen(text); + if (!n || n >= FIELD) return 0; + for (size_t i = 0; i < n; ++i) { + char ch = text[i]; + int word = (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9') || ch == '_'; + if (!word && (i == 0 || (ch != '.' && ch != ':' && ch != '-'))) return 0; + } + return 1; +} + /* Parse a topology file (net_sircl.h "Topology file"). 0 on success; `err` says why not. */ int sircl_core_topology_parse(const char *path, struct sircl_core_topology *t, char *err, size_t len) { memset(t, 0, sizeof *t); - snprintf(t->fn[0][0], 64, "rocep1s0f0"); - snprintf(t->fn[0][1], 64, "roceP2p1s0f0"); - snprintf(t->fn[1][0], 64, "rocep1s0f1"); - snprintf(t->fn[1][1], 64, "roceP2p1s0f1"); + snprintf(t->fn[0][0], FIELD, "rocep1s0f0"); + snprintf(t->fn[0][1], FIELD, "roceP2p1s0f0"); + snprintf(t->fn[1][0], FIELD, "rocep1s0f1"); + snprintf(t->fn[1][1], FIELD, "roceP2p1s0f1"); t->budget = 393216; /* 75 % of a ConnectX-7 hairpin queue of 512 KiB (SIRCL's relay budget) */ FILE *f = fopen(path, "r"); - if (!f) { - snprintf(err, len, "cannot open %s: %s", path, strerror(errno)); - return -1; - } + if (!f) return reject(err, len, "cannot open %s: %s", path, strerror(errno)); char line[1024], cabling[16] = ""; int lineno = 0, rc = 0; - while (fgets(line, sizeof line, f) && !rc) { + while (!rc && fgets(line, sizeof line, f)) { ++lineno; + size_t got = strlen(line); + if (got == sizeof line - 1 && line[got - 1] != '\n') { + /* The buffer is full without a line end: more of this line follows unless the file ends here. */ + int next = fgetc(f); + if (next != EOF) { + rc = reject(err, len, "%s:%d: the line is longer than %zu characters", path, lineno, sizeof line - 2); + break; + } + } char *hash = strchr(line, '#'); if (hash) *hash = '\0'; - char *save = NULL, *key = strtok_r(line, " \t\r\n", &save); + char *save = NULL, *key = strtok_r(line, BLANK, &save); if (!key) continue; if (!strcmp(key, "hosts")) { - for (char *h; (h = strtok_r(NULL, " \t\r\n", &save)) && t->nhosts < MAX_POSITIONS;) - snprintf(t->host[t->nhosts++], 64, "%s", h); + for (char *h; !rc && (h = strtok_r(NULL, BLANK, &save));) { + if (t->nhosts == MAX_POSITIONS) + rc = reject(err, len, "%s:%d: more than %d hosts", path, lineno, MAX_POSITIONS); + else if (strlen(h) >= FIELD) + rc = reject(err, len, "%s:%d: a host name is longer than %d characters", path, lineno, FIELD - 1); + else + snprintf(t->host[t->nhosts++], FIELD, "%s", h); + } } else if (!strcmp(key, "cabling")) { - char *v = strtok_r(NULL, " \t\r\n", &save); - snprintf(cabling, sizeof cabling, "%s", v ? v : ""); + char *v = strtok_r(NULL, BLANK, &save); + if (!v || strtok_r(NULL, BLANK, &save)) + rc = reject(err, len, "%s:%d: cabling takes one of ring, path, explicit", path, lineno); + else + snprintf(cabling, sizeof cabling, "%s", v); } else if (!strcmp(key, "cable")) { - char *x = strtok_r(NULL, " \t\r\n", &save), *y = strtok_r(NULL, " \t\r\n", &save); + char *x = strtok_r(NULL, BLANK, &save), *y = strtok_r(NULL, BLANK, &save); int a, pa, b, pb; - if (!x || !y || sscanf(x, "%d.port%d", &a, &pa) != 2 || sscanf(y, "%d.port%d", &b, &pb) != 2 || pa < 0 || - pa > 1 || pb < 0 || pb > 1 || t->ncables >= 2 * MAX_POSITIONS) { - snprintf(err, len, "%s:%d: a cable is `cable .port<0|1> .port<0|1>`", path, lineno); - rc = -1; + if (!x || !y || strtok_r(NULL, BLANK, &save) || cable_end(x, &a, &pa) || cable_end(y, &b, &pb)) { + rc = reject(err, len, "%s:%d: a cable is `cable .port<0|1> .port<0|1>`", path, lineno); + } else if (t->ncables >= 2 * MAX_POSITIONS) { + rc = reject(err, len, "%s: too many cables", path); } else { t->cable[t->ncables].a = a, t->cable[t->ncables].pa = pa; t->cable[t->ncables].b = b, t->cable[t->ncables].pb = pb; @@ -48,70 +108,77 @@ int sircl_core_topology_parse(const char *path, struct sircl_core_topology *t, c } } else if (!strcmp(key, "port0") || !strcmp(key, "port1")) { int p = key[4] - '0'; - for (int l = 0; l < NET_SIRCL_MAX_LANES; ++l) { - char *v = strtok_r(NULL, " \t\r\n", &save); - if (v) snprintf(t->fn[p][l], 64, "%s", v); + char *v[NET_SIRCL_MAX_LANES + 1]; + for (int l = 0; l <= NET_SIRCL_MAX_LANES; ++l) v[l] = strtok_r(NULL, BLANK, &save); + if (!v[0] || !v[1] || v[2]) + rc = reject(err, len, "%s:%d: %s requires exactly two device identifiers", path, lineno, key); + for (int l = 0; !rc && l < NET_SIRCL_MAX_LANES; ++l) { + if (!function_name(v[l])) + rc = reject(err, len, "%s:%d: invalid device identifier %s", path, lineno, v[l]); + else + snprintf(t->fn[p][l], FIELD, "%s", v[l]); } } else if (!strcmp(key, "relay_budget")) { - char *v = strtok_r(NULL, " \t\r\n", &save), *end; - unsigned long b = v ? strtoul(v, &end, 10) : 0; - if (!v || *end || b == 0 || b > UINT32_MAX) { - snprintf(err, len, "%s:%d: relay_budget is a positive byte count", path, lineno); - rc = -1; - } else { - t->budget = (uint32_t)b; + char *v = strtok_r(NULL, BLANK, &save); + unsigned long long b = 0; + int ok = v && *v && !strtok_r(NULL, BLANK, &save); + for (const char *p = v; ok && *p; ++p) { + if (*p < '0' || *p > '9') ok = 0; + else if ((b = b * 10 + (unsigned)(*p - '0')) > UINT32_MAX) ok = 0; } - } else if (strcmp(key, "net-sircl-topology")) { - snprintf(err, len, "%s:%d: unknown key %s", path, lineno, key); - rc = -1; + if (!ok || b == 0) rc = reject(err, len, "%s:%d: relay_budget is a positive byte count", path, lineno); + else t->budget = (uint32_t)b; + } else if (!strcmp(key, "net-sircl-topology")) { + if (strtok_r(NULL, BLANK, &save)) + rc = reject(err, len, "%s:%d: unknown words after net-sircl-topology", path, lineno); + } else { + rc = reject(err, len, "%s:%d: unknown key %s", path, lineno, key); } } + if (!rc && ferror(f)) rc = reject(err, len, "cannot read %s", path); fclose(f); if (rc) return rc; - if (t->nhosts < 2) { - snprintf(err, len, "%s: `hosts` names fewer than two hosts", path); - return -1; - } + if (t->nhosts < 2) return reject(err, len, "%s: `hosts` names fewer than two hosts", path); + for (int a = 0; a < t->nhosts; ++a) + for (int b = a + 1; b < t->nhosts; ++b) + if (!strcmp(t->host[a], t->host[b])) return reject(err, len, "%s: hosts names one host twice", path); /* ring and path: host i's port 0 is cabled to host i+1's port 1 (SIRCL's ring cabling). */ if (!strcmp(cabling, "ring") || !strcmp(cabling, "path")) { int n = t->nhosts, last = !strcmp(cabling, "ring") ? n : n - 1; if (n == 2 && last == 2) last = 1; /* a pair has one cable between its two hosts */ - if (t->ncables + last > 2 * MAX_POSITIONS) { - snprintf(err, len, "%s: too many cables", path); - return -1; - } + if (t->ncables + last > 2 * MAX_POSITIONS) return reject(err, len, "%s: too many cables", path); for (int i = 0; i < last; ++i) { t->cable[t->ncables].a = i, t->cable[t->ncables].pa = 0; t->cable[t->ncables].b = (i + 1) % n, t->cable[t->ncables].pb = 1; t->ncables++; } - } else if (strcmp(cabling, "explicit") && cabling[0]) { - snprintf(err, len, "%s: cabling is ring, path or explicit", path); - return -1; + } else if (strcmp(cabling, "explicit")) { + /* A missing `cabling` line used to yield a topology without cables, and so without routes. */ + return reject(err, len, "%s: cabling is ring, path or explicit", path); } for (int c = 0; c < t->ncables; ++c) if (t->cable[c].a < 0 || t->cable[c].a >= t->nhosts || t->cable[c].b < 0 || t->cable[c].b >= t->nhosts || - t->cable[c].a == t->cable[c].b) { - snprintf(err, len, "%s: a cable joins a host index outside 0-%d", path, t->nhosts - 1); - return -1; - } + t->cable[c].a == t->cable[c].b) + return reject(err, len, "%s: a cable joins a host index outside 0-%d", path, t->nhosts - 1); unsigned occupied[MAX_POSITIONS] = {0}; for (int c = 0; c < t->ncables; ++c) { int a = t->cable[c].a, b = t->cable[c].b; unsigned pa = 1u << t->cable[c].pa, pb = 1u << t->cable[c].pb; - if ((occupied[a] & pa) || (occupied[b] & pb)) { - snprintf(err, len, "%s: topology connects a port more than once", path); - return -1; - } + if ((occupied[a] & pa) || (occupied[b] & pb)) + return reject(err, len, "%s: topology connects a port more than once", path); occupied[a] |= pa; occupied[b] |= pb; } - for (int a = 0; a < t->nhosts; ++a) - for (int b = a + 1; b < t->nhosts; ++b) - if (!strcmp(t->host[a], t->host[b])) { - snprintf(err, len, "%s: hosts names one host twice", path); - return -1; - } + /* One fabric: every host is cabled, and the cables join them all. With two ports per host that is + * one path or one cycle. Relay admission is planned over the whole file, so a host the cables do + * not reach, or a second island, is a mistake in the file rather than something to route around. */ + for (int h = 0; h < t->nhosts; ++h) + if (!occupied[h]) + return reject(err, len, "%s: the cables leave host %d (%s) without a cable", path, h, t->host[h]); + int reach[MAX_POSITIONS]; + topo_distances(t, 0, reach); + for (int h = 0; h < t->nhosts; ++h) + if (reach[h] < 0) return reject(err, len, "%s: the cables do not join the hosts into one path or cycle", path); return 0; } @@ -130,10 +197,26 @@ static void topo_distances(const struct sircl_core_topology *t, int from, int *d } } +/* The far end of the cable in `port` of `host`: 1 with its host and arrival port, 0 for an empty port. */ +static int topo_cross(const struct sircl_core_topology *t, int host, int port, int *far, int *far_port) { + for (int c = 0; c < t->ncables; ++c) { + if (t->cable[c].a == host && t->cable[c].pa == port) { + *far = t->cable[c].b, *far_port = t->cable[c].pb; + return 1; + } + if (t->cable[c].b == host && t->cable[c].pb == port) { + *far = t->cable[c].a, *far_port = t->cable[c].pa; + return 1; + } + } + return 0; +} + /* The route from `me` to `peer` as lane functions (names) and relays. One shortest direction: both functions - * of that port. Two (opposite ends of an even ring): lane 0 follows the path that leaves the lower position - * through its port 0 and lane 1 the other, as SIRCL's planner splits them (sparkring_sircl/routes.py - * derive_lanes), so both ends name the same function class per lane. -1 when the peer is unreachable. */ + * of that port. Two (opposite ends of an even ring, or a pair joined by two cables): lane 0 follows the path + * that leaves the lower position through its port 0 and lane 1 the other, as SIRCL's planner splits them + * (sparkring_sircl/routes.py derive_lanes), so both ends name the same function class per lane on the same + * path. -1 when the peer is unreachable. */ int sircl_core_topology_route(const struct sircl_core_topology *t, int me, int peer, const char **fn, int *relays) { if (!t || !fn || !relays || me < 0 || peer < 0 || me >= t->nhosts || peer >= t->nhosts) return -1; int from_me[MAX_POSITIONS], from_peer[MAX_POSITIONS]; @@ -156,10 +239,22 @@ int sircl_core_topology_route(const struct sircl_core_topology *t, int me, int p fn[1] = t->fn[p][1]; return 2; } - /* Both ports start a shortest path: path A leaves the lower of the two positions through port 0. At the - * lower position that is its own port 0; at the higher position path A arrives, so it leaves by the port - * that the path from the lower position's port 0 reaches it on: in ring cabling, port 1. */ - int a_port = me < peer ? 0 : 1; + /* Both ports start a shortest path. Path A leaves the lower of the two positions through its port 0. The + * higher position sends lane 0 out of the port on which path A arrives there: port 1 in ring cabling, and + * whichever port the cables give when explicit cabling turns a host around. Assuming port 1 for every + * cabling put the two ends of a lane on different paths. */ + int a_port = 0; + if (me > peer) { + int at = peer, out = 0; + for (int hop = 0; hop < d; ++hop) { + int next, in; + if (!topo_cross(t, at, out, &next, &in)) return -1; + at = next; + a_port = in; + out = 1 - in; + } + if (at != me) return -1; + } fn[0] = t->fn[a_port][0]; fn[1] = t->fn[1 - a_port][1]; return 2; diff --git a/transport-core/tests/test_planning.py b/transport-core/tests/test_planning.py index 41df6b7..0a8f9cd 100644 --- a/transport-core/tests/test_planning.py +++ b/transport-core/tests/test_planning.py @@ -74,6 +74,66 @@ def test_topology_rejects_ambiguous_ports_and_duplicate_hosts(self): self.assertEqual(self.lib.sircl_core_topology_parse(str(path).encode(), out, error, len(error)), -1) self.assertIn(expected, error.value) + def parse(self, text): + path = self.root / "case.topology" + path.write_bytes(text.encode()) + out = ctypes.create_string_buffer(16384) + error = ctypes.create_string_buffer(256) + rc = self.lib.sircl_core_topology_parse(str(path).encode(), out, error, len(error)) + return rc, error.value.decode() + + def test_topology_refuses_what_it_would_have_guessed(self): + long_name = "h" * 64 + many = " ".join(f"h{i}" for i in range(65)) + for text, expected in ( + ("hosts a b\n", "cabling is ring, path or explicit"), # no cabling: no cables, no routes + ("hosts a b\ncabling mesh\n", "cabling is ring, path or explicit"), + ("hosts a b\ncabling ring path\n", "cabling takes one of"), + ("hosts a b\ncabling explicit\n", "without a cable"), + ("hosts a b c\ncabling explicit\ncable 0.port0 1.port1\n", "leave host 2 (c) without a cable"), + ("hosts a b c d\ncabling explicit\ncable 0.port0 1.port1\ncable 2.port0 3.port1\n", + "do not join the hosts into one path or cycle"), + ("hosts a b\ncabling explicit\ncable 0.port0 1.port1x\n", "a cable is"), # trailing text + ("hosts a b\ncabling explicit\ncable -0.port0 1.port1\n", "a cable is"), # a sign + ("hosts a b\ncabling explicit\ncable 0.port0 1.port1 2.port0\n", "a cable is"), + ("hosts a b\ncabling explicit\ncable 0.port0 7.port1\n", "outside 0-1"), + ("hosts a b\ncabling path\nport0 only_one\n", "requires exactly two"), + ("hosts a b\ncabling path\nport1 a b c\n", "requires exactly two"), + ("hosts a b\ncabling path\nport0 ok bad/name\n", "invalid device identifier"), + ("hosts a b\ncabling path\nport0 ok " + "f" * 64 + "\n", "invalid device identifier"), + (f"hosts a {long_name}\ncabling path\n", "longer than 63 characters"), # was silently cut short + (f"hosts {many}\ncabling path\n", "more than 64 hosts"), # was silently dropped + ("hosts a b\ncabling path\nrelay_budget 65536 extra\n", "positive byte count"), + ("hosts a b\ncabling path\nrelay_budget -65536\n", "positive byte count"), + ("hosts a b\ncabling path\nrelay_budget 0x10000\n", "positive byte count"), + ("hosts a b\ncabling path\nrelay_budget 99999999999\n", "positive byte count"), + ("hosts a b\ncabling path\nnet-sircl-topology 2\n", "unknown words"), + ("hosts a b\ncabling path\n# " + "x" * 1100 + "\n", "longer than 1022 characters")): + with self.subTest(text=text[:60]): + rc, error = self.parse(text) + self.assertEqual(rc, -1, text[:80]) + self.assertIn(expected, error) + + def test_topology_accepts_the_documented_forms(self): + sixty_three = "h" * 63 + many = " ".join(f"h{i}" for i in range(64)) + for text in ( + "hosts a b\ncabling path\n", + "hosts a b\ncabling ring\n", # a pair: one cable, as path + "# comment\nnet-sircl-topology\nhosts a b c # trailing comment\n\tcabling\tring\r\n", + "hosts a b\nhosts c d\ncabling path\nrelay_budget 196608\n", # hosts lines append + "hosts a b\ncabling explicit\ncable 0.port0 1.port1\ncable 1.port0 0.port1\n", # two cables + "hosts a b c\ncabling explicit\ncable 2.port0 0.port1\ncable 1.port1 0.port0\n", + "hosts a b\ncabling path\nport0 emu0 emu1\nport1 emu0 emu1\n", # aliased names: emulation + "hosts a b\ncabling path\nport0 mlx5_0 mlx5-1.a:b\nport1 _x y\n", + f"hosts a {sixty_three}\ncabling path\n", + f"hosts {many}\ncabling ring\n", + "hosts a b\ncabling path\n# " + "x" * 1019, # a full last line without a line end + ): + with self.subTest(text=text[:60]): + rc, error = self.parse(text) + self.assertEqual(rc, 0, error) + if __name__ == "__main__": unittest.main() From a85d0bd0050d962e1e18eaecdad2fb0851181133 Mon Sep 17 00:00:00 2001 From: Cody Cessna <87842395+FujitsuPolycom@users.noreply.github.com> Date: Mon, 9 Nov 2026 18:48:40 -0600 Subject: [PATCH 2/2] Build env_long only for the stand-in, where it is still used Every plugin setting now goes through env_range, so the production build no longer calls env_long and -Werror=unused-function rejected it. Only NET_SIRCL_STANDIN_DEVICES, a test knob of the stand-in build, still uses the lenient parser. Regenerate SOURCE.json for the changed header. Co-Authored-By: Claude Fable 5.2 --- SOURCE.json | 2 +- net-sircl/net_sircl_config.h | 3 +++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/SOURCE.json b/SOURCE.json index dd0e45b..0af7bb5 100644 --- a/SOURCE.json +++ b/SOURCE.json @@ -142,7 +142,7 @@ "net-sircl/net_sircl.h": "de03b0ae808c101c2a3acc1dc7361b78eaf3d6baefa94f21af97723cb4a978d1", "net-sircl/net_sircl_admission.h": "6e92a7e07863fc7667f1db549ac89761a34a4a372388497915fb6c362fea1409", "net-sircl/net_sircl_compat.h": "0053800750c2f061a1254d1db95e65e4317de000c1b52873c0fe2cec9afafdf9", - "net-sircl/net_sircl_config.h": "af52fb32b73d7ed3a60e08bad0a5c5567cbf2614f86a27d12e200000ab2265de", + "net-sircl/net_sircl_config.h": "872feba25ac32d7e4e5e1444787edb8fe78188b6484e8fac58758dbc092dac37", "net-sircl/net_sircl_connection.h": "901f799e6964445294f2a5fbca0413419d601f8a0cd5bde59f948a8650cff067", "net-sircl/net_sircl_plan.c": "6fc1f03374562864b5b5898a54f4b2cf471e6d11003af83839e0f5a1f777e856", "net-sircl/net_sircl_plan.h": "dcb857dce8247ff61756e216e90cfd40c6ce3a2b24f5e990b39ec561d2169526", diff --git a/net-sircl/net_sircl_config.h b/net-sircl/net_sircl_config.h index 4da200e..81d31fe 100644 --- a/net-sircl/net_sircl_config.h +++ b/net-sircl/net_sircl_config.h @@ -1,5 +1,7 @@ /* Private configuration boundary: validated settings and topology-to-device binding. */ /* -- settings -- */ +#ifdef NET_SIRCL_STANDIN +/* Lenient parsing, for the stand-in's own test knob only; every plugin setting goes through env_range. */ static long env_long(const char *name, long fallback) { const char *v = getenv(name); if (!v || !*v) return fallback; @@ -7,6 +9,7 @@ static long env_long(const char *name, long fallback) { long x = strtol(v, &end, 10); return *end ? fallback : x; } +#endif /* Reject malformed or overflowing QP fields before opening devices; never truncate to uint8_t. */ static ncclResult_t env_range(const char *name, int fallback, int min, int max, int *out) {