carlos / platform Public

region HA P1a Task 8: keep decision: a local copy only on a matching clean marker and unchanged state

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 134697360943091727aa4699402e2073340e791c parent e00a157
6 files changed, +753 −0
  • internal/activator/harecord.go +123 −0
  • internal/activator/harecord_linux.go +141 −0
  • internal/activator/harecord_linux_test.go +286 −0
  • internal/activator/harecord_other.go +19 −0
  • internal/hafresh/keep.go +105 −0
  • internal/hafresh/keep_test.go +79 −0

CI cancelled — superseded by a newer push — run details

diff --git a/internal/activator/harecord.go b/internal/activator/harecord.go
new file mode 100644
index 000000000..1a0819f04
--- /dev/null
+++ b/internal/activator/harecord.go
@@ -0,0 +1,123 @@
+package activator
+
+import (
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io/fs"
+ "os"
+ "path/filepath"
+
+ "github.com/carlosframework/platform/internal/hafresh"
+)
+
+// The local release record (region HA, I2): <db>.release.json, written
+// beside the database when an HA host is released, and read back at its
+// next wake to feed hafresh.DecideKeep. Reading it, statting the database
+// and digesting the files tree are Linux-only (ctime); on other systems
+// readLocalNow errors, so they never keep a local copy.
+
+// maxRecordBytes bounds a release record read. A real one is well under a
+// kilobyte; anything bigger is not a record this box wrote.
+const maxRecordBytes = 64 << 10
+
+// recordPath is the host's local release record: <dbPath>.release.json.
+func recordPath(p instancePaths, host string) string {
+ return p.dbPath + ".release.json"
+}
+
+// hostFilesDir is the host's files directory: <dataDir>/<host>, the
+// instance directory's <host> on the nested layout.
+func hostFilesDir(p instancePaths, host string) string {
+ return filepath.Join(p.dataDir, host)
+}
+
+// writeReleaseRecord writes rec as the host's local release record,
+// durably: a new temporary file in the record's directory (created
+// exclusively, so a planted link is never followed), fsynced, renamed over
+// the record, and the directory fsynced.
+func writeReleaseRecord(p instancePaths, host string, rec hafresh.LocalRecord) error {
+ body, err := json.Marshal(rec)
+ if err != nil {
+ return fmt.Errorf("release record: %w", err)
+ }
+ path := recordPath(p, host)
+ dir := filepath.Dir(path)
+ f, err := os.CreateTemp(dir, ".release-*.tmp")
+ if err != nil {
+ return fmt.Errorf("release record: %w", err)
+ }
+ tmp := f.Name()
+ ok := false
+ defer func() {
+ if !ok {
+ _ = os.Remove(tmp)
+ }
+ }()
+ if _, err := f.Write(body); err != nil {
+ _ = f.Close()
+ return fmt.Errorf("release record: %w", err)
+ }
+ if err := f.Sync(); err != nil {
+ _ = f.Close()
+ return fmt.Errorf("release record: %w", err)
+ }
+ if err := f.Close(); err != nil {
+ return fmt.Errorf("release record: %w", err)
+ }
+ if err := os.Rename(tmp, path); err != nil {
+ return fmt.Errorf("release record: %w", err)
+ }
+ ok = true
+ d, err := os.Open(dir)
+ if err != nil {
+ return fmt.Errorf("release record: sync dir: %w", err)
+ }
+ defer d.Close()
+ if err := d.Sync(); err != nil {
+ return fmt.Errorf("release record: sync dir: %w", err)
+ }
+ return nil
+}
+
+// readLocalNow reads the host's local state for the keep decision: the
+// local release record, the database's identity, whether its -wal is
+// absent or empty, and the files tree digest (the files directory and the
+// env file). A missing or undecodable record is HaveRecord false, a
+// missing database DBExists false; neither is an error. Any other read
+// failure is an error, and the caller restores: an error never keeps.
+func readLocalNow(p instancePaths, host string) (hafresh.LocalNow, error) {
+ var now hafresh.LocalNow
+ body, err := readRecordFile(recordPath(p, host))
+ switch {
+ case errors.Is(err, fs.ErrNotExist):
+ case err != nil:
+ return hafresh.LocalNow{}, fmt.Errorf("release record: %w", err)
+ default:
+ var rec hafresh.LocalRecord
+ if json.Unmarshal(body, &rec) == nil {
+ now.HaveRecord, now.Record = true, rec
+ }
+ }
+ db, err := statFileID(p.dbPath)
+ switch {
+ case errors.Is(err, fs.ErrNotExist):
+ case err != nil:
+ return hafresh.LocalNow{}, fmt.Errorf("release record: database: %w", err)
+ default:
+ now.DBExists, now.DB = true, db
+ }
+ wal, err := statFileID(p.dbPath + "-wal")
+ switch {
+ case errors.Is(err, fs.ErrNotExist):
+ now.WALEmpty = true
+ case err != nil:
+ return hafresh.LocalNow{}, fmt.Errorf("release record: wal: %w", err)
+ default:
+ now.WALEmpty = wal.Size == 0
+ }
+ if now.TreeDigest, err = treeDigest(hostFilesDir(p, host), p.envFile); err != nil {
+ return hafresh.LocalNow{}, fmt.Errorf("release record: files: %w", err)
+ }
+ return now, nil
+}
diff --git a/internal/activator/harecord_linux.go b/internal/activator/harecord_linux.go
new file mode 100644
index 000000000..4edba977c
--- /dev/null
+++ b/internal/activator/harecord_linux.go
@@ -0,0 +1,141 @@
+//go:build linux
+
+package activator
+
+import (
+ "crypto/sha256"
+ "encoding/binary"
+ "encoding/hex"
+ "errors"
+ "fmt"
+ "hash"
+ "io"
+ "io/fs"
+ "os"
+ "path/filepath"
+
+ "golang.org/x/sys/unix"
+
+ "github.com/carlosframework/platform/internal/hafresh"
+)
+
+// statFileID is path's identity: inode, size, and mtime and ctime in
+// nanoseconds. A missing file answers an error that is fs.ErrNotExist.
+func statFileID(path string) (hafresh.FileID, error) {
+ var st unix.Stat_t
+ if err := unix.Stat(path, &st); err != nil {
+ return hafresh.FileID{}, &fs.PathError{Op: "stat", Path: path, Err: err}
+ }
+ return fileIDOf(&st), nil
+}
+
+func fileIDOf(st *unix.Stat_t) hafresh.FileID {
+ return hafresh.FileID{
+ Inode: uint64(st.Ino),
+ Size: uint64(st.Size),
+ MtimeNs: st.Mtim.Nano(),
+ CtimeNs: st.Ctim.Nano(),
+ }
+}
+
+// treeDigest is the files tree digest: SHA-256 over every entry of
+// filesDir (the directory itself included) and the env file, each as its
+// path, type and mode, size, inode, mtime_ns and ctime_ns. It reads
+// metadata only, never contents, and never follows a link: a link is an
+// entry of its own. Entries go in WalkDir's lexical order, so the same
+// tree always hashes the same. An absent filesDir, or an absent env file,
+// hashes as "absent" in its place; an empty envFile is left out. A tree it
+// cannot read completely is an error, never a digest.
+func treeDigest(filesDir, envFile string) (string, error) {
+ h := sha256.New()
+ io.WriteString(h, "carlos-tree/v1\x00")
+ if _, err := os.Lstat(filesDir); errors.Is(err, fs.ErrNotExist) {
+ writeAbsent(h, "files")
+ } else if err != nil {
+ return "", err
+ } else {
+ err := filepath.WalkDir(filesDir, func(path string, _ fs.DirEntry, err error) error {
+ if err != nil {
+ return err
+ }
+ rel, err := filepath.Rel(filesDir, path)
+ if err != nil {
+ return err
+ }
+ var st unix.Stat_t
+ if err := unix.Lstat(path, &st); err != nil {
+ return &fs.PathError{Op: "lstat", Path: path, Err: err}
+ }
+ writeEntry(h, "files/"+filepath.ToSlash(rel), &st)
+ return nil
+ })
+ if err != nil {
+ return "", err
+ }
+ }
+ if envFile != "" {
+ var st unix.Stat_t
+ switch err := unix.Lstat(envFile, &st); {
+ case errors.Is(err, unix.ENOENT):
+ writeAbsent(h, "env")
+ case err != nil:
+ return "", &fs.PathError{Op: "lstat", Path: envFile, Err: err}
+ default:
+ writeEntry(h, "env", &st)
+ }
+ }
+ return hex.EncodeToString(h.Sum(nil)), nil
+}
+
+func writeAbsent(h hash.Hash, name string) {
+ writeField(h, []byte(name))
+ writeField(h, []byte("absent"))
+}
+
+// writeEntry hashes one entry: its name, length-prefixed so no two
+// entries' bytes can run together, then its fixed-width metadata.
+func writeEntry(h hash.Hash, name string, st *unix.Stat_t) {
+ writeField(h, []byte(name))
+ var b [4 + 8*4]byte
+ binary.BigEndian.PutUint32(b[0:], st.Mode) // type and permission bits
+ id := fileIDOf(st)
+ binary.BigEndian.PutUint64(b[4:], id.Size)
+ binary.BigEndian.PutUint64(b[12:], id.Inode)
+ binary.BigEndian.PutUint64(b[20:], uint64(id.MtimeNs))
+ binary.BigEndian.PutUint64(b[28:], uint64(id.CtimeNs))
+ writeField(h, b[:])
+}
+
+func writeField(h hash.Hash, b []byte) {
+ var n [8]byte
+ binary.BigEndian.PutUint64(n[:], uint64(len(b)))
+ h.Write(n[:])
+ h.Write(b)
+}
+
+// readRecordFile reads the release record at path, never through a link
+// and never blocking on a special file: it must be a regular file of at
+// most maxRecordBytes. A missing record is fs.ErrNotExist.
+func readRecordFile(path string) ([]byte, error) {
+ fd, err := unix.Open(path, unix.O_RDONLY|unix.O_NOFOLLOW|unix.O_NONBLOCK|unix.O_CLOEXEC, 0)
+ if err != nil {
+ return nil, &fs.PathError{Op: "open", Path: path, Err: err}
+ }
+ f := os.NewFile(uintptr(fd), path)
+ defer f.Close()
+ fi, err := f.Stat()
+ if err != nil {
+ return nil, err
+ }
+ if !fi.Mode().IsRegular() {
+ return nil, fmt.Errorf("%s: not a regular file", path)
+ }
+ b, err := io.ReadAll(io.LimitReader(f, maxRecordBytes+1))
+ if err != nil {
+ return nil, err
+ }
+ if len(b) > maxRecordBytes {
+ return nil, fmt.Errorf("%s: larger than %d bytes", path, maxRecordBytes)
+ }
+ return b, nil
+}
diff --git a/internal/activator/harecord_linux_test.go b/internal/activator/harecord_linux_test.go
new file mode 100644
index 000000000..00399afec
--- /dev/null
+++ b/internal/activator/harecord_linux_test.go
@@ -0,0 +1,286 @@
+//go:build linux
+
+package activator
+
+import (
+ "os"
+ "path/filepath"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/hafresh"
+)
+
+// filesTree makes a files directory holding files (name to content), and
+// returns its path.
+func filesTree(t *testing.T, files map[string]string) string {
+ t.Helper()
+ dir := filepath.Join(t.TempDir(), "shop.example.com")
+ for name, content := range files {
+ p := filepath.Join(dir, name)
+ if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(p, []byte(content), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err := os.MkdirAll(dir, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ return dir
+}
+
+func mustDigest(t *testing.T, filesDir, envFile string) string {
+ t.Helper()
+ d, err := treeDigest(filesDir, envFile)
+ if err != nil || d == "" {
+ t.Fatalf("treeDigest(%s, %s) = %q, %v", filesDir, envFile, d, err)
+ }
+ return d
+}
+
+// nextTick waits out the kernel's coarse timestamp granularity, so a
+// change made next gets a ctime different from the last one.
+func nextTick() { time.Sleep(20 * time.Millisecond) }
+
+func TestTreeDigestStableAndSeesChmod(t *testing.T) {
+ absent := filepath.Join(t.TempDir(), "absent")
+ a, _ := treeDigest(absent, "")
+ b, _ := treeDigest(absent, "")
+ if a != b {
+ t.Fatal("absent dir unstable")
+ }
+ dir := filesTree(t, map[string]string{"report.token": "x"})
+ before, _ := treeDigest(dir, "")
+ if err := os.Chmod(filepath.Join(dir, "report.token"), 0o640); err != nil {
+ t.Fatal(err)
+ }
+ if after, _ := treeDigest(dir, ""); after == before {
+ t.Fatal("chmod not seen")
+ }
+}
+
+func TestTreeDigestAbsentDirStable(t *testing.T) {
+ root := t.TempDir()
+ absent := filepath.Join(root, "shop.example.com")
+ env := filepath.Join(root, "shop.example.com.env")
+ a, b := mustDigest(t, absent, env), mustDigest(t, absent, env)
+ if a != b {
+ t.Fatalf("absent dir unstable: %s, %s", a, b)
+ }
+ // Absent is its own state: not the same as an empty directory, and
+ // the env file still counts beside it.
+ if err := os.WriteFile(env, []byte("K=v\n"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ withEnv := mustDigest(t, absent, env)
+ if withEnv == a {
+ t.Fatal("env file not seen beside an absent files dir")
+ }
+ if mustDigest(t, absent, env) != withEnv {
+ t.Fatal("absent dir with an env file unstable")
+ }
+ if err := os.Mkdir(absent, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if mustDigest(t, absent, env) == withEnv {
+ t.Fatal("an empty dir hashes as an absent one")
+ }
+}
+
+func TestTreeDigestSeesEveryChange(t *testing.T) {
+ // Each change gets a fresh tree, so no change depends on another.
+ for name, change := range map[string]func(dir, env string){
+ "write, same size": func(dir, env string) { os.WriteFile(filepath.Join(dir, "uploads/a.txt"), []byte("bbb"), 0o600) },
+ "new file": func(dir, env string) { os.WriteFile(filepath.Join(dir, "uploads/b.txt"), nil, 0o600) },
+ "removed file": func(dir, env string) { os.Remove(filepath.Join(dir, "instance.key")) },
+ "rename and back": func(dir, env string) {
+ p := filepath.Join(dir, "report.token")
+ os.Rename(p, p+".x")
+ os.Rename(p+".x", p)
+ },
+ "chmod and back": func(dir, env string) {
+ p := filepath.Join(dir, "uploads/a.txt")
+ os.Chmod(p, 0o640)
+ os.Chmod(p, 0o600)
+ },
+ "chmod of a dir": func(dir, env string) { os.Chmod(filepath.Join(dir, "uploads"), 0o700) },
+ "chmod of root": func(dir, env string) { os.Chmod(dir, 0o700) },
+ "env chmod": func(dir, env string) { os.Chmod(env, 0o640) },
+ "env removed": func(dir, env string) { os.Remove(env) },
+ "a link": func(dir, env string) { os.Symlink("/etc/passwd", filepath.Join(dir, "link")) },
+ } {
+ dir := filesTree(t, map[string]string{"report.token": "x", "uploads/a.txt": "aaa", "instance.key": "k"})
+ env := filepath.Join(filepath.Dir(dir), "shop.example.com.env")
+ if err := os.WriteFile(env, []byte("K=v\n"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ before := mustDigest(t, dir, env)
+ if again := mustDigest(t, dir, env); again != before {
+ t.Fatalf("%s: unstable before the change", name)
+ }
+ nextTick()
+ change(dir, env)
+ if mustDigest(t, dir, env) == before {
+ t.Errorf("%s: not seen", name)
+ }
+ }
+}
+
+func TestTreeDigestNeverFollowsLinks(t *testing.T) {
+ outside := filesTree(t, map[string]string{"secret": "s"})
+ dir := filesTree(t, nil)
+ for name, target := range map[string]string{"dir": outside, "file": filepath.Join(outside, "secret")} {
+ if err := os.Symlink(target, filepath.Join(dir, name)); err != nil {
+ t.Fatal(err)
+ }
+ }
+ for _, change := range []func(){
+ func() { os.Chmod(filepath.Join(outside, "secret"), 0o644) },
+ func() { os.Chmod(outside, 0o700) },
+ func() { os.WriteFile(filepath.Join(outside, "secret"), []byte("longer"), 0o644) },
+ } {
+ before := mustDigest(t, dir, "")
+ nextTick()
+ change()
+ if mustDigest(t, dir, "") != before {
+ t.Fatal("the digest followed a link out of the tree")
+ }
+ }
+}
+
+func TestTreeDigestUnreadableIsAnError(t *testing.T) {
+ if os.Geteuid() == 0 {
+ t.Skip("root reads a mode-000 directory")
+ }
+ dir := filesTree(t, map[string]string{"sub/a": "a"})
+ if err := os.Chmod(filepath.Join(dir, "sub"), 0); err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { os.Chmod(filepath.Join(dir, "sub"), 0o755) })
+ if d, err := treeDigest(dir, ""); err == nil {
+ t.Fatalf("a tree read partly gave a digest: %s", d)
+ }
+}
+
+// recordFixture is a host's paths on the flat layout, with a database and
+// a files tree.
+func recordFixture(t *testing.T) (instancePaths, string) {
+ t.Helper()
+ const host = "shop.example.com"
+ files := filesTree(t, map[string]string{"report.token": "x", "uploads/a.txt": "a"})
+ dataDir := filepath.Dir(files)
+ p := instancePaths{dataDir: dataDir, dbPath: filepath.Join(dataDir, host+".db"), envFile: filepath.Join(dataDir, host+".env")}
+ for path, body := range map[string]string{p.dbPath: "sqlite", p.envFile: "K=v\n"} {
+ if err := os.WriteFile(path, []byte(body), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ }
+ return p, host
+}
+
+func TestReleaseRecordKeepsOnlyUnchangedState(t *testing.T) {
+ self := hafresh.Self{Ref: "a", IID: "i-a"}
+ m := hafresh.Marker{V: 1, Box: "a", IID: "i-a", Lifetime: "L1", TXID: 9, FilesGen: "3:ab", Clean: true}
+ view := hafresh.View{Lock: hafresh.Lock{Release: &m}}
+ decide := func(p instancePaths, host string) string {
+ t.Helper()
+ now, err := readLocalNow(p, host)
+ if err != nil {
+ t.Fatal(err)
+ }
+ _, r := hafresh.DecideKeep(view, self, "L1", now)
+ return r
+ }
+ release := func(p instancePaths, host string) {
+ t.Helper()
+ now, err := readLocalNow(p, host)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := writeReleaseRecord(p, host, hafresh.LocalRecord{Marker: m, DB: now.DB, WALEmpty: now.WALEmpty, TreeDigest: now.TreeDigest}); err != nil {
+ t.Fatal(err)
+ }
+ }
+
+ p, host := recordFixture(t)
+ if got, want := recordPath(p, host), p.dbPath+".release.json"; got != want {
+ t.Fatalf("recordPath = %s, want %s", got, want)
+ }
+ if r := decide(p, host); r != "no-record" {
+ t.Fatalf("before any release: %s", r)
+ }
+ release(p, host)
+ if r := decide(p, host); r != "kept" {
+ t.Fatalf("unchanged since the release: %s", r)
+ }
+ // An empty -wal is no change; one with content is.
+ if err := os.WriteFile(p.dbPath+"-wal", nil, 0o600); err != nil {
+ t.Fatal(err)
+ }
+ if r := decide(p, host); r != "kept" {
+ t.Fatalf("empty wal: %s", r)
+ }
+
+ for name, c := range map[string]struct {
+ change func(p instancePaths, host string)
+ want string
+ }{
+ "db chmod": {func(p instancePaths, _ string) { os.Chmod(p.dbPath, 0o640) }, "db-changed"},
+ "db write": {func(p instancePaths, _ string) { os.WriteFile(p.dbPath, []byte("sqlitE"), 0o600) }, "db-changed"},
+ "db replaced": {func(p instancePaths, _ string) {
+ os.WriteFile(p.dbPath+".n", []byte("sqlite"), 0o600)
+ os.Rename(p.dbPath+".n", p.dbPath)
+ }, "db-changed"},
+ "db removed": {func(p instancePaths, _ string) { os.Remove(p.dbPath) }, "no-db"},
+ "wal content": {func(p instancePaths, _ string) { os.WriteFile(p.dbPath+"-wal", []byte("frame"), 0o600) }, "wal"},
+ "file touched": {func(p instancePaths, host string) {
+ os.Chtimes(filepath.Join(p.dataDir, host, "report.token"), time.Now(), time.Now())
+ }, "tree-changed"},
+ "env written": {func(p instancePaths, _ string) { os.WriteFile(p.envFile, []byte("K=w\n"), 0o600) }, "tree-changed"},
+ "record torn": {func(p instancePaths, host string) { os.WriteFile(recordPath(p, host), []byte(`{"marker":`), 0o600) }, "no-record"},
+ "record gone": {func(p instancePaths, host string) { os.Remove(recordPath(p, host)) }, "no-record"},
+ } {
+ p, host := recordFixture(t)
+ release(p, host)
+ if r := decide(p, host); r != "kept" {
+ t.Fatalf("%s: before the change: %s", name, r)
+ }
+ nextTick()
+ c.change(p, host)
+ if r := decide(p, host); r != c.want {
+ t.Errorf("%s: %s, want %s", name, r, c.want)
+ }
+ }
+}
+
+func TestWriteReleaseRecordReplacesAPlantedLink(t *testing.T) {
+ p, host := recordFixture(t)
+ target := filepath.Join(t.TempDir(), "target")
+ if err := os.WriteFile(target, []byte("keep me"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Symlink(target, recordPath(p, host)); err != nil {
+ t.Fatal(err)
+ }
+ if err := writeReleaseRecord(p, host, hafresh.LocalRecord{Marker: hafresh.Marker{V: 1, Box: "a"}}); err != nil {
+ t.Fatal(err)
+ }
+ if b, _ := os.ReadFile(target); string(b) != "keep me" {
+ t.Fatalf("written through the link: %q", b)
+ }
+ if fi, err := os.Lstat(recordPath(p, host)); err != nil || !fi.Mode().IsRegular() {
+ t.Fatalf("record is not a regular file: %v %v", fi, err)
+ }
+ now, err := readLocalNow(p, host)
+ if err != nil || !now.HaveRecord || now.Record.Marker.Box != "a" {
+ t.Fatalf("%+v %v", now, err)
+ }
+ entries, _ := os.ReadDir(p.dataDir)
+ for _, e := range entries {
+ if filepath.Ext(e.Name()) == ".tmp" {
+ t.Fatalf("temporary file left: %s", e.Name())
+ }
+ }
+}
diff --git a/internal/activator/harecord_other.go b/internal/activator/harecord_other.go
new file mode 100644
index 000000000..96c4d3221
--- /dev/null
+++ b/internal/activator/harecord_other.go
@@ -0,0 +1,19 @@
+//go:build !linux
+
+package activator
+
+import (
+ "errors"
+
+ "github.com/carlosframework/platform/internal/hafresh"
+)
+
+// errNoKeepProof is every local-state read off Linux: the keep proof needs
+// ctime, so these systems never keep a local copy of an HA host.
+var errNoKeepProof = errors.New("release record: the keep proof needs Linux")
+
+func statFileID(string) (hafresh.FileID, error) { return hafresh.FileID{}, errNoKeepProof }
+
+func treeDigest(string, string) (string, error) { return "", errNoKeepProof }
+
+func readRecordFile(string) ([]byte, error) { return nil, errNoKeepProof }
diff --git a/internal/hafresh/keep.go b/internal/hafresh/keep.go
new file mode 100644
index 000000000..d13cc0a8c
--- /dev/null
+++ b/internal/hafresh/keep.go
@@ -0,0 +1,105 @@
+package hafresh
+
+// FileID is a file's identity as the keep decision compares it: inode,
+// size, and modification and change times in nanoseconds. ctime cannot be
+// set from userspace, so a write, rename or chmod since the record was
+// written changes it.
+type FileID struct {
+ Inode uint64 `json:"inode"`
+ Size uint64 `json:"size"`
+ MtimeNs int64 `json:"mtime_ns"`
+ CtimeNs int64 `json:"ctime_ns"`
+}
+
+// LocalRecord is <db>.release.json: what this box wrote beside the
+// database when it released the host, just before the marker. It holds the
+// marker it released with, the database file's identity, whether its -wal
+// was absent or empty, and the files tree digest (metadata only).
+type LocalRecord struct {
+ Marker Marker `json:"marker"`
+ DB FileID `json:"db"`
+ WALEmpty bool `json:"wal_empty"`
+ TreeDigest string `json:"tree_digest"`
+}
+
+// LocalNow is the local state as it is now, read at wake: the local record
+// if there is one, and the database, WAL and files tree recomputed. The
+// zero LocalNow never keeps.
+type LocalNow struct {
+ HaveRecord bool
+ Record LocalRecord
+ DBExists bool
+ DB FileID
+ WALEmpty bool
+ TreeDigest string
+}
+
+// Keep reasons, in DecideKeep's order. KeepKept is the one that keeps.
+const (
+ KeepNoMarker = "no-marker"
+ KeepUnclean = "unclean"
+ KeepOtherBox = "other-box"
+ KeepLifetime = "lifetime"
+ KeepNoRecord = "no-record"
+ KeepTXID = "txid"
+ KeepFilesGen = "files-gen"
+ KeepNoDB = "no-db"
+ KeepDBChanged = "db-changed"
+ KeepWAL = "wal"
+ KeepTreeChanged = "tree-changed"
+ KeepKept = "kept"
+)
+
+// DecideKeep is the keep decision (I2), its one place: a box reuses its
+// local database and files only on positive proof. It keeps only when
+//
+// - the lock v is a release marker, and the marker is clean;
+// - the marker names this box, by reference and by a non-empty instance
+// id (a box that does not know its instance id proves nothing);
+// - its lifetime is the current record's incarnation, lifetime, which is
+// never empty;
+// - the local record exists and carries the marker's txid and files
+// generation;
+// - the database exists and its identity is the record's, and the -wal
+// is absent or empty, both now and when the record was written;
+// - the files tree digest, recomputed now, is the record's.
+//
+// Anything else answers keep false and the first reason that failed, and
+// the caller sets the local copy aside and restores.
+func DecideKeep(v View, self Self, lifetime string, now LocalNow) (keep bool, reason string) {
+ if v.Absent || v.Lock.Release == nil {
+ return false, KeepNoMarker
+ }
+ m := v.Lock.Release
+ if !m.Clean {
+ return false, KeepUnclean
+ }
+ if self.IID == "" || m.IID != self.IID || m.Box != self.Ref {
+ return false, KeepOtherBox
+ }
+ if lifetime == "" || m.Lifetime != lifetime {
+ return false, KeepLifetime
+ }
+ if !now.HaveRecord {
+ return false, KeepNoRecord
+ }
+ if now.Record.Marker.TXID != m.TXID {
+ return false, KeepTXID
+ }
+ if now.Record.Marker.FilesGen != m.FilesGen {
+ return false, KeepFilesGen
+ }
+ if !now.DBExists {
+ return false, KeepNoDB
+ }
+ if now.DB != now.Record.DB {
+ return false, KeepDBChanged
+ }
+ if !now.WALEmpty || !now.Record.WALEmpty {
+ return false, KeepWAL
+ }
+ if now.TreeDigest == "" || now.TreeDigest != now.Record.TreeDigest {
+ return false, KeepTreeChanged
+ }
+ return true, KeepKept
+}
diff --git a/internal/hafresh/keep_test.go b/internal/hafresh/keep_test.go
new file mode 100644
index 000000000..9e6c8f075
--- /dev/null
+++ b/internal/hafresh/keep_test.go
@@ -0,0 +1,79 @@
+package hafresh
+
+import "testing"
+
+func TestDecideKeep(t *testing.T) {
+ self := Self{Ref: "a", IID: "i-a"}
+ m := Marker{V: 1, Box: "a", IID: "i-a", Lifetime: "L1", TXID: 9, FilesGen: "3:ab", Clean: true}
+ rec := LocalRecord{Marker: m, DB: FileID{1, 2, 3, 4}, WALEmpty: true, TreeDigest: "d"}
+ ok := LocalNow{HaveRecord: true, Record: rec, DBExists: true, DB: rec.DB, WALEmpty: true, TreeDigest: "d"}
+ if k, r := DecideKeep(View{Lock: Lock{Release: &m}}, self, "L1", ok); !k || r != "kept" {
+ t.Fatal(r)
+ }
+ try := func(want string, f func(*Marker, *LocalNow, *string)) {
+ t.Helper()
+ m2, n2, l := m, ok, "L1"
+ f(&m2, &n2, &l)
+ if k, r := DecideKeep(View{Lock: Lock{Release: &m2}}, self, l, n2); k || r != want {
+ t.Errorf("want %s, got %v %s", want, k, r)
+ }
+ }
+ try("unclean", func(m *Marker, n *LocalNow, _ *string) { m.Clean = false; n.Record.Marker.Clean = false })
+ try("other-box", func(m *Marker, _ *LocalNow, _ *string) { m.IID = "i-b" })
+ try("lifetime", func(_ *Marker, _ *LocalNow, l *string) { *l = "" })
+ try("txid", func(_ *Marker, n *LocalNow, _ *string) { n.Record.Marker.TXID = 8 })
+ try("db-changed", func(_ *Marker, n *LocalNow, _ *string) { n.DB.CtimeNs++ })
+ try("wal", func(_ *Marker, n *LocalNow, _ *string) { n.WALEmpty = false })
+ try("tree-changed", func(_ *Marker, n *LocalNow, _ *string) { n.TreeDigest = "e" })
+
+ // G4: the reasons the plan's test leaves out.
+ try("no-record", func(_ *Marker, n *LocalNow, _ *string) { n.HaveRecord = false })
+ try("files-gen", func(_ *Marker, n *LocalNow, _ *string) { n.Record.Marker.FilesGen = "2:cd" })
+ try("no-db", func(_ *Marker, n *LocalNow, _ *string) { n.DBExists = false })
+ for name, v := range map[string]View{
+ "absent": {Absent: true},
+ "a held lease": {Lock: Lock{Owner: OwnerFor(self, 7, true)}},
+ "a legacy lock": {Lock: Lock{Owner: "ip-10-0-0-1:77"}},
+ "marker owner only": {Lock: Lock{Owner: MarkerOwner(m)}},
+ } {
+ if k, r := DecideKeep(v, self, "L1", ok); k || r != "no-marker" {
+ t.Errorf("%s: want no-marker, got %v %s", name, k, r)
+ }
+ }
+
+ // Beyond the plan: the other identity checks and the record's own
+ // facts.
+ try("other-box", func(m *Marker, _ *LocalNow, _ *string) { m.Box = "b" })
+ try("lifetime", func(_ *Marker, _ *LocalNow, l *string) { *l = "L2" })
+ // An empty lifetime counts, even against a marker with none.
+ try("lifetime", func(m *Marker, n *LocalNow, l *string) { m.Lifetime, n.Record.Marker.Lifetime, *l = "", "", "" })
+ try("db-changed", func(_ *Marker, n *LocalNow, _ *string) { n.DB.Inode++ })
+ try("db-changed", func(_ *Marker, n *LocalNow, _ *string) { n.DB.Size++ })
+ try("db-changed", func(_ *Marker, n *LocalNow, _ *string) { n.DB.MtimeNs++ })
+ try("wal", func(_ *Marker, n *LocalNow, _ *string) { n.Record.WALEmpty = false })
+ try("tree-changed", func(_ *Marker, n *LocalNow, _ *string) { n.TreeDigest, n.Record.TreeDigest = "", "" })
+ // A box that does not know its instance id never proves the marker
+ // its own, even one written with no iid either.
+ noIID := m
+ noIID.IID = ""
+ n := ok
+ n.Record.Marker = noIID
+ if k, r := DecideKeep(View{Lock: Lock{Release: &noIID}}, Self{Ref: "a"}, "L1", n); k || r != "other-box" {
+ t.Errorf("unknown iid: %v %s", k, r)
+ }
+ // The order: an unclean marker naming another box is "unclean", and a
+ // clean one naming another box with no record is "other-box".
+ other := m
+ other.Clean, other.IID = false, "i-b"
+ if _, r := DecideKeep(View{Lock: Lock{Release: &other}}, self, "L1", LocalNow{}); r != "unclean" {
+ t.Errorf("order: %s", r)
+ }
+ other.Clean = true
+ if _, r := DecideKeep(View{Lock: Lock{Release: &other}}, self, "L1", LocalNow{}); r != "other-box" {
+ t.Errorf("order: %s", r)
+ }
+ // The zero LocalNow never keeps.
+ if k, r := DecideKeep(View{Lock: Lock{Release: &m}}, self, "L1", LocalNow{}); k || r != "no-record" {
+ t.Errorf("zero local state: %v %s", k, r)
+ }
+}