beads/scripts/update_nix_vendorhash_unix_test.go
Rongjun GENG 7838c4b449
fix(scripts): update-nix-vendorhash no longer reports a build failure as success (#7504)
* fix(scripts): update-nix-vendorhash no longer reports a build failure as success

scripts/update-nix-vendorhash.sh treated the absence of a "got:" hash
line as proof the vendorHash was already correct, so a build failure
unrelated to a hash mismatch (e.g. a Go toolchain too old for a
dependency) was misreported as success and the workflow went green on
a broken build (#7496). Fixed by capturing the intentional-failure
build's real exit status instead of discarding it with `|| true`, and
using that exit status (not a "hash mismatch" string grep) to tell a
genuine no-op apart from an unrelated build break.

The step-5 verification build had the same shape of bug: piping
through `tee` without pipefail meant the if-condition tested tee's
exit status, not the build's, so a failing verification build still
printed "Build successful!". Scoped `set -o pipefail` to just that one
line rather than the whole script, since the earlier hash-extraction
step legitimately relies on `grep -o` returning non-zero on no match.

Fixes gastownhall/beads#7498.

Added an independent `nix build .#default` step to
update-vendor-hash.yml so the workflow no longer trusts the script's
exit status alone, even if a future bug in the script reintroduces a
false-success path.

Fixes gastownhall/beads#7499.

Added TestPinnedDoltCLIAtLeastRecommendedMin, asserting the pinned
Dolt CLI version (scripts/ci/install-dolt.sh) is at least
doltversion.RecommendedMin, so the two policies can't silently drift
apart — RecommendedMin's own doc comment already claims this alignment
but nothing enforced it.

Fixes gastownhall/beads#7500.

Verified by reproducing both update-nix-vendorhash.sh failure modes
with a stub `nix` binary (a non-hash build failure, and a step-5
verification build failure) and confirming the intended successful
hash-update path still works end to end. go build/vet clean,
golangci-lint 0 issues, go test ./scripts/... passes except a
pre-existing unrelated failure (TestControlQueryScriptPreservesReadyProbeFailure,
tracked separately as beads#7293 and untouched by this change).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VN2SgXAHW1eTB1izwWwmyr

* chore: empty commit to retrigger CI -- retrying after a 3-hour quota recovery window

* chore: empty commit to retrigger CI -- isolated single retry after real-bug fixes landed on sibling PRs

* fix(scripts): add missing BUILD.bazel dep, sharpen vendorhash diagnostics

scripts_test now imports internal/doltversion (for
TestPinnedDoltCLIAtLeastRecommendedMin) but scripts/BUILD.bazel had no
matching dep row, which would fail the target's compile under
rules_go once Bazel actually runs against this branch (the Bazel /
jobs failing so far died in bazel.fork-cert, unrelated to this).

Also, per review: scope set -o pipefail to just the step-5 verify
block (turn it back off after, rather than leaving it on for the rest
of the script with a comment claiming it's scoped when it isn't), and
keep the old "hash mismatch" string check as a sub-case in the
ACTUAL_HASH-empty branch, so a hash mismatch whose got: line fails to
parse (e.g. a future Nix output-format change) is diagnosed
differently from a build that failed for an unrelated reason.

Re-verified all four failure/success paths with a stub nix binary
(non-hash failure, hash-mismatch-with-unparseable-got-line,
step-5-verify failure, and the genuine happy path). go build/vet
clean, golangci-lint 0 issues.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VN2SgXAHW1eTB1izwWwmyr

* fix(scripts): update-nix-vendorhash preserves operator backups, restores on any handled failure

The script backed up default.nix to a fixed name in the repo root,
default.nix.backup, before editing it -- but that is also the
conventional name an operator gives their own manual backup. Running
the script unconditionally overwrote (then later deleted) any such
file. A failed step-5 verification build also left the candidate hash
in default.nix with no backup at all to restore from, since the
backup had already been deleted right after step 4 applied the real
hash.

Moved the backup into a private per-run scratch directory
(mktemp -d, cleaned on every exit via an EXIT trap) instead of a
fixed repo-root name, so it can never collide with an operator's own
default.nix.backup. Copy with cp -p so a restore brings back the
exact original bytes AND mode, not just content. Kept the backup
around through step 5 instead of deleting it right after step 4, and
added a restore on the step-5 verification-failure path, which
previously left the unverified candidate hash in place.

Also: the "no hash mismatch, already correct" exit-0 path previously
inferred correctness purely from the fake-hash probe build's
unexpected success, without ever building the real, restored file.
It now runs a second build against the restored file and only exits 0
if that succeeds too, surfacing a diagnostic log if it doesn't.

Fixes gastownhall/beads#7529.

Verified with a stub nix binary across five scenarios: a pre-existing
operator default.nix.backup (distinct content + mode 600) survives
untouched in every one; a non-hash build failure restores the
original (content + mode 640); the already-correct path now runs two
builds and only succeeds if both do; the core bug repro (hash
extracted, step-5 verify fails) now restores the original instead of
leaving the unverified candidate hash with no backup; the genuine
happy path still updates the hash correctly. No leftover scratch
directories in any case. go build unaffected (shell-only change).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VN2SgXAHW1eTB1izwWwmyr

* fix(scripts): update-nix-vendorhash restores the original on an interrupted run

A SIGINT/SIGTERM during the probe build (the long step) reaches this
script and its nix child as one process group; the child dies, this
script exits through the EXIT trap with the placeholder hash still in
default.nix. The plain `rm -rf "$SCRATCH_DIR"` trap deleted the only
backup at that point, leaving no way back except `git checkout
default.nix` -- which also discards any uncommitted operator edits.
Worse than every handled failure case this file already restores
from.

The placeholder is never a valid end state, so the EXIT trap now
checks for it and restores first, before dropping the scratch
directory. Every handled exit path has already restored or verified
default.nix by the time it runs, so this is a no-op there -- it only
fires on an interrupted run.

Found by review on PR #7504 (beads#7529's own follow-up): reproduced
and confirmed with a stub nix that signals its own parent process
group, matching a real Ctrl-C mid-build. Confirmed the bug first
(plain trap: placeholder left in place, backup gone, matching the
report exactly), then confirmed the fix (original hash and mode
restored, operator backup untouched, no leftover scratch dir). Also
re-ran the full existing scenario matrix (non-hash failure, hash
mismatch with step-5 verify failure, genuine happy path) to confirm no
regression.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VN2SgXAHW1eTB1izwWwmyr

* fix(scripts): restore default.nix if vendorhash verification is interrupted

The EXIT trap restored default.nix only while it still held the placeholder
hash. A SIGINT/SIGTERM during the step-5 verification build therefore left
the unverified candidate hash in place and deleted the only backup with the
scratch dir. Track VERIFIED instead: until a build has verified default.nix
as it stands, any exit restores the original. On handled paths this is a
no-op, since they have already restored or verified the file.

Write the build logs under ${TMPDIR:-/tmp} with per-run names. The
verification log had a fixed /tmp name shared by every run and every user.

Add the regression tests the #7498/#7499/#7529 fixes lacked:
- TestUpdateNixVendorHashReportsTheRealBuildResult runs the script with a
  stub nix over a non-hash build failure, an unparseable mismatch, a failed
  verification, a half-parsed got: hash, a real update, and a probe that
  accepts the placeholder (restored file builds, or not). Every failure
  exits 1 with default.nix restored byte for byte and mode for mode, the
  operator's own default.nix.backup untouched and the named logs kept.
  Against main's script it reproduces each false success.
- TestUpdateNixVendorHashInterruptRestoresOriginal signals the script's
  process group during the probe build and during verification.
- TestUpdateVendorHashWorkflowBuildsIndependently pins the workflow's
  unconditional `nix build .#default` between the script and the
  match-report and push steps.

The scenario matrix, operator-backup and file-mode fixture, and workflow
ordering check are adapted from BlueboxC's correction of this PR in their
fork (62e7718e), as described on #7498 and #7529.

Refs #7504, #7496, #7498, #7499, #7500, #7529

Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Julian Knutsen
Co-authored-by: BlueboxC <david@blueboxcomputers.es>
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
Co-authored-by: Julian Knutsen <julianknutsen@users.noreply.github.com>
Co-authored-by: BlueboxC <david@blueboxcomputers.es>
2026-10-14 22:18:15 +00:00

127 lines
4.1 KiB
Go

//go:build !windows
package scripts_test
import (
"bytes"
"errors"
"os"
"os/exec"
"path/filepath"
"slices"
"strconv"
"syscall"
"testing"
"time"
)
// TestUpdateNixVendorHashInterruptRestoresOriginal signals the script's whole
// process group mid-build, as a terminal Ctrl-C or a cancelled job does. Until
// a build has verified the file it leaves behind, an interrupted run must put
// the original default.nix back: during the probe build default.nix holds the
// placeholder hash, and during the verification build an unverified candidate;
// neither may outlive the run once its private backup is gone. SIGTERM rather
// than SIGINT because a process started with SIGINT ignored (any background
// job of a non-interactive shell) passes that on to the script, and the EXIT
// trap under test runs the same way for both.
func TestUpdateNixVendorHashInterruptRestoresOriginal(t *testing.T) {
tests := []struct {
name string
plan string
blockedBuild int
wantBuilds []string
}{
{
name: "during the probe build",
plan: "block",
blockedBuild: 1,
wantBuilds: []string{nixFixturePlaceholder},
},
{
name: "during the verification build",
plan: "mismatch block",
blockedBuild: 2,
wantBuilds: []string{nixFixturePlaceholder, nixFixtureUpdatedHash},
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
fx := newNixVendorHashFixture(t, test.plan)
cmd := fx.command()
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
cmd.WaitDelay = 10 * time.Second
var output bytes.Buffer
cmd.Stdout = &output
cmd.Stderr = &output
if err := cmd.Start(); err != nil {
t.Fatal(err)
}
group := -cmd.Process.Pid
done := make(chan error, 1)
go func() { done <- cmd.Wait() }()
// stop kills the group unless the script has already been reaped
// (its group id may be reused after that), then returns the output,
// which is only safe to read once Wait has returned.
reaped := false
stop := func() string {
if !reaped {
_ = syscall.Kill(group, syscall.SIGKILL)
<-done
reaped = true
}
return output.String()
}
t.Cleanup(func() { stop() })
marker := filepath.Join(fx.state, "blocked-"+strconv.Itoa(test.blockedBuild))
deadline := time.Now().Add(30 * time.Second)
for {
if _, err := os.Stat(marker); err == nil {
break
}
select {
case err := <-done:
reaped = true
t.Fatalf("script exited (%v) before nix build %d started\n%s", err, test.blockedBuild, stop())
default:
}
if time.Now().After(deadline) {
t.Fatalf("nix build %d never started\n%s", test.blockedBuild, stop())
}
time.Sleep(10 * time.Millisecond)
}
if err := syscall.Kill(group, syscall.SIGTERM); err != nil {
t.Fatalf("signal the script's process group: %v\n%s", err, stop())
}
var err error
select {
case err = <-done:
reaped = true
case <-time.After(30 * time.Second):
t.Fatalf("script still running 30s after SIGTERM\n%s", stop())
}
// bash runs its EXIT trap, then dies of the signal it caught (or,
// with a TERM trap of its own, exits 128+15).
var exitErr *exec.ExitError
if !errors.As(err, &exitErr) {
t.Fatalf("script exited %v after SIGTERM, want it to fail\n%s", err, output.String())
}
status, ok := exitErr.Sys().(syscall.WaitStatus)
killed := ok && status.Signaled() && status.Signal() == syscall.SIGTERM
if !killed && (!ok || !status.Exited() || status.ExitStatus() != 128+int(syscall.SIGTERM)) {
t.Errorf("script ended with %v after SIGTERM, want termination by SIGTERM\n%s", exitErr, output.String())
}
if got := fx.builds(t); !slices.Equal(got, test.wantBuilds) {
t.Errorf("nix built vendorHash %q, want %q\n%s", got, test.wantBuilds, output.String())
}
fx.assertCheckout(t, nixFixtureOriginalHash)
for _, name := range fx.tmpEntries(t) {
if info, err := os.Stat(filepath.Join(fx.tmp, name)); err == nil && info.IsDir() {
t.Errorf("interrupted run left its private directory %s behind", name)
}
}
})
}
}