carlos / platform Public

test: witness pool isolation through the real HA ingress

Co-Authored-By: GPT-6 Astra <noreply@openai.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 6cbb688f5d78382ec1ab39b3da1a82aed6f26a30 parent 27db776
4 files changed, +1,842 −0
  • internal/host/region_ha_g2_pool_root_linux_test.go +503 −0
  • internal/host/region_ha_g2_root_fixture_test.go +720 −0
  • scripts/region-ha-g2-pool-witness.py +510 −0
  • scripts/region_ha_g2_pool_witness_test.py +109 −0

Intent

Human

<task-notification> <task-id>a8e8dd0c8b309cefb</task-id> <tool-use-id>toolu_01UPbTmA2VhaxgwJfKBayk1f</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/5555438b-7fa2-408d-b2c4-9fa87ea89332/tasks/a8e8dd0c8b309cefb.output</output-file> <status>completed</status> <summary>Agent "F-A re-review R2 (Opus)" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>**Verdict: READY.** Per-finding verdicts: - **P2-1: ADDRESSED.** Shutdown now waits only for each recovery attempt's discovery step, and gives up when its own deadline passes (activator.go:6143-6177). Once a recovery entry is installed, Shutdown's normal stop pass handles it. - **P2-2: ADDRESSED.** - Every request refusal records demand: serve, begin on each loop pass, WakeWorker and forwardTarget, both normal and memory-only. - The sweep retries a host only if a request came in the last 60 s (haleaseloss.go:139). - A foreign-owner record is not retried until a new request arrives. - Changed routes are parked after a local registry read, with no S3 call, and the latch stays. - The latch is still cleared only at haleaseloss.go:264, after a fresh healthy acquire. - **P3-1: ADDRESSED.** The early return in finishStop is gone (activator.go:5203). The latch checks entry identity itself (haleaseloss.go:61). - **P3-2: ADDRESSED.** Requests waiting on a stop now wake when the loss is latched (activator.go:1909-1916, haleaseloss.go:78-82). I found no double close and no busy loop. - **P3-3: ADDRESSED.** A failed post-check now stops the recovery entry with `StopLeaseLost` (haleaseloss.go:256-262). **Ruling soundness:** the T7 change matches your ruling, and I found no unsafe consequence. - Silence never refuses, and there is one shared lock re-read per window. - Only lock evidence changes routing. A read error does not extend the holder's cache lifetime. - A dial failure still escalates to the existing N-HA15 refusal. One thing for T11 / drill 4: a client on a frozen holder no longer gets a fast answer from the 3 s silence check. It now depends on the holder's own C1 refusal or on the lease expiring, and the witness expectations should say which. **New P1/P2:** none. The file also lists five P3s, none blocking: - Silent forwards still mark the holder box as a suspect placement peer for other hosts. - Held-stream refusals on a latched host neither answer C1 nor record demand. - The foreign-owner park lifts on any request, so a busy peer-held host costs one lock GET every 10 s. - The recovery worker group (`haLoss.joined`) is no longer waited on in production. - A latched host whose route turns non-HA in place repeats a wake-and-stop every 10 s while requests keep coming. I ran no tests; this is from reading the diff and the code at 1d74483b. Review: /home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-g2-fixes/.superpowers/sdd/2026-11-06-region-ha-g2-fixes/fa-review-r2.md</result> <usage><subagent_tokens>120516</subagent_tokens><tool_uses>36</tool_uses><duration_ms>461210</duration_ms></usage> </task-notification>

