gunk-dev/the-valley
the-valley:oc-a1e21bboutcomeabandoned

Converge is ported to Go, with its open review findings fixed

State
abandoned
Created
2026-10-17 by contributor
Source
2026-10-04, plan.md Status (M1-A) and the deployment ROADMAP.md D11
Lands in
a knot in an unpublished project
Blocks
Changes
  • a change in an unpublished project

Body

Port the deployment project's converge from Bash to Go, and fix the open findings from Astra's review of the deployment change that last reworked converge on the way. The operator merged that change with those findings open; they are the port's acceptance criteria.

Done when converge's state machine is Go, with Bash only as thin glue, and each finding in that review has a fix and a test (boot-default verification, GC-root ordering, the unchecked last-known-good after `switch`, the Pi reboot exception, the rebuild tool's `hold clear`, one-attempt recovery, lock handoff at shutdown, missing fault tests, Waybar's drift message).

Source: `plan.md` Status 2026-10-04 (M1-A), and the deployment project's `ROADMAP.md` D11.

---

Design revision 2, 2026-10-21: authored by Astra (Codex gpt-6-astra), reviewed cross-family by Claude against the deployment project at a45d858; every review finding adopted (see the final section). The review of revision 1 is a comment on this knot. The agent guest does not converge and is out of scope.

# Converge in Go (design, revision 2)

Converge lives in the deployment project as one Go binary, with Nix defining host policy and systemd units.
It preserves the existing ledger and separates durable deployment decisions from status.
Only initrd, kernel and kernel-modules require staging.
Promotion performs `test`, checks health and the candidate deployer, then installs the boot configuration.
Boot verification uses bootctl’s resolved selection or extlinux’s selected label.
Converge and its boot installer never write EFI variables.
Superseded stages are pruned; missing last-known-good boot entries stop unattended reboot.
A durable hold consumes recovery’s single attempt.
A nonblocking lock and systemd ordering replace the proposed runtime barrier.
Delivery consists of D8 plus five changes, each running live code.

## Source basis and scope

The inspected checkout is `a45d858f1167141495358932ace2e16dad61d2a9`, equal to `origin/main`. D11’s acceptance criteria are recorded in `ROADMAP.md:199` and the Astra review, line 30.

**Operator-supplied baseline:** D8 supplies the three-component divergence set, rollback as an independent reboot reason, durable restoration of last-known-good before staged-to-live activation, and the `loader/loader.tmp` guard. These changes are required behavior here. Their implementation is **unconfirmed in this checkout**, which contains the earlier code at `modules/converge/scripts.nix:234`, `modules/converge/scripts.nix:614`, `modules/common/auto-reboot-scripts.nix:29` and `modules/converge/scripts.nix:195`.

The deploying fleet is a workstation, the valley host and the two Raspberry Pis. The agent guest is only a constrained development environment, not a converging host.

Citations below use repository paths. These abbreviations identify files in nixpkgs commit `6510408d147d8c5e6d76043e899e9251756f6a75`, pinned by `flake.lock:264` and inspected locally:

| Abbreviation | Pinned nixpkgs path |
|---|---|
| `STC` | `pkgs/by-name/sw/switch-to-configuration-ng/src/main.rs` |
| `SDboot` | `nixos/modules/system/boot/loader/systemd-boot/systemd-boot-builder.py` |
| `Extlinux` | `nixos/modules/system/boot/loader/generic-extlinux-compatible/extlinux-conf-builder.sh` |
| `Image` | `nixos/lib/make-disk-image.nix` |

This is a source-grounded design, not a test report. Builds and VM tests are not run for this revision.

## 1. Home and shape

**Decision:** add `pkgs/converge/`, a Go module producing the `converge` binary, beside `pkgs/converge-status`. Keep `converge-status` as the status writer and renderer.

Converge manages local NixOS activation, boot files, roots and services. Those responsibilities already belong to the deployment project’s host module; the valley supplies deployment input. Moving this executor into the-valley couples host recovery to a separate project without removing a local responsibility. The existing package and unit boundaries support a local package (`flake.nix:369`, `modules/converge/default.nix:414`).

| Entry point | Responsibility |
|---|---|
| `converge run` | Resolve, build, activate, stage, validate boot and recover interrupted work |
| `converge result` | Report systemd termination; never repair deployment state |
| `converge hold [clear [REV]]` | Inspect holds, clear quarantine and reconcile operator choices |
| `converge self-check` | Read-only validation of configuration and ledger |
| `converge reboot-needed` | Project current reboot reasons |
| `converge reboot-check` | Read-only convergence and boot-selection blockers |
| `converge reboot-attempt` | Acquire locks, check blockers and request reboot |
| `converge health` | Execute the Nix-defined health contract |
| `converge probe dns` | Reusable exact-answer DNS probe |

The rebuild service runs `run`, with `result` in `ExecStopPost`. The existing `reboot-needed.service` and `reboot-attempt.service` run their corresponding commands. The rebuild tool’s hold command remains a thin compatibility wrapper. The interactive rebuild tool is outside this change; its naming conflict is already D10 (`ROADMAP.md:194`).

Nix retains:

- Options, backend selection, immutable command paths and generated configuration.
- Units, timers, resource limits, SSH credentials and webhook dispatch.
- Required services, DNS answers, TCP banners and health timing.
- The host-specific peer-check command and boot-installer configuration.

These are existing module responsibilities (`modules/converge/default.nix:227`, `modules/converge/default.nix:393`, `modules/converge/default.nix:429`, `modules/common/auto-reboot.nix:144`). Preserve `restartIfChanged = false` and `stopIfChanged = false`; activation must not kill its own executor (`modules/converge/default.nix:419`).

The shared reboot commands also work without converge enabled. Ledger-dependent checks are enabled through Nix’s converge integration, rather than assumed on every consumer of auto-reboot (`modules/converge/default.nix:564`).

### Deployment input

Use the valley URLs already exercised by `modules/converge/valley-read-test.nix:97`: SSH for revision discovery and `git+ssh` for the flake. Preserve the scoped deploy identity and forced read access tested at `modules/converge/valley-read-test.nix:167` and `modules/converge/valley-read-test.nix:176`. The host declarations still point at GitHub in this checkout, so valley wiring is an explicit change, not claimed existing fleet behavior.

