carlos / platform Public

Managed fleets 1b task 4, review round 1: durable set-aside and marker

The set-aside now orders its persistence barriers: .superseded, the
host directory and the .partial entry are each created and their parent
synced before any data moves; each moved file's source and destination
directories are synced before the next rename; and the host directory
is synced after the entry is marked complete. A barrier that fails
fails the wake. The assignment marker's directory is synced after its
rename (writeDurable, a local helper; WriteAtomic's contract is left
alone for its other callers), and a failed sync fails the wake before
the copy counts as established.

TestInterruptedSetAsideIsDurableInOrder records the rename and sync
seams to prove the order, and shows a parent that will not sync moves
nothing; TestMarkerIsDurableBeforeEstablishment covers the marker.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 815890a5082d8c2efa10f24bbb81ec0ec8d65cd7 parent 8820081
2 files changed, +228 −11
  • internal/activator/startrule.go +68 −11
  • internal/activator/startrule_test.go +160 −0

CI failed — run details

diff --git a/internal/activator/startrule.go b/internal/activator/startrule.go
index 55cb60e2d..3090e793f 100644
--- a/internal/activator/startrule.go
+++ b/internal/activator/startrule.go
@@ -64,6 +64,24 @@ var ErrNothingToRestore = errors.New("nothing to restore")
// interrupted-move test. It never replaces anything at the destination.
var setAsideRename = instancefs.RenameBetweenNoReplace
+// durableSync fsyncs a directory, so the entries just created or renamed
+// in it survive a power cut. A seam, so the tests can see the order of the
+// barriers and fail one.
+var durableSync = syncDirNoFollow
+
+// syncDirNoFollow fsyncs dir, opened without following a symlink (the
+// instance directory is the tenant's to write; instancekey.go's syncDir
+// follows one). Unlike syncDirIfThere, a directory that is not there is
+// an error: every directory this file syncs must exist.
+func syncDirNoFollow(dir string) error {
+ f, err := instancefs.OpenDirBeneath(dir, ".")
+ if err != nil {
+ return err
+ }
+ defer f.Close()
+ return f.Sync()
+}
+
// supersededHostDir is <DataDir>/.superseded/<host>. The DataDir is the
// agent's own root, never a tenant's instance directory, so a tenant
// cannot plant or remove the set-aside evidence.
@@ -202,18 +220,37 @@ func (b *ExecBackend) reconcileAssignment(rt registry.Route, dbPath string) erro
// supersede moves names from dir into a new set-aside entry for host and
// returns the entry's final path. On a failure part way, what has moved
// stays in the .partial directory, whose path the error names.
+//
+// Durable in order, so that a power cut at any point leaves every file
+// reachable under one of its two names and the evidence findable:
+//
+// 1. .superseded, <host> and <nanos>.partial are each created and their
+// parent synced (the data root, .superseded, <host>) before any data
+// moves, whether or not they already existed;
+// 2. each file is renamed, then its source and destination directories
+// are synced before the next rename;
+// 3. <nanos>.partial is renamed to <nanos>, then <host> is synced.
+//
+// Any barrier that fails fails the wake.
func (b *ExecBackend) supersede(host, dir string, names []string) (string, error) {
hostDir, err := b.supersededHostDir(host)
if err != nil {
return "", err
}
root := filepath.Dir(hostDir)
- if _, err := instancefs.EnsureDirBeneath(filepath.Dir(root), supersededDirName, 0o700); err != nil {
+ dataRoot := filepath.Dir(root)
+ if _, err := instancefs.EnsureDirBeneath(dataRoot, supersededDirName, 0o700); err != nil {
return "", err
}
+ if err := durableSync(dataRoot); err != nil {
+ return "", fmt.Errorf("sync %s: %w", dataRoot, err)
+ }
if _, err := instancefs.EnsureDirBeneath(root, host, 0o700); err != nil {
return "", err
}
+ if err := durableSync(root); err != nil {
+ return "", fmt.Errorf("sync %s: %w", root, err)
+ }
var stamp string
for i := 0; ; i++ {
stamp = strconv.FormatInt(time.Now().UnixNano(), 10)
@@ -228,25 +265,29 @@ func (b *ExecBackend) supersede(host, dir string, names []string) (string, error
time.Sleep(time.Microsecond)
}
partial := filepath.Join(hostDir, stamp+partialSuffix)
+ if err := durableSync(hostDir); err != nil {
+ // An empty .partial is left: it counts as set aside, which only
+ // refuses an empty start, and nothing has moved.
+ return partial, fmt.Errorf("sync %s: %w", hostDir, err)
+ }
for _, n := range names {
if err := setAsideRename(dir, n, partial, n); err != nil {
return partial, fmt.Errorf("interrupted with part of it at %s: %w", partial, err)
}
- }
- // Durable before it is marked complete: a crash that loses a rename
- // leaves the file where it was (rename is atomic), never nowhere.
- for _, d := range []string{dir, partial} {
- if err := syncDirIfThere(d); err != nil {
- return partial, fmt.Errorf("moved to %s, which could not be synced: %w", partial, err)
+ for _, d := range []string{dir, partial} {
+ if err := durableSync(d); err != nil {
+ return partial, fmt.Errorf("interrupted with part of it at %s: sync %s: %w", partial, d, err)
+ }
}
}
+ final := filepath.Join(hostDir, stamp)
if err := setAsideRename(hostDir, stamp+partialSuffix, hostDir, stamp); err != nil {
return partial, fmt.Errorf("moved to %s, which could not be marked complete: %w", partial, err)
}
- if err := syncDirIfThere(hostDir); err != nil {
- return filepath.Join(hostDir, stamp), fmt.Errorf("moved to %s, whose directory could not be synced: %w", filepath.Join(hostDir, stamp), err)
+ if err := durableSync(hostDir); err != nil {
+ return final, fmt.Errorf("moved to %s, whose directory could not be synced: %w", final, err)
}
- return filepath.Join(hostDir, stamp), nil
+ return final, nil
}
// startAllowed is the one start rule. haveLocal reports a local copy kept
@@ -319,8 +360,24 @@ func (b *ExecBackend) establishAssignment(rt registry.Route, dbPath string) erro
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 {
+ if err := writeDurable(dir, base+AssignedMarkerSuffix, []byte(rt.Assigned+"\n")); 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
}
+
+// writeDurable is instancefs.WriteAtomic (temp file, fsync, rename)
+// followed by an fsync of the containing directory, so the rename itself
+// survives a power cut. A local helper rather than a change to
+// WriteAtomic's contract: its other callers (env and launch files, config
+// renders, seed markers) are rewritten often and do not all want the
+// directory sync.
+func writeDurable(dir, name string, data []byte) error {
+ if err := instancefs.WriteAtomic(dir, name, data, 0o600); err != nil {
+ return err
+ }
+ if err := durableSync(dir); err != nil {
+ return fmt.Errorf("sync %s: %w", dir, err)
+ }
+ return nil
+}
diff --git a/internal/activator/startrule_test.go b/internal/activator/startrule_test.go
index c97e43012..002734017 100644
--- a/internal/activator/startrule_test.go
+++ b/internal/activator/startrule_test.go
@@ -449,6 +449,166 @@ func TestInterruptedSetAsideRefuses(t *testing.T) {
})
}
+// recordDurability swaps the set-aside's rename and the directory sync
+// for ones that log each call in order ("rename <src> -> <dst>", "sync
+// <dir>") and then pass through, unless fail answers an error for that
+// sync.
+func recordDurability(t *testing.T, fail func(dir string) error) *[]string {
+ t.Helper()
+ var ops []string
+ prevRename, prevSync := setAsideRename, durableSync
+ setAsideRename = func(sd, sn, dd, dn string) error {
+ ops = append(ops, "rename "+filepath.Join(sd, sn)+" -> "+filepath.Join(dd, dn))
+ return prevRename(sd, sn, dd, dn)
+ }
+ durableSync = func(dir string) error {
+ ops = append(ops, "sync "+dir)
+ if fail != nil {
+ if err := fail(dir); err != nil {
+ return err
+ }
+ }
+ return prevSync(dir)
+ }
+ t.Cleanup(func() { setAsideRename, durableSync = prevRename, prevSync })
+ return &ops
+}
+
+func opIndex(ops []string, op string) int {
+ for i, o := range ops {
+ if o == op {
+ return i
+ }
+ }
+ return -1
+}
+
+// The set-aside is durable in order: each directory it creates is
+// recorded in its parent before any file moves, each moved file's source
+// and destination directories are synced before the next move, and the
+// host directory is synced after the entry is marked complete. A power
+// cut at any point leaves every file reachable at one of its two names.
+func TestInterruptedSetAsideIsDurableInOrder(t *testing.T) {
+ t.Run("order", func(t *testing.T) {
+ b := testExecBackend(t)
+ rt := fleetRoute(b, assignB, false)
+ localCopy(t, rt.DBPath, assignA)
+ replicaCalls(t, true)
+ ops := recordDurability(t, nil)
+ if _, err := b.Restore(context.Background(), rt); err != nil {
+ t.Fatalf("Restore: %v", err)
+ }
+ root := filepath.Join(b.DataDir, supersededDirName)
+ hostDir := filepath.Join(root, rt.Host)
+ firstMove := -1
+ for i, o := range *ops {
+ if strings.HasPrefix(o, "rename ") {
+ firstMove = i
+ break
+ }
+ }
+ if firstMove < 0 {
+ t.Fatalf("nothing moved: %q", *ops)
+ }
+ for _, parent := range []string{b.DataDir, root, hostDir} {
+ if i := opIndex(*ops, "sync "+parent); i < 0 || i > firstMove {
+ t.Errorf("parent %s synced at %d, first move at %d: a new directory must be durable before data moves into it (%q)", parent, i, firstMove, *ops)
+ }
+ }
+ // Every file move is followed by syncs of both directories before
+ // the next rename.
+ src := filepath.Dir(rt.DBPath)
+ var moves []int
+ for i, o := range *ops {
+ if strings.HasPrefix(o, "rename ") {
+ moves = append(moves, i)
+ }
+ }
+ final := moves[len(moves)-1]
+ for k, i := range moves[:len(moves)-1] {
+ next := moves[k+1]
+ dst := filepath.Dir(strings.SplitN((*ops)[i], " -> ", 2)[1])
+ for _, d := range []string{src, dst} {
+ j := opIndex((*ops)[i:next], "sync "+d)
+ if j < 0 {
+ t.Errorf("%q not followed by a sync of %s before the next rename", (*ops)[i], d)
+ }
+ }
+ }
+ if !strings.HasSuffix((*ops)[final], partialSuffix+" -> "+filepath.Join(hostDir, strings.TrimSuffix(filepath.Base(strings.SplitN((*ops)[final], " -> ", 2)[0]), partialSuffix))) {
+ t.Fatalf("the last rename is not the .partial being marked complete: %q", (*ops)[final])
+ }
+ if opIndex((*ops)[final:], "sync "+hostDir) < 0 {
+ t.Fatalf("the host directory is not synced after the entry is marked complete: %q", (*ops)[final:])
+ }
+ })
+ t.Run("a parent that will not sync moves nothing", func(t *testing.T) {
+ b := testExecBackend(t)
+ rt := fleetRoute(b, assignB, false)
+ want := localCopy(t, rt.DBPath, assignA)
+ replicaCalls(t, true)
+ root := filepath.Join(b.DataDir, supersededDirName)
+ ops := recordDurability(t, func(dir string) error {
+ if dir == root {
+ return errors.New("injected: fsync failed")
+ }
+ return nil
+ })
+ if fresh, err := b.Restore(context.Background(), rt); err == nil || fresh {
+ t.Fatalf("fresh %v err %v; a set-aside that cannot be made durable fails the wake", fresh, err)
+ }
+ for _, o := range *ops {
+ if strings.HasPrefix(o, "rename ") {
+ t.Fatalf("a file moved under an unsynced parent: %q", *ops)
+ }
+ }
+ dir := filepath.Dir(rt.DBPath)
+ for name, body := range want {
+ if got, err := os.ReadFile(filepath.Join(dir, name)); err != nil || string(got) != body {
+ t.Errorf("%s = %q, %v; want it left in place", name, got, err)
+ }
+ }
+ })
+}
+
+// The marker's rename is made durable before the copy counts as
+// established: its directory is synced after the marker is in place, and a
+// sync that fails fails the wake.
+func TestMarkerIsDurableBeforeEstablishment(t *testing.T) {
+ b := testExecBackend(t)
+ rt := fleetRoute(b, assignA, false)
+ replicaCalls(t, false)
+ dir := filepath.Dir(rt.DBPath)
+ synced := false
+ recordDurability(t, func(d string) error {
+ if d == dir {
+ if _, err := os.Stat(rt.DBPath + AssignedMarkerSuffix); err == nil {
+ synced = true
+ }
+ }
+ return nil
+ })
+ if fresh, err := b.Restore(context.Background(), rt); err != nil || !fresh {
+ t.Fatalf("fresh %v err %v", fresh, err)
+ }
+ if !synced {
+ t.Fatal("the marker's directory was not synced after the marker was in place")
+ }
+
+ b2 := testExecBackend(t)
+ rt2 := fleetRoute(b2, assignA, false)
+ dir2 := filepath.Dir(rt2.DBPath)
+ recordDurability(t, func(d string) error {
+ if d == dir2 {
+ return errors.New("injected: fsync failed")
+ }
+ return nil
+ })
+ if fresh, err := b2.Restore(context.Background(), rt2); err == nil || fresh {
+ t.Fatalf("fresh %v err %v; an unsynced marker must fail the wake", fresh, err)
+ }
+}
+
func TestMovedInstanceOnACleanBoxRefusesWithoutReplica(t *testing.T) {
b := testExecBackend(t)
rt := fleetRoute(b, assignB, true)