carlos / platform Public

region HA P1a Task 9: born-HA hosts: keep on proof, otherwise restore DB and files into a clean tree, on every box

ExecBackend.Acquire classifies in one place (acquireClassified): legacy
routes (sidecar, unprovisioned, non-instance) take the legacy acquire
before any record read, and an HA-format lock there refuses; provisioned
instances read the record facts (index, then Config.Record), failing
closed; an HA-format lock under a stale negative entry marks the host HA
and goes on to the HA path in the same call. HA hosts are admitted only on
the nested layout (haContained) before any lock request, asked again before
every spawn, and unit rows are refused through SplitBackend. restoreHA
keeps on DecideKeep's proof, otherwise sets the copy aside (DB, files,
release record, stale <host>.env) and restores the replica and the files
into a clean tree, never through the staging fallback. errLeaseRefused
answers 503 with Retry-After: 10. SetSameBoxProof is the same-box hook
(nil refuses). lease.CurrentSelf is the keep decision's identity.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 23ba923316cb904f7f0b95f67eb1ea08401e838d parent de9b96b
7 files changed, +1,427 −14
  • internal/activator/activator.go +23 −0
  • internal/activator/backend_exec.go +53 −14
  • internal/activator/backend_unit.go +12 −0
  • internal/activator/hawake.go +584 −0
  • internal/activator/hawake_test.go +729 −0
  • internal/lease/self.go +10 −0
  • internal/lease/self_test.go +16 −0