Resolve a revision once, build that revision and retain the existing bounded catch-up loop. Valley unavailability leaves the current deployment intact; local recovery precedes remote discovery, as it does today (`modules/converge/scripts.nix:308`, `modules/converge/scripts.nix:455`).

Later signed releases can replace revision selection and authorization; caches can supply the same target closure; canaries can control which target a host receives. This port adds none of those policies. SHA-keyed quarantine remains the current contract, with its documented limitation for future release identities (`docs/converge.md:156`).

**Rejected:** a valley-owned executor, separate stateful daemons and a general deployment framework. One process under the existing units is sufficient.

## 2. State machine and durable records

**Decision:** preserve the line-oriented `key=value` ledger under the rebuild tool’s state directory in `/var/lib`. Introduce typed parsing and explicit transitions, not a database or a replacement journal.

The existing formats and transaction fields are specified in `modules/converge/scripts.nix:17`. The Go reader accepts records written by Bash, including an empty revision and legacy transaction identities. Missing mandatory fields or contradictory records cause a hold; they do not mean “no deployment”.

| Record | Meaning and compatibility |
|---|---|
| `good` | Accepted revision, system, generation-local checker and committing transaction |
| `txn` | Existing `id`, `kind`, target, previous system, profile/default snapshots, trusted checker and commit flag |
| `staged` | Target awaiting boot, previous running system, trusted checker, divergence and transaction |
| `rollback` | Failed boot awaiting return to `good`; retain `rev`, `from`, `detail` |
| `quarantine/<rev>` | Failed revision and diagnostic details |
| `hold` | Durable operator hold; its existence also consumes automatic recovery |
| `adopt` | Operator’s request to validate the named running system |
| `roots/` | Existing `good` and `staged` aliases, plus unique protection roots |
| `status` | Reconstructible display projection, never deployment authority |

No attempt counter, boot ID, compensation record or runtime barrier is added.

### Transitions

| Observed state | Action and resulting state |
|---|---|
| Hold exists | Report `needs-operator`; perform no automatic repair |
| Committed transaction remains | Replay cleanup, using transaction identity |
| Uncommitted transaction remains | Persist hold, attempt at most one boot-only repair, remain held |
| No `good` exists | Validate running/profile/default agreement and its own health; bootstrap with `rev=` |
| Running differs from `good`, with no staged boot or rollback explanation | Report persistent drift; require operator reconciliation |
| Target has different initrd, kernel or kernel-modules | Install for boot; commit `staged`; retain `good` |
| Target matches those three booted components | Perform the live promotion sequence below |
| Staged target is actually booted | Validate with the stored trusted checker, its own checker and its own binary; promote or stage rollback |
| Rollback exists | Keep a reboot pending until the host returns to `good` and passes its checker |

Transaction equality remains explicit: `committed=1`, or a `good`/`staged` record naming that transaction, establishes commitment. Matching closure paths alone does not (`modules/converge/scripts.nix:316`).

A leftover stage whose three boot components now match the booted system takes the live path. Check this **before** the “same staged revision” early return, which currently waits unconditionally (`modules/converge/scripts.nix:493`).

### Promotion

The live path is:

1. Protect all participating closures and persist the transaction.
2. If replacing an existing stage with live activation, restore, flush and verify `good` as the persistent boot selection **before any live test**, preserving D8.
3. Run the target’s `switch-to-configuration test` directly as a child.
4. Run the checker frozen from `good`.
5. Run the target’s own generation-local health checker.
6. Run the target’s own `converge self-check`, read-only against the real ledger and its generated configuration.
7. Set the system profile and perform boot-only installation; flush and verify selection and the LKG entry.
8. Commit `good`, then clean up.

The pinned implementation confirms that `switch` installs the bootloader and continues into activation, while `boot` exits before activation (`STC:1843`, `STC:1859`). Therefore `test → checks → boot` removes the unchecked second activation currently at `modules/converge/scripts.nix:605`.

Hooks receive the actual `NIXOS_ACTION`; `switch`-only hooks do not run in this sequence (`STC:1784`). That is an accepted semantic change, covered by an action-order test.

The candidate’s own checker must execute, not merely exist. Today only its presence is checked (`modules/converge/scripts.nix:603`). Otherwise a broken new checker becomes the authority that rejects every later target.

Nix exposes the candidate binary through a generation-local path. `self-check` validates parsing, referenced paths and supported ledger semantics, including an in-progress transaction. It neither takes the parent’s exclusive lock nor writes records, probes the network or starts services. A crash or nonzero exit prevents promotion. The same checks apply to post-boot promotion and operator adoption.

### Failure and compensation

For an ordinary live failure:

1. Record quarantine.
2. Restore and verify the prior valid staged boot selection, if retained, otherwise `good`.
3. Only then `test` the previous live system.
4. Check that system with the trusted checker.
5. Finish cleanup, or hold on any failed compensation step.

In the D8 staged-to-live path, the safe selection is already `good`; compensation preserves it. Failure of the old system’s `test` cannot leave the failed candidate selected for boot. The checkout has the unsafe reverse order at `modules/converge/scripts.nix:614`.

After an unhealthy **boot**, recovery only installs `good` for the next boot. It never activates an old userspace across an unverified kernel boundary, preserving the resolved finding in the Astra review, line 19.

### Hold clearing and bootstrap

`hold clear` performs bookkeeping under the lock:

- Clear the requested quarantine, preserving the existing revision-scoped CLI behavior.
- If a known persistent selection differs from `staged.system`, durably remove stale `staged`, then its root and obsolete reboot projection.
- Preserve a genuine pending rollback.
- Reconcile an interrupted transaction only when the observed profile and boot selection establish the operator’s repaired state; unknown selection retains the hold.
- Derive drift from the ledger and running system. Persist an `adopt` request when the operator keeps that running system.
- Remove the hold last, release the lock and start the service.

Health and adoption happen in `run`, not inside `clear`. This closes the stale-stage loop at `modules/converge/scripts.nix:753` without making the operator command another deployment engine.

Bootstrap remains automatic for a healthy, consistently selected running system. It records `rev=`; it does not copy the unproven legacy `deployed-rev` association used at `modules/converge/scripts.nix:363`.

