carlos / platform Public

ha: let pool withdrawal run on a live activator

Keep completed withdrawal proofs across build-state read_at refreshes. Preserve every other row and build-state field and the exact-row deletion transaction. Cover production startup, the provision hook, refresh during and after proof, and later-tick deletion.
Co-Authored-By: GPT-6 Astra <noreply@openai.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev e598c19f7fd5daca80fc04e9966d728c2060005f parent 557700e
3 files changed, +220 −3
  • internal/activator/poolwithdrawal.go +23 −3
  • internal/activator/poolwithdrawal_test.go +52 −0
  • internal/host/poolwithdrawal_live_test.go +145 −0
diff --git a/internal/activator/poolwithdrawal.go b/internal/activator/poolwithdrawal.go
index 93b746358..1fedda5af 100644
--- a/internal/activator/poolwithdrawal.go
+++ b/internal/activator/poolwithdrawal.go
@@ -1,11 +1,13 @@
package activator
import (
+ "bytes"
"context"
"encoding/json"
"errors"
"io/fs"
"log"
+ "maps"
"time"
@@ -37,7 +39,7 @@ func (a *Service) PreparePoolWithdrawal(ctx context.Context, rt registry.Route)
eligible := a.LocalEligible(rt)
a.mu.Lock()
defer a.mu.Unlock()
- if err != nil || current == nil || *current != withdrawalRow(rt) || eligible {
+ if err != nil || current == nil || !samePoolWithdrawalRoute(*current, withdrawalRow(rt)) || eligible {
return pending("changed")
}
if a.shuttingDown {
@@ -64,7 +66,7 @@ func (a *Service) PreparePoolWithdrawal(ctx context.Context, rt registry.Route)
if !old.done {
return pending("stopping")
}
- if old.route == rt {
+ if samePoolWithdrawalRoute(old.route, rt) {
if old.err == nil {
return nil
}
@@ -208,7 +210,7 @@ func (a *Service) poolWithdrawalProof(ctx context.Context, b *ExecBackend, job *
return pending("duties")
}
current, err := b.Registry.Get(rt.Host)
- if err != nil || current == nil || *current != withdrawalRow(rt) || b.poolEligible(rt) {
+ if err != nil || current == nil || !samePoolWithdrawalRoute(*current, withdrawalRow(rt)) || b.poolEligible(rt) {
return pending("changed")
}
if current.NextDue != 0 || len(timers) != 0 {
@@ -219,6 +221,24 @@ func (a *Service) poolWithdrawalProof(ctx context.Context, b *ExecBackend, job *
func withdrawalRow(rt registry.Route) registry.Route { rt.WakeIncarnation = ""; return rt }
+func samePoolWithdrawalRoute(a, b registry.Route) bool {
+ ac, bc := a.BuildState, b.BuildState
+ a.BuildState, b.BuildState = "", ""
+ if a != b {
+ return false
+ }
+ if ac == bc {
+ return true
+ }
+ var av, bv map[string]json.RawMessage
+ if json.Unmarshal([]byte(ac), &av) != nil || av == nil || json.Unmarshal([]byte(bc), &bv) != nil || bv == nil {
+ return false
+ }
+ delete(av, "read_at")
+ delete(bv, "read_at")
+ return maps.EqualFunc(av, bv, func(a, b json.RawMessage) bool { return bytes.Equal(a, b) })
+}
+
func (b *ExecBackend) poolWithdrawalEmpty(rt registry.Route) error {
events := b.CgroupEvents
if events == nil {
diff --git a/internal/activator/poolwithdrawal_test.go b/internal/activator/poolwithdrawal_test.go
index 7b3562d08..8fcaa773a 100644
--- a/internal/activator/poolwithdrawal_test.go
+++ b/internal/activator/poolwithdrawal_test.go
@@ -4,6 +4,7 @@ import (
"context"
"errors"
"log"
+ "reflect"
"strings"
"sync/atomic"
"testing"
@@ -14,6 +15,57 @@ import (
"github.com/carlosframework/platform/internal/registry"
)
+func TestPoolWithdrawalProofIdentity(t *testing.T) {
+ base := registry.Route{Host: "shop.example.com", WakeIncarnation: "life", BuildState: `{"known":true,"state":{"last_executed":"v1"},"read_at":"2026-11-06T12:00:00Z"}`}
+ refreshed := base
+ refreshed.BuildState = strings.Replace(base.BuildState, "12:00:00", "12:00:05", 1)
+ if !samePoolWithdrawalRoute(base, refreshed) {
+ t.Fatal("refresh timestamp invalidated proof")
+ }
+ for _, state := range []string{
+ strings.Replace(refreshed.BuildState, `"v1"`, `"v2"`, 1),
+ strings.Replace(refreshed.BuildState, `"known":true`, `"known":false`, 1),
+ strings.Replace(refreshed.BuildState, `"known":true`, `"known":true,"read_err":"unavailable"`, 1),
+ strings.Replace(refreshed.BuildState, `"known":true`, `"known":true,"future_field":true`, 1),
+ `{`, `null`, `[]`, `"state"`, "",
+ } {
+ changed := refreshed
+ changed.BuildState = state
+ if samePoolWithdrawalRoute(base, changed) {
+ t.Fatalf("changed or malformed build state accepted: %s", state)
+ }
+ }
+ value := reflect.ValueOf(&refreshed).Elem()
+ for i := range value.NumField() {
+ field := value.Type().Field(i).Name
+ if field == "BuildState" {
+ continue
+ }
+ t.Run(field, func(t *testing.T) {
+ changed := refreshed
+ v := reflect.ValueOf(&changed).Elem().Field(i)
+ if v.Kind() == reflect.Struct {
+ v = v.Field(0)
+ }
+ switch v.Kind() {
+ case reflect.String:
+ v.SetString(v.String() + "changed")
+ case reflect.Bool:
+ v.SetBool(!v.Bool())
+ case reflect.Int, reflect.Int64:
+ v.SetInt(v.Int() + 1)
+ case reflect.Uint64:
+ v.SetUint(v.Uint() + 1)
+ default:
+ t.Fatalf("uncovered field kind %s", v.Kind())
+ }
+ if samePoolWithdrawalRoute(base, changed) {
+ t.Fatal("changed row reused proof")
+ }
+ })
+ }
+}
+
type withdrawalSyncFailure struct {
Rep
haRep
diff --git a/internal/host/poolwithdrawal_live_test.go b/internal/host/poolwithdrawal_live_test.go
new file mode 100644
index 000000000..bc35191d6
--- /dev/null
+++ b/internal/host/poolwithdrawal_live_test.go
@@ -0,0 +1,145 @@
+package host
+
+import (
+ "context"
+ "log"
+ "path/filepath"
+ "strings"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/activator"
+ "github.com/carlosframework/platform/internal/edge"
+ "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"
+)
+
+type withdrawalProofLog struct {
+ done chan string
+ starts atomic.Int32
+}
+
+func (l *withdrawalProofLog) Write(p []byte) (int, error) {
+ line := string(p)
+ if strings.Contains(line, "ha_pool_withdrawal_proof_start") {
+ l.starts.Add(1)
+ }
+ if strings.Contains(line, "ha_pool_withdrawal_proof_finish") {
+ l.done <- line
+ }
+ return len(p), nil
+}
+
+func TestPoolWithdrawalLiveAgentTicks(t *testing.T) {
+ for _, during := range []bool{false, true} {
+ t.Run(map[bool]string{false: "refresh-after-proof", true: "refresh-during-proof"}[during], func(t *testing.T) {
+ testPoolWithdrawalLiveAgentTicks(t, during)
+ })
+ }
+}
+
+func testPoolWithdrawalLiveAgentTicks(t *testing.T, during bool) {
+ t.Cleanup(lease.ProcessStateForTest())
+ fx := locktest.NewLockFixture(t)
+ reg := edgesTestRegistry(t)
+ store := release.NewDirStore(t.TempDir())
+ pcfg := provision.ReconcileConfig{Region: "ie", Pools: []string{"other"}, DataDir: t.TempDir()}
+ rec := provision.Record{Schema: 1, Host: "shop.example.com", Account: "bbw", App: "shop", Pool: "ha", Region: "ie", Channel: "stable", HA: true, CreatedAt: time.Now().UTC()}
+ if err := provision.CreateRecord(t.Context(), store, rec); err != nil {
+ t.Fatal(err)
+ }
+ b := armableBackend(t)
+ b.Cfg = activator.Config{Bucket: fx.Bucket, Region: "eu-west-1", Prefix: "instances", Idle: time.Hour, Record: haRecordFacts(func(context.Context) (release.Store, error) { return store, nil }, nil)}
+ b.Registry, b.DataDir, b.RunDirOverride = reg, pcfg.DataDir, t.TempDir()
+ b.CgroupRoot = t.TempDir()
+ b.ServedPools = pcfg.ServedPools
+ b.NestedOK = func() error { return nil }
+ var swept atomic.Bool
+ b.StartupSwept = swept.Load
+ inspecting, resume := make(chan struct{}), make(chan struct{})
+ if during {
+ b.CgroupEvents = func(string, string) (bool, bool, error) {
+ close(inspecting)
+ <-resume
+ return false, false, nil
+ }
+ }
+ if err := lease.SetObligationDir(t.TempDir()); err != nil {
+ t.Fatal(err)
+ }
+ rt := registry.Route{Host: rec.Host, Account: rec.Account, App: rec.App, Kind: "instance", Status: "ready", Provisioned: true, Hibernate: true, HA: true, Pool: rec.Pool, Region: rec.Region, DBPath: provision.NestedDBPath(b.DataDir, rec.Host), Socket: filepath.Join(b.RunDirOverride, "instances", provision.InstanceID(rec.Host), "app.sock")}
+ if err := reg.Upsert(rt); err != nil {
+ t.Fatal(err)
+ }
+ clock := time.Now()
+ bs := &buildStates{hibBucket: fx.Bucket, prefix: func(h string) string { return "instances/" + h }, storeFor: storesOf(map[string]release.Store{fx.Bucket: release.NewDirStore(t.TempDir())}), reg: reg, optDir: t.TempDir(), bakeDir: t.TempDir(), now: func() time.Time { return clock }}
+ bs.refreshAll(t.Context())
+ svc := activator.New(b.Cfg, &activator.SplitBackend{Exec: b, Unit: &activator.UnitBackend{}}, reg)
+ svc.Routes, svc.DutyStore = reg, reg
+ svc.GenerationsFile = filepath.Join(t.TempDir(), "generations.json")
+ old := armedPoolWithdrawal.Swap(svc)
+ defer armedPoolWithdrawal.Store(old)
+ startActivator(t.Context(), func(context.Context) error { return nil }, func(_ context.Context, ok bool) { swept.Store(ok) }, svc.Start)
+ defer svc.Shutdown(context.Background())
+ if _, err := edge.New(reg, svc); err != nil {
+ t.Fatal(err)
+ }
+ logs := &withdrawalProofLog{done: make(chan string, 20)}
+ prior := log.Writer()
+ log.SetOutput(logs)
+ defer log.SetOutput(prior)
+ tick := func() {
+ t.Helper()
+ if err := reconcileSerializedAuth(t.Context(), store, reg, pcfg, nil, newAssetAuthority(nil)); err != nil {
+ t.Fatal(err)
+ }
+ }
+ tick()
+ if row, err := reg.Get(rt.Host); err != nil || row == nil {
+ t.Fatalf("first tick removed unproven row: %v", err)
+ }
+ if !svc.Fenced(rt.Host) {
+ t.Fatal("withdrawal did not fence the edge's service")
+ }
+ if during {
+ select {
+ case <-inspecting:
+ case <-time.After(5 * time.Second):
+ close(resume)
+ t.Fatal("proof did not reach cgroup inspection")
+ }
+ clock = clock.Add(5 * time.Second)
+ bs.refreshAll(t.Context())
+ close(resume)
+ }
+ select {
+ case line := <-logs.done:
+ if !strings.Contains(line, "result=success") {
+ t.Fatal(line)
+ }
+ case <-time.After(5 * time.Second):
+ t.Fatal("proof did not complete")
+ }
+ if !during {
+ clock = clock.Add(5 * time.Second)
+ bs.refreshAll(t.Context())
+ }
+ tick()
+ if row, err := reg.Get(rt.Host); err != nil || row != nil {
+ t.Fatalf("completed proof did not remove row on second tick: row=%+v err=%v starts=%d", row, err, logs.starts.Load())
+ }
+ if logs.starts.Load() != 1 {
+ t.Fatalf("proof restarted %d times", logs.starts.Load())
+ }
+ if !svc.Fenced(rt.Host) {
+ t.Fatal("deletion lifted the withdrawal fence")
+ }
+ tick()
+ if row, err := reg.Get(rt.Host); err != nil || row != nil || logs.starts.Load() != 1 {
+ t.Fatalf("third tick recreated row or proof: row=%+v err=%v starts=%d", row, err, logs.starts.Load())
+ }
+}