carlos / platform Public

ha: publish the ingress projection at agent start

Build routing metadata promptly from the existing record source, with bounded startup retries. Reuse the judged instance scan without running reconciliation, and cover forwarding before the first instances pass.
Co-Authored-By: GPT-6 Astra <noreply@openai.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 7a6447a01085e42a6d5ee4741a4dfc87d5608a1f parent b9ab90c
5 files changed, +613 −300
  • internal/host/agent.go +7 −3
  • internal/host/haingress.go +70 −0
  • internal/host/haingress_startup_test.go +223 −0
  • internal/provision/haingress.go +15 −0
  • internal/provision/reconcile.go +298 −297

Intent

Human

<task-notification> <task-id>bs5nfe6rd</task-id> <tool-use-id>toolu_01YV59tYvTyjUACQXr3mLXAY</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/5555438b-7fa2-408d-b2c4-9fa87ea89332/tasks/bs5nfe6rd.output</output-file> <status>completed</status> <summary>Background command "Run F-B witness live, run 2" completed (exit code 0)</summary> </task-notification>

diff --git a/internal/host/agent.go b/internal/host/agent.go
index 95c6c392c..2974c3e86 100644
--- a/internal/host/agent.go
+++ b/internal/host/agent.go
@@ -1004,9 +1004,13 @@ func runAgent(args []string, buildClaims ClaimFactory) {
// The change index (S3 change-index design §4): armed before the
// loops that read through it, with its backstop running from here.
// Unset CARLOS_CHANGE_INDEX, or a fleet box: nothing.
- if v := armChangeIndex(agentCtx, os.Getenv, openDeployStore); v != nil {
- go recordViewBackstopLoop(agentCtx, v)
- }
+ v := armChangeIndex(agentCtx, os.Getenv, openDeployStore)
+ go func() {
+ runHAIngressStartup(agentCtx, openDeployStore, boxJudge)
+ if v != nil && agentCtx.Err() == nil {
+ recordViewBackstopLoop(agentCtx, v)
+ }
+ }()
// The app policy cache (#328, #329), built once the index is armed
// so it follows the watch just armed (nil on a fleet or disarmed
// box), before any loop that reconciles.
diff --git a/internal/host/haingress.go b/internal/host/haingress.go
index 0b0e83d97..0b1bf406d 100644
--- a/internal/host/haingress.go
+++ b/internal/host/haingress.go
@@ -2,9 +2,12 @@ package host
import (
"context"
+ "errors"
+ "log"
"os"
"sync"
"sync/atomic"
+ "time"
"github.com/carlosframework/platform/internal/provision"
"github.com/carlosframework/platform/internal/registry"
@@ -120,3 +123,70 @@ func wireHAIngressScan(ctx context.Context, s release.Store, cfg *provision.Reco
boxHAIngress.publish(routes, err)
}
}
+
+// runHAIngressStartup finishes after success or three retries. The existing
+// instances and record-view loops own every later refresh.
+func runHAIngressStartup(ctx context.Context, open func(context.Context) (release.Store, error), judge *provision.LifetimeJudge) {
+ for _, delay := range []time.Duration{0, 2 * time.Second, 5 * time.Second, 10 * time.Second} {
+ if delay != 0 {
+ timer := time.NewTimer(delay)
+ select {
+ case <-ctx.Done():
+ timer.Stop()
+ return
+ case <-timer.C:
+ }
+ }
+ if ctx.Err() != nil {
+ return
+ }
+ attempt, cancel := context.WithTimeout(ctx, 5*time.Second)
+ err := refreshHAIngressAtStart(attempt, open, judge)
+ cancel()
+ if err == nil {
+ return
+ }
+ log.Printf("agent: startup HA ingress: %v", err)
+ }
+}
+
+func refreshHAIngressAtStart(ctx context.Context, open func(context.Context) (release.Store, error), judge *provision.LifetimeJudge) error {
+ // Share the instance pass's publication order without waiting beyond the
+ // startup attempt's deadline for a pass already in flight.
+ for !reconcileMu.TryLock() {
+ select {
+ case <-ctx.Done():
+ return ctx.Err()
+ case <-time.After(10 * time.Millisecond):
+ }
+ }
+ defer reconcileMu.Unlock()
+ if err := ctx.Err(); err != nil {
+ return err
+ }
+ if v := armedRecordView.Load(); v != nil {
+ err := v.Refresh(ctx)
+ sn := v.Snapshot()
+ if sn == nil || !sn.Complete {
+ err = errors.Join(err, errors.New("HA ingress: incomplete record view"))
+ }
+ publishHAIngressSnapshot(sn, err)
+ return err
+ }
+ s, err := open(ctx)
+ if err != nil {
+ boxHAIngress.publish(nil, err)
+ return err
+ }
+ cfg := provisionTickConfig(os.Getenv)
+ cfg.Judge = judge
+ records, err := provision.ScanHAIngress(ctx, s, cfg)
+ if err != nil {
+ boxHAIngress.publish(nil, err)
+ return err
+ }
+ routes, err := provision.HAIngressRoutesFromRecords(ctx, s, records, cfg.Region)
+ err = errors.Join(err, ctx.Err())
+ boxHAIngress.publish(routes, err)
+ return err
+}
diff --git a/internal/host/haingress_startup_test.go b/internal/host/haingress_startup_test.go
new file mode 100644
index 000000000..71de11028
--- /dev/null
+++ b/internal/host/haingress_startup_test.go
@@ -0,0 +1,223 @@
+package host
+
+import (
+ "context"
+ "crypto/ed25519"
+ "crypto/x509"
+ "fmt"
+ "io"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "strings"
+ "sync/atomic"
+ "testing"
+ "time"
+ _ "unsafe"
+
+ "github.com/carlosframework/platform/internal/activator"
+ "github.com/carlosframework/platform/internal/edge"
+ "github.com/carlosframework/platform/internal/hafresh"
+ "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"
+)
+
+//go:linkname startupForwardDial github.com/carlosframework/platform/internal/edge.forwardDial
+var startupForwardDial func(context.Context, string, string) (net.Conn, error)
+
+//go:linkname startupBackhaulRoots github.com/carlosframework/platform/internal/edge.backhaulRootCAs
+var startupBackhaulRoots *x509.CertPool
+
+func TestHAIngressStartupWiring(t *testing.T) {
+ src, err := os.ReadFile("agent.go")
+ if err != nil {
+ t.Fatal(err)
+ }
+ body := string(src)
+ start := strings.Index(body, "runHAIngressStartup(agentCtx, openDeployStore, boxJudge)")
+ if strings.Count(body, "runHAIngressStartup(agentCtx, openDeployStore, boxJudge)") != 1 || start < 0 || start < strings.Index(body, "armChangeIndex(agentCtx,") || start > strings.Index(body, "go instancesLoop(") {
+ t.Fatal("agent does not build the ingress projection at startup after arming the index and before starting instancesLoop")
+ }
+}
+
+func TestHAIngressStartupForwards(t *testing.T) {
+ for _, indexed := range []bool{false, true} {
+ for _, fail := range []bool{false, true} {
+ t.Run(fmt.Sprintf("indexed=%v/failure=%v", indexed, fail), func(t *testing.T) {
+ disarmView(t)
+ oldRoutes, oldNames, oldEpoch := boxHAIngress.routes.Load(), boxHAIngress.regional.Load(), boxHAIngress.epoch
+ boxHAIngress.routes.Store(nil)
+ boxHAIngress.regional.Store(nil)
+ boxHAIngress.epoch = 0
+ t.Cleanup(func() {
+ boxHAIngress.routes.Store(oldRoutes)
+ boxHAIngress.regional.Store(oldNames)
+ boxHAIngress.epoch = oldEpoch
+ })
+ w := newCIWorld(t)
+ t.Setenv("CARLOS_REGION", "")
+ t.Setenv("CARLOS_REGION_HA", "1")
+ t.Setenv("CARLOS_POOLS", "other")
+ fx := locktest.NewLockFixture(t)
+ rec := provision.Record{Schema: 1, Host: "example.com", Slug: "ha", Account: w.acct, App: "shop", Channel: "stable", Pool: "ha", HA: true, CreatedAt: time.Now()}
+ if err := provision.CreateRecord(t.Context(), w.live, rec); err != nil {
+ t.Fatal(err)
+ }
+ if indexed {
+ armView(t, w.live)
+ }
+ reg := edgesTestRegistry(t)
+ peerReg := edgesTestRegistry(t)
+ if err := peerReg.Upsert(registry.Route{Host: rec.Host, Account: rec.Account, App: rec.App, Pool: rec.Pool, HA: true, Hibernate: true, Socket: "/unused"}); err != nil {
+ t.Fatal(err)
+ }
+ for _, peer := range []struct {
+ name, ip, pool string
+ reg *registry.Registry
+ }{
+ {"ingress", "127.0.0.1", "other", reg}, {"holder", "127.0.0.2", "ha", peerReg},
+ } {
+ t.Setenv("CARLOS_POOLS", peer.pool)
+ var last []byte
+ yes, no := true, false
+ ident := edgesFile{ServedPools: (provision.ReconcileConfig{Pools: []string{peer.pool}}).ServedPools(), Box: peer.name, Region: "eu-west-1", DataBucket: fx.Bucket, SecretsKeyFP: "shared", HibernationConfigured: true, Capabilities: []string{capRegionHA1}, BoxRole: "serve", Admitted: &yes, Drained: &no, Headroom: &edgeHeadroom{MemFreeMiB: 300, MemTotalMiB: 1000, DiskFreeMiB: 300, DiskTotalMiB: 1000}}
+ if err := edgesFileWrite(t.Context(), w.live, peer.reg, ident, peer.ip, &last, true); err != nil {
+ t.Fatal(err)
+ }
+ }
+ t.Setenv("CARLOS_POOLS", "other")
+ stale := registry.Route{Host: rec.Host, Account: rec.Account, App: rec.App, Pool: rec.Pool, Hibernate: true, Socket: "/unused"}
+ if err := reg.Upsert(stale); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := w.live.Put(t.Context(), "control/edge-mesh-key", []byte(strings.Repeat("a", 64)), ""); err != nil {
+ t.Fatal(err)
+ }
+ var deliveries atomic.Int32
+ peer := httptest.NewTLSServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
+ if r.Header.Get("X-Carlos-Hop-Auth") == "" || r.Host != rec.Host {
+ t.Errorf("unsigned or wrong host: %s %v", r.Host, r.Header)
+ }
+ deliveries.Add(1)
+ io.WriteString(rw, "forwarded")
+ }))
+ defer peer.Close()
+ oldDial, oldRoots := startupForwardDial, startupBackhaulRoots
+ startupBackhaulRoots = x509.NewCertPool()
+ startupBackhaulRoots.AddCert(peer.Certificate())
+ startupForwardDial = func(ctx context.Context, network, addr string) (net.Conn, error) {
+ if !strings.HasPrefix(addr, "127.0.0.2:") {
+ return nil, fmt.Errorf("unexpected target %s", addr)
+ }
+ return (&net.Dialer{}).DialContext(ctx, network, peer.Listener.Addr().String())
+ }
+ defer func() { startupForwardDial, startupBackhaulRoots = oldDial, oldRoots }()
+ cfg := activator.Config{Bucket: fx.Bucket, Idle: time.Hour, Self: func() hafresh.Self { return hafresh.Self{Ref: "ingress", IID: "i-ingress"} }}
+ svc := activator.New(cfg, &activator.ExecBackend{Cfg: cfg, ServedPools: (provision.ReconcileConfig{Pools: []string{"other"}}).ServedPools}, nil)
+ defer svc.Shutdown(context.Background())
+ e, err := edge.New(reg, svc)
+ if err != nil {
+ t.Fatal(err)
+ }
+ edge.WithBoxLabel("ingress")(e)
+ e.EnableStatic(w.live, ed25519.NewKeyFromSeed(make([]byte, 32)).Public().(ed25519.PublicKey), t.TempDir())
+ e.SetHAIngressLookup(boxHAIngress.lookup)
+ if e.ArmHomeMap() == nil {
+ t.Fatal("peer view not armed")
+ }
+ snapshot := e.DutySnapshot(registry.Route{Host: rec.Host, Account: rec.Account, App: rec.App, Pool: rec.Pool, HA: true})
+ if !snapshot.Usable || !snapshot.LocalDenied || len(snapshot.Serving) != 1 || snapshot.Serving[0].BoxID != "holder" {
+ t.Fatalf("startup peer view: %+v", snapshot)
+ }
+ request := func() *httptest.ResponseRecorder {
+ r := httptest.NewRequest(http.MethodPost, "https://"+rec.Host+"/", strings.NewReader("once"))
+ rw := httptest.NewRecorder()
+ e.ServeHTTP(rw, r)
+ return rw
+ }
+ if fail {
+ w.live.setFailList("accounts/")
+ }
+ ctx, cancel := context.WithCancel(t.Context())
+ done := make(chan struct{})
+ go func() {
+ defer close(done)
+ runHAIngressStartup(ctx, func(context.Context) (release.Store, error) { return w.live, nil }, newBoxJudge(claimsOffEnv))
+ }()
+ defer func() { cancel(); <-done }()
+ start := time.Now()
+ if fail {
+ deadline := time.Now().Add(time.Second)
+ for boxHAIngress.routes.Load() == nil && time.Now().Before(deadline) {
+ time.Sleep(time.Millisecond)
+ }
+ if boxHAIngress.routes.Load() == nil {
+ t.Fatal("initial failure was not published")
+ }
+ if rw := request(); rw.Code != 503 || rw.Header().Get("X-Carlos-Holder") != "none" || deliveries.Load() != 0 {
+ t.Fatalf("failed projection served: %d", rw.Code)
+ }
+ if rt, _ := boxHAIngress.lookup(rec.Host); rt.HA {
+ t.Fatal("failed projection usable")
+ }
+ w.live.setFailList("")
+ }
+ select {
+ case <-done:
+ case <-time.After(9 * time.Second):
+ t.Fatal("startup did not publish within 10 seconds without instancesLoop")
+ }
+ if rt, ok := boxHAIngress.lookup(rec.Host); !ok || !rt.HA {
+ t.Fatalf("startup projection missing: %+v %v", rt, ok)
+ }
+ rw := request()
+ if rw.Code != 200 || rw.Body.String() != "forwarded" || deliveries.Load() != 1 {
+ t.Fatalf("startup forward: %d %q deliveries=%d", rw.Code, rw.Body.String(), deliveries.Load())
+ }
+ if time.Since(start) >= 10*time.Second {
+ t.Fatal("forward took 10 seconds")
+ }
+ if rows, err := reg.List(); err != nil || len(rows) != 1 || rows[0].Host != stale.Host || rows[0].HA || rows[0].Provisioned {
+ t.Fatalf("ingress acquired local routes: %+v %v", rows, err)
+ }
+ for _, req := range fx.Requests() {
+ if strings.HasPrefix(req, "PUT ") {
+ t.Fatalf("ingress acquired a lease: %s", req)
+ }
+ }
+ t.Logf("forwarded in %s without instancesLoop", time.Since(start).Round(time.Millisecond))
+ })
+ }
+ }
+}
+
+func TestHAIngressStartupCancellation(t *testing.T) {
+ ctx, cancel := context.WithCancel(t.Context())
+ var calls int
+ runHAIngressStartup(ctx, func(context.Context) (release.Store, error) {
+ calls++
+ cancel()
+ return nil, fmt.Errorf("store unavailable")
+ }, nil)
+ if calls != 1 {
+ t.Fatalf("cancelled startup opened store %d times", calls)
+ }
+}
+
+func TestHAIngressStartupLockDeadline(t *testing.T) {
+ reconcileMu.Lock()
+ defer reconcileMu.Unlock()
+ ctx, cancel := context.WithTimeout(t.Context(), 30*time.Millisecond)
+ defer cancel()
+ start := time.Now()
+ err := refreshHAIngressAtStart(ctx, func(context.Context) (release.Store, error) {
+ t.Fatal("opened store after timing out waiting for reconcile")
+ return nil, nil
+ }, nil)
+ if err != context.DeadlineExceeded || time.Since(start) > time.Second {
+ t.Fatalf("startup lock deadline: %v, %s", err, time.Since(start))
+ }
+}
diff --git a/internal/provision/haingress.go b/internal/provision/haingress.go
index 065e38f32..c4c8e1fb3 100644
--- a/internal/provision/haingress.go
+++ b/internal/provision/haingress.go
@@ -65,3 +65,18 @@ func HAIngressRoutesFromRecords(ctx context.Context, s release.Store, records []
}
return out, nil
}
+
+// ScanHAIngress uses the instance pass's judged scan without changing routes,
+// withdrawing pools, or running any reconciliation hooks.
+func ScanHAIngress(ctx context.Context, s release.Store, cfg ReconcileConfig) ([]Record, error) {
+ cfg.HAIngress = func([]Record, error) {}
+ sc, err := scanInstanceRecords(WithLifetimes(ctx, cfg.Judge), s, cfg)
+ return sc.ingress, sc.ingressError(err)
+}
+
+func (sc recordScan) ingressError(err error) error {
+ if sc.readFailed || sc.partial || len(sc.unread) > 0 || len(sc.protect) > 0 {
+ return errors.Join(err, errors.New("HA ingress: incomplete instance scan"))
+ }
+ return err
+}
diff --git a/internal/provision/reconcile.go b/internal/provision/reconcile.go
index 379997814..2c30a0e6f 100644
--- a/internal/provision/reconcile.go
+++ b/internal/provision/reconcile.go
@@ -1113,6 +1113,302 @@ func convergeOwned(reg *registry.Registry, existing registry.Route, rec Record,
return policyMoved, errors.Join(errs...)
}
+// scan is the record-collection phase over st: the in-scope records by
+// host, the hosts whose record is there but cannot be used (protect),
+// and whether anything failed to read (readFailed, which disables
+// removal for the whole pass). The pass scans s; a pass over a record
+// view snapshot that has a removal to decide scans the bucket too
+// (freshStore), so both judge every record by exactly these rules (S3
+// change-index design §4.4).
+//
+// For the report (ReconcileReport) it also names what it could not
+// vouch for: unread holds every "<acct>/<app>" with a record that would
+// not read, could not be used, or collided with another's host;
+// failedAccts the accounts whose manifest would not read; partial a
+// listing that came back incomplete, which could hide any app's record.
+type recordScan struct {
+ ingress []Record
+
+ observed map[string]Record
+ departureRecords []DepartureHost
+ departureInvalid bool
+ recs map[string]Record
+ protect map[string]bool
+ readFailed bool
+ unread map[string]bool
+ failedAccts map[string]bool
+ partial bool
+ // known is the scan's account set and stale the hosts whose listed
+ // record the judge found its slot no longer vouches for; the
+ // removal phase reads both for the scan it judges.
+ known map[string]bool
+ stale map[string]bool
+ // fleet, hosts and unreadHosts are the forward phase's, kept only on
+ // the hub (FleetOwners set): fleet the fleet-placed records the scan
+ // skips only at the fleet boundary, by host; hosts the number of
+ // usable records naming each host, in scope or not; unreadHosts the
+ // hosts (from the key) of listed records whose GET failed. A host
+ // two records name, or one an unreadable record names, is disputed
+ // (forwardView).
+ fleet map[string]Record
+ hosts map[string]int
+ unreadHosts map[string]bool
+}
+
+func scanInstanceRecords(ctx context.Context, st release.Store, cfg ReconcileConfig) (recordScan, error) {
+ var ingress []Record
+ var departureRecords []DepartureHost
+ departureInvalid := false
+ known, failedAccts, err := knownAccountsNaming(ctx, st)
+ if err != nil {
+ return recordScan{}, err
+ }
+ readFailed := len(failedAccts) > 0
+ unread := map[string]bool{}
+
+ // --- collect in-scope records --------------------------------------------
+ keys, partial, err := listAppSubtree(ctx, st, known, "instances/")
+ if err != nil {
+ return recordScan{}, fmt.Errorf("provision: list apps: %w", err)
+ }
+ if partial {
+ readFailed = true // unseen records must not read as retired
+ }
+ recs := map[string]Record{} // host -> record, in-scope only
+ // protect holds hosts whose record KEY parsed (ParseRecordKey succeeded)
+ // but whose body could not be trusted — unparseable JSON, or a body that
+ // disagrees with its own path. Such a host must NEVER be treated as "the
+ // bucket retired it": a non-additive Record encoding change reaching an
+ // older binary would make EVERY existing record fail exactly this way,
+ // and without this guard one tick would delete every provisioned route
+ // in scope. This is narrower than readFailed (which vetoes removal for
+ // the WHOLE pass): only the specific host with the unusable body is held
+ // back — every other record still converges/removes normally the same
+ // pass.
+ protect := map[string]bool{}
+ observed := map[string]Record{}
+ var recordKeys []string
+ for _, key := range keys {
+ if _, _, _, ok := ParseRecordKey(key, known); ok {
+ recordKeys = append(recordKeys, key)
+ }
+ }
+ // stale holds hosts whose listed record the judge found its slot no
+ // longer vouches for (a fieldless record beside a slot, a lifetime
+ // behind its slot, a tombstone). Such a record is not in recs and not
+ // protected: to this pass it is gone. The removal phase observes a
+ // row's own key afresh before it acts on that.
+ stale := map[string]bool{}
+ var fleet map[string]Record
+ var hosts map[string]int
+ var unreadHosts map[string]bool
+ if cfg.FleetOwners != nil {
+ fleet, hosts, unreadHosts = map[string]Record{}, map[string]int{}, map[string]bool{}
+ }
+ for _, part := range chunks(recordKeys) {
+ bodies := getEach(ctx, st, part)
+ // One sequence per key: the prefetched read, then the judge's
+ // observation of it (the slot read after the record, in bounded
+ // rounds), then the checks below on the observation's record. A nil
+ // judge decodes and path-checks the prefetched body only. The slot
+ // reads run as the prefetch does, a handful at a time.
+ observations := make(map[string]Observation, len(part))
+ var obsMu sync.Mutex
+ observe := func(key string) {
+ acct, app, host, _ := ParseRecordKey(key, known)
+ b := bodies[key]
+ obs := cfg.Judge.ObserveWith(ctx, st, acct, app, host, b.body, b.etag, b.err)
+ obsMu.Lock()
+ observations[key] = obs
+ obsMu.Unlock()
+ }
+ if cfg.Judge == nil {
+ for _, key := range part {
+ observe(key)
+ }
+ } else {
+ forEach(part, observe)
+ }
+ for _, key := range part {
+ acct, app, host, _ := ParseRecordKey(key, known)
+ obs := observations[key]
+ if !obs.Present {
+ err := bodies[key].err
+ if err == nil {
+ err = obs.Err
+ }
+ if err == nil {
+ err = os.ErrNotExist
+ }
+ log.Printf("provision: skipping record %s: read failed: %v", key, err)
+ // The record's absence from recs below must not read as "the
+ // bucket retired it" — a transient Get failure disables removal
+ // for the whole pass, same as an unreadable account manifest.
+ // A listed key whose body is gone by the time it is read is
+ // the same failure, judge or no judge: absence is not
+ // staleness.
+ readFailed = true
+ unread[acct+"/"+app] = true
+ // The record may name a host another account's readable
+ // record names too: the forward phase gives that host
+ // nothing this pass.
+ if unreadHosts != nil {
+ unreadHosts[host] = true
+ }
+ continue
+ }
+ if obs.Verdict == LifetimeCorrupt {
+ log.Printf("provision: skipping record %s: malformed: %v", key, obs.Err)
+ protect[host] = true
+ unread[acct+"/"+app] = true
+ continue
+ }
+ if obs.Verdict == LifetimeUnreadable {
+ // The record read, but its lifetime could not be judged this
+ // pass (the slot would not read or is malformed, the rounds
+ // ran out, a counter is out of range): protected like a
+ // corrupt body, never taken for retired.
+ log.Printf("provision: skipping record %s: its lifetime could not be judged: %v", key, obs.Err)
+ protect[host] = true
+ unread[acct+"/"+app] = true
+ continue
+ }
+ if obs.Verdict == LifetimeStale {
+ if cfg.HAIngress != nil && obs.Rec != nil {
+ retired := *obs.Rec
+ retired.Retired = true
+ ingress = append(ingress, retired)
+ }
+ log.Printf("provision: skipping record %s: its host incarnation slot no longer vouches for it", key)
+ stale[host] = true
+ // Over a record view snapshot the body may be older than
+ // the bucket's slot (a record migrated after the snapshot
+ // was taken), so the bucket's own observation decides the
+ // report: a body still stale there, or gone, is a
+ // confirmed retirement and leaves the app vouched for; a
+ // valid, corrupt or unjudgeable one is a record this pass
+ // did not apply, so the app is not.
+ // The confirmation is cached per snapshot under an
+ // unchanged retired slot (reportRetirementConfirmed).
+ if onSnapshot(st) && !reportRetirementConfirmed(ctx, cfg.Judge, st, obs, acct, app, host) {
+ unread[acct+"/"+app] = true
+ }
+ continue
+ }
+ rec := *obs.Rec
+ if cfg.HAIngress != nil {
+ ingress = append(ingress, rec)
+ }
+ observed[rec.Host] = rec
+ // The record IS the authorization, and this pass turns its host into
+ // a socket path and a database path (DefaultSocket/DefaultDBPath)
+ // and a registry primary key. The console's create door enforces
+ // this same shape — but a door is not a guarantee about what is
+ // already in the bucket: anything with bucket write access, and any
+ // record written by a different (older, or future) writer, arrives
+ // here unexamined. Both doors hold the invariant, neither trusts
+ // the other. Protected like a corrupted body, and for the same
+ // reason: a record that cannot be used is not a record that was
+ // retired.
+ if !ValidHostShape(rec.Host) {
+ log.Printf("provision: skipping record %s: host %q is not a hostname", key, rec.Host)
+ protect[host] = true
+ unread[acct+"/"+app] = true
+ continue
+ }
+ // ValidateShape is the console create door's policy check — but a
+ // door is not a guarantee about what is already in the bucket (the
+ // same reasoning as the host-shape check just above). This pass
+ // materializes whatever it finds, so a record whose Kind/Addr/Unit/
+ // Environment combination is malformed must be caught here too, or
+ // a bad value becomes a live route. Protected like a corrupted
+ // body: the record is there, it just cannot be used.
+ if err := ValidateShape(rec); err != nil {
+ log.Printf("provision: skipping record %s: invalid shape: %v", key, err)
+ protect[host] = true
+ unread[acct+"/"+app] = true
+ continue
+ }
+ if rec.ReplicaAssignment != nil && !replicaAssignmentAdmitted(rec) {
+ protect[host] = true
+ unread[acct+"/"+app] = true
+ continue
+ }
+ // ValidateShape deliberately does not inspect Channel (it validates
+ // shape fields, and Channel is not one), but a channel-less record
+ // must not become — or converge — a route pinned to no channel:
+ // that is issue #130's failure mode arriving through a different
+ // door than the one Task 3 closed. Protected like a corrupted body:
+ // the record is there, it just cannot be used.
+ if rec.Channel == "" {
+ log.Printf("provision: skipping record %s: empty channel", key)
+ protect[host] = true
+ unread[acct+"/"+app] = true
+ continue
+ }
+ // Scope. For a home-boxed record this is the region/pool test it
+ // always was; for a static or public-addr one the region half widens
+ // to every platform box in the deployment (everywhereClass, above).
+ // A replica record narrows it: it belongs ONLY to the box whose
+ // placement is the record's own Region — the placement the create
+ // door validated as armed — so a replica record minted on the wrong
+ // region would mint a route with no mirror behind it and no lease
+ // speaking to it, a process holding live order data nobody
+ // authorized into that region (the residence rule, #162). Every
+ // other box skips it exactly like any other out-of-scope record;
+ // the replica's own box sees Region == cfg.Region through the
+ // ordinary test above.
+ if hosts != nil {
+ hosts[rec.Host]++
+ }
+ if cfg.Departures != nil {
+ h, ok := departureInstance(rec, bodies[key].body)
+ departureRecords = append(departureRecords, h)
+ departureInvalid = departureInvalid || !ok
+ }
+ if !cfg.inScope(rec.Region, rec.Pool, everywhereClass(rec)) {
+ // On the hub, a fleet-placed record skipped only at the
+ // fleet boundary is the forward phase's (spec §4.3 step
+ // 1): judged and validated above exactly as an in-scope
+ // record, kept here for its decision. Pool records are
+ // kept too, so the phase refuses them out loud.
+ if fleet != nil {
+ if _, onFleet := registry.FleetPlacement(rec.Region); onFleet && rec.Region != cfg.Region {
+ if _, dup := fleet[rec.Host]; !dup {
+ fleet[rec.Host] = rec
+ }
+ }
+ }
+ continue // another agent's jurisdiction, not this pass's business
+ }
+ // On a fleet box, a record labelled for another box is that
+ // box's alone (managed fleets 1b, rule 2): skipped exactly as an
+ // out-of-scope record is, so it is never minted, staged or
+ // started here, and the removal phase removes this box's row of
+ // it as record gone. Not kept for the forward phase: the
+ // record's region is this box's own.
+ if !cfg.ownsRecord(rec) {
+ continue
+ }
+ // Two accounts writing the same host is a collision this pass
+ // cannot arbitrate silently: whichever record this listing reaches
+ // FIRST wins the host, and the loser is skipped loudly rather than
+ // overwriting the winner in the map with no trace of the conflict.
+ if prev, dup := recs[rec.Host]; dup {
+ log.Printf("provision: duplicate host %s: keeping %s, skipping %s", rec.Host,
+ RecordKey(prev.Account, prev.App, prev.Host), RecordKey(rec.Account, rec.App, rec.Host))
+ // The host's owner is in dispute: neither app vouches for it.
+ unread[prev.Account+"/"+prev.App] = true
+ unread[rec.Account+"/"+rec.App] = true
+ continue
+ }
+ recs[rec.Host] = rec
+ }
+ }
+ return recordScan{ingress: ingress, observed: observed, departureRecords: departureRecords, departureInvalid: departureInvalid, recs: recs, protect: protect, readFailed: readFailed, known: known, stale: stale,
+ unread: unread, failedAccts: failedAccts, partial: partial, fleet: fleet, hosts: hosts, unreadHosts: unreadHosts}, nil
+}
+
// Reconcile materializes bucket instance records into registry routes for
// THIS agent's region and pools: mint on appearance, converge seed, remove
// on record deletion — removal only for routes this pass (or an earlier one
@@ -1136,307 +1432,12 @@ func Reconcile(ctx context.Context, s release.Store, reg *registry.Registry, cfg
cfg.Report.Complete = map[string]bool{}
}
- // scan is the record-collection phase over st: the in-scope records by
- // host, the hosts whose record is there but cannot be used (protect),
- // and whether anything failed to read (readFailed, which disables
- // removal for the whole pass). The pass scans s; a pass over a record
- // view snapshot that has a removal to decide scans the bucket too
- // (freshStore), so both judge every record by exactly these rules (S3
- // change-index design §4.4).
- //
- // For the report (ReconcileReport) it also names what it could not
- // vouch for: unread holds every "<acct>/<app>" with a record that would
- // not read, could not be used, or collided with another's host;
- // failedAccts the accounts whose manifest would not read; partial a
- // listing that came back incomplete, which could hide any app's record.
- type recordScan struct {
- ingress []Record
-
- observed map[string]Record
- departureRecords []DepartureHost
- departureInvalid bool
- recs map[string]Record
- protect map[string]bool
- readFailed bool
- unread map[string]bool
- failedAccts map[string]bool
- partial bool
- // known is the scan's account set and stale the hosts whose listed
- // record the judge found its slot no longer vouches for; the
- // removal phase reads both for the scan it judges.
- known map[string]bool
- stale map[string]bool
- // fleet, hosts and unreadHosts are the forward phase's, kept only on
- // the hub (FleetOwners set): fleet the fleet-placed records the scan
- // skips only at the fleet boundary, by host; hosts the number of
- // usable records naming each host, in scope or not; unreadHosts the
- // hosts (from the key) of listed records whose GET failed. A host
- // two records name, or one an unreadable record names, is disputed
- // (forwardView).
- fleet map[string]Record
- hosts map[string]int
- unreadHosts map[string]bool
- }
scan := func(st release.Store) (recordScan, error) {
- var ingress []Record
- var departureRecords []DepartureHost
- departureInvalid := false
- known, failedAccts, err := knownAccountsNaming(ctx, st)
- if err != nil {
- return recordScan{}, err
- }
- readFailed := len(failedAccts) > 0
- unread := map[string]bool{}
-
- // --- collect in-scope records --------------------------------------------
- keys, partial, err := listAppSubtree(ctx, st, known, "instances/")
- if err != nil {
- return recordScan{}, fmt.Errorf("provision: list apps: %w", err)
- }
- if partial {
- readFailed = true // unseen records must not read as retired
- }
- recs := map[string]Record{} // host -> record, in-scope only
- // protect holds hosts whose record KEY parsed (ParseRecordKey succeeded)
- // but whose body could not be trusted — unparseable JSON, or a body that
- // disagrees with its own path. Such a host must NEVER be treated as "the
- // bucket retired it": a non-additive Record encoding change reaching an
- // older binary would make EVERY existing record fail exactly this way,
- // and without this guard one tick would delete every provisioned route
- // in scope. This is narrower than readFailed (which vetoes removal for
- // the WHOLE pass): only the specific host with the unusable body is held
- // back — every other record still converges/removes normally the same
- // pass.
- protect := map[string]bool{}
- observed := map[string]Record{}
- var recordKeys []string
- for _, key := range keys {
- if _, _, _, ok := ParseRecordKey(key, known); ok {
- recordKeys = append(recordKeys, key)
- }
- }
- // stale holds hosts whose listed record the judge found its slot no
- // longer vouches for (a fieldless record beside a slot, a lifetime
- // behind its slot, a tombstone). Such a record is not in recs and not
- // protected: to this pass it is gone. The removal phase observes a
- // row's own key afresh before it acts on that.
- stale := map[string]bool{}
- var fleet map[string]Record
- var hosts map[string]int
- var unreadHosts map[string]bool
- if cfg.FleetOwners != nil {
- fleet, hosts, unreadHosts = map[string]Record{}, map[string]int{}, map[string]bool{}
- }
- for _, part := range chunks(recordKeys) {
- bodies := getEach(ctx, st, part)
- // One sequence per key: the prefetched read, then the judge's
- // observation of it (the slot read after the record, in bounded
- // rounds), then the checks below on the observation's record. A nil
- // judge decodes and path-checks the prefetched body only. The slot
- // reads run as the prefetch does, a handful at a time.
- observations := make(map[string]Observation, len(part))
- var obsMu sync.Mutex
- observe := func(key string) {
- acct, app, host, _ := ParseRecordKey(key, known)
- b := bodies[key]
- obs := cfg.Judge.ObserveWith(ctx, st, acct, app, host, b.body, b.etag, b.err)
- obsMu.Lock()
- observations[key] = obs
- obsMu.Unlock()
- }
- if cfg.Judge == nil {
- for _, key := range part {
- observe(key)
- }
- } else {
- forEach(part, observe)
- }
- for _, key := range part {
- acct, app, host, _ := ParseRecordKey(key, known)
- obs := observations[key]
- if !obs.Present {
- err := bodies[key].err
- if err == nil {
- err = obs.Err
- }
- if err == nil {
- err = os.ErrNotExist
- }
- log.Printf("provision: skipping record %s: read failed: %v", key, err)
- // The record's absence from recs below must not read as "the
- // bucket retired it" — a transient Get failure disables removal
- // for the whole pass, same as an unreadable account manifest.
- // A listed key whose body is gone by the time it is read is
- // the same failure, judge or no judge: absence is not
- // staleness.
- readFailed = true
- unread[acct+"/"+app] = true
- // The record may name a host another account's readable
- // record names too: the forward phase gives that host
- // nothing this pass.
- if unreadHosts != nil {
- unreadHosts[host] = true
- }
- continue
- }
- if obs.Verdict == LifetimeCorrupt {
- log.Printf("provision: skipping record %s: malformed: %v", key, obs.Err)
- protect[host] = true
- unread[acct+"/"+app] = true
- continue
- }
- if obs.Verdict == LifetimeUnreadable {
- // The record read, but its lifetime could not be judged this
- // pass (the slot would not read or is malformed, the rounds
- // ran out, a counter is out of range): protected like a
- // corrupt body, never taken for retired.
- log.Printf("provision: skipping record %s: its lifetime could not be judged: %v", key, obs.Err)
- protect[host] = true
- unread[acct+"/"+app] = true
- continue
- }
- if obs.Verdict == LifetimeStale {
- if cfg.HAIngress != nil && obs.Rec != nil {
- retired := *obs.Rec
- retired.Retired = true
- ingress = append(ingress, retired)
- }
- log.Printf("provision: skipping record %s: its host incarnation slot no longer vouches for it", key)
- stale[host] = true
- // Over a record view snapshot the body may be older than
- // the bucket's slot (a record migrated after the snapshot
- // was taken), so the bucket's own observation decides the
- // report: a body still stale there, or gone, is a
- // confirmed retirement and leaves the app vouched for; a
- // valid, corrupt or unjudgeable one is a record this pass
- // did not apply, so the app is not.
- // The confirmation is cached per snapshot under an
- // unchanged retired slot (reportRetirementConfirmed).
- if onSnapshot(st) && !reportRetirementConfirmed(ctx, cfg.Judge, st, obs, acct, app, host) {
- unread[acct+"/"+app] = true
- }
- continue
- }
- rec := *obs.Rec
- if cfg.HAIngress != nil {
- ingress = append(ingress, rec)
- }
- observed[rec.Host] = rec
- // The record IS the authorization, and this pass turns its host into
- // a socket path and a database path (DefaultSocket/DefaultDBPath)
- // and a registry primary key. The console's create door enforces
- // this same shape — but a door is not a guarantee about what is
- // already in the bucket: anything with bucket write access, and any
- // record written by a different (older, or future) writer, arrives
- // here unexamined. Both doors hold the invariant, neither trusts
- // the other. Protected like a corrupted body, and for the same
- // reason: a record that cannot be used is not a record that was
- // retired.
- if !ValidHostShape(rec.Host) {
- log.Printf("provision: skipping record %s: host %q is not a hostname", key, rec.Host)
- protect[host] = true
- unread[acct+"/"+app] = true
- continue
- }
- // ValidateShape is the console create door's policy check — but a
- // door is not a guarantee about what is already in the bucket (the
- // same reasoning as the host-shape check just above). This pass
- // materializes whatever it finds, so a record whose Kind/Addr/Unit/
- // Environment combination is malformed must be caught here too, or
- // a bad value becomes a live route. Protected like a corrupted
- // body: the record is there, it just cannot be used.
- if err := ValidateShape(rec); err != nil {
- log.Printf("provision: skipping record %s: invalid shape: %v", key, err)
- protect[host] = true
- unread[acct+"/"+app] = true
- continue
- }
- if rec.ReplicaAssignment != nil && !replicaAssignmentAdmitted(rec) {
- protect[host] = true
- unread[acct+"/"+app] = true
- continue
- }
- // ValidateShape deliberately does not inspect Channel (it validates
- // shape fields, and Channel is not one), but a channel-less record
- // must not become — or converge — a route pinned to no channel:
- // that is issue #130's failure mode arriving through a different
- // door than the one Task 3 closed. Protected like a corrupted body:
- // the record is there, it just cannot be used.
- if rec.Channel == "" {
- log.Printf("provision: skipping record %s: empty channel", key)
- protect[host] = true
- unread[acct+"/"+app] = true
- continue
- }
- // Scope. For a home-boxed record this is the region/pool test it
- // always was; for a static or public-addr one the region half widens
- // to every platform box in the deployment (everywhereClass, above).
- // A replica record narrows it: it belongs ONLY to the box whose
- // placement is the record's own Region — the placement the create
- // door validated as armed — so a replica record minted on the wrong
- // region would mint a route with no mirror behind it and no lease
- // speaking to it, a process holding live order data nobody
- // authorized into that region (the residence rule, #162). Every
- // other box skips it exactly like any other out-of-scope record;
- // the replica's own box sees Region == cfg.Region through the
- // ordinary test above.
- if hosts != nil {
- hosts[rec.Host]++
- }
- if cfg.Departures != nil {
- h, ok := departureInstance(rec, bodies[key].body)
- departureRecords = append(departureRecords, h)
- departureInvalid = departureInvalid || !ok
- }
- if !cfg.inScope(rec.Region, rec.Pool, everywhereClass(rec)) {
- // On the hub, a fleet-placed record skipped only at the
- // fleet boundary is the forward phase's (spec §4.3 step
- // 1): judged and validated above exactly as an in-scope
- // record, kept here for its decision. Pool records are
- // kept too, so the phase refuses them out loud.
- if fleet != nil {
- if _, onFleet := registry.FleetPlacement(rec.Region); onFleet && rec.Region != cfg.Region {
- if _, dup := fleet[rec.Host]; !dup {
- fleet[rec.Host] = rec
- }
- }
- }
- continue // another agent's jurisdiction, not this pass's business
- }
- // On a fleet box, a record labelled for another box is that
- // box's alone (managed fleets 1b, rule 2): skipped exactly as an
- // out-of-scope record is, so it is never minted, staged or
- // started here, and the removal phase removes this box's row of
- // it as record gone. Not kept for the forward phase: the
- // record's region is this box's own.
- if !cfg.ownsRecord(rec) {
- continue
- }
- // Two accounts writing the same host is a collision this pass
- // cannot arbitrate silently: whichever record this listing reaches
- // FIRST wins the host, and the loser is skipped loudly rather than
- // overwriting the winner in the map with no trace of the conflict.
- if prev, dup := recs[rec.Host]; dup {
- log.Printf("provision: duplicate host %s: keeping %s, skipping %s", rec.Host,
- RecordKey(prev.Account, prev.App, prev.Host), RecordKey(rec.Account, rec.App, rec.Host))
- // The host's owner is in dispute: neither app vouches for it.
- unread[prev.Account+"/"+prev.App] = true
- unread[rec.Account+"/"+rec.App] = true
- continue
- }
- recs[rec.Host] = rec
- }
- }
- return recordScan{ingress: ingress, observed: observed, departureRecords: departureRecords, departureInvalid: departureInvalid, recs: recs, protect: protect, readFailed: readFailed, known: known, stale: stale,
- unread: unread, failedAccts: failedAccts, partial: partial, fleet: fleet, hosts: hosts, unreadHosts: unreadHosts}, nil
+ return scanInstanceRecords(ctx, st, cfg)
}
sc, err := scan(s)
if cfg.HAIngress != nil {
- ingressErr := err
- if sc.readFailed || sc.partial || len(sc.unread) > 0 || len(sc.protect) > 0 {
- ingressErr = errors.Join(ingressErr, errors.New("HA ingress: incomplete instance scan"))
- }
- cfg.HAIngress(sc.ingress, ingressErr)
+ cfg.HAIngress(sc.ingress, sc.ingressError(err))
}
cfg.Departures.family("instance", sc.departureRecords, err == nil && !sc.departureInvalid && !sc.readFailed && !sc.partial && len(sc.unread) == 0 && len(sc.protect) == 0)