### Reboot and Waybar projections

Retain `/var/lib/reboot-pending/state` with `since` and `diverged`, and `last-blocked` with `at` and `reason`. A pending rollback independently requires reboot, even when the three components match. Preserve `since` while any reboot reason remains.

Waybar currently reads `since` and the blocked reason directly (`pkgs/converge-status/render.go:31`); retain those fields and existing status phases (`pkgs/converge-status/status.go:25`). Deployment decisions never depend on their freshness.

Replace the drift tooltip with wording that says drift persists until operator reconciliation. Moving `main` does not clear it; the current text says otherwise (`pkgs/converge-status/render.go:165`, `modules/converge/scripts.nix:482`).

**Rejected:** a new ledger format, automatic drift adoption, provenance guessed from an old revision file, and health checks inside `hold clear`.

## 3. Crash safety and recovery

**Decision:** use roots before references, atomic durable record replacement and a hold before repair. Keep failure handling local and inspectable.

### Persistence rules

For every authoritative record:

1. Create a temporary file in the destination directory.
2. Write the complete record; check write and close errors.
3. `fsync` the file.
4. Rename over the destination.
5. `fsync` its parent directory.

For deletion, unlink and sync the **actual parent directory**. The current `drop` syncs only the state directory, even for children elsewhere (`modules/converge/scripts.nix:133`). Use the same discipline for quarantine entries and root-directory changes.

A persistence error stops progress. An existing transaction blocks unattended reboot even if writing the hold itself fails. Status reporting cannot turn such an error into a successful deployment.

### Root and record order

Register unique roots through Nix before publishing any record that needs them. Sync the root links and their registration directories. Retain both old and new LKG roots across promotion.

The stable `roots/good` and `roots/staged` names remain operator conveniences and compatibility aliases. Unique roots prevent replacing an alias from exposing the old recorded system to GC—the current failure at `modules/converge/scripts.nix:398` and `modules/converge/scripts.nix:447`.

| Operation | Durable order |
|---|---|
| Begin transaction | Root target, old good, prior stage and relevant profile → write `txn` → permit side effects |
| Stage | Install, flush and verify → write `staged` → mark transaction committed → cleanup |
| Promote or adopt | Protect old/new good → write `good` naming transaction → mark committed → update aliases → cleanup |
| Bootstrap | Root running system → write `good` with empty revision |
| Quarantine | Write failed revision’s record before completing failure handling |
| Stage rollback | Root good → transaction → install/verify good → write `rollback` → mark committed → retire stage |
| Consume recovery | Write hold → optional repair → rewrite hold with outcome |
| Clear hold | Reconcile records and adoption intent → delete hold last |
| Cleanup | Delete superseded authoritative records and sync → remove unused roots and sync |
| Reboot projection | Read authoritative state under lock → atomically replace or remove projection files |

Cleanup must not remove transaction roots before durably retiring the transaction. The existing order does that at `modules/converge/scripts.nix:349`.

Go tolerates old fixed root names. On first reading a Bash ledger, it protects every still-valid referenced closure before changing aliases. Unreferenced roots left by a crash are harmless and are reclaimed only after checking all durable references.

### One automatic recovery attempt

The hold itself is the consumed-attempt marker because a standing hold is checked before transaction recovery (`modules/converge/scripts.nix:301`).

For an uncommitted transaction, write a hold saying recovery is consumed **before** invoking any repair. If selection demonstrably moved and repair is safe, install and verify `good` once. Rewrite the hold with success or failure. Never activate a live system during this recovery.

A crash immediately after writing the hold can consume the attempt without performing repair. That conservative outcome is intentional. Repeated timers cannot repeat a hanging installer. The existing code persists the hold only after restoration (`modules/converge/scripts.nix:337`, `modules/converge/scripts.nix:348`).

A leftover `loader/loader.tmp`, persistent EFI override or unknown selection prevents blind retry. Diagnostics name the obstruction and the operator’s repair action.

### Power loss

| Cut point | Restart behavior |
|---|---|
| During build or root preparation, before `txn` | No deployment change; leftover roots are reclaimable |
| After `txn`, before or during activation | Uncommitted recovery consumes one attempt and holds |
| During profile or boot installation | Keep old good rooted; inspect actual selection; repair once or hold |
| After installing a target, before `good`/`staged` | Target is not accepted; recover from the transaction |
| After `good`/`staged`, before commit flag | Matching transaction identity establishes commitment |
| During cleanup | Replay cleanup; remaining roots keep referenced closures alive |
| During recovery | Durable hold prevents another automatic attempt |
| During hold clearing | Hold survives until bookkeeping is durable; a later run handles remaining adoption intent |
| During status/projection writes | Recompute from the ledger and actual systems |

File durability does not make FAT boot installation transactional. Flush the boot filesystems after the installer and before committing a record; propagate flush errors. The pinned systemd-boot builder already calls `syncfs`, explicitly because FAT offers limited crash recovery (`SDboot:665`). Torn-installation tests and removable-media recovery remain necessary.

### Lock and shutdown

Keep the lock file in the rebuild tool’s state directory as a stable inode. Never replace or delete it. `run` and `hold clear` use nonblocking exclusive flock. A busy run exits without creating a transaction.

Reboot-attempt takes the same lock before checking fresh deployment state and retains it through the reboot request and shutdown handoff. A hold, unresolved transaction, invalid boot selection or missing required root blocks reboot. Failure to open a configured lock also blocks; the current script skips some lock-open failures (`modules/common/auto-reboot-scripts.nix:107`).

Add:

```nix
systemd.services.<rebuild service>.after = [ "reboot-attempt.service" ];
```