diff --git a/internal/activator/activator.go b/internal/activator/activator.go
index 196f8be8f..68c208fa5 100644
--- a/internal/activator/activator.go
+++ b/internal/activator/activator.go
@@ -72,10 +72,12 @@ import (
"github.com/carlosframework/platform/internal/cgroup"
"github.com/carlosframework/platform/internal/edge"
+ "github.com/carlosframework/platform/internal/hafresh"
"github.com/carlosframework/platform/internal/hostclaim"
"github.com/carlosframework/platform/internal/hostwrite"
"github.com/carlosframework/platform/internal/instancectl"
"github.com/carlosframework/platform/internal/lease"
+ "github.com/carlosframework/platform/internal/provision"
"github.com/carlosframework/platform/internal/registry"
"github.com/carlosframework/platform/internal/release"
)
@@ -104,6 +106,16 @@ type Config struct {
// children call in; the platform never dials a sidecar. Handed to every
// worker as CARLOS_AGENT_SOCKET. Empty falls back to DefaultAgentSocket.
AgentSocket string
+ // Record reads a host's record facts for region HA (P1a): its lifetime
+ // and whether it is born HA. ExecBackend asks it on a lifetime index
+ // miss, before the lease; an error fails the wake. The host wires it to
+ // provision.GetRecord on the deployment store. Nil: no record source,
+ // and only the row and the index say a host is HA.
+ Record func(ctx context.Context, rt registry.Route) (provision.LifetimeEntry, error)
+ // Self is this box's lease identity, asked at each HA wake (so an
+ // instance id that arrives late is picked up), for the keep decision.
+ // Nil: lease.CurrentSelf, the identity every lock this box writes names.
+ Self func() hafresh.Self
}
// DefaultAgentSocket is where the agent listens for its worker children.
@@ -5521,9 +5533,20 @@ func (a *Service) serve(w http.ResponseWriter, r *http.Request, rt registry.Rout
func (a *Service) serveWakeError(w http.ResponseWriter, r *http.Request, rt registry.Route, err error) bool {
var held *errLeaseHeld
var refused *errConfigRefused
+ var leaseRefused *errLeaseRefused
switch {
case errors.Is(err, ErrFenced):
maintenanceResponse(w, r)
+ case errors.As(err, &leaseRefused):
+ // The refusal outlives a request (region HA P1a: a born-HA host
+ // outside the nested layout, or an HA acquire's refusal): logged
+ // here, once per request, and answered with a long Retry-After.
+ if a.allowFilesDiagnostic(rt.Host, err, "http") {
+ log.Printf("activator: wake %s: %v", rt.Host, err)
+ }
+ w.Header().Set("Retry-After", strconv.Itoa(leaseRefusedRetryAfter))
+ edge.MarkAnswered(r)
+ http.Error(w, "instance failed to wake", http.StatusServiceUnavailable)
case errors.As(err, &refused):
// Quiet by design: the config guard logs once per host and
// publishes the refusal in the box's status snapshot. A line per
diff --git a/internal/activator/backend_exec.go b/internal/activator/backend_exec.go
index ebe4a1b72..1b75808ba 100644
--- a/internal/activator/backend_exec.go
+++ b/internal/activator/backend_exec.go
@@ -30,6 +30,7 @@ import (
"github.com/carlosframework/platform/internal/instanceupdates"
"github.com/carlosframework/platform/internal/lease"
"github.com/carlosframework/platform/internal/moves"
+ "github.com/carlosframework/platform/internal/provision"
"github.com/carlosframework/platform/internal/registry"
"github.com/carlosframework/platform/internal/release"
"github.com/carlosframework/platform/internal/safefile"
@@ -318,6 +319,28 @@ type ExecBackend struct {
// supersession after the preparation and before the launch (final
// review F1).
launchHook func(host string)
+
+ // Registry is the box's registry, which an HA host's restore imports its
+ // published wake state into (hostfiles.ImportWake). Nil: an HA restore
+ // whose manifest carries wake state fails.
+ Registry *registry.Registry
+ // FilesStore is the hibernate bucket as a release.Store, where an HA
+ // host's files are published (<hibernate prefix>/files/0/). Nil: an HA
+ // restore that needs the files fails.
+ FilesStore release.Store
+ // Lifetimes is the box's lifetime index (provision.LifetimeIndex),
+ // filled by the reconcile pass and read by the HA classification
+ // before every wake. Nil: every provisioned instance reads its record.
+ Lifetimes *provision.LifetimeIndex
+ // StartupSwept reports whether this agent's startup sweep proved every
+ // instance unit stopped (the same-box recovery proof, Task 12). Nil:
+ // never proven.
+ StartupSwept func() bool
+ // sameBoxProof is SetSameBoxProof's hook. Nil refuses every same-box
+ // takeover of an expired HA lock.
+ sameBoxProof func(ctx context.Context, rt registry.Route) func() (bool, error)
+ // haWakes is each host's last Acquire classification (hawake.go).
+ haWakes haWakes
}
// hostGate serialises everything that touches one host's group once Strict
@@ -716,7 +739,6 @@ func (b *ExecBackend) LiveVersion(host string) (string, error) {
// *HeldError is this package's only view of it) so the edge can 503 with a
// Retry-After that tracks the holder's expiry.
func (b *ExecBackend) Acquire(ctx context.Context, rt registry.Route) (Lease, error) {
- host := rt.Host
// Admission before the lease: the instance's config has to be
// providable from THIS box, or it must not be the one that starts it.
// Here, not in doWake, because this is the only place an instance or
@@ -724,19 +746,9 @@ func (b *ExecBackend) Acquire(ctx context.Context, rt registry.Route) (Lease, er
if err := b.AdmitConfig(ctx, rt); err != nil {
return nil, err
}
- held, err := lease.Acquire(ctx, b.Cfg.Bucket, b.Cfg.hibernatePrefix(host), b.Cfg.Region)
- if err != nil {
- var he *lease.HeldError
- if errors.As(err, &he) {
- retry := time.Until(he.ExpiresAt)
- if retry < time.Second {
- retry = time.Second
- }
- return nil, &errLeaseHeld{holder: he.Owner, retryAfter: retry}
- }
- return nil, err
- }
- return &execLease{held: held, defaultDB: b.pathsFor(rt).dbPath}, nil
+ // Then the region HA classification (hawake.go): a legacy route, a
+ // host that is not HA, or an HA one, each to its own acquire.
+ return b.acquireClassified(ctx, rt)
}
// AdmitConfig asks the config gate whether this box can provide rt's config:
@@ -799,6 +811,11 @@ func (b *ExecBackend) Restore(ctx context.Context, rt registry.Route) (bool, err
return false, err
}
if seedRestores(src) {
+ // A born-HA host is never seeded (P1a): the seed fallback is the
+ // legacy restore, so an HA host with a seed refuses.
+ if _, ok := b.haAcquired(rt.Host); ok {
+ return false, fmt.Errorf("%s: refusing to restore: a high availability host with a seed", rt.Host)
+ }
return b.seededRestore(ctx, rt, src)
}
return b.restorePlain(ctx, rt)
@@ -808,6 +825,13 @@ func (b *ExecBackend) Restore(ctx context.Context, rt registry.Route) (bool, err
// then the staging fallback, then the host's own replica, and fresh only
// when there is none of the three.
func (b *ExecBackend) restorePlain(ctx context.Context, rt registry.Route) (bool, error) {
+ // An HA host restores by the HA rules (hawake.go), never through the
+ // warm cache or the staging fallback below.
+ if s, ha, err := b.haRestore(ctx, rt); err != nil {
+ return false, err
+ } else if ha {
+ return b.restoreHA(ctx, rt, s.view, s.view.Absent)
+ }
host, dbPath := rt.Host, b.pathsFor(rt).dbPath
// A failed seed whose processes were not proven gone left its database
// and an obligation (Task 8): it is answered before the database can
@@ -929,6 +953,9 @@ var restoreReplica = lease.Restore
// through its own launch file and unit, a fenced or conflicting row
// refuses, and a flat or foreign row seeds through today's exec child.
func (b *ExecBackend) Seed(ctx context.Context, rt registry.Route) error {
+ if err := b.haSpawnGate(rt); err != nil {
+ return err
+ }
p := b.pathsFor(rt)
switch p.layout {
case LayoutNested:
@@ -1871,6 +1898,9 @@ func (b *ExecBackend) BuildIdentity(rt registry.Route, build string) (release.St
// after every refusal of rootfsGates, and never through the layout switch:
// it is nested or it does not start.
func (b *ExecBackend) Start(ctx context.Context, rt registry.Route) (Proc, string, error) {
+ if err := b.haSpawnGate(rt); err != nil {
+ return nil, "", err
+ }
if rt.Runtime == registry.RuntimeRootfsV1 {
if err := b.rootfsGates(rt); err != nil {
return nil, "", err
@@ -1904,6 +1934,9 @@ func (b *ExecBackend) Start(ctx context.Context, rt registry.Route) (Proc, strin
// (left there by an earlier agent process, whose counter started at 1 like
// this one's). A sibling generation's path is never touched.
func (b *ExecBackend) StartGen(ctx context.Context, rt registry.Route, n uint64, perGen bool) (Proc, Gen, error) {
+ if err := b.haSpawnGate(rt); err != nil {
+ return nil, Gen{}, err
+ }
if rt.Runtime == registry.RuntimeRootfsV1 {
return b.startRootfsGen(ctx, rt, n, perGen, nil)
}
@@ -1925,6 +1958,9 @@ func (b *ExecBackend) StartGen(ctx context.Context, rt registry.Route, n uint64,
// asked, and root may have repointed the link since the record, which
// would run A's bytes under B's limits.
func (b *ExecBackend) StartGenExe(ctx context.Context, rt registry.Route, n uint64, perGen bool, id release.StagedIdentity) (Proc, Gen, error) {
+ if err := b.haSpawnGate(rt); err != nil {
+ return nil, Gen{}, err
+ }
if rt.Runtime == registry.RuntimeRootfsV1 {
return b.startRootfsGen(ctx, rt, n, perGen, &id)
}
@@ -2991,6 +3027,9 @@ func (b *ExecBackend) HasSidecar(rt registry.Route) bool {
// StartSidecar dispatches by layout, the same way Start does.
func (b *ExecBackend) StartSidecar(ctx context.Context, rt registry.Route) (Proc, error) {
+ if err := b.haSpawnGate(rt); err != nil {
+ return nil, err
+ }
p := b.pathsFor(rt)
switch p.layout {
case LayoutNested:
diff --git a/internal/activator/backend_unit.go b/internal/activator/backend_unit.go
index e6b64abb3..9a73d9240 100644
--- a/internal/activator/backend_unit.go
+++ b/internal/activator/backend_unit.go
@@ -299,6 +299,18 @@ func (b *SplitBackend) pick(rt registry.Route) Backend {
}
func (b *SplitBackend) Acquire(ctx context.Context, rt registry.Route) (Lease, error) {
+ // A unit-backed row never reaches ExecBackend.Acquire, where the region
+ // HA classification lives: a born-HA host there is refused (it is not
+ // contained), asked of the exec half before the unit's own acquire.
+ if rt.Backing == registry.BackingUnit {
+ if g, ok := b.Exec.(interface {
+ refuseHAUnit(context.Context, registry.Route) error
+ }); ok {
+ if err := g.refuseHAUnit(ctx, rt); err != nil {
+ return nil, err
+ }
+ }
+ }
return b.pick(rt).Acquire(ctx, rt)
}
diff --git a/internal/activator/hawake.go b/internal/activator/hawake.go
new file mode 100644
index 000000000..b958fb572
--- /dev/null
+++ b/internal/activator/hawake.go
@@ -0,0 +1,584 @@
+package activator
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "io/fs"
+ "log"
+ "path/filepath"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/carlosframework/platform/internal/hafresh"
+ "github.com/carlosframework/platform/internal/hostfiles"
+ "github.com/carlosframework/platform/internal/instancefs"
+ "github.com/carlosframework/platform/internal/lease"
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+// Region HA P1a, the wake (spec §5, §7.3): a host born HA (its record's ha,
+// or its lock HA-format) is acquired through lease.AcquireHA, only in the
+// nested layout, and woken by keeping its local copy on positive proof
+// (hafresh.DecideKeep) or else restoring the database and the files into
+// a clean tree. Every box applies these rules to an HA host, whatever its
+// own CARLOS_REGION_HA. Every other host takes today's path unchanged.
+
+// errLeaseRefused: the wake was refused before or by the lease, with
+// nothing written (a born-HA host outside the nested layout, an HA-format
+// lock on a route with no instance record, or one of the HA acquire's
+// refusals). The condition outlives a request, so the edge answers 503 with
+// Retry-After: 10.
+type errLeaseRefused struct{ reason string }
+
+func (e *errLeaseRefused) Error() string { return "instance lease refused: " + e.reason }
+
+// leaseRefusedRetryAfter is the Retry-After, in seconds, of a refused wake.
+const leaseRefusedRetryAfter = 10
+
+// haLease is the HA side of the Lease execLease hands back (*lease.Held's).
+type haLease interface {
+ HA() bool
+ View() hafresh.View
+ SetMonitorInterval(d time.Duration)
+}
+
+// haRep is the HA side of the Rep an HA lease replicates through.
+type haRep interface {
+ HA() bool
+ Finish(ctx context.Context) (uint64, error)
+ ReleaseMarker(ctx context.Context, m hafresh.Marker) error
+}
+
+var (
+ _ haLease = (*execLease)(nil)
+ _ haRep = (*lease.Replicator)(nil)
+)
+
+func (l *execLease) HA() bool { return l.held.HA() }
+func (l *execLease) View() hafresh.View { return l.held.View() }
+func (l *execLease) SetMonitorInterval(d time.Duration) { l.held.SetMonitorInterval(d) }
+
+// The lease calls behind seams, so the classification is testable against
+// the lock fixture with a short-circuit where a test needs one.
+var (
+ acquireLegacyLease = lease.Acquire
+ acquireHALease = lease.AcquireHA
+)
+
+// haLegacyRoute reports a route that is legacy before any record lookup
+// (r3.4): a sidecar, a route the provision pass did not mint (hand-added),
+// or any kind but an instance. It keeps today's acquire, and an HA-format
+// lock under it refuses the wake.
+func haLegacyRoute(rt registry.Route) bool {
+ return rt.IsSidecar() || !rt.Provisioned || rt.Kind != "instance"
+}
+
+// isHA is the HA classification, its one place: record facts only, never
+// the lock. A legacy route (haLegacyRoute) is not HA and reads nothing.
+// Otherwise the lifetime index answers first; a miss, or an entry with no
+// lifetime (a host only marked HA), reads the record (Config.Record). A
+// failed read is an error, and the caller fails the wake: it never falls
+// back to legacy. The row's sticky mark (registry.Route.HA) and the index's
+// sticky marks only ever add HA. A nil Config.Record is a box with no
+// record source: the row and the index decide, and an HA host there has no
+// lifetime, so it never keeps a local copy.
+func (b *ExecBackend) isHA(ctx context.Context, rt registry.Route) (provision.LifetimeEntry, bool, error) {
+ if haLegacyRoute(rt) {
+ return provision.LifetimeEntry{}, false, nil
+ }
+ var e provision.LifetimeEntry
+ var ok bool
+ if b.Lifetimes != nil {
+ e, ok = b.Lifetimes.Lookup(rt.Host)
+ }
+ if (!ok || e.ID == "") && b.Cfg.Record != nil {
+ got, err := b.Cfg.Record(ctx, rt)
+ if err != nil {
+ return provision.LifetimeEntry{}, false, fmt.Errorf("%s: read the instance record: %w", rt.Host, err)
+ }
+ got.HA = got.HA || e.HA
+ e = got
+ }
+ e.HA = e.HA || rt.HA
+ return e, e.HA, nil
+}
+
+// IsHA is isHA for the rest of the box (internal/host): whether rt is an
+// HA host, by the one classification.
+func (b *ExecBackend) IsHA(ctx context.Context, rt registry.Route) (bool, error) {
+ _, ha, err := b.isHA(ctx, rt)
+ return ha, err
+}
+
+// haContained is the containment admission (r3.2): nil only for a row in
+// the nested layout, not unit-backed, on a box whose nested gate passes
+// (the control channel configured and NestedOK). An HA host never runs
+// anywhere else, and there is no uncontained fallback.
+//
+// The box half is nestedReady, nestedGate's own: nestedGate also refuses
+// every rootfs row, because it guards the binary launch, and a rootfs row
+// is nested under root's control service too (its start asks nestedReady).
+func (b *ExecBackend) haContained(rt registry.Route) error {
+ if rt.Backing == registry.BackingUnit {
+ return errors.New("the row is unit-backed")
+ }
+ if p := b.pathsFor(rt); p.layout != LayoutNested {
+ reason := string(p.layout)
+ if p.reason != "" {
+ reason += ": " + p.reason
+ }
+ return fmt.Errorf("the row's layout is %s", reason)
+ }
+ return b.nestedReady(rt)
+}
+
+func refusedUncontained(err error) error {
+ return &errLeaseRefused{reason: "high availability needs the nested layout: " + err.Error()}
+}
+
+// haWake is what Acquire classified for a host, for the Restore after it
+// (and the spawns under that lease): whether it took the HA path, the view
+// it classified before its take, and the host's lifetime entry.
+type haWake struct {
+ ha bool
+ view hafresh.View
+ entry provision.LifetimeEntry
+}
+
+// haWakes holds each host's last Acquire classification.
+type haWakes struct {
+ mu sync.Mutex
+ m map[string]haWake
+}
+
+func (w *haWakes) set(host string, s haWake) {
+ w.mu.Lock()
+ defer w.mu.Unlock()
+ if w.m == nil {
+ w.m = map[string]haWake{}
+ }
+ w.m[host] = s
+}
+
+func (w *haWakes) get(host string) (haWake, bool) {
+ w.mu.Lock()
+ defer w.mu.Unlock()
+ s, ok := w.m[host]
+ return s, ok
+}
+
+func (w *haWakes) forget(host string) {
+ w.mu.Lock()
+ defer w.mu.Unlock()
+ delete(w.m, host)
+}
+
+// SetSameBoxProof installs the same-box emptiness proof the HA acquire
+// hands lease (hafresh.Proofs.SameBoxEmpty) for a host this box's own
+// instance id last held and that expired. Nil, the default, refuses every
+// same-box takeover. Call it before the Service starts.
+func (b *ExecBackend) SetSameBoxProof(f func(ctx context.Context, rt registry.Route) func() (bool, error)) {
+ b.sameBoxProof = f
+}
+
+// self is this box's lease identity: Config.Self, else lease's own.
+func (b *ExecBackend) self() hafresh.Self {
+ if b.Cfg.Self != nil {
+ return b.Cfg.Self()
+ }
+ return lease.CurrentSelf()
+}
+
+// leaseError maps a lease package error onto the activator's: a held lease
+// is errLeaseHeld (503 with the holder's Retry-After), an HA acquire's
+// refusal errLeaseRefused, and anything else as it is (an obligation that
+// could not be settled, a missing obligation store, a store error).
+func leaseError(err error) error {
+ var he *lease.HeldError
+ if errors.As(err, &he) {
+ retry := time.Until(he.ExpiresAt)
+ if retry < time.Second {
+ retry = time.Second
+ }
+ return &errLeaseHeld{holder: he.Owner, retryAfter: retry}
+ }
+ var re *lease.RefusedError
+ if errors.As(err, &re) {
+ return &errLeaseRefused{reason: re.Reason}
+ }
+ return err
+}
+
+// acquireClassified is Acquire after the config gate: the classification
+// order (r3.1, r3.2, r3.4), in one place.
+//
+// 1. A legacy route takes the legacy acquire before any record lookup; an
+// HA-format lock there refuses the wake.
+// 2. Otherwise the record facts (isHA); a failed read fails the wake.
+// 3. Not HA: the legacy acquire. An HA-format lock (a stale index entry, or
+// a host re-created born HA) marks the host HA for good and goes on to 4
+// in the same call.
+// 4. HA: the containment admission, before any lock request, then the HA
+// acquire.
+func (b *ExecBackend) acquireClassified(ctx context.Context, rt registry.Route) (Lease, error) {
+ host := rt.Host
+ prefix := b.Cfg.hibernatePrefix(host)
+ b.haWakes.forget(host)
+ if haLegacyRoute(rt) {
+ held, err := acquireLegacyLease(ctx, b.Cfg.Bucket, prefix, b.Cfg.Region)
+ if err != nil {
+ var hl *lease.HALockError
+ if errors.As(err, &hl) {
+ return nil, &errLeaseRefused{reason: "ha lock on a route with no instance record"}
+ }
+ return nil, leaseError(err)
+ }
+ b.haWakes.set(host, haWake{})
+ return &execLease{held: held, defaultDB: b.pathsFor(rt).dbPath}, nil
+ }
+ entry, ha, err := b.isHA(ctx, rt)
+ if err != nil {
+ return nil, fmt.Errorf("refusing to wake: %w", err)
+ }
+ if !ha {
+ held, err := acquireLegacyLease(ctx, b.Cfg.Bucket, prefix, b.Cfg.Region)
+ if err == nil {
+ b.haWakes.set(host, haWake{entry: entry})
+ return &execLease{held: held, defaultDB: b.pathsFor(rt).dbPath}, nil
+ }
+ var hl *lease.HALockError
+ if !errors.As(err, &hl) {
+ return nil, leaseError(err)
+ }
+ if b.Lifetimes != nil {
+ b.Lifetimes.MarkHA(host)
+ }
+ entry.HA = true
+ log.Printf("activator: %s: the lock is HA-format; the host is HA from now on", host)
+ }
+ if err := b.haContained(rt); err != nil {
+ return nil, refusedUncontained(err)
+ }
+ var proofs hafresh.Proofs
+ if b.sameBoxProof != nil {
+ proofs.SameBoxEmpty = b.sameBoxProof(ctx, rt)
+ }
+ held, err := acquireHALease(ctx, b.Cfg.Bucket, prefix, b.Cfg.Region, hafresh.Marker{Lifetime: entry.ID}, proofs)
+ if err != nil {
+ return nil, leaseError(err)
+ }
+ b.haWakes.set(host, haWake{ha: true, view: held.View(), entry: entry})
+ return &execLease{held: held, defaultDB: b.pathsFor(rt).dbPath}, nil
+}
+
+// haAcquired reports whether host's last Acquire took the HA path, and
+// what it classified.
+func (b *ExecBackend) haAcquired(host string) (haWake, bool) {
+ s, ok := b.haWakes.get(host)
+ return s, ok && s.ha
+}
+
+// haSpawnGate is the containment admission again before every spawn of a
+// host this backend acquired HA (the wake's start, a generation start, a
+// co-spawned sidecar, a seed): a layout change mid-life refuses the next
+// spawn instead of running it uncontained.
+func (b *ExecBackend) haSpawnGate(rt registry.Route) error {
+ if _, ok := b.haAcquired(rt.Host); !ok {
+ return nil
+ }
+ if err := b.haContained(rt); err != nil {
+ return refusedUncontained(err)
+ }
+ return nil
+}
+
+// refuseHAUnit is SplitBackend's question for a unit-backed row, which
+// never reaches ExecBackend.Acquire: an HA host there is refused (it is
+// not contained), and a failed record read fails the wake.
+func (b *ExecBackend) refuseHAUnit(ctx context.Context, rt registry.Route) error {
+ _, ha, err := b.isHA(ctx, rt)
+ if err != nil {
+ return fmt.Errorf("refusing to wake: %w", err)
+ }
+ if ha {
+ return refusedUncontained(errors.New("the row is unit-backed"))
+ }
+ return nil
+}
+
+// haRestore is Restore's question for an HA host: the classification its
+// Acquire recorded, or, with none recorded, the record facts (a Restore
+// that did not follow this backend's Acquire). An HA host with no HA
+// acquire behind it fails: its restore needs the view that acquire
+// classified.
+func (b *ExecBackend) haRestore(ctx context.Context, rt registry.Route) (haWake, bool, error) {
+ if s, ok := b.haWakes.get(rt.Host); ok {
+ return s, s.ha, nil
+ }
+ if haLegacyRoute(rt) {
+ return haWake{}, false, nil
+ }
+ _, ha, err := b.isHA(ctx, rt)
+ if err != nil {
+ return haWake{}, false, err
+ }
+ if ha {
+ return haWake{}, false, fmt.Errorf("%s: a high availability host restored without its HA lease", rt.Host)
+ }
+ return haWake{}, false, nil
+}
+
+// restoreHA is an HA host's restore, in place of restorePlain (and never
+// the staging fallback). first, an absent lock, is a first wake: the
+// prefix was proven empty by the acquire, so the local copy is set aside
+// and the wake is fresh, with an empty tree. Otherwise the local copy is
+// kept only on proof (hafresh.DecideKeep over v, the view the acquire
+// classified); anything else sets it aside and restores the database and
+// the files into a clean tree. A local state that cannot be read restores.
+// Every error fails the wake, and fresh is false on every error path.
+func (b *ExecBackend) restoreHA(ctx context.Context, rt registry.Route, v hafresh.View, first bool) (fresh bool, err error) {
+ host := rt.Host
+ if err := b.haContained(rt); err != nil {
+ return false, refusedUncontained(err)
+ }
+ p := b.pathsFor(rt)
+ // An earlier seed whose processes were not proven gone is answered
+ // first, as restorePlain does, and a database a foreign seed left is
+ // purged: neither is a copy this box released.
+ if err := b.settleSeedObligation(ctx, rt, p.dbPath); err != nil {
+ return false, err
+ }
+ if err := reconcileSeedMarker(rt, p.dbPath); err != nil {
+ return false, err
+ }
+ if first {
+ if err := b.setAside(p, host); err != nil {
+ return false, fmt.Errorf("%s: set aside the local copy: %w", host, err)
+ }
+ log.Printf("activator: %s: restored (%s): first wake, the prefix proven empty, booting fresh", host, hafresh.KeepNoMarker)
+ return true, nil
+ }
+ lifetime, err := b.haLifetime(ctx, rt)
+ if err != nil {
+ return false, err
+ }
+ now, rerr := readLocalNow(p, host)
+ keep, reason := false, "local-unreadable"
+ if rerr == nil {
+ keep, reason = hafresh.DecideKeep(v, b.self(), lifetime, now)
+ } else {
+ log.Printf("activator: %s: %v", host, rerr)
+ }
+ if keep {
+ log.Printf("activator: %s: kept local", host)
+ return false, nil
+ }
+ if err := b.setAside(p, host); err != nil {
+ return false, fmt.Errorf("%s: set aside the local copy: %w", host, err)
+ }
+ restored, err := restoreReplica(ctx, p.dbPath, b.Cfg.Bucket, b.Cfg.hibernatePrefix(host), b.Cfg.Region)
+ if err != nil {
+ return false, err
+ }
+ if restored {
+ if err := lease.CheckDB(p.dbPath); err != nil {
+ // The same rule as restorePlain: a corrupt restore never serves
+ // and never boots fresh. It is quarantined (one, the newest),
+ // or removed if it cannot be, and the next wake restores again.
+ dbDir, dbName := filepath.Dir(p.dbPath), filepath.Base(p.dbPath)
+ if qerr := errors.Join(removeIfThere(dbDir, dbName+quarantineSuffix), renameIfThere(dbDir, dbName, dbName+quarantineSuffix)); qerr != nil {
+ _ = removeIfThere(dbDir, dbName)
+ }
+ _ = removeIfThere(dbDir, dbName+"-wal")
+ _ = removeIfThere(dbDir, dbName+"-shm")
+ return false, fmt.Errorf("restored replica for %s is corrupt: %w", host, err)
+ }
+ }
+ if err := b.restoreFilesClean(ctx, rt); err != nil {
+ return false, fmt.Errorf("%s: restore files: %w", host, err)
+ }
+ log.Printf("activator: %s: restored (%s)", host, reason)
+ return !restored, nil
+}
+
+// haLifetime is the host's lifetime ID for the keep decision: the one its
+// Acquire classified with, else the record facts read now.
+func (b *ExecBackend) haLifetime(ctx context.Context, rt registry.Route) (string, error) {
+ if s, ok := b.haAcquired(rt.Host); ok && s.entry.ID != "" {
+ return s.entry.ID, nil
+ }
+ e, _, err := b.isHA(ctx, rt)
+ if err != nil {
+ return "", err
+ }
+ return e.ID, nil
+}
+
+// staleSuffix names what setAside keeps of the copy it set aside: one, the
+// newest; the one before is removed.
+const staleSuffix = ".stale"
+
+// setAside clears the host's local copy for a restore into a clean tree:
+// the database becomes <db>.stale (its WAL <db>.stale-wal), the files
+// directory <host>.stale; the shared-memory file, the local release record,
+// a seed marker, litestream's local state and the host's own env file
+// (<host>.env) are removed. The previous stale copy is removed first, so
+// there is only ever one. Every operation goes through instancefs, beneath
+// directories opened without following a link, since a nested host's
+// directory is the tenant's to write. Anything absent is skipped; any other
+// failure is returned and fails the wake, since a restore over a tree that
+// was not cleared could serve old files.
+func (b *ExecBackend) setAside(p instancePaths, host string) error {
+ dbDir, dbName := filepath.Dir(p.dbPath), filepath.Base(p.dbPath)
+ steps := []func() error{
+ func() error { return removeIfThere(dbDir, dbName+staleSuffix) },
+ func() error { return removeIfThere(dbDir, dbName+staleSuffix+"-wal") },
+ func() error { return renameIfThere(dbDir, dbName, dbName+staleSuffix) },
+ func() error { return renameIfThere(dbDir, dbName+"-wal", dbName+staleSuffix+"-wal") },
+ func() error { return removeIfThere(dbDir, dbName+"-shm") },
+ func() error { return removeIfThere(dbDir, filepath.Base(recordPath(p, host))) },
+ func() error { return removeIfThere(dbDir, dbName+SeedMarkerSuffix) },
+ func() error { return removeAllIfThere(p.dataDir, host+staleSuffix) },
+ func() error { return renameIfThere(p.dataDir, host, host+staleSuffix) },
+ func() error { return removeIfThere(filepath.Dir(p.envFile), filepath.Base(p.envFile)) },
+ }
+ for _, step := range steps {
+ if err := step(); err != nil {
+ return err
+ }
+ }
+ // litestream's own local state describes the database set aside.
+ PurgeLocalDBArtifacts(p.dbPath, false)
+ for _, dir := range uniqueDirs(dbDir, p.dataDir, filepath.Dir(p.envFile)) {
+ if err := syncDirIfThere(dir); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func gone(err error) bool { return errors.Is(err, fs.ErrNotExist) }
+
+func removeIfThere(dir, name string) error {
+ if err := instancefs.RemoveBeneath(dir, name); err != nil && !gone(err) {
+ return err
+ }
+ return nil
+}
+
+func removeAllIfThere(dir, name string) error {
+ if err := instancefs.RemoveAllBeneath(dir, name); err != nil && !gone(err) {
+ return err
+ }
+ return nil
+}
+
+func renameIfThere(dir, from, to string) error {
+ if err := instancefs.RenameBetween(dir, from, dir, to); err != nil && !gone(err) {
+ return err
+ }
+ return nil
+}
+
+func syncDirIfThere(dir string) error {
+ f, err := instancefs.OpenDirBeneath(dir, ".")
+ if err != nil {
+ if gone(err) {
+ return nil
+ }
+ return err
+ }
+ defer f.Close()
+ return f.Sync()
+}
+
+func uniqueDirs(dirs ...string) []string {
+ var out []string
+ seen := map[string]bool{}
+ for _, d := range dirs {
+ if !seen[d] {
+ seen[d] = true
+ out = append(out, d)
+ }
+ }
+ return out
+}
+
+// filesPrefix is the host's files generation prefix in the hibernate
+// bucket: <hibernate prefix>/files/0/.
+func (b *ExecBackend) filesPrefix(host string) string {
+ return b.Cfg.hibernatePrefix(host) + "/files/0/"
+}
+
+// restoreSuffix names the directory restoreFilesClean restores into
+// before it renames it over the files directory.
+const restoreSuffix = ".restore"
+
+// restoreFilesClean restores the host's published files into a clean
+// tree: into <host>.restore/ (a leftover one removed first), which is
+// renamed into place as the files directory, never over one (setAside
+// moved the old one away; anything there now refuses). The manifest's
+// env item becomes <host>.env, and its wake state goes into the registry
+// (hostfiles.ImportWake). A host with no manifest gets an empty files
+// directory and no env file. Every failure fails the wake.
+func (b *ExecBackend) restoreFilesClean(ctx context.Context, rt registry.Route) error {
+ host := rt.Host
+ if b.FilesStore == nil {
+ return errors.New("no files store configured")
+ }
+ p := b.pathsFor(rt)
+ prefix := b.filesPrefix(host)
+ tmp := host + restoreSuffix
+ if err := removeAllIfThere(p.dataDir, tmp); err != nil {
+ return err
+ }
+ if _, err := instancefs.EnsureDirBeneath(p.dataDir, tmp, 0o700); err != nil {
+ return err
+ }
+ root, err := instancefs.OpenRootBeneath(p.dataDir, tmp)
+ if err != nil {
+ return err
+ }
+ // One read of the manifest; none is an empty one, and an empty tree.
+ rm, st, err := hostfiles.RestoreRoot(ctx, b.FilesStore, prefix, root, nil)
+ root.Close()
+ if err != nil {
+ return err
+ }
+ if len(st.Skipped) > 0 {
+ log.Printf("activator: %s: %d file(s) the manifest holds as unpublished were not restored: %s", host, len(st.Skipped), strings.Join(st.Skipped, ", "))
+ }
+ if err := instancefs.RenameBetweenNoReplace(p.dataDir, tmp, p.dataDir, host); err != nil {
+ return err
+ }
+ if _, ok := rm.Platform[hostfiles.EnvItem]; ok {
+ env, err := hostfiles.ReadPlatform(ctx, b.FilesStore, prefix, rm, hostfiles.EnvItem, nil)
+ if err != nil {
+ return err
+ }
+ if err := instancefs.WriteAtomic(filepath.Dir(p.envFile), filepath.Base(p.envFile), env, 0o600); err != nil {
+ return err
+ }
+ }
+ for _, dir := range uniqueDirs(p.dataDir, filepath.Dir(p.envFile)) {
+ if err := syncDirIfThere(dir); err != nil {
+ return err
+ }
+ }
+ ws, ok, err := hostfiles.LoadWake(ctx, b.FilesStore, prefix, rm, nil)
+ if err != nil {
+ return err
+ }
+ if ok {
+ if b.Registry == nil {
+ return errors.New("the files manifest carries wake state and no registry is configured")
+ }
+ if err := hostfiles.ImportWake(b.Registry, host, ws); err != nil {
+ return err
+ }
+ }
+ return nil
+}
diff --git a/internal/activator/hawake_test.go b/internal/activator/hawake_test.go
new file mode 100644
index 000000000..65a98e72b
--- /dev/null
+++ b/internal/activator/hawake_test.go
@@ -0,0 +1,729 @@
+package activator
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/domains"
+ "github.com/carlosframework/platform/internal/hafresh"
+ "github.com/carlosframework/platform/internal/hostfiles"
+ "github.com/carlosframework/platform/internal/lease"
+ "github.com/carlosframework/platform/internal/lease/locktest"
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+// haFix is one HA backend's test state: the lock fixture behind lease,
+// the deployment store's records the Record seam reads, and the counters
+// the witnesses assert on.
+type haFix struct {
+ fx *locktest.LockFixture
+ ctl *fakeControl
+ mu sync.Mutex
+ records map[string]provision.Record // host -> the record in the deployment store
+ gets int
+ failRead bool
+ restores int
+ lifetime string // the HA record's lifetime (L1)
+ // applied counts, by key, the writes that changed an object (a refused
+ // conditional write is logged by the fixture but changes nothing).
+ applied map[string]int
+ before map[string][]byte
+}
+
+var haFixtures sync.Map // *ExecBackend -> *haFix
+
+func haFixOf(b *ExecBackend) *haFix {
+ f, ok := haFixtures.Load(b)
+ if !ok {
+ panic("not an HA test backend")
+ }
+ return f.(*haFix)
+}
+
+func haRecord(host string, ha bool) provision.Record {
+ return provision.Record{Schema: 1, Host: host, App: "shop", Account: domains.Sqid(2), Channel: "stable",
+ CreatedAt: time.Date(2026, 10, 26, 9, 0, 0, 0, time.UTC), HA: ha}
+}
+
+// haBackendEmptyIndex is a production-shaped ExecBackend for a provisioned
+// instance on the nested layout: the real lease against the lock fixture
+// (this box is Self{a, i-a}, an obligation store set), NestedOK nil with a
+// control channel, StartupSwept true, a files store, a registry holding
+// the route, the restoreReplica seam counting calls, and a record in the
+// deployment store saying the host is HA. Its lifetime index is empty.
+func haBackendEmptyIndex(t *testing.T, host string) (*ExecBackend, registry.Route) {
+ t.Helper()
+ fx := locktest.NewLockFixture(t)
+ if err := lease.SetObligationDir(t.TempDir()); err != nil {
+ t.Fatal(err)
+ }
+ lease.SetSelf(hafresh.Self{Ref: "a", IID: "i-a"})
+ root := t.TempDir()
+ b := testExecBackend(t)
+ b.Cfg.Bucket = fx.Bucket
+ b.DataDir = filepath.Join(root, "data")
+ b.RunDirOverride = filepath.Join(root, "run")
+ ctl := &fakeControl{}
+ b.Control = ctl
+ b.StartupSwept = func() bool { return true }
+ b.FilesStore = release.NewDirStore(t.TempDir())
+ b.Lifetimes = &provision.LifetimeIndex{}
+ if err := os.MkdirAll(b.DataDir, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ rt := nestedRoute(b, host)
+ rt.Provisioned, rt.App, rt.Account, rt.Status = true, "shop", domains.Sqid(2), "ready"
+ reg, err := registry.Open(filepath.Join(t.TempDir(), "registry.db"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := reg.Upsert(rt); err != nil {
+ t.Fatal(err)
+ }
+ b.Registry = reg
+ rec := haRecord(host, true)
+ e, err := provision.LifetimeEntryOf(rec)
+ if err != nil {
+ t.Fatal(err)
+ }
+ h := &haFix{fx: fx, ctl: ctl, records: map[string]provision.Record{host: rec}, lifetime: e.ID,
+ applied: map[string]int{}, before: map[string][]byte{}}
+ body := func(key string) []byte {
+ prefix, _ := strings.CutSuffix(key, "/lock.json")
+ return fx.LockBody(prefix)
+ }
+ fx.BeforeWrite(func(_, key string) {
+ b := body(key)
+ h.mu.Lock()
+ h.before[key] = b
+ h.mu.Unlock()
+ })
+ fx.AfterWrite(func(_, key string) {
+ after := body(key)
+ h.mu.Lock()
+ if string(after) != string(h.before[key]) {
+ h.applied[key]++
+ }
+ h.mu.Unlock()
+ })
+ b.Cfg.Record = func(_ context.Context, rt registry.Route) (provision.LifetimeEntry, error) {
+ h.mu.Lock()
+ defer h.mu.Unlock()
+ h.gets++
+ if h.failRead {
+ return provision.LifetimeEntry{}, errors.New("deployment store unavailable")
+ }
+ rec, ok := h.records[rt.Host]
+ if !ok {
+ return provision.LifetimeEntry{}, os.ErrNotExist
+ }
+ return provision.LifetimeEntryOf(rec)
+ }
+ old := restoreReplica
+ restoreReplica = func(_ context.Context, dbPath, _, _, _ string) (bool, error) {
+ h.mu.Lock()
+ h.restores++
+ h.mu.Unlock()
+ if err := os.MkdirAll(filepath.Dir(dbPath), 0o700); err != nil {
+ return false, err
+ }
+ return true, writeMinimalSQLite(dbPath)
+ }
+ t.Cleanup(func() { restoreReplica = old })
+ haFixtures.Store(b, h)
+ t.Cleanup(func() { haFixtures.Delete(b) })
+ return b, rt
+}
+
+// haBackend is haBackendEmptyIndex with the record in the index too.
+func haBackend(t *testing.T, host string) (*ExecBackend, registry.Route) {
+ t.Helper()
+ b, rt := haBackendEmptyIndex(t, host)
+ b.Lifetimes.Merge(map[string]provision.Record{host: haFixOf(b).records[host]})
+ return b, rt
+}
+
+// haBackendIndexed is haBackendEmptyIndex whose index holds a non-HA
+// record of host (a stale negative entry).
+func haBackendIndexed(t *testing.T, host string) (*ExecBackend, registry.Route) {
+ t.Helper()
+ b, rt := haBackendEmptyIndex(t, host)
+ b.Lifetimes.Merge(map[string]provision.Record{host: haRecord(host, false)})
+ return b, rt
+}
+
+func recordGets(b *ExecBackend) int {
+ h := haFixOf(b)
+ h.mu.Lock()
+ defer h.mu.Unlock()
+ return h.gets
+}
+
+func restoreCalls(b *ExecBackend) int {
+ h := haFixOf(b)
+ h.mu.Lock()
+ defer h.mu.Unlock()
+ return h.restores
+}
+
+func failRecordReads(b *ExecBackend) {
+ h := haFixOf(b)
+ h.mu.Lock()
+ h.failRead = true
+ h.mu.Unlock()
+}
+
+func lockKeyOf(b *ExecBackend, rt registry.Route) string {
+ return b.Cfg.hibernatePrefix(rt.Host) + "/lock.json"
+}
+
+// lockRequests counts every request about rt's lock: its reads and writes,
+// and the prefix listing a first wake makes.
+func lockRequests(t *testing.T, b *ExecBackend, rt registry.Route) int {
+ t.Helper()
+ n := 0
+ for _, r := range haFixOf(b).fx.Requests() {
+ if strings.HasSuffix(r, " "+lockKeyOf(b, rt)) || strings.HasPrefix(r, "LIST "+b.Cfg.hibernatePrefix(rt.Host)) {
+ n++
+ }
+ }
+ return n
+}
+
+// lockWrites counts the writes that changed rt's lock (a conditional
+// create refused because a lock is there writes nothing).
+func lockWrites(t *testing.T, b *ExecBackend, rt registry.Route) int {
+ t.Helper()
+ h := haFixOf(b)
+ h.mu.Lock()
+ defer h.mu.Unlock()
+ return h.applied[lockKeyOf(b, rt)]
+}
+
+func lockIsHA(t *testing.T, b *ExecBackend, rt registry.Route) bool {
+ t.Helper()
+ body := haFixOf(b).fx.LockBody(b.Cfg.hibernatePrefix(rt.Host))
+ if body == nil {
+ return false
+ }
+ v, err := hafresh.DecodeLock(body, "x")
+ return err == nil && v.HAOn()
+}
+
+func putLockFor(t *testing.T, b *ExecBackend, rt registry.Route, body []byte) {
+ t.Helper()
+ haFixOf(b).fx.PutLock(b.Cfg.hibernatePrefix(rt.Host), body)
+}
+
+func markerBody(t *testing.T, box, iid, lifetime string, txid uint64, clean bool) []byte {
+ t.Helper()
+ body, err := hafresh.MarkerBody(6, hafresh.Marker{V: 1, Box: box, IID: iid, Lifetime: lifetime, TXID: txid, Clean: clean})
+ if err != nil {
+ t.Fatal(err)
+ }
+ return body
+}
+
+func leaseBody(t *testing.T, owner string, expires time.Time) []byte {
+ t.Helper()
+ body, err := json.Marshal(hafresh.Lock{Generation: 9, ExpiresAt: expires.UTC(), Owner: owner})
+ if err != nil {
+ t.Fatal(err)
+ }
+ return body
+}
+
+func markerView(box, iid, lifetime string, txid uint64, clean bool) hafresh.View {
+ return hafresh.View{ETag: `"x"`, Lock: hafresh.Lock{Generation: 6, ExpiresAt: time.Unix(0, 0).UTC(),
+ Owner: hafresh.MarkerOwner(hafresh.Marker{Box: box, IID: iid}),
+ Release: &hafresh.Marker{V: 1, Box: box, IID: iid, Lifetime: lifetime, TXID: txid, Clean: clean}}}
+}
+
+func spawns(b *ExecBackend) int {
+ c := haFixOf(b).ctl
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ return len(c.calls)
+}
+
+// flattenRoute moves rt to the flat layout's paths.
+func flattenRoute(t *testing.T, b *ExecBackend, rt *registry.Route) {
+ t.Helper()
+ rt.DBPath = provision.DefaultDBPath(b.DataDir, rt.Host)
+ rt.Socket = filepath.Join(b.RunDirOverride, rt.Host+".sock")
+ if l, _ := b.Layout(*rt); l != LayoutFlat {
+ t.Fatalf("fixture: the route classifies %s, not flat", l)
+ }
+}
+
+func dbPathOf(b *ExecBackend, rt registry.Route) string { return b.pathsFor(rt).dbPath }
+
+func filesDirOf(b *ExecBackend, rt registry.Route) string {
+ return hostFilesDir(b.pathsFor(rt), rt.Host)
+}
+
+func exists(path string) bool { _, err := os.Lstat(path); return err == nil }
+
+func writeFiles(t *testing.T, b *ExecBackend, rt registry.Route, files map[string]string) {
+ t.Helper()
+ dir := filesDirOf(b, rt)
+ if err := os.MkdirAll(dir, 0o700); err != nil {
+ t.Fatal(err)
+ }
+ for name, body := range files {
+ if err := os.WriteFile(filepath.Join(dir, name), []byte(body), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ }
+}
+
+func readFile(t *testing.T, b *ExecBackend, rt registry.Route, name string) string {
+ t.Helper()
+ body, err := os.ReadFile(filepath.Join(filesDirOf(b, rt), name))
+ if err != nil {
+ t.Fatal(err)
+ }
+ return string(body)
+}
+
+// writeDBAndRecord puts a local copy in place (a database, a files tree,
+// an env file) and the release record this box would have written when it
+// released the host with m.
+func writeDBAndRecord(t *testing.T, b *ExecBackend, rt registry.Route, m hafresh.Marker) {
+ t.Helper()
+ p := b.pathsFor(rt)
+ if err := os.MkdirAll(p.dataDir, 0o700); err != nil {
+ t.Fatal(err)
+ }
+ if err := writeMinimalSQLite(p.dbPath); err != nil {
+ t.Fatal(err)
+ }
+ writeFiles(t, b, rt, map[string]string{"local.txt": "mine"})
+ if err := os.WriteFile(p.envFile, []byte("CARLOS_ADMIN_TOKEN=local\n"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ now, err := readLocalNow(p, rt.Host)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := writeReleaseRecord(p, rt.Host, hafresh.LocalRecord{Marker: m, DB: now.DB, WALEmpty: now.WALEmpty, TreeDigest: now.TreeDigest}); err != nil {
+ t.Fatal(err)
+ }
+}
+
+// publishManifest publishes files (and the env item, when env is not
+// empty) as the host's files manifest.
+func publishManifest(t *testing.T, b *ExecBackend, rt registry.Route, files map[string]string, env string) {
+ t.Helper()
+ ctx := context.Background()
+ p, err := hostfiles.Open(ctx, b.FilesStore, b.filesPrefix(rt.Host))
+ if err != nil {
+ t.Fatal(err)
+ }
+ for name, body := range files {
+ if err := p.Stage(ctx, name, []byte(body), 0o644, false); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if env != "" {
+ if err := p.StagePlatform(ctx, hostfiles.EnvItem, []byte(env)); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if _, err := p.Commit(ctx); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func releaseHALease(t *testing.T, l Lease) {
+ t.Helper()
+ t.Cleanup(func() {
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+ _ = l.Release(ctx)
+ })
+}
+
+func TestRestoreHAKeepsOnlyOnProof(t *testing.T) {
+ ctx := context.Background()
+ b, rt := haBackend(t, "shop.example.com")
+ l1 := haFixOf(b).lifetime
+ writeDBAndRecord(t, b, rt, hafresh.Marker{V: 1, Box: "a", IID: "i-a", Lifetime: l1, TXID: 5, Clean: true})
+ if fresh, err := b.restoreHA(ctx, rt, markerView("a", "i-a", l1, 5, true), false); err != nil || fresh || restoreCalls(b) != 0 {
+ t.Fatalf("own clean marker: fresh %v, err %v, %d restores", fresh, err, restoreCalls(b))
+ }
+ if readFile(t, b, rt, "local.txt") != "mine" {
+ t.Fatal("the kept copy's files were touched")
+ }
+ if fresh, err := b.restoreHA(ctx, rt, markerView("b", "i-b", l1, 5, true), false); err != nil || fresh {
+ t.Fatalf("another box's marker: fresh %v, err %v", fresh, err)
+ }
+ if restoreCalls(b) != 1 || !exists(dbPathOf(b, rt)+".stale") {
+ t.Fatal("not set aside and restored")
+ }
+ if exists(recordPath(b.pathsFor(rt), rt.Host)) {
+ t.Fatal("the release record of the set-aside copy is still beside the restored database")
+ }
+}
+
+// Every reason that does not keep restores: a lifetime that is not the
+// record's, an unclean marker, a txid the record does not carry, a
+// changed tree.
+func TestRestoreHARestoresOnEveryOtherReason(t *testing.T) {
+ ctx := context.Background()
+ for name, tc := range map[string]struct {
+ view func(l1 string) hafresh.View
+ local func(t *testing.T, b *ExecBackend, rt registry.Route)
+ }{
+ "lifetime": {view: func(string) hafresh.View { return markerView("a", "i-a", "L0", 5, true) }},
+ "unclean": {view: func(l1 string) hafresh.View { return markerView("a", "i-a", l1, 5, false) }},
+ "txid": {view: func(l1 string) hafresh.View { return markerView("a", "i-a", l1, 6, true) }},
+ "tree": {
+ view: func(l1 string) hafresh.View { return markerView("a", "i-a", l1, 5, true) },
+ local: func(t *testing.T, b *ExecBackend, rt registry.Route) {
+ writeFiles(t, b, rt, map[string]string{"new.txt": "x"})
+ },
+ },
+ } {
+ t.Run(name, func(t *testing.T) {
+ b, rt := haBackend(t, "shop.example.com")
+ l1 := haFixOf(b).lifetime
+ writeDBAndRecord(t, b, rt, hafresh.Marker{V: 1, Box: "a", IID: "i-a", Lifetime: l1, TXID: 5, Clean: true})
+ if tc.local != nil {
+ tc.local(t, b, rt)
+ }
+ if _, err := b.restoreHA(ctx, rt, tc.view(l1), false); err != nil {
+ t.Fatal(err)
+ }
+ if restoreCalls(b) != 1 || !exists(dbPathOf(b, rt)+".stale") || exists(filepath.Join(filesDirOf(b, rt), "local.txt")) {
+ t.Fatalf("%s: kept a copy without proof", name)
+ }
+ })
+ }
+}
+
+func TestRestoreHAFilesIntoCleanTree(t *testing.T) {
+ ctx := context.Background()
+ b, rt := haBackend(t, "shop.example.com")
+ l1 := haFixOf(b).lifetime
+ publishManifest(t, b, rt, map[string]string{"a.txt": "s3"}, "CARLOS_INSTANCE_KEY=k1\n")
+ writeFiles(t, b, rt, map[string]string{"a.txt": "local", "stray.txt": "x"})
+ if err := os.WriteFile(b.pathsFor(rt).envFile, []byte("CARLOS_INSTANCE_KEY=stale\n"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := b.restoreHA(ctx, rt, markerView("b", "i-b", l1, 5, true), false); err != nil {
+ t.Fatal(err)
+ }
+ if readFile(t, b, rt, "a.txt") != "s3" || exists(filepath.Join(filesDirOf(b, rt), "stray.txt")) {
+ t.Fatal("tree not clean")
+ }
+ if env, _ := os.ReadFile(b.pathsFor(rt).envFile); string(env) != "CARLOS_INSTANCE_KEY=k1\n" {
+ t.Fatalf("env file %q, want the manifest's", env)
+ }
+ if exists(filesDirOf(b, rt) + restoreSuffix) {
+ t.Fatal("the restore directory was left behind")
+ }
+}
+
+// A no-marker restore (r P15): the stale <host>.env goes with the tree, and
+// with no manifest nothing replaces it, so the next launch mints afresh.
+func TestRestoreHANoMarkerRemovesStaleEnv(t *testing.T) {
+ ctx := context.Background()
+ b, rt := haBackend(t, "shop.example.com")
+ writeDBAndRecord(t, b, rt, hafresh.Marker{V: 1, Box: "a", IID: "i-a", Lifetime: haFixOf(b).lifetime, TXID: 5, Clean: true})
+ own := hafresh.View{ETag: `"x"`, Lock: hafresh.Lock{Generation: 3, ExpiresAt: time.Now().Add(-time.Hour), Owner: hafresh.OwnerFor(hafresh.Self{Ref: "a", IID: "i-a"}, 7, true)}}
+ if _, err := b.restoreHA(ctx, rt, own, false); err != nil {
+ t.Fatal(err)
+ }
+ if exists(b.pathsFor(rt).envFile) {
+ t.Fatal("the stale env file survived a no-marker restore")
+ }
+ if restoreCalls(b) != 1 {
+ t.Fatal("no restore")
+ }
+}
+
+func TestRestoreHANestedRenameFailureFailsWake(t *testing.T) { // Review Focus 3
+ ctx := context.Background()
+ b, rt := haBackend(t, "shop.example.com")
+ if l, _ := b.Layout(rt); l != LayoutNested {
+ t.Fatalf("fixture: %s, not nested", l)
+ }
+ writeDBAndRecord(t, b, rt, hafresh.Marker{V: 1, Box: "a", IID: "i-a", Lifetime: haFixOf(b).lifetime, TXID: 5, Clean: true})
+ // The stale name is a non-empty directory: neither removed nor renamed
+ // over, by any user.
+ if err := os.MkdirAll(filepath.Join(dbPathOf(b, rt)+".stale", "x"), 0o700); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := b.restoreHA(ctx, rt, markerView("b", "i-b", haFixOf(b).lifetime, 5, true), false); err == nil {
+ t.Fatal("wake proceeded over an old tree")
+ }
+ if restoreCalls(b) != 0 {
+ t.Fatal("restored over a copy that was not set aside")
+ }
+}
+
+func TestHAHostRulesHoldWithSwitchOff(t *testing.T) { // Review Focus 5
+ ctx := context.Background()
+ b, rt := haBackend(t, "shop.example.com")
+ t.Setenv("CARLOS_REGION_HA", "")
+ l1 := haFixOf(b).lifetime
+ writeDBAndRecord(t, b, rt, hafresh.Marker{V: 1, Box: "a", IID: "i-a", Lifetime: l1, TXID: 5, Clean: true})
+ putLockFor(t, b, rt, markerBody(t, "b", "i-b", l1, 6, true))
+ l, err := b.Acquire(ctx, rt)
+ if err != nil {
+ t.Fatal(err)
+ }
+ releaseHALease(t, l)
+ if hl, ok := l.(haLease); !ok || !hl.HA() || hl.View().Lock.Release == nil {
+ t.Fatalf("not an HA lease over the marker: %+v", l)
+ }
+ if fresh, err := b.Restore(ctx, rt); err != nil || fresh || restoreCalls(b) != 1 {
+ t.Fatalf("stale copy reused with the switch off: fresh %v, err %v, %d restores", fresh, err, restoreCalls(b))
+ }
+}
+
+func TestIndexMissReadsRecordBeforeAcquire(t *testing.T) { // Review Focus 1
+ ctx := context.Background()
+ b, rt := haBackendEmptyIndex(t, "shop.example.com") // the record in the deployment store says HA
+ l, err := b.Acquire(ctx, rt)
+ if err != nil {
+ t.Fatal(err)
+ }
+ releaseHALease(t, l)
+ if !lockIsHA(t, b, rt) || recordGets(b) != 1 {
+ t.Fatalf("an HA host was treated as legacy after a restart (HA lock %v, %d record reads)", lockIsHA(t, b, rt), recordGets(b))
+ }
+ // The first wake: fresh, with an empty tree, and the leftover local
+ // copy set aside.
+ if err := os.MkdirAll(b.pathsFor(rt).dataDir, 0o700); err != nil {
+ t.Fatal(err)
+ }
+ if err := writeMinimalSQLite(dbPathOf(b, rt)); err != nil {
+ t.Fatal(err)
+ }
+ if fresh, err := b.Restore(ctx, rt); err != nil || !fresh || exists(dbPathOf(b, rt)) || restoreCalls(b) != 0 {
+ t.Fatalf("first wake: fresh %v, err %v", fresh, err)
+ }
+}
+
+func TestHAFirstWakeRefusesLeftoverFiles(t *testing.T) {
+ ctx := context.Background()
+ b, rt := haBackend(t, "shop.example.com")
+ haFixOf(b).fx.PutObject(b.filesPrefix(rt.Host)+"manifest.json", []byte("{}"))
+ _, err := b.Acquire(ctx, rt)
+ var refused *errLeaseRefused
+ if !errors.As(err, &refused) || !strings.Contains(refused.reason, lease.ReasonLeftoverData) || lockWrites(t, b, rt) != 0 {
+ t.Fatalf("first wake over a files tree: %v", err)
+ }
+}
+
+type countingMirror struct {
+ *fakeMirrorStore
+ mu sync.Mutex
+ calls int
+}
+
+func (m *countingMirror) List(ctx context.Context, bucket, prefix string) (map[string]lease.MirrorObject, error) {
+ m.mu.Lock()
+ m.calls++
+ m.mu.Unlock()
+ return m.fakeMirrorStore.List(ctx, bucket, prefix)
+}
+
+func TestHAWakeSkipsStagingFallback(t *testing.T) {
+ ctx := context.Background()
+ b, rt := haBackend(t, "shop.example.com")
+ fm := &countingMirror{fakeMirrorStore: newFakeMirrorStore()}
+ fm.put(b.Cfg.Bucket, MovesPrefix(rt.Host)+"generations/x", `"e"`)
+ b.Mirror = fm
+ if _, err := b.restoreHA(ctx, rt, markerView("b", "i-b", haFixOf(b).lifetime, 5, true), false); err != nil {
+ t.Fatal(err)
+ }
+ // Through Restore too, after an HA acquire.
+ putLockFor(t, b, rt, markerBody(t, "b", "i-b", haFixOf(b).lifetime, 6, true))
+ l, err := b.Acquire(ctx, rt)
+ if err != nil {
+ t.Fatal(err)
+ }
+ releaseHALease(t, l)
+ if _, err := b.Restore(ctx, rt); err != nil {
+ t.Fatal(err)
+ }
+ if fm.calls != 0 {
+ t.Fatal("staging promoted for an HA host")
+ }
+}
+
+func TestStaleNegativeIndexTakesHAPath(t *testing.T) { // r3.1: the index says legacy; the host was re-created born HA and B holds it
+ ctx := context.Background()
+ b, rt := haBackendIndexed(t, "shop.example.com")
+ putLockFor(t, b, rt, leaseBody(t, hafresh.OwnerFor(hafresh.Self{Ref: "b", IID: "i-b"}, 9, true), time.Now().Add(-time.Hour))) // B hung past expiry
+ _, err := b.Acquire(ctx, rt)
+ var refused *errLeaseRefused
+ if !errors.As(err, &refused) || !strings.Contains(refused.reason, "another box") || lockWrites(t, b, rt) != 0 {
+ t.Fatalf("legacy took B's lock: %v", err)
+ }
+ if e, _ := b.Lifetimes.Lookup(rt.Host); !e.HA {
+ t.Fatal("not marked HA")
+ }
+ if recordGets(b) != 0 {
+ t.Fatal("an index hit read the record")
+ }
+}
+
+func TestSidecarKeepsLegacyAcquireWithoutRecordRead(t *testing.T) { // r3.4
+ ctx := context.Background()
+ b, rt := haBackendEmptyIndex(t, "worker.shop.example.com")
+ rt.Kind = "sidecar"
+ failRecordReads(b)
+ l, err := b.Acquire(ctx, rt)
+ if err != nil || recordGets(b) != 0 {
+ t.Fatalf("sidecar wake: %v, %d record reads", err, recordGets(b))
+ }
+ releaseHALease(t, l)
+ if lockIsHA(t, b, rt) {
+ t.Fatal("a sidecar took an HA lock")
+ }
+}
+
+func TestUnprovisionedRouteKeepsLegacyAcquire(t *testing.T) { // r3.4: a hand-added hibernating route
+ ctx := context.Background()
+ b, rt := haBackendEmptyIndex(t, "hand.example.com")
+ rt.Provisioned = false
+ failRecordReads(b)
+ l, err := b.Acquire(ctx, rt)
+ if err != nil || recordGets(b) != 0 {
+ t.Fatal(err)
+ }
+ releaseHALease(t, l)
+ if lockIsHA(t, b, rt) {
+ t.Fatal("a hand-added route took an HA lock")
+ }
+ // Its restore stays the legacy one: the warm copy is used as it is.
+ p := b.pathsFor(rt)
+ if err := os.MkdirAll(p.dataDir, 0o700); err != nil {
+ t.Fatal(err)
+ }
+ if err := writeMinimalSQLite(p.dbPath); err != nil {
+ t.Fatal(err)
+ }
+ if fresh, err := b.Restore(ctx, rt); err != nil || fresh || restoreCalls(b) != 0 || exists(p.dbPath+".stale") {
+ t.Fatalf("legacy restore changed: fresh %v, err %v", fresh, err)
+ }
+}
+
+// An HA-format lock under a route with no instance record refuses the
+// wake, and nothing is written.
+func TestLegacyRouteRefusesHALock(t *testing.T) {
+ ctx := context.Background()
+ b, rt := haBackendEmptyIndex(t, "hand.example.com")
+ rt.Provisioned = false
+ putLockFor(t, b, rt, markerBody(t, "b", "i-b", "L1", 6, true))
+ _, err := b.Acquire(ctx, rt)
+ var refused *errLeaseRefused
+ if !errors.As(err, &refused) || refused.reason != "ha lock on a route with no instance record" || lockWrites(t, b, rt) != 0 {
+ t.Fatalf("%v", err)
+ }
+}
+
+func TestProvisionedInstanceFailsClosedOnRecordRead(t *testing.T) {
+ ctx := context.Background()
+ b, rt := haBackendEmptyIndex(t, "shop.example.com")
+ failRecordReads(b)
+ if _, err := b.Acquire(ctx, rt); err == nil || lockRequests(t, b, rt) != 0 {
+ t.Fatal("wake went on without its record")
+ }
+}
+
+func TestHAWakeRefusedOutsideNested(t *testing.T) { // r3.2, through the production Acquire
+ ctx := context.Background()
+ for name, mod := range map[string]func(*testing.T, *ExecBackend, *registry.Route){
+ "flat": func(t *testing.T, b *ExecBackend, rt *registry.Route) { flattenRoute(t, b, rt) },
+ "unit": func(_ *testing.T, _ *ExecBackend, rt *registry.Route) { rt.Backing = registry.BackingUnit },
+ "no nested gate": func(_ *testing.T, b *ExecBackend, _ *registry.Route) {
+ b.NestedOK = func() error { return errors.New("mounts") }
+ },
+ "no control": func(_ *testing.T, b *ExecBackend, _ *registry.Route) { b.Control = nil },
+ } {
+ t.Run(name, func(t *testing.T) {
+ b, rt := haBackend(t, "shop.example.com")
+ mod(t, b, &rt)
+ _, err := b.Acquire(ctx, rt)
+ var refused *errLeaseRefused
+ if !errors.As(err, &refused) || !strings.HasPrefix(refused.reason, "high availability needs the nested layout") || lockRequests(t, b, rt) != 0 || spawns(b) != 0 {
+ t.Errorf("%s: %v", name, err)
+ }
+ })
+ }
+}
+
+// A unit-backed row reaches the unit backend, never ExecBackend.Acquire:
+// the split backend asks the exec half first.
+func TestSplitBackendRefusesHAUnitRow(t *testing.T) {
+ ctx := context.Background()
+ b, rt := haBackend(t, "shop.example.com")
+ rt.Backing = registry.BackingUnit
+ s := &SplitBackend{Exec: b, Unit: &UnitBackend{OptDir: b.OptDir}}
+ _, err := s.Acquire(ctx, rt)
+ var refused *errLeaseRefused
+ if !errors.As(err, &refused) {
+ t.Fatalf("an HA unit row was acquired: %v", err)
+ }
+ // A legacy unit row is untouched and reads nothing.
+ rt.Provisioned = false
+ failRecordReads(b)
+ if _, err := s.Acquire(ctx, rt); err != nil || recordGets(b) != 0 {
+ t.Fatalf("legacy unit row: %v", err)
+ }
+}
+
+// The admission is asked again before every spawn of a host acquired HA:
+// a row converted out of the nested layout mid-life refuses the next one.
+func TestHASpawnRefusedAfterLayoutChange(t *testing.T) {
+ ctx := context.Background()
+ b, rt := haBackend(t, "shop.example.com")
+ l, err := b.Acquire(ctx, rt)
+ if err != nil {
+ t.Fatal(err)
+ }
+ releaseHALease(t, l)
+ flattenRoute(t, b, &rt)
+ var refused *errLeaseRefused
+ if _, _, err := b.Start(ctx, rt); !errors.As(err, &refused) {
+ t.Fatalf("Start: %v", err)
+ }
+ if _, _, err := b.StartGen(ctx, rt, 1, true); !errors.As(err, &refused) {
+ t.Fatalf("StartGen: %v", err)
+ }
+ if _, err := b.StartSidecar(ctx, rt); !errors.As(err, &refused) {
+ t.Fatalf("StartSidecar: %v", err)
+ }
+ if err := b.Seed(ctx, rt); !errors.As(err, &refused) {
+ t.Fatalf("Seed: %v", err)
+ }
+ if spawns(b) != 0 {
+ t.Fatal("something was started")
+ }
+}
+
+func TestLeaseRefusedAnswers503RetryAfter10(t *testing.T) {
+ a := &Service{}
+ w := httptest.NewRecorder()
+ a.serveWakeError(w, httptest.NewRequest("GET", "/", nil), registry.Route{Host: "shop.example.com"},
+ &errLeaseRefused{reason: "high availability needs the nested layout: the row's layout is flat"})
+ if w.Code != http.StatusServiceUnavailable || w.Header().Get("Retry-After") != "10" {
+ t.Fatalf("%d, Retry-After %q", w.Code, w.Header().Get("Retry-After"))
+ }
+}
diff --git a/internal/lease/self.go b/internal/lease/self.go
index 4334a953e..f68ba7fd9 100644
--- a/internal/lease/self.go
+++ b/internal/lease/self.go
@@ -18,6 +18,16 @@ var self atomic.Pointer[hafresh.Self]
// acquired with.
func SetSelf(s hafresh.Self) { self.Store(&s) }
+// CurrentSelf is the box SetSelf last named, the zero Self before it: the
+// identity the keep decision compares a release marker with, the same one
+// every lock this process writes from now on names.
+func CurrentSelf() hafresh.Self {
+ if s := self.Load(); s != nil {
+ return *s
+ }
+ return hafresh.Self{}
+}
+
// currentOwner is the owner a lock written now carries: the box format
// (hafresh.OwnerFor) once SetSelf has named the box. Before that, and in
// any process other than the agent (the console, a CLI), a legacy lock
diff --git a/internal/lease/self_test.go b/internal/lease/self_test.go
index 0ae7f7e0d..14e6190cd 100644
--- a/internal/lease/self_test.go
+++ b/internal/lease/self_test.go
@@ -55,3 +55,19 @@ func TestAcquireWritesTheBoxOwner(t *testing.T) {
t.Fatalf("HA owner %q", got)
}
}
+
+// CurrentSelf is what SetSelf last named (the keep decision's identity),
+// the zero Self before any.
+func TestCurrentSelfIsTheLastSetSelf(t *testing.T) {
+ prev := self.Load()
+ t.Cleanup(func() { self.Store(prev) })
+ self.Store(nil)
+ if got := CurrentSelf(); got != (hafresh.Self{}) {
+ t.Fatalf("before SetSelf: %+v", got)
+ }
+ SetSelf(hafresh.Self{Ref: "a"})
+ SetSelf(hafresh.Self{Ref: "a", IID: "i-a"})
+ if got := CurrentSelf(); got != (hafresh.Self{Ref: "a", IID: "i-a"}) {
+ t.Fatalf("after SetSelf: %+v", got)
+ }
+}