package activator import ( "context" "errors" "fmt" "slices" "strings" "sync" "testing" "time" "github.com/carlosframework/platform/internal/registry" ) // execLog is a BeforeExec hook that records host@build, the backend's spawn // count when it was asked (so a test can tell the record came before the // spawn), and the build-state location the context carried. fail, when // set, says which builds it refuses. type execLog struct { mu sync.Mutex calls []string at []int locs []BuildStateLocation spawns func() int fail func(build string) bool } func (l *execLog) hook(ctx context.Context, host, build string) error { n := -1 if l.spawns != nil { n = l.spawns() } loc, _ := BuildStateLocationFrom(ctx) l.mu.Lock() defer l.mu.Unlock() l.calls = append(l.calls, host+"@"+build) l.at = append(l.at, n) l.locs = append(l.locs, loc) if l.fail != nil && l.fail(build) { return errors.New("bucket refused the build state") } return nil } func (l *execLog) seen() ([]string, []int, []BuildStateLocation) { l.mu.Lock() defer l.mu.Unlock() return append([]string(nil), l.calls...), append([]int(nil), l.at...), append([]BuildStateLocation(nil), l.locs...) } func failAll(string) bool { return true } // --- the hook itself --- // Ruling R-EXEC-NOVERSION: an identity outside the version store has no // build a build state could name. With the hook set it is refused; with no // hook (a box with no replica bucket) it runs as today. func TestAnUnrecordableBuildIsRefused(t *testing.T) { a := &Service{cfg: Config{Bucket: "b"}} if err := a.recordBuild(context.Background(), "one.example.com", ""); err != nil { t.Fatalf("a nil hook refused: %v", err) } var l execLog a.BeforeExec = l.hook err := a.recordBuild(context.Background(), "one.example.com", "") if !errors.Is(err, errBuildStateUnwritten) { t.Fatalf("err = %v, want errBuildStateUnwritten", err) } if calls, _, _ := l.seen(); len(calls) != 0 { t.Fatalf("the hook was asked to record no build: %v", calls) } } // The unclaimed lease's location rides to the hook, so the agent writes // beside this lease's lock.json; a location the caller already attached // (the claimed path, Task 5c) is kept. A hook error is wrapped so every // classifier reads it as a refusal. func TestTheHookIsToldWhereTheLeaseIs(t *testing.T) { a := &Service{cfg: Config{Bucket: "hib", Prefix: "inst"}} var l execLog a.BeforeExec = l.hook if err := a.recordBuild(context.Background(), "one.example.com", "v1"); err != nil { t.Fatal(err) } claimed := BuildStateLocation{Bucket: "data", Prefix: "instances/one.example.com/inc1"} if err := a.recordBuild(WithBuildStateLocation(context.Background(), claimed), "one.example.com", "v1"); err != nil { t.Fatal(err) } calls, _, locs := l.seen() if len(calls) != 2 || calls[0] != "one.example.com@v1" { t.Fatalf("calls = %v", calls) } if want := (BuildStateLocation{Bucket: "hib", Prefix: HibernatePrefix("inst", "one.example.com")}); locs[0] != want { t.Fatalf("location = %+v, want the hibernate lease's %+v", locs[0], want) } if locs[1] != claimed { t.Fatalf("location = %+v, want the caller's %+v kept", locs[1], claimed) } l.fail = failAll err := a.recordBuild(context.Background(), "one.example.com", "v1") if !errors.Is(err, errBuildStateUnwritten) || !strings.Contains(err.Error(), "bucket refused") { t.Fatalf("err = %v, want errBuildStateUnwritten carrying the cause", err) } } // A wake's own record (Task 5b) is pending until its first exec (amadan // #272): a call for that build writes nothing, the exec seam writes it // once, and another build is written at once. A record of another build // supersedes the pending one, which the exec seam then never writes. func TestARecordedBuildIsNotWrittenTwice(t *testing.T) { rt := registry.Route{Host: "one.example.com"} a := &Service{cfg: Config{Bucket: "b"}} var l execLog a.BeforeExec = l.hook ctx := wakeRecord(a, rt.Host, "v1") if err := a.recordBuild(ctx, rt.Host, "v1"); err != nil { t.Fatal(err) } if calls, _, _ := l.seen(); len(calls) != 0 { t.Fatalf("calls = %v before any exec, want none", calls) } for range 2 { if _, err := runPendingRecord(ctx); err != nil { t.Fatal(err) } } if err := a.recordBuild(ctx, rt.Host, "v2"); err != nil { t.Fatal(err) } if calls, _, _ := l.seen(); !slices.Equal(calls, []string{"one.example.com@v1", "one.example.com@v2"}) { t.Fatalf("calls = %v, want v1 once at the exec, then the fallback's v2", calls) } var s execLog a.BeforeExec = s.hook ctx = wakeRecord(a, rt.Host, "v1") if err := a.recordBuild(ctx, rt.Host, "v2"); err != nil { t.Fatal(err) } if _, err := runPendingRecord(ctx); err != nil { t.Fatal(err) } if calls, _, _ := s.seen(); !slices.Equal(calls, []string{"one.example.com@v2"}) { t.Fatalf("calls = %v, want only v2: the superseded v1 is never written", calls) } // A write that fails refuses every exec of the wake, and is not retried. f := execLog{fail: failAll} a.BeforeExec = f.hook ctx = wakeRecord(a, rt.Host, "v1") for range 2 { if _, err := runPendingRecord(ctx); !errors.Is(err, errBuildStateUnwritten) { t.Fatalf("err = %v, want errBuildStateUnwritten", err) } } if calls, _, _ := f.seen(); len(calls) != 1 { t.Fatalf("calls = %v, want one attempt", calls) } } // wakeRecord is the context settleWakeIdentity returns for a wake of host // that settled build: its record pending. func wakeRecord(a *Service, host, build string) context.Context { return withPendingRecord(context.Background(), build, func() error { return a.recordBuild(context.Background(), host, build) }, nil) } // Ruling R-WAKEWORDS: a member never sees the internal text. func TestMemberSeesFencedForAnUnwrittenBuildState(t *testing.T) { err := fmt.Errorf("start one.example.com: %w", fmt.Errorf("%w: s3: access denied", errBuildStateUnwritten)) if got, want := memberSafeWakeReason(err), memberSafeWakeReason(ErrFenced); got != want { t.Fatalf("member reads %q, want the fence's %q", got, want) } } // A refused record is never a failure of the build, whichever classifier // reads it. func TestAnUnwrittenBuildStateIsARefusal(t *testing.T) { err := fmt.Errorf("spawn: %w", fmt.Errorf("%w: s3: access denied", errBuildStateUnwritten)) if got := classifyStep(nil, err); got != stepStale { t.Fatalf("classifyStep = %v, want stepStale", got) } if got := verdictOf(err); got != gateNoOwnership { t.Fatalf("verdictOf = %v, want a refusal", got) } } // --- every chokepoint that execs a captured identity (anchors-exec ยง1) --- // #11: a hold swap's pinned wake records the attempt's build before its // exec; a refused record abandons the attempt with nothing exec'd. func TestBeforeExecRunsBeforeAHoldSwap(t *testing.T) { t.Parallel() f := newSwapFixture(t) l := &execLog{spawns: func() int { n, _, _ := f.b.calls(); return n }} f.a.BeforeExec = l.hook res := f.a.Swap(context.Background(), f.attempt(ModeHold), f.newest) if res.Outcome != SwapDone { t.Fatalf("Swap = %+v", res) } calls, at, locs := l.seen() if len(calls) != 1 || calls[0] != f.host+"@v2" || at[0] != 0 { t.Fatalf("records %v at spawn counts %v, want %s@v2 before the exec", calls, at, f.host) } if locs[0] != (BuildStateLocation{Bucket: "test-bucket", Prefix: HibernatePrefix("", f.host)}) { t.Fatalf("location = %+v", locs[0]) } if gens, _, _ := f.b.calls(); gens != 1 { t.Fatalf("StartStaged calls = %d, want 1", gens) } f = newSwapFixture(t) f.a.BeforeExec = (&execLog{fail: failAll}).hook res = f.a.Swap(context.Background(), f.attempt(ModeHold), f.newest) if res.Outcome != SwapAbandoned || !strings.Contains(res.Reason, errBuildStateUnwritten.Error()) { t.Fatalf("Swap = %+v, want abandoned for the unwritten build state", res) } if gens, _, _ := f.b.calls(); gens != 0 { t.Fatalf("StartStaged calls = %d: a build ran unrecorded", gens) } } // #12: an overlap successor records its build before its exec; a refused // record is SwapAbandoned, never SwapFailed (which the scheduler writes as // the build's failure), and the incumbent keeps serving. func TestBeforeExecRunsBeforeAnOverlapSuccessor(t *testing.T) { t.Parallel() f := newSwapFixture(t) l := &execLog{spawns: func() int { n, _, _ := f.b.calls(); return n }} f.a.BeforeExec = l.hook res := f.a.Swap(context.Background(), f.attempt(ModeOverlap), f.newest) if res.Outcome != SwapDone { t.Fatalf("Swap = %+v", res) } if calls, at, _ := l.seen(); len(calls) != 1 || calls[0] != f.host+"@v2" || at[0] != 0 { t.Fatalf("records %v at spawn counts %v, want %s@v2 before the exec", calls, at, f.host) } f = newSwapFixture(t) f.a.BeforeExec = (&execLog{fail: failAll}).hook res = f.a.Swap(context.Background(), f.attempt(ModeOverlap), f.newest) if res.Outcome != SwapAbandoned || !strings.Contains(res.Reason, errBuildStateUnwritten.Error()) { t.Fatalf("Swap = %+v, want abandoned (never failed) for the unwritten build state", res) } if gens, _, _ := f.b.calls(); gens != 0 { t.Fatalf("StartStaged calls = %d: a build ran unrecorded", gens) } if got := f.appSocket(t); got != f.incumbent.Socket { t.Fatalf("AppSocket = %q, want the incumbent's", got) } if _, raises, restores := f.b.calls(); raises != restores { t.Fatalf("raises %d restores %d: the parent limit was not restored", raises, restores) } } // #13: a planned boot records B before its exec; a refused record execs // nothing and records nothing against B. func TestBeforeExecRunsBeforeAPlannedBoot(t *testing.T) { t.Parallel() dir := t.TempDir() next := stagedID(t, dir, "v2") a, b, _ := planActivator(t, WakePlan{Boot: next, Mode: ModeOverlap}) l := &execLog{spawns: func() int { return len(b.started()) }} a.BeforeExec = l.hook done, err := a.beginRequest(context.Background(), testRoute("one.example.com")) if err != nil { t.Fatalf("the wake: %v", err) } done() if calls, at, _ := l.seen(); len(calls) != 1 || calls[0] != "one.example.com@v2" || at[0] != 0 { t.Fatalf("records %v at spawn counts %v, want one.example.com@v2 before the exec", calls, at) } dir = t.TempDir() good, next := stagedID(t, dir, "v1"), stagedID(t, dir, "v2") a, b, evs := planActivator(t, WakePlan{Boot: next, Mode: ModeOverlap, FirstWake: true, Fallback: &good}) a.BeforeExec = (&execLog{fail: failAll}).hook _, err = a.beginRequest(context.Background(), testRoute("one.example.com")) if !errors.Is(err, errBuildStateUnwritten) { t.Fatalf("err = %v, want errBuildStateUnwritten", err) } if gens := b.started(); len(gens) != 0 { t.Fatalf("spawned %+v: a build ran unrecorded", gens) } time.Sleep(50 * time.Millisecond) if k := evs.kinds(); len(k) != 0 { t.Fatalf("events %v: a build that never ran was recorded", k) } } // #15: the fallback is a different build touching the data, so it records // again before its own exec. A refused record starts no good build; B's own // failure (it did fail) stays its own, and nothing falls back. func TestBeforeExecRunsBeforeAPlannedFallback(t *testing.T) { t.Parallel() dir := t.TempDir() good, next := stagedID(t, dir, "v1"), stagedID(t, dir, "v2") a, b, evs := planActivator(t, WakePlan{Boot: next, Mode: ModeOverlap, FirstWake: true, Fallback: &good}) a.genHealth = func(_ context.Context, g Gen) error { if g.Build == "v2" { return errors.New("GET / answered 500") } return nil } l := &execLog{spawns: func() int { return len(b.started()) }} a.BeforeExec = l.hook done, err := a.beginRequest(context.Background(), testRoute("one.example.com")) if err != nil { t.Fatalf("the wake: %v", err) } done() calls, at, _ := l.seen() if len(calls) != 2 || calls[0] != "one.example.com@v2" || calls[1] != "one.example.com@v1" || at[0] != 0 || at[1] != 1 { t.Fatalf("records %v at spawn counts %v, want v2 before B's exec, then v1 before the fallback's", calls, at) } evs.wait(t, GenFellBack) a, b, evs = planActivator(t, WakePlan{Boot: next, Mode: ModeOverlap, FirstWake: true, Fallback: &good}) a.genHealth = func(context.Context, Gen) error { return errors.New("GET / answered 500") } a.BeforeExec = (&execLog{fail: func(build string) bool { return build == "v1" }}).hook // The wake's error is B's failure (spawnPlanned wraps it); the // fallback's refusal is its detail. if _, err := a.beginRequest(context.Background(), testRoute("one.example.com")); err == nil || !strings.Contains(err.Error(), errBuildStateUnwritten.Error()) { t.Fatalf("err = %v, want B's failure with the fallback's unwritten build state", err) } if gens := b.started(); len(gens) != 1 || gens[0].Build != "v2" { t.Fatalf("spawned %+v, want B alone", gens) } if ev := evs.wait(t, GenFailed); ev.Failed.Version != "v2" { t.Fatalf("failure event = %+v, want B's own", ev) } time.Sleep(50 * time.Millisecond) for _, k := range evs.kinds() { if k == GenFellBack { t.Fatalf("events %v: a fallback that never ran was reported", evs.kinds()) } } } // #5: a worker wake records the identity it is about to exec, after its // publication; a refused record execs nothing and fails the wake. func TestBeforeExecRunsBeforeAWorkerWake(t *testing.T) { t.Parallel() a, b, _, _, _ := stagedActivator(t) host := "bot.x.internal" l := &execLog{spawns: b.workerStarts} a.BeforeExec = l.hook if err := a.WakeWorker(alwaysOnWorkerRoute(host)); err != nil { t.Fatalf("WakeWorker: %v", err) } calls, at, locs := l.seen() if len(calls) != 1 || calls[0] != host+"@v1" || at[0] != 0 { t.Fatalf("records %v at spawn counts %v, want %s@v1 before the exec", calls, at, host) } if locs[0] != (BuildStateLocation{Bucket: "test-bucket", Prefix: HibernatePrefix("", host)}) { t.Fatalf("location = %+v, want the worker's own lease", locs[0]) } a, b, _, _, _ = stagedActivator(t) a.BeforeExec = (&execLog{fail: failAll}).hook if err := a.WakeWorker(alwaysOnWorkerRoute(host)); !errors.Is(err, errBuildStateUnwritten) { t.Fatalf("WakeWorker = %v, want errBuildStateUnwritten", err) } if n := b.workerStarts(); n != 0 { t.Fatalf("%d worker children: a build ran unrecorded", n) } } // #7: a crash restart records the captured build before it respawns it. A // refused record is a refusal: nothing exec'd, no "failed to respawn" // member error event, and the sweep asks again. func TestBeforeExecRunsBeforeAWorkerRecycle(t *testing.T) { t.Parallel() a, b, clk, _, _ := stagedActivator(t) sink := &lockedSink{} a.Logs = sink host := "bot.x.internal" l := &execLog{spawns: b.workerStarts} a.BeforeExec = l.hook if err := a.WakeWorker(alwaysOnWorkerRoute(host)); err != nil { t.Fatalf("WakeWorker: %v", err) } b.lastWorker().kill() a.sweepOnce() waitForRestart(t, a, b.fakeBackend, host, 2) calls, at, _ := l.seen() if len(calls) != 2 || calls[1] != host+"@v1" || at[1] != 1 { t.Fatalf("records %v at spawn counts %v, want the recycle's %s@v1 before its exec", calls, at, host) } l.mu.Lock() l.fail = failAll l.mu.Unlock() b.lastWorker().kill() clk.advance(sidecarRestartMax + time.Second) a.sweepOnce() waitForSpawnCalls(t, a, b, host, 3) if n := b.workerStarts(); n != 2 { t.Fatalf("%d worker children: a build ran unrecorded", n) } sink.mu.Lock() defer sink.mu.Unlock() for _, ev := range sink.events { if ev.level == "error" { t.Fatalf("member event %+v: a refused record read as a failed respawn", ev) } } } // #10: ReplaceWorker's attempt records its build before the exec; a refused // record is abandonment, never a failure of the build. func TestBeforeExecRunsBeforeReplaceWorker(t *testing.T) { shrinkFirstWake(t, 55*time.Second, 25*time.Second, 100*time.Millisecond) a, b, _, _, _ := stagedActivator(t) host := "bot.x.internal" l := &execLog{spawns: b.workerStarts} a.BeforeExec = l.hook if err := a.WakeWorker(alwaysOnWorkerRoute(host)); err != nil { t.Fatal(err) } res := a.ReplaceWorker(context.Background(), workerAttempt(CauseRelease, ModeOverlap, fakeIdentity("v2")), nil, one) if res.Outcome != SwapDone { t.Fatalf("ReplaceWorker = %+v", res) } if calls, at, _ := l.seen(); len(calls) != 2 || calls[1] != host+"@v2" || at[1] != 1 { t.Fatalf("records %v at spawn counts %v, want %s@v2 before the attempt's exec", calls, at, host) } a, b, _, _, _ = stagedActivator(t) l = &execLog{fail: func(build string) bool { return build == "v2" }} a.BeforeExec = l.hook if err := a.WakeWorker(alwaysOnWorkerRoute(host)); err != nil { t.Fatal(err) } res = a.ReplaceWorker(context.Background(), workerAttempt(CauseRelease, ModeOverlap, fakeIdentity("v2")), nil, one) if res.Outcome != SwapAbandoned || !strings.Contains(res.Reason, errBuildStateUnwritten.Error()) { t.Fatalf("ReplaceWorker = %+v, want abandoned: an unrecorded build never ran", res) } waitFor(t, "the respawns to finish", func() bool { return !a.entryRespawning(host) }) // Every child had a recorded build before it, and v2 never served. calls, _, _ := l.seen() recorded := 0 for _, c := range calls { if c != host+"@v2" { recorded++ } } if !slices.Contains(calls, host+"@v2") || b.workerStarts() != recorded { t.Fatalf("records %v, %d worker children: a child ran without its build recorded", calls, b.workerStarts()) } if got := a.entryServing(host); got.Version == "v2" { t.Fatalf("serving %+v: v2 ran unrecorded", got) } // Fix round 1: nothing of v2 ran, so the replaced v1 is restored at // once, with no sweep: the worker is not left down until the next // crash restart. if got, w := a.entryServing(host), b.lastWorker(); got != fakeIdentity("v1") || b.workerStarts() != 2 || w == nil || w.Exited() { t.Fatalf("serving %+v with %d children (last exited: %v); want v1 restored and running without a sweep", got, b.workerStarts(), w != nil && w.Exited()) } }