Files
Kelx/powerop_acquire_race_test.go
2026-11-30 16:32:37 +00:00

525 lines
22 KiB
Go

package main
// adpanel:backup-race residual-risk regression tests.
//
// acquireServerOpLockFailFast replaced the power ops' marker-check +
// blocking Lock() (whose gap let a long op slip in and turn the queued power
// op into a phantom action after its relay gave up) with bounded polling.
// These tests pin the three outcomes of that acquisition - acquire after a
// short holder releases, refuse on budget expiry behind a stuck holder,
// refuse immediately when a long op is (or becomes) the holder - plus
// handleKill's marker withdrawal on refusal, the serverOpConflictBody
// vocabulary, and the runtime seed's pull gating.
import (
"context"
"io"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"time"
)
// withShortAcquireBudget shortens powerOpAcquireWaitBudget for one test and
// restores it afterwards (the tests in this file are not parallel).
func withShortAcquireBudget(t *testing.T, d time.Duration) {
t.Helper()
prev := powerOpAcquireWaitBudget
powerOpAcquireWaitBudget = d
t.Cleanup(func() { powerOpAcquireWaitBudget = prev })
}
// TestPowerOpWaitsForShortHolderThenAcquires: a power op arriving while a
// short op holds the lock must poll, acquire as soon as it releases, and
// proceed normally - the bounded acquisition must not refuse legitimate
// short-op queueing.
func TestPowerOpWaitsForShortHolderThenAcquires(t *testing.T) {
a := newReinstallRaceTestAgent(t)
name := "alpha"
seedRaceServer(t, a, name)
opMu := a.getServerOpLock(name)
opMu.Lock()
go func() {
time.Sleep(200 * time.Millisecond)
opMu.Unlock()
}()
done := make(chan *httptest.ResponseRecorder, 1)
go func() {
rec := httptest.NewRecorder()
a.handleStop(rec, httptest.NewRequest(http.MethodPost, "/v1/servers/"+name+"/stop", nil), name)
done <- rec
}()
select {
case rec := <-done:
if rec.Code == http.StatusConflict {
t.Fatalf("stop behind a short holder must acquire and proceed, got 409: %s", rec.Body.String())
}
case <-time.After(10 * time.Second):
t.Fatal("stop never acquired after the short holder released")
}
}
// TestPowerOpTimesOutBehindStuckShortHolder: when the lock is held (by
// anything) past the acquisition budget with no long op registered, the
// power op must refuse with server_op_in_progress instead of queueing
// indefinitely - performServerStart maps it to errServerOpInProgress and
// handleStart surfaces the 409.
func TestPowerOpTimesOutBehindStuckShortHolder(t *testing.T) {
a := newReinstallRaceTestAgent(t)
name := "alpha"
seedRaceServer(t, a, name)
withShortAcquireBudget(t, 150*time.Millisecond)
opMu := a.getServerOpLock(name)
opMu.Lock()
t.Cleanup(opMu.Unlock)
if _, err := a.performServerStart(context.Background(), name, 0, nil); err == nil || err.Error() != errServerOpInProgress.Error() {
t.Fatalf("performServerStart must return errServerOpInProgress on budget expiry, got %v", err)
}
rec := httptest.NewRecorder()
a.handleStop(rec, httptest.NewRequest(http.MethodPost, "/v1/servers/"+name+"/stop", nil), name)
if rec.Code != http.StatusConflict {
t.Fatalf("expected 409 on budget expiry, got %d: %s", rec.Code, rec.Body.String())
}
body := decodeResponse(t, rec)
if body["code"] != "server_op_in_progress" || body["ok"] != false {
t.Fatalf("expected server_op_in_progress refusal, got: %v", body)
}
// The full start handler must surface the same 409 from the sentinel.
startRec := httptest.NewRecorder()
a.handleStart(startRec, httptest.NewRequest(http.MethodPost, "/v1/servers/"+name+"/start", nil), name)
if startRec.Code != http.StatusConflict {
t.Fatalf("handleStart expected 409 on budget expiry, got %d: %s", startRec.Code, startRec.Body.String())
}
if startBody := decodeResponse(t, startRec); startBody["code"] != "server_op_in_progress" {
t.Fatalf("handleStart expected server_op_in_progress, got: %v", startBody)
}
}
func TestStartReturnsReinstallConflictDuringDirectoryHandoff(t *testing.T) {
a := newReinstallRaceTestAgent(t)
name := "alpha"
opMu := a.getServerOpLock(name)
opMu.Lock()
defer opMu.Unlock()
a.beginLongOp(name, longOpReinstall)
defer a.endLongOp(name)
rec := httptest.NewRecorder()
a.handleStart(rec, httptest.NewRequest(http.MethodPost, "/v1/servers/"+name+"/start", nil), name)
if rec.Code != http.StatusConflict || decodeResponse(t, rec)["code"] != "reinstall_in_progress" {
t.Fatalf("expected reinstall conflict during directory handoff, got %d: %s", rec.Code, rec.Body.String())
}
}
func TestStartKeepsExistingContainerAndLogsOnRefusal(t *testing.T) {
for _, scenario := range []struct {
name string
transport reinstallDockerRemovalTransport
wantStatus int
wantError string
}{
{"running", reinstallDockerRemovalTransport{startedState: "running"}, http.StatusConflict, "server_already_running"},
{"paused", reinstallDockerRemovalTransport{startedState: "paused"}, http.StatusConflict, "server_already_running"},
{"unknown", reinstallDockerRemovalTransport{startedState: "running", failStartedInspection: func() bool { return true }}, http.StatusServiceUnavailable, "server_state_unconfirmed"},
} {
t.Run(scenario.name, func(t *testing.T) {
agent := newReinstallRaceTestAgent(t)
const serverName = "alpha"
seedRaceServer(t, agent, serverName)
dockerEngineHTTPClient = &http.Client{Transport: scenario.transport}
tail := agent.logs.getOrCreate(serverName)
tail.appendRecentBatch([]string{"fixture log entry"})
response := httptest.NewRecorder()
agent.handleStart(response, httptest.NewRequest(http.MethodPost, "/v1/servers/alpha/start", nil), serverName)
if body := decodeResponse(t, response); response.Code != scenario.wantStatus || body["error"] != scenario.wantError {
t.Fatalf("unexpected Start response: %d %v", response.Code, body)
}
if lines := strings.Join(tail.snapshotRecent(10), "\n"); lines != "fixture log entry" {
t.Fatalf("refused Start changed console history: %q", lines)
}
})
}
}
func TestConsoleCommandReturnsReinstallConflictDuringDirectoryHandoff(t *testing.T) {
agent := newReinstallRaceTestAgent(t)
const serverName = "alpha"
opMu := agent.getServerOpLock(serverName)
opMu.Lock()
defer opMu.Unlock()
agent.beginLongOp(serverName, longOpReinstall)
defer agent.endLongOp(serverName)
direct := httptest.NewRecorder()
agent.handleCommand(direct, httptest.NewRequest(http.MethodPost, "/v1/servers/alpha/command", strings.NewReader(`{"command":"list"}`)), serverName)
legacy := httptest.NewRecorder()
agent.handleServerCommandBody(legacy, httptest.NewRequest(http.MethodPost, "/v1/server/command", strings.NewReader(`{"name":"alpha","command":"list"}`)))
for _, response := range []*httptest.ResponseRecorder{direct, legacy} {
if response.Code != http.StatusConflict || decodeResponse(t, response)["code"] != "reinstall_in_progress" {
t.Fatalf("expected a console refusal during reinstall, got %d: %s", response.Code, response.Body.String())
}
}
}
func TestConsoleCommandAdmissionAllowsConcurrentReaders(t *testing.T) {
agent := newReinstallRaceTestAgent(t)
const serverName = "alpha"
opMu := agent.getServerOpLock(serverName)
opMu.RLock()
defer opMu.RUnlock()
if operation := agent.tryLockServerOp(serverName); operation != nil {
operation.Unlock()
t.Fatal("reinstall must not acquire the lock while a console command has it")
}
response := httptest.NewRecorder()
agent.handleCommand(response, httptest.NewRequest(http.MethodPost, "/v1/servers/alpha/command", strings.NewReader(`{"command":"list"}`)), serverName)
if response.Code != http.StatusNotFound {
t.Fatalf("a concurrent command should reach the directory lookup, got %d: %s", response.Code, response.Body.String())
}
}
func TestPowerOpWithdrawsWhenRequestEndsWhileWaiting(t *testing.T) {
a := newReinstallRaceTestAgent(t)
name := "alpha"
withShortAcquireBudget(t, 200*time.Millisecond)
opMu := a.getServerOpLock(name)
opMu.Lock()
defer opMu.Unlock()
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond)
defer cancel()
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPost, "/v1/servers/"+name+"/stop", nil).WithContext(ctx)
a.handleStop(rec, req, name)
if rec.Code != http.StatusRequestTimeout {
t.Fatalf("expected the caller's deadline to withdraw the stop, got %d: %s", rec.Code, rec.Body.String())
}
}
// TestPowerOpRefusesWhenLongOpHoldsWhileShortHolderKeptLock is the exact
// residual-risk window: a short op holds the lock AND a long op's marker is
// registered. The old marker-check would have passed (the check ran before
// the marker existed) and queued the power op behind the long op; the polled
// acquisition must refuse immediately with the long op's code.
func TestPowerOpRefusesWhenLongOpHoldsWhileShortHolderKeptLock(t *testing.T) {
a := newReinstallRaceTestAgent(t)
name := "alpha"
seedRaceServer(t, a, name)
opMu := a.getServerOpLock(name)
opMu.Lock()
t.Cleanup(opMu.Unlock)
a.beginLongOp(name, longOpBackup)
t.Cleanup(func() { a.endLongOp(name) })
started := time.Now()
rec := httptest.NewRecorder()
a.handleStop(rec, httptest.NewRequest(http.MethodPost, "/v1/servers/"+name+"/stop", nil), name)
if rec.Code != http.StatusConflict {
t.Fatalf("expected 409, got %d: %s", rec.Code, rec.Body.String())
}
if body := decodeResponse(t, rec); body["code"] != "backup_in_progress" {
t.Fatalf("expected backup_in_progress refusal, got: %v", body)
}
// The refusal must be immediate (first poll), not after the full budget.
if elapsed := time.Since(started); elapsed > 5*time.Second {
t.Fatalf("refusal behind a registered long op must be immediate, took %s", elapsed)
}
}
// TestKillWithdrawsKillPendingWhenRefused: handleKill arms killPending
// before acquiring (to abort in-flight starts while it waits); if the
// acquisition refuses, that marker MUST be withdrawn - a lingering
// killPending would abort later starts as a phantom side effect of a kill
// that never ran.
func TestKillWithdrawsKillPendingWhenRefused(t *testing.T) {
a := newReinstallRaceTestAgent(t)
name := "alpha"
seedRaceServer(t, a, name)
a.beginLongOp(name, longOpReinstall)
t.Cleanup(func() { a.endLongOp(name) })
rec := httptest.NewRecorder()
a.handleKill(rec, httptest.NewRequest(http.MethodPost, "/v1/servers/"+name+"/kill", nil), name)
if rec.Code != http.StatusConflict {
t.Fatalf("expected 409 during reinstall, got %d: %s", rec.Code, rec.Body.String())
}
if body := decodeResponse(t, rec); body["code"] != "reinstall_in_progress" {
t.Fatalf("expected reinstall_in_progress, got: %v", body)
}
a.stopMu.Lock()
_, pending := a.killPending[name]
a.stopMu.Unlock()
if pending {
t.Fatal("killPending must be withdrawn when the kill refuses without running")
}
}
func TestStartAndRuntimeChangesRefusePendingGracefulStop(t *testing.T) {
agent := newReinstallRaceTestAgent(t)
const serverName = "alpha"
serverDir := seedRaceServer(t, agent, serverName)
requestedAt := time.Now().Add(-10 * time.Second)
agent.stoppingNow[serverName] = requestedAt
for _, attempt := range []struct {
path string
body string
handler func(http.ResponseWriter, *http.Request, string)
}{
{"start", "{}", agent.handleStart},
{"restart", "{}", agent.handleRestart},
{"runtime", `{"template":"nodejs","runtime":{}}`, agent.handleRuntime},
} {
response := httptest.NewRecorder()
attempt.handler(response, httptest.NewRequest(http.MethodPost, "/v1/servers/alpha/"+attempt.path, strings.NewReader(attempt.body)), serverName)
if response.Code != http.StatusConflict || decodeResponse(t, response)["code"] != serverStopInProgress {
t.Fatalf("%s must not overtake graceful shutdown: %d %s", attempt.path, response.Code, response.Body.String())
}
}
response := httptest.NewRecorder()
agent.handleStop(response, httptest.NewRequest(http.MethodPost, "/v1/servers/alpha/stop", nil), serverName)
if response.Code != http.StatusOK || decodeResponse(t, response)["stopping"] != true || !agent.stoppingNow[serverName].Equal(requestedAt) {
t.Fatalf("a duplicate stop must not supersede the accepted stop: %d %s", response.Code, response.Body.String())
}
assertServerDirUntouched(t, agent, serverName, serverDir)
}
func TestStopWaitDoesNotReportDockerFailureAsSuccess(t *testing.T) {
agent := newReinstallRaceTestAgent(t)
const serverName = "alpha"
seedRaceServer(t, agent, serverName)
dockerEngineHTTPClient = &http.Client{Transport: reinstallDockerRemovalTransport{containerOwner: serverName}}
binDir := t.TempDir()
if err := os.WriteFile(filepath.Join(binDir, "docker"), []byte("#!/bin/sh\nif [ \"$1\" = stop ]; then exit 1; fi\n"), 0o755); err != nil {
t.Fatal(err)
}
t.Setenv("PATH", binDir+string(os.PathListSeparator)+os.Getenv("PATH"))
response := httptest.NewRecorder()
agent.handleStop(response, httptest.NewRequest(http.MethodPost, "/v1/servers/alpha/stop?wait=true", nil), serverName)
body := decodeResponse(t, response)
if response.Code != http.StatusServiceUnavailable || body["ok"] != false || body["stopped"] != nil {
t.Fatalf("an unconfirmed Docker stop must not report success: %d %v", response.Code, body)
}
if _, pending := agent.stoppingNow[serverName]; pending {
t.Fatal("a finished stop attempt must release the pending marker")
}
}
func TestDeferredStopOnlyStopsOriginalRun(t *testing.T) {
for _, scenario := range []struct {
name string
originalID string
originalStartedAt string
inspectionFails bool
newerStop bool
wantStop bool
stopFails bool
}{
{name: "original run", originalID: reinstallFixtureContainerID, wantStop: true},
{name: "Docker stop fails", originalID: reinstallFixtureContainerID, wantStop: true, stopFails: true},
{name: "replacement", originalID: strings.Repeat("a", 64)},
{name: "restarted run", originalID: reinstallFixtureContainerID, originalStartedAt: "2026-01-01T00:00:00Z"},
{name: "inspection unavailable", originalID: reinstallFixtureContainerID, inspectionFails: true},
{name: "newer stop", originalID: reinstallFixtureContainerID, newerStop: true},
} {
t.Run(scenario.name, func(t *testing.T) {
agent := newReinstallRaceTestAgent(t)
serverName := "alpha"
transport := reinstallDockerRemovalTransport{containerOwner: serverName}
if scenario.inspectionFails {
transport = reinstallDockerRemovalTransport{startedState: "running", failStartedInspection: func() bool { return true }}
}
dockerEngineHTTPClient = &http.Client{Transport: transport}
binDir := t.TempDir()
stopTarget := filepath.Join(binDir, "stop-target")
if err := os.WriteFile(filepath.Join(binDir, "docker"), []byte("#!/bin/sh\nif [ \"$1\" = stop ]; then printf '%s' \"$4\" > \"$TEST_STOP_TARGET\"; exit \"$TEST_STOP_STATUS\"; fi\n"), 0o755); err != nil {
t.Fatal(err)
}
t.Setenv("PATH", binDir+string(os.PathListSeparator)+os.Getenv("PATH"))
t.Setenv("TEST_STOP_TARGET", stopTarget)
if scenario.stopFails {
t.Setenv("TEST_STOP_STATUS", "1")
} else {
t.Setenv("TEST_STOP_STATUS", "0")
}
requestedAt := time.Now()
pendingAt := requestedAt
if scenario.newerStop {
pendingAt = pendingAt.Add(time.Second)
}
agent.stoppingNow[serverName] = pendingAt
agent.completeDeferredServerStop(serverName, dockerContainerInspectForStats{
ID: scenario.originalID, State: dockerContainerStateForStats{StartedAt: scenario.originalStartedAt},
}, requestedAt)
target, err := os.ReadFile(stopTarget)
if scenario.wantStop {
if err != nil || string(target) != scenario.originalID {
t.Fatalf("stop must target the original immutable container ID, got %q, %v", target, err)
}
} else if !os.IsNotExist(err) {
t.Fatalf("stale stop must not touch Docker, got %q, %v", target, err)
}
if scenario.stopFails {
logs := strings.Join(agent.logs.getOrCreate(serverName).snapshotRecent(20), "\n")
if !strings.Contains(logs, "shutdown could not be confirmed") || strings.Contains(logs, "completed successfully") {
t.Fatalf("failed stop must not announce shutdown success: %q", logs)
}
}
remaining, pending := agent.stoppingNow[serverName]
if pending != scenario.newerStop || (pending && !remaining.Equal(pendingAt)) {
t.Fatalf("deferred stop must only clear its own pending entry, got %v", agent.stoppingNow)
}
})
}
}
func TestPolicyStopIgnoresReplacementRun(t *testing.T) {
agent := newReinstallRaceTestAgent(t)
serverName := "alpha"
dockerEngineHTTPClient = &http.Client{Transport: reinstallDockerRemovalTransport{failRemoval: true}}
binDir := t.TempDir()
commandFile := filepath.Join(binDir, "mutation")
if err := os.WriteFile(filepath.Join(binDir, "docker"), []byte("#!/bin/sh\ncase \"$1\" in stop|update) printf '%s' \"$*\" > \"$TEST_DOCKER_MUTATION\";; esac\n"), 0o755); err != nil {
t.Fatal(err)
}
t.Setenv("PATH", binDir+string(os.PathListSeparator)+os.Getenv("PATH"))
t.Setenv("TEST_DOCKER_MUTATION", commandFile)
if err := agent.stopServerForPolicy(serverName, "network-abuse", "test limit", dockerContainerInspectForStats{ID: strings.Repeat("a", 64)}, func() bool { return true }); err != nil {
t.Fatal(err)
}
if command, err := os.ReadFile(commandFile); !os.IsNotExist(err) {
t.Fatalf("an old network sample must not change the replacement container: %q, %v", command, err)
}
}
func TestNetworkPolicyStopHonorsResourceUpdateDuringSampling(t *testing.T) {
agent := newReinstallRaceTestAgent(t)
serverName := "alpha"
serverDir := seedRaceServer(t, agent, serverName)
if err := agent.saveMeta(serverDir, map[string]any{"type": "runtime", "resources": map[string]any{"networkInboundLimitMb": 1}}); err != nil {
t.Fatal(err)
}
agent.resourceStats = newServerResourceStatsCache(time.Second, time.Second)
container := reinstallDockerRemovalTransport{
startedState: "running", startedLabels: map[string]string{dockerServerOwnershipLabel: serverName},
}
var edited bool
dockerEngineHTTPClient = &http.Client{Transport: reinstallDockerTransportFunc(func(request *http.Request) (*http.Response, error) {
if request.Method != http.MethodGet {
t.Errorf("stale network limit must not mutate Docker: %s %s", request.Method, request.URL.Path)
}
if strings.HasSuffix(request.URL.Path, "/stats") {
reply := httptest.NewRecorder()
patch := httptest.NewRequest(http.MethodPatch, "/v1/servers/alpha/resources", strings.NewReader(`{"resources":{"networkInboundLimitMb":0}}`))
agent.handleUpdateResources(reply, patch, serverName)
if reply.Code != http.StatusOK {
t.Errorf("clear network limit: got %d: %s", reply.Code, reply.Body)
}
edited = true
return &http.Response{StatusCode: http.StatusOK, Body: io.NopCloser(strings.NewReader(`{"networks":{"eth0":{"rx_bytes":2097152}}}`))}, nil
}
return container.RoundTrip(request)
})}
newNetworkAbuseMonitor(agent, time.Second, false).checkServer(serverName)
if !edited {
t.Fatal("the fixture did not sample the running container")
}
entry := agent.resourceStats.get(serverName)
if entry.networkWindowRx != 2*1024*1024 {
t.Fatalf("the fixture did not sample over the old limit: %d", entry.networkWindowRx)
}
}
func TestForceRemovalRetryTargetsOriginalContainer(t *testing.T) {
agent := newReinstallRaceTestAgent(t)
serverName := "alpha"
var targets []string
dockerEngineHTTPClient = &http.Client{Transport: reinstallDockerRemovalTransport{
containerOwner: serverName,
onRemovalTarget: func(target string) {
targets = append(targets, target)
},
}}
originalID := strings.Repeat("a", 64)
agent.retryRemoveServerContainer(serverName, originalID)
if len(targets) != 1 || targets[0] != originalID {
t.Fatalf("removal retry must scope Docker removal to the original ID, got %v", targets)
}
if err := agent.removeServerContainerWithRetry(context.Background(), serverName); err != nil {
t.Fatal(err)
}
if len(targets) != 2 || targets[1] != reinstallFixtureContainerID {
t.Fatalf("a new removal must resolve its own immutable ID, got %v", targets)
}
}
// TestServerOpConflictBodyContract pins the shared refusal vocabulary: every
// known code yields ok:false with its own message and the same code back, and
// unknown codes degrade to the generic short-holder body.
func TestServerOpConflictBodyContract(t *testing.T) {
for _, code := range []string{
"backup_in_progress",
"reinstall_in_progress",
"runtime_seed_in_progress",
"server_op_in_progress",
} {
body := serverOpConflictBody(code)
if body["ok"] != false || body["code"] != code {
t.Fatalf("code %q: expected ok:false with the code echoed, got %v", code, body)
}
msg, _ := body["error"].(string)
detail, _ := body["detail"].(string)
if msg == "" || detail == "" {
t.Fatalf("code %q: message and detail must be populated, got %v", code, body)
}
if !strings.Contains(msg, "in progress") {
t.Fatalf("code %q: unexpected message %q", code, msg)
}
}
unknown := serverOpConflictBody("no_such_code")
if unknown["code"] != "server_op_in_progress" || unknown["ok"] != false {
t.Fatalf("unknown code must degrade to the generic body, got %v", unknown)
}
}
// TestRuntimeSeedNeedsPull pins the pull gating: routine re-seeds of the
// identical runtime skip the pre-warm pull; first seeds, missing/legacy meta
// and image/tag changes still pull.
func TestRuntimeSeedNeedsPull(t *testing.T) {
cases := []struct {
label string
meta map[string]any
img string
tag string
want bool
}{
{"nil meta", nil, "node", "20-alpine", true},
{"no runtime key", map[string]any{"type": "nodejs"}, "node", "20-alpine", true},
{"runtime without image", map[string]any{"runtime": map[string]any{"tag": "20-alpine"}}, "node", "20-alpine", true},
{"runtime without tag", map[string]any{"runtime": map[string]any{"image": "node"}}, "node", "20-alpine", true},
{"nil-typed image", map[string]any{"runtime": map[string]any{"image": "<nil>", "tag": "20-alpine"}}, "node", "20-alpine", true},
{"identical image+tag", map[string]any{"runtime": map[string]any{"image": "node", "tag": "20-alpine"}}, "node", "20-alpine", false},
{"same image different tag", map[string]any{"runtime": map[string]any{"image": "node", "tag": "20-alpine"}}, "node", "22-alpine", true},
{"different image", map[string]any{"runtime": map[string]any{"image": "node", "tag": "20-alpine"}}, "python", "3.12-slim", true},
}
for _, c := range cases {
if got := runtimeSeedNeedsPull(c.meta, c.img, c.tag); got != c.want {
t.Fatalf("%s: runtimeSeedNeedsPull(%v, %q, %q) = %v, want %v", c.label, c.meta, c.img, c.tag, got, c.want)
}
}
}