carlos / platform Public

ha: finish departure imports before removing evidence

Scan authoritative inventory in bounded pages and persist source authority before adoption. Require a fresh complete zero-match lock rescan before conditional edge deletion, acknowledged indexing, and current-receipt acknowledgment. Retain unresolved hosts without widening pool policy.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 83900c0c765a765b5dcfabd623ad8bb52d599873 parent df7acfe
11 files changed, +1,157 −21
  • internal/hadeparture/consumer.go +17 −2
  • internal/hadeparture/consumer_test.go +2 −2
  • internal/host/hadepartures.go +81 −12
  • internal/host/hadepartures_scan.go +415 −0
  • internal/host/hadepartures_scan_test.go +356 −0
  • internal/host/hadepartures_wiring.go +38 −2
  • internal/lease/ha.go +20 −3
  • internal/registry/ha_journal.go +5 −0
  • internal/registry/ha_scan.go +129 −0
  • internal/release/conditional_delete.go +55 −0
  • internal/release/conditional_delete_test.go +39 −0
diff --git a/internal/hadeparture/consumer.go b/internal/hadeparture/consumer.go
index d31100482..81ef5b38d 100644
--- a/internal/hadeparture/consumer.go
+++ b/internal/hadeparture/consumer.go
@@ -30,6 +30,7 @@ type Consumer struct {
wait func(context.Context, time.Duration) error
mu sync.Mutex
invoked bool
+ queue Queue
ctx context.Context
cancel context.CancelFunc
started, done chan struct{}
@@ -136,6 +137,9 @@ func (c *Consumer) Start(parent context.Context, makeQueue func(context.Context)
failures++
}
if q != nil && ctx.Err() == nil {
+ c.mu.Lock()
+ c.queue = q
+ c.mu.Unlock()
c.receive(ctx, q)
}
c.cancel()
@@ -163,8 +167,7 @@ func (c *Consumer) receive(ctx context.Context, q Queue) {
receiveFailed := err != nil
if err == nil {
for _, m := range messages {
- // A handle belongs only to this receive. The journal never sees it.
- m.Receipt = ""
+ // The controller retains this handle only in process memory.
if err = c.record(request, m); err != nil {
break
}
@@ -223,3 +226,15 @@ func waitContext(ctx context.Context, d time.Duration) error {
return nil
}
}
+
+func (c *Consumer) DeleteReceipt(ctx context.Context, receipt string) error {
+ c.mu.Lock()
+ q := c.queue
+ c.mu.Unlock()
+ if q == nil || receipt == "" {
+ return errors.New("ha_receipt_unavailable")
+ }
+ call, cancel := context.WithTimeout(ctx, 5*time.Second)
+ defer cancel()
+ return q.Delete(call, receipt)
+}
diff --git a/internal/hadeparture/consumer_test.go b/internal/hadeparture/consumer_test.go
index 2dfcda3e3..c85bfdb2d 100644
--- a/internal/hadeparture/consumer_test.go
+++ b/internal/hadeparture/consumer_test.go
@@ -86,8 +86,8 @@ func TestTerminationConsumerLifecycle(t *testing.T) {
entered, release := make(chan struct{}), make(chan struct{})
c := testConsumer()
c.record = func(ctx context.Context, m Message) error {
- if m.Receipt != "" {
- t.Error("receipt persisted")
+ if m.Receipt != "private" {
+ t.Error("current receipt lost before controller")
}
close(entered)
select {
diff --git a/internal/host/hadepartures.go b/internal/host/hadepartures.go
index cd0c4a0b4..0c1a7bb30 100644
--- a/internal/host/hadepartures.go
+++ b/internal/host/hadepartures.go
@@ -11,11 +11,14 @@ import (
"sync"
"time"
+ "github.com/carlosframework/platform/internal/activator"
"github.com/carlosframework/platform/internal/awsterminations"
"github.com/carlosframework/platform/internal/boxid"
"github.com/carlosframework/platform/internal/hadeparture"
+ "github.com/carlosframework/platform/internal/hafresh"
"github.com/carlosframework/platform/internal/provision"
"github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/release"
"github.com/carlosframework/platform/internal/termfence"
)
@@ -52,18 +55,23 @@ func departureCoverageGap(h provision.DepartureHost, s hadeparture.Scope) bool {
}
type DepartureConfig struct {
- Registry *registry.Registry
- Identities *departureIdentities
- Confirmer *termfence.Confirmer
- Cache *termfence.ProofCache
- ProofStore func(context.Context, string, string) (termfence.ProofStore, error)
- Self hadeparture.Box
- DeploymentBucket string
- Inventory func() provision.InventorySnapshot
- Policy func() LocalPolicy
- Invalidate func(string, string)
- Now func() time.Time
- Logf func(string, ...any)
+ Registry *registry.Registry
+ OpenStore func(context.Context) (release.Store, error)
+ NewReader func(context.Context, string) (DepartureLockReader, error)
+ Prefix func(string) string
+ Adopt func(context.Context, provision.DepartureHost, registry.HADeparture, hafresh.View) (activator.AdoptResult, error)
+ ValidateSuccessor func(context.Context, string, string) (bool, error)
+ Identities *departureIdentities
+ Confirmer *termfence.Confirmer
+ Cache *termfence.ProofCache
+ ProofStore func(context.Context, string, string) (termfence.ProofStore, error)
+ Self hadeparture.Box
+ DeploymentBucket string
+ Inventory func() provision.InventorySnapshot
+ Policy func() LocalPolicy
+ Invalidate func(string, string)
+ Now func() time.Time
+ Logf func(string, ...any)
// Pending is the B4 scan-page entry. A nil entry retains all work.
Pending func(context.Context, registry.HADeparture, provision.InventorySnapshot) error
Page func(context.Context, registry.HADeparture, []provision.DepartureHost) error
@@ -76,6 +84,9 @@ type Controller struct {
view hadeparture.DepartureView
wake chan struct{}
peerOffset int
+ scanMu sync.Mutex
+ receiptMu sync.Mutex
+ receipts map[string]string
evidence map[string]bool
suspects map[string]bool
notices map[string]time.Time
@@ -138,8 +149,32 @@ func (c *Controller) Start(ctx context.Context, makeQueue func(context.Context)
func (c *Controller) record(ctx context.Context, m hadeparture.Message) error {
iid, err := awsterminations.Hint(m.Body, departureCloud(c.cfg.Self))
if err != nil {
+ if m.Receipt != "" {
+ return c.consumer.DeleteReceipt(ctx, m.Receipt)
+ }
return nil
}
+ c.receiptMu.Lock()
+ if c.receipts == nil {
+ c.receipts = map[string]string{}
+ }
+ if len(c.receipts) >= 1024 {
+ for k := range c.receipts {
+ delete(c.receipts, k)
+ break
+ }
+ }
+ if m.Receipt != "" {
+ c.receipts[iid] = m.Receipt
+ }
+ c.receiptMu.Unlock()
+ if c.cfg.Identities != nil {
+ if o, ok, e := c.cfg.Identities.Resolve(ctx, "", iid); e == nil && ok {
+ if d, e := c.cfg.Registry.Departure(ctx, departureID(c.cfg.DeploymentBucket, o.Box)); e == nil && d.Phase == "complete" {
+ return c.ackDeparture(ctx, d)
+ }
+ }
+ }
return c.cfg.Registry.ParkTermination(ctx, registry.HAPendingTermination{Account: c.cfg.Self.Account, Region: c.cfg.Self.Scope.CloudRegion, IID: iid, ReceivedAt: c.now()}, "")
}
func departureID(bucket string, b hadeparture.Box) string {
@@ -352,6 +387,9 @@ func (c *Controller) step(ctx context.Context) error {
continue
}
if e == nil && !known && complete && !h.ReceivedAt.After(started) && !c.cfg.Identities.walkBlocks(blocked, h.IID) {
+ if e = c.ackIID(ctx, h.IID); e != nil {
+ return e
+ }
if e = c.cfg.Registry.RemovePendingTermination(ctx, h); e != nil {
return e
}
@@ -370,6 +408,10 @@ func (c *Controller) step(ctx context.Context) error {
}
}
}
+ if c.cfg.NewReader != nil {
+ _, err := c.ScanPass(ctx)
+ return err
+ }
pending, err := c.cfg.Registry.PendingDepartures(ctx, c.now(), 1)
if err != nil {
return err
@@ -430,3 +472,30 @@ func (c *Controller) step(ctx context.Context) error {
}
return nil
}
+
+func (c *Controller) ackIID(ctx context.Context, iid string) error {
+ c.receiptMu.Lock()
+ defer c.receiptMu.Unlock()
+ receipt := c.receipts[iid]
+ if receipt == "" {
+ return nil
+ }
+ if c.consumer == nil {
+ return errDeparturePending
+ }
+ if err := c.consumer.DeleteReceipt(ctx, receipt); err != nil {
+ return err
+ }
+ delete(c.receipts, iid)
+ return nil
+}
+func (c *Controller) ackDeparture(ctx context.Context, d registry.HADeparture) error {
+ current, err := c.cfg.Registry.Departure(ctx, d.ID)
+ if err != nil {
+ return err
+ }
+ if current.Phase != "complete" {
+ return errDeparturePending
+ }
+ return c.ackIID(ctx, d.Box.InstanceID)
+}
diff --git a/internal/host/hadepartures_scan.go b/internal/host/hadepartures_scan.go
new file mode 100644
index 000000000..ce1e8d630
--- /dev/null
+++ b/internal/host/hadepartures_scan.go
@@ -0,0 +1,415 @@
+package host
+
+import (
+ "context"
+ "crypto/sha256"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "os"
+ "time"
+
+ "github.com/aws/smithy-go"
+ "github.com/carlosframework/platform/internal/activator"
+ "github.com/carlosframework/platform/internal/hafresh"
+ "github.com/carlosframework/platform/internal/lease"
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+type DepartureLockReader interface {
+ ReadLock(context.Context, string, string) (hafresh.View, error)
+}
+
+var errDeparturePending = errors.New("ha_departure_pending")
+
+// MatchesDeparture never treats an unparsed owner or a partial marker as evidence.
+func MatchesDeparture(v hafresh.View, deadRef, deadIID, life string) bool {
+ ref, iid, ok := departureLockIdentity(v, life)
+ return ok && ref == deadRef && iid == deadIID
+}
+
+func departureLockIdentity(v hafresh.View, life string) (string, string, bool) {
+ if v.Absent || v.ETag == "" || v.Lock.Generation < 0 || v.Lock.ExpiresAt.IsZero() || life == "" {
+ return "", "", false
+ }
+ if m := v.Lock.Release; m != nil {
+ return m.Box, m.IID, m.V == 1 && m.Box != "" && m.IID != "" && m.Lifetime == life && v.Lock.Owner == hafresh.MarkerOwner(*m) && !v.Lock.ExpiresAt.After(time.Unix(0, 0))
+ }
+ o, ok := hafresh.ParseOwner(v.Lock.Owner)
+ return o.Ref, o.IID, ok && o.HA && o.IID != ""
+}
+func scanDigest(v any) string { b, _ := json.Marshal(v); return fmt.Sprintf("%x", sha256.Sum256(b)) }
+func (c *Controller) ScanPass(ctx context.Context) (bool, error) {
+ c.scanMu.Lock()
+ defer c.scanMu.Unlock()
+ ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
+ defer cancel()
+ rows, err := c.cfg.Registry.PendingDepartures(ctx, c.now(), 1)
+ if err != nil || len(rows) == 0 {
+ return false, err
+ }
+ d := rows[0]
+ // Reserve the next slot before I/O so one failing departure cannot starve peers.
+ if _, err = c.cfg.Registry.RetryDeparture(ctx, d.ID, c.now(), c.now().Add(30*time.Second), "scan", false); err != nil {
+ return false, err
+ }
+ if d.Phase == "edges_deleted_or_absent" || d.Phase == "indexed" {
+ return true, c.complete(ctx, d.ID)
+ }
+ if !c.evidence[d.ID] {
+ if c.cfg.Identities == nil {
+ return false, errDeparturePending
+ }
+ o, ok, e := c.cfg.Identities.Resolve(ctx, d.Box.Ref, d.Box.InstanceID)
+ if e != nil || !ok {
+ return false, errors.Join(e, errDeparturePending)
+ }
+ if e = c.Enqueue(ctx, o); e != nil {
+ return false, e
+ }
+ d.ObservedAt = c.now()
+ if e = c.cfg.Registry.ReobserveDeparture(ctx, d.ID, d.ObservedAt); e != nil {
+ return false, e
+ }
+ d.Phase = "pending"
+ if c.evidence == nil {
+ c.evidence = map[string]bool{}
+ }
+ c.evidence[d.ID] = true
+ }
+ inv := c.cfg.Inventory()
+ s, err := c.cfg.Registry.DepartureScan(ctx, d.ID)
+ if err != nil {
+ return false, err
+ }
+ // A process restart requires a new qualifying inventory and a new full scan.
+ generation := scanDigest(inv)
+ if d.Phase == "pending" || s.Generation != generation {
+ s.Generation = generation
+ s.Cursor = 0
+ s.Rescan = false
+ s.Unresolved = 0
+ if s.Hosts == nil {
+ s.Hosts = map[string]registry.HADepartureHostScan{}
+ }
+ d.Phase = "scanning"
+ }
+ if !inv.FreshAfter(d.ObservedAt) {
+ return false, c.retryScan(ctx, d, nil, "inventory", true)
+ }
+ if c.cfg.NewReader == nil || c.cfg.Prefix == nil {
+ return false, c.retryScan(ctx, d, nil, "reader", true)
+ }
+ reader, err := c.cfg.NewReader(ctx, d.Box.Scope.CloudRegion)
+ if err != nil {
+ return false, errors.Join(err, c.retryScan(ctx, d, nil, "reader", true))
+ }
+ blockers := []provision.DepartureHost{}
+ count := 0
+ for s.Cursor < len(inv.Records) && count < 32 && ctx.Err() == nil {
+ h := inv.Records[s.Cursor]
+ s.Cursor++
+ count++
+ if h.Placement != d.Box.Scope.Placement {
+ continue
+ }
+ old, seen := s.Hosts[h.Host]
+ if seen && old.Lifetime != h.Lifetime {
+ delete(s.Hosts, h.Host)
+ seen = false
+ old = registry.HADepartureHostScan{}
+ }
+ if h.Lifetime == "" || !provision.ValidHostShape(h.Host) || departureCoverageGap(h, d.Box.Scope) {
+ s.Unresolved++
+ blockers = append(blockers, h)
+ continue
+ }
+ if !s.Rescan && seen && old.RecordDigest == scanDigest(h) && !old.NotBefore.IsZero() && !c.now().After(old.NotBefore) {
+ s.Unresolved++
+ continue
+ }
+ call, done := context.WithTimeout(ctx, 5*time.Second)
+ v, e := reader.ReadLock(call, d.Box.Scope.DataBucket, c.cfg.Prefix(h.Host))
+ done()
+ if e != nil {
+ s.Unresolved++
+ continue
+ }
+ if v.Absent {
+ if seen {
+ s.Unresolved++
+ }
+ continue
+ }
+ ref, iid, valid := departureLockIdentity(v, h.Lifetime)
+ if !valid {
+ s.Unresolved++
+ blockers = append(blockers, h)
+ continue
+ }
+ match := MatchesDeparture(v, d.Box.Ref, d.Box.InstanceID, h.Lifetime)
+ if !match {
+ if seen && v.Lock.Generation <= old.Observed.Lock.Generation {
+ s.Unresolved++
+ continue
+ }
+ if c.cfg.ValidateSuccessor == nil {
+ s.Unresolved++
+ continue
+ }
+ ok, e := c.cfg.ValidateSuccessor(ctx, ref, iid)
+ if e != nil || !ok {
+ s.Unresolved++
+ continue
+ }
+ if seen {
+ old.Result = "superseded"
+ old.NotBefore = time.Time{}
+ s.Hosts[h.Host] = old
+ }
+ continue
+ }
+ if !seen {
+ old = registry.HADepartureHostScan{Lifetime: h.Lifetime, Observed: v}
+ }
+ // Keep the strongest departure observation across retries and record changes.
+ if v.Lock.Generation >= old.Observed.Lock.Generation {
+ old.Observed = v
+ }
+ old.RecordDigest = scanDigest(h)
+ old.Result = "pending"
+ old.NotBefore = time.Time{}
+ s.Hosts[h.Host] = old
+ if s.Rescan {
+ s.Unresolved++
+ continue
+ }
+ if !CanAdopt(h, c.cfg.Policy()) || !h.HA {
+ s.Unresolved++
+ blockers = append(blockers, h)
+ continue
+ }
+ if v.Lock.Release == nil && !c.now().After(v.Lock.ExpiresAt) {
+ old.NotBefore = v.Lock.ExpiresAt
+ s.Hosts[h.Host] = old
+ s.Unresolved++
+ continue
+ }
+ // Save the source authority before the importer may transfer it.
+ if e = c.cfg.Registry.SaveDepartureScan(ctx, d.ID, "scanning", s); e != nil {
+ return true, e
+ }
+ s.Version++
+ if c.cfg.Adopt == nil {
+ s.Unresolved++
+ continue
+ }
+ result, e := c.cfg.Adopt(ctx, h, d, v)
+ if e != nil || result == activator.Deferred {
+ s.Unresolved++
+ if errors.Is(e, registry.ErrHAWake) {
+ blockers = append(blockers, h)
+ }
+ continue
+ }
+ old.Result = fmt.Sprint(result)
+ s.Hosts[h.Host] = old
+ }
+ if ctx.Err() != nil {
+ return true, ctx.Err()
+ }
+ // A changed or incomplete published inventory invalidates the entire pass.
+ if scanDigest(c.cfg.Inventory()) != generation {
+ s.Generation = ""
+ s.Cursor = 0
+ s.Rescan = false
+ s.Unresolved++
+ }
+ phase := "scanning"
+ if s.Cursor == len(inv.Records) && s.Generation == generation {
+ if s.Rescan && CanCompleteDeparture(RescanResult{Inventory: inv, EvidenceAt: d.ObservedAt, Finished: true, Unresolved: s.Unresolved}) {
+ phase = "authority_complete"
+ } else {
+ // A clean adoption pass is followed by an independent full lock walk.
+ s.Rescan = s.Unresolved == 0
+ s.Cursor = 0
+ s.Unresolved = 0
+ }
+ }
+ if err = c.cfg.Registry.SaveDepartureScan(ctx, d.ID, phase, s); err != nil {
+ return true, err
+ }
+ if phase == "authority_complete" {
+ return true, c.complete(ctx, d.ID)
+ }
+ return true, c.retryScan(ctx, d, blockers, "scan", len(blockers) > 0 || s.Unresolved > 0)
+}
+func (c *Controller) retryScan(ctx context.Context, d registry.HADeparture, hosts []provision.DepartureHost, code string, page bool) error {
+ claimed, err := c.cfg.Registry.RetryDeparture(ctx, d.ID, c.now(), c.now().Add(30*time.Second), code, page)
+ if err != nil {
+ return err
+ }
+ if claimed {
+ c.logf("Duties from box %s have not been recovered. The scan will retry automatically. Check the box's wake state before removing its records.", d.Box.Ref)
+ if c.cfg.Page != nil {
+ return c.cfg.Page(ctx, d, hosts)
+ }
+ }
+ return nil
+}
+func (c *Controller) Complete(ctx context.Context, id string) error {
+ c.scanMu.Lock()
+ defer c.scanMu.Unlock()
+ return c.complete(ctx, id)
+}
+func (c *Controller) complete(ctx context.Context, id string) error {
+ d, err := c.cfg.Registry.Departure(ctx, id)
+ if err != nil {
+ return err
+ }
+ if d.Phase == "complete" {
+ return c.ackDeparture(ctx, d)
+ }
+ s, err := c.cfg.Registry.DepartureScan(ctx, id)
+ if err != nil {
+ return err
+ }
+ save := func(phase string) error {
+ e := c.cfg.Registry.SaveDepartureScan(ctx, id, phase, s)
+ if e == nil {
+ s.Version++
+ d.Phase = phase
+ }
+ return e
+ }
+ if d.Phase != "authority_complete" && d.Phase != "edges_deleted_or_absent" && d.Phase != "indexed" {
+ return errDeparturePending
+ }
+ if c.cfg.OpenStore == nil {
+ return errDeparturePending
+ }
+ store, err := c.cfg.OpenStore(ctx)
+ if err != nil {
+ return err
+ }
+ indexed, ok := store.(release.IndexedDeleter)
+ if !ok {
+ return release.ErrConditionalDeleteUnsupported
+ }
+ if d.EdgesKey != "control/edges/"+d.Box.Ref+".json" {
+ return errDepartureScope
+ }
+ if d.Phase == "authority_complete" {
+ inv := c.cfg.Inventory()
+ if !inv.FreshAfter(d.ObservedAt) || scanDigest(inv) != s.Generation {
+ s.Cursor = 0
+ s.Rescan = false
+ s.Generation = ""
+ return save("scanning")
+ }
+ tag := d.EdgesETag
+ if s.EdgesETag != "" {
+ tag = s.EdgesETag
+ }
+ if s.DeleteUncertain || tag == "" {
+ call, cancel := context.WithTimeout(ctx, 5*time.Second)
+ raw, newTag, e := store.Get(call, d.EdgesKey)
+ cancel()
+ if errors.Is(e, os.ErrNotExist) {
+ if err = save("edges_deleted_or_absent"); err != nil {
+ return err
+ }
+ } else if e != nil {
+ return e
+ } else {
+ // Replacements need their own full scan, and must retain the exact binding.
+ var f struct{ Box, BoxID, Region, Placement, DataBucket, SecretsKeyFP, IID string }
+ var wire map[string]json.RawMessage
+ if json.Unmarshal(raw, &wire) != nil {
+ return errDepartureScope
+ }
+ get := func(k string) string { var v string; _ = json.Unmarshal(wire[k], &v); return v }
+ f.Box = get("box")
+ f.BoxID = get("box_id")
+ f.Region = get("region")
+ f.Placement = get("placement")
+ f.DataBucket = get("data_bucket")
+ f.SecretsKeyFP = get("secrets_key_fp")
+ f.IID = get("instance_id")
+ if f.Box != d.Box.Ref || (f.BoxID != "" && f.BoxID != d.Box.Ref) || f.Region != d.Box.Scope.CloudRegion || f.Placement != d.Box.Scope.Placement || f.DataBucket != d.Box.Scope.DataBucket || f.SecretsKeyFP != d.Box.Scope.SecretsKeyFP || (f.IID != "" && f.IID != d.Box.InstanceID) || string(wire["placement"]) == "null" {
+ return errDepartureScope
+ }
+ if c.cfg.Identities == nil {
+ return errDepartureIdentity
+ }
+ o, known, e := c.cfg.Identities.Resolve(ctx, d.Box.Ref, d.Box.InstanceID)
+ if e != nil || !known || o.Box != d.Box {
+ return errDepartureIdentity
+ }
+ s.EdgesETag = newTag
+ s.DeleteUncertain = false
+ s.Generation = ""
+ s.Rescan = false
+ s.Cursor = 0
+ return save("scanning")
+ }
+ }
+ if d.Phase == "authority_complete" {
+ // Persist uncertainty before the call, including death after the remote effect.
+ s.DeleteUncertain = true
+ if err = save("authority_complete"); err != nil {
+ return err
+ }
+ call, cancel := context.WithTimeout(ctx, 5*time.Second)
+ err = indexed.DeleteRevision(call, d.EdgesKey, tag)
+ cancel()
+ if err != nil {
+ var ae smithy.APIError
+ if errors.As(err, &ae) && ae.ErrorCode() == "AccessDenied" {
+ s.DeleteUncertain = false
+ if !s.PermissionAlerted {
+ s.PermissionAlerted = true
+ if e := save("authority_complete"); e != nil {
+ return e
+ }
+ c.logf("ha_departure_permission id=%s code=AccessDenied", id)
+ if c.cfg.Page != nil {
+ _ = c.cfg.Page(ctx, d, nil)
+ }
+ } else {
+ if e := save("authority_complete"); e != nil {
+ return e
+ }
+ }
+ }
+ _ = c.retryScan(ctx, d, nil, "delete", false)
+ return err
+ }
+ if err = save("edges_deleted_or_absent"); err != nil {
+ return err
+ }
+ }
+ }
+ if d.Phase == "edges_deleted_or_absent" {
+ call, cancel := context.WithTimeout(ctx, 5*time.Second)
+ err = indexed.IndexDeletion(call, d.EdgesKey)
+ cancel()
+ if err != nil {
+ _ = c.retryScan(ctx, d, nil, "index", false)
+ return err
+ }
+ if err = save("indexed"); err != nil {
+ return err
+ }
+ }
+ if err = save("complete"); err != nil {
+ return err
+ }
+ c.logf("Recovered duties for %d instances from box %s.", len(s.Hosts), d.Box.Ref)
+ return c.ackDeparture(ctx, d)
+}
+func defaultDepartureReader(ctx context.Context, region string) (DepartureLockReader, error) {
+ return lease.NewLockReader(ctx, region)
+}
diff --git a/internal/host/hadepartures_scan_test.go b/internal/host/hadepartures_scan_test.go
new file mode 100644
index 000000000..a7c5e163a
--- /dev/null
+++ b/internal/host/hadepartures_scan_test.go
@@ -0,0 +1,356 @@
+package host
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "github.com/aws/smithy-go"
+ "path/filepath"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/activator"
+ "github.com/carlosframework/platform/internal/hadeparture"
+ "github.com/carlosframework/platform/internal/hafresh"
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+type scanReader struct {
+ views map[string]hafresh.View
+ reads int
+ err error
+}
+
+func (r *scanReader) ReadLock(ctx context.Context, bucket, prefix string) (hafresh.View, error) {
+ r.reads++
+ if r.err != nil {
+ return hafresh.View{}, r.err
+ }
+ v, ok := r.views[prefix]
+ if !ok {
+ return hafresh.View{Absent: true}, nil
+ }
+ return v, nil
+}
+
+type scanRig struct {
+ c *Controller
+ r *registry.Registry
+ inv provision.InventorySnapshot
+ locks *scanReader
+ now time.Time
+ d registry.HADeparture
+ store *release.DirStore
+ imports int
+}
+
+func newScanRig(t *testing.T, n int) *scanRig {
+ t.Helper()
+ r, err := registry.Open(filepath.Join(t.TempDir(), "registry.db"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { r.Close() })
+ x := &scanRig{r: r, now: time.Now(), locks: &scanReader{views: map[string]hafresh.View{}}, store: release.NewDirStore(t.TempDir())}
+ scope := hadeparture.Scope{CloudRegion: "eu-west-1", DataBucket: "data", SecretsKeyFP: "fp"}
+ x.d = registry.HADeparture{Departure: hadeparture.Departure{ID: "dead", Box: hadeparture.Box{Ref: "dead", InstanceID: "i-1123456789abcdef0", Account: "111122223333", Scope: scope}, ObservedAt: x.now.Add(-time.Hour), EdgesKey: "control/edges/dead.json"}, ProofKey: "proof", ProofDigest: "digest"}
+ x.d.EdgesETag, err = x.store.Put(t.Context(), x.d.EdgesKey, []byte(`{"box":"dead"}`), "")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err = r.EnrollDeparture(t.Context(), x.d, ""); err != nil {
+ t.Fatal(err)
+ }
+ x.inv = provision.InventorySnapshot{Generation: "one", Complete: true, WalkStartedAt: x.now, SourceReadStartedAt: x.now}
+ for i := 0; i < n; i++ {
+ h := provision.DepartureHost{Host: fmt.Sprintf("shop%d.example.com", i), Account: "acct", App: "shop", Kind: "instance", HA: true, Lifetime: "life", Revision: "one"}
+ x.inv.Records = append(x.inv.Records, h)
+ x.locks.views[h.Host] = hafresh.View{ETag: "old", Lock: hafresh.Lock{Generation: 1, ExpiresAt: time.Unix(0, 0), Owner: "released/v1;ref=dead;iid=i-1123456789abcdef0", Release: &hafresh.Marker{V: 1, Box: "dead", IID: "i-1123456789abcdef0", Lifetime: "life"}}}
+ }
+ x.c = &Controller{cfg: DepartureConfig{Registry: r, Self: hadeparture.Box{Ref: "self", Scope: scope}, Inventory: func() provision.InventorySnapshot { return x.inv }, Policy: func() LocalPolicy { return LocalPolicy{Scope: scope} }, Now: func() time.Time { return x.now }, Logf: func(string, ...any) {}, OpenStore: func(context.Context) (release.Store, error) { return x.store, nil }, NewReader: func(context.Context, string) (DepartureLockReader, error) { return x.locks, nil }, Prefix: func(h string) string { return h }, ValidateSuccessor: func(context.Context, string, string) (bool, error) { return true, nil }}, evidence: map[string]bool{"dead": true}}
+ x.c.cfg.Adopt = func(ctx context.Context, h provision.DepartureHost, d registry.HADeparture, v hafresh.View) (activator.AdoptResult, error) {
+ x.imports++
+ v.ETag = "new"
+ v.Lock.Generation++
+ if v.Lock.Release == nil {
+ v.Lock.Release = &hafresh.Marker{V: 1, Lifetime: h.Lifetime}
+ v.Lock.ExpiresAt = time.Unix(0, 0)
+ }
+ v.Lock.Release.Box = "self"
+ v.Lock.Release.IID = "i-0123456789abcdef0"
+ v.Lock.Owner = hafresh.MarkerOwner(*v.Lock.Release)
+ x.locks.views[h.Host] = v
+ return activator.Adopted, nil
+ }
+ return x
+}
+func (x *scanRig) pass(t *testing.T) {
+ t.Helper()
+ _, err := x.c.ScanPass(t.Context())
+ if err != nil {
+ t.Fatal(err)
+ }
+ x.now = x.now.Add(31 * time.Second)
+}
+func TestDepartureCompletionRescan(t *testing.T) {
+ x := newScanRig(t, 33)
+ x.pass(t)
+ if x.locks.reads != 32 || x.imports != 32 {
+ t.Fatal(x.locks.reads, x.imports)
+ }
+ x.pass(t)
+ if x.imports != 33 {
+ t.Fatal(x.imports)
+ }
+ if _, _, err := x.store.Get(t.Context(), x.d.EdgesKey); err != nil {
+ t.Fatal("early delete", err)
+ }
+ x.pass(t)
+ if x.locks.reads != 65 {
+ t.Fatal(x.locks.reads)
+ }
+ x.pass(t)
+ if x.locks.reads != 66 {
+ t.Fatal(x.locks.reads)
+ }
+ d, err := x.r.Departure(t.Context(), x.d.ID)
+ if err != nil || d.Phase != "complete" {
+ t.Fatal(d, err)
+ }
+}
+func TestDepartureNoEarlyDelete(t *testing.T) {
+ x := newScanRig(t, 1)
+ x.c.cfg.Adopt = func(context.Context, provision.DepartureHost, registry.HADeparture, hafresh.View) (activator.AdoptResult, error) {
+ return activator.Adopted, nil
+ }
+ for range 4 {
+ x.pass(t)
+ }
+ d, err := x.r.Departure(t.Context(), x.d.ID)
+ if err != nil || d.Phase == "complete" {
+ t.Fatal(d, err)
+ }
+ if _, _, err = x.store.Get(t.Context(), x.d.EdgesKey); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func TestDepartureWaitsExpiry(t *testing.T) {
+ x := newScanRig(t, 1)
+ h := x.inv.Records[0]
+ v := x.locks.views[h.Host]
+ v.Lock.Release = nil
+ v.Lock.Owner = hafresh.OwnerFor(hafresh.Self{Ref: x.d.Box.Ref, IID: x.d.Box.InstanceID}, 1, true)
+ v.Lock.ExpiresAt = x.now.Add(time.Hour)
+ x.locks.views[h.Host] = v
+ x.pass(t)
+ x.pass(t)
+ if x.imports != 0 || x.locks.reads != 1 {
+ t.Fatal(x.imports, x.locks.reads)
+ }
+ x.now = v.Lock.ExpiresAt.Add(time.Nanosecond)
+ x.pass(t)
+ if x.imports != 1 {
+ t.Fatal(x.imports)
+ }
+}
+func TestDepartureScanOwnersAndReleasers(t *testing.T) {
+ x := newScanRig(t, 3)
+ h := x.inv.Records[0]
+ v := x.locks.views[h.Host]
+ v.Lock.Release = nil
+ v.Lock.ExpiresAt = x.now.Add(-time.Hour)
+ v.Lock.Owner = hafresh.OwnerFor(hafresh.Self{Ref: x.d.Box.Ref, IID: x.d.Box.InstanceID}, 1, true)
+ x.locks.views[h.Host] = v
+ x.inv.Records[2].Kind = "sidecar"
+ x.inv.Records[2].HA = false
+ x.pass(t)
+ if x.imports != 2 {
+ t.Fatal(x.imports)
+ }
+ d, e := x.r.Departure(t.Context(), x.d.ID)
+ if e != nil || d.Phase == "complete" {
+ t.Fatal(d, e)
+ }
+}
+func TestDepartureRescanInvalidation(t *testing.T) {
+ for _, mode := range []string{"dead remains", "absence", "malformed", "unbound successor", "new record", "incomplete"} {
+ t.Run(mode, func(t *testing.T) {
+ x := newScanRig(t, 1)
+ h := x.inv.Records[0]
+ original := x.locks.views[h.Host]
+ original.Lock.Release = nil
+ original.Lock.Owner = hafresh.OwnerFor(hafresh.Self{Ref: x.d.Box.Ref, IID: x.d.Box.InstanceID}, 1, true)
+ original.Lock.ExpiresAt = x.now.Add(-time.Hour)
+ x.pass(t)
+ switch mode {
+ case "dead remains":
+ x.locks.views[h.Host] = original
+ case "absence":
+ delete(x.locks.views, h.Host)
+ case "malformed":
+ x.locks.views[h.Host] = hafresh.View{ETag: "bad"}
+ case "unbound successor":
+ x.c.cfg.ValidateSuccessor = func(context.Context, string, string) (bool, error) { return false, nil }
+ case "new record":
+ h.Host = "new.example.com"
+ h.Pool = "other"
+ x.inv.Records = append(x.inv.Records, h)
+ x.locks.views[h.Host] = original
+ case "incomplete":
+ x.inv.Complete = false
+ }
+ x.pass(t)
+ d, e := x.r.Departure(t.Context(), x.d.ID)
+ if e != nil || d.Phase == "complete" {
+ t.Fatal(d, e)
+ }
+ })
+ }
+}
+
+type completionStore struct {
+ release.Store
+ raw release.IndexedDeleter
+ deletes, indexes int
+ deny, lost, indexFail bool
+}
+
+func (s *completionStore) DeleteRevision(ctx context.Context, k, e string) error {
+ s.deletes++
+ if s.deny {
+ return &smithy.GenericAPIError{Code: "AccessDenied"}
+ }
+ err := s.raw.DeleteRevision(ctx, k, e)
+ if err == nil && s.lost {
+ s.lost = false
+ return errors.New("lost_response")
+ }
+ return err
+}
+func (s *completionStore) IndexDeletion(ctx context.Context, k string) error {
+ s.indexes++
+ if s.indexFail {
+ return errors.New("index_offline")
+ }
+ return s.raw.IndexDeletion(ctx, k)
+}
+func TestDepartureDeleteDenied(t *testing.T) {
+ x := newScanRig(t, 1)
+ store := &completionStore{Store: x.store, raw: x.store, deny: true}
+ x.c.cfg.OpenStore = func(context.Context) (release.Store, error) { return store, nil }
+ pages := 0
+ x.c.cfg.Page = func(context.Context, registry.HADeparture, []provision.DepartureHost) error { pages++; return nil }
+ x.pass(t)
+ _, err := x.c.ScanPass(t.Context())
+ if err == nil {
+ t.Fatal("denial swallowed")
+ }
+ for range 3 {
+ _ = x.c.Complete(t.Context(), x.d.ID)
+ }
+ if pages != 1 || store.indexes != 0 || x.imports != 1 {
+ t.Fatal(pages, store.indexes, x.imports)
+ }
+ store.deny = false
+ if err = x.c.Complete(t.Context(), x.d.ID); err != nil {
+ t.Fatal(err)
+ }
+ if x.imports != 1 {
+ t.Fatal("reimported")
+ }
+}
+func TestDepartureDeletionRace(t *testing.T) {
+ for _, mode := range []string{"lost", "index", "replacement"} {
+ t.Run(mode, func(t *testing.T) {
+ x := newScanRig(t, 1)
+ store := &completionStore{Store: x.store, raw: x.store}
+ x.c.cfg.OpenStore = func(context.Context) (release.Store, error) { return store, nil }
+ x.pass(t)
+ switch mode {
+ case "lost":
+ store.lost = true
+ case "index":
+ store.indexFail = true
+ case "replacement":
+ _, err := x.store.Put(t.Context(), x.d.EdgesKey, []byte(`{"box":"replacement","instance_id":"i-other"}`), x.d.EdgesETag)
+ if err != nil {
+ t.Fatal(err)
+ }
+ }
+ _, err := x.c.ScanPass(t.Context())
+ if err == nil {
+ t.Fatal("failure swallowed")
+ }
+ d, e := x.r.Departure(t.Context(), x.d.ID)
+ if e != nil || d.Phase == "complete" {
+ t.Fatal(d, e)
+ }
+ store.indexFail = false
+ err = x.c.Complete(t.Context(), x.d.ID)
+ if mode == "replacement" {
+ if err == nil {
+ t.Fatal("replacement accepted")
+ }
+ if _, _, e = x.store.Get(t.Context(), x.d.EdgesKey); e != nil {
+ t.Fatal(e)
+ }
+ } else {
+ if err != nil {
+ t.Fatal(err)
+ }
+ if store.deletes != 1 || x.imports != 1 {
+ t.Fatal(store.deletes, x.imports)
+ }
+ }
+ })
+ }
+}
+func TestDepartureRequestBudget(t *testing.T) {
+ x := newScanRig(t, 65)
+ constructs := 0
+ x.c.cfg.NewReader = func(context.Context, string) (DepartureLockReader, error) { constructs++; return x.locks, nil }
+ for range 6 {
+ before := x.locks.reads
+ x.pass(t)
+ if x.locks.reads-before > 32 {
+ t.Fatal("page exceeded", x.locks.reads-before)
+ }
+ }
+ if x.locks.reads != 130 || constructs != 6 || x.imports != 65 {
+ t.Fatal(x.locks.reads, constructs, x.imports)
+ }
+ x.pass(t)
+ if constructs != 6 {
+ t.Fatal("idle opened reader")
+ }
+}
+func TestDepartureFairScheduling(t *testing.T) {
+ x := newScanRig(t, 65)
+ d := x.d
+ d.ID = "other"
+ d.Box.Ref = "other"
+ d.Box.InstanceID = "i-2123456789abcdef0"
+ d.EdgesKey = "control/edges/other.json"
+ d.EdgesETag = "other"
+ if err := x.r.EnrollDeparture(t.Context(), d, ""); err != nil {
+ t.Fatal(err)
+ }
+ x.c.evidence[d.ID] = true
+ for range 4 {
+ x.pass(t)
+ }
+ a, err := x.r.DepartureScan(t.Context(), x.d.ID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ b, err := x.r.DepartureScan(t.Context(), d.ID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if a.Cursor != 64 || b.Cursor != 64 {
+ t.Fatal(a.Cursor, b.Cursor)
+ }
+}
diff --git a/internal/host/hadepartures_wiring.go b/internal/host/hadepartures_wiring.go
index 2714ee069..c70256d9d 100644
--- a/internal/host/hadepartures_wiring.go
+++ b/internal/host/hadepartures_wiring.go
@@ -3,7 +3,9 @@ package host
import (
"context"
"encoding/json"
+ "errors"
"fmt"
+ "github.com/carlosframework/platform/internal/hafresh"
"log"
"strconv"
"strings"
@@ -103,13 +105,21 @@ func armHADepartures(ctx context.Context, a departureArm) (*Controller, hadepart
return api, nil
}
}
- c, err := NewController(DepartureConfig{Registry: a.Registry, Identities: repo, Confirmer: a.Confirmer, Cache: cache, ProofStore: a.ProofStore, Self: a.Self, DeploymentBucket: a.Getenv("CARLOS_DEPLOYMENT_BUCKET"), Inventory: func() provision.InventorySnapshot { return departureInventorySnapshot(a.Inventory) }, Policy: func() LocalPolicy {
+ c, err := NewController(DepartureConfig{Registry: a.Registry, OpenStore: a.OpenStore, NewReader: defaultDepartureReader, Prefix: func(host string) string { return activator.HibernatePrefix(a.Backend.Cfg.Prefix, host) }, Identities: repo, Confirmer: a.Confirmer, Cache: cache, ProofStore: a.ProofStore, Self: a.Self, DeploymentBucket: a.Getenv("CARLOS_DEPLOYMENT_BUCKET"), Inventory: func() provision.InventorySnapshot { return departureInventorySnapshot(a.Inventory) }, Policy: func() LocalPolicy {
return LocalPolicy{Scope: a.Self.Scope, Pools: provision.ParseBoxPools(a.Getenv("CARLOS_POOLS"))}
}, Invalidate: a.Service.InvalidateDutyHolder, PageIdentity: func(ctx context.Context, h registry.HAPendingTermination, code string) error {
return PageOperator(ctx, alerting.LevelWarning, "ha_departure_pending", fmt.Sprintf("code=%s account=%s region=%s iid=%s", code, h.Account, h.Region, h.IID))
}, Page: func(ctx context.Context, d registry.HADeparture, hosts []provision.DepartureHost) error {
- var messages []string
+ messages := []string{fmt.Sprintf("Duties from box %s have not been recovered. The scan will retry automatically. Check the box's wake state before removing its records.", d.Box.Ref)}
for _, h := range hosts {
+ if h.Kind != "sidecar" {
+ pool := h.Pool
+ if pool == "" {
+ pool = "shared"
+ }
+ messages = append(messages, fmt.Sprintf("Duties for instance %s need a box that serves pool %s. Recovery is incomplete.", h.Host, pool))
+ continue
+ }
messages = append(messages, fmt.Sprintf("Duties for sidecar %s cannot be recovered by this version. Keep the departure records. The departure stays open. Upgrading alone will not recover the sidecar.", h.Host))
}
return PageOperator(ctx, alerting.LevelWarning, fmt.Sprintf("Duties from box %s need attention", d.Box.Ref), strings.Join(messages, "\n"))
@@ -160,6 +170,32 @@ func armHADepartures(ctx context.Context, a departureArm) (*Controller, hadepart
o, known, err := repo.Resolve(ctx, ref, iid)
return known && o.Known && !o.PlacementNull && o.Box.Account == a.Self.Account && o.Box.Scope == a.Self.Scope, err
}
+ c.cfg.ValidateSuccessor = a.Service.AdoptionIdentity
+ c.cfg.Adopt = func(ctx context.Context, h provision.DepartureHost, d registry.HADeparture, v hafresh.View) (activator.AdoptResult, error) {
+ rt, err := a.Registry.Get(h.Host)
+ if err != nil {
+ return activator.Deferred, err
+ }
+ if rt == nil || rt.Account != h.Account || rt.App != h.App || rt.Pool != h.Pool || rt.Region != h.Placement {
+ return activator.Deferred, registry.ErrHAChanged
+ }
+ pair := registry.Pair{Incarnation: rt.Incarnation, ServingSeq: rt.ServingSeq}
+ duty, ok, err := a.Registry.HADuty(h.Host, h.Lifetime)
+ if err != nil {
+ return activator.Deferred, err
+ }
+ if !ok {
+ bound, e := a.Registry.BindHADuty(ctx, h.Host, pair, h.Lifetime, duty.Revision)
+ if e != nil || !bound {
+ return activator.Deferred, errors.Join(e, registry.ErrHAChanged)
+ }
+ duty, err = a.Registry.LoadDuty(ctx, h.Host, h.Lifetime)
+ if err != nil {
+ return activator.Deferred, err
+ }
+ }
+ return a.Service.AdoptHost(ctx, *rt, activator.Adoption{Departure: d.ID, Ref: d.Box.Ref, IID: d.Box.InstanceID, Lifetime: h.Lifetime, Pair: pair, Revision: duty.Revision, Observed: v})
+ }
a.Service.OnDepartureSuspect = c.Suspect
life, err := c.Start(ctx, queue)
if err != nil {
diff --git a/internal/lease/ha.go b/internal/lease/ha.go
index 37660360b..0e5192910 100644
--- a/internal/lease/ha.go
+++ b/internal/lease/ha.go
@@ -182,16 +182,33 @@ func (h *Held) View() hafresh.View { return h.view }
// ReadLock reads s3://bucket/<prefix>/lock.json with its ETag, through the
// client Acquire builds. Only S3's NoSuchKey is Absent.
-func ReadLock(ctx context.Context, bucket, prefix, region string) (hafresh.View, error) {
+type LockReader struct{ client lss3.S3API }
+
+func NewLockReader(ctx context.Context, region string) (*LockReader, error) {
+ client, _, err := newLeaserClient(ctx, region)
+ if err != nil {
+ return nil, err
+ }
+ return &LockReader{client: client}, nil
+}
+func (r *LockReader) ReadLock(ctx context.Context, bucket, prefix string) (hafresh.View, error) {
key, err := lockKey(bucket, prefix)
if err != nil {
return hafresh.View{}, err
}
- client, _, err := newLeaserClient(ctx, region)
+ ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
+ defer cancel()
+ return readView(ctx, r.client, bucket, key)
+}
+func ReadLock(ctx context.Context, bucket, prefix, region string) (hafresh.View, error) {
+ if _, err := lockKey(bucket, prefix); err != nil {
+ return hafresh.View{}, err
+ }
+ r, err := NewLockReader(ctx, region)
if err != nil {
return hafresh.View{}, err
}
- return readView(ctx, client, bucket, key)
+ return r.ReadLock(ctx, bucket, prefix)
}
// PrefixEmpty reports whether nothing at all is stored under prefix/: one
diff --git a/internal/registry/ha_journal.go b/internal/registry/ha_journal.go
index afaf24639..58cf2f03b 100644
--- a/internal/registry/ha_journal.go
+++ b/internal/registry/ha_journal.go
@@ -54,8 +54,10 @@ type haJournalRequest struct {
Identity HABoxIdentity
Walk HAIdentityWalk
Hint HAPendingTermination
+ Scan HADepartureScan
}
type haJournalResponse struct {
+ Scan HADepartureScan
Inbox []HATerminationInbox
Hints []HAPendingTermination
Departures []HADeparture
@@ -71,6 +73,7 @@ func (r *Registry) migrateHAJournal() error {
CREATE TABLE IF NOT EXISTS ha_departures(id TEXT PRIMARY KEY,body BLOB NOT NULL,phase TEXT NOT NULL DEFAULT 'pending',next_attempt INTEGER NOT NULL,last_page INTEGER NOT NULL DEFAULT 0,last_error TEXT NOT NULL DEFAULT '');
CREATE TABLE IF NOT EXISTS ha_box_identities(ref TEXT PRIMARY KEY,iid TEXT NOT NULL UNIQUE,body BLOB NOT NULL);
CREATE TABLE IF NOT EXISTS ha_confirmation_retries(ref TEXT PRIMARY KEY,next_attempt INTEGER NOT NULL,attempts INTEGER NOT NULL);
+ CREATE TABLE IF NOT EXISTS ha_departure_scans(id TEXT PRIMARY KEY,body BLOB NOT NULL,version INTEGER NOT NULL);
CREATE TABLE IF NOT EXISTS ha_identity_pages(id INTEGER PRIMARY KEY CHECK(id=1),last_page INTEGER NOT NULL);
CREATE TABLE IF NOT EXISTS ha_identity_walk(id INTEGER PRIMARY KEY CHECK(id=1),body BLOB NOT NULL);
`)
@@ -164,6 +167,8 @@ func (r *Registry) haJournal(ctx context.Context, q haJournalRequest) (out haJou
return resp.HAJournal, e
}
switch q.Op {
+ case "departure", "scan", "scan_save":
+ return r.departureScanJournal(ctx, q)
case "park":
h := q.Hint
if len(h.Account) != 12 || len(h.Region) == 0 || len(h.Region) > 32 || len(h.IID) > 32 || len(h.IID) < 3 || h.ReceivedAt.IsZero() {
diff --git a/internal/registry/ha_scan.go b/internal/registry/ha_scan.go
new file mode 100644
index 000000000..707ef98af
--- /dev/null
+++ b/internal/registry/ha_scan.go
@@ -0,0 +1,129 @@
+package registry
+
+import (
+ "context"
+ "database/sql"
+ "encoding/json"
+ "errors"
+ "time"
+
+ "github.com/carlosframework/platform/internal/hafresh"
+)
+
+type HADepartureHostScan struct {
+ RecordDigest, Lifetime string
+ Observed hafresh.View
+ Result string
+ NotBefore time.Time
+}
+type HADepartureScan struct {
+ Version uint64
+ Generation string
+ Cursor int
+ Rescan bool
+ Unresolved int
+ Hosts map[string]HADepartureHostScan
+ DeleteUncertain bool
+ EdgesETag string
+ PermissionAlerted bool
+}
+
+func (r *Registry) Departure(ctx context.Context, id string) (HADeparture, error) {
+ out, err := r.haJournal(ctx, haJournalRequest{Op: "departure", ID: id})
+ if err != nil {
+ return HADeparture{}, err
+ }
+ if len(out.Departures) != 1 {
+ return HADeparture{}, ErrHAJournal
+ }
+ return out.Departures[0], nil
+}
+func (r *Registry) DepartureScan(ctx context.Context, id string) (HADepartureScan, error) {
+ out, err := r.haJournal(ctx, haJournalRequest{Op: "scan", ID: id})
+ return out.Scan, err
+}
+func (r *Registry) SaveDepartureScan(ctx context.Context, id, phase string, s HADepartureScan) error {
+ _, err := r.haJournal(ctx, haJournalRequest{Op: "scan_save", ID: id, Code: phase, Scan: s})
+ return err
+}
+func (r *Registry) departureScanJournal(ctx context.Context, q haJournalRequest) (out haJournalResponse, err error) {
+ if q.Op == "departure" {
+ var body []byte
+ var phase, code string
+ var next, page int64
+ err = r.sql.QueryRowContext(ctx, `SELECT body,phase,next_attempt,last_page,last_error FROM ha_departures WHERE id=?`, q.ID).Scan(&body, &phase, &next, &page, &code)
+ if err != nil {
+ return out, err
+ }
+ var d HADeparture
+ if err = json.Unmarshal(body, &d); err != nil {
+ return out, err
+ }
+ d.Phase = phase
+ d.LastError = code
+ d.NextAttempt = journalDate(next)
+ d.LastPage = journalDate(page)
+ out.Departures = []HADeparture{d}
+ return out, nil
+ }
+ if q.Op == "scan" {
+ var body []byte
+ err = r.sql.QueryRowContext(ctx, `SELECT body FROM ha_departure_scans WHERE id=?`, q.ID).Scan(&body)
+ if errors.Is(err, sql.ErrNoRows) {
+ return out, nil
+ }
+ if err == nil {
+ err = json.Unmarshal(body, &out.Scan)
+ }
+ return out, err
+ }
+ tx, err := r.beginClaimTransaction(ctx, true)
+ if err != nil {
+ return out, err
+ }
+ defer tx.Rollback()
+ var phase string
+ if err = tx.QueryRowContext(ctx, `SELECT phase FROM ha_departures WHERE id=?`, q.ID).Scan(&phase); err != nil {
+ return out, err
+ }
+ allowed := map[string]map[string]bool{
+ "pending": {"scanning": true}, "scanning": {"scanning": true, "authority_complete": true},
+ "authority_complete": {"scanning": true, "authority_complete": true, "edges_deleted_or_absent": true},
+ "edges_deleted_or_absent": {"edges_deleted_or_absent": true, "indexed": true}, "indexed": {"complete": true},
+ }
+ if !allowed[phase][q.Code] {
+ return out, ErrHAJournal
+ }
+ s := q.Scan
+ s.Version++
+ body, err := json.Marshal(s)
+ if err != nil {
+ return out, err
+ }
+ res, err := tx.ExecContext(ctx, `INSERT INTO ha_departure_scans(id,body,version) SELECT ?,?,? WHERE ?=0 ON CONFLICT(id) DO UPDATE SET body=excluded.body,version=excluded.version WHERE version=?`, q.ID, body, s.Version, q.Scan.Version, q.Scan.Version)
+ // Existing rows need an UPDATE; INSERT SELECT's guard deliberately excludes them.
+ if err != nil {
+ return out, err
+ }
+ n, err := res.RowsAffected()
+ if err != nil {
+ return out, err
+ }
+ if n == 0 && q.Scan.Version > 0 {
+ res, err = tx.ExecContext(ctx, `UPDATE ha_departure_scans SET body=?,version=? WHERE id=? AND version=?`, body, s.Version, q.ID, q.Scan.Version)
+ if err != nil {
+ return out, err
+ }
+ n, err = res.RowsAffected()
+ if err != nil {
+ return out, err
+ }
+ }
+ if n != 1 {
+ return out, ErrHAChanged
+ }
+ if _, err = tx.ExecContext(ctx, `UPDATE ha_departures SET phase=? WHERE id=?`, q.Code, q.ID); err != nil {
+ return out, err
+ }
+ return out, tx.Commit()
+}
diff --git a/internal/release/conditional_delete.go b/internal/release/conditional_delete.go
index 290104747..1f42a7142 100644
--- a/internal/release/conditional_delete.go
+++ b/internal/release/conditional_delete.go
@@ -118,3 +118,58 @@ var (
_ ConditionalDeleter = (*S3Store)(nil)
_ ConditionalDeleter = prefixStore{}
)
+
+// IndexedDeleter acknowledges each effect separately so a journal can resume
+// after deletion without repeating authority work or hiding an index failure.
+type IndexedDeleter interface {
+ DeleteRevision(context.Context, string, string) error
+ IndexDeletion(context.Context, string) error
+}
+
+func DeleteIfMatchIndexed(ctx context.Context, s Store, key, etag string) error {
+ if !exactDeleteETag(etag) {
+ return ErrInvalidETag
+ }
+ d, ok := s.(IndexedDeleter)
+ if !ok {
+ return ErrConditionalDeleteUnsupported
+ }
+ if err := d.DeleteRevision(ctx, key, etag); err != nil {
+ return err
+ }
+ return d.IndexDeletion(ctx, key)
+}
+func (d *DirStore) DeleteRevision(ctx context.Context, key, etag string) error {
+ return d.deleteIfMatchRaw(ctx, key, etag)
+}
+func (s *S3Store) DeleteRevision(ctx context.Context, key, etag string) error {
+ return s.deleteIfMatchRaw(ctx, key, etag)
+}
+func (d *DirStore) IndexDeletion(ctx context.Context, key string) error {
+ scope, ok := ChangeScope(key)
+ if !ok {
+ return ErrConditionalDeleteUnsupported
+ }
+ return bumpChangeIndex(ctx, d.Get, d.putRaw, scope)
+}
+func (s *S3Store) IndexDeletion(ctx context.Context, key string) error {
+ scope, ok := ChangeScope(key)
+ if !ok {
+ return ErrConditionalDeleteUnsupported
+ }
+ return bumpChangeIndex(ctx, s.Get, s.putRaw, scope)
+}
+func (p prefixStore) DeleteRevision(ctx context.Context, key, etag string) error {
+ d, ok := p.Store.(IndexedDeleter)
+ if !ok {
+ return ErrConditionalDeleteUnsupported
+ }
+ return d.DeleteRevision(ctx, p.full(key), etag)
+}
+func (p prefixStore) IndexDeletion(ctx context.Context, key string) error {
+ d, ok := p.Store.(IndexedDeleter)
+ if !ok {
+ return ErrConditionalDeleteUnsupported
+ }
+ return d.IndexDeletion(ctx, p.full(key))
+}
diff --git a/internal/release/conditional_delete_test.go b/internal/release/conditional_delete_test.go
index b6405dfb2..7fa4618af 100644
--- a/internal/release/conditional_delete_test.go
+++ b/internal/release/conditional_delete_test.go
@@ -185,3 +185,42 @@ func TestConditionalDeleteS3ActualWire(t *testing.T) {
})
}
}
+
+func TestDepartureIndexedDeleteAcknowledgesBoth(t *testing.T) {
+ ctx := t.Context()
+ s := NewDirStore(t.TempDir())
+ key := "control/edges/dead.json"
+ tag, err := s.Put(ctx, key, []byte("old"), "")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err = DeleteIfMatchIndexed(ctx, s, key, tag); err != nil {
+ t.Fatal(err)
+ }
+ idx, _, err := ReadChangeIndex(ctx, s)
+ if err != nil || idx.Entries["control/edges"] != 1 {
+ t.Fatal(idx, err)
+ }
+ if err = DeleteIfMatchIndexed(ctx, &deleteTrap{}, key, tag); !errors.Is(err, ErrConditionalDeleteUnsupported) {
+ t.Fatal(err)
+ }
+}
+func TestDepartureIndexedDeleteReturnsIndexFailure(t *testing.T) {
+ ctx := t.Context()
+ s := NewDirStore(t.TempDir())
+ key := "control/edges/dead.json"
+ tag, err := s.Put(ctx, key, []byte("old"), "")
+ if err != nil {
+ t.Fatal(err)
+ }
+ _, err = s.Put(ctx, ChangeIndexKey, []byte(`{"schema":99}`), "")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err = DeleteIfMatchIndexed(ctx, s, key, tag); !errors.Is(err, ErrChangeIndexSchema) {
+ t.Fatal(err)
+ }
+ if _, _, err = s.Get(ctx, key); !errors.Is(err, os.ErrNotExist) {
+ t.Fatal(err)
+ }
+}