diff --git a/AGENTS.md b/AGENTS.md index 962f9013..4bdf74d8 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,344 +1,65 @@ # Working in this repository -## What this is - -A virtual machine: QEMU, a guest kernel, a base image, and the definition of the machine -they make. Four artefacts and one version. - -Anything that gets a workspace to its first login sooner may live here: an init, a guest -agent, a different kernel, machine or login path. Name what it is and who uses it. +A virtual machine: QEMU, a guest kernel, a base image, and the definition of the machine they +make. Anything that gets a workspace to its first login sooner may live here. ## The goal -**A cold boot to the first SSH login in under 100 ms.** `task boot:ssh-first` measures it on the -bench fleet, from the moment before QEMU is exec'd until `true` has run as the workspace user -over SSH through vsock. - -The second number is a checkpoint restored to the same first login (`task boot:restore-first`). -A change goes in when it moves one of the two, interleaved against the release, without making -the other worse. A functional change (security, correctness) goes in too. Every other number, -such as the console prompt, a phase, an initcall or a unit's time, is a tool for finding why one -of the two moved, never a target of its own. The log (`docs/log`) shows what optimising the others -cost. - -`docs/boot-time.md` says where both stand and what each of their phases costs, and -`docs/measuring.md` says how a number is taken and read. `docs/boot-time.md` also says why the -cold number cannot reach 100 ms by userspace work alone: QEMU, the firmware and the kernel spend -~140 ms before PID 1 runs (its cold budget, 2026-11-20). - -**Every part of the machine may be changed, without limit.** The kernel, systemd, QEMU, qboot and -swtpm are all ours to patch when a patch serves the goal. Carry a patch where the tree keeps that -part's patches today: the kernel's in `kernel/patches`, QEMU's in `qemu/patches`, qboot's beside -its README in `qemu/qboot`, swtpm's beside its README in `qemu/swtpm`, systemd's in `image/systemd` and OpenSSH's in `image/openssh`, whose -Dockerfiles rebuild Ubuntu's source packages. `image/systemd/Dockerfile` applies systemd's. An -experiment's systemd patch goes in `image/systemd/experiments`. -A kernel patch is written to the kernel's coding style, [coding-style.rst](https://raw.githubusercontent.com/torvalds/linux/refs/heads/master/Documentation/process/coding-style.rst), -and read against it before it is carried: checkpatch checks only part of it. - -**A carried patch is not offered upstream until it has run in production.** Do not ask whether to -send one, and do not draft one for sending. A patch earns an upstream offer by running in spin's -workspaces first, and the owner decides when. Record a patch's upstream relevance in its header -or its issue (an upstream commit it reverses, a refused series it answers), and leave it there. +**A cold boot to the first SSH login in under 100 ms** (`task boot:ssh-first`), and a checkpoint +restored to the same login (`task boot:restore-first`). A change goes in when it moves one of the +two, interleaved against the release, without making the other worse, or when it is a functional +change (security, correctness). Every other number (a phase, an initcall, a unit's time) is a tool +for finding why one of the two moved, never a target. `docs/boot-time.md` says where both stand, +`docs/measuring.md` how a number is taken and read. + +Every part of the machine may be changed: the kernel, systemd, QEMU, qboot and swtpm are ours to +patch. Carry a patch where that part's patches live (`kernel/patches`, `qemu/patches`, +`qemu/qboot`, `qemu/swtpm`, `image/systemd`, `image/openssh`; an experiment's systemd patch in +`image/systemd/experiments`). A kernel patch follows the kernel's coding-style.rst, read against it +and not only checkpatch. A carried patch is not offered upstream until it has run in production: +never ask whether to send one or draft one for sending. Record its upstream relevance in its header +or its issue. ## What must not break -1. **The base image is never written to.** Every VM maps it read-only through a qcow2 - backing chain, and many share one file. Anything that opens it for writing invalidates - every overlay in existence. The damage is silent, because the overlays keep working until - they read a cluster that moved. A new image is written beside the old one and renamed over it. - -2. **No identity in the base image.** No hostname, no machine-id with a value, no - `/etc/resolv.conf`, no SSH host keys, no random seed. Anything baked in is shared by every - VM that ever boots from that image. `image/build.sh` asserts each of these on the finished - filesystem. - -3. **CPUs, memory and devices stay dynamic.** CPU hotplug up to the machine's ceiling, memory - through virtio-mem and the balloon's free page reporting, and disks attached and detached - while the machine runs let a workspace grow, shrink and give memory back without a restart. - No change trades any of it for boot time, whether a lower ceiling, a missing device or a - machine without ACPI. Make what they cost cheaper instead. - -4. **systemd runs the guest.** Much of what runs in a workspace expects it: units, logind - sessions, user managers. An init without systemd is never a candidate. Measured, such an init - is only a bound on what systemd costs, and that cost is cut inside systemd. - -**The machine's record says which checkpoints a machine resumes, nothing more.** -A checkpoint carries the record of the machine it was taken on (`machine.Saved`), which -`machine.QEMU.Target` reads from the running QEMU: its version, the CPU its vCPU shows, every -device it was started with and their properties, its `-machine` options and its RAM blocks. -`machine.CanResume` compares it with the record of the machine it resumes into and refuses any -difference, naming each. That includes the ones QEMU loads silently: an extra device, a larger -BIOS block, more base RAM. `machine.QEMU.Resume` takes the record of the machine it resumes into -from its caller, who reads it once for a host, and refuses before QEMU reads a byte: read inside -the restore, the record was on the second goal number's clock. Changing the machine is allowed -whenever it serves the goal. The record moves, `task boot:compat` names the first release whose -checkpoints it refuses, and checkpoints from before the change boot cold instead. -`task boot:record` checks that a machine resumes its own checkpoint and refuses what QEMU would -load silently. - -## Simplicity - -Prefer the boring solution. The measure of a change here is not what it makes possible but -what it makes clear. - -- **Build what is needed now.** Not what will probably be needed. A flag with one caller - should be that caller's constant. An interface with one implementation should be the - implementation. A configuration option nobody sets is a branch nobody tests. When a - second case actually arrives, generalise then. The second case tells you what the - abstraction should be, and guessing beforehand almost always produces the wrong one. -- **Deleting is a change like any other.** If something no longer earns its place, remove - it rather than leaving it for a future that may not come. Commented-out code is deleted - code with extra steps, and git keeps the history anyway. -- **A little duplication is cheaper than the wrong abstraction.** Two similar things that - drift apart for good reasons are healthier than one thing with a mode flag. -- **Put the thing where the thing belongs.** Static configuration goes in the image, next - to the other configuration. A decision about one boot goes in whatever made that boot. A - systemd unit written by a Go program at run time was the wrong answer to a real problem. - The unit belongs in `image/`, and only the symlink that enables it belongs in the boot. - -### Experiments - -Explore freely, and promote on evidence. `docs/measuring.md` is the -full method. These are its rules. - -- **Write the budget entry first.** Name the phase an experiment attacks in `docs/boot-time.md`'s - budget, its p50 today, its ceiling (what the goal number gains if the phase cost nothing), and - the result that would decide it. An experiment whose ceiling is under the noise needs more - boots before it needs a run. -- **Measure spin's shape.** That is the CPUs, memory, ceilings and disks spin boots a workspace - with. Name the shape on every table. A gain in another shape is a lead. -- **Decide on the end-to-end numbers in "The goal", interleaved in one run** against the - release, on the kind of host the goal is measured on. Two runs are two machines: never compare - a number with one from another run. Runs may go at once, each on its own bench instance. A - laptop finds leads. -- **One acceptance rule.** A change is a gain only when the bootstrap 95% interval of its Δp50 - excludes 0. At 20 boots a side the interval is about ±7-9 ms (`docs/measuring.md`). A smaller - effect needs more boots, not a second look. -- **One change per arm.** A comparison that decides a change carries that change alone. A floor - or a bound may change as many things at once as its question needs. A floor built from every - change together says what is possible before any one of them is tuned. -- **An instrument must see the phase it claims.** The kernel's "Freeing" clock starts after the - bzImage is decompressed, and it recorded the bzImage's cost as zero. Before trusting a phase, - check that something on the other side of it moved by the same amount. -- **Measure the bounds each release**, the no-systemd floor first. A bound that is not - re-measured stops being one. -- Keep experiment outputs, overlays, initrds, firmware and caches apart from release outputs, - and never open the shared base image for writing. -- Remove an experiment once its question is answered. When a change decides something, kept or - rejected, add its record to `docs/experiments` and its entry, dated and with its run, to - `docs/log`. Each is a file of its own, so two pull requests in flight never edit the same one - (#709); the pages they make are rendered, never committed. - - **An entry** is `docs/log/-.md`: YAML front matter (`date`, `order`, the - entry's place among that day's, `area`, `title`, and the `issues`, `prs` and `runs` its text - cites), then the prose. `spin-machine-dev docs log` renders the page, its head - `**MM-DD · area · title.**`. - - **A record** is `docs/experiments/[-].json`, one row of `docs/boot-time.md`'s - tables: `decision` (`carried`, `rejected` or `open`), a rejected one's `section`, `order` - (its place in the table), and the cells its table shows. `spin-machine-dev docs tables` - renders the tables. A record that moves, from open to rejected, changes its `decision`. - - `gates/docs_test.go` refuses an entry or record that lacks a field, names a decision or - section that does not exist, or lists a run, issue or pull request its text does not cite. -- **Read before starting.** Read the "Measured and rejected" records - (`spin-machine-dev docs tables`) and the log's rework cycles (`docs/log/rework.md`). An idea - already there needs a new reason, not a new run. `docs/memory-and-disk.md` says what the - guest's memory and disk cost. -- **Search outside the repository too.** Many people work on KVM, QEMU, the kernel and systemd, - and a boot-time idea has usually been tried, measured or refused somewhere: the projects' - mailing lists, issue trackers and commit history, conference talks (LPC, KVM Forum, All - Systems Go, FOSDEM), and the boot-time work of Clear Linux, Firecracker, Kata, Yocto and - others. Before an experiment's first run, look for its prior art and put what was found in - its budget entry: the link, the date, what they measured and in what shape, and why it - applies here or not. A patch upstream refused needs that reason answered before it is - carried. Nothing found is a finding too: say where you looked. - -## Go - -- **Clarity beats cleverness.** This code is read far more often than it is written, and - usually by someone trying to find out why a VM did not start. -- **Handle an error once.** Wrap it with what was being attempted, as in `fmt.Errorf("mounting - %s at %s: %w", …)`, and return it. Do not log it and return it. An error message should - say what failed, on what, so that the person reading a serial console at 2am does not - have to guess. A bare `no such file or directory`, which this repository shipped once, - names nothing. -- **Do not panic**, and do not exit from a library. `cmd/` decides what a failure means. -- **Accept interfaces, return structs**, and only introduce an interface when there is a - second implementation or a test that genuinely needs one. -- **Make the zero value useful** where it is cheap to do so, and validate where it is not. - `Disk.validate`, which every bind runs, refuses an image with no format because a guessed - format is how an image the guest can write gets read as another one. That is worth a check - at the boundary, not a sensible default. -- **Name things for what they are** to the reader, not for their type. `Spec`, `Target`, - `Refusal` are the words used when talking about this machine. Use those. - -## Comments - -Comments here are longer than usual, on purpose. These rules are what make them worth reading: - -- **Say why, not what.** The code says what. If a comment restates it, delete the comment. -- **Carry durable evidence.** When a production decision rests on a measurement, put a - concise result and its context near the decision, or link to a maintained measurement - record. Include a number when it is the reason for the decision. Do not turn an exploratory - observation into a permanent claim. -- **Record failed approaches selectively.** Keep a failed attempt near code only when it - prevents a plausible, costly regression or repeats a non-obvious tool failure. Put raw - samples and short-lived exploration in a measurement record, issue, or commit instead. -- **Date a fact that could go stale.** "measured 2026-09-07" tells a reader whether to - re-check. -- **Do not write down that it works.** The README had a "Status" section listing what had - been built and verified on a date. Every line of it was something CI answers - continuously and can answer *red*, or something already said next to the decision it - justified. So the section could only rot, and it did. A claim about the state of the tree - belongs in a workflow, a badge, or a commit message. Never in prose that nobody - re-reads. -- **Name external contracts when relevant.** A consumer's protocol, provisioned file or - lifecycle that this machine has to honour is described here and tested where it can be. -- **A decision, an open question or a follow-up is an issue.** "Left as it is", "not settled", - "not in this change" and "the consumer should change this" each get a GitHub issue in the repo - that owns it (spin-stack/machine or spin-stack/spin), with its evidence and how to settle it. - A comment, a PR body or a log entry cites the issue and never stands in for it: a comment is - read only by whoever opens that file, and an issue is where the next person looks for work. - An issue closed because its proposal was decided against carries the label `rejected`, and a - finding that does not apply to this machine (an osv CVE, an upstream bug) carries `not-affected`, - whatever reason GitHub's close records: most rejected experiments were closed as completed, and - `label:rejected` is how the next person finds what was already decided against. -- **The image explains itself in `docs/image.md`, not in `image/`.** Why a unit is masked, - reordered or added, why a package is in or out, what measured it and what a workspace gives - up: all of it is a row or a note in `docs/image.md`. A script, Dockerfile or drop-in under - `image/` carries at most a one-line pointer, `# docs/image.md, "
"`. A deviation from - the packages that `image/build.sh` finds and `image/deviations.txt` lists, with no row in - `docs/image.md`, fails `gates/image_doc_test.go`. - -## Artefacts leave this machine - -Host-executed binaries published in a release should be statically linked unless there is a -documented deployment reason not to be. This rule does not apply to guest userspace, build -tools, or diagnostic artefacts. A released host binary that depends on host libraries needs a -compatibility and packaging story, because its failure otherwise arrives on someone else's -machine at start-up. - -## Verifying - -- **Assert what came out, not what went in.** A build that produced an empty filesystem - produces a perfectly valid empty filesystem. `image/build.sh` opens the finished image - and looks for `/sbin/init`. The QEMU build asks the binary it just produced which devices - it has. `spin-machine-dev verify kernel` reads the ELF notes out of the kernel it just stripped. -- **Check the tool's output, not only its exit status.** `debugfs -R` exits 0 whether or - not the file it was asked about exists. Every filesystem check in this repository passed - vacuously because of that, until someone looked. -- **Fail where the cause is.** A missing option ROM should fail in the build that did not - ship it, not in a VM three weeks later that will not start. Every workflow ends in the - verification that belongs to it. -- **A tarball with something missing is worse than no tarball.** It installs, and the - missing piece surfaces somewhere else. `spin-machine-dev release` refuses rather than warning. - A list of files to ship is how one goes missing: the release script named qboot's patches one - by one, and v20261001.01 shipped a `qboot.bin` without the patch it was built with. Ship - what a directory holds. -- **Ask the kernel for a feature, never for its module.** Spin OS's kernels have no loadable - modules. What they have is built in, `modprobe` finds nothing, and a built-in driver without - parameters has no `/sys/module` entry. Look for what the feature makes, such as `/dev/nbd0` - or `/dev/vhost-vsock`, and only then load a module. Asking for the module said no to features - that were there, twice (#56, #82). +1. **The base image is never written to.** Overlays share it read-only through a qcow2 backing + chain; one write silently corrupts every overlay. A new image is written beside it and renamed. +2. **No identity in the base image**: no hostname, machine-id value, resolv.conf, SSH host keys or + random seed. +3. **CPUs, memory and devices stay dynamic** (CPU hotplug, virtio-mem, balloon free page + reporting, disk hot(un)plug). Never trade any of it for boot time; make it cheaper instead. +4. **systemd runs the guest.** An init without it is only a bound on what systemd costs. + +A checkpoint resumes only into a machine whose record matches (`machine.CanResume`). Changing the +machine is allowed when it serves the goal: `task boot:compat` names the first release whose +checkpoints it refuses, `task boot:record` checks a machine resumes its own. + +## Experiments + +`docs/measuring.md` is the method. Before a run: read the "Measured and rejected" records +(`spin-machine-dev docs tables`) and `docs/log/rework.md`, since an idea already there needs a new +reason; search outside the repo for prior art (mailing lists, trackers, LPC, KVM Forum, Firecracker, +Kata, Clear Linux) and put it in the budget entry; write the budget entry first (phase, p50, ceiling, +deciding result). Measure spin's shape and name it on every table. Decide on the two goal numbers, +interleaved in one run against the release, one change per arm; a gain is a bootstrap 95% interval +of Δp50 that excludes 0. Never compare numbers from two runs. Check that an instrument sees the +phase it claims. When a change decides something, add its record to `docs/experiments` and its entry +to `docs/log` (`gates/docs_test.go` checks their shape); a record that moves changes its `decision`. + +A decision, open question or follow-up is a GitHub issue (spin-stack/machine or spin-stack/spin). +A rejected proposal's issue carries the label `rejected`; a finding that does not apply here, +`not-affected`. The image explains itself in `docs/image.md`, not in files under `image/`. ## Trying the machine -`spin-machine` (`cmd/spin-machine`, built by `spin-machine-dev build spin-machine`) is how this -machine is run by hand. Use whatever is quickest to explore with. A check that will be repeated, -or that decides something, ends up in `boot/` as a Task target, so the next person measures the -same thing. - -- **Rebuild it first.** `_output/bin/spin-machine` is whatever `spin-machine-dev build` last built, so - a change to `machine/` is invisible until the tool is rebuilt. `spin-machine args` shows - the command line that will actually run. -- **The base is safe by default.** Without `--disk`, `boot` puts the base image under a - throwaway qcow2 overlay, made in a directory of its own and deleted once it is open, and - root is `/dev/vda`. `--disk` opens the named file as given, so point it at an overlay and - never at `rootfs.qcow2`. -- **Driving a guest.** `--init /bin/sh` gives a shell with nothing mounted. Its console is - on stdin/stdout, or on a socket with `--console unix:PATH,server=on,wait=off`. `--qmp - PATH` opens the socket that `attach`, `detach`, `save` and the others talk to. -- **Every machine starts held.** QEMU runs `-S` (or `-incoming defer` with `--restore`) until a - monitor binds its disk and lets it go. `boot` starts QEMU through `machine.Start`, does that - over Start's own monitor and stays beside QEMU until it exits; `boot --held` leaves it for - `start`, as a machine started ahead of its workspace is. -- **A socket's path fits in 108 bytes.** `sun_path` is that long, and a QMP or console socket - under `t.TempDir()`, a scratch directory or `_output/` easily exceeds it. QEMU then does not - start, and the probe reports the guest never answering, not the path. Put sockets in a - short directory of their own (`os.MkdirTemp("/tmp", …)`) and keep overlays and states where - they belong. The limit has been hit more than once, again in boot:restore-first (2026-11-19). - -```sh -spin-machine boot --hotplug-disks 2 --qmp /tmp/q.sock --init /bin/sh & -spin-machine attach --qmp /tmp/q.sock --disk disk.raw --disk-format raw --disk-serial ext # sda, in the guest -spin-machine detach --qmp /tmp/q.sock --disk-serial ext -``` - -`detach` returns when QEMU reports the device free, but the guest notices the -ejection asynchronously. A check that greps for the node inside the guest right after -`detach` can still see it, and one saw it gone seconds later (measured 2026-10-03). -Leave the guest a moment before treating a visible node as a hot-unplug failure. - -A one-off check needs no socket and no QMP. The shell's console is stdin/stdout, so -a script on stdin is what the guest runs, and `poweroff -f` ends the boot. `--init -/bin/sh` runs the script as PID 1 with nothing mounted, so the script mounts `/proc` and -`/sys` itself when the check reads them. `poweroff` needs `/proc`. - -```sh -printf '\n\n\n\n\n\n\n\n\n\nmount -t proc proc /proc\ncat /proc/cpuinfo | head -1\npoweroff -f\n' | - spin-machine boot --release _output --init /bin/sh --console stdio --memory 1024 --cpus 2 -``` - -Keep the leading blank lines. The guest's shell is not reading its console when QEMU -starts feeding it, so the first bytes of the first line are lost, and a leading `sleep` -would be the thing eaten. Before the blanks absorbed it, `mount` arrived as `unt` and -`sleep` as `ep`. How far the window reaches is host timing, not a line count, so keep -the number of blanks generous rather than tuning it. A blank costs only a prompt. - -## spin-machine-dev and the Taskfile - -`spin-machine-dev` (`cmd/spin-machine-dev`, `docs/cli.md`) is what a person types to build, -verify, boot, release and keep the pins. A verb is a goal, its state is files under `_output`, -and a workflow is the same verbs, a step each. `task bin` builds it into `_output/bin`; `task` is -go-tools' task command (`go install github.com/spin-stack/go-tools/cmd/task@latest` once), so a -go-tools command in the Taskfile is its bare name, and a verb that runs one is `task dev -- `. -The Taskfile holds go-tools' gates (`test`, `lint`, `mutate`, `coverage`), CI's plumbing, and -the probes' targets in `boot/`. CI calls what a developer calls. A second definition of what -the gate is, kept in a workflow file, goes out of step with the first exactly when a check -is added. - -Before pushing, run `task lint test mutate` after `git fetch origin`. It gives CI's -verdict whatever the checkout has built. `test` and `mutate` hide the release tree, as CI has -none when they run. A test keeps its state in a directory of its own, never in the checkout's -`_output`. `task mutate` links that directory into every copy it runs tests in at once, so two -tests writing there fail each other and refuse edits CI lets survive (#413). `task test` fails -on a test that makes `_output` in a checkout that had none. - -**Check whether `/tmp` is a tmpfs before writing to it** (`findmnt -no FSTYPE /tmp`). On a tmpfs, -what is written there is RAM: a scratch tree, a worktree, an unpacked release or a build's objects -in it are memory gone, and a full one had the OOM killer take `task lint` (2026-11-23: 20 GiB of -agents' scratch filled a 23 GiB `/tmp` to 94%). Write scratch to a directory on disk, -`/var/tmp/`, and point `TMPDIR` at it for the tools that make their own (`go`, `docker`, -`git`). `/tmp` is the last resort, for what is small by nature: a socket in a short directory of -its own (see "Trying the machine") is a few bytes. Remove scratch once its question is answered. - -## Licence and third-party source - -Apache-2.0. New Go files carry `// SPDX-License-Identifier: Apache-2.0`. - -Anything vendored into this tree goes in `NOTICE`, with its licence and, if it was -changed, a statement that it was. Anything that ends up *inside a release* goes in the -`SOURCES` file that `spin-machine-dev release` writes: what it is, which upstream tarball it was -built from, that tarball's SHA-256, and how to get it. The repository's licence covers the -recipes. A tarball of GPL binaries carries obligations of its own, and the release is where -they are answered. - -An input downloaded from outside is pinned by hash and checked on every build, not only -after a download, because the caches outlive the builds that filled them. The pin is written -once, in `versions.yaml`, and handed to the Dockerfile as a build argument with no default. A -test in `gates/` fails on a digest or a commit written anywhere else. `task dev -- bump ` moves -one entry, and the entry's note says what the bump is checked with. +`spin-machine` (`spin-machine-dev build spin-machine`) runs the machine by hand; rebuild it after +changing `machine/`. Without `--disk` it boots the base under a throwaway overlay; `--disk` opens +the file as given, so never point it at `rootfs.qcow2`. A script piped to `--init /bin/sh` over +`--console stdio` loses its first bytes: start it with ten or more blank lines. After `detach`, the +guest notices the ejection asynchronously. Ask the guest kernel for a feature (`/dev/vhost-vsock`), +never for its module: it has none. -## Versions +## Before pushing -CalVer, `vYYYYMMDD.NN`. A release is the machine as it stood on a date. There is no API here -to promise compatibility about. The one thing a version could promise is that checkpoints -still resume, and the machine's record decides that (`machine.CanResume`), not a number anybody chose. +Run `task lint test mutate` after `git fetch origin`. `/tmp` may be a tmpfs: put scratch under +`/var/tmp/` and point `TMPDIR` there. diff --git a/docs/cli.md b/docs/cli.md index 294bf3e4..80c536ab 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -185,7 +185,7 @@ the release that needed them. ## The log and the experiments The log is one file an entry under `docs/log`, and the rows of `docs/boot-time.md`'s tables are one -record each under `docs/experiments` (AGENTS.md, "Experiments", says what each holds). A pull +record each under `docs/experiments` (`internal/docsrec` says what each holds). A pull request adds files of its own, so two in flight do not conflict. The pages they make are rendered, never committed (#709): diff --git a/docs/measuring.md b/docs/measuring.md index 3eb13631..fad5a448 100644 --- a/docs/measuring.md +++ b/docs/measuring.md @@ -14,7 +14,7 @@ stand, where their time goes, and what was kept, rejected and is open are in 4. Measure it with the rules below. The commands are in `docs/cli.md`, "Measuring". 5. When it is decided, move the record: its `decision` becomes `carried` ("What the machine carries") when it is kept, or `rejected` ("Measured and rejected") when it is not. Then write - its entry, dated and with its run, as a file of its own in `docs/log` (AGENTS.md says how). + its entry, dated and with its run, as a file of its own in `docs/log` (`internal/docsrec` says what it holds). ## Follow the rules of a measurement diff --git a/gates/docs_test.go b/gates/docs_test.go index b73aad2a..612f14d7 100644 --- a/gates/docs_test.go +++ b/gates/docs_test.go @@ -10,8 +10,8 @@ import ( ) // Every log entry and experiment record parses, with its required fields, a decision and section -// that exist, valid dates, and the issues, pull requests and runs its text cites (AGENTS.md, -// "Experiments"). The pages they make are rendered, never committed (#709), so this is where a +// that exist, valid dates, and the issues, pull requests and runs its text cites (internal/docsrec +// says what each holds). The pages they make are rendered, never committed (#709), so this is where a // broken file is found, not on the site after a merge. func TestEveryLogEntryAndExperimentRecordParses(t *testing.T) { l, err := docsrec.ReadLog(filepath.Join(root, docsrec.LogDir)) diff --git a/gates/go_rules_test.go b/gates/go_rules_test.go new file mode 100644 index 00000000..0ebdb7f2 --- /dev/null +++ b/gates/go_rules_test.go @@ -0,0 +1,83 @@ +// SPDX-License-Identifier: Apache-2.0 + +package gates_test + +import ( + "go/ast" + "go/parser" + "go/token" + "io/fs" + "path/filepath" + "strings" + "testing" +) + +// goFiles parses every Go file in the repository, comments kept, and hands each to check. +func goFiles(t *testing.T, check func(path string, fset *token.FileSet, f *ast.File)) { + t.Helper() + n := 0 + err := filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error { + if err != nil { + return err + } + if d.IsDir() { + switch d.Name() { + case "_output", ".git", ".claude", ".cache", "node_modules": + return filepath.SkipDir + } + return nil + } + if !strings.HasSuffix(path, ".go") { + return nil + } + fset := token.NewFileSet() + f, err := parser.ParseFile(fset, path, nil, parser.ParseComments) + if err != nil { + return err + } + n++ + check(path, fset, f) + return nil + }) + if err != nil { + t.Fatal(err) + } + if n < 200 { + t.Fatalf("read %d Go files: the check reads almost nothing", n) + } +} + +func TestEveryGoFileCarriesTheLicence(t *testing.T) { + goFiles(t, func(path string, _ *token.FileSet, f *ast.File) { + if len(f.Comments) == 0 || f.Comments[0].List[0].Text != "// SPDX-License-Identifier: Apache-2.0" { + t.Errorf("%s: does not open with // SPDX-License-Identifier: Apache-2.0", path) + } + }) +} + +// A library returns its error; cmd/ decides what a failure means. +func TestNoLibraryPanicsOrExits(t *testing.T) { + goFiles(t, func(path string, fset *token.FileSet, f *ast.File) { + if f.Name.Name == "main" || strings.HasSuffix(path, "_test.go") { + return + } + ast.Inspect(f, func(n ast.Node) bool { + call, ok := n.(*ast.CallExpr) + if !ok { + return true + } + switch fn := call.Fun.(type) { + case *ast.Ident: + if fn.Name == "panic" { + t.Errorf("%s: panics; return the error", fset.Position(call.Pos())) + } + case *ast.SelectorExpr: + if pkg, ok := fn.X.(*ast.Ident); ok && (pkg.Name == "os" && fn.Sel.Name == "Exit" || + pkg.Name == "log" && strings.HasPrefix(fn.Sel.Name, "Fatal")) { + t.Errorf("%s: %s.%s outside package main; return the error", fset.Position(call.Pos()), pkg.Name, fn.Sel.Name) + } + } + return true + }) + }) +} diff --git a/machine/machine_test.go b/machine/machine_test.go index 6141dc47..645a5af9 100644 --- a/machine/machine_test.go +++ b/machine/machine_test.go @@ -558,6 +558,9 @@ func TestValidateRefuses(t *testing.T) { {"a descriptor set holding stdin", func(s *Spec) { s.FDSets = []FDSet{{ID: 1, FDs: []FD{{Num: 0}}}} }}, {"a monitor given a path and a descriptor", func(s *Spec) { s.Monitors = []Monitor{{Socket: "/qmp", FD: 3}} }}, {"a monitor given neither", func(s *Spec) { s.Monitors = []Monitor{{Socket: "/qmp"}, {}} }}, + {"a monitor's socket path longer than sun_path holds", func(s *Spec) { s.Monitors = []Monitor{{Socket: "/" + strings.Repeat("a", 107)}} }}, + {"a console's socket path longer than sun_path holds", func(s *Spec) { s.Console = "unix:/" + strings.Repeat("a", 107) + ",server=on,wait=off" }}, + {"a multiplexed console's socket path longer than sun_path holds", func(s *Spec) { s.Console = "mon:unix:/" + strings.Repeat("a", 107) + ",server=on" }}, {"a monitor on stderr", func(s *Spec) { s.Monitors = []Monitor{{FD: 2}} }}, // A value from a fixed set is refused, not escaped: an escaped "qcow2,,x" is // still not a format, and an unescaped one is a second option. @@ -701,6 +704,18 @@ func TestValidateRefuses(t *testing.T) { if err := s.validate(); err != nil { t.Fatalf("a console by path does not validate: %v", err) } + + // The longest socket path sun_path holds, and a file console has no such limit. + s = spec(t) + s.Monitors = []Monitor{{Socket: "/" + strings.Repeat("a", 106)}} + s.Console = "unix:/" + strings.Repeat("a", 106) + ",server=on,wait=off" + if err := s.validate(); err != nil { + t.Fatalf("a 107-byte socket path does not validate: %v", err) + } + s.Console = "file:/" + strings.Repeat("a", 200) + if err := s.validate(); err != nil { + t.Fatalf("a long file console does not validate: %v", err) + } s = spec(t) s.FDSets = []FDSet{{ID: 1, FDs: []FD{{Num: 10}}}} s.ConsoleFDSet = 1 diff --git a/machine/process.go b/machine/process.go index 8f661d59..46a5ab95 100644 --- a/machine/process.go +++ b/machine/process.go @@ -508,6 +508,12 @@ func (h *handover) monitors(s *Spec) (*net.UnixConn, error) { if m.Socket == "" { continue } + // Here and not only in validate, which Start runs once the sockets are bound: Go's + // refusal of too long a path is a bare "invalid argument". + if err := socketFits(m.Socket); err != nil { + h.removeSockets() + return nil, err + } f, err := listen(m.Socket) if err != nil { h.removeSockets() diff --git a/machine/process_test.go b/machine/process_test.go index 3e4d3fe7..7e08a8bc 100644 --- a/machine/process_test.go +++ b/machine/process_test.go @@ -912,3 +912,13 @@ func TestAMissingPasstFailsTheStart(t *testing.T) { t.Fatalf("Start with no passt = %v, want an error naming it", err) } } + +// Start binds a monitor's socket before anything else reads the Spec, so too long a path is +// refused there, by name, and not as bind's "invalid argument". +func TestStartRefusesASocketPathSunPathCannotHold(t *testing.T) { + long := "/" + strings.Repeat("a", 107) + _, err := startFake(t, t.Context(), "", Spec{Monitors: []Monitor{{Socket: long}}}, StartOptions{}) + if err == nil || !strings.Contains(err.Error(), long) || strings.Contains(err.Error(), "invalid argument") { + t.Fatalf("Start with a 108-byte socket path: %v", err) + } +} diff --git a/machine/spec.go b/machine/spec.go index 4ead97b5..6cab3eff 100644 --- a/machine/spec.go +++ b/machine/spec.go @@ -206,6 +206,19 @@ func (m Monitor) validate() error { case m.FD != 0 && m.FD < 3: return fmt.Errorf("a monitor descriptor of %d is stdin, stdout or stderr", m.FD) } + return socketFits(m.Socket) +} + +// maxSocketPath is the longest path a Unix socket is bound or reached at: sun_path is 108 bytes, +// the NUL that ends the path among them. Too long a path was refused only once QEMU ran, and a +// probe then read the guest as never answering, not the path (hit more than once, last in +// boot:restore-first, 2026-11-19). +const maxSocketPath = 107 + +func socketFits(path string) error { + if len(path) > maxSocketPath { + return fmt.Errorf("socket %s is %d bytes, and a Unix socket's path holds %d", path, len(path), maxSocketPath) + } return nil } @@ -466,6 +479,11 @@ func (s Spec) validate() error { switch { case s.ConsoleFDSet != 0 && s.Console != "": return errors.New("a console given both as a chardev and as a descriptor set") + case strings.HasPrefix(strings.TrimPrefix(s.Console, "mon:"), "unix:"): + path, _, _ := strings.Cut(strings.TrimPrefix(strings.TrimPrefix(s.Console, "mon:"), "unix:"), ",") + if err := socketFits(path); err != nil { + return fmt.Errorf("console: %w", err) + } case s.ConsoleFDSet != 0 && !sets[s.ConsoleFDSet]: return fmt.Errorf("the console is descriptor set %d, which Spec.FDSets does not have", s.ConsoleFDSet) case s.KVMFDSet != 0 && s.Accel != "" && s.Accel != "kvm":