fix(block): preserve mini executable and cleanup proof

This commit is contained in:
pingqiu committed 2026-12-05 17:17:31 -08:00
1 parent 97d582db43
commit fe313eac98
6 files changed
+168 -14

No files matched your search

@@ -115,6 +115,7 @@ func TestMiniStartsWithoutRootAndNamesItsBinaries(t *testing.T) {
defer cancel2()
p2 := startOwnedMini(t, ctx2, cli, "mini", "--dir", dir2, "--bin", broken, "--weed", weed, "--port-shift", fmt.Sprint(miniPortShift(t)))
err = p2.join(t, 3*time.Minute+miniShutdownGrace+10*time.Second)
p2.assertNaturalExit(t)
b2 := p2.output.String()
t.Logf("failed start:\n%s", b2)
if err == nil || !strings.Contains(b2, "start again on it with") || !strings.Contains(b2, miniHintWord(cli)+" mini --dir "+miniHintWord(dir2)+" --reuse") {
@@ -90,10 +90,12 @@ type ownedMini struct {
leaderFD int
leaderKey string
dispatches atomic.Int64
watchdog atomic.Bool
// Only the isolated fail-stop controls replace the census or its window.
groupExists func() bool
census func() []int
censusWait time.Duration
groupExists func() bool
census func() []int
censusWait time.Duration
captureLeader func(int) (miniProcInfo, error)
}
const miniShutdownGrace = 35 * time.Second // three 10-second child stops plus margin
@@ -118,7 +120,7 @@ func startOwnedMini(t *testing.T, ctx context.Context, bin string, args ...strin
p.cmd.Stdout, p.cmd.Stderr = &p.output, &p.output
// os/exec must not kill only the leader after a short WaitDelay. Our
// watchdog grants the full product shutdown window, then owns group cleanup.
p.cmd.Cancel = func() error { go p.stop(t); return nil }
p.cmd.Cancel = func() error { p.watchdog.Store(true); go p.stop(t); return nil }
p.mu.Lock() // a context cancellation cannot observe the unopened pidfd
if err := p.cmd.Start(); err != nil {
p.mu.Unlock()
@@ -193,6 +195,12 @@ func (p *ownedMini) join(t *testing.T, bound time.Duration) error {
return nil
}
}
func (p *ownedMini) assertNaturalExit(t *testing.T) {
t.Helper()
if p.watchdog.Load() {
t.Fatal("watchdog intervened; failed-start cleanup was not completed by mini")
}
}
func (p *ownedMini) stop(t *testing.T) {
p.stopOnce.Do(func() {
if p.isSettled() {
@@ -246,7 +254,17 @@ func (p *ownedMini) stopGroup(t *testing.T) {
}()
deadline := time.Now().Add(time.Second)
for {
leader, err := miniProc(pgid)
select {
case <-p.done:
p.assertStopped(t)
return
default:
}
readLeader := miniProc
if p.captureLeader != nil {
readLeader = p.captureLeader
}
leader, err := readLeader(pgid)
if err != nil || leader.key != p.leaderKey || (leader.state != "T" && leader.state != "t") || unix.PidfdSendSignal(leaderFD, 0, nil, 0) != nil {
if time.Now().After(deadline) {
miniFailStop(t, "leader incarnation not held during member capture")
@@ -444,7 +462,7 @@ func TestMiniSettledCleanupDoesNotSignal(t *testing.T) {
}
func TestMiniCleanupFailStopAndSettlement(t *testing.T) {
for _, mode := range []string{"join", "residue", "missed-member", "settled"} {
for _, mode := range []string{"join", "residue", "missed-member", "settled", "capture-settled", "capture-residue", "natural", "watchdog"} {
t.Run(mode, func(t *testing.T) {
marker := filepath.Join(t.TempDir(), "cleanup-ran")
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
@@ -459,10 +477,15 @@ func TestMiniCleanupFailStopAndSettlement(t *testing.T) {
err = p.join(t, 3*time.Second)
p.assertStopped(t)
_, statErr := os.Stat(marker)
if mode == "settled" {
if mode == "settled" || mode == "capture-settled" || mode == "natural" {
if err != nil || statErr != nil {
t.Fatalf("positive cleanup twin: err=%v marker=%v", err, statErr)
}
} else if mode == "watchdog" {
var exit *exec.ExitError
if !errors.As(err, &exit) || exit.ExitCode() != 1 || !strings.Contains(p.output.String(), "watchdog intervened") || statErr != nil {
t.Fatalf("watchdog cannot prove natural cleanup: err=%v marker=%v output=%s", err, statErr, p.output.String())
}
} else {
var exit *exec.ExitError
if !errors.As(err, &exit) || exit.ExitCode() != miniFailStopExit || !errors.Is(statErr, os.ErrNotExist) {
@@ -499,6 +522,35 @@ func TestMiniCleanupFailStopHelper(t *testing.T) {
close(p.done)
p.census = func() []int { return nil }
p.assertStopped(t)
case "capture-settled", "capture-residue":
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
p := startOwnedMini(t, ctx, "/bin/sleep", "60")
p.censusWait = 10 * time.Millisecond
if mode == "capture-residue" {
p.census = func() []int { return []int{1234} }
p.groupExists = func() bool { return true }
}
p.captureLeader = func(int) (miniProcInfo, error) {
_ = p.signalLeader(unix.SIGKILL)
_ = p.join(t, time.Second)
return miniProcInfo{}, os.ErrNotExist
}
p.stopGroup(t)
case "natural", "watchdog":
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
bin, args := "/bin/false", []string{}
if mode == "watchdog" {
bin, args = "/bin/sleep", []string{"60"}
}
p := startOwnedMini(t, ctx, bin, args...)
if mode == "watchdog" {
cancel()
}
_ = p.join(t, time.Second)
p.assertStopped(t)
p.assertNaturalExit(t)
default:
t.Fatal("invalid control")
}
+19 -2
View File
@@ -101,6 +101,23 @@ type miniRecord struct {
const miniRecordFile = "mini.json"
// Make an executable path absolute without collapsing symlink/.. components.
func miniExecutablePath(path string) (string, error) {
if filepath.IsAbs(path) {
return path, nil
}
volume := filepath.VolumeName(path)
base, err := filepath.Abs(volume + ".")
if err != nil {
return "", err
}
relative := strings.TrimPrefix(path, volume)
if len(relative) > 0 && os.IsPathSeparator(relative[0]) {
return filepath.VolumeName(base) + relative, nil
}
return base + string(os.PathSeparator) + relative, nil
}
func writeMiniRecord(dir string, r miniRecord) error {
b, err := json.MarshalIndent(r, "", " ")
if err != nil {
@@ -122,7 +139,7 @@ func reuseMiniRecord(c *miniConfig, weedFound string) (string, error) {
return "", fmt.Errorf("--reuse: %s/%s: %w", c.Dir, miniRecordFile, err)
}
if r.Weed != "" {
abs, err := filepath.Abs(r.Weed)
abs, err := miniExecutablePath(r.Weed)
if err != nil {
return "", fmt.Errorf("--reuse: resolve weed path: %w", err)
}
@@ -465,7 +482,7 @@ func mini(ctx context.Context, cfg miniConfig, stdout, stderr io.Writer) (int, e
return ops.VolumeStatusExitInvalid, fmt.Errorf("--weed %s not found", weed)
}
if weed != "" {
abs, err := filepath.Abs(weed)
abs, err := miniExecutablePath(weed)
if err != nil {
return ops.VolumeStatusExitInvalid, fmt.Errorf("resolve weed path: %w", err)
}
+7 -5
View File
@@ -609,9 +609,6 @@ func TestMiniRelativeWeedIsRecordedAndPrintedAbsolutely(t *testing.T) {
if code == 0 || err == nil {
t.Fatalf("fixture must reach the dying weed: code=%d err=%v", code, err)
}
if !strings.Contains(out.String(), "+ "+abs+" ") {
t.Errorf("relative weed command: %s", out.String())
}
b, err := os.ReadFile(filepath.Join(c.Dir, miniRecordFile))
if err != nil {
t.Fatal(err)
@@ -620,8 +617,13 @@ func TestMiniRelativeWeedIsRecordedAndPrintedAbsolutely(t *testing.T) {
if err := json.Unmarshal(b, &record); err != nil {
t.Fatal(err)
}
if record.Weed != abs {
t.Errorf("record weed=%q, want %q", record.Weed, abs)
selected, selectedErr := os.Stat(abs)
recorded, recordedErr := os.Stat(record.Weed)
if selectedErr != nil || recordedErr != nil || !filepath.IsAbs(record.Weed) || !os.SameFile(selected, recorded) {
t.Errorf("record weed=%q changed selected executable %q", record.Weed, abs)
}
if !strings.Contains(out.String(), "+ "+record.Weed+" ") {
t.Errorf("relative weed command: %s", out.String())
}
}
@@ -0,0 +1,81 @@
package main
import (
"context"
"encoding/json"
"io"
"os"
"path/filepath"
"runtime"
"strings"
"testing"
"time"
)
func TestMiniWeedSymlinkParentKeepsSelectedExecutable(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("Unix symlink and child-process fixture")
}
t.Setenv("SWB_MINI_FAKE_CHILD", "die-weed")
bin := fakeBin(t)
root := t.TempDir()
for _, dir := range []string{"tools", "releases/v2"} {
if err := os.MkdirAll(filepath.Join(root, dir), 0o755); err != nil {
t.Fatal(err)
}
}
selected := filepath.Join(root, "releases", "weed")
if err := os.Symlink(filepath.Join(bin, "weed"), selected); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(root, "tools", "weed"), []byte("wrong executable"), 0o755); err != nil {
t.Fatal(err)
}
if err := os.Symlink(filepath.Join(root, "releases", "v2"), filepath.Join(root, "tools", "current")); err != nil {
t.Fatal(err)
}
t.Chdir(root)
rel := "tools/current/../weed"
want, err := os.Stat(selected)
if err != nil {
t.Fatal(err)
}
check := func(t *testing.T, path string) {
t.Helper()
got, err := os.Stat(path)
if err != nil || !filepath.IsAbs(path) || !os.SameFile(want, got) {
t.Fatalf("selected executable changed: path=%q stat=%v", path, err)
}
}
t.Run("fresh", func(t *testing.T) {
c := miniConfig{Dir: filepath.Join(t.TempDir(), "run"), Bin: bin, Weed: rel, NQN: "n", SizeBytes: 1 << 20, Ports: freePorts(t)}
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
out := &syncBuf{}
_, _ = mini(ctx, c, out, io.Discard)
data, err := os.ReadFile(filepath.Join(c.Dir, miniRecordFile))
if err != nil {
t.Fatalf("did not reach record publication: %v; %s", err, out.String())
}
var record miniRecord
if err := json.Unmarshal(data, &record); err != nil {
t.Fatal(err)
}
check(t, record.Weed)
if !strings.Contains(out.String(), "+ "+record.Weed+" ") {
t.Fatalf("selected executable was not launched: %s", out.String())
}
})
t.Run("legacy", func(t *testing.T) {
dir := t.TempDir()
if err := writeMiniRecord(dir, miniRecord{Weed: rel, Bin: bin, SizeBytes: 1 << 20, NQN: "n"}); err != nil {
t.Fatal(err)
}
c := miniConfig{Dir: dir}
weed, err := reuseMiniRecord(&c, "")
if err != nil {
t.Fatal(err)
}
check(t, weed)
})
}
+1
View File
@@ -1272,6 +1272,7 @@ Notes:
| `INV-CLI-DELETE-RETRY-001` | Only the final lease barrier after a committed volume-delete reservation permits retryable true/exit 75 at its horizon. A live-holder Reserve refusal requires stopping the volume first (not_admitted, non-retryable, exit 1). No lease guard is bypassed. | M9 delete admission result projection | `cmd/sw-block/chunk_volume_delete.go` `authorityErr`; `cmd/sw-block/chunk.go` `chunkResult` | `TestVolumeDeleteAdmissionRetryAnswer`; `TestOpsChunkVolumeDeleteRefusalSaysNothingWasPersisted` | MoveAdmission.DelRead; MoveAdmission.DelMark (unchanged guards) | STUB |
| `INV-SNAPSHOT-REPLAY-FLAG-001` | A successful same-ID snapshot admission reports replayed true without changing HEAD or its retained outcome. First creation reports false; the flag decorates only the response. | M9 snapshot outcome projection | `core/host/volume/snapshot_operation.go`, `chunk_control.go`; `cmd/sw-block/snapshot_operation.go` | `TestSnapshotReplayFlagDoesNotRewriteOutcome`, `TestSnapshotCLIUsesReplayedAdmissionAnswer` | SnapOps.Poll; SnapOps.Start (no transition change) | STUB |
| `INV-CLI-UNSENT-REQUEST-001` | An observed operation's initial typed dial failure sends no admission and is remote_unavailable (75) through the shared classifier. A lost answer after send, or a dial failure while polling an admitted handle, retains outcome_unknown. | CLI pre-admission error projection; no server transition | `cmd/sw-block/cut_progress_poll.go` `chunkObserveHandle`; `chunkTransportFailure`, `chunkFail` | `TestPlainDetachRefusedDialIsRemoteUnavailable`, `TestPlainDetachLostAnswerAfterSendStaysUnknown`, `TestPlainDetachPollDialFailureKeepsAdmittedOutcomeUnknown`, `TestOpsChunk_ErrorsAreJSONOnStdout` | CutTime Poll/CliGiveUp boundary; pre-admission transport proof | ACTIVE |
| `INV-CLI-MINI-EXECUTABLE-001` | Mini records and launches the executable selected by --weed without changing symlink/.. resolution; fresh and legacy runs use an absolute path. | TrialLauncher path wiring, no protocol transition | `cmd/sw-block/mini.go` `miniExecutablePath`, `mini`, `reuseMiniRecord` | `TestMiniWeedSymlinkParentKeepsSelectedExecutable`, `TestMiniRelativeWeedIsRecordedAndPrintedAbsolutely` (`cmd/sw-block`); `TestMiniCleanupFailStopAndSettlement` (`cmd/blockvolume`: failed-start proof rejects watchdog intervention; settled capture completes and live residue refuses cleanup) | NONE (path selection and test ownership only; fresh Linux qualification pending) | STUB |
| `INV-CLI-CATALOG-ERROR-001` | The chunk CLI reports filer/master transport failures as retryable remote_unavailable (exit 75), including census, dial, resolve and read failures; configuration refusals stay distinct. An absent v1.1 delete reports snapshot_not_found; its not_found receipt stays unchanged. | M9 client error projection; M4 census refusal, no transition change | `cmd/sw-block/chunk_transport.go` `chunkTransportFailure`; `cmd/sw-block/chunk.go` `chunkResult`; `cmd/sw-block/catalog_snapshot_operation.go` `catalogSnapshotDeleteRefusal`; `core/frontend/chunkstore/single_filer.go` `CheckSingleFiler`; `core/frontend/chunkstore/layout/delete.go` `RunMarkDeleting` | `TestOpsChunkTransportFailureMatrix`, `TestOpsChunkVerifyUnreachableCensusPreservesTransport`, `TestCheckSingleFilerKeepsTransportCause`, `TestSingleFilerConfigurationErrorDeadlineBetweenReads`, `TestCheckSingleFilerSlowDialOrdering`, `TestDialBCatalogKeepsCustomCallerDeadline`, `TestMasterCensusKeepsCustomCallerDeadline`, `TestCheckSingleFilerValidatesAllMasterAddressesBeforeCensus`; `TestOpsChunkCatalogUnavailableIsTyped`, `TestCatalogTransportClassificationKeepsDefiniteAnswers`, `TestSnapshotDeleteAbsentCLIUsesContractCodeAndKeepsReceipt` | SnapOps.Poll | STUB |
| `INV-CLI-CHUNK-LOOP-001` | Above the per-request bound, sw-block ops chunk snapshot\|detach repeats the SAME request (same name and request id) only after a retryable or outcome_unknown answer. Manual cut and plain detach use the separate one-POST/read-only-poll contract. | client (no state machine): the CLI side of M5 requests | `cmd/sw-block/chunk_loop.go` `chunkPostLoop`; `cmd/sw-block/chunk.go` `chunkPostUntil` | `TestChunkSnapshotRepeatsTimedOutRequestsWithTheSameBody`, `TestChunkSnapshotLoopReusesTheGeneratedRequestID`, `TestChunkLoopRepeatsAnOutcomeUnknownNotMarkedRetryable` (`cmd/sw-block`) | — | ACTIVE |
| `INV-CLI-CHUNK-LOOP-002` | Above the per-request bound, sw-block ops chunk snapshot\|detach stops at the first definite answer (success or non-retryable refusal). | client (no state machine): the CLI side of M5 cut requests | `cmd/sw-block/chunk_loop.go` `chunkPostLoop` | `TestChunkLoopStopsOnANonRetryableRefusal`, `TestChunkDetachOutcomeUnknownSettles` (`cmd/sw-block`) | — | ACTIVE |