test: witness prompt HA refusals and bounded holder revalidation
Add the offline-built loss witness with real lease timing, scoped MinIO faults, bounded refusal and revalidation assertions, and isolated mutation builds. Share the existing disposable-runner lifecycle with the pool witness.
Co-Authored-By: GPT-6 Astra <noreply@openai.com>
7 files changed,
+1,505
−521
internal/host/region_ha_g2_loss_helpers_test.go+182 −0internal/host/region_ha_g2_loss_root_linux_test.go+568 −0internal/host/region_ha_g2_root_fixture_test.go+42 −5scripts/region-ha-g2-loss-witness.py+96 −0scripts/region-ha-g2-pool-witness.py+2 −516scripts/region_ha_g2_loss_witness_test.py+67 −0scripts/region_ha_g2_witness.py+548 −0
Intent
Human
<task-notification> <task-id>bfn815ebk</task-id> <tool-use-id>toolu_01DDdSFdY64iK5957LjeArYf</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/5555438b-7fa2-408d-b2c4-9fa87ea89332/tasks/bfn815ebk.output</output-file> <status>completed</status> <summary>Background command "Run F-B witness live, run 13" completed (exit code 0)</summary> </task-notification>
diff --git a/internal/host/region_ha_g2_loss_helpers_test.go b/internal/host/region_ha_g2_loss_helpers_test.go| new file mode 100644 |
| index 000000000..d141c5fb5 |
| --- /dev/null |
| +++ b/internal/host/region_ha_g2_loss_helpers_test.go |
| @@ -0,0 +1,182 @@ |
| +//go:build linux && rootrunner |
| + |
| +package host |
| + |
| +import ( |
| + "context" |
| + "database/sql" |
| + "fmt" |
| + "net" |
| + "net/http" |
| + "os" |
| + "os/exec" |
| + "path/filepath" |
| + "strings" |
| + "testing" |
| + "time" |
| +) |
| + |
| +func TestG2LossLatencyAssertion(t *testing.T) { |
| + response := g2Response{Status: 503, Headers: http.Header{"Retry-After": {"10"}, "X-Carlos-Holder": {"none"}}, Body: []byte(g2C1Body), Elapsed: time.Millisecond} |
| + if err := g2LossRefusal(response); err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, mode := range []string{"slow", "body", "status", "holder", "retry"} { |
| + t.Run(mode, func(t *testing.T) { |
| + bad := response |
| + bad.Headers = response.Headers.Clone() |
| + switch mode { |
| + case "slow": |
| + bad.Elapsed = time.Second |
| + case "body": |
| + bad.Body = []byte("wrong") |
| + case "status": |
| + bad.Status = 200 |
| + case "holder": |
| + bad.Headers.Set("X-Carlos-Holder", "somewhere") |
| + case "retry": |
| + bad.Headers.Set("Retry-After", "1") |
| + } |
| + if g2LossRefusal(bad) == nil { |
| + t.Fatal("invalid refusal accepted") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestG2LossFaultScopeAndCancellation(t *testing.T) { |
| + fault := newG2LossFault() |
| + fault.arm("10.0.0.2", "/bucket/instances/host/") |
| + for _, tc := range []struct { |
| + source, path string |
| + blocked bool |
| + }{ |
| + {"10.0.0.2", "/bucket/instances/host/lock.json", true}, |
| + {"10.0.0.1", "/bucket/instances/host/lock.json", false}, |
| + {"10.0.0.2", "/bucket/instances/other/lock.json", false}, |
| + {"10.0.0.2", "/deployment/status/boxes/b.json", false}, |
| + } { |
| + ctx, cancel := context.WithCancel(context.Background()) |
| + cancel() |
| + event := g2S3Event{Source: tc.source, Path: tc.path, Method: "PUT", At: time.Now()} |
| + blocked := fault.wait(ctx, event) |
| + if blocked != tc.blocked { |
| + t.Fatalf("%+v: blocked %t", tc, blocked) |
| + } |
| + } |
| + events := fault.snapshot() |
| + if len(events) != 1 || events[0].CancelledAt.IsZero() { |
| + t.Fatalf("cancellation not recorded: %+v", events) |
| + } |
| + fault.restore() |
| + if fault.wait(context.Background(), g2S3Event{Source: "10.0.0.2", Path: "/bucket/instances/host/lock.json"}) { |
| + t.Fatal("restore left fault armed") |
| + } |
| +} |
| + |
| +func TestG2LossG5Attribution(t *testing.T) { |
| + chain := "goroutine 1 [sync.Mutex.Lock]:\nsync.(*Mutex).lockSlow(\n" + |
| + "github.com/benbjohnson/litestream.(*Replica).Sync(\n" + |
| + "github.com/benbjohnson/litestream.(*DB).SyncAndWait(\n" + |
| + "github.com/carlosframework/platform/internal/lease.(*Replicator).finalize(\n" |
| + if !g2LossG5Stack(chain) { |
| + t.Fatal("real final sync chain not recognized") |
| + } |
| + for _, fragment := range []string{"(*Mutex).lockSlow(", "(*Replica).Sync(", "(*DB).SyncAndWait(", "(*Replicator).finalize("} { |
| + if g2LossG5Stack(strings.ReplaceAll(chain, fragment, "other")) { |
| + t.Fatalf("accepted missing %s", fragment) |
| + } |
| + } |
| + if g2LossG5Stack(strings.ReplaceAll(chain, "github.com/carlosframework", "goroutine 2 [running]:\ngithub.com/carlosframework")) { |
| + t.Fatal("combined unrelated goroutines into G5 evidence") |
| + } |
| +} |
| + |
| +func TestG2LossRequestCensus(t *testing.T) { |
| + now := time.Now() |
| + events := []g2S3Event{ |
| + {At: now, Source: "peer", Method: "GET", Path: "/" + g2Data + "/instances/h/lock.json"}, |
| + {At: now.Add(-time.Second), Source: "peer", Method: "GET", Path: "/" + g2Data + "/instances/h/lock.json"}, |
| + {At: now, Source: "audit", Method: "GET", Path: "/" + g2Data + "/instances/h/lock.json"}, |
| + {At: now, Source: "peer", Method: "PUT", Path: "/" + g2Data + "/instances/h/lock.json"}, |
| + {At: now, Source: "peer", Method: "GET", Path: "/" + g2Data + "/instances/other/lock.json"}, |
| + } |
| + if got := g2LossReads(events, "peer", "h", now); got != 1 { |
| + t.Fatalf("reads=%d", got) |
| + } |
| +} |
| + |
| +func TestG2LossTenantCommitsBeforeSlowHeaders(t *testing.T) { |
| + dir := t.TempDir() |
| + socket, dbpath := filepath.Join(dir, "slow.sock"), filepath.Join(dir, "slow.db") |
| + binary, err := os.Executable() |
| + g2Must(t, err) |
| + cmd := exec.Command(binary, "--db", dbpath, "--socket", socket) |
| + cmd.Dir, cmd.Env = dir, []string{"HOME=" + dir, "PATH=/usr/bin:/bin"} |
| + g2Must(t, cmd.Start()) |
| + t.Cleanup(func() { cmd.Process.Kill(); cmd.Wait() }) |
| + transport := &http.Transport{DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) { |
| + return (&net.Dialer{}).DialContext(ctx, "unix", socket) |
| + }} |
| + t.Cleanup(transport.CloseIdleConnections) |
| + client := &http.Client{Transport: transport, Timeout: 25 * time.Second} |
| + g2Wait(t, "fixture tenant", 10*time.Second, func() bool { |
| + response, err := client.Get("http://tenant/") |
| + if err != nil { |
| + return false |
| + } |
| + response.Body.Close() |
| + return response.StatusCode == 200 |
| + }) |
| + db, err := sql.Open("sqlite", dbpath) |
| + g2Must(t, err) |
| + defer db.Close() |
| + completed := make(chan error, 1) |
| + start := time.Now() |
| + go func() { |
| + response, err := client.Post("http://tenant/slow", "text/plain", strings.NewReader("slow-once")) |
| + if err == nil { |
| + response.Body.Close() |
| + if response.StatusCode != 200 { |
| + err = fmt.Errorf("status %d", response.StatusCode) |
| + } |
| + } |
| + completed <- err |
| + }() |
| + g2Wait(t, "commit before headers", 2*time.Second, func() bool { |
| + var n int |
| + return db.QueryRow("SELECT deliveries FROM deliveries WHERE id='slow-once'").Scan(&n) == nil && n == 1 |
| + }) |
| + ctx, cancel := context.WithTimeout(t.Context(), time.Second) |
| + defer cancel() |
| + request, err := http.NewRequestWithContext(ctx, "POST", "http://tenant/slow", strings.NewReader("cancel-once")) |
| + g2Must(t, err) |
| + response, err := client.Do(request) |
| + if err == nil { |
| + response.Body.Close() |
| + t.Fatal("slow request did not cancel") |
| + } |
| + select { |
| + case err := <-completed: |
| + t.Fatalf("headers arrived early after %s: %v", time.Since(start), err) |
| + default: |
| + } |
| + g2Must(t, <-completed) |
| + if elapsed := time.Since(start); elapsed < 20*time.Second || elapsed > 25*time.Second { |
| + t.Fatalf("slow headers elapsed=%s", elapsed) |
| + } |
| + for _, id := range []string{"slow-once", "cancel-once"} { |
| + var n int |
| + g2Must(t, db.QueryRow("SELECT deliveries FROM deliveries WHERE id=?", id).Scan(&n)) |
| + if n != 1 { |
| + t.Fatalf("id=%s count=%d", id, n) |
| + } |
| + } |
| +} |
| + |
| +func TestG2LossOwedHostScope(t *testing.T) { |
| + raw := `{"Bucket":"g2fix-data","Key":"instances/one/lock.json"}` |
| + if !g2LossOwed([]string{raw}, "one") || g2LossOwed([]string{raw}, "two") || g2LossOwed([]string{"invalid"}, "one") { |
| + t.Fatal("owed host scope mismatch") |
| + } |
| +} |
diff --git a/internal/host/region_ha_g2_loss_root_linux_test.go b/internal/host/region_ha_g2_loss_root_linux_test.go| new file mode 100644 |
| index 000000000..fca39fdf1 |
| --- /dev/null |
| +++ b/internal/host/region_ha_g2_loss_root_linux_test.go |
| @@ -0,0 +1,568 @@ |
| +//go:build linux && rootrunner |
| + |
| +package host |
| + |
| +import ( |
| + "context" |
| + "crypto/hmac" |
| + "crypto/sha256" |
| + "encoding/hex" |
| + "encoding/json" |
| + "fmt" |
| + "io" |
| + "net" |
| + "net/http" |
| + "os" |
| + "slices" |
| + "strconv" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/hafresh" |
| + "github.com/carlosframework/platform/internal/lease" |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +type g2LossFaultEvent struct { |
| + g2S3Event |
| + CancelledAt time.Time |
| + RestoredAt time.Time |
| +} |
| + |
| +type g2LossFault struct { |
| + arrivals []g2S3Event |
| + mu sync.Mutex |
| + source, prefix string |
| + open chan struct{} |
| + events []g2LossFaultEvent |
| +} |
| + |
| +func newG2LossFault() *g2LossFault { return &g2LossFault{} } |
| +func (f *g2LossFault) arm(source, prefix string) { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + if f.open != nil { |
| + panic("fault already armed") |
| + } |
| + f.source, f.prefix, f.open = source, prefix, make(chan struct{}) |
| +} |
| +func (f *g2LossFault) restore() { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + if f.open != nil { |
| + close(f.open) |
| + f.open = nil |
| + } |
| +} |
| +func (f *g2LossFault) snapshot() []g2LossFaultEvent { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + return slices.Clone(f.events) |
| +} |
| +func (f *g2LossFault) wait(ctx context.Context, event g2S3Event) bool { |
| + f.mu.Lock() |
| + f.arrivals = append(f.arrivals, event) |
| + if f.open == nil || event.Source != f.source || !strings.HasPrefix(event.Path, f.prefix) { |
| + f.mu.Unlock() |
| + return false |
| + } |
| + open, index := f.open, len(f.events) |
| + f.events = append(f.events, g2LossFaultEvent{g2S3Event: event}) |
| + f.mu.Unlock() |
| + select { |
| + case <-ctx.Done(): |
| + f.mu.Lock() |
| + f.events[index].CancelledAt = time.Now() |
| + f.mu.Unlock() |
| + return true |
| + case <-open: |
| + f.mu.Lock() |
| + f.events[index].RestoredAt = time.Now() |
| + f.mu.Unlock() |
| + return false |
| + } |
| +} |
| + |
| +func g2LossRefusal(response g2Response) error { |
| + if err := g2C1(response); err != nil { |
| + return fmt.Errorf("G2_LOSS_LATENCY: %w", err) |
| + } |
| + if response.Elapsed >= time.Second { |
| + return fmt.Errorf("G2_LOSS_LATENCY: refusal took %s", response.Elapsed) |
| + } |
| + return nil |
| +} |
| + |
| +func g2LossClient(t *testing.T, ca, ip string) *http.Client { |
| + client := g2Client(t, ca) |
| + transport := client.Transport.(*http.Transport) |
| + transport.DialContext = func(ctx context.Context, network, address string) (net.Conn, error) { |
| + return (&net.Dialer{Timeout: time.Second}).DialContext(ctx, network, net.JoinHostPort(ip, "443")) |
| + } |
| + return client |
| +} |
| +func g2LossRequest(ctx context.Context, client *http.Client, host, path, method, id string) g2Response { |
| + started := time.Now() |
| + request, err := http.NewRequestWithContext(ctx, method, "https://"+host+path, strings.NewReader(id)) |
| + if err != nil { |
| + return g2Response{Err: err} |
| + } |
| + // Avoid the edge's ordinary response cache in every witness observation. |
| + request.Header.Set("Cache-Control", "no-cache") |
| + response, err := client.Do(request) |
| + if err != nil { |
| + return g2Response{Err: err, Elapsed: time.Since(started)} |
| + } |
| + 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, Err: err, Elapsed: time.Since(started)} |
| +} |
| +func g2LossReads(events []g2S3Event, source, host string, since time.Time) int { |
| + count := 0 |
| + for _, event := range events { |
| + if !event.At.Before(since) && event.Source == source && event.Method == "GET" && event.Path == "/"+g2Data+"/instances/"+host+"/lock.json" { |
| + count++ |
| + } |
| + } |
| + return count |
| +} |
| +func g2LossCheck(t *testing.T, client *http.Client, name string) { |
| + t.Helper() |
| + ctx, cancel := context.WithTimeout(t.Context(), 2*time.Second) |
| + defer cancel() |
| + response := g2LossRequest(ctx, client, g2Host, "/", "POST", name) |
| + g2LogResponse(t, name, response) |
| + g2Must(t, g2LossRefusal(response)) |
| +} |
| + |
| +func g2LossSlow(t *testing.T, storage *g2Storage, client, direct *http.Client, ref string) { |
| + t.Helper() |
| + const host = g2AbsentOldHost |
| + g2Served(t, direct, "slow-holder-ready", host, ref, func() {}) |
| + // First forwarding request learns the holder; the next must use that cache. |
| + g2Served(t, client, "slow-ingress-ready", host, ref, func() {}) |
| + since := time.Now() |
| + slow := make(chan g2Response, 1) |
| + go func() { slow <- g2LossRequest(t.Context(), client, host, "/slow", "POST", "slow-post") }() |
| + // At 3 s the production header observer marks suspicion. There are no |
| + // successful responses until the following cancellation has been classified. |
| + time.Sleep(2500 * time.Millisecond) |
| + cancelledCtx, cancel := context.WithTimeout(t.Context(), time.Second) |
| + cancelled := g2LossRequest(cancelledCtx, client, host, "/slow", "POST", "cancel-post") |
| + cancel() |
| + if cancelled.Err == nil || cancelled.Elapsed < 900*time.Millisecond || cancelled.Elapsed > 2*time.Second { |
| + t.Fatalf("client cancellation was not observed at 1 s: %+v", cancelled) |
| + } |
| + g2LogResponse(t, "cancel-at-one-second", cancelled) |
| + // The cancellation arrives after the first request's 3 s silence signal, |
| + // without itself having supplied either a header or a lock reread. |
| + if reads := g2LossReads(storage.snapshot(), os.Getenv("G2_A_IP"), host, since); reads != 0 { |
| + t.Fatalf("unexpected lock read before demand: %d", reads) |
| + } |
| + second := make(chan g2Response, 1) |
| + go func() { second <- g2LossRequest(t.Context(), client, host, "/slow", "GET", "") }() |
| + // A reset by the old cancellation classifier suppresses this immediate |
| + // reread. Do not wait until second's own 3 s timer can hide that defect. |
| + until := time.Now().Add(2 * time.Second) |
| + reads := 0 |
| + for time.Now().Before(until) { |
| + reads = g2LossReads(storage.snapshot(), os.Getenv("G2_A_IP"), host, since) |
| + if reads != 0 { |
| + break |
| + } |
| + time.Sleep(20 * time.Millisecond) |
| + } |
| + if reads != 1 { |
| + t.Fatalf("G2_CANCEL_CONFIRMED: post-cancel demand lock_reads=%d, want 1", reads) |
| + } |
| + t.Logf("CASE cancel-does-not-confirm PASS cancelled=1s window_reads=%d", reads) |
| + // A further silence report within the spent window must not spend again. |
| + time.Sleep(3500 * time.Millisecond) |
| + probe := make(chan g2Response, 1) |
| + go func() { probe <- g2LossRequest(t.Context(), client, host, "/slow", "GET", "") }() |
| + time.Sleep(500 * time.Millisecond) |
| + if reads = g2LossReads(storage.snapshot(), os.Getenv("G2_A_IP"), host, since); reads != 1 { |
| + t.Fatalf("G2_SILENCE_READS: first window made %d reads, want 1", reads) |
| + } |
| + // No response arrives before t=20s. Start a new silent request after the |
| + // t=3s window expires at t=13s, then another demand after its own timer. |
| + if delay := time.Until(since.Add(13500 * time.Millisecond)); delay > 0 { |
| + time.Sleep(delay) |
| + } |
| + next := make(chan g2Response, 1) |
| + go func() { next <- g2LossRequest(t.Context(), client, host, "/slow", "GET", "") }() |
| + time.Sleep(3500 * time.Millisecond) |
| + last := make(chan g2Response, 1) |
| + go func() { last <- g2LossRequest(t.Context(), client, host, "/slow", "GET", "") }() |
| + time.Sleep(500 * time.Millisecond) |
| + reads = g2LossReads(storage.snapshot(), os.Getenv("G2_A_IP"), host, since) |
| + if reads != 2 { |
| + t.Fatalf("G2_SILENCE_READS: two windows made %d reads, want 2", reads) |
| + } |
| + for i, answer := range []<-chan g2Response{slow, second, probe, next, last} { |
| + response := <-answer |
| + g2LogResponse(t, fmt.Sprintf("slow-%d", i), response) |
| + delivery, err := g2ServedDelivery(response, ref) |
| + g2Must(t, err) |
| + if response.Elapsed < 20*time.Second || response.Elapsed > 25*time.Second || delivery.Deliveries["slow-post"] != 1 { |
| + t.Fatalf("G2_SLOW_POST: delay or replay violation: %+v %+v", response, delivery) |
| + } |
| + } |
| + final := g2LossRequest(t.Context(), direct, host, "/", "GET", "") |
| + delivery, err := g2ServedDelivery(final, ref) |
| + g2Must(t, err) |
| + if delivery.Deliveries["slow-post"] != 1 || delivery.Deliveries["cancel-post"] != 1 { |
| + t.Fatalf("unexpected POST counts: %+v", delivery) |
| + } |
| + t.Logf("CASE slow-post-once PASS deliveries=%v refusals=0", delivery.Deliveries) |
| + t.Logf("CASE one-reread-per-window PASS lock_reads=%d", reads) |
| +} |
| + |
| +func TestRootG2LostLeaseResponses(t *testing.T) { |
| + g2Prereqs(t, "A") |
| + g2Wait(t, "peer fixture control", 30*time.Second, func() bool { |
| + request, _ := http.NewRequest("POST", "http://"+os.Getenv("G2_B_IP")+":9444/", strings.NewReader(`{"Action":"ready"}`)) |
| + request.Header.Set("Authorization", "Bearer "+os.Getenv("G2_TOKEN")) |
| + response, err := (&http.Client{Timeout: time.Second}).Do(request) |
| + if err != nil { |
| + return false |
| + } |
| + response.Body.Close() |
| + return response.StatusCode == 200 |
| + }) |
| + fault := newG2LossFault() |
| + storage := g2MinIOWithFault(t, fault) |
| + defer fault.restore() |
| + config, mesh := g2Seed(t, storage) |
| + config.Idle = "30m" |
| + 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())) |
| + t.Logf("S3 fault census %s", g2JSON(t, fault.snapshot())) |
| + g2Peer(t, g2RPC{Action: "thaw-control"}) |
| + // Shutdown returns a boolean, unlike the state RPCs. |
| + request, _ := http.NewRequest("POST", "http://"+os.Getenv("G2_B_IP")+":9444/", strings.NewReader(`{"Action":"shutdown"}`)) |
| + request.Header.Set("Authorization", "Bearer "+os.Getenv("G2_TOKEN")) |
| + response, err := (&http.Client{Timeout: 90 * time.Second}).Do(request) |
| + if err != nil { |
| + t.Error(err) |
| + } else { |
| + response.Body.Close() |
| + } |
| + }) |
| + client := g2LossClient(t, config.CA, os.Getenv("G2_A_IP")) |
| + direct := g2LossClient(t, config.CA, os.Getenv("G2_B_IP")) |
| + b = g2Peer(t, g2RPC{Action: "start"}) |
| + g2Must(t, a.start()) |
| + g2WaitBoxSnapshots(t, storage.deploy, a.state().Ref, b.Ref) |
| + g2Serial(t, storage.deploy) |
| + g2WaitPeer(t, storage.deploy, b.Ref, []string{"ha"}) |
| + if os.Getenv("G2_CASE") != "loss" { |
| + g2LossSlow(t, storage, client, direct, b.Ref) |
| + } |
| + if os.Getenv("G2_CASE") == "slow" { |
| + return |
| + } |
| + g2Served(t, direct, "loss-holder-ready", g2Host, b.Ref, func() {}) |
| + g2Served(t, client, "loss-ingress-ready", g2Host, b.Ref, func() {}) |
| + // Audit reads bypass the fault proxy and never count as production discovery. |
| + audit := &release.S3Store{Client: storage.direct, Bucket: g2Data} |
| + initial := g2Lock(t, audit, g2Host) |
| + t.Logf("INITIAL_LOCK %s", g2JSON(t, initial)) |
| + owner, ok := hafresh.ParseOwner(initial.Lock.Owner) |
| + if !ok || owner.IID != b.IID || initial.Lock.Release != nil { |
| + t.Fatalf("wrong initial holder: %+v", initial) |
| + } |
| + if left := time.Until(initial.Lock.ExpiresAt); left < 14*time.Minute || left > lease.LeaseTTL { |
| + t.Fatalf("production TTL changed: remaining=%s ttl=%s", left, lease.LeaseTTL) |
| + } |
| + // Root control is stopped only after both production isolation verdicts. |
| + // The edge and HTTP peer remain live, so loss must refuse before stop finishes. |
| + cursor := g2Peer(t, g2RPC{Action: "journal-cursor"}).AgentJournal |
| + g2Peer(t, g2RPC{Action: "freeze-control"}) |
| + fault.arm(os.Getenv("G2_B_IP"), "/"+g2Data+"/instances/"+g2Host+"/") |
| + var renewal g2LossFaultEvent |
| + g2Wait(t, "real five-minute renewal cancellation", 6*time.Minute, func() bool { |
| + for _, event := range fault.snapshot() { |
| + if event.Method == "PUT" && strings.HasSuffix(event.Path, "/lock.json") && !event.Release && !event.CancelledAt.IsZero() { |
| + renewal = event |
| + return true |
| + } |
| + } |
| + return false |
| + }) |
| + safeUntil := initial.Lock.ExpiresAt.Add(-lease.RenewMargin) |
| + if elapsed := renewal.CancelledAt.Sub(renewal.At); elapsed > 30*time.Second || elapsed < 29*time.Second || renewal.CancelledAt.After(safeUntil) { |
| + t.Fatalf("renew attempt outside budget: start=%s cancellation=%s elapsed=%s SafeUntil=%s", renewal.At, renewal.CancelledAt, elapsed, safeUntil) |
| + } |
| + acquisition := initial.Lock.ExpiresAt.Add(-lease.LeaseTTL) |
| + if cadence := renewal.At.Sub(acquisition); cadence < 295*time.Second || cadence > 305*time.Second { |
| + t.Fatalf("renew cadence changed: %s", cadence) |
| + } |
| + t.Logf("CASE renewal-budget PASS start=%s cancellation=%s safe_until=%s", renewal.At, renewal.CancelledAt, safeUntil) |
| + g2Wait(t, "holder loss latch in sweep journal", 30*time.Second, func() bool { |
| + journal := g2Peer(t, g2RPC{Action: "journal", Value: cursor}).AgentJournal |
| + return strings.Contains(journal, "LEASE LOST for "+g2Host) |
| + }) |
| + g2LossCheck(t, direct, "direct-loss-refusal") |
| + t.Log("CASE direct-loss-refusal PASS basis=holder-own-latched-loss") |
| + g2LossCheck(t, client, "forwarded-loss-refusal") |
| + t.Log("CASE forwarded-loss-refusal PASS basis=holder-own-C1-not-silence") |
| + state := g2Peer(t, g2RPC{Action: "state"}) |
| + t.Logf("PENDING_STOP %s", g2JSON(t, state)) |
| + if state.TenantPIDs[g2Host] == "0" || !strings.Contains(state.TenantCgroups[g2Host], "populated 1") { |
| + t.Fatal("stop completed before refusal assertion") |
| + } |
| + for range 3 { |
| + g2LossCheck(t, direct, "pending-stop") |
| + } |
| + t.Log("CASE pending-stop-refusal PASS") |
| + since := time.Now() |
| + g2LossCheck(t, client, "cache-drop-discovery") |
| + if g2LossReads(storage.snapshot(), os.Getenv("G2_A_IP"), g2Host, since) != 1 { |
| + t.Fatal("holder-none did not drop cache and rediscover") |
| + } |
| + t.Log("CASE holder-none-cache-drop PASS lock_reads=1") |
| + health := g2LossRequest(t.Context(), direct, g2Host, "/.carlos/lb-health", "GET", "") |
| + g2LogResponse(t, "lb-health", health) |
| + if health.Err != nil || health.Status != 200 { |
| + t.Fatal("LB health changed during lease loss") |
| + } |
| + t.Log("CASE lb-health PASS") |
| + g2Stopped(t, a.state(), g2Host) |
| + if err := g2ZeroAcquire(storage.snapshot(), os.Getenv("G2_A_IP"), g2Host); err != nil { |
| + t.Fatal(err) |
| + } |
| + unchanged := g2Lock(t, audit, g2Host) |
| + if unchanged.ETag != initial.ETag { |
| + t.Fatal("lock changed while holder S3 unavailable") |
| + } |
| + t.Log("CASE no-second-writer PASS") |
| + // With no demand, a latched entry must not start additional discovery. Count |
| + // attempted as well as completed requests, including blocked proxy arrivals. |
| + quietStart := time.Now() |
| + time.Sleep(65 * time.Second) |
| + quietEnd := time.Now() |
| + reads := g2LossReads(storage.snapshot(), os.Getenv("G2_B_IP"), g2Host, quietStart) |
| + for _, event := range fault.snapshot() { |
| + if !event.At.Before(quietStart) && event.Method == "GET" && strings.HasSuffix(event.Path, "/lock.json") { |
| + reads++ |
| + } |
| + } |
| + if reads != 0 { |
| + t.Fatalf("latched host without demand made %d lock reads", reads) |
| + } |
| + quietCalls := 0 |
| + quietWindow := quietStart.Add(60 * time.Second) |
| + for _, event := range storage.snapshot() { |
| + if event.Source == os.Getenv("G2_B_IP") && !event.At.Before(quietWindow) && strings.HasPrefix(event.Path, "/"+g2Data+"/instances/"+g2Host+"/") { |
| + quietCalls++ |
| + } |
| + } |
| + for _, event := range fault.snapshot() { |
| + if !event.At.Before(quietWindow) { |
| + quietCalls++ |
| + } |
| + } |
| + if quietCalls != 0 { |
| + t.Fatalf("latched host made %d S3 calls without demand", quietCalls) |
| + } |
| + t.Logf("NO_DEMAND_STOPPING start=%s demand_expired=%s end=%s discovery_reads=0 s3_calls_after_expiry=0", quietStart, quietWindow, quietEnd) |
| + // Let the real process stop and replication finish, but withhold only |
| + // the marker. This can expose a removed entry with durable release work. |
| + storage.mu.Lock() |
| + storage.releaseSource, storage.blockRelease = os.Getenv("G2_B_IP"), true |
| + storage.mu.Unlock() |
| + fault.restore() |
| + g2Peer(t, g2RPC{Action: "thaw-control"}) |
| + owed := false |
| + cleanupStart := time.Now() |
| + for time.Since(cleanupStart) < 180*time.Second { |
| + state = g2Peer(t, g2RPC{Action: "state"}) |
| + if state.TenantPIDs[g2Host] == "0" && g2LossOwed(state.Owed, g2Host) { |
| + owed = true |
| + break |
| + } |
| + g2LossCheck(t, direct, "cleanup-pending") |
| + time.Sleep(time.Second) |
| + } |
| + if !owed { |
| + g2LossBoundary(t, state) |
| + return |
| + } |
| + t.Logf("PENDING_RELEASE %s", g2JSON(t, state)) |
| + // A discovery GET proves the production gate passed old.stopped and the |
| + // entry-absent check. The marker stays refused, so reacquisition cannot win. |
| + discoveryStart := time.Now() |
| + g2Wait(t, "removed-entry recovery discovery", 60*time.Second, func() bool { |
| + g2LossCheck(t, direct, "removed-entry") |
| + return g2LossReads(storage.snapshot(), os.Getenv("G2_B_IP"), g2Host, discoveryStart) > 0 |
| + }) |
| + g2Stopped(t, g2Peer(t, g2RPC{Action: "state"}), g2Host) |
| + for _, event := range storage.snapshot() { |
| + if event.At.After(renewal.At) && event.Path == "/"+g2Data+"/instances/"+g2Host+"/lock.json" && event.Method == "PUT" && !event.Release { |
| + t.Fatal("second acquire before outstanding release completed") |
| + } |
| + } |
| + t.Log("ENTRY_REMOVAL_WITH_OWED_RELEASE verified: real recovery discovery, C1, zero writer") |
| + storage.block(false) |
| + recovered := false |
| + recoveryStart := time.Now() |
| + var final hafresh.View |
| + for time.Since(recoveryStart) < 60*time.Second { |
| + ctx, cancel := context.WithTimeout(t.Context(), 2*time.Second) |
| + response := g2LossRequest(ctx, direct, g2Host, "/", "POST", "recover") |
| + cancel() |
| + g2LogResponse(t, "recovery", response) |
| + if response.Err == nil && response.Status == 200 { |
| + _, err := g2ServedDelivery(response, b.Ref) |
| + g2Must(t, err) |
| + final = g2Lock(t, audit, g2Host) |
| + if final.Lock.Generation <= initial.Lock.Generation || final.Lock.Release != nil { |
| + t.Fatal("recovery did not conditionally reacquire") |
| + } |
| + recovered = true |
| + break |
| + } |
| + g2Must(t, g2LossRefusal(response)) |
| + time.Sleep(time.Second) |
| + } |
| + if !recovered { |
| + t.Fatal("fresh acquire did not recover within 60 s of demand after cleanup") |
| + } |
| + var marker, acquire time.Time |
| + markerETag := "" |
| + for _, event := range storage.snapshot() { |
| + if event.Source == os.Getenv("G2_B_IP") && event.Path == "/"+g2Data+"/instances/"+g2Host+"/lock.json" && event.Method == "PUT" && event.Status >= 200 && event.Status < 300 && event.At.After(renewal.At) { |
| + if event.Release { |
| + marker = event.AcceptedAt |
| + markerETag = event.ResultETag |
| + } else { |
| + acquire = event.AcceptedAt |
| + if event.IfMatch == "" || strings.Trim(event.IfMatch, "\"") != strings.Trim(markerETag, "\"") { |
| + t.Fatal("acquire did not use marker ETag") |
| + } |
| + } |
| + } |
| + } |
| + if marker.IsZero() || acquire.IsZero() || !acquire.After(marker) { |
| + t.Fatal("recovery lacks release-before-acquire evidence") |
| + } |
| + t.Logf("CASE recovery-or-g5-boundary PASS recovered=true release=%s acquire=%s lock=%s", marker, acquire, g2JSON(t, final)) |
| + g2LossNoDemand(t, storage, audit, a, b, client, direct, mesh) |
| + |
| +} |
| + |
| +func g2LossG5Stack(journal string) bool { |
| + // Require the final-sync chain and mutex wait in one goroutine, not an |
| + // unrelated periodic sync elsewhere in the dump. |
| + for _, stack := range strings.Split(journal, "goroutine ") { |
| + if strings.Contains(stack, "(*Replica).Sync(") && strings.Contains(stack, "(*DB).SyncAndWait(") && |
| + strings.Contains(stack, "(*Replicator).finalize(") && |
| + (strings.Contains(stack, "(*Mutex).Lock(") || strings.Contains(stack, "(*Mutex).lockSlow(")) { |
| + return true |
| + } |
| + } |
| + return false |
| +} |
| + |
| +func g2LossBoundary(t *testing.T, state g2State) { |
| + t.Helper() |
| + t.Logf("RECOVERY_PENDING %s", g2JSON(t, state)) |
| + if state.TenantPIDs[g2Host] != "0" { |
| + t.Fatal("cleanup blocked outside final sync: tenant still running") |
| + } |
| + // All live refusals have passed. SIGQUIT captures real stacks and ends this |
| + // disposable agent; no recovery is claimed after that diagnostic. |
| + stacks := g2Peer(t, g2RPC{Action: "diagnose-stalled-sync"}).AgentJournal |
| + t.Logf("RECOVERY_STACKS %s", stacks) |
| + if !g2LossG5Stack(stacks) { |
| + t.Fatal("stalled cleanup without proven G5 sync boundary") |
| + } |
| + t.Log("BLOCKED-BY-G5: final sync waits on litestream sync mutex; recovery not proved") |
| + t.Log("CASE recovery-or-g5-boundary PASS recovered=false boundary=BLOCKED-BY-G5") |
| + t.Log("CASE no-demand-no-s3 PASS scope=stopping-only completed-stop-boundary=BLOCKED-BY-G5") |
| +} |
| + |
| +func g2LossOwed(raw []string, host string) bool { |
| + for _, data := range raw { |
| + var obligation lease.Obligation |
| + if json.Unmarshal([]byte(data), &obligation) == nil && obligation.Bucket == g2Data && obligation.Key == "instances/"+host+"/lock.json" { |
| + return true |
| + } |
| + } |
| + return false |
| +} |
| + |
| +func g2LossNoDemand(t *testing.T, storage *g2Storage, audit release.Store, a *g2Box, b g2State, ingress, direct *http.Client, mesh []byte) { |
| + t.Helper() |
| + // Establish a second loss using the real pause detector, then let the real |
| + // stop finish. The new A holder acquires only B's actual release marker. |
| + g2Peer(t, g2RPC{Action: "freeze"}) |
| + time.Sleep(35 * time.Second) |
| + g2Peer(t, g2RPC{Action: "thaw"}) |
| + // The sweep latches this loss without demand. A request here could |
| + // legitimately schedule B to reacquire before A obtains the marker. |
| + var released hafresh.View |
| + g2Wait(t, "real pause-loss release", 60*time.Second, func() bool { |
| + released = g2Lock(t, audit, g2Host) |
| + return !released.Absent && released.Lock.Release != nil && released.Lock.Release.IID == b.IID |
| + }) |
| + g2Stopped(t, g2Peer(t, g2RPC{Action: "state"}), g2Host) |
| + g2Must(t, a.pools("ha")) |
| + g2Must(t, a.isolationReady("no-demand/new-holder")) |
| + timestamp := strconv.FormatInt(time.Now().Unix(), 10) |
| + mac := hmac.New(sha256.New, mesh) |
| + mac.Write([]byte(g2Host + "\n" + timestamp)) |
| + hop := timestamp + ":" + hex.EncodeToString(mac.Sum(nil)) |
| + self := a.state().Ref |
| + g2Outcome(t, ingress, "new-holder-after-marker", g2Host, "GET", "", hop, func(response g2Response) error { |
| + _, err := g2ServedDelivery(response, self) |
| + return err |
| + }, func() { g2Stopped(t, g2Peer(t, g2RPC{Action: "state"}), g2Host) }) |
| + acquired := g2Lock(t, audit, g2Host) |
| + owner, ok := hafresh.ParseOwner(acquired.Lock.Owner) |
| + if !ok || owner.IID != a.iid || acquired.Lock.Generation <= released.Lock.Generation || acquired.Lock.Release != nil { |
| + t.Fatal("foreign holder lacks new lease") |
| + } |
| + matched := false |
| + for _, event := range storage.snapshot() { |
| + if event.Source == os.Getenv("G2_A_IP") && event.Path == "/"+g2Data+"/instances/"+g2Host+"/lock.json" && event.Method == "PUT" && event.Status == 200 && strings.Trim(event.IfMatch, "\"") == strings.Trim(released.ETag, "\"") { |
| + matched = true |
| + } |
| + } |
| + if !matched { |
| + t.Fatal("foreign acquisition did not condition on B's release marker") |
| + } |
| + // One request provides demand. The latched B host discovers the real A |
| + // lease and then must make no more per-host S3 calls without another request. |
| + start := time.Now() |
| + g2LossCheck(t, direct, "foreign-discovery-demand") |
| + t.Log("FROZEN_HOLDER_REFUSAL basis=holder-own-C1-after-pause-loss-and-resume") |
| + g2Wait(t, "first foreign discovery", 5*time.Second, func() bool { |
| + return g2LossReads(storage.snapshot(), os.Getenv("G2_B_IP"), g2Host, start) > 0 |
| + }) |
| + // The observer records completion after proxying the response. Allow its |
| + // worker to consume that response; do not send another tenant request. |
| + time.Sleep(250 * time.Millisecond) |
| + quiet := time.Now() |
| + time.Sleep(65 * time.Second) |
| + attempts := 0 |
| + storage.loss.mu.Lock() |
| + arrivals := slices.Clone(storage.loss.arrivals) |
| + storage.loss.mu.Unlock() |
| + for _, event := range arrivals { |
| + if event.Source == os.Getenv("G2_B_IP") && !event.At.Before(quiet) && strings.HasPrefix(event.Path, "/"+g2Data+"/instances/"+g2Host+"/") { |
| + attempts++ |
| + } |
| + } |
| + reads := g2LossReads(storage.snapshot(), os.Getenv("G2_B_IP"), g2Host, start) |
| + if attempts != 0 || reads != 1 { |
| + t.Fatalf("no-demand foreign holder: first_attempt_reads=%d later_s3_calls=%d", reads, attempts) |
| + } |
| + t.Logf("CASE no-demand-no-s3 PASS scope=completed-stop first_attempt_reads=%d later_s3_calls=%d window=65s", reads, attempts) |
| + g2Served(t, direct, "foreign-holder-http-recovery", g2Host, self, func() { g2Stopped(t, g2Peer(t, g2RPC{Action: "state"}), g2Host) }) |
| +} |
diff --git a/internal/host/region_ha_g2_root_fixture_test.go b/internal/host/region_ha_g2_root_fixture_test.go| index 06884dc0c..37d012b88 100644 |
| --- a/internal/host/region_ha_g2_root_fixture_test.go |
| +++ b/internal/host/region_ha_g2_root_fixture_test.go |
| @@ -71,6 +71,7 @@ const ( |
| ) |
| type g2Config struct { |
| + Idle string |
| Certificate, CertificateKey, CA, SecretsKey, ReleasePub string |
| Records []provision.Record |
| } |
| @@ -361,7 +362,7 @@ func g2ConfigureBox(t testing.TB, role string, config g2Config, iid, ip string, |
| 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" { |
| + if binary != "carlos" && binary != "carlos-mutant" && binary != "carlos-stop-mutant" && binary != "carlos-cancel-mutant" { |
| t.Fatal("invalid branch binary") |
| } |
| image, err := os.ReadFile(filepath.Join(g2Root, binary)) |
| @@ -378,6 +379,9 @@ func g2ConfigureBox(t testing.TB, role string, config g2Config, iid, ip string, |
| "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 config.Idle != "" { |
| + b.env["CARLOS_HIBERNATE_IDLE"] = config.Idle |
| + } |
| if role == "B" { |
| b.env["CARLOS_POOLS"] = "ha" |
| } |
| @@ -762,6 +766,10 @@ func TestRootG2Peer(t *testing.T) { |
| isolationErr = box.start() |
| case "pools": |
| isolationErr = box.pools(call.request.Value) |
| + case "freeze-control": |
| + g2Command(scope, "systemctl", "kill", "--kill-whom=main", "--signal=STOP", "carlos-instance-control.service") |
| + case "thaw-control": |
| + g2Command(scope, "systemctl", "kill", "--kill-whom=main", "--signal=CONT", "carlos-instance-control.service") |
| case "freeze": |
| g2Command(scope, "systemctl", "kill", "--kill-whom=main", "--signal=STOP", "carlos-edge.service") |
| case "thaw": |
| @@ -780,6 +788,17 @@ func TestRootG2Peer(t *testing.T) { |
| state := box.state() |
| state.AgentJournal = g2Command(scope, "journalctl", "-u", "carlos-edge.service", "--no-pager", "-n", "2000", arg) |
| return state |
| + case "diagnose-stalled-sync": |
| + if box.config.Idle != "30m" { |
| + scope.Fatal("loss witness only") |
| + } |
| + g2Command(scope, "systemctl", "kill", "--kill-whom=main", "--signal=QUIT", "carlos-edge.service") |
| + g2Wait(scope, "agent stack dump", 10*time.Second, func() bool { |
| + return g2Command(scope, "systemctl", "show", "carlos-edge.service", "-p", "MainPID", "--value") == "0" |
| + }) |
| + state := box.state() |
| + state.AgentJournal = g2Command(scope, "journalctl", "-u", "carlos-edge.service", "--no-pager", "-n", "30000") |
| + return state |
| case "state": |
| default: |
| scope.Fatal("invalid fixture action ", call.request.Action) |
| @@ -828,14 +847,18 @@ func g2Peer(t *testing.T, req g2RPC) g2State { |
| } |
| type g2S3Event struct { |
| + ResultETag string |
| At time.Time |
| AcceptedAt time.Time |
| Method, Path, Source, Owner string |
| + IfMatch, IfNoneMatch string |
| Release bool |
| Status int |
| } |
| type g2EventKey struct{} |
| type g2Storage struct { |
| + releaseSource string |
| + loss *g2LossFault |
| mu sync.Mutex |
| events []g2S3Event |
| blockRelease bool |
| @@ -856,7 +879,8 @@ func (s *g2Storage) snapshot() []g2S3Event { |
| } |
| 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 { |
| +func g2MinIO(t *testing.T) *g2Storage { return g2MinIOWithFault(t, nil) } |
| +func g2MinIOWithFault(t *testing.T, loss *g2LossFault) *g2Storage { |
| t.Helper() |
| _, ip := g2Prereqs(t, "A") |
| dir := filepath.Join(g2Root, "minio-"+os.Getenv("G2_PHASE")) |
| @@ -869,19 +893,20 @@ func g2MinIO(t *testing.T) *g2Storage { |
| cmd.Stdout, cmd.Stderr = log, log |
| g2Must(t, cmd.Start()) |
| t.Cleanup(func() { cmd.Process.Signal(syscall.SIGTERM); cmd.Wait(); log.Close() }) |
| - s := &g2Storage{} |
| + s := &g2Storage{loss: loss} |
| 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() |
| + event.ResultETag = response.Header.Get("ETag") |
| } |
| 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} |
| + event := g2S3Event{At: time.Now(), Method: r.Method, Path: r.URL.Path, IfMatch: r.Header.Get("If-Match"), IfNoneMatch: r.Header.Get("If-None-Match")} |
| 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") { |
| @@ -896,8 +921,15 @@ func g2MinIO(t *testing.T) *g2Storage { |
| json.Unmarshal(raw, &lock) |
| event.Owner, event.Release = lock.Owner, lock.Release != nil |
| } |
| + if s.loss != nil && s.loss.wait(r.Context(), event) { |
| + return |
| + } |
| s.mu.Lock() |
| - blocked := (s.blockRelease && event.Release && event.Source == ip) || (s.heldPeer != "" && r.Method == "PUT" && r.URL.Path == "/"+g2Deploy+"/"+s.heldPeer) |
| + releaseSource := s.releaseSource |
| + if releaseSource == "" { |
| + releaseSource = ip |
| + } |
| + blocked := (s.blockRelease && event.Release && event.Source == releaseSource) || (s.heldPeer != "" && r.Method == "PUT" && r.URL.Path == "/"+g2Deploy+"/"+s.heldPeer) |
| s.mu.Unlock() |
| record := &g2Recorder{ResponseWriter: w, status: 200} |
| if blocked { |
| @@ -968,6 +1000,7 @@ func g2Tenant() int { |
| return 5 |
| } |
| handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + w.Header().Set("Cache-Control", "no-store") |
| if strings.HasPrefix(r.URL.Path, "/api/") { |
| w.Header().Set("Content-Type", "application/json") |
| io.WriteString(w, `{"due":0}`) |
| @@ -984,6 +1017,10 @@ func g2Tenant() int { |
| return |
| } |
| } |
| + // Fixture-only delay: commit first, then withhold final headers. |
| + if r.URL.Path == "/slow" { |
| + time.Sleep(20 * time.Second) |
| + } |
| rows, err := db.Query("SELECT id,deliveries FROM deliveries ORDER BY id") |
| if err != nil { |
| http.Error(w, err.Error(), 500) |
diff --git a/scripts/region-ha-g2-loss-witness.py b/scripts/region-ha-g2-loss-witness.py| new file mode 100755 |
| index 000000000..7b4382007 |
| --- /dev/null |
| +++ b/scripts/region-ha-g2-loss-witness.py |
| @@ -0,0 +1,96 @@ |
| +#!/usr/bin/env python3 |
| +"""Task 11 controller; --dry-run makes zero AWS calls.""" |
| +import json |
| +import sys |
| + |
| +import region_ha_g2_witness as shared |
| + |
| +PASS = "PASS TestRootG2LostLeaseResponses" |
| +REQUIRED_CASES = ("slow-post-once", "cancel-does-not-confirm", "one-reread-per-window", |
| + "renewal-budget", "direct-loss-refusal", "forwarded-loss-refusal", |
| + "holder-none-cache-drop", "pending-stop-refusal", "no-second-writer", |
| + "no-demand-no-s3", "recovery-or-g5-boundary", "lb-health") |
| +MUTATION_FAILURES = {"mutant-stop": "G2_LOSS_LATENCY", "mutant-cancel": "G2_CANCEL_CONFIRMED"} |
| + |
| + |
| +def verify_result(result, log, phase): |
| + shared.verify_environment(log) |
| + if phase in MUTATION_FAILURES: |
| + if result["Status"] != "Failed" or MUTATION_FAILURES[phase] not in log or "--- SKIP:" in log: |
| + raise RuntimeError("mutation did not fail its specific assertion: " + phase) |
| + return |
| + missing = [name for name in REQUIRED_CASES if f"CASE {name} PASS" not in log] |
| + if result["Status"] != "Success" or "--- PASS: TestRootG2LostLeaseResponses " not in log or "--- SKIP:" in log or missing: |
| + raise RuntimeError(f"{phase} did not pass without skips; missing cases: {missing}") |
| + |
| + |
| +def replace_once(body, before, after): |
| + if body.count(before) != 1: |
| + raise ValueError("loss mutation anchor changed; inspect before running") |
| + return body.replace(before, after) |
| + |
| + |
| +def mutant_overlays(worktree, scratch): |
| + variants = {} |
| + for name in ("stop", "cancel"): |
| + directory = scratch / name |
| + directory.mkdir() |
| + replacements = {} |
| + if name == "stop": |
| + files = { |
| + "internal/activator/haleaseloss.go": [( |
| + "func (a *Service) haLeaseRefusalLocked(rt registry.Route) error {", |
| + "func (a *Service) haLeaseRefusalLocked(rt registry.Route) error {\nreturn nil // witness mutation")], |
| + "internal/activator/activator.go": [], |
| + } |
| + else: |
| + files = { |
| + "internal/edge/forwardha.go": [("res.Outcome = ForwardCanceled", "res.Outcome = ForwardDone")], |
| + "internal/activator/hacache.go": [( |
| + 'case res.Status != 0 && res.Ref != "":', 'case res.Ref != "":')], |
| + } |
| + for relative, changes in files.items(): |
| + source = worktree / relative |
| + body = source.read_text() |
| + for before, after in changes: |
| + body = replace_once(body, before, after) |
| + if relative.endswith("/activator.go"): |
| + anchor = "refused := e.haRefused" |
| + if body.count(anchor) != 1: |
| + raise ValueError("stopping-wait mutation anchor changed") |
| + body = body.replace(anchor, "var refused <-chan struct{} // old stop wait") |
| + if relative.endswith("/hacache.go"): |
| + anchor = ' || (res.Holder == "" && res.Status == 0)' |
| + if body.count(anchor) != 2: |
| + raise ValueError("cancellation mutation anchor changed") |
| + body = body.replace(anchor, "") |
| + target = directory / source.name |
| + target.write_text(body) |
| + replacements[str(source)] = str(target) |
| + overlay = directory / "overlay.json" |
| + overlay.write_text(json.dumps({"Replace": replacements})) |
| + variants[f"carlos-{name}-mutant"] = overlay |
| + return variants |
| + |
| + |
| +class Run(shared.Run): |
| + test_name = "TestRootG2LostLeaseResponses" |
| + pass_line = PASS |
| + work_minutes = 45 |
| + witness_timeout = 900 |
| + peer_minutes = 17 |
| + test_minutes = 14 |
| + mutation_names = ("carlos-stop-mutant", "carlos-cancel-mutant") |
| + mutation_failures = MUTATION_FAILURES |
| + phases = (("baseline", "carlos", "all"), ("mutant-stop", "carlos-stop-mutant", "loss"), |
| + ("mutant-cancel", "carlos-cancel-mutant", "slow"), ("restored", "carlos", "all")) |
| + |
| + def build_mutants(self, worktree, scratch): |
| + return mutant_overlays(worktree, scratch) |
| + |
| + def verify(self, result, log, phase): |
| + verify_result(result, log, phase) |
| + |
| + |
| +if __name__ == "__main__": |
| + sys.exit(shared.main(Run)) |
diff --git a/scripts/region-ha-g2-pool-witness.py b/scripts/region-ha-g2-pool-witness.py| index 0dafb0fc8..07c04dff2 100644 |
| --- a/scripts/region-ha-g2-pool-witness.py |
| +++ b/scripts/region-ha-g2-pool-witness.py |
| @@ -1,520 +1,6 @@ |
| #!/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" |
| -ENVIRONMENT_NOT_READY = "G2_ENVIRONMENT_NOT_READY" |
| -FIXTURE_ERROR = "G2_FIXTURE_ERROR" |
| -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", "absent-leftover", "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_environment(log): |
| - failures = [line for line in log.splitlines() if ENVIRONMENT_NOT_READY in line or FIXTURE_ERROR in line] |
| - if failures: |
| - raise RuntimeError("\n".join(failures)) |
| - |
| - |
| -def verify_result(result, log, phase): |
| - verify_environment(log) |
| - 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}", "PublicIpAddress": f"203.0.113.{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": True, "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 not 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. |
| - verify_environment(log + "\n" + peer_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 |
| - |
| +"""Task 10 controller; --dry-run makes zero AWS calls.""" |
| +from region_ha_g2_witness import * |
| if __name__ == "__main__": |
| sys.exit(main()) |
diff --git a/scripts/region_ha_g2_loss_witness_test.py b/scripts/region_ha_g2_loss_witness_test.py| new file mode 100644 |
| index 000000000..8ade42328 |
| --- /dev/null |
| +++ b/scripts/region_ha_g2_loss_witness_test.py |
| @@ -0,0 +1,67 @@ |
| +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("g2loss", Path(__file__).with_name("region-ha-g2-loss-witness.py")) |
| +driver = importlib.util.module_from_spec(spec) |
| +spec.loader.exec_module(driver) |
| + |
| + |
| +class LossDriverTest(unittest.TestCase): |
| + def test_dry_run_has_no_process_or_network(self): |
| + with tempfile.TemporaryDirectory(dir=os.environ["TMPDIR"]) as directory: |
| + root = Path(directory) |
| + args = argparse.Namespace(worktree=str(root), evidence_dir=str(root / "evidence"), |
| + expected_tip="a" * 40, dry_run=True, keep_on_fail="false") |
| + run = driver.Run(args) |
| + with patch.object(driver.shared.subprocess, "run", side_effect=AssertionError("process")), \ |
| + patch.object(driver.shared.urllib.request, "urlopen", side_effect=AssertionError("network")), \ |
| + patch.object(driver.shared.signal, "signal"), contextlib.redirect_stdout(io.StringIO()) as output: |
| + run.execute(root) |
| + run.cleanup() |
| + self.assertEqual(run.manifest["checks"], ["baseline", "mutant-stop", "mutant-cancel", "restored"]) |
| + self.assertLessEqual(run.work_minutes, 45) |
| + self.assertIn("TestRootG2LostLeaseResponses", output.getvalue()) |
| + self.assertIn("terminate-instances", output.getvalue()) |
| + self.assertFalse((root / "evidence").exists()) |
| + |
| + def test_result_requires_all_cases(self): |
| + log = "--- PASS: TestRootG2LostLeaseResponses (1.0s)\n" + "\n".join( |
| + f"CASE {case} PASS" for case in driver.REQUIRED_CASES) |
| + for phase in ("baseline", "restored"): |
| + driver.verify_result({"Status": "Success"}, log, phase) |
| + for case in driver.REQUIRED_CASES: |
| + with self.subTest(case=case), self.assertRaises(RuntimeError): |
| + driver.verify_result({"Status": "Success"}, log.replace(f"CASE {case} PASS", ""), phase) |
| + with self.assertRaises(RuntimeError): |
| + driver.verify_result({"Status": "Success"}, log + "\n--- SKIP: missing", phase) |
| + for phase, code in driver.MUTATION_FAILURES.items(): |
| + driver.verify_result({"Status": "Failed"}, code, phase) |
| + for bad in ("missing prerequisite", "G2_FIXTURE_ERROR " + code, "G2_ENVIRONMENT_NOT_READY " + code): |
| + with self.assertRaises(RuntimeError): |
| + driver.verify_result({"Status": "Failed"}, bad, phase) |
| + with self.assertRaises(RuntimeError): |
| + driver.verify_result({"Status": "Success"}, code, phase) |
| + |
| + def test_mutations_are_isolated_and_anchors_fail_closed(self): |
| + worktree = Path(__file__).resolve().parents[1] |
| + with tempfile.TemporaryDirectory(dir=os.environ["TMPDIR"]) as directory: |
| + overlays = driver.mutant_overlays(worktree, Path(directory)) |
| + self.assertEqual(set(overlays), {"carlos-stop-mutant", "carlos-cancel-mutant"}) |
| + import json |
| + for overlay in overlays.values(): |
| + replacements = json.loads(overlay.read_text())["Replace"] |
| + for source, replacement in replacements.items(): |
| + self.assertNotEqual(Path(source).read_text(), Path(replacement).read_text()) |
| + with self.assertRaises(ValueError): |
| + driver.replace_once("missing", "anchor", "replacement") |
| + |
| + |
| +if __name__ == "__main__": |
| + unittest.main() |
diff --git a/scripts/region_ha_g2_witness.py b/scripts/region_ha_g2_witness.py| new file mode 100644 |
| index 000000000..6b4f7cd99 |
| --- /dev/null |
| +++ b/scripts/region_ha_g2_witness.py |
| @@ -0,0 +1,548 @@ |
| +#!/usr/bin/env python3 |
| +"""Shared disposable-runner lifecycle for the G2 witnesses.""" |
| +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" |
| +ENVIRONMENT_NOT_READY = "G2_ENVIRONMENT_NOT_READY" |
| +FIXTURE_ERROR = "G2_FIXTURE_ERROR" |
| +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", "absent-leftover", "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_environment(log): |
| + failures = [line for line in log.splitlines() if ENVIRONMENT_NOT_READY in line or FIXTURE_ERROR in line] |
| + if failures: |
| + raise RuntimeError("\n".join(failures)) |
| + |
| + |
| +def verify_result(result, log, phase): |
| + verify_environment(log) |
| + 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: |
| + test_name = "TestRootG2PoolIngress" |
| + pass_line = PASS |
| + work_minutes = 70 |
| + witness_timeout = 1000 |
| + peer_minutes = 18 |
| + test_minutes = 16 |
| + phases = (("baseline", "carlos", "all"), ("mutant", "carlos-mutant", "all"), |
| + ("restored", "carlos", "all")) |
| + mutation_names = ("carlos-mutant",) |
| + mutation_failures = {"mutant": "G2_POOL_VIOLATION"} |
| + |
| + def build_mutants(self, worktree, scratch): |
| + return {"carlos-mutant": mutant_overlay(worktree, scratch)} |
| + |
| + def verify(self, result, log, phase): |
| + verify_result(result, log, phase) |
| + |
| + 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() + self.work_minutes * 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}", "PublicIpAddress": f"203.0.113.{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.deadline = time.monotonic() + self.work_minutes * 60 |
| + 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": True, "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 not 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", "g2.test", "minio", *self.mutation_names)} |
| + 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 isolated Go mutation overlays: " + ", ".join(self.mutation_names)) |
| + 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) |
| + for name, overlay in self.build_mutants(worktree, scratch).items(): |
| + command(["go", "build", "-overlay", str(overlay), "-o", str(binaries[name]), "."], 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. Mutation |
| + # placement follows the suite; assertions always use the same test binary. |
| + for phase, binary, case in self.phases: |
| + 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": binary, "G2_CASE": case} |
| + peer_binary = binary if phase == "mutant-stop" else "carlos" |
| + if phase == "mutant-stop": |
| + env["G2_BINARY"] = "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={peer_binary}\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={peer_binary} /var/lib/g2fix/g2.test -test.run=^TestRootG2Peer$ -test.v -test.timeout={self.peer_minutes}m\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=^{self.test_name}$ -test.v -test.count=1 -test.timeout={self.test_minutes}m\n" |
| + try: |
| + result = self.ssm(runner, script, phase + "-witness", self.witness_timeout) |
| + finally: |
| + # Preserve service journals even when Go's test timeout prevents |
| + # test cleanup. These commands only target the owned pair. |
| + for iid in (runner, peer): |
| + self.require_ssm(iid, "journalctl -u carlos-edge -u carlos-instance-control --no-pager\n", |
| + phase + "-services-" + iid, 60) |
| + 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 " + self.mutation_failures[phase] if phase in self.mutation_failures else "Success, exact test PASS, all case evidence, no SKIP")) |
| + else: |
| + # SSM truncates inline output. Read the complete, automatically uploaded log. |
| + verify_environment(log + "\n" + peer_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") |
| + self.verify(result, log, phase) |
| + self.manifest["checks"].append(phase) |
| + self.save() |
| + |
| + |
| +def main(run_type=Run): |
| + 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_type(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 run.pass_line) |
| + return 0 |
| + |
| + |
| +if __name__ == "__main__": |
| + sys.exit(main()) |