Reverse stop ordering stops converge before reboot-attempt releases its lock. Nonblocking acquisition removes the waiting converge process described by the review (`modules/converge/scripts.nix:84`; the Astra review, line 82). Systemd documents the reverse shutdown order in [systemd.unit, Before=/After=](https://www.freedesktop.org/software/systemd/man/latest/systemd.unit.html#Before=).

Keep normal, non-forced `systemctl reboot` and the bounded lock-holding behavior on an accepted request (`modules/common/auto-reboot-scripts.nix:216`). A cancelled shutdown leaves no durable barrier to clear.

**Rejected:** a runtime shutdown barrier, durable attempt counters and automatic live recovery after a crash. Direct root invocation during shutdown remains outside the systemd handoff guarantee.

## 4. Boot loaders and reboot exceptions

**Decision:** boot installation and boot verification are separate operations. Verification never accepts an empty result, unlike `modules/converge/scripts.nix:185`.

### No EFI writes

Neither Go nor its installer writes firmware variables. There are no calls to `set-default`, `set-oneshot`, firmware `BootNext` setters or automatic clearing commands.

This includes child installers: both systemd-boot hosts currently allow EFI writes in their hardware configuration. The pinned builder uses that setting for both command-line and Varlink installation (`SDboot:498`, `SDboot:518`).

Nix therefore supplies a boot-only installer configured with `canTouchEfiVariables = false`. Go invokes that standard installer with the selected closure, including when restoring a legacy LKG; it does not fall back to the legacy generation’s EFI-writing wrapper. Passing the closure to the installer is the existing NixOS interface (`STC:256`). Firmware registration remains an operator installation/repair action.

Here, **boot-only installation** means profile update, Nix-provided installer, filesystem flush and verification. It performs no live activation.

### systemd-boot

Read `bootctl list --json=short` using the configured ESP/boot paths. Require exactly one resolved default, a supported NixOS entry and one unambiguous `init=` identifying the expected closure. Check referenced boot payloads as well as the profile.

A set `LoaderEntryDefault` is an operator override even when it currently names the expected system. Hold staging and promotion, name the variable and suggest the operator command:

```sh
sudo bootctl set-default ""
```

Converge never executes it. Also reject other persistent selection overrides that prevent establishing the managed default.

There is a necessary distinction between **next boot** and **persistent selection**. Upstream v261 selects `LoaderEntryOneShot` before persistent defaults and exposes that result as `isDefault` (`src/shared/bootspec.c:1475`, `src/shared/bootspec.c:2113`). Thus one JSON result cannot serve both purposes. [systemd v261 boot selection source](https://github.com/systemd/systemd/blob/v261/src/shared/bootspec.c#L1475)

When a one-shot exists, retain the normal EFI-aware read for diagnosis and obtain the file-based persistent selection through bootctl’s rooted, read-only view of the same boot files. This view is valid only after separately establishing that persistent EFI overrides are absent. Upstream’s rooted reader skips EFI pointers (`src/bootctl/bootspec-util.c:41`). [systemd rooted reader](https://github.com/systemd/systemd/blob/main/src/bootctl/bootspec-util.c#L41)

**Unconfirmed at the exact systemd pin:** the JSON and rooted-view behavior of 261.3. Nixpkgs selects that version at `pkgs/os-specific/linux/systemd/default.nix:206`. Real OVMF tests must establish both behaviors before the boot-selection change merges. Do not substitute a hand-written wildcard resolver or silently ignore EFI on ordinary verification.

### ESP capacity and the LKG entry

Before installing a replacement stage, prune profile generations positively identified as superseded stages. Protect their closures through the transaction first. Exclude the running, booted and LKG systems and unrelated manual generations. If a staged generation is currently the profile target, set the new profile before deleting that now-superseded generation.

After **every** installation, verify both the intended selection and a usable LKG entry with its payloads. Absence of the LKG entry creates a hold and blocks unattended reboot.

This prevents repeated stages from consuming the ten-entry allowance without copying additional recovery kernels and initrds onto the ESP. The repository records an actual ESP-full failure and sets `configurationLimit = 10` for that reason (`modules/common/system.nix:122`).

A rooted LKG can still age out of the profile/menu while a stage waits; daily GC removes generations older than seven days (`modules/common/system.nix:116`). The post-install check detects that condition. Root protection preserves the closure for console repair; it does not promise permanent menu membership.

### extlinux on the Pis

Nix selects extlinux on the Pis. Parse `DEFAULT`, resolve its unique `LABEL`, and validate its `APPEND init=`, kernel, initrd and applicable device-tree paths. Unknown or malformed selection holds.

This is hardening of the current parser, not evidence that ordinary generated configurations select the wrong label: the pinned builder writes `DEFAULT nixos-default` and creates that entry (`Extlinux:132`, `Extlinux:140`). Flush `/boot` after installation; the builder renames its configuration and removes obsolete payloads (`Extlinux:161`).

### Reboot exceptions

- **systemd-boot hosts:** any pending `LoaderEntryOneShot` or firmware `BootNext` blocks unattended reboot with a visible reason. It does not by itself block live deployment. Persistent overrides hold staging and promotion. Unreadable selection state blocks reboot.
- **The workstation:** Windows has its own ESP. `reboot-windows` sets firmware `BootNext` before requesting reboot, so a refused reboot can leave that choice pending. Converge preserves it.
- **Pis:** a failed local DNS probe permits bypassing the peer requirement; otherwise at least one peer must answer correctly. A rollback marker grants no exception. Remove the bypass in the Pis’ peer check and the corresponding option; retain the existing self-check there.

Idle, active-unit, agent and inhibitor checks remain in force. The DNS exception bypasses only the peer requirement.

**Rejected:** EFI setters, duplicated console-fallback payloads, firmware-choice cleanup and a new resolver-policy subsystem. Console recovery uses an existing LKG menu entry when available, otherwise a USB installer and `roots/good`; a Pi can be repaired through its SD card.

## 5. Testing and build cost

**Decision:** keep the existing harnesses and VM test, replacing their executable under test with the real Go binary. Stubs represent external commands, not a second implementation of the state machine.

`modules/converge/test.nix` already drives command boundaries; its GC implementation is only a symlink stub (`modules/converge/test.nix:66`). `modules/common/auto-reboot-test.nix` supplies the reboot harness. The VM supplies real activation and systemd-boot (`modules/converge/vm-test/node.nix:35`).

| Check | Required behavior | Cost |
|---|---|---|
| Go package and small unit tests | Strict ledger parsing, extlinux selection, DNS equality, transaction identity | Quick; compile and local tests |
| Rebuild tool harness | Real CLI, all ledger transitions, seeded Bash records, hold clearing, candidate checks, action order | Quick; no NixOS VM |
| Record fault matrix | Process termination before/after record publication, deletion and root replacement; restart and inspect invariants | Quick harness cases |
| `auto-reboot` harness | Rollback-only reason, hold/transaction blockers, lock failure, one-shot/BootNext deferral, existing blockers | Quick |
| `converge-status`, `waybar-converge` | Compatible projections and corrected drift wording | Quick |
| Pinned extlinux-builder check | Run the real builder in a sandbox; parse its output and verify referenced files | Quick; no aarch64 boot VM |
| Rebuild tool VM test | Real GC, OVMF variables, interrupted installer, actual subsequent boot and unit ordering | Slow |
| `resolver-redundancy` | Healthy sole resolver cannot reboot; locally broken resolvers can recover | Slow |
| `valley-converge-read` | Actual scoped SSH discovery and flake read | Slow |
| Host evaluation and architecture package builds | All deploying host configurations; x86_64 and aarch64 binary availability | Eval quick; cold builds unmeasured |

The existing policy marks the harnesses quick and VM checks slow (`policy/project/policy.cue:20`). Add `pkgs/converge/**` to the relevant check mappings so implementation changes owe the same behavior checks as module changes (`policy/project/policy.cue:65`). Preserve other owed checks, including the webhook-secret VM when applicable.

### Required fault cases

1. **D8:** systemd-only changes activate live; rollback alone remains pending; staged-to-live restoration precedes `test`; a failing old-system `test` leaves the safe boot selection; `loader.tmp` blocks repair; a now-compatible leftover stage goes live.
2. **GC ordering:** kill around bootstrap, adoption and promotion. In the VM, arrange that the old good is neither running nor booted, remove its old profile generations and exclude it from fixture roots. Run real GC and prove it survives solely through converge’s roots.
3. **One attempt:** kill or hang recovery before, during and after the installer. Repeated runs leave the hold and do not call the installer again.
4. **Boot verification:** missing/malformed entries, wildcard defaults resolved by bootctl, persistent overrides, one-shot selection, `BootNext`, unreadable EFI state and payload loss.
5. **EFI preservation:** fixture code sets real OVMF variables; converge never changes them. Persistent overrides hold; one-shot choices permit live deployment but block reboot.
6. **Torn installation:** pause the real pinned installer inside configuration/payload writes and cut VM power without an added `sync`. Test `loader.tmp` and selection recovery. The existing F case hangs after installation and explicitly syncs before the cut, so it is not this test (`modules/converge/vm-test/node.nix:137`, `modules/converge/vm-test/default.nix:336`).
7. **Promotion:** assert `test → trusted check → own check → self-check → boot`. A failing candidate checker or crashing candidate binary prevents promotion. No second activation follows the checks.
8. **Hold clear:** reproduce stale stage B with running/profile/default A and main still B; invoke the actual CLI and service; the stale contradiction does not recreate the hold.
9. **Lock handoff:** hold the lock, start converge and assert prompt exit with no transaction. Verify the installed `After=` relationship and exercise shutdown in the VM. No production shutdown pause hook is required.
10. **DNS/Pi:** reject expected-plus-wrong DNS answers; invert the rollback-bypass expectation in the Pis’ redundancy test.

For the GC VM, root other offline fixtures explicitly. `additionalPaths` copies closures into the image; it does **not** root them (`modules/converge/vm-test/default.nix:72`, `Image:524`). Include an unrooted control closure that GC actually deletes.

Keep the health command’s documented timing contract. The outer allowance already includes one probe timeout; kill grace is visible in the implementation (`modules/converge/default.nix:322`, `modules/converge/default.nix:101`). The defect fixed immediately is DNS membership matching at `modules/converge/default.nix:125`, not a newly discovered timeout policy.

Run quick checks individually in the agent environment. Heavy VM and cold architecture builds run on a larger machine. The repository forbids full `nix flake check` in the guest and reports roughly seventeen minutes for the existing converge VM there (`AGENTS.md:73`); new timings are unmeasured.

**Rejected:** an aarch64/U-Boot VM, a dedicated Bash-to-Go compatibility VM and mocked state-machine unit tests. Seeded records, the pinned builder and real-binary harnesses cover those boundaries more cheaply.

## 6. Cutover and rollback

**Decision:** use ordinary NixOS generations and the compatible ledger. There is no fleet-wide migration command or engine feature flag.

The change introducing Go also changes the unit entry points. An existing Bash run finishes under its own executable and lock; the unit’s existing no-restart settings preserve that behavior (`modules/converge/default.nix:419`). The next invocation runs Go and reads the same records.

A host with a committed transaction finishes cleanup. A host with an interrupted transaction consumes one recovery attempt and holds. A staged host continues boot validation. A held host remains held. No records are cleared merely because the executable changes.

Before the boot-selection change lands, its real OVMF tests pass. Land it during an attended maintenance period so an unexpected hold is inspectable at a console. This is an operational precaution, not a new rollout system.

Rollback selects the previous NixOS generation. Preserve the ledger and roots. Older Bash can read the retained record fields and stable aliases; extra unique roots can leak temporarily but remain protective. Returning to Bash also returns its known defects, so it is a recovery option, not the completed acceptance state.

If boot files are unusable, use removable media, mount the host filesystems and reinstall the boot configuration from the closure reachable through `roots/good`. For a Pi, repair the SD card. Never make deleting the ledger part of recovery.

**Rejected:** exporting/importing state, resetting hosts to bootstrap and a final all-at-once engine flip.

## 7. Slices

**Decision:** use the review’s six-change shape. Every change includes the tests for its live behavior.

| Change | Live result | Findings closed |
|---|---|---|
| **0. D8 baseline** | Three-component divergence, rollback-only reboot reason, safe staged-to-live order and `loader.tmp` guard | Retains operator-supplied fixes; tests the two D8 defects and corrected leftover guard |
| **1. In-place fixes** | Correct Waybar text, remove Pi rollback bypass and `rollbackMarker` option, require exact DNS answer | Waybar, Pi exception, DNS probe defect |
| **2. Go executor** | Package and wire `run`, `result`, `hold`; use valley input; preserve record formats; add unique roots, durable deletion, hold-before-repair, nonblocking lock and `After=` | GC-root ordering, one-attempt recovery, shutdown handoff; record-boundary and real-GC coverage |
| **3. Boot selection** | Use resolved bootctl selection and extlinux `DEFAULT`; provide no-EFI installer; prune superseded stages; check LKG entry; add one-shot/BootNext reboot guard | Boot-default verification and torn-installer coverage; revision-1 EFI-write defect |
| **4. Promotion and operator reconciliation** | Use `test → checks → boot`; run candidate checker and read-only binary self-check; reconcile stale stage in `hold clear`; bootstrap with empty revision | Unchecked activation, hold-clear loop, bootstrap provenance and candidate-deployer failure |
| **5. Reboot and health commands** | Wire Go reboot commands and Go health checker; reuse the DNS probe from the small Nix-defined peer command; remove embedded Bash state machines | Completes the port with behavior parity |

Change 2 makes the existing reboot path consult Go’s read-only blocker check while holding the shared lock, so holds and unresolved transactions already inhibit reboot. Change 3 extends that same check with boot-selection blockers. Change 5 replaces the remaining reboot orchestration.

The health checker stays live in its existing form, with exact DNS matching, until change 5. Its port preserves service, route, DNS, banner and sustain semantics. The peer command retains the existing local-DNS-fails-or-peer-answers rule; it gains no separate Go resolver policy, recovery token or coordination ledger.

Changes 2–4 complete their respective behavior in the same change that wires it. Helpers appear when a live command uses them.

**Rejected:** separately landing unused engines, a large final cutover and an unspecified “finish fault tests” slice.

## Open questions for the operator

- **Where are the rescue USB and Pi SD-card reader kept?** Recommendation: keep them available at the machines and verify access to the host filesystems and `roots/good` before the boot-selection landing.
- **Which attended window covers the first boot-selection deployment?** Recommendation: use a period with console access to the workstation and the valley host and physical access to the Pis. No separate rollout mechanism is required.

The one-shot policy, EFI-write prohibition, Pi exception and six-change delivery shape are settled decisions, not open questions.

## Risks

- A failure before converge starts still needs console recovery. Existing documentation records this limitation for both loaders (`docs/converge.md:181`).
- FAT corruption or ESP exhaustion can defeat boot-file installation despite a sound ledger. Roots preserve recovery inputs; they do not make the ESP transactional.
- An LKG generation can disappear from the menu while its closure remains rooted. The post-install check stops unattended reboot, leaving operator repair.
- Exact systemd 261.3 JSON/rooted-view behavior remains a verification dependency. The boot-selection change cannot merge on fixtures alone.
- `switch`-specific hooks do not run. Candidate self-check proves that the deployer starts and understands the ledger, not that all its future behavior is correct.
- A locally broken Pi may reboot without a healthy peer; a healthy sole resolver waits. These are the intended availability tradeoffs.
- Rollback may wait for the next configured reboot window, as documented at `docs/converge.md:178`. This port does not add emergency scheduling.

## Changes from revision 1

All numbered review findings are **adopted**. Two implementation qualifications are explicit above: one-shot-aware verification needs separate persistent and next-boot views, and the no-EFI rule includes the child installer.

| Review finding | Disposition and evidence |
|---|---|
| **1. VM fixture roots** | **Adopted.** `additionalPaths` copies closures; GC tests remove profile protection and root only the other fixtures (`Image:524`, `modules/common/system.nix:119`). |
| **2. Windows selection** | **Adopted.** Separate ESP and firmware `BootNext`, not a systemd-boot Windows entry, per the workstation’s host configuration. |
| **3. Health deadline** | **Adopted.** Existing documented allowance is preserved; exact DNS equality is the fix (`modules/converge/default.nix:322`, `modules/converge/default.nix:125`). |
| **4. extlinux `DEFAULT`** | **Adopted.** Parsing it is hardening; the pinned builder emits the expected label (`Extlinux:132`, `Extlinux:140`). |
| **5. Citation corrections** | **Adopted.** Correct references include `docs/converge.md:156`, `docs/converge.md:181`, the Astra review, line 99, and `modules/common/system.nix:130`. |
| **6. ESP fallback payloads** | **Adopted.** Remove them; prune stages and verify the LKG entry. The ESP-full incident is documented at `modules/common/system.nix:126`. |
| **7. Runtime barrier** | **Adopted.** Nonblocking acquisition removes the waiter; add stop ordering (`modules/converge/scripts.nix:84`, `modules/common/auto-reboot-scripts.nix:216`). |
| **8. Consumed-attempt records** | **Adopted.** Write the existing hold before repair (`modules/converge/scripts.nix:301`, `modules/converge/scripts.nix:348`). |
| **9. Resolver policy and health order** | **Adopted.** Remove the bypass, retain the self-check, port health last and execute the candidate checker (the Pis’ peer check, `modules/converge/scripts.nix:603`). |
| **10. Promotion sequence** | **Adopted and verified at the nixpkgs pin.** Boot installation does not perform another activation (`STC:1843`, `STC:1859`). |
| **11. Clear/bootstrap** | **Adopted.** Clear reconciles bookkeeping; bootstrap does not inherit unproven revision provenance (`modules/converge/scripts.nix:753`, `modules/converge/scripts.nix:363`). |
| **12. Test simplification** | **Adopted.** Use seeded records, the pinned extlinux builder and deterministic lock contention (`modules/converge/test.nix:1`, `Extlinux:126`, `modules/converge/scripts.nix:84`). |
| **13. EFI-write P1** | **Adopted.** No EFI setters; persistent overrides hold. Installer writes also require disabling (the Astra review, line 32; `SDboot:498`, `SDboot:518`). |
| **14. Compensation order** | **Adopted as D8 baseline.** Boot restoration precedes live compensation; test failure cannot reverse that order. Earlier unsafe order: `modules/converge/scripts.nix:614`. |
| **15. Rollback reboot reason** | **Adopted as D8 baseline.** Rollback independently keeps reboot pending. Earlier component-only detector: `modules/common/auto-reboot-scripts.nix:29`. |
| **16. Candidate deployer** | **Adopted.** Run its binary read-only before acceptance; current promotion only checks for a checker executable (`modules/converge/scripts.nix:603`). |
| **17. Fleet-wide accidental holds** | **Adopted.** Real OVMF variable tests gate boot-selection delivery; the existing VM already uses UEFI (`modules/converge/vm-test/node.nix:35`). |

The coverage omission for a now-compatible leftover stage is also adopted (`modules/converge/scripts.nix:493`). Agent-guest deployment material is removed per the operator’s corrected scope.

Comments

  1. contributor2026-10-21 10:15 UTCedited2026-10-29 01:08 UTC by contributor
    Cross-family review (Claude) of the converge-in-Go design revision 1, 2026-10-21. Revision 2 (the body) adopts every finding.
    
    # Review: "Converge in Go" (the deployment project at a45d858)
    
    **Verdict.** The diagnosis is right: all nine D11 findings are open, at the lines the design cites. The compatible ledger, status as a projection, the trusted checker, a nonblocking lock, roots before records and parent-directory fsync all hold against the source. But the design adds a new way to boot a quarantined system through EFI writes (13), misses both D8 defects (14, 15), carries about five unneeded mechanisms, and ships seven slices of dark code before one big flip.
    
    ## 1. Citations
    
    I checked about 60 citations, including every one a decision rests on. Most are exact. These are wrong or misleading:
    
    1. **P3 — `vm-test/default.nix:70`, "blanket reachability".**
       - `additionalPaths` is copied in with `nix copy --to` (`make-disk-image.nix`) and registered, but not rooted.
       - Profile generations keep the deployed systems, since they all sit inside `nix.gc`'s 7-day window (`system.nix:116-119`).
       - The real hazard runs the other way: GC deletes prebuilt systems that the offline VM still needs. The GC case must drop old generations and root its own fixtures.
    2. **P3 — `flake.nix:325` as grounds for "foreign-OS selection".** The workstation's Windows has its own ESP, which systemd-boot cannot select (per its host configuration); `reboot-windows` sets firmware `BootNext` and reboots. No systemd-boot Windows entry exists.
    3. **P3 — the "fix" at `default.nix:100`.** The deadline overrun is already documented (`default.nix:322-324`). Only the DNS match at `:125` is a defect.
    4. **P3 — `scripts.nix:172`.** It's true that the parser ignores `DEFAULT`. But the pinned extlinux builder always writes `DEFAULT nixos-default` with that label, so this is hardening, not a defect.
    5. **P3 — offsets:** `docs/converge.md:154`→156, `:176`→181; review `:97`→99; `system.nix:122`→130.
    
    ## 2. Coverage
    
    | Finding | Slice | Assessment |
    |---|---|---|
    | Boot default | 3 | Concrete fix and VM test; but see 13 |
    | GC-root order | 2, 6 | Concrete fix; the test's premise is wrong (1) |
    | Unchecked switch | 5 | Concrete and tested |
    | Pi exception | 4 | Concrete and tested |
    | `hold clear` | 7 | Concrete; tested through the real CLI |
    | One attempt, `loader.tmp` | 3, 7 | Concrete and tested |
    | Shutdown handoff | 8 | The fix is concrete. The test needs a pause hook in production code, so this is only **claimed** |
    | Fault tests | 2–9 | Record boundaries, GC and the installer are concrete. Slice 9's "complete missing-test matrix" is a placeholder |
    | Waybar | 1 | Concrete |
    
    **Missed:** both D8 defects (14, 15), and a leftover staged record whose kernel parts match the booted system, which must go live rather than wait for a reboot.
    
    ## 3. Simplification
    
    6. **P2 — Cut the console fallback and the ESP recovery payloads.**
       - **The real gap.** Every rev after a kernel bump stages, and `configurationLimit = 10` (`system.nix:130`). Ten superseding stages before a reboot push the LKG off the menu.
       - **Simpler.** Delete superseded staged generations before staging. After each install, hold if no LKG entry exists; a hold blocks the reboot. Document USB-installer recovery from `roots/good`. For the Pis, pull the SD card.
       - **What the design does instead.** It copies a kernel and initrd to FAT on every promotion, on an ESP that has already filled up once (`system.nix:126-128`).
       - **Accepted risk.** An LKG generation can age past seven days while a stage waits. The post-install check catches it.
    7. **P2 — Cut the runtime barrier; keep the one-line `After=`.**
       - The only blocking waiter is converge's own `flock` (`scripts.nix:84`). Made nonblocking, a run started earlier exits on the busy lock.
       - Once `systemctl reboot` queues shutdown, systemd refuses start jobs that conflict with `shutdown.target`.
       - The barrier also adds a stuck state: a cancelled shutdown needs an operator.
       - **Accepted risk.** A root user invokes it by hand during shutdown.
    8. **P2 — Reduce durable consumed-attempt bookkeeping to write order.**
       - The hold file is the consumed attempt, since `scripts.nix:301` exits on it.
       - Write the hold, repair, then rewrite the hold with the outcome.
       - Drop the attempt fields, the boot ID and the compensation fields. No new risk.
    9. **P2 — Cut the resolver policy in Go.**
       - Delete `peer-check.nix:37-40` and the `rollbackMarker` option, and invert `redundancy-test.nix:240`.
       - The existing self-check (`:41-45`) is exactly D11's exception.
    
       **Port the Go health command last.** Fix DNS now with exact equality at `default.nix:125`. Accepted risk: about 80 lines of Bash stay a while.
    
       **Keep the candidate's own check**, for a stronger reason than the design gives. The LKG's checker judges every target. An accepted generation whose new checker always fails would therefore quarantine every later rev.
    10. **P2 — Close "unchecked switch" with `test`, check, `boot` instead of a second check.**
        - `switch` is a bootloader install plus the same activation (`switch-to-configuration-ng` `main.rs:1843`). I read this in a local 26.11 nixpkgs; it is unverified at the pin.
        - So a `boot` after a healthy `test` leaves no unchecked activation. The design rejects this without a source argument.
        - **Accepted risk.** Hooks keyed on `NIXOS_ACTION=switch` don't run.
    11. **P2 — `hold clear` does bookkeeping only.**
        - Under the lock, drop `staged`, its root and the reboot state when the effective selection isn't the staged system. Then start the service, which runs the health checks.
        - Bootstrap records an empty `rev=` instead of holding. Holding by default would stall every re-imaged Pi.
    12. **P2 — Tests.**
        - Cut the aarch64/U-Boot boot VM. Instead, run the pinned extlinux builder in a sandbox and parse what it writes.
        - Replace the Bash-to-Go compatibility VM with harness cases seeded with Bash-format records.
        - Make the shutdown test deterministic: hold the lock, start converge, and assert that it exits with no transaction.
    
    The agent-guest material is out of scope, so drop it (P3).
    
    ## 4. Safety gaps
    
    13. **P1 — `bootctl set-default` (§4) can boot a quarantined system.**
        - A pinned `LoaderEntryDefault` overrides `loader.conf`, so later writes silently lose. That covers the interactive rebuild tool, `nixos-rebuild`, and the hold's own instruction (`switch-to-configuration boot`, `scripts.nix:336`).
        - If the pin points at a staged system that then fails, every reboot returns to it.
        - **Fix.** Never write EFI variables. Read the bootctl-resolved default (`bootctl list --json` `isDefault`; verify at the pinned systemd). Hold on any override, and name `bootctl set-default ""` in the hold.
    14. **P1 — Compensation order is unspecified (D8 defect 2).**
        - Today the old system is `test`ed before the boot default is restored (`scripts.nix:614-616`). If that `test` fails, the next boot is the quarantined target.
        - **Specify the order:**
          1. Restore and verify the boot selection: the prior stage if one exists, else the LKG.
          2. Then `test` the old system.
          3. Then check it.
        - Test the case where that `test` fails.
    15. **P1 — A pending rollback must be a reboot reason on its own (D8 defect 1).**
        - reboot-needed compares only components (`auto-reboot-scripts.nix:18-33`).
        - Take a pre-D8 stage that differs only in systemd and boots unhealthy. Its rollback shows no divergence.
        - The host then waits on the failed system forever (`scripts.nix:471`). The projection must include `rollback`.
    16. **P2 — Nothing proves the candidate's deployer runs.**
        - A Go binary that crashes on the ledger still passes the health check and becomes the LKG. After that, no host can deploy the fix.
        - **Fix.** Before promotion, run the target's converge binary read-only against the ledger.
    17. **P2 — Fleet-wide hold at cutover.**
        - Wrong bootctl parsing holds every systemd-boot host on its first Go run.
        - The VM case with real OVMF variables must pass before merge.
    
    ## 5. Proposed shape
    
    Six changes including D8, each shipping live code:
    
    0. **D8 (in flight).** Its two fixes become harness cases.
    1. **In-place fixes**, each with a test. This closes three findings in days.
       - Waybar wording.
       - Remove the Pi bypass.
       - Exact DNS match.
       - The `loader.tmp` guard.
    2. **`converge run|result|hold` replaces `scripts.nix`.** The units switch in the same change, and the existing harness and VM test drive it. This closes GC-root order, one attempt and the shutdown handoff. Split the translation from the fixes if the diff is too big. It includes:
       - unique roots written before records;
       - the hold written before repair;
       - parent-directory fsync;
       - a nonblocking lock plus `After=`;
       - kill points at every record write;
       - a real-GC VM case.
    3. **Boot selection.** This closes boot-default verification and torn writes.
       - Use the bootctl-resolved default and extlinux `DEFAULT`.
       - Unknown selection holds.
       - No EFI writes.
       - Prune superseded stages and check for the LKG entry.
       - A one-shot or `BootNext` blocks the reboot.
       - VM cases: a `set-default` override, and a power cut inside the installer without `sync`.
    4. **Promotion.** This closes the unchecked switch and `hold clear`.
       - `test`, check, `boot`.
       - The candidate's own checker and a binary self-check.
       - `hold clear` as bookkeeping.
       - Bootstrap provenance.
    5. **The reboot side and the health checker in Go.** The peer check reuses the DNS probe. This is parity only, and it deletes the last Bash.
    
    **One-shot and foreign defaults on the workstation: what I recommend.**
    
    - **Never write `LoaderEntry*` or `BootNext`.**
    - **Windows isn't a systemd-boot entry.** The only foreign state is a firmware `BootNext` that `reboot-windows` leaves behind when logind refuses its reboot. It would send the 04:45 auto-reboot into Windows.
    - **Block the reboot, not deployment.** reboot-attempt blocks, with a visible reason, while `LoaderEntryOneShot` or `BootNext` is set. Live deployment continues.
    - **A persistent override holds staging.** A `LoaderEntryDefault` override leaves the selection unverified, so staging and promotion hold and name the command that clears it.
    - **Never silently erase the operator's choice.**
  2. contributor2026-10-21 16:49 UTCedited2026-10-29 01:08 UTC by contributor
    Residual from the change-1 review (a deployment change, Codex, 2026-10-21), for change 5 when the peer check reuses the Go DNS probe: the Pis' peer check merges dig's stderr into the answer and ignores its exit status, so three probe errors (e.g. dig unable to create sockets) count as three resolver failures and authorize the reboot of the only working resolver. Count only a reply with the wrong answer, or dig's no-reply exit (9), as failure; any other probe error blocks the bypass. Pre-existing; that change requires three failures 10 s apart, which covers transient timeouts.
  3. contributor2026-10-21 20:51 UTCedited2026-10-29 01:08 UTC by contributor
    Change 2 launched 2026-10-21 (run 20261021-2050-e9bbc402) after a Codex critique of its brief. Design amendment: the switch to valley deployment input moves out of change 2 into its own change after it, because it also needs host read identities in the valley's registry (the instance repository); change 2 is a port that keeps each host's declared source. Also: self-check moves to change 4, where it gains its caller. Changes 0 (D8) and 1 have landed.
  4. contributor2026-10-22 10:48 UTCedited2026-10-29 01:08 UTC by contributor
    Change 2 landed 2026-10-22: the deploy side runs as the converge binary in Go; GC roots before records, one recovery attempt, the shutdown handoff, plus the review fixes (a rejection stands before quarantine, every reference rooted centrally, commitment matched on kind, rev and system, fault hooks only in a test build). Next: a docs/converge.md fix for the trigger wording (push where webhookDispatch is on, timer as backstop), then change 3 (boot selection), which wants the operator near the consoles.
  5. contributor2026-11-08 22:29 UTC
    Tracked in the project its work lands in, named in target, whose deploy-safety outcome cites this knot.