diff --git a/internal/host/region_ha_g2_pool_root_linux_test.go b/internal/host/region_ha_g2_pool_root_linux_test.go
new file mode 100644
index 000000000..dd80897a6
--- /dev/null
+++ b/internal/host/region_ha_g2_pool_root_linux_test.go
@@ -0,0 +1,503 @@
+//go:build linux && rootrunner
+
+package host
+
+import (
+ "bytes"
+ "crypto/ed25519"
+ "crypto/hmac"
+ "crypto/rand"
+ "crypto/sha256"
+ "encoding/base64"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "os"
+ "slices"
+ "strconv"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/appconfig"
+ "github.com/carlosframework/platform/internal/domains"
+ "github.com/carlosframework/platform/internal/hafresh"
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+type g2Response struct {
+ Status int
+ Headers http.Header
+ Body []byte
+ Elapsed time.Duration
+ Err error
+}
+type g2Delivery struct {
+ Ref string `json:"ref"`
+ PID int `json:"pid"`
+ Cgroup string `json:"cgroup"`
+ Deliveries map[string]int `json:"deliveries"`
+}
+
+func g2Request(client *http.Client, host, method, id, hop string) g2Response {
+ start := time.Now()
+ req, err := http.NewRequest(method, "https://"+host+"/", strings.NewReader(id))
+ if err != nil {
+ return g2Response{Err: err}
+ }
+ if hop != "" {
+ req.Header.Set("X-Carlos-Hop", "1")
+ req.Header.Set("X-Carlos-Hop-Auth", hop)
+ }
+ response, err := client.Do(req)
+ if err != nil {
+ return g2Response{Elapsed: time.Since(start), Err: err}
+ }
+ defer response.Body.Close()
+ body, err := io.ReadAll(io.LimitReader(response.Body, 1<<20))
+ return g2Response{Status: response.StatusCode, Headers: response.Header.Clone(), Body: body, Elapsed: time.Since(start), Err: err}
+}
+func g2LogResponse(t *testing.T, name string, response g2Response) {
+ t.Helper()
+ t.Logf("HTTP case=%s status=%d elapsed=%s headers=%v body=%s error=%v", name, response.Status, response.Elapsed, response.Headers, response.Body, response.Err)
+}
+func g2Served(t *testing.T, client *http.Client, name, host, ref string) g2Delivery {
+ t.Helper()
+ response := g2Request(client, host, "GET", "", "")
+ g2LogResponse(t, name, response)
+ if response.Err != nil || response.Status != 200 {
+ t.Fatalf("%s: expected successful peer response", name)
+ }
+ var delivery g2Delivery
+ g2Must(t, json.Unmarshal(response.Body, &delivery))
+ if delivery.Ref != ref || delivery.PID <= 1 || !strings.Contains(delivery.Cgroup, "carlos-instance") {
+ t.Fatalf("%s: wrong writer or missing nested cgroup: %+v", g2PoolViolation, delivery)
+ }
+ return delivery
+}
+func g2Refused(t *testing.T, client *http.Client, name, host, hop string) {
+ t.Helper()
+ response := g2Request(client, host, "POST", name, hop)
+ g2LogResponse(t, name, response)
+ if response.Err != nil || response.Status != 503 || response.Headers.Get("Retry-After") != "10" || response.Headers.Get("X-Carlos-Holder") != "none" {
+ t.Fatalf("%s: %s expected 503/Retry-After 10/holder none", g2PoolViolation, name)
+ }
+}
+func g2Lock(t *testing.T, store release.Store, host string) hafresh.View {
+ t.Helper()
+ raw, etag, err := store.Get(t.Context(), "instances/"+host+"/lock.json")
+ if errors.Is(err, os.ErrNotExist) {
+ return hafresh.View{Absent: true}
+ }
+ g2Must(t, err)
+ view, err := hafresh.DecodeLock(raw, etag)
+ g2Must(t, err)
+ return view
+}
+func g2Put(t *testing.T, store release.Store, key string, value []byte) {
+ t.Helper()
+ _, etag, err := store.Get(t.Context(), key)
+ if err != nil && !errors.Is(err, os.ErrNotExist) {
+ t.Fatal(err)
+ }
+ _, err = store.Put(t.Context(), key, value, etag)
+ g2Must(t, err)
+}
+func g2Serial(t *testing.T, store release.Store) {
+ g2Put(t, store, "control/serial", []byte(strconv.FormatInt(time.Now().UnixNano(), 10)))
+}
+func g2ZeroAcquire(events []g2S3Event, ip, host string) error {
+ for _, event := range events {
+ if event.Source == ip && event.Method == "PUT" && event.Path == "/"+g2Data+"/instances/"+host+"/lock.json" && !event.Release {
+ return fmt.Errorf("%s: ineligible box attempted lock PUT: %+v", g2PoolViolation, event)
+ }
+ }
+ return nil
+}
+func g2NoLocal(t *testing.T, box *g2Box, storage *g2Storage, since int) {
+ t.Helper()
+ state := box.state()
+ t.Logf("A evidence %s", g2JSON(t, state))
+ if state.TenantPIDs[g2Host] != "0" && state.TenantPIDs[g2Host] != "" {
+ t.Fatalf("%s: local PID %s", g2PoolViolation, state.TenantPIDs[g2Host])
+ }
+ if strings.Contains(state.TenantCgroups[g2Host], "populated 1") {
+ t.Fatalf("%s: populated local tenant cgroup", g2PoolViolation)
+ }
+ g2Must(t, g2ZeroAcquire(storage.snapshot()[since:], box.ip, g2Host))
+ view := g2Lock(t, storage.data, g2Host)
+ t.Logf("lock evidence %s", g2JSON(t, view))
+ if owner, ok := hafresh.ParseOwner(view.Lock.Owner); ok && owner.IID == box.iid && !view.Absent {
+ t.Fatalf("%s: A holds lock", g2PoolViolation)
+ }
+}
+func g2WaitReleased(t *testing.T, storage *g2Storage, iid string) hafresh.View {
+ t.Helper()
+ var view hafresh.View
+ g2Wait(t, "real idle sleep and release", 100*time.Second, func() bool {
+ view = g2Lock(t, storage.data, g2Host)
+ return view.Lock.Release != nil && view.Lock.Release.IID == iid
+ })
+ t.Logf("release evidence %s", g2JSON(t, view))
+ return view
+}
+func g2WaitPeer(t *testing.T, store release.Store, ref string, pools []string) {
+ t.Helper()
+ g2Wait(t, "production peer publication "+ref, 100*time.Second, func() bool {
+ raw, _, err := store.Get(t.Context(), "control/edges/"+ref+".json")
+ if err != nil {
+ return false
+ }
+ var file struct {
+ Pools []string `json:"served_pools"`
+ Generation string `json:"generation"`
+ Hosts map[string]any `json:"hosts"`
+ }
+ return json.Unmarshal(raw, &file) == nil && slices.Equal(file.Pools, pools) && file.Generation != ""
+ })
+ // The real edge polls its peer view; no in-process refresh seam.
+ time.Sleep(35 * time.Second)
+}
+func g2Seed(t *testing.T, storage *g2Storage) (g2Config, []byte) {
+ cert, key, ca := g2Certificates(t)
+ secret, _, err := appconfig.GenerateKey()
+ g2Must(t, err)
+ config := g2Config{Certificate: cert, CertificateKey: key, CA: ca, SecretsKey: secret, Records: []provision.Record{{Schema: 1, Host: g2Host, Slug: "pool", Account: g2Account, App: g2App, Pool: "ha", Region: "ie", Channel: "stable", HA: true, CreatedAt: time.Now().Add(-time.Hour).UTC()}}}
+ _, err = storage.deploy.Put(t.Context(), provision.ManifestKey(g2Account, g2App), g2JSON(t, provision.Manifest{Schema: 1, App: g2App, Domain: "g2fix.test", Pool: "ha", Channel: "stable", Regions: []string{"ie"}}), "")
+ g2Must(t, err)
+ for _, rec := range config.Records {
+ g2Must(t, provision.CreateRecord(t.Context(), storage.deploy, rec))
+ }
+ for _, host := range []string{g2Alias, g2Regional} {
+ claim := domains.Claim{Schema: 1, Host: host, Account: g2Account, App: g2App, Route: g2Host, CreatedAt: time.Now().UTC().Format(time.RFC3339)}
+ if host == g2Regional {
+ claim.Schema = 2
+ claim.Placements = []domains.Placement{{Region: "ie", Host: g2Host}}
+ }
+ _, err := storage.deploy.Put(t.Context(), domains.ClaimKey(host), g2JSON(t, claim), "")
+ g2Must(t, err)
+ }
+ mesh := make([]byte, 32)
+ _, err = rand.Read(mesh)
+ g2Must(t, err)
+ _, err = storage.deploy.Put(t.Context(), "control/edge-mesh-key", []byte(hex.EncodeToString(mesh)), "")
+ g2Must(t, err)
+ for _, host := range []string{g2Host, g2Alias, g2Regional} {
+ _, err = storage.deploy.Put(t.Context(), "control/certs/"+host, []byte(key+cert), "")
+ g2Must(t, err)
+ }
+ // A real signed channel and canonical manifest allow before-exec policy to
+ // record the exact staged build. There is no build-state bypass.
+ pub, priv, err := ed25519.GenerateKey(rand.Reader)
+ g2Must(t, err)
+ config.ReleasePub = base64.StdEncoding.EncodeToString(pub)
+ image, err := os.ReadFile(g2Root + "/g2.test")
+ g2Must(t, err)
+ sum := sha256.Sum256(image)
+ manifest := release.Manifest{Schema: 1, App: g2App, Version: g2Version, Kind: "binary", Artifacts: map[string]release.Artifact{"linux-arm64": {File: "g2.test", SHA256: hex.EncodeToString(sum[:]), Size: int64(len(image))}}}
+ _, err = storage.deploy.Put(t.Context(), release.ManifestKey(g2Account, g2App, g2Version), g2JSON(t, manifest), "")
+ g2Must(t, err)
+ _, err = storage.deploy.Put(t.Context(), release.ReleasesPrefix(g2Account, g2App)+g2Version+"/g2.test", image, "")
+ g2Must(t, err)
+ g2Must(t, release.RootSigner(priv).Promote(t.Context(), storage.deploy, g2Account, g2App, "stable", g2Version))
+ g2Serial(t, storage.deploy)
+ return config, mesh
+}
+
+func TestRootG2PoolIngress(t *testing.T) {
+ g2Prereqs(t, "A")
+ // Local helpers never call this test: it requires the two driver-owned IIDs.
+ g2Wait(t, "peer fixture control", 30*time.Second, func() bool {
+ req, _ := http.NewRequest("POST", "http://"+os.Getenv("G2_B_IP")+":9444/", strings.NewReader(`{"Action":"ready"}`))
+ req.Header.Set("Authorization", "Bearer "+os.Getenv("G2_TOKEN"))
+ r, err := (&http.Client{Timeout: time.Second}).Do(req)
+ if err != nil {
+ return false
+ }
+ r.Body.Close()
+ return r.StatusCode == 200
+ })
+ storage := g2MinIO(t)
+ config, mesh := g2Seed(t, storage)
+ a := g2NewBox(t, "A", config)
+ b := g2Peer(t, g2RPC{Action: "configure", Config: config})
+ t.Cleanup(func() {
+ t.Logf("S3 request census %s", g2JSON(t, storage.snapshot()))
+ // B's teardown is also run by SIGTERM if this request is interrupted.
+ req, _ := http.NewRequest("POST", "http://"+os.Getenv("G2_B_IP")+":9444/", strings.NewReader(`{"Action":"shutdown"}`))
+ req.Header.Set("Authorization", "Bearer "+os.Getenv("G2_TOKEN"))
+ r, err := (&http.Client{Timeout: 90 * time.Second}).Do(req)
+ if err == nil {
+ r.Body.Close()
+ } else {
+ t.Error(err)
+ }
+ })
+ if a.iid == b.IID || a.state().Ref == b.Ref {
+ t.Fatal("distinct IMDS and box references required")
+ }
+ client := g2Client(t, config.CA)
+ b = g2Peer(t, g2RPC{Action: "start"})
+ a.start()
+ g2Serial(t, storage.deploy)
+ g2WaitPeer(t, storage.deploy, b.Ref, []string{"ha"})
+ // Any changed guard is observed at the first ineligible local service,
+ // acquisition attempt, or signed-hop acceptance, not at a setup failure.
+ start := len(storage.snapshot())
+ ts := strconv.FormatInt(time.Now().Unix(), 10)
+ mac := hmac.New(sha256.New, mesh)
+ mac.Write([]byte(g2Host + "\n" + ts))
+ g2Refused(t, client, "signed-hop-ineligible", g2Host, ts+":"+hex.EncodeToString(mac.Sum(nil)))
+ g2NoLocal(t, a, storage, start)
+ t.Log("CASE signed-hop-ineligible PASS")
+
+ // Run all lease shapes with the old-row startup and again after explicit
+ // row removal. No fake local row replaces the production ingress projection.
+ for _, projection := range []string{"old-row-startup", "row-absent"} {
+ if projection == "row-absent" {
+ g2Must(t, a.reg.Delete(g2Host))
+ g2Serial(t, storage.deploy)
+ time.Sleep(3 * time.Second)
+ }
+ start = len(storage.snapshot())
+ first := g2Served(t, client, projection+"/initial", g2Host, b.Ref)
+ held := g2Lock(t, storage.data, g2Host)
+ owner, ok := hafresh.ParseOwner(held.Lock.Owner)
+ if !ok || owner.IID != b.IID || held.Lock.Generation <= 0 || held.Lock.Release != nil {
+ t.Fatalf("expected B live holder: %+v", held)
+ }
+ second := g2Served(t, client, projection+"/held", g2Host, b.Ref)
+ if first.PID != second.PID {
+ t.Fatal("held request replaced the writer")
+ }
+ t.Logf("CASE %s/held PASS", projection)
+ livePeer := g2Peer(t, g2RPC{Action: "state"})
+ t.Logf("B live evidence %s", g2JSON(t, livePeer))
+ if livePeer.TenantPIDs[g2Host] == "0" || !strings.Contains(livePeer.TenantCgroups[g2Host], "populated 1") {
+ t.Fatal("B has no live nested tenant cgroup")
+ }
+ for _, kind := range []string{"clean", "unclean", "absent"} {
+ released := g2WaitReleased(t, storage, b.IID)
+ if kind == "clean" && !released.Lock.Release.Clean {
+ t.Fatal("real clean release was not clean")
+ }
+ stoppedPeer := g2Peer(t, g2RPC{Action: "state"})
+ t.Logf("B release evidence %s", g2JSON(t, stoppedPeer))
+ if stoppedPeer.TenantPIDs[g2Host] != "0" && stoppedPeer.TenantPIDs[g2Host] != "" {
+ t.Fatal("B released with a live tenant PID")
+ }
+ if strings.Contains(stoppedPeer.TenantCgroups[g2Host], "populated 1") {
+ t.Fatal("B released with a populated tenant cgroup")
+ }
+ if kind == "unclean" {
+ marker := *released.Lock.Release
+ marker.Clean = false
+ raw, err := hafresh.MarkerBody(released.Lock.Generation, marker)
+ g2Must(t, err)
+ _, err = storage.data.Put(t.Context(), "instances/"+g2Host+"/lock.json", raw, released.ETag)
+ g2Must(t, err)
+ }
+ if kind == "absent" {
+ g2Must(t, storage.data.Delete(t.Context(), "instances/"+g2Host+"/lock.json"))
+ }
+ // Restart A through its supported startup path to clear holder-cache
+ // history. Its pool remains 'other' and no membership seam is used.
+ a.pools("other")
+ g2Served(t, client, projection+"/"+kind, g2Host, b.Ref)
+ g2NoLocal(t, a, storage, start)
+ t.Logf("CASE %s/%s PASS", projection, kind)
+ }
+ g2Served(t, client, projection+"/alias", g2Alias, b.Ref)
+ t.Logf("CASE %s/alias PASS", projection)
+ g2Served(t, client, projection+"/regional", g2Regional, b.Ref)
+ t.Logf("CASE %s/regional PASS", projection)
+ g2NoLocal(t, a, storage, start)
+ }
+
+ // Every POST has a unique receipt ID; replay increments a count rather
+ // than being hidden by an application's idempotency response.
+ start = len(storage.snapshot())
+ const count = 16
+ responses := make([]g2Response, count)
+ var wg sync.WaitGroup
+ for i := range count {
+ wg.Add(1)
+ go func(i int) {
+ defer wg.Done()
+ responses[i] = g2Request(client, g2Host, "POST", fmt.Sprintf("concurrent-%02d", i), "")
+ }(i)
+ }
+ wg.Wait()
+ for i, response := range responses {
+ g2LogResponse(t, fmt.Sprintf("concurrent-%02d", i), response)
+ if response.Err != nil || response.Status != 200 {
+ t.Fatal("concurrent POST failed")
+ }
+ }
+ delivered := g2Served(t, client, "receipt-counts", g2Host, b.Ref)
+ for i := range count {
+ if delivered.Deliveries[fmt.Sprintf("concurrent-%02d", i)] != 1 {
+ t.Fatal("duplicate or missing delivery", delivered.Deliveries)
+ }
+ }
+ if delivered.Deliveries["signed-hop-ineligible"] != 0 {
+ t.Fatalf("%s: refused signed hop went onward", g2PoolViolation)
+ }
+ g2NoLocal(t, a, storage, start)
+ t.Log("CASE concurrent-posts PASS")
+
+ // Freeze only the publisher's S3 writes while retaining its real pool
+ // evidence. The peer still serves through its real agent.
+ g2WaitReleased(t, storage, b.IID)
+ g2PeerEvidence(t, storage, b.Ref, true, false)
+ a.pools("other")
+ g2Served(t, client, "eligible-low-headroom", g2Host, b.Ref)
+ g2NoLocal(t, a, storage, start)
+ storage.holdPeer("")
+ t.Log("CASE eligible-low-headroom PASS")
+ g2WaitReleased(t, storage, b.IID)
+ b = g2Peer(t, g2RPC{Action: "pools", Value: "other"})
+ g2Serial(t, storage.deploy)
+ g2WaitPeer(t, storage.deploy, b.Ref, []string{"other"})
+ start = len(storage.snapshot())
+ a.pools("other")
+ g2Refused(t, client, "no-eligible-peer", g2Host, "")
+ g2NoLocal(t, a, storage, start)
+ t.Log("CASE no-eligible-peer PASS")
+ g2PeerEvidence(t, storage, b.Ref, false, true)
+ a.pools("other")
+ g2Refused(t, client, "host-advertised-wrong-pool", g2Host, "")
+ g2NoLocal(t, a, storage, start)
+ storage.holdPeer("")
+ t.Log("CASE host-advertised-wrong-pool PASS")
+
+ // Previously awake A, first clean withdrawal, then a stop whose root
+ // control channel cannot complete, then a durable owed release.
+ for _, fault := range []string{"clean", "blocked-stop", "pending-release"} {
+ a.pools("ha")
+ g2Serial(t, storage.deploy)
+ g2Wait(t, "A reminted eligible row", 60*time.Second, func() bool { row, err := a.reg.Get(g2Host); return err == nil && row != nil })
+ aRef := a.state().Ref
+ g2Served(t, client, "withdrawal/"+fault+"/awake", g2Host, aRef)
+ awake := a.state()
+ if awake.TenantPIDs[g2Host] == "0" {
+ t.Fatal("withdrawal fixture never woke")
+ }
+ if fault == "blocked-stop" {
+ g2Command(t, "systemctl", "kill", "--kill-whom=main", "--signal=STOP", "carlos-instance-control.service")
+ }
+ if fault == "pending-release" {
+ storage.block(true)
+ }
+ boundary := len(storage.snapshot())
+ a.pools("other")
+ g2Serial(t, storage.deploy)
+ g2Refused(t, client, "withdrawal/"+fault+"/fenced", g2Host, "")
+ if fault != "clean" {
+ state := a.state()
+ found := false
+ for _, row := range state.Rows {
+ if row.Host == g2Host {
+ found = true
+ }
+ }
+ if !found {
+ t.Fatal("row removed before stop/duties were proven", fault)
+ }
+ g2Must(t, g2ZeroAcquire(storage.snapshot()[boundary:], a.ip, g2Host))
+ if fault == "pending-release" && len(state.Owed) == 0 {
+ t.Fatal("pending release fixture produced no durable obligation")
+ }
+ if fault == "blocked-stop" {
+ g2Command(t, "systemctl", "kill", "--kill-whom=main", "--signal=CONT", "carlos-instance-control.service")
+ }
+ storage.block(false)
+ g2Serial(t, storage.deploy)
+ }
+ // Observe the release before permitting row disappearance to count as a pass.
+ g2Wait(t, "withdrawal stop-release-remove ordering", 100*time.Second, func() bool {
+ row, err := a.reg.Get(g2Host)
+ g2Must(t, err)
+ if row != nil {
+ g2Serial(t, storage.deploy)
+ return false
+ }
+ view := g2Lock(t, storage.data, g2Host)
+ if view.Lock.Release == nil || view.Lock.Release.IID != a.iid {
+ t.Fatal("row removed without A release marker", view)
+ }
+ var deletedAt float64
+ g2Must(t, a.audit.QueryRow("SELECT max(at) FROM g2_deletions WHERE host=?", g2Host).Scan(&deletedAt))
+ ordered := false
+ for _, event := range storage.snapshot()[boundary:] {
+ if event.Source == a.ip && event.Release && event.Status == 200 &&
+ event.Path == "/"+g2Data+"/instances/"+g2Host+"/lock.json" &&
+ !event.AcceptedAt.IsZero() && float64(event.AcceptedAt.UnixMilli()) <= deletedAt*1000+1 {
+ ordered = true
+ t.Logf("withdrawal order: release accepted %s, registry delete %.3f", event.AcceptedAt, deletedAt)
+ }
+ }
+ if !ordered {
+ t.Fatal("registry deletion preceded acknowledged release")
+ }
+ state := a.state()
+ if state.TenantPIDs[g2Host] != "0" && state.TenantPIDs[g2Host] != "" {
+ t.Fatal("row removed with a live tenant", state)
+ }
+ return true
+ })
+ g2Must(t, g2ZeroAcquire(storage.snapshot()[boundary:], a.ip, g2Host))
+ t.Logf("CASE withdrawal/%s PASS", fault)
+ }
+ t.Log("PASS TestRootG2PoolIngress")
+}
+
+func g2PeerEvidence(t *testing.T, storage *g2Storage, ref string, low, advertise bool) {
+ t.Helper()
+ key := "control/edges/" + ref + ".json"
+ storage.holdPeer(key)
+ raw, _, err := storage.deploy.Get(t.Context(), key)
+ g2Must(t, err)
+ var doc map[string]json.RawMessage
+ g2Must(t, json.Unmarshal(raw, &doc))
+ if low {
+ doc["headroom"] = json.RawMessage(`{"mem_free_mib":1,"mem_total_mib":2048,"disk_free_mib":1,"disk_total_mib":30000,"awake":0}`)
+ }
+ if advertise {
+ doc["hosts"] = g2JSON(t, map[string]any{g2Host: map[string]any{"role": "home", "account": g2Account, "app": g2App, "platform": true}})
+ }
+ // Controller fixture writes use the direct MinIO client, bypassing the
+ // publication fault, and never edit served_pools.
+ target := &release.S3Store{Client: storage.direct, Bucket: g2Deploy}
+ g2Put(t, target, key, g2JSON(t, doc))
+ time.Sleep(35 * time.Second)
+}
+
+func TestG2PoolEvidenceHelpers(t *testing.T) {
+ valid := g2S3Event{Source: "10.0.0.1", Method: "PUT", Path: "/" + g2Data + "/instances/" + g2Host + "/lock.json", Release: true}
+ if err := g2ZeroAcquire([]g2S3Event{valid}, "10.0.0.1", g2Host); err != nil {
+ t.Fatal(err)
+ }
+ for _, status := range []int{200, 412, 503} {
+ bad := valid
+ bad.Release = false
+ bad.Status = status
+ if err := g2ZeroAcquire([]g2S3Event{bad}, "10.0.0.1", g2Host); err == nil {
+ t.Fatal("missed attempted acquisition", status)
+ }
+ }
+ other := valid
+ other.Release = false
+ other.Source = "10.0.0.2"
+ if err := g2ZeroAcquire([]g2S3Event{other}, "10.0.0.1", g2Host); err != nil {
+ t.Fatal(err)
+ }
+ if bytes.Equal(g2JSON(t, g2Response{Status: 200}), g2JSON(t, g2Response{Status: 503})) {
+ t.Fatal("evidence collapses status")
+ }
+}
diff --git a/internal/host/region_ha_g2_root_fixture_test.go b/internal/host/region_ha_g2_root_fixture_test.go
new file mode 100644
index 000000000..bf3b77b6d
--- /dev/null
+++ b/internal/host/region_ha_g2_root_fixture_test.go
@@ -0,0 +1,720 @@
+//go:build linux && rootrunner
+
+package host
+
+import (
+ "bytes"
+ "context"
+ "crypto/ecdsa"
+ "crypto/elliptic"
+ "crypto/rand"
+ "crypto/sha256"
+ "crypto/subtle"
+ "crypto/tls"
+ "crypto/x509"
+ "crypto/x509/pkix"
+ "database/sql"
+ "encoding/hex"
+ "encoding/json"
+ "encoding/pem"
+ "errors"
+ "flag"
+ "io"
+ "math/big"
+ "net"
+ "net/http"
+ "net/http/httputil"
+ "net/url"
+ "os"
+ "os/exec"
+ "os/signal"
+ "os/user"
+ "path/filepath"
+ "slices"
+ "strconv"
+ "strings"
+ "sync"
+ "syscall"
+ "testing"
+ "time"
+
+ "github.com/aws/aws-sdk-go-v2/aws"
+ "github.com/aws/aws-sdk-go-v2/credentials"
+ "github.com/aws/aws-sdk-go-v2/service/s3"
+ "github.com/carlosframework/platform/internal/hafresh"
+ "github.com/carlosframework/platform/internal/instancectl"
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+const (
+ g2Root = "/var/lib/g2fix"
+ g2Host = "pool.g2fix.test"
+ g2Alias = "alias.g2fix.test"
+ g2Regional = "pool.ie.g2fix.test"
+ g2Account = "bab"
+ g2App = "g2witness"
+ g2Version = "a0123456"
+ g2Deploy = "g2fix-deployment"
+ g2Data = "g2fix-data"
+ g2Access = "g2fix-access"
+ g2Secret = "g2fix-secret-only-disposable-minio"
+ g2PoolViolation = "G2_POOL_VIOLATION"
+)
+
+type g2Config struct {
+ Certificate, CertificateKey, CA, SecretsKey, ReleasePub string
+ Records []provision.Record
+}
+
+type g2State struct {
+ IID, Ref, AgentPID, AgentCgroup, Pools string
+ Rows []registry.Route
+ TenantPIDs map[string]string
+ TenantCgroups map[string]string
+ Owed []string
+}
+
+type g2Box struct {
+ t *testing.T
+ role, iid, ip string
+ config g2Config
+ reg *registry.Registry
+ audit *sql.DB
+ uid, gid int
+ env map[string]string
+ units []string
+}
+
+func g2Must(t *testing.T, err error) {
+ t.Helper()
+ if err != nil {
+ t.Fatal(err)
+ }
+}
+func g2JSON(t *testing.T, value any) []byte {
+ t.Helper()
+ data, err := json.Marshal(value)
+ g2Must(t, err)
+ return data
+}
+func g2Write(t *testing.T, path string, data []byte, mode os.FileMode) {
+ t.Helper()
+ g2Must(t, os.MkdirAll(filepath.Dir(path), 0755))
+ g2Must(t, os.WriteFile(path, data, mode))
+}
+func g2Command(t *testing.T, name string, args ...string) string {
+ t.Helper()
+ ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second)
+ defer cancel()
+ cmd := exec.CommandContext(ctx, name, args...)
+ cmd.Dir = g2Root
+ out, err := cmd.CombinedOutput()
+ if err != nil {
+ t.Fatalf("%s %v: %v\n%s", name, args, err, out)
+ }
+ return strings.TrimSpace(string(out))
+}
+func g2Wait(t *testing.T, why string, timeout time.Duration, fn func() bool) {
+ t.Helper()
+ deadline := time.Now().Add(timeout)
+ for time.Now().Before(deadline) {
+ if fn() {
+ return
+ }
+ time.Sleep(250 * time.Millisecond)
+ }
+ t.Fatalf("timeout: %s", why)
+}
+func g2Prereqs(t *testing.T, role string) (string, string) {
+ t.Helper()
+ egressRootPrereqs(t)
+ // Refuse every deployment-owned root before installing anything.
+ for _, path := range []string{"/data", "/opt/carlos", "/etc/carlos", "/run/carlos", "/run/carlos-control"} {
+ if _, err := os.Lstat(path); !errors.Is(err, os.ErrNotExist) {
+ t.Fatalf("refuse existing deployment path %s: %v", path, err)
+ }
+ }
+ if os.Getenv("G2_RUN") == "" || len(os.Getenv("G2_TOKEN")) < 32 {
+ t.Fatal("driver ownership environment required")
+ }
+ if role != "A" && role != "B" {
+ t.Fatal("invalid role")
+ }
+ iid, account, region, err := readIdentity(haIMDSClient, imdsBase)
+ g2Must(t, err)
+ if iid != os.Getenv("G2_"+role+"_IID") || account != "640012953448" || region != "eu-west-1" || os.Getenv("G2_A_IID") == os.Getenv("G2_B_IID") {
+ t.Fatalf("runner identity mismatch: %s %s %s", iid, account, region)
+ }
+ ip := os.Getenv("G2_" + role + "_IP")
+ parsed := net.ParseIP(ip)
+ if parsed == nil || !parsed.IsPrivate() || parsed.To4() == nil {
+ t.Fatal("private IPv4 required")
+ }
+ local, err := net.InterfaceAddrs()
+ g2Must(t, err)
+ found := false
+ for _, addr := range local {
+ p, _, _ := net.ParseCIDR(addr.String())
+ if p.Equal(parsed) {
+ found = true
+ }
+ }
+ if !found {
+ t.Fatal("private address is not local")
+ }
+ return iid, ip
+}
+
+func g2Certificates(t *testing.T) (cert, key, ca string) {
+ t.Helper()
+ priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
+ g2Must(t, err)
+ root := &x509.Certificate{SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: "g2fix fixture CA"}, IsCA: true, BasicConstraintsValid: true, KeyUsage: x509.KeyUsageCertSign, NotBefore: time.Now().Add(-time.Minute), NotAfter: time.Now().Add(90 * 24 * time.Hour)}
+ der, err := x509.CreateCertificate(rand.Reader, root, root, &priv.PublicKey, priv)
+ g2Must(t, err)
+ ca = string(pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}))
+ leafKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
+ g2Must(t, err)
+ leaf := &x509.Certificate{SerialNumber: big.NewInt(2), DNSNames: []string{g2Host, g2Alias, g2Regional}, KeyUsage: x509.KeyUsageDigitalSignature, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, NotBefore: time.Now().Add(-time.Minute), NotAfter: time.Now().Add(90 * 24 * time.Hour)}
+ leafDER, err := x509.CreateCertificate(rand.Reader, leaf, root, &leafKey.PublicKey, priv)
+ g2Must(t, err)
+ raw, err := x509.MarshalECPrivateKey(leafKey)
+ g2Must(t, err)
+ key = string(pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: raw}))
+ cert = string(pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: leafDER})) + ca
+ return
+}
+
+func g2NewBox(t *testing.T, role string, config g2Config) *g2Box {
+ t.Helper()
+ iid, ip := g2Prereqs(t, role)
+ b := &g2Box{t: t, role: role, iid: iid, ip: ip, config: config}
+ b.uid, b.gid = generationRunnerRegistryUser(t)
+ if _, err := user.LookupGroup(socketsGroup); err == nil {
+ t.Fatal("refuse existing socket-consumer group")
+ }
+ g2Command(t, "groupadd", "--system", socketsGroup)
+ t.Cleanup(func() { exec.Command("groupdel", socketsGroup).Run() })
+ for _, path := range []string{"/data", "/opt/carlos", "/etc/carlos", "/run/carlos", "/run/carlos-control"} {
+ g2Must(t, os.Mkdir(path, 0755))
+ p := path
+ t.Cleanup(func() {
+ if err := os.RemoveAll(p); err != nil {
+ t.Error(err)
+ }
+ })
+ }
+ g2Must(t, os.Chown("/data", b.uid, b.gid))
+ g2Must(t, os.Chmod("/data", 0750))
+ tmpConf := filepath.Join(g2Root, "tmpfiles.conf")
+ g2Write(t, tmpConf, []byte(tmpfilesConf), 0600)
+ if _, err := os.Lstat("/dev/shm/carlos-probe"); !errors.Is(err, os.ErrNotExist) {
+ t.Fatal("probe fixture already exists")
+ }
+ t.Cleanup(func() { os.Remove("/dev/shm/carlos-probe"); os.Remove(tmpConf) })
+ g2Command(t, "systemd-tmpfiles", "--create", tmpConf)
+ binary := os.Getenv("G2_BINARY")
+ if binary != "carlos" && binary != "carlos-mutant" {
+ t.Fatal("invalid branch binary")
+ }
+ image, err := os.ReadFile(filepath.Join(g2Root, binary))
+ g2Must(t, err)
+ g2Write(t, "/opt/carlos/carlos", image, 0755)
+ b.env = map[string]string{
+ "CARLOS_DATA_DIR": "/data", "CARLOS_OPT_DIR": "/opt/carlos", "CARLOS_DEPLOYMENT_BUCKET": g2Deploy,
+ "CARLOS_HIBERNATE_BUCKET": g2Data, "CARLOS_HIBERNATE_REGION": "eu-west-1", "CARLOS_HIBERNATE_PREFIX": "instances",
+ "CARLOS_HIBERNATE_IDLE": "8s", "CARLOS_S3_ENDPOINT": "http://" + os.Getenv("G2_A_IP") + ":9000",
+ "CARLOS_REGION": "ie", "CARLOS_AWS_REGION": "eu-west-1", "CARLOS_REGION_HA": "true",
+ "CARLOS_POOLS": "other", "CARLOS_LAYOUT_DEFAULT": "nested", "CARLOS_SECRETS_KEY": config.SecretsKey, "CARLOS_RELEASE_PUBKEY": config.ReleasePub,
+ "AWS_REGION": "eu-west-1", "AWS_DEFAULT_REGION": "eu-west-1", "AWS_ACCESS_KEY_ID": g2Access, "AWS_SECRET_ACCESS_KEY": g2Secret,
+ "AWS_CONFIG_FILE": "/dev/null", "AWS_SHARED_CREDENTIALS_FILE": "/dev/null", "HOME": "/nonexistent",
+ "CARLOS_PUBLIC_IP": ip, "CARLOS_PRIVATE_IP": ip, "CARLOS_PRIVATE_CIDR": ip + "/32",
+ "SSL_CERT_FILE": "/etc/carlos/g2-ca.pem", "CARLOS_HOST_CLAIM": "", "CARLOS_GROUP_ADMISSION": "",
+ }
+ if role == "B" {
+ b.env["CARLOS_POOLS"] = "ha"
+ }
+ b.writeEnv()
+ g2Write(t, "/etc/carlos/g2-ca.pem", []byte(config.CA), 0644)
+ for _, host := range []string{g2Host, g2Alias, g2Regional} {
+ g2Write(t, "/data/acme/"+host, []byte(config.CertificateKey+config.Certificate), 0600)
+ g2Must(t, os.Chown("/data/acme/"+host, b.uid, b.gid))
+ }
+ g2Must(t, os.Chown("/data/acme", b.uid, b.gid))
+ // Install embedded units unchanged except the explicit listener addresses,
+ // restart policy and environment of the two services under test.
+ entries, err := unitsFS.ReadDir("units")
+ g2Must(t, err)
+ for _, entry := range entries {
+ name := entry.Name()
+ if !strings.HasPrefix(name, "carlos-instance") && !slices.Contains([]string{"carlos-edge.service", "carlos.slice", "carlos-instances.slice", "carlos-exec@.service", "data-instances.mount", "run-carlos-instances.mount", "run-carlos-logs.mount"}, name) {
+ continue
+ }
+ if strings.Contains(name, "rootfs") {
+ continue
+ }
+ raw, err := unitsFS.ReadFile("units/" + name)
+ g2Must(t, err)
+ text := string(raw)
+ if name == "carlos-edge.service" {
+ text = strings.Replace(text, "ExecStart=/opt/carlos/carlos agent", "ExecStart=/opt/carlos/carlos agent --http 127.0.0.1:8080 --https "+ip+":443", 1)
+ text = strings.Replace(text, "Restart=always", "Restart=no", 1)
+ }
+ if name == "carlos-instance-control.service" {
+ text += "\n[Service]\nEnvironmentFile=/etc/carlos/host.env\n"
+ }
+ for _, dir := range []string{"/etc/systemd/system", "/run/systemd/system", "/usr/lib/systemd/system", "/lib/systemd/system"} {
+ if _, err := os.Lstat(filepath.Join(dir, name)); !errors.Is(err, os.ErrNotExist) {
+ t.Fatalf("pre-existing unit %s in %s", name, dir)
+ }
+ }
+ path := filepath.Join("/run/systemd/system", name)
+ g2Write(t, path, []byte(text), 0644)
+ b.units = append(b.units, name)
+ t.Cleanup(func() { os.Remove(path) })
+ }
+ g2Command(t, "systemctl", "daemon-reload")
+ g2Command(t, "systemctl", "start", "data-instances.mount", "run-carlos-instances.mount", "run-carlos-logs.mount")
+ // Registered after paths and units, so it runs before their deletion.
+ t.Cleanup(func() { b.cleanup() })
+ b.reg, err = registry.Open("/data/registry.db")
+ g2Must(t, err)
+ b.audit, err = sql.Open("sqlite", "/data/registry.db")
+ g2Must(t, err)
+ _, err = b.audit.Exec(`PRAGMA busy_timeout=5000;
+CREATE TABLE g2_deletions(host TEXT, at REAL);
+CREATE TRIGGER g2_delete AFTER DELETE ON routes BEGIN
+ INSERT INTO g2_deletions VALUES (old.host, unixepoch('subsec'));
+END;`)
+ g2Must(t, err)
+ for _, p := range []string{"/data/registry.db", "/data/registry.db-wal", "/data/registry.db-shm"} {
+ if _, err := os.Stat(p); err == nil {
+ g2Must(t, os.Chown(p, b.uid, b.gid))
+ }
+ }
+ b.seedRows()
+ g2Command(t, "systemctl", "start", "carlos-instance-control.socket", "carlos-instance-control.service")
+ return b
+}
+func (b *g2Box) writeEnv() {
+ keys := make([]string, 0, len(b.env))
+ for key := range b.env {
+ keys = append(keys, key)
+ }
+ slices.Sort(keys)
+ var lines []string
+ for _, key := range keys {
+ lines = append(lines, key+"="+strconv.Quote(b.env[key]))
+ }
+ g2Write(b.t, "/etc/carlos/host.env", []byte(strings.Join(lines, "\n")+"\n"), 0600)
+}
+func (b *g2Box) seedRows() {
+ t := b.t
+ image, err := os.ReadFile(filepath.Join(g2Root, "g2.test"))
+ g2Must(t, err)
+ sum := sha256.Sum256(image)
+ staged := release.VersionPath("/opt/carlos", g2Account, g2Version, g2App)
+ g2Write(t, staged, image, 0755)
+ manifest := release.Manifest{Schema: 1, App: g2App, Version: g2Version, Kind: "binary", Artifacts: map[string]release.Artifact{"linux-arm64": {File: "g2.test", SHA256: hex.EncodeToString(sum[:]), Size: int64(len(image))}}}
+ g2Write(t, release.StagedManifestPath("/opt/carlos", g2Account, g2Version, g2App), g2JSON(t, manifest), 0644)
+ for _, rec := range b.config.Records {
+ rt := provision.RouteFor(rec, "/data", "", true, nil)
+ // RouteFor is also used by the real reconciler; only initial old rows
+ // are seeded here. Every later pool decision comes from host.env.
+ g2Must(t, b.reg.Upsert(rt))
+ for _, dir := range []string{provision.InstanceDir("/data", rt.Host), provision.InstanceRunDir(rt.Host)} {
+ g2Must(t, os.MkdirAll(dir, 0750))
+ g2Must(t, os.Chown(dir, b.uid, b.gid))
+ }
+ env := provision.InstanceDir("/data", rt.Host) + "/.env"
+ g2Write(t, env, []byte("G2_POOL_TENANT=1\nG2_TENANT_IID="+b.iid+"\n"), 0600)
+ g2Must(t, os.Chown(env, b.uid, b.gid))
+ link := release.LiveLink("/opt/carlos", rt.Host)
+ g2Must(t, os.MkdirAll(filepath.Dir(link), 0755))
+ g2Must(t, os.Symlink(staged, link))
+ }
+ g2Must(t, b.reg.UpsertAlias(registry.RouteAlias{Alias: g2Alias, Host: g2Host, Account: g2Account, App: g2App, DNSStatus: "ok", CertExpiresAt: time.Now().Add(time.Hour).Unix()}))
+}
+func (b *g2Box) listening() {
+ g2Wait(b.t, "real agent listener", 60*time.Second, func() bool {
+ conn, err := net.DialTimeout("tcp", net.JoinHostPort(b.ip, "443"), time.Second)
+ if err != nil {
+ return false
+ }
+ conn.Close()
+ return true
+ })
+}
+func (b *g2Box) start() {
+ g2Command(b.t, "systemctl", "start", "carlos-edge.service")
+ b.listening()
+}
+func (b *g2Box) pools(value string) {
+ if value != "ha" && value != "other" {
+ b.t.Fatal("invalid fixture pool")
+ }
+ b.env["CARLOS_POOLS"] = value
+ b.writeEnv()
+ g2Command(b.t, "systemctl", "restart", "carlos-edge.service")
+ b.listening()
+}
+func (b *g2Box) state() g2State {
+ t := b.t
+ rows, err := b.reg.List()
+ g2Must(t, err)
+ state := g2State{IID: b.iid, Ref: metricsBoxLabel(func(k string) string { return b.env[k] }, readMachineID()), Pools: b.env["CARLOS_POOLS"], Rows: rows, TenantPIDs: map[string]string{}, TenantCgroups: map[string]string{}}
+ state.AgentPID = g2Command(t, "systemctl", "show", "carlos-edge.service", "-p", "MainPID", "--value")
+ state.AgentCgroup = g2Command(t, "systemctl", "show", "carlos-edge.service", "-p", "ControlGroup", "--value")
+ for _, rec := range b.config.Records {
+ unit := instancectl.UnitName(instancectl.RoleRun, rec.Host)
+ state.TenantPIDs[rec.Host] = g2Command(t, "systemctl", "show", unit, "-p", "MainPID", "--value")
+ cg := g2Command(t, "systemctl", "show", unit, "-p", "ControlGroup", "--value")
+ if cg != "" {
+ raw, err := os.ReadFile("/sys/fs/cgroup" + cg + "/cgroup.events")
+ if err == nil {
+ state.TenantCgroups[rec.Host] = cg + "\n" + string(raw)
+ }
+ }
+ }
+ paths, _ := filepath.Glob("/data/.ha-owed/*")
+ for _, path := range paths {
+ raw, err := os.ReadFile(path)
+ if err == nil {
+ state.Owed = append(state.Owed, string(raw))
+ }
+ }
+ return state
+}
+func (b *g2Box) cleanup() {
+ // SIGTERM is handled by the peer test; the instance watchdog is the final backstop.
+ for _, unit := range []string{"carlos-instance-control.service", "carlos-edge.service"} {
+ exec.Command("systemctl", "kill", "--signal=CONT", unit).Run()
+ }
+ for _, rec := range b.config.Records {
+ exec.Command("systemctl", "stop", instancectl.UnitName(instancectl.RoleRun, rec.Host)).Run()
+ }
+ for _, unit := range []string{"carlos-edge.service", "carlos-instance-control.socket", "carlos-instance-control.service", "carlos-instance-probe.service"} {
+ exec.Command("systemctl", "stop", unit).Run()
+ }
+ for _, unit := range []string{"carlos-edge.service", "carlos-instance-control.service"} {
+ out, _ := exec.Command("journalctl", "-u", unit, "--no-pager").CombinedOutput()
+ b.t.Logf("journal %s\n%s", unit, out)
+ }
+ if b.reg != nil {
+ b.reg.Close()
+ }
+ if b.audit != nil {
+ b.audit.Close()
+ }
+ for _, unit := range []string{"run-carlos-logs.mount", "run-carlos-instances.mount", "data-instances.mount"} {
+ if out, err := exec.Command("systemctl", "stop", unit).CombinedOutput(); err != nil {
+ b.t.Errorf("cleanup %s: %v %s", unit, err, out)
+ }
+ }
+ for _, rec := range b.config.Records {
+ exec.Command("systemctl", "stop", instancectl.SliceName(rec.Host)).Run()
+ }
+ for _, root := range []string{"/run/systemd/system.control", "/etc/systemd/system.control"} {
+ for _, rec := range b.config.Records {
+ os.RemoveAll(filepath.Join(root, instancectl.SliceName(rec.Host)+".d"))
+ os.RemoveAll(filepath.Join(root, instancectl.UnitName(instancectl.RoleRun, rec.Host)+".d"))
+ }
+ }
+ for _, unit := range b.units {
+ os.Remove(filepath.Join("/run/systemd/system", unit))
+ }
+ exec.Command("systemctl", "daemon-reload").Run()
+}
+
+type g2RPC struct {
+ Action, Value string
+ Config g2Config
+}
+type g2Call struct {
+ request g2RPC
+ result chan any
+}
+
+func TestRootG2Peer(t *testing.T) {
+ _, ip := g2Prereqs(t, "B")
+ calls := make(chan g2Call)
+ stop := make(chan os.Signal, 1)
+ signal.Notify(stop, syscall.SIGTERM, syscall.SIGINT)
+ defer signal.Stop(stop)
+ listener, err := net.Listen("tcp", net.JoinHostPort(ip, "9444"))
+ g2Must(t, err)
+ server := &http.Server{ReadHeaderTimeout: 5 * time.Second, Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if subtle.ConstantTimeCompare([]byte(r.Header.Get("Authorization")), []byte("Bearer "+os.Getenv("G2_TOKEN"))) != 1 {
+ http.Error(w, "denied", 403)
+ return
+ }
+ var req g2RPC
+ if r.Method != "POST" || json.NewDecoder(io.LimitReader(r.Body, 1<<20)).Decode(&req) != nil {
+ http.Error(w, "request", 400)
+ return
+ }
+ call := g2Call{request: req, result: make(chan any, 1)}
+ select {
+ case calls <- call:
+ case <-r.Context().Done():
+ return
+ }
+ select {
+ case result := <-call.result:
+ json.NewEncoder(w).Encode(result)
+ case <-r.Context().Done():
+ return
+ }
+ })}
+ t.Cleanup(func() { server.Close() })
+ go server.Serve(listener)
+ var box *g2Box
+ for {
+ select {
+ case <-stop:
+ return
+ case call := <-calls:
+ switch call.request.Action {
+ case "ready":
+ call.result <- map[string]string{"iid": os.Getenv("G2_B_IID")}
+ case "configure":
+ if box != nil {
+ t.Fatal("already configured")
+ }
+ box = g2NewBox(t, "B", call.request.Config)
+ call.result <- box.state()
+ case "shutdown":
+ call.result <- true
+ return
+ default:
+ if box == nil {
+ t.Fatal("configure first")
+ }
+ switch call.request.Action {
+ case "start":
+ box.start()
+ case "pools":
+ box.pools(call.request.Value)
+ case "freeze":
+ g2Command(t, "systemctl", "kill", "--kill-whom=main", "--signal=STOP", "carlos-edge.service")
+ case "thaw":
+ g2Command(t, "systemctl", "kill", "--kill-whom=main", "--signal=CONT", "carlos-edge.service")
+ case "state":
+ default:
+ t.Fatal("invalid fixture action", call.request.Action)
+ }
+ call.result <- box.state()
+ }
+ }
+ }
+}
+func g2Peer(t *testing.T, req g2RPC) g2State {
+ t.Helper()
+ client := &http.Client{Timeout: 100 * time.Second}
+ request, err := http.NewRequest("POST", "http://"+os.Getenv("G2_B_IP")+":9444/", bytes.NewReader(g2JSON(t, req)))
+ g2Must(t, err)
+ request.Header.Set("Authorization", "Bearer "+os.Getenv("G2_TOKEN"))
+ response, err := client.Do(request)
+ g2Must(t, err)
+ defer response.Body.Close()
+ if response.StatusCode != 200 {
+ t.Fatalf("peer %s: %d", req.Action, response.StatusCode)
+ }
+ var state g2State
+ g2Must(t, json.NewDecoder(response.Body).Decode(&state))
+ return state
+}
+
+type g2S3Event struct {
+ At time.Time
+ AcceptedAt time.Time
+ Method, Path, Source, Owner string
+ Release bool
+ Status int
+}
+type g2EventKey struct{}
+type g2Storage struct {
+ mu sync.Mutex
+ events []g2S3Event
+ blockRelease bool
+ heldPeer string
+ client, direct *s3.Client
+ deploy, data *release.S3Store
+}
+type g2Recorder struct {
+ http.ResponseWriter
+ status int
+}
+
+func (w *g2Recorder) WriteHeader(code int) { w.status = code; w.ResponseWriter.WriteHeader(code) }
+func (s *g2Storage) snapshot() []g2S3Event {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ return slices.Clone(s.events)
+}
+func (s *g2Storage) holdPeer(key string) { s.mu.Lock(); s.heldPeer = key; s.mu.Unlock() }
+func (s *g2Storage) block(value bool) { s.mu.Lock(); s.blockRelease = value; s.mu.Unlock() }
+func g2MinIO(t *testing.T) *g2Storage {
+ t.Helper()
+ _, ip := g2Prereqs(t, "A")
+ dir := filepath.Join(g2Root, "minio-"+os.Getenv("G2_PHASE"))
+ g2Must(t, os.Mkdir(dir, 0700))
+ t.Cleanup(func() { os.RemoveAll(dir) })
+ log, err := os.Create(filepath.Join(dir, "minio.log"))
+ g2Must(t, err)
+ cmd := exec.Command(filepath.Join(g2Root, "minio"), "server", "--address", "127.0.0.1:9001", "--console-address", "127.0.0.1:9002", filepath.Join(dir, "data"))
+ cmd.Env = []string{"PATH=/usr/bin:/bin", "HOME=" + dir, "MINIO_ROOT_USER=" + g2Access, "MINIO_ROOT_PASSWORD=" + g2Secret, "MINIO_BROWSER=off", "MINIO_UPDATE=off"}
+ cmd.Stdout, cmd.Stderr = log, log
+ g2Must(t, cmd.Start())
+ t.Cleanup(func() { cmd.Process.Signal(syscall.SIGTERM); cmd.Wait(); log.Close() })
+ s := &g2Storage{}
+ target, _ := url.Parse("http://127.0.0.1:9001")
+ proxy := httputil.NewSingleHostReverseProxy(target)
+ proxy.ModifyResponse = func(response *http.Response) error {
+ if event, ok := response.Request.Context().Value(g2EventKey{}).(*g2S3Event); ok {
+ event.AcceptedAt = time.Now()
+ }
+ return nil
+ }
+ listener, err := net.Listen("tcp", net.JoinHostPort(ip, "9000"))
+ g2Must(t, err)
+ server := &http.Server{ReadHeaderTimeout: 5 * time.Second, Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ event := g2S3Event{At: time.Now(), Method: r.Method, Path: r.URL.Path}
+ r = r.WithContext(context.WithValue(r.Context(), g2EventKey{}, &event))
+ event.Source, _, _ = net.SplitHostPort(r.RemoteAddr)
+ if r.Method == "PUT" && strings.HasSuffix(r.URL.Path, "/lock.json") {
+ raw, err := io.ReadAll(io.LimitReader(r.Body, 1<<20))
+ if err != nil {
+ http.Error(w, "read", 500)
+ return
+ }
+ r.Body.Close()
+ r.Body = io.NopCloser(bytes.NewReader(raw))
+ var lock hafresh.Lock
+ json.Unmarshal(raw, &lock)
+ event.Owner, event.Release = lock.Owner, lock.Release != nil
+ }
+ s.mu.Lock()
+ blocked := (s.blockRelease && event.Release && event.Source == ip) || (s.heldPeer != "" && r.Method == "PUT" && r.URL.Path == "/"+g2Deploy+"/"+s.heldPeer)
+ s.mu.Unlock()
+ record := &g2Recorder{ResponseWriter: w, status: 200}
+ if blocked {
+ http.Error(record, "fixture release unavailable", 503)
+ } else {
+ proxy.ServeHTTP(record, r)
+ }
+ event.Status = record.status
+ s.mu.Lock()
+ s.events = append(s.events, event)
+ s.mu.Unlock()
+ })}
+ t.Cleanup(func() { server.Close() })
+ go server.Serve(listener)
+ endpoint := "http://" + ip + ":9000"
+ s.client = s3.New(s3.Options{Region: "eu-west-1", Credentials: credentials.NewStaticCredentialsProvider(g2Access, g2Secret, ""), BaseEndpoint: aws.String(endpoint), UsePathStyle: true, RequestChecksumCalculation: aws.RequestChecksumCalculationWhenRequired, ResponseChecksumValidation: aws.ResponseChecksumValidationWhenRequired})
+ s.direct = s3.New(s3.Options{Region: "eu-west-1", Credentials: credentials.NewStaticCredentialsProvider(g2Access, g2Secret, ""), BaseEndpoint: aws.String("http://127.0.0.1:9001"), UsePathStyle: true, RequestChecksumCalculation: aws.RequestChecksumCalculationWhenRequired, ResponseChecksumValidation: aws.ResponseChecksumValidationWhenRequired})
+ g2Wait(t, "MinIO healthy", 30*time.Second, func() bool {
+ r, err := (&http.Client{Timeout: time.Second}).Get("http://127.0.0.1:9001/minio/health/live")
+ if err != nil {
+ return false
+ }
+ r.Body.Close()
+ return r.StatusCode == 200
+ })
+ for _, bucket := range []string{g2Deploy, g2Data} {
+ _, err := s.client.CreateBucket(t.Context(), &s3.CreateBucketInput{Bucket: aws.String(bucket)})
+ g2Must(t, err)
+ }
+ s.deploy = &release.S3Store{Client: s.client, Bucket: g2Deploy}
+ s.data = &release.S3Store{Client: s.client, Bucket: g2Data}
+ return s
+}
+
+// The tenant is the tagged test binary acting only as fixture application code.
+// Agent, activator, edge, instance-exec and root control use the ordinary binary.
+func init() {
+ if len(os.Args) > 1 && (os.Args[1] == "--socket" || os.Args[1] == "--db") {
+ os.Exit(g2Tenant())
+ }
+}
+func g2Tenant() int {
+ fs := flag.NewFlagSet("g2-tenant", flag.ContinueOnError)
+ socket := fs.String("socket", "", "")
+ dbpath := fs.String("db", "", "")
+ args := os.Args[1:]
+ if len(args) > 0 && (args[0] == "serve" || args[0] == "server" || args[0] == "seed") {
+ args = args[1:]
+ }
+ if fs.Parse(args) != nil || *dbpath == "" {
+ return 2
+ }
+ db, err := sql.Open("sqlite", *dbpath)
+ if err != nil {
+ return 3
+ }
+ defer db.Close()
+ if _, err = db.Exec("PRAGMA journal_mode=WAL; CREATE TABLE IF NOT EXISTS deliveries (id TEXT PRIMARY KEY, deliveries INTEGER NOT NULL)"); err != nil {
+ return 4
+ }
+ if *socket == "" {
+ return 0
+ }
+ os.Remove(*socket)
+ ln, err := net.Listen("unix", *socket)
+ if err != nil {
+ return 5
+ }
+ handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if strings.HasPrefix(r.URL.Path, "/api/") {
+ w.Header().Set("Content-Type", "application/json")
+ io.WriteString(w, `{"due":0}`)
+ return
+ }
+ if r.Method == "POST" {
+ raw, err := io.ReadAll(io.LimitReader(r.Body, 4096))
+ if err != nil {
+ http.Error(w, "body", 400)
+ return
+ }
+ if _, err = db.Exec("INSERT INTO deliveries VALUES (?,1) ON CONFLICT(id) DO UPDATE SET deliveries=deliveries+1", string(raw)); err != nil {
+ http.Error(w, err.Error(), 500)
+ return
+ }
+ }
+ rows, err := db.Query("SELECT id,deliveries FROM deliveries ORDER BY id")
+ if err != nil {
+ http.Error(w, err.Error(), 500)
+ return
+ }
+ defer rows.Close()
+ counts := map[string]int{}
+ for rows.Next() {
+ var id string
+ var n int
+ if rows.Scan(&id, &n) != nil {
+ return
+ }
+ counts[id] = n
+ }
+ cg, _ := os.ReadFile("/proc/self/cgroup")
+ json.NewEncoder(w).Encode(map[string]any{"ref": metricsBoxLabel(func(string) string { return "" }, readMachineID()), "pid": os.Getpid(), "cgroup": string(cg), "deliveries": counts})
+ })
+ if err := http.Serve(ln, handler); err != nil {
+ return 6
+ }
+ return 0
+}
+
+func g2Client(t *testing.T, ca string) *http.Client {
+ roots := x509.NewCertPool()
+ if !roots.AppendCertsFromPEM([]byte(ca)) {
+ t.Fatal("fixture CA invalid")
+ }
+ transport := &http.Transport{TLSClientConfig: &tls.Config{RootCAs: roots, MinVersion: tls.VersionTLS12}, DisableKeepAlives: true, DialContext: func(ctx context.Context, network, address string) (net.Conn, error) {
+ return (&net.Dialer{Timeout: 3 * time.Second}).DialContext(ctx, network, net.JoinHostPort(os.Getenv("G2_A_IP"), "443"))
+ }}
+ t.Cleanup(transport.CloseIdleConnections)
+ return &http.Client{Transport: transport, Timeout: 45 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
+}
diff --git a/scripts/region-ha-g2-pool-witness.py b/scripts/region-ha-g2-pool-witness.py
new file mode 100644
index 000000000..9d29407bb
--- /dev/null
+++ b/scripts/region-ha-g2-pool-witness.py
@@ -0,0 +1,510 @@
+#!/usr/bin/env python3
+"""Task 10 controller. Offline by default only when --dry-run is supplied."""
+import argparse
+import datetime as dt
+import hashlib
+import json
+import os
+from pathlib import Path
+import re
+import shlex
+import shutil
+import signal
+import subprocess
+import sys
+import tempfile
+import time
+import urllib.request
+import uuid
+
+PROFILE, REGION, ACCOUNT = "kass", "eu-west-1", "640012953448"
+BUCKET = "carlos-dev-640012953448"
+AMI, SUBNET = "ami-071babd89cea53fa3", "subnet-0975dda9ac0e65347"
+VPC, RUNNER_SG = "vpc-02212d67a9fca3b20", "sg-0c328faf839a02986"
+INSTANCE_PROFILE = "carlos-root-runner"
+MINIO_URL = ("https://github.com/minio/minio/releases/download/RELEASE.2025-09-07T16-13-09Z/"
+ "minio.linux-arm64.RELEASE.2025-09-07T16-13-09Z")
+MINIO_SHA = "5c83cd2cf151717ba0243f73e1c7802ff36e272b67144bdd7f1f7d684fd6f03d"
+PASS = "PASS TestRootG2PoolIngress"
+REQUIRED_CASES = (["signed-hop-ineligible", "concurrent-posts", "eligible-low-headroom",
+ "no-eligible-peer", "host-advertised-wrong-pool"] +
+ [f"{projection}/{shape}" for projection in ("old-row-startup", "row-absent")
+ for shape in ("held", "clean", "unclean", "absent", "alias", "regional")] +
+ ["withdrawal/" + fault for fault in ("clean", "blocked-stop", "pending-release")])
+USER_DATA = """#!/bin/sh
+set -eu
+shutdown -h +85
+install -d -m 700 /var/lib/g2fix-boot
+curl --fail --silent --show-error --location --max-time 180 -o /var/lib/g2fix-boot/ssm.deb https://s3.eu-west-1.amazonaws.com/amazon-ssm-eu-west-1/latest/debian_arm64/amazon-ssm-agent.deb
+dpkg -i /var/lib/g2fix-boot/ssm.deb
+rm /var/lib/g2fix-boot/ssm.deb
+systemctl enable --now amazon-ssm-agent
+"""
+
+
+def digest(path):
+ with open(path, "rb") as f:
+ return hashlib.file_digest(f, "sha256").hexdigest()
+
+
+def command(argv, **kw):
+ return subprocess.run(argv, check=True, text=True, capture_output=True, timeout=900, **kw).stdout.strip()
+
+
+def validate_tip(worktree, expected):
+ if not re.fullmatch(r"[0-9a-f]{40}", expected):
+ raise ValueError("expected-tip must be a full lowercase commit SHA")
+ if command(["git", "rev-parse", "HEAD"], cwd=worktree) != expected:
+ raise ValueError("expected-tip does not match HEAD")
+ if command(["git", "status", "--porcelain", "--untracked-files=normal"], cwd=worktree):
+ raise ValueError("worktree must be clean")
+
+
+def verify_result(result, log, phase):
+ if phase == "mutant":
+ if result["Status"] == "Success" or "G2_POOL_VIOLATION" not in log:
+ raise RuntimeError("mutation must fail the pool assertion, not an infrastructure prerequisite")
+ return
+ missing = [name for name in REQUIRED_CASES if f"CASE {name} PASS" not in log]
+ if (result["Status"] != "Success" or "--- PASS: TestRootG2PoolIngress " not in log or
+ "--- SKIP:" in log or missing):
+ raise RuntimeError(f"{phase} witness did not pass without skips; missing cases: {missing}")
+
+
+def mutant_overlay(worktree, scratch):
+ # An overlay leaves the reviewed checkout byte-identical, including on interruption.
+ source = worktree / "internal/activator/backend_exec.go"
+ before = "return b.ServedPools != nil && b.ServedPools().Serves(rt.Pool)"
+ body = source.read_text()
+ if body.count(before) != 1:
+ raise ValueError("pool mutation anchor changed; inspect the guard before running")
+ replacement = scratch / "backend_exec.go"
+ replacement.write_text(body.replace(before, "return true // G2 witness mutation, never shipped"))
+ overlay = scratch / "overlay.json"
+ overlay.write_text(json.dumps({"Replace": {str(source): str(replacement)}}))
+ return overlay
+
+
+class Run:
+ def __init__(self, args):
+ self.args = args
+ self.run = dt.datetime.now(dt.timezone.utc).strftime("%Y%m%dT%H%M%SZ-") + uuid.uuid4().hex[:10]
+ self.prefix = f"root-runner/g2fix-{self.run}/"
+ self.sg = None
+ self.instances = []
+ self.volumes = []
+ self.enis = []
+ self.deadline = time.monotonic() + 70 * 60
+ self.cleanup_mode = False
+ self.cloud_started = False
+ self.group_attempted = False
+ self.launch_attempts = 0
+ self.evidence = Path(args.evidence_dir).resolve()
+ self.manifest = {"run": self.run, "tip": args.expected_tip, "account": ACCOUNT,
+ "region": REGION, "prefix": self.prefix, "instances": [],
+ "minio_sha256": MINIO_SHA, "checks": [],
+ "usage_bound": {"instance_hours": 3, "gp3_gib_hours": 90,
+ "lifetime_minutes": 90}}
+ self.expires = (dt.datetime.now(dt.timezone.utc) + dt.timedelta(minutes=90)).isoformat()
+
+ def save(self):
+ if not self.args.dry_run:
+ target = self.evidence / "ownership.json"
+ temporary = target.with_suffix(".new")
+ temporary.write_text(json.dumps(self.manifest, indent=2) + "\n")
+ temporary.replace(target)
+
+ def aws(self, *args, allow_missing=False):
+ if not self.cleanup_mode and time.monotonic() > self.deadline:
+ raise TimeoutError("witness time budget exhausted; cleaning up")
+ argv = ["aws", "--profile", PROFILE, "--region", REGION, "--no-cli-pager", *args]
+ if args[:2] != ("s3", "presign"):
+ argv += ["--output", "json"]
+ if self.args.dry_run:
+ print("DRY RUN " + shlex.join(argv))
+ return self.simulated(args)
+ p = subprocess.run(argv, text=True, capture_output=True, timeout=60)
+ with (self.evidence / "aws-calls.jsonl").open("a") as f:
+ # Presigned URLs and SSM parameters contain run-local secrets.
+ f.write(json.dumps({"service": args[0], "operation": args[1], "code": p.returncode,
+ "at": dt.datetime.now(dt.timezone.utc).isoformat()}) + "\n")
+ if p.returncode:
+ if allow_missing and any(code in p.stderr for code in
+ ("InvalidGroup.NotFound", "InvalidVolume.NotFound", "InvalidNetworkInterfaceID.NotFound", "InvocationDoesNotExist")):
+ return None
+ raise RuntimeError(f"AWS {args[0]} {args[1]}: {p.stderr.strip()}")
+ if args[:2] == ("s3", "presign"):
+ return p.stdout.strip()
+ return json.loads(p.stdout) if p.stdout.strip() else {}
+
+ def simulated(self, args):
+ op = args[:2]
+ if op == ("sts", "get-caller-identity"):
+ return {"Account": ACCOUNT}
+ if op == ("ec2", "describe-subnets"):
+ return {"Subnets": [{"SubnetId": SUBNET, "VpcId": VPC}]}
+ if op == ("ec2", "create-security-group"):
+ return {"GroupId": "sg-DRYRUN-owned"}
+ if op == ("ec2", "run-instances"):
+ return {"Instances": [{"InstanceId": f"i-DRYRUN-{len(self.instances)}"}]}
+ if op == ("ec2", "describe-instances"):
+ return {"Reservations": [{"Instances": [
+ {"InstanceId": iid, "State": {"Name": "terminated" if self.cleanup_mode else "running"},
+ "PrivateIpAddress": f"10.0.0.{10+i}", "SubnetId": SUBNET,
+ "Tags": self.tags(), "BlockDeviceMappings": [{"Ebs": {"VolumeId": f"vol-DRYRUN-{i}", "DeleteOnTermination": True}}],
+ "NetworkInterfaces": [{"NetworkInterfaceId": f"eni-DRYRUN-{i}"}]} for i, iid in enumerate(self.instances)]}]}
+ if op == ("ec2", "describe-security-groups"):
+ if "--filters" in args:
+ return {"SecurityGroups": [{"GroupId": self.sg, "VpcId": VPC}]} if self.sg else {"SecurityGroups": []}
+ if self.cleanup_mode:
+ return None
+ return {"SecurityGroups": [{"GroupId": RUNNER_SG, "VpcId": VPC}]}
+ if op in (("ec2", "describe-volumes"), ("ec2", "describe-network-interfaces")):
+ if "--filters" in args:
+ return {"Volumes": [], "NetworkInterfaces": []}
+ return None
+ if op == ("ssm", "describe-instance-information"):
+ return {"InstanceInformationList": [{"PingStatus": "Online"}]}
+ if op == ("ssm", "send-command"):
+ return {"Command": {"CommandId": "DRYRUN-command"}}
+ if op == ("ssm", "get-command-invocation"):
+ return {"Status": "Success", "StandardOutputContent": PASS}
+ if op == ("s3", "presign"):
+ return "https://DRYRUN.invalid/presigned"
+ if op == ("s3api", "list-objects-v2"):
+ return {"Contents": []}
+ return {}
+
+ def tags(self, name=None):
+ values = {"purpose": "g2fix-witness", "g2fix-run": self.run, "expires-at": self.expires}
+ if name:
+ values["Name"] = name
+ return [{"Key": key, "Value": val} for key, val in values.items()]
+
+ def ssm(self, iid, script, label, timeout=900):
+ if iid not in self.instances:
+ raise ValueError("SSM target not owned by this run")
+ cid = self.aws("ssm", "send-command", "--instance-ids", iid,
+ "--document-name", "AWS-RunShellScript", "--timeout-seconds", str(timeout),
+ "--output-s3-bucket-name", BUCKET, "--output-s3-key-prefix", self.prefix + "logs/" + label,
+ "--parameters", json.dumps({"commands": [script], "executionTimeout": [str(timeout)]}))["Command"]["CommandId"]
+ until = time.monotonic() + timeout + 60
+ while time.monotonic() < until:
+ result = self.aws("ssm", "get-command-invocation", "--command-id", cid, "--instance-id", iid, allow_missing=True)
+ if result and result.get("Status") in ("Success", "Failed", "TimedOut", "Cancelled", "Cancelling"):
+ if not self.args.dry_run:
+ (self.evidence / (label + ".json")).write_text(json.dumps(result, indent=2))
+ return result
+ time.sleep(3)
+ raise TimeoutError(f"SSM {label} did not complete")
+
+ def require_ssm(self, iid, script, label, timeout=900):
+ result = self.ssm(iid, script, label, timeout)
+ if result.get("Status") != "Success":
+ raise RuntimeError(f"{label}: {result}")
+ return result
+
+ def full_log(self, label):
+ self.aws("s3", "sync", f"s3://{BUCKET}/{self.prefix}logs/{label}/",
+ str(self.evidence / label), "--only-show-errors")
+ if self.args.dry_run:
+ return ""
+ return "\n".join(p.read_text(errors="replace") for p in (self.evidence / label).rglob("stdout"))
+
+ def launch(self):
+ self.cloud_started = True
+ if self.aws("sts", "get-caller-identity")["Account"] != ACCOUNT:
+ raise ValueError("refusing account mismatch")
+ subnets = self.aws("ec2", "describe-subnets", "--subnet-ids", SUBNET)["Subnets"]
+ if len(subnets) != 1 or subnets[0]["VpcId"] != VPC:
+ raise ValueError("refusing subnet/VPC mismatch")
+ groups = self.aws("ec2", "describe-security-groups", "--group-ids", RUNNER_SG)["SecurityGroups"]
+ if len(groups) != 1 or groups[0]["VpcId"] != VPC:
+ raise ValueError("refusing runner SG/VPC mismatch")
+ # Start the resource lifetime after the local download and builds.
+ self.expires = (dt.datetime.now(dt.timezone.utc) + dt.timedelta(minutes=90)).isoformat()
+ self.manifest["expires_at"] = self.expires
+ self.group_attempted = True
+ self.sg = self.aws("ec2", "create-security-group", "--group-name", "g2fix-" + self.run,
+ "--description", "G2 pool witness private peer traffic", "--vpc-id", VPC,
+ "--tag-specifications", json.dumps([{"ResourceType": "security-group", "Tags": self.tags()}]))["GroupId"]
+ self.manifest["security_group"] = self.sg
+ self.save()
+ self.aws("ec2", "authorize-security-group-ingress", "--group-id", self.sg, "--ip-permissions",
+ json.dumps([{"IpProtocol": "tcp", "FromPort": 1, "ToPort": 65535,
+ "UserIdGroupPairs": [{"GroupId": self.sg}]}]))
+ for role in ("A", "B"):
+ self.launch_attempts += 1
+ expiry = dt.datetime.fromisoformat(self.expires).strftime("%Y-%m-%d %H:%M:%S UTC")
+ user_data = USER_DATA.replace("shutdown -h +85\n", "shutdown -h +85\n" +
+ "systemd-run --unit=g2fix-expiry --on-calendar=" + shlex.quote(expiry) + " /sbin/shutdown -h now\n")
+ result = self.aws("ec2", "run-instances", "--client-token", f"g2fix-{self.run}-{role}",
+ "--image-id", AMI, "--instance-type", "t4g.small", "--count", "1",
+ "--network-interfaces", json.dumps([{"DeviceIndex": 0, "SubnetId": SUBNET,
+ "Groups": [RUNNER_SG, self.sg], "AssociatePublicIpAddress": False, "DeleteOnTermination": True}]),
+ "--iam-instance-profile", f"Name={INSTANCE_PROFILE}",
+ "--instance-initiated-shutdown-behavior", "terminate",
+ "--metadata-options", "HttpTokens=required,HttpEndpoint=enabled",
+ "--block-device-mappings", json.dumps([{"DeviceName": "/dev/xvda", "Ebs": {
+ "VolumeSize": 30, "VolumeType": "gp3", "DeleteOnTermination": True}}]),
+ "--user-data", user_data, "--tag-specifications", json.dumps([
+ {"ResourceType": kind, "Tags": self.tags("g2fix-witness-" + role)}
+ for kind in ("instance", "volume", "network-interface")]))
+ iid = result["Instances"][0]["InstanceId"]
+ self.instances.append(iid)
+ self.manifest["instances"] = self.instances.copy()
+ self.save()
+ print(f"{role}={iid}", flush=True)
+ until = time.monotonic() + 600
+ while not all(i["State"]["Name"] == "running" for i in self.describe_owned()):
+ if time.monotonic() > until:
+ raise TimeoutError("instance running readback timed out")
+ time.sleep(5)
+ instances = self.describe_owned()
+ for instance in instances:
+ if instance.get("PublicIpAddress") or instance["SubnetId"] != SUBNET:
+ raise ValueError("runner has unexpected networking")
+ for mapping in instance["BlockDeviceMappings"]:
+ if not mapping["Ebs"]["DeleteOnTermination"]:
+ raise ValueError("runner volume is not delete-on-termination")
+ self.volumes.append(mapping["Ebs"]["VolumeId"])
+ self.enis.extend(nic["NetworkInterfaceId"] for nic in instance["NetworkInterfaces"])
+ self.manifest.update(volumes=self.volumes, interfaces=self.enis, addresses={i["InstanceId"]: i["PrivateIpAddress"] for i in instances})
+ self.save()
+ for iid in self.instances:
+ until = time.monotonic() + 600
+ while True:
+ online = self.aws("ssm", "describe-instance-information", "--filters", f"Key=InstanceIds,Values={iid}")
+ if any(i["PingStatus"] == "Online" for i in online.get("InstanceInformationList", [])):
+ break
+ if time.monotonic() > until:
+ raise TimeoutError(f"SSM unavailable on {iid}")
+ time.sleep(5)
+
+ def describe_owned(self):
+ result = self.aws("ec2", "describe-instances", "--instance-ids", *self.instances)
+ found = [i for reservation in result["Reservations"] for i in reservation["Instances"]]
+ if {i["InstanceId"] for i in found} != set(self.instances):
+ raise ValueError("incomplete instance readback")
+ for instance in found:
+ tags = {x["Key"]: x["Value"] for x in instance.get("Tags", [])}
+ if tags.get("g2fix-run") != self.run or tags.get("purpose") != "g2fix-witness":
+ raise ValueError("ownership tag mismatch")
+ return found
+
+ def cleanup(self):
+ self.cleanup_mode = True
+ failures = []
+ # Finish cleanup even if another termination signal arrives.
+ for sig in (signal.SIGTERM, signal.SIGINT, signal.SIGHUP):
+ signal.signal(sig, signal.SIG_IGN)
+ # A creation response can be lost after AWS commits it. Recover only
+ # resources carrying this invocation's unguessable run tag.
+ try:
+ for attempt in range(4):
+ result = self.aws("ec2", "describe-instances", "--filters", f"Name=tag:g2fix-run,Values={self.run}",
+ "Name=tag:purpose,Values=g2fix-witness")
+ count = sum(len(r["Instances"]) for r in result.get("Reservations", []))
+ if count >= self.launch_attempts or self.args.dry_run:
+ break
+ time.sleep(5)
+ if count < self.launch_attempts:
+ failures.append(f"LEAKED possible unacknowledged launch for run {self.run}; inventory incomplete")
+ for reservation in result.get("Reservations", []):
+ for instance in reservation["Instances"]:
+ iid = instance["InstanceId"]
+ if iid not in self.instances:
+ self.instances.append(iid)
+ for mapping in instance.get("BlockDeviceMappings", []):
+ volume = mapping["Ebs"]["VolumeId"]
+ if volume not in self.volumes:
+ self.volumes.append(volume)
+ for nic in instance.get("NetworkInterfaces", []):
+ eni = nic["NetworkInterfaceId"]
+ if eni not in self.enis:
+ self.enis.append(eni)
+ groups = self.aws("ec2", "describe-security-groups", "--filters", f"Name=tag:g2fix-run,Values={self.run}",
+ f"Name=vpc-id,Values={VPC}").get("SecurityGroups", [])
+ if self.group_attempted and not self.sg and not groups:
+ failures.append(f"LEAKED possible unacknowledged group creation for run {self.run}")
+ if len(groups) > 1 or (groups and self.sg and groups[0]["GroupId"] != self.sg):
+ raise RuntimeError("unexpected owned security group inventory")
+ if groups:
+ self.sg = groups[0]["GroupId"]
+ volumes = self.aws("ec2", "describe-volumes", "--filters", f"Name=tag:g2fix-run,Values={self.run}")
+ for volume in volumes.get("Volumes", []):
+ if volume["VolumeId"] not in self.volumes:
+ self.volumes.append(volume["VolumeId"])
+ interfaces = self.aws("ec2", "describe-network-interfaces", "--filters", f"Name=tag:g2fix-run,Values={self.run}")
+ for nic in interfaces.get("NetworkInterfaces", []):
+ if nic["NetworkInterfaceId"] not in self.enis:
+ self.enis.append(nic["NetworkInterfaceId"])
+ self.manifest.update(instances=self.instances, volumes=self.volumes, interfaces=self.enis, security_group=self.sg)
+ self.save()
+ except Exception as exc:
+ failures.append(f"LEAKED possible unacknowledged resources for run {self.run}: {exc}")
+ terminated = not self.instances
+ if self.instances:
+ try:
+ self.describe_owned()
+ for attempt in range(5):
+ try:
+ self.aws("ec2", "terminate-instances", "--instance-ids", *self.instances)
+ break
+ except Exception:
+ if attempt == 4:
+ raise
+ time.sleep(3)
+ until = time.monotonic() + 600
+ while True:
+ if all(i["State"]["Name"] == "terminated" for i in self.describe_owned()):
+ terminated = True
+ break
+ if time.monotonic() > until:
+ raise TimeoutError("termination readback timed out")
+ time.sleep(5)
+ except Exception as exc:
+ failures.append(str(exc))
+ for iid in self.instances:
+ print(f"LEAKED {iid}", file=sys.stderr, flush=True)
+ if terminated:
+ for operation, flag, identifiers in (("describe-volumes", "--volume-ids", self.volumes),
+ ("describe-network-interfaces", "--network-interface-ids", self.enis)):
+ for identifier in identifiers:
+ try:
+ until = time.monotonic() + 120
+ while self.aws("ec2", operation, flag, identifier, allow_missing=True) is not None:
+ if time.monotonic() > until:
+ raise RuntimeError("still present")
+ time.sleep(3)
+ except Exception as exc:
+ failures.append(f"LEAKED {identifier}: {exc}")
+ if self.sg:
+ try:
+ self.aws("ec2", "delete-security-group", "--group-id", self.sg)
+ if self.aws("ec2", "describe-security-groups", "--group-ids", self.sg, allow_missing=True) is not None:
+ raise RuntimeError("group still present")
+ except Exception as exc:
+ failures.append(f"LEAKED {self.sg}: {exc}")
+ elif self.sg:
+ failures.append(f"LEAKED {self.sg}: waiting for verified termination")
+ try:
+ self.aws("s3", "sync", f"s3://{BUCKET}/{self.prefix}logs/", str(self.evidence / "logs"), "--only-show-errors")
+ except Exception as exc:
+ failures.append(f"evidence download failed for {self.prefix}: {exc}")
+ try:
+ self.aws("s3", "rm", f"s3://{BUCKET}/{self.prefix}", "--recursive", "--only-show-errors")
+ if self.aws("s3api", "list-objects-v2", "--bucket", BUCKET, "--prefix", self.prefix).get("Contents"):
+ raise RuntimeError("staging prefix is not empty")
+ except Exception as exc:
+ failures.append(f"LEAKED staging prefix {self.prefix}: {exc}")
+ self.manifest["cleanup"] = {"verified": not failures, "failures": failures}
+ self.save()
+ if failures:
+ raise RuntimeError("; ".join(failures))
+ print(("DRY RUN would verify: " if self.args.dry_run else "CLEANUP verified: ") +
+ "instances terminated, disks/interfaces/group absent, staging prefix empty")
+
+ def execute(self, scratch):
+ binaries = {name: scratch / name for name in ("carlos", "carlos-mutant", "g2.test", "minio")}
+ if self.args.dry_run:
+ print(f"LOCAL download {MINIO_URL}; verify sha256={MINIO_SHA} BEFORE build or AWS")
+ print("LOCAL validate clean worktree and expected tip; build linux/arm64 carlos and rootrunner host test")
+ print("LOCAL build carlos-mutant with isolated Go overlay: localHAEligible returns true")
+ hashes = {name: "DRYRUN-sha256" for name in binaries}
+ else:
+ with urllib.request.urlopen(MINIO_URL, timeout=60) as source, binaries["minio"].open("wb") as dest:
+ shutil.copyfileobj(source, dest)
+ if digest(binaries["minio"]) != MINIO_SHA:
+ raise ValueError("MinIO SHA-256 mismatch")
+ worktree = Path(self.args.worktree).resolve()
+ validate_tip(worktree, self.args.expected_tip)
+ env = dict(os.environ, CGO_ENABLED="0", GOOS="linux", GOARCH="arm64")
+ for key in ("GOCACHE", "GOMODCACHE", "GOTMPDIR", "GOFLAGS"):
+ env.pop(key, None)
+ command(["go", "build", "-o", str(binaries["carlos"]), "."], cwd=worktree, env=env)
+ command(["go", "test", "-c", "-tags", "rootrunner", "-o", str(binaries["g2.test"]), "./internal/host"], cwd=worktree, env=env)
+ overlay = mutant_overlay(worktree, scratch)
+ command(["go", "build", "-overlay", str(overlay), "-o", str(binaries["carlos-mutant"]), "."], cwd=worktree, env=env)
+ hashes = {name: digest(path) for name, path in binaries.items()}
+ validate_tip(worktree, self.args.expected_tip)
+ self.manifest["sha256"] = hashes
+ self.save()
+ self.launch()
+ urls = {}
+ for name, path in binaries.items():
+ key = self.prefix + name
+ self.aws("s3", "cp", str(path), f"s3://{BUCKET}/{key}", "--only-show-errors")
+ urls[name] = self.aws("s3", "presign", f"s3://{BUCKET}/{key}", "--expires-in", "5400")
+ for iid in self.instances:
+ script = "set -eu\ninstall -d -m 700 /var/lib/g2fix\ncd /var/lib/g2fix\n"
+ for name, url in urls.items():
+ script += f"curl -fSsL --max-time 180 -o {name} {shlex.quote(url)}\n"
+ script += "printf '%s %s\\n' " + shlex.quote(hashes[name]) + " " + name + " | sha256sum -c -\nchmod 755 " + name + "\n"
+ self.require_ssm(iid, script, "download-" + iid)
+ addresses = self.manifest["addresses"]
+ token = "DRYRUN-token" if self.args.dry_run else uuid.uuid4().hex + uuid.uuid4().hex
+ runner, peer = self.instances
+ # Each pass has fresh services, MinIO data and registries. Only A's platform
+ # binary is mutated; B and the assertions stay byte-identical.
+ for phase in ("baseline", "mutant", "restored"):
+ env = {"G2_RUN": self.run, "G2_A_IID": runner, "G2_B_IID": peer,
+ "G2_A_IP": addresses[runner], "G2_B_IP": addresses[peer],
+ "G2_TOKEN": token, "G2_PHASE": phase, "G2_BINARY": "carlos-mutant" if phase == "mutant" else "carlos"}
+ exports = "\n".join(f"export {k}={shlex.quote(v)}" for k, v in env.items())
+ peer_script = f"set -eu\ncd /var/lib/g2fix\n{exports}\nexport G2_BINARY=carlos\nsystemd-run --unit=g2fix-peer --collect --setenv=G2_RUN=$G2_RUN --setenv=G2_A_IID=$G2_A_IID --setenv=G2_B_IID=$G2_B_IID --setenv=G2_A_IP=$G2_A_IP --setenv=G2_B_IP=$G2_B_IP --setenv=G2_TOKEN=$G2_TOKEN --setenv=G2_PHASE=$G2_PHASE --setenv=G2_BINARY=carlos /var/lib/g2fix/g2.test -test.run=^TestRootG2Peer$ -test.v -test.timeout=18m\n"
+ self.require_ssm(peer, peer_script, phase + "-peer-start")
+ script = f"set -eu\ncd /var/lib/g2fix\n{exports}\n./g2.test -test.run=^TestRootG2PoolIngress$ -test.v -test.count=1 -test.timeout=16m\n"
+ result = self.ssm(runner, script, phase + "-witness", 1000)
+ self.require_ssm(peer, "set -eu\nsystemctl stop g2fix-peer || "
+ "test \"$(systemctl show -p LoadState --value g2fix-peer)\" = not-found\n"
+ "journalctl -u g2fix-peer --no-pager\n"
+ "test ! -e /data\ntest ! -e /opt/carlos\n", phase + "-peer-journal")
+ log = self.full_log(phase + "-witness")
+ peer_log = self.full_log(phase + "-peer-journal")
+ if self.args.dry_run:
+ print(f"ASSERT {phase}: " + ("nonzero exit AND G2_POOL_VIOLATION" if phase == "mutant" else "Success, exact test PASS, all case evidence, no SKIP"))
+ else:
+ # SSM truncates inline output. Read the complete, automatically uploaded log.
+ if "--- PASS: TestRootG2Peer " not in peer_log or "--- FAIL:" in peer_log or "--- SKIP:" in peer_log:
+ raise RuntimeError(f"{phase}: peer fixture or its cleanup failed")
+ verify_result(result, log, phase)
+ self.manifest["checks"].append(phase)
+ self.save()
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--worktree", required=True)
+ parser.add_argument("--evidence-dir", required=True)
+ parser.add_argument("--expected-tip", required=True)
+ parser.add_argument("--dry-run", action="store_true")
+ # No preservation mode: the controller ruling requires cleanup after failure.
+ parser.add_argument("--keep-on-fail", choices=("false",), default="false")
+ args = parser.parse_args()
+ if not re.fullmatch(r"[0-9a-f]{40}", args.expected_tip):
+ parser.error("--expected-tip requires 40 lowercase hex characters")
+ run = Run(args)
+ if not args.dry_run:
+ run.evidence.mkdir(mode=0o700, parents=True, exist_ok=False)
+ def interrupted(signum, frame):
+ raise SystemExit(f"interrupted by {signum}")
+ for sig in (signal.SIGTERM, signal.SIGINT, signal.SIGHUP):
+ signal.signal(sig, interrupted)
+ scratch_root = Path(os.environ.get("TMPDIR", str(Path.home() / ".cache")))
+ if scratch_root == Path("/tmp") or Path("/tmp") in scratch_root.parents:
+ parser.error("scratch must be on disk, not /tmp")
+ scratch_root.mkdir(parents=True, exist_ok=True)
+ with tempfile.TemporaryDirectory(prefix="g2fix-", dir=scratch_root) as directory:
+ try:
+ run.execute(Path(directory))
+ finally:
+ # A bad MinIO pin must make zero AWS calls, including cleanup.
+ if run.cloud_started:
+ run.cleanup()
+ print("DRY RUN ONLY: zero AWS calls, no acceptance claimed" if args.dry_run else PASS)
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/scripts/region_ha_g2_pool_witness_test.py b/scripts/region_ha_g2_pool_witness_test.py
new file mode 100644
index 000000000..1d7cf7057
--- /dev/null
+++ b/scripts/region_ha_g2_pool_witness_test.py
@@ -0,0 +1,109 @@
+import argparse
+import contextlib
+import importlib.util
+import io
+import os
+from pathlib import Path
+import tempfile
+import unittest
+from unittest.mock import patch
+
+spec = importlib.util.spec_from_file_location("g2driver", Path(__file__).with_name("region-ha-g2-pool-witness.py"))
+driver = importlib.util.module_from_spec(spec)
+spec.loader.exec_module(driver)
+
+
+class DriverOfflineTest(unittest.TestCase):
+ def args(self, root):
+ return argparse.Namespace(worktree=str(root), evidence_dir=str(root / "evidence"),
+ expected_tip="a" * 40, dry_run=True, keep_on_fail="false")
+
+ def test_dry_run_never_invokes_process_or_network(self):
+ with tempfile.TemporaryDirectory(dir=os.environ["TMPDIR"]) as directory:
+ root = Path(directory)
+ run = driver.Run(self.args(root))
+ output = io.StringIO()
+ with patch.object(driver.subprocess, "run", side_effect=AssertionError("process in dry run")), \
+ patch.object(driver.urllib.request, "urlopen", side_effect=AssertionError("network in dry run")), \
+ patch.object(driver.signal, "signal"), contextlib.redirect_stdout(output):
+ run.execute(root)
+ run.cleanup()
+ text = output.getvalue()
+ for call in ("run-instances", "terminate-instances", "delete-security-group", "describe-volumes",
+ "describe-network-interfaces", "get-command-invocation", "list-objects-v2"):
+ self.assertIn(call, text)
+ self.assertLess(text.index("verify sha256="), text.index("get-caller-identity"))
+ self.assertEqual(run.manifest["checks"], ["baseline", "mutant", "restored"])
+ self.assertFalse((root / "evidence").exists())
+
+ def test_group_waits_for_terminated_readback(self):
+ with tempfile.TemporaryDirectory(dir=os.environ["TMPDIR"]) as directory:
+ run = driver.Run(self.args(Path(directory)))
+ run.sg = "sg-owned"
+ run.instances = ["i-A", "i-B"]
+ calls = []
+ original = run.aws
+ def failed_termination(*args, **kwargs):
+ calls.append(args[:2])
+ if args[:2] == ("ec2", "terminate-instances"):
+ raise RuntimeError("termination failed")
+ return original(*args, **kwargs)
+ with patch.object(run, "aws", failed_termination), patch.object(driver.time, "sleep"), \
+ patch.object(driver.signal, "signal"), contextlib.redirect_stdout(io.StringIO()), \
+ contextlib.redirect_stderr(io.StringIO()), self.assertRaises(RuntimeError):
+ run.cleanup()
+ self.assertNotIn(("ec2", "delete-security-group"), calls)
+ self.assertFalse(run.manifest["cleanup"]["verified"])
+
+ def test_no_false_cleanup_after_volume_survives(self):
+ with tempfile.TemporaryDirectory(dir=os.environ["TMPDIR"]) as directory:
+ run = driver.Run(self.args(Path(directory)))
+ run.sg = "sg-owned"
+ run.instances = ["i-A"]
+ run.volumes = ["vol-owned"]
+ original = run.aws
+ def bad_volume(*args, **kwargs):
+ if args[:2] == ("ec2", "describe-volumes"):
+ raise RuntimeError("volume not gone")
+ return original(*args, **kwargs)
+ with patch.object(run, "aws", bad_volume), patch.object(driver.signal, "signal"), \
+ contextlib.redirect_stdout(io.StringIO()), self.assertRaises(RuntimeError):
+ run.cleanup()
+ self.assertFalse(run.manifest["cleanup"]["verified"])
+ self.assertIn("vol-owned", " ".join(run.manifest["cleanup"]["failures"]))
+
+ def test_ssm_refuses_unowned_machine(self):
+ run = driver.Run(self.args(Path("/uncreated")))
+ with self.assertRaisesRegex(ValueError, "not owned"):
+ run.ssm("i-dev-box", "true", "bad")
+
+ def test_acceptance_requires_every_case_and_a_specific_mutation_failure(self):
+ complete = "--- PASS: TestRootG2PoolIngress (1.0s)\n" + "\n".join(
+ f"CASE {name} PASS" for name in driver.REQUIRED_CASES)
+ driver.verify_result({"Status": "Success"}, complete, "baseline")
+ for bad in (complete.replace("CASE signed-hop-ineligible PASS", ""), complete + "\n--- SKIP: prerequisite"):
+ with self.assertRaises(RuntimeError):
+ driver.verify_result({"Status": "Success"}, bad, "restored")
+ for status, log in (("Success", "G2_POOL_VIOLATION"), ("Failed", "missing systemd")):
+ with self.assertRaises(RuntimeError):
+ driver.verify_result({"Status": status}, log, "mutant")
+ driver.verify_result({"Status": "Failed"}, "G2_POOL_VIOLATION", "mutant")
+
+ def test_mutation_does_not_edit_source(self):
+ with tempfile.TemporaryDirectory(dir=os.environ["TMPDIR"]) as directory:
+ root = Path(directory)
+ source = root / "internal/activator/backend_exec.go"
+ source.parent.mkdir(parents=True)
+ original = "return b.ServedPools != nil && b.ServedPools().Serves(rt.Pool)"
+ source.write_text(original)
+ overlay = driver.mutant_overlay(root, root)
+ self.assertTrue(overlay.exists())
+ self.assertEqual(source.read_text(), original)
+ self.assertIn("return true", (root / "backend_exec.go").read_text())
+ source.write_text(original + "\n" + original)
+ with self.assertRaisesRegex(ValueError, "anchor changed"):
+ driver.mutant_overlay(root, root)
+
+
+if __name__ == "__main__":
+ unittest.main()