carlos / platform Public

Managed fleets 1b task 4, ruling: the marker is written when the copy is established

Controller ruling, correcting "marker only after the start succeeded":
the assignment marker records that the local copy belongs to the
current assignment, so it is written right after a successful restore
or seed placement, and when startAllowed permits an empty start, before
the spawn; a kept matching copy is not rewritten. A spawn that fails
after an empty start now leaves a copy the next wake keeps, instead of
one it sets aside and refuses over. A failed restore still establishes
nothing. A marker that cannot be written fails the wake before anything
runs. The post-start hook in doWake and the SplitBackend forwarding go.

TestFailedFirstStartKeepsItsCopy covers the empty start, a restored
copy and a labelled seed placement; the guard test now also requires
the fresh-boot paths to establish the marker.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 1c1f7c23fca99a68e0fba52d5079e6fd7297e90b parent 27b3518
5 files changed, +127 −97
  • internal/activator/activator.go +0 −13
  • internal/activator/backend_exec.go +6 −0
  • internal/activator/seedplace.go +4 −0
  • internal/activator/startrule.go +20 −34
  • internal/activator/startrule_test.go +97 −50
diff --git a/internal/activator/activator.go b/internal/activator/activator.go
index 88f748408..4812abc73 100644
--- a/internal/activator/activator.go
+++ b/internal/activator/activator.go
@@ -2960,19 +2960,6 @@ func (a *Service) doWake(ctx context.Context, e *actEntry) (*wokenInstance, erro
}
w.steps.mark(a.now(), "settle")
}
- // 4c. The start rule's marker (startrule.go): the restore passed
- // startAllowed and the start succeeded, so a labelled row's local
- // copy is now kept under its current assignment. Written only here; a
- // failed write only logs, and the next wake sets the copy aside and
- // restores (nothing is lost by a missing marker).
- if rt.Assigned != "" {
- if n, ok := a.backend.(assignmentNoter); ok {
- if err := n.NoteAssignment(ctx, rt); err != nil {
- log.Printf("activator: ERROR %s: assignment marker not written (%v); the next wake sets this copy aside", host, err)
- }
- }
- }
-
if ctx.Err() != nil || !a.wakeAllowed(host) {
a.cleanupFailedWake(ctx, e, rt, w, lease)
return w, ErrFenced
diff --git a/internal/activator/backend_exec.go b/internal/activator/backend_exec.go
index 6b773d34b..759041a5f 100644
--- a/internal/activator/backend_exec.go
+++ b/internal/activator/backend_exec.go
@@ -976,6 +976,9 @@ func (b *ExecBackend) restorePlain(ctx context.Context, rt registry.Route) (bool
if err := b.startAllowed(rt, false, true); err != nil {
return false, err
}
+ if err := b.establishAssignment(rt, dbPath); err != nil {
+ return false, err
+ }
} else {
// Never replicated: a brand-new instance boots fresh and creates its
// own DB — the register-only create path (provisioning as a metadata
@@ -988,6 +991,9 @@ func (b *ExecBackend) restorePlain(ctx context.Context, rt registry.Route) (bool
log.Printf("activator: no replica for %s in s3://%s/%s — NOT booting fresh: %v", host, b.Cfg.Bucket, b.Cfg.hibernatePrefix(host), err)
return false, err
}
+ if err := b.establishAssignment(rt, dbPath); err != nil {
+ return false, err
+ }
log.Printf("activator: no replica for %s in s3://%s/%s — booting fresh", host, b.Cfg.Bucket, b.Cfg.hibernatePrefix(host))
}
return !restored, nil
diff --git a/internal/activator/seedplace.go b/internal/activator/seedplace.go
index bb15bb155..679efa5df 100644
--- a/internal/activator/seedplace.go
+++ b/internal/activator/seedplace.go
@@ -233,6 +233,10 @@ func (b *ExecBackend) seededRestore(ctx context.Context, rt registry.Route, src
if err := b.placeSeed(ctx, host, src, dir, base); err != nil {
return fail(err)
}
+ // The placed snapshot is this assignment's copy now (startrule.go).
+ if err := b.establishAssignment(rt, paths.dbPath); err != nil {
+ return fail(err)
+ }
log.Printf("activator: %s: placed seed %s (%d bytes)", host, src.ID, src.Bytes)
return false, nil
}
diff --git a/internal/activator/startrule.go b/internal/activator/startrule.go
index 25bb56b5b..55cb60e2d 100644
--- a/internal/activator/startrule.go
+++ b/internal/activator/startrule.go
@@ -27,7 +27,6 @@ package activator
// host restores by the HA rules (hawake.go), unchanged.
import (
- "context"
"errors"
"fmt"
"log"
@@ -297,44 +296,31 @@ func (b *ExecBackend) startAllowed(rt registry.Route, haveLocal, restored bool)
return nil
}
-// assignmentNoter is the optional Backend half that records, after a
-// start, the assignment a labelled row's local copy is now kept under.
-type assignmentNoter interface {
- NoteAssignment(ctx context.Context, rt registry.Route) error
-}
-
-// NoteAssignment writes rt.Assigned to the marker beside the database,
-// through a temp file in the same directory, fsync and rename. doWake calls
-// it only after Restore (and so startAllowed) passed and the start
-// succeeded. An unlabelled row, or an HA host (the HA rules, unchanged),
-// writes nothing.
-func (b *ExecBackend) NoteAssignment(_ context.Context, rt registry.Route) error {
+// establishAssignment writes rt.Assigned to the marker beside dbPath,
+// through a temp file in the same directory, fsync and rename, at the
+// moment the local copy is established under the assignment (controller
+// ruling, correcting "after the start"): right after a successful restore
+// or seed placement, and when startAllowed permits an empty start, before
+// the spawn. A kept matching copy needs no rewrite. So a spawn that fails
+// after an empty start leaves a copy the next wake keeps, not one it sets
+// aside and then refuses over. A failed restore establishes nothing. The
+// instance directory is created first (0700, as the seed path and the
+// restore create it) for an empty start, which has no database yet. A
+// write that fails fails the wake, before anything runs. An unlabelled row
+// writes nothing; HA hosts never reach it (restoreHA).
+func (b *ExecBackend) establishAssignment(rt registry.Route, dbPath string) error {
if rt.Assigned == "" {
return nil
}
- if _, ha := b.haAcquired(rt.Host); ha {
- return nil
- }
- dir, base, err := splitDBPath(b.pathsFor(rt).dbPath)
+ dir, base, err := splitDBPath(dbPath)
if err != nil {
- return err
+ return fmt.Errorf("%s: refusing to start: %w", rt.Host, err)
}
- return instancefs.WriteAtomic(dir, base+AssignedMarkerSuffix, []byte(rt.Assigned+"\n"), 0o600)
-}
-
-// Both backends doWake can be handed carry the marker write: a production
-// agent runs a SplitBackend, and one that dropped it would set every
-// labelled copy aside on every wake.
-var (
- _ assignmentNoter = (*ExecBackend)(nil)
- _ assignmentNoter = (*SplitBackend)(nil)
-)
-
-// NoteAssignment dispatches like SeedPlaced: a unit-backed row has no
-// marker to write.
-func (b *SplitBackend) NoteAssignment(ctx context.Context, rt registry.Route) error {
- if n, ok := b.pick(rt).(assignmentNoter); ok {
- return n.NoteAssignment(ctx, rt)
+ if err := os.MkdirAll(dir, 0o700); err != nil {
+ return fmt.Errorf("%s: refusing to start: %w", rt.Host, err)
+ }
+ if err := instancefs.WriteAtomic(dir, base+AssignedMarkerSuffix, []byte(rt.Assigned+"\n"), 0o600); err != nil {
+ return fmt.Errorf("%s: refusing to start: the assignment marker beside %s could not be written: %w", rt.Host, dbPath, err)
}
return nil
}
diff --git a/internal/activator/startrule_test.go b/internal/activator/startrule_test.go
index ae0bdb046..c97e43012 100644
--- a/internal/activator/startrule_test.go
+++ b/internal/activator/startrule_test.go
@@ -163,14 +163,18 @@ func replicaCalls(t *testing.T, has bool) *int {
return &n
}
-// ruleBackend runs a real ExecBackend's Restore and NoteAssignment under
-// the fake's start, lease and replication, so a test drives doWake's own
-// order: the rule in the restore, the marker after the start.
+// ruleBackend runs a real ExecBackend's Restore under the fake's start,
+// lease and replication, so a test drives doWake's own order: the rule
+// and the marker in the restore, then the start.
type ruleBackend struct {
*fakeBackend
- eb *ExecBackend
- noted int
- mu sync.Mutex
+ eb *ExecBackend
+ t *testing.T
+ // startWrites makes the start create the app's database before it
+ // answers, as an app that opens CARLOS_DB and then fails its health
+ // probe does.
+ startWrites bool
+ mu sync.Mutex
}
func (r *ruleBackend) Restore(ctx context.Context, rt registry.Route) (bool, error) {
@@ -178,22 +182,26 @@ func (r *ruleBackend) Restore(ctx context.Context, rt registry.Route) (bool, err
return r.eb.Restore(ctx, rt)
}
-func (r *ruleBackend) NoteAssignment(ctx context.Context, rt registry.Route) error {
+func (r *ruleBackend) Start(ctx context.Context, rt registry.Route) (Proc, string, error) {
r.mu.Lock()
- r.noted++
+ writes := r.startWrites
r.mu.Unlock()
- return r.eb.NoteAssignment(ctx, rt)
+ if writes {
+ if _, err := os.Stat(rt.DBPath); errors.Is(err, os.ErrNotExist) {
+ writeUsableDB(r.t, rt.DBPath)
+ }
+ }
+ return r.fakeBackend.Start(ctx, rt)
}
// wakeOn wakes rt once through a Service over eb, and returns the wake's
// error and the fake half (its start count).
-func wakeOn(t *testing.T, eb *ExecBackend, rt registry.Route, tweak func(*fakeBackend)) (*ruleBackend, error) {
+func wakeOn(t *testing.T, eb *ExecBackend, rt registry.Route, tweak func(*ruleBackend)) (*ruleBackend, error) {
t.Helper()
- fb := &fakeBackend{}
+ rb := &ruleBackend{fakeBackend: &fakeBackend{}, eb: eb, t: t}
if tweak != nil {
- tweak(fb)
+ tweak(rb)
}
- rb := &ruleBackend{fakeBackend: fb, eb: eb}
reg, err := registry.Open(filepath.Join(t.TempDir(), "registry.db"))
if err != nil {
t.Fatal(err)
@@ -328,8 +336,9 @@ func TestMissingMarkerSetsAside(t *testing.T) {
t.Fatalf("restores = %d; a copy with no marker is set aside and restored", *restores)
}
assertSetAside(t, b, rt.Host, want)
- if _, ok := markerAt(t, rt.DBPath); ok {
- t.Fatal("Restore wrote the marker; it is written only after the start")
+ // The restored copy is established under the assignment at once.
+ if got, ok := markerAt(t, rt.DBPath); !ok || got != assignA {
+ t.Fatalf("marker = %q (present %v); want %q after the restore", got, ok, assignA)
}
}
@@ -469,12 +478,16 @@ func TestNewInstanceBootsFresh(t *testing.T) {
if err != nil || !fresh {
t.Fatalf("fresh %v err %v; a never-moved record with nothing set aside boots fresh", fresh, err)
}
+ // Permitted empty, so established before any spawn.
+ if got, ok := markerAt(t, rt.DBPath); !ok || got != assignA {
+ t.Fatalf("marker = %q (present %v); want %q once the empty start is permitted", got, ok, assignA)
+ }
rb, err := wakeOn(t, b, rt, nil)
if err != nil || rb.starts != 1 {
t.Fatalf("wake: err %v starts %d", err, rb.starts)
}
if got, ok := markerAt(t, rt.DBPath); !ok || got != assignA {
- t.Fatalf("marker = %q (present %v); want %q after the start", got, ok, assignA)
+ t.Fatalf("marker = %q (present %v); want %q after the wake", got, ok, assignA)
}
// The marker went through a temp file and a rename: nothing else is
// left beside it.
@@ -486,26 +499,72 @@ func TestNewInstanceBootsFresh(t *testing.T) {
}
}
-// The production agent's backend is a SplitBackend: it forwards the marker
-// write to the exec half, and a unit-backed row writes nothing.
-func TestSplitBackendNotesTheAssignment(t *testing.T) {
- b := testExecBackend(t)
- rt := fleetRoute(b, assignA, false)
- sb := &SplitBackend{Exec: b, Unit: &UnitBackend{OptDir: t.TempDir()}}
- unit := rt
- unit.Backing = registry.BackingUnit
- if err := sb.NoteAssignment(context.Background(), unit); err != nil {
- t.Fatal(err)
- }
- if _, ok := markerAt(t, rt.DBPath); ok {
- t.Fatal("a unit-backed row wrote a marker")
- }
- if err := sb.NoteAssignment(context.Background(), rt); err != nil {
- t.Fatal(err)
- }
- if got, ok := markerAt(t, rt.DBPath); !ok || got != assignA {
- t.Fatalf("marker = %q (present %v); want %q", got, ok, assignA)
+// A never-moved instance's permitted empty start establishes its copy
+// before the spawn: when the spawn then fails (a broken first build that
+// created its database and missed its health probe), the next wake keeps
+// that copy instead of setting it aside and refusing for ever. The same
+// holds for a restored copy whose start fails.
+func TestFailedFirstStartKeepsItsCopy(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ replica bool
+ }{{"empty start", false}, {"restored copy", true}} {
+ t.Run(tc.name, func(t *testing.T) {
+ b := testExecBackend(t)
+ rt := fleetRoute(b, assignA, false)
+ restores := replicaCalls(t, tc.replica)
+ _, err := wakeOn(t, b, rt, func(r *ruleBackend) {
+ r.startWrites = true
+ r.startErr = errors.New("injected: health probe timed out")
+ })
+ if err == nil {
+ t.Fatal("the wake succeeded with a failing start")
+ }
+ if got, ok := markerAt(t, rt.DBPath); !ok || got != assignA {
+ t.Fatalf("marker = %q (present %v); want %q, written before the spawn", got, ok, assignA)
+ }
+ before, err := os.ReadFile(rt.DBPath)
+ if err != nil {
+ t.Fatalf("the first start's database: %v", err)
+ }
+ asked := *restores
+
+ rb, err := wakeOn(t, b, rt, nil)
+ if err != nil || rb.starts != 1 {
+ t.Fatalf("second wake: err %v starts %d; want the kept copy started", err, rb.starts)
+ }
+ if *restores != asked {
+ t.Fatalf("restores %d -> %d; the kept copy needs no restore", asked, *restores)
+ }
+ if names := supersededEntries(t, b, rt.Host); len(names) != 0 {
+ t.Fatalf("set aside %q: the copy was established under this assignment", names)
+ }
+ if after, _ := os.ReadFile(rt.DBPath); string(after) != string(before) {
+ t.Fatal("the kept copy changed")
+ }
+ })
}
+ // A labelled seed placement is established at once too: a wake that
+ // dies after it resumes from the placed copy, as an unlabelled one does.
+ t.Run("seed placement", func(t *testing.T) {
+ noOwnReplica(t)
+ b, rt := nestedBackend(t, &fakeControl{}, &fakeUnit{})
+ rt.Assigned = assignA
+ rt, objs, _ := seededRoute(t, b, rt, seeds.StateReady)
+ replicaCalls(t, false)
+ if fresh, err := b.Restore(context.Background(), rt); err != nil || fresh {
+ t.Fatalf("placement: fresh %v err %v", fresh, err)
+ }
+ if got, ok := markerAt(t, rt.DBPath); !ok || got != assignA {
+ t.Fatalf("marker = %q (present %v); want %q after the placement", got, ok, assignA)
+ }
+ if fresh, err := b.Restore(context.Background(), rt); err != nil || fresh || objs.opens != 1 {
+ t.Fatalf("resume: fresh %v err %v opens %d; want the placed copy kept", fresh, err, objs.opens)
+ }
+ if names := supersededEntries(t, b, rt.Host); len(names) != 0 {
+ t.Fatalf("set aside %q", names)
+ }
+ })
}
func TestFailedRestoreLeavesNoMarker(t *testing.T) {
@@ -538,21 +597,6 @@ func TestFailedRestoreLeavesNoMarker(t *testing.T) {
t.Fatal("a corrupt restore left a marker")
}
})
- t.Run("start fails", func(t *testing.T) {
- b := testExecBackend(t)
- rt := fleetRoute(b, assignA, false)
- replicaCalls(t, true)
- rb, err := wakeOn(t, b, rt, func(f *fakeBackend) { f.startErr = errors.New("injected: health probe timed out") })
- if err == nil {
- t.Fatal("the wake succeeded with a failing start")
- }
- if rb.noted != 0 {
- t.Fatalf("NoteAssignment called %d times after a failed start", rb.noted)
- }
- if _, ok := markerAt(t, rt.DBPath); ok {
- t.Fatal("a failed start left a marker")
- }
- })
}
// walCopy builds a WAL-mode database whose last rows live only in its
@@ -703,6 +747,9 @@ func TestEveryFreshBootPathConsultsTheRule(t *testing.T) {
if !uses["startAllowed"] {
t.Errorf("%s (%s) reaches %v without consulting startAllowed", fd.Name.Name, fset.Position(fd.Pos()), hit)
}
+ if !uses["establishAssignment"] && !uses["restorePlain"] {
+ t.Errorf("%s (%s) reaches %v without establishing the assignment marker", fd.Name.Name, fset.Position(fd.Pos()), hit)
+ }
if !uses["reconcileAssignment"] && !uses["restorePlain"] {
t.Errorf("%s (%s) reaches %v without reconcileAssignment", fd.Name.Name, fset.Position(fd.Pos()), hit)
}