Files
netris-nestri/apps/nesdoctor/src/hostreq.rs
Wanjohi 79f1732a14 feat(nesdoctor): a host readiness checker that measures instead of asking (#310)
The first executable form of our host requirements. Until now a machine
was qualified by a human reading a table of hard requirements — and a
requirement that nothing can check is one that is silently optional.

It also replaces a form. Everything we wanted from a prospective host is
measurable, and most of it **cannot be answered honestly by a human
anyway**: almost nobody knows their real upstream, and essentially
nobody has ever seen their own bufferbloat figure. What's left for the
questions is only what a machine cannot know — intent, and what someone
already pays.

## What it does

```
nesdoctor
```

- **Checks every hard requirement**: `/dev/kvm`, an AMD or Intel GPU
with a DRM render node, `VK_KHR_video_encode_queue` plus a codec,
`virglrenderer`, the two stores, the `io` cgroup controller,
`virtiofsd`. Pass / fail / **unknown**, and unknown is never collapsed
into fail — a machine we could not ask is not a machine that failed, and
losing a capable host to a missing `lspci` is the failure mode that
matters.
- **Measures upstream and, the point of the whole thing, added latency
under load.** Grade bands come from the frame budget rather than
convention: the network allowance is ~40 ms because render, encode,
decode, display and jitter buffer have already spent ~58 ms.
- **Reads Steam, only with an explicit yes**, for library size and shape
plus an hour-of-day histogram of launches — one sample per title, which
is a real distribution obtained without asking anybody anything.
- **Asks at most five questions**, branched on what was found, all
skippable.

## No server

Nothing is uploaded and no telemetry endpoint exists. The network test
talks to Cloudflare's public speed-test sink and to `1.1.1.1`, neither
of which is ours. The output is a line on the terminal that the person
may choose to paste.

The shareable line carries **no hostname, IP, username, game title or
path** — a size band rather than a size, hours rather than dates. The
long version, which does include titles and paths, stays in a local JSON
file the person is told the path of.

That is a property of the design and not a promise about our intentions:
there is nothing to switch on later.

```
nesdoctor 0.1.0 | linux/x86_64 | gpu=AMD Barcelo | cpu=12t ram=13G |
kvm=y venc=y zfs=n boxfs=n io=y | up=28Mbps rtt=179ms bloat=+19ms grade=B |
disk=91G | edge=KE/JNB | steam=1 titles/<100G | plays=20-03h n=74 |
role=- share=- pays=- | HOST-READY-LOCAL
```

## Five bugs found by running it, every one of which would have produced
wrong data

- **`vulkaninfo --summary` lists ZERO `VK_KHR_video` entries** where
full `vulkaninfo` lists five on the same machine. Preferring the summary
reported "not advertised" on a card that advertises it — a false
negative on the check most likely to disqualify a host.
- **btrfs subvolumes counted as separate disks**: `/`, `/home` and
`/srv` each reporting 91 GiB of one 91 GiB device. Now deduped by
backing device, which the two-stores check needs anyway since it wants
*separate devices*.
- **Proton and the Steam Linux Runtimes are installed like games and are
not games.** Five of eight entries on the test machine, so the title
count was 5× too high and the library-shape question was corrupted.
- **`--quiet` printed the whole questionnaire** before its summary line,
breaking the one thing `--quiet` promises. Prompts are now skipped when
output is quiet or stdin is not a terminal — and a pipe is explicitly
*not* treated as consent to read a Steam library, unlike `--yes`.
- Boot history was reporting `13.2 h/day` off **two days** of history.
Under a three-day span it now reports the span and no rate.

## One finding, now encoded as a verdict

The development connection measures **179 ms idle RTT, served from
Johannesburg**. That machine passes every other check and cannot host
for a European player, because it is distance and no upgrade shortens
it.

`HOST-READY-LOCAL` exists for exactly that case, and the wording is
deliberate:

> Every requirement passes and your uplink queues cleanly. But the idle
round trip to the nearest major network is already most of the latency
budget, and that is distance rather than a fault: no upgrade shortens
it. So this machine is a good host for people on your side of the world
and cannot be one for anybody else. **If you are somewhere without a
cloud gaming edge, that is not a consolation prize — it is the only way
anyone there gets a playable stream.**

## CI

- **`ci.yml` gains a `nesdoctor` job** — fmt, `clippy -D warnings`,
test, one real run. Scoped to this member deliberately: the rest of the
Rust half has never been under CI, so `--workspace` would turn every PR
red for unrelated reasons. Widen it one member at a time.
- **`release-nesdoctor.yml`** builds four targets on tag `nesdoctor-v*`
— x86_64 linux-musl, x86_64 windows-msvc, aarch64 and x86_64 macOS —
with `SHA256SUMS`. musl rather than glibc so one Linux binary runs on
every distro.

The step that justifies the workflow **runs the binary it just built,
network included**. `ring` under rustls resolves root certificates
through the host trust store, so a static musl build can compile cleanly
and then fail TLS on the machine it ships to — breaking the network
test, silently, and only for other people. The step fails the build if
the summary line comes back `net=unmeasured`.

## Dependencies

Four: `anyhow`, `clap`, `serde`, `ureq`. The VDF parser, every platform
probe and the text wrapping are in-tree. A binary handed to strangers
has a dependency tree that is part of its interface, so anything that
could be done with `std` is.

4 MB release binary.

## What it deliberately does not claim

- **A pass is not a promise.** Every check is a *necessary* condition,
and nothing here runs under load — a machine that passes can still fail
on block I/O.
- **The encode extension being advertised is not proof the path works.**
We have had a correct extension list over a broken path before, so that
row says so.
- **Whether `libvirglrenderer` carries the native-context patches cannot
be determined from outside**, so that row reports presence only and
stays `unknown` rather than `pass`.










<!-- greptile_comment -->

<h3>Greptile Summary</h3>

The PR adds the nesdoctor host-readiness executable, local Steam
analysis, network measurement, installers, CI validation, and
multi-platform release packaging. Two attempted correctness fixes remain
incomplete:
- physical disk deduplication does not resolve common device-mapper
source names before comparing backing devices
- unknown historical Steam appids can still be counted as game launches
without passing runtime filtering

<h3>Confidence Score: 3/5</h3>

The PR is not yet safe to merge because shared LVM-backed stores can be
reported as physically independent and unknown Steam tools can still be
reported as game launches.

The new disk resolver fails open for common device-mapper names,
preserving a false host-readiness verdict, while Steam history still
counts absent appids without determining whether they are games or
runtime tools.

**Files Needing Attention:** apps/nesdoctor/src/sys.rs,
apps/nesdoctor/src/hostreq.rs, apps/nesdoctor/src/steam.rs

<h3>Important Files Changed</h3>




| Filename | Overview |
|----------|----------|
| apps/nesdoctor/src/sys.rs | Adds system and disk discovery, but
unresolved device-mapper names undermine physical-backing comparisons. |
| apps/nesdoctor/src/hostreq.rs | Implements host requirement verdicts
and uses physical-device sets that can falsely classify shared LVM
backing as independent. |
| apps/nesdoctor/src/steam.rs | Adds manifest and launch-history
analysis, but unknown appids bypass runtime classification and
contaminate launch metrics. |
| apps/nesdoctor/src/net.rs | Adds bounded upload-based upstream and
bufferbloat measurement; the previously reported unbounded request path
is addressed. |
| .github/workflows/release-nesdoctor.yml | Builds, smoke-tests,
packages, checksums, and publishes the four release targets. |
| .github/workflows/ci.yml | Adds focused formatting, linting, testing,
and offline execution checks for nesdoctor. |


<h3>Flowchart</h3>

```mermaid
%%{init: {'theme': 'neutral'}}%%
flowchart LR
  Run[nesdoctor] --> Host[Host requirement probes]
  Run --> Net[Upload and latency measurement]
  Run --> Consent{Steam consent}
  Consent -->|yes| Steam[Installed manifests and LastPlayed records]
  Host --> Physical[Resolve filesystem sources to physical devices]
  Physical --> Verdict[Host readiness verdict]
  Net --> Report[Detailed JSON and shareable summary]
  Steam --> Report
  Verdict --> Report
```

<details><summary>Prompt To Fix All With AI</summary>

`````markdown
### Issue 1
apps/nesdoctor/src/sys.rs:369-374
**Mapper devices remain unresolved**

When root and box-store filesystems are separate LVM or dm-crypt mappings on the same physical disk, `df` supplies `/dev/mapper/...` names that do not exist under `/sys/class/block`. This branch returns those unrelated logical names unchanged, so the overlap check passes stores that still share one physical I/O queue.

### Issue 2
apps/nesdoctor/src/steam.rs:247-250
**Unknown appids bypass runtime filtering**

If `localconfig.vdf` retains `LastPlayed` data for an uninstalled Proton build, Steam runtime, or other non-game tool, its appid is absent from the installed-manifest map and this branch treats it as an uninstalled game. The tool activity then changes the launch histogram, peak window, and shareable `n` value.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.
`````

</details>

<sub>Reviews (5): Last reviewed commit: ["fix(nesdoctor): three valid P1
findings
..."](7afc8929a6)
| [Re-trigger
Greptile](https://app.greptile.com/api/retrigger?id=59231233)</sub>

> Greptile also left **2 inline comments** on this PR.

<!-- /greptile_comment -->
2026-09-02 12:52:47 +03:00

322 lines
12 KiB
Rust

//! Can this machine run a box?
//!
//! One check per hard requirement for running a box, in the order our host
//! requirements list them. This is the first thing that has ever *executed* that
//! list — until now a host was qualified by a human reading a table, and a
//! requirement nothing can check is a requirement that is silently optional.
//!
//! Three deliberate limits, stated because a green result here is not a promise:
//!
//! - **`vulkaninfo` is not sufficient by itself.** The contract says so twice,
//! we have had the case that proves it: extension present, path still broken. So the encode row reports what the extension list says
//! and labels it as such.
//! - **The renderer is not checked at all, on purpose.** It used to be, and the
//! row could only ever say "present, patch state unknown" — which is a row
//! that cannot pass. The box now carries its own virglrenderer and Mesa
//! inside the image it runs in, so the host's copies are not on the path and
//! asking about them told a prospective host their machine was wrong when it
//! was not.
//! - **Nothing here is measured under load.** A host that passes every row can
//! still fail on block I/O, which is the real density ceiling and needs a
//! benchmark rather than a probe.
use serde::Serialize;
use crate::sys::{self, SysInfo};
/// A single requirement's outcome.
///
/// `Unknown` is a first-class result and is never collapsed into `Fail`. The
/// difference matters: a failed check is a machine that cannot host, an unknown
/// one is a machine we could not ask, and reporting the second as the first is
/// how you lose a capable host to a missing `lspci`.
#[derive(Debug, Serialize, Clone, Copy, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum State {
Pass,
Fail,
Unknown,
}
#[derive(Debug, Serialize, Clone)]
pub struct Check {
pub id: &'static str,
pub what: &'static str,
pub state: State,
pub detail: String,
/// True when a `Fail` here means the machine cannot host at all.
pub blocking: bool,
}
#[derive(Debug, Serialize)]
pub struct HostReport {
pub checks: Vec<Check>,
/// `true` only when no blocking check failed.
pub could_host: bool,
/// Blocking checks we could not determine. A host with these is a
/// *maybe*, and saying so is the point.
pub unknowns: usize,
}
pub fn probe(sys: &SysInfo) -> HostReport {
let mut c: Vec<Check> = Vec::new();
// Not Linux: every row below is meaningless, and pretending otherwise
// produces a page of red for a machine that was never a candidate. A
// Windows box is a *client*, which is a perfectly good thing to be.
if sys.os != "linux" {
c.push(Check {
id: "os",
what: "Linux with KVM",
state: State::Fail,
detail: format!(
"this is {}. A host must be Linux; nesbox is a microVM hypervisor. \
As a client, this machine is fine and nothing below applies.",
sys.os
),
blocking: true,
});
return HostReport {
could_host: false,
unknowns: 0,
checks: c,
};
}
// --- KVM -------------------------------------------------------------
let kvm = sys::exists("/dev/kvm");
let kvm_rw = std::fs::OpenOptions::new()
.read(true)
.write(true)
.open("/dev/kvm")
.is_ok();
c.push(Check {
id: "kvm",
what: "/dev/kvm present and openable",
state: if kvm_rw { State::Pass } else { State::Fail },
detail: match (kvm, kvm_rw) {
(true, true) => "yes".into(),
(true, false) => {
"present but not openable — you are not in the `kvm` group, or virtualisation \
is disabled in firmware"
.into()
}
_ => {
"missing — enable SVM/VT-x in firmware, or this is a VM without nested virt".into()
}
},
blocking: true,
});
// --- GPU vendor and render node --------------------------------------
let usable: Vec<_> = sys
.gpus
.iter()
.filter(|g| {
g.render_node.is_some() && matches!(g.vendor.as_deref(), Some("AMD") | Some("Intel"))
})
.collect();
let nvidia_only = !sys.gpus.is_empty()
&& sys
.gpus
.iter()
.all(|g| g.vendor.as_deref() == Some("NVIDIA"));
c.push(Check {
id: "gpu",
what: "an AMD or Intel GPU with a DRM render node",
state: if !usable.is_empty() {
State::Pass
} else {
State::Fail
},
detail: if let Some(g) = usable.first() {
format!(
"{} at {}",
g.name,
g.render_node.clone().unwrap_or_default()
)
} else if nvidia_only {
"NVIDIA only. Nvidia needs virtio-nvgpu, which is not funded — so this card \
cannot host today. It is a fine client."
.into()
} else if sys.gpus.is_empty() {
"no GPU found under /sys/class/drm".into()
} else {
format!(
"found {} but none with both a supported vendor and a render node",
sys.gpus.len()
)
},
blocking: true,
});
// --- Vulkan Video encode ---------------------------------------------
// The contract is explicit that this is stricter than "has a hardware
// encoder": VA-API and NVENC are far more common than this extension, so a
// machine can encode well and still fail.
// `--summary` is NOT usable here and the order used to be the other way
// round. Measured on the development laptop 2026-09-02: `vulkaninfo
// --summary` lists **zero** `VK_KHR_video*` entries while full `vulkaninfo`
// lists five on the same machine — so preferring the summary reported "not
// advertised" on a card that advertises it, which is a false negative on
// the one check most likely to disqualify a host.
let vk = sys::sh("vulkaninfo", &[]).unwrap_or_default();
let has_encode_q = vk.contains("VK_KHR_video_encode_queue");
let has_codec = vk.contains("VK_KHR_video_encode_h264")
|| vk.contains("VK_KHR_video_encode_h265")
|| vk.contains("VK_KHR_video_encode_av1");
c.push(Check {
id: "vkvideo",
what: "VK_KHR_video_encode_queue plus a codec extension",
state: if vk.is_empty() {
State::Unknown
} else if has_encode_q && has_codec {
State::Pass
} else {
State::Fail
},
detail: if vk.is_empty() {
"vulkaninfo not installed, so this could not be checked. Install `vulkan-tools`.".into()
} else if has_encode_q && has_codec {
"extensions present. Note: presence is not proof — a working extension list with a \
broken path has happened here before, so this row is a necessary and not a \
sufficient condition."
.into()
} else if has_encode_q {
"encode queue present but no codec extension found".into()
} else {
"not advertised. This is stricter than 'has a hardware encoder': VA-API and NVENC \
are much more common than this extension."
.into()
},
blocking: true,
});
// --- two stores -------------------------------------------------------
// ZFS for content, direct-I/O-capable for box images, and not the same
// filesystem, because ZFS ignores `O_DIRECT`.
let zfs_mounts: Vec<&crate::sys::Disk> = sys
.disks
.iter()
.filter(|d| d.fs.as_deref() == Some("zfs"))
.collect();
c.push(Check {
id: "content-store",
what: "a ZFS pool for game datasets",
state: if zfs_mounts.is_empty() {
State::Fail
} else {
State::Pass
},
detail: if let Some(d) = zfs_mounts.first() {
format!("{} ({:.0} GiB free)", d.mount, d.free_gib)
} else {
"no ZFS mount found. One dataset per game, cloned per player, is the whole of the \
content store — no other filesystem gives clones and send/recv."
.into()
},
blocking: false,
});
// "Its own device" is part of the requirement, not a nicety: separate
// devices keep a box's disk latency out of a game download's write path.
//
// Compared by *physical* device, not by the `df` source string. Two
// partitions of one SSD are two strings and one queue, and two LVM logical
// volumes on one disk look entirely unrelated — so a string comparison
// passes exactly the topology this requirement exists to reject.
let root_phys: Vec<String> = sys
.disks
.iter()
.find(|d| d.mount == "/")
.and_then(|d| d.source.as_deref())
.map(sys::physical_devices)
.unwrap_or_default();
let box_store = sys.disks.iter().find(|d| {
let Some(src) = d.source.as_deref() else {
return false;
};
let phys = sys::physical_devices(src);
matches!(d.fs.as_deref(), Some("ext4") | Some("xfs"))
&& d.mount != "/"
&& d.free_gib >= 64.0
// No overlap with whatever carries the root filesystem.
&& !phys.iter().any(|p| root_phys.contains(p))
});
c.push(Check {
id: "box-store",
what: "ext4 or xfs, not /, for box images (O_DIRECT)",
state: match box_store {
Some(_) => State::Pass,
None => State::Fail,
},
detail: match box_store {
Some(d) => format!(
"{} on {} ({:.0} GiB free)",
d.mount,
d.fs.clone().unwrap_or_default(),
d.free_gib
),
None => "none found. A box image must be openable O_DIRECT or the box has no storage \
bound at all — ZFS ignores the flag, and a warm page cache let a capped \
guest read at 13.3 GB/s against a 20 MB/s cap. Games are hundreds of GiB, \
so / is not an option either."
.into(),
},
blocking: false,
});
// --- cgroup io delegation --------------------------------------------
// `io.max` is applied per box, and a user session gets `cpu memory pids`
// but not `io` — so an unprivileged bound has nothing to attach to.
let io_ctrl = std::fs::read_to_string("/sys/fs/cgroup/cgroup.controllers")
.map(|s| s.split_whitespace().any(|w| w == "io"))
.unwrap_or(false);
c.push(Check {
id: "cgroup-io",
what: "the io cgroup controller available",
state: if io_ctrl { State::Pass } else { State::Fail },
detail: if io_ctrl {
"present at the root".into()
} else {
"not available. Without it a per-box io.max silently has nothing to attach to.".into()
},
blocking: false,
});
// --- virtiofsd --------------------------------------------------------
let virtiofsd = [
"/usr/bin/virtiofsd",
"/usr/libexec/virtiofsd",
"/usr/lib/virtiofsd",
]
.iter()
.find(|p| sys::exists(p));
c.push(Check {
id: "virtiofsd",
what: "virtiofsd, for shared directories into the guest",
state: if virtiofsd.is_some() {
State::Pass
} else {
State::Unknown
},
detail: match virtiofsd {
Some(p) => (*p).to_string(),
None => "not found in the usual places; it may still be packaged elsewhere".into(),
},
blocking: false,
});
let unknowns = c
.iter()
.filter(|k| k.blocking && k.state == State::Unknown)
.count();
let could_host = !c.iter().any(|k| k.blocking && k.state == State::Fail);
HostReport {
checks: c,
could_host,
unknowns,
}
}