region-ha p1b-3a: model placement and add wake test harnesses
Exercise DecidePlacement through modeled requests and bounded recovery invariants, with deterministic witnesses for ten placement regressions. Check isolated HA acquires and refusal read budgets against real S3 transports, and add a tagged nested-wake root-runner payload. This is a partial Task 4 checkpoint. The full production acceptance set remains incomplete, as recorded in the controller task report.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
8 files changed,
+1,672
−23
internal/host/haplacement_root_linux_test.go+583 −0internal/host/haplacement_wiring_test.go+305 −1internal/sim/regionha/actions_test.go+245 −0internal/sim/regionha/invariants_test.go+6 −0internal/sim/regionha/rules_test.go+11 −0internal/sim/regionha/sim_test.go+1 −1internal/sim/regionha/witness_test.go+343 −0internal/sim/regionha/world_test.go+178 −21
diff --git a/internal/host/haplacement_root_linux_test.go b/internal/host/haplacement_root_linux_test.go| new file mode 100644 |
| index 000000000..8ba104ddb |
| --- /dev/null |
| +++ b/internal/host/haplacement_root_linux_test.go |
| @@ -0,0 +1,583 @@ |
| +//go:build linux && rootrunner |
| + |
| +package host |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "crypto/ecdsa" |
| + "crypto/ed25519" |
| + "crypto/elliptic" |
| + "crypto/rand" |
| + "crypto/sha256" |
| + "crypto/tls" |
| + "crypto/x509" |
| + "crypto/x509/pkix" |
| + "encoding/base64" |
| + "encoding/hex" |
| + "encoding/json" |
| + "encoding/pem" |
| + "io" |
| + "math/big" |
| + "net" |
| + "net/http" |
| + "net/http/httptest" |
| + "os" |
| + "os/exec" |
| + "path/filepath" |
| + "runtime" |
| + "strings" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/activator" |
| + "github.com/carlosframework/platform/internal/analytics" |
| + "github.com/carlosframework/platform/internal/cgroup" |
| + "github.com/carlosframework/platform/internal/controlsock" |
| + "github.com/carlosframework/platform/internal/edge" |
| + "github.com/carlosframework/platform/internal/gate" |
| + "github.com/carlosframework/platform/internal/hafresh" |
| + "github.com/carlosframework/platform/internal/hostactors" |
| + "github.com/carlosframework/platform/internal/hostbox" |
| + "github.com/carlosframework/platform/internal/hostfloor" |
| + "github.com/carlosframework/platform/internal/instancectl" |
| + "github.com/carlosframework/platform/internal/lease" |
| + "github.com/carlosframework/platform/internal/lease/leasetest" |
| + "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/rollout" |
| + "github.com/carlosframework/platform/internal/rootparticipation" |
| + "github.com/carlosframework/platform/internal/rootstate" |
| + "github.com/carlosframework/platform/internal/usage" |
| + "github.com/carlosframework/platform/internal/version" |
| +) |
| + |
| +func init() { |
| + if os.Getenv("COLD_ROOT_BOX") != "" { |
| + version.Build = "v2.0.0" |
| + } |
| + if os.Getenv("COLD_ROOT_BOX") != "" && len(os.Args) == 2 && os.Args[1] == "agent" { |
| + os.Args = []string{os.Args[0], "-test.run=^TestColdPlacementRootAgent$", "-test.v", "-test.timeout=5m"} |
| + } |
| + if os.Getenv("COLD_ROOT_BOX") != "" && len(os.Args) >= 2 && os.Args[1] == "instance-control" { |
| + RunInstanceControl(os.Args[2:]) |
| + os.Exit(0) |
| + } |
| +} |
| + |
| +type coldRootStats struct { |
| + Owned bool |
| + Apps map[string]int |
| + Meter usage.EdgeFlush |
| + Analytics int64 |
| +} |
| + |
| +type coldRootAnalytics struct{ n atomic.Int64 } |
| + |
| +func (a *coldRootAnalytics) Observe(analytics.Obs) { a.n.Add(1) } |
| + |
| +func TestColdPlacementRootAgent(t *testing.T) { |
| + ref := os.Getenv("COLD_ROOT_BOX") |
| + if ref == "" { |
| + t.Skip("installed edge child payload") |
| + } |
| + version.Build = "v2.0.0" |
| + t.Setenv("CARLOS_S3_ENDPOINT", os.Getenv("COLD_ROOT_DATA_ENDPOINT")) |
| + t.Setenv("CARLOS_DEPLOYMENT_BUCKET", "") |
| + data := os.Getenv("CARLOS_DATA_DIR") |
| + store := release.NewDirStore(os.Getenv("CARLOS_DEPLOYMENT_DIR")) |
| + reg, err := registry.Open(filepath.Join(data, "registry.db")) |
| + lifecycleCheck(t, "edge registry", err) |
| + defer reg.Close() |
| + cfg := activator.Config{Bucket: "data", Region: "eu-west-1", Prefix: "instances", Idle: time.Hour, Record: func(ctx context.Context, rt registry.Route) (provision.LifetimeEntry, error) { |
| + r, _, err := provision.FindRecordByHost(ctx, store, rt.Host) |
| + if err != nil { |
| + return provision.LifetimeEntry{}, err |
| + } |
| + if r == nil { |
| + return provision.LifetimeEntry{}, os.ErrNotExist |
| + } |
| + return provision.LifetimeEntryOf(*r) |
| + }} |
| + lease.SetSelf(hafresh.Self{Ref: ref, IID: "i-" + ref, Account: "111122223333", Region: "eu-west-1"}) |
| + lifecycleCheck(t, "obligation store", lease.SetObligationDir(filepath.Join(data, "obligations"))) |
| + files, err := newProductionFilesStore(t.Context(), cfg.Bucket, cfg.Region) |
| + lifecycleCheck(t, "files store", err) |
| + ctl := instancectl.NewClient(controlsock.Path) |
| + manager := cgroup.SetupRetaining(t.Logf) |
| + eb := &activator.ExecBackend{Cfg: cfg, Registry: reg, DataDir: data, OptDir: "/opt/carlos", FilesStore: files, EscrowKey: haEscrowKey(os.Getenv("CARLOS_SECRETS_KEY")), Control: ctl, Cgroups: manager} |
| + if ref == "leo" { |
| + deadline := time.Now().Add(time.Minute) |
| + for { |
| + err := ctl.Ready(t.Context()) |
| + if err == nil { |
| + break |
| + } |
| + if time.Now().After(deadline) { |
| + t.Fatal("real nested readiness", err) |
| + } |
| + time.Sleep(100 * time.Millisecond) |
| + } |
| + swept, err := ctl.Sweep(t.Context()) |
| + lifecycleCheck(t, "startup stop-and-prove", err) |
| + eb.StartupSwept = func() bool { return len(swept.Failed) == 0 } |
| + eb.NestedOK = func() error { return ctl.Ready(t.Context()) } |
| + } |
| + svc := activator.New(cfg, &activator.SplitBackend{Exec: eb, Unit: &activator.UnitBackend{}}, reg) |
| + armHAPlacementWitness(svc, func(context.Context, string, string, string) error { return nil }) |
| + svc.Start() |
| + defer func() { |
| + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) |
| + defer cancel() |
| + svc.Shutdown(ctx) |
| + }() |
| + meter := edge.NewUsageMeter() |
| + observer := &coldRootAnalytics{} |
| + admin := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + _ = json.NewEncoder(w).Encode(coldRootStats{Owned: svc.Owns(lifecycleHost), Apps: svc.AwakeApps(), Meter: meter.Drain(), Analytics: observer.n.Load()}) |
| + })) |
| + defer admin.Close() |
| + lifecycleCheck(t, "admin address", os.WriteFile(filepath.Join(data, "cold-root-admin"), []byte(admin.URL), 0600)) |
| + edge.RunWithActivatorReady([]string{"--registry", filepath.Join(data, "registry.db"), "--https", os.Getenv("COLD_ROOT_HTTPS"), "--http", "127.0.0.1:0"}, svc, nil, func(e *edge.Edge) { |
| + e.EnableUsage(meter) |
| + e.EnableAnalytics(observer) |
| + e.SetAnalyticsOn(map[string]bool{"bab/lifecycle": true}) |
| + }, edge.WithBoxLabel(ref)) |
| +} |
| + |
| +func TestColdPlacementRootRunner(t *testing.T) { |
| + egressRootPrereqs(t) |
| + uid, gid := generationRunnerRegistryUser(t) |
| + for _, path := range []string{lifecycleHome, "/data", "/opt/carlos", "/run/carlos", "/run/carlos-control", "/etc/carlos", "/var/lib/carlos-claims", "/var/lib/carlos-release"} { |
| + lifecycleCheck(t, "exclusive root "+path, os.Mkdir(path, 0755)) |
| + t.Cleanup(func() { lifecycleCheck(t, "remove owned root "+path, os.RemoveAll(path)) }) |
| + } |
| + lifecycleCheck(t, "private root authority", os.Chmod("/var/lib/carlos-claims", 0700)) |
| + for _, path := range []string{lifecycleHome + "/deployment", "/data/.instances", "/data/instances", "/run/carlos/.instances", "/run/carlos/instances", "/run/carlos/.logs", "/run/carlos/logs", "/opt/carlos/versions"} { |
| + lifecycleCheck(t, "tree", os.MkdirAll(path, 0755)) |
| + } |
| + model := leasetest.NewVersionedBucket() |
| + model.AddBucket("data") |
| + s3, _ := leasetest.NewS3Server(model) |
| + server := httptest.NewServer(lifecycleS3(s3, model)) |
| + defer server.Close() |
| + lifecycleEnvironment(t, server.URL) |
| + t.Setenv("CARLOS_HOST_CLAIM", "") |
| + t.Setenv("CARLOS_REGION_HA", "true") |
| + key := ed25519.NewKeyFromSeed(bytes.Repeat([]byte{1}, ed25519.SeedSize)) |
| + store := release.NewDirStore(lifecycleHome + "/deployment") |
| + identity := handoverRecoveryIdentity(t, hostbox.Actor{Box: "box", Enrollment: strings.Repeat("a", 32), Revision: 1, Binding: "1", Region: "ie", FleetHomeRegion: "ie", ControlBucket: "deployment"}) |
| + identity.HomeRegion = "ie" |
| + actor, err := identity.Verify(t.Context()) |
| + lifecycleCheck(t, "guard fixture identity", err) |
| + binary, err := os.Executable() |
| + lifecycleCheck(t, "binary", err) |
| + image, err := os.ReadFile(binary) |
| + lifecycleCheck(t, "binary bytes", err) |
| + lifecycleCheck(t, "executor", os.WriteFile("/opt/carlos/carlos", image, 0755)) |
| + lifecycleCheck(t, "previous executor", os.WriteFile("/opt/carlos/carlos.prev", image, 0755)) |
| + sum := sha256.Sum256(image) |
| + platform := runtime.GOOS + "-" + runtime.GOARCH |
| + pointer := release.SystemPointer{Schema: 1, Component: "router", Channel: "stable", Spread: "0s", PromotedAt: time.Now(), Current: release.SystemRelease{Version: "v2.0.0", ReleaseTag: "v2.0.0", MovesProtocol: 1, Artifacts: map[string]release.SystemArtifact{platform: {Key: release.SystemArtifactKey("v2.0.0", platform), SHA256: hex.EncodeToString(sum[:])}}}} |
| + identityBytes, err := release.SignRootEnvelope(release.RootSigner(key), pointer) |
| + lifecycleCheck(t, "executor identity", err) |
| + identities, err := rootstate.Open("/opt/carlos/system/guard/identities", false, true) |
| + lifecycleCheck(t, "executor identities", err) |
| + lifecycleCheck(t, "executor identity persistence", identities.Write("v2.0.0.json", identityBytes)) |
| + identities.Close() |
| + roster := hostactors.Roster{V: 1, HomeRegion: "ie", DeploymentBucket: actor.ControlBucket, Revision: 1, RequestLimitNS: int64(hostbox.RequestLimit), Boxes: map[string]hostactors.Box{actor.Box: {BoxID: actor.Box, Enrollment: actor.Enrollment, Namespace: actor.Namespace, Label: actor.Box, Region: actor.Region, Pool: "default", Cloud: hostactors.Cloud{Provider: actor.Cloud.Provider, Account: actor.Cloud.Account, Region: actor.Cloud.Region, InstanceID: actor.Cloud.InstanceID}, EvidenceSHA256: strings.Repeat("c", 64), CensusPublicKey: ed25519.NewKeyFromSeed(bytes.Repeat([]byte{2}, ed25519.SeedSize)).Public().(ed25519.PublicKey), State: "active"}}, Consoles: map[string]hostactors.Console{}, Holds: map[string]hostactors.Reservation{}, Activations: map[string]hostactors.Reservation{}} |
| + rosterBytes, err := release.SignRootEnvelope(release.RootSigner(key), roster) |
| + lifecycleCheck(t, "guard roster", err) |
| + _, err = store.Put(t.Context(), hostactors.Key, rosterBytes, "") |
| + lifecycleCheck(t, "guard roster persistence", err) |
| + filesSeedConstructionMigration(t, "/opt/carlos", actor.ControlBucket, actor.Box, actor.Enrollment) |
| + coldRootArmGuard(t, store, key, actor, pointer) |
| + censusState, err := rootstate.Open(rootparticipation.Namespace, true, false) |
| + lifecycleCheck(t, "census store", err) |
| + census := rootparticipation.Census{Schema: 1, Box: actor.Box, Enrollment: actor.Enrollment, Migration: 1, Revision: 1, LaunchRevision: 1, Complete: true} |
| + censusBytes, err := json.Marshal(census) |
| + lifecycleCheck(t, "census fixture", err) |
| + lifecycleCheck(t, "census persistence", censusState.Write("census.json", censusBytes)) |
| + censusState.Close() |
| + failures, err := rootstate.Open(rollout.RootFailuresDir, true, false) |
| + lifecycleCheck(t, "failures store", err) |
| + _, err = rollout.InitializeRootFailures(failures, rootUpdatesMigration(census), nil) |
| + lifecycleCheck(t, "failure migration", err) |
| + failures.Close() |
| + pins, err := rootstate.Open(release.RootGenerationsDir, true, false) |
| + lifecycleCheck(t, "generation pins", err) |
| + pins.Close() |
| + lifecycleInstallUnits(t) |
| + ctl := func(args ...string) (string, error) { |
| + out, err := exec.Command("systemctl", args...).CombinedOutput() |
| + return string(out), err |
| + } |
| + for _, name := range []string{"carlos-edge.service", "carlos-instance-probe.service"} { |
| + raw, err := unitsFS.ReadFile("units/" + name) |
| + lifecycleCheck(t, "production unit", err) |
| + path := filepath.Join("/etc/systemd/system", name) |
| + f, err := os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0644) |
| + lifecycleCheck(t, "exclusive production unit", err) |
| + _, err = f.Write(raw) |
| + lifecycleCheck(t, "write production unit", err) |
| + lifecycleCheck(t, "close production unit", f.Close()) |
| + t.Cleanup(func() { _, _ = ctl("stop", name); _ = os.Remove(path); _, _ = ctl("daemon-reload") }) |
| + } |
| + secret := base64.StdEncoding.EncodeToString(bytes.Repeat([]byte{7}, 32)) |
| + caFile := lifecycleHome + "/root-ca.pem" |
| + coldRootCertificate(t, store, caFile) |
| + _, err = store.Put(t.Context(), "control/edge-mesh-key", []byte(strings.Repeat("a", 64)), "") |
| + lifecycleCheck(t, "mesh key", err) |
| + env := map[string]string{"COLD_ROOT_BOX": "leo", "COLD_ROOT_HTTPS": "127.0.0.1:443", "PLAN14_LIFECYCLE_GUARD": "1", "CARLOS_HOST_CLAIM": "", "CARLOS_REGION_HA": "true", "CARLOS_HIBERNATE_BUCKET": "data", "CARLOS_HIBERNATE_REGION": "eu-west-1", "CARLOS_HIBERNATE_PREFIX": "instances", "CARLOS_DATA_DIR": "/data", "CARLOS_OPT_DIR": "/opt/carlos", "CARLOS_DEPLOYMENT_DIR": lifecycleHome + "/deployment", "CARLOS_DEPLOYMENT_BUCKET": actor.ControlBucket, "CARLOS_RELEASE_PUBKEY": base64.StdEncoding.EncodeToString(key.Public().(ed25519.PublicKey)), "CARLOS_SECRETS_KEY": secret, "CARLOS_S3_ENDPOINT": activationS3Fixture(t, store), "COLD_ROOT_DATA_ENDPOINT": server.URL, "AWS_ACCESS_KEY_ID": "test-key", "AWS_SECRET_ACCESS_KEY": "test-secret", "AWS_EC2_METADATA_DISABLED": "true", "AWS_CONFIG_FILE": "/nonexistent", "AWS_SHARED_CREDENTIALS_FILE": "/nonexistent", "AWS_REGION": "eu-west-1", "SSL_CERT_FILE": caFile, "TMPDIR": "/run/carlos", "PATH": os.Getenv("PATH")} |
| + var lines []string |
| + for name, value := range env { |
| + lines = append(lines, name+"="+value) |
| + } |
| + lifecycleCheck(t, "host environment", os.WriteFile("/etc/carlos/host.env", []byte(strings.Join(lines, "\n")+"\n"), 0600)) |
| + reg, err := openServiceRegistry("/data/registry.db") |
| + lifecycleCheck(t, "registry", err) |
| + defer reg.Close() |
| + gateHash, err := gate.Hash("cold-root-password") |
| + lifecycleCheck(t, "selected gate", err) |
| + rec := provision.Record{Gate: gateHash, Schema: 1, Host: lifecycleHost, Account: "bab", App: "lifecycle", Channel: "stable", HA: true, CreatedAt: time.Now().UTC()} |
| + raw, err := json.Marshal(rec) |
| + lifecycleCheck(t, "record encode", err) |
| + _, err = store.Put(t.Context(), provision.RecordKey(rec.Account, rec.App, rec.Host), raw, "") |
| + lifecycleCheck(t, "record", err) |
| + cfg := provision.ReconcileConfig{DataDir: "/data", Layout: func(context.Context, release.Store) (string, error) { return release.LayoutModeNested, nil }} |
| + lifecycleCheck(t, "provision real HA record", provision.Reconcile(t.Context(), store, reg, cfg)) |
| + |
| + manifest := release.Manifest{App: "lifecycle", Version: "v1", Kind: "binary", Artifacts: map[string]release.Artifact{release.AdoptPlatform(): {}}} |
| + lifecycleCheck(t, "ship", release.Ship(t.Context(), store, "bab", manifest, map[string][]byte{release.AdoptPlatform(): image})) |
| + lifecycleCheck(t, "promote", release.Promote(t.Context(), store, key, "bab", "lifecycle", "stable", "v1")) |
| + _, _, err = release.StageSignedHead(t.Context(), store, key.Public().(ed25519.PublicKey), nil, "/opt/carlos", registry.Route{Host: lifecycleHost, Account: "bab", App: "lifecycle", Channel: "stable"}) |
| + |
| + lifecycleCheck(t, "stage signed app", err) |
| + lifecycleCheck(t, "point live", release.PointLive("/opt/carlos", lifecycleHost, "bab", "v1", "lifecycle")) |
| + for _, path := range []string{"/data", "/run/carlos", lifecycleHome} { |
| + lifecycleCheck(t, "fixture service owner", filepath.Walk(path, func(path string, _ os.FileInfo, err error) error { |
| + if err != nil { |
| + return err |
| + } |
| + return os.Chown(path, uid, gid) |
| + })) |
| + } |
| + var last []byte |
| + ident := edgesFile{Box: "leo", Region: "eu-west-1", Placement: "ie", DataBucket: "data", SecretsKeyFP: "shared", HibernationConfigured: true, Capabilities: []string{capRegionHA1}, Headroom: &edgeHeadroom{MemFreeMiB: 800, MemTotalMiB: 1000, DiskFreeMiB: 500, DiskTotalMiB: 1000}} |
| + lifecycleCheck(t, "selected publication", edgesFileWrite(t.Context(), store, reg, ident, "127.0.0.1", &last, true)) |
| + ident.Box, ident.Headroom.MemFreeMiB = "sophie", 300 |
| + last = nil |
| + lifecycleCheck(t, "ingress publication", edgesFileWrite(t.Context(), store, reg, ident, "127.0.0.1", &last, true)) |
| + for _, name := range systemUnitFiles { |
| + path := filepath.Join("/etc/systemd/system", name) |
| + if _, e := os.Lstat(path); os.IsNotExist(e) { |
| + t.Cleanup(func() { _, _ = ctl("disable", "--now", name); _ = os.Remove(path); _, _ = ctl("daemon-reload") }) |
| + } |
| + } |
| + |
| + controlDropin := "/etc/systemd/system/carlos-instance-control.service.d" |
| + lifecycleCheck(t, "exclusive control fixture environment", os.Mkdir(controlDropin, 0755)) |
| + lifecycleCheck(t, "control fixture environment", os.WriteFile(filepath.Join(controlDropin, "10-cold-root.conf"), []byte("[Service]\nEnvironmentFile=/etc/carlos/host.env\n"), 0644)) |
| + t.Cleanup(func() { |
| + _, _ = ctl("stop", "carlos-instance-control.service") |
| + _ = os.RemoveAll(controlDropin) |
| + _, _ = ctl("daemon-reload") |
| + }) |
| + ensureSystemUnits("/etc", "/opt/carlos/system/router/lock", ctl, ctl, t.Logf) |
| + out, err := ctl("daemon-reload") |
| + lifecycleCheck(t, out, err) |
| + out, err = ctl("start", "data-instances.mount", "run-carlos-instances.mount", "run-carlos-logs.mount") |
| + lifecycleCheck(t, out, err) |
| + dropin := "/run/systemd/system/carlos-edge.service.d" |
| + lifecycleCheck(t, "exclusive edge fixture drop-in", os.Mkdir(dropin, 0755)) |
| + lifecycleCheck(t, "disable fixture automatic restart", os.WriteFile(filepath.Join(dropin, "10-cold-root.conf"), []byte("[Service]\nRestart=no\n"), 0644)) |
| + t.Cleanup(func() { |
| + _, _ = ctl("stop", "carlos-edge.service") |
| + _ = os.RemoveAll(dropin) |
| + _, _ = ctl("daemon-reload") |
| + }) |
| + _, err = ctl("daemon-reload") |
| + lifecycleCheck(t, "fixture daemon reload", err) |
| + coldRootProbeFixtures(t, uid, gid) |
| + out, err = ctl("start", "carlos-edge.service") |
| + lifecycleCheck(t, out, err) |
| + ingress := t.TempDir() |
| + ingressReg, err := registry.Open(filepath.Join(ingress, "registry.db")) |
| + lifecycleCheck(t, "ingress registry", err) |
| + route, err := reg.Get(lifecycleHost) |
| + lifecycleCheck(t, "provisioned row", err) |
| + if route == nil || !route.HA { |
| + t.Fatal("provisioning did not produce an HA route") |
| + } |
| + ingressRoute := *route |
| + ingressRoute.Gate, err = gate.Hash("ingress-must-not-run-this-gate") |
| + lifecycleCheck(t, "ingress gate", err) |
| + lifecycleCheck(t, "ingress row", ingressReg.Upsert(ingressRoute)) |
| + ingressReg.Close() |
| + listener, err := net.Listen("tcp", "127.0.0.1:0") |
| + lifecycleCheck(t, "reserve ingress address", err) |
| + addr := listener.Addr().String() |
| + listener.Close() |
| + cmd := exec.Command(binary, "-test.run=^TestColdPlacementRootAgent$", "-test.v", "-test.timeout=5m") |
| + cmd.Dir = ingress |
| + for name, value := range env { |
| + switch name { |
| + case "COLD_ROOT_BOX": |
| + value = "sophie" |
| + case "COLD_ROOT_HTTPS": |
| + value = addr |
| + case "CARLOS_DATA_DIR": |
| + value = ingress |
| + case "TMPDIR": |
| + value = ingress |
| + } |
| + cmd.Env = append(cmd.Env, name+"="+value) |
| + } |
| + log, err := os.Create(filepath.Join(ingress, "edge.log")) |
| + lifecycleCheck(t, "ingress log", err) |
| + cmd.Stdout, cmd.Stderr = log, log |
| + lifecycleCheck(t, "start ingress process", cmd.Start()) |
| + t.Cleanup(func() { |
| + _ = cmd.Process.Signal(os.Interrupt) |
| + timer := time.AfterFunc(15*time.Second, func() { _ = cmd.Process.Kill() }) |
| + _ = cmd.Wait() |
| + timer.Stop() |
| + log.Close() |
| + }) |
| + caBytes, err := os.ReadFile(caFile) |
| + lifecycleCheck(t, "parent CA", err) |
| + pool := x509.NewCertPool() |
| + if !pool.AppendCertsFromPEM(caBytes) { |
| + t.Fatal("invalid fixture CA") |
| + } |
| + client := &http.Client{Transport: &http.Transport{TLSClientConfig: &tls.Config{RootCAs: pool}, DialContext: func(ctx context.Context, network, _ string) (net.Conn, error) { |
| + return (&net.Dialer{}).DialContext(ctx, network, addr) |
| + }}, Timeout: 45 * time.Second} |
| + defer client.CloseIdleConnections() |
| + deadline := time.Now().Add(2 * time.Minute) |
| + for { |
| + conn, err := net.DialTimeout("tcp", addr, time.Second) |
| + if err == nil { |
| + conn.Close() |
| + break |
| + } |
| + if time.Now().After(deadline) { |
| + raw, _ := os.ReadFile(log.Name()) |
| + t.Fatalf("ingress never listened: %s", raw) |
| + } |
| + time.Sleep(100 * time.Millisecond) |
| + } |
| + response, err := coldRootGET(client) |
| + lifecycleCheck(t, "non-choice request", err) |
| + body, err := io.ReadAll(response.Body) |
| + response.Body.Close() |
| + lifecycleCheck(t, "response body", err) |
| + if response.StatusCode != 200 || string(body) != "lifecycle tenant" { |
| + t.Fatalf("production wake: %d %q", response.StatusCode, body) |
| + } |
| + selectedStats := coldRootReadStats(t, "/data") |
| + ingressStats := coldRootReadStats(t, ingress) |
| + if !selectedStats.Owned || ingressStats.Owned || selectedStats.Apps["bab/lifecycle"] != 1 { |
| + t.Fatalf("ownership selected=%+v ingress=%+v", selectedStats, ingressStats) |
| + } |
| + selectedRow := selectedStats.Meter.Rows[lifecycleHost] |
| + ingressRow := ingressStats.Meter.Rows[lifecycleHost] |
| + selectedChecks, ingressChecks := int64(0), int64(0) |
| + for _, g := range selectedStats.Meter.Guard { |
| + selectedChecks += g.Checked |
| + } |
| + for _, g := range ingressStats.Meter.Guard { |
| + ingressChecks += g.Checked |
| + } |
| + if selectedRow.Requests != 1 || selectedRow.HopRequests != 1 || ingressRow.Requests != 0 || selectedChecks != 1 || ingressChecks != 0 || selectedStats.Analytics != 1 || ingressStats.Analytics != 0 { |
| + t.Fatalf("accounting owner selected=%+v ingress=%+v", selectedStats, ingressStats) |
| + } |
| + |
| + if owner, ok := hafresh.ParseOwner(func() string { |
| + v, e := lease.ReadLock(t.Context(), "data", "instances/"+lifecycleHost, "eu-west-1") |
| + lifecycleCheck(t, "lock owner", e) |
| + return v.Lock.Owner |
| + }()); !ok || owner.Ref != "leo" { |
| + t.Fatalf("wrong writer: %+v", owner) |
| + } |
| + untilReplicated := time.Now().Add(30 * time.Second) |
| + for { |
| + versions, err := model.ListVersions(t.Context(), "data", "instances/"+lifecycleHost+"/") |
| + lifecycleCheck(t, "replica evidence", err) |
| + haveLTX := false |
| + for _, v := range versions { |
| + haveLTX = haveLTX || strings.HasSuffix(v.Key, ".ltx") |
| + } |
| + if haveLTX { |
| + break |
| + } |
| + if time.Now().After(untilReplicated) { |
| + t.Fatal("real replication did not persist the database before the crash") |
| + } |
| + time.Sleep(100 * time.Millisecond) |
| + } |
| + out, err = ctl("kill", "--kill-whom=main", "--signal=KILL", "carlos-edge.service") |
| + lifecycleCheck(t, "crash selected edge: "+out, err) |
| + out, err = ctl("stop", "carlos-edge.service") |
| + lifecycleCheck(t, "stop and prove edge: "+out, err) |
| + // SIGKILL cannot create a clean marker; the real startup sweep must stop the tenant before recovery. |
| + v, err := lease.ReadLock(t.Context(), "data", "instances/"+lifecycleHost, "eu-west-1") |
| + lifecycleCheck(t, "crashed owner observation", err) |
| + if v.Lock.Release != nil { |
| + t.Fatal("agent crash fabricated a clean release") |
| + } |
| + if state, _ := ctl("show", instancectl.UnitName(instancectl.RoleRun, lifecycleHost), "-p", "ActiveState", "--value"); strings.TrimSpace(state) == "active" { |
| + t.Fatal("nested writer survived the stopped edge") |
| + } |
| + // Move only the crashed lease deadline at the low-level store seam. Acquire, |
| + // same-box proof, restore, publication and launch remain production code. |
| + v.Lock.ExpiresAt = time.Now().Add(-time.Minute) |
| + expired, err := json.Marshal(v.Lock) |
| + lifecycleCheck(t, "expired lock fixture", err) |
| + model.Put("data", "instances/"+lifecycleHost+"/lock.json", expired) |
| + out, err = ctl("reset-failed", "carlos-edge.service") |
| + lifecycleCheck(t, out, err) |
| + out, err = ctl("start", "carlos-edge.service") |
| + lifecycleCheck(t, "restart actual edge: "+out, err) |
| + readyUntil := time.Now().Add(2 * time.Minute) |
| + var recovered bool |
| + for time.Now().Before(readyUntil) { |
| + response, e := coldRootGET(client) |
| + if e == nil { |
| + raw, _ := io.ReadAll(response.Body) |
| + response.Body.Close() |
| + if response.StatusCode == 200 && string(raw) == "lifecycle tenant" { |
| + recovered = true |
| + break |
| + } |
| + } |
| + time.Sleep(100 * time.Millisecond) |
| + } |
| + if !recovered { |
| + journal, _ := ctl("status", "carlos-edge.service") |
| + t.Fatal("restart did not recover through the request path", journal) |
| + } |
| + selectedStats = coldRootReadStats(t, "/data") |
| + ingressStats = coldRootReadStats(t, ingress) |
| + if !selectedStats.Owned || ingressStats.Owned { |
| + t.Fatal("recovery moved authority away from the expired owner", selectedStats, ingressStats) |
| + } |
| + v, err = lease.ReadLock(t.Context(), "data", "instances/"+lifecycleHost, "eu-west-1") |
| + lifecycleCheck(t, "recovered writer", err) |
| + owner, ok := hafresh.ParseOwner(v.Lock.Owner) |
| + if !ok || owner.Ref != "leo" { |
| + t.Fatalf("wrong recovered writer: %+v", owner) |
| + } |
| + out, err = ctl("stop", "carlos-edge.service") |
| + lifecycleCheck(t, "graceful real stop: "+out, err) |
| + v, err = lease.ReadLock(t.Context(), "data", "instances/"+lifecycleHost, "eu-west-1") |
| + lifecycleCheck(t, "release after stop-and-prove", err) |
| + if v.Lock.Release == nil { |
| + t.Fatal("graceful stop did not publish a release marker") |
| + } |
| + t.Log("selected nested host woke, crashed without a marker, recovered through real emptiness proof and restore, and released only after stop-and-prove") |
| +} |
| + |
| +func coldRootProbeFixtures(t *testing.T, uid, gid int) { |
| + lifecycleCheck(t, "probe secret", os.WriteFile("/etc/carlos/probe-secret", []byte("probe"), 0640)) |
| + lifecycleCheck(t, "probe secret group", os.Chown("/etc/carlos/probe-secret", 0, gid)) |
| + f, err := os.OpenFile("/dev/shm/carlos-probe", os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0644) |
| + lifecycleCheck(t, "exclusive probe shared memory", err) |
| + _, err = f.WriteString("probe") |
| + lifecycleCheck(t, "probe fixture", err) |
| + f.Close() |
| + t.Cleanup(func() { _ = os.Remove("/dev/shm/carlos-probe") }) |
| + for _, path := range []string{"/data/instances/_probe", "/run/carlos/instances/_probe"} { |
| + lifecycleCheck(t, "probe directory", os.Mkdir(path, 0700)) |
| + lifecycleCheck(t, "probe directory owner", os.Chown(path, uid, gid)) |
| + } |
| +} |
| + |
| +func coldRootCertificate(t *testing.T, store release.Store, caFile string) { |
| + key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) |
| + lifecycleCheck(t, "CA key", err) |
| + ca := &x509.Certificate{SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: "cold-wake witness"}, NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(90 * 24 * time.Hour), IsCA: true, BasicConstraintsValid: true, KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageDigitalSignature} |
| + der, err := x509.CreateCertificate(rand.Reader, ca, ca, &key.PublicKey, key) |
| + lifecycleCheck(t, "CA", err) |
| + lifecycleCheck(t, "CA trust", os.WriteFile(caFile, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}), 0644)) |
| + leafKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) |
| + lifecycleCheck(t, "leaf key", err) |
| + leaf := &x509.Certificate{SerialNumber: big.NewInt(2), DNSNames: []string{lifecycleHost}, NotBefore: ca.NotBefore, NotAfter: ca.NotAfter, KeyUsage: x509.KeyUsageDigitalSignature, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}} |
| + der, err = x509.CreateCertificate(rand.Reader, leaf, ca, &leafKey.PublicKey, key) |
| + lifecycleCheck(t, "leaf", err) |
| + priv, err := x509.MarshalECPrivateKey(leafKey) |
| + lifecycleCheck(t, "leaf private key", err) |
| + bundle := append(pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: priv}), pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der})...) |
| + _, err = store.Put(t.Context(), "control/certs/"+lifecycleHost, bundle, "") |
| + lifecycleCheck(t, "certificate publication", err) |
| +} |
| + |
| +func coldRootReadStats(t *testing.T, data string) coldRootStats { |
| + raw, err := os.ReadFile(filepath.Join(data, "cold-root-admin")) |
| + lifecycleCheck(t, "stats address", err) |
| + client := &http.Client{Timeout: 5 * time.Second} |
| + defer client.CloseIdleConnections() |
| + response, err := client.Get(string(raw)) |
| + lifecycleCheck(t, "stats request", err) |
| + defer response.Body.Close() |
| + var stats coldRootStats |
| + lifecycleCheck(t, "stats decode", json.NewDecoder(response.Body).Decode(&stats)) |
| + return stats |
| +} |
| + |
| +func coldRootGET(client *http.Client) (*http.Response, error) { |
| + req, err := http.NewRequest("GET", "https://"+lifecycleHost+"/", nil) |
| + if err != nil { |
| + return nil, err |
| + } |
| + req.SetBasicAuth("", "cold-root-password") |
| + return client.Do(req) |
| +} |
| + |
| +func coldRootArmGuard(t *testing.T, store release.Store, key ed25519.PrivateKey, actor hostbox.Actor, pointer release.SystemPointer) { |
| + t.Helper() |
| + for _, unit := range []string{"carlos-edge.service", "carlos-system-update.service", "carlos-system-recover.service"} { |
| + path := "/etc/systemd/system/" + unit + ".d" |
| + if _, err := os.Lstat(path); !os.IsNotExist(err) { |
| + t.Fatal("pre-existing guard drop-in", path, err) |
| + } |
| + t.Cleanup(func() { _ = os.RemoveAll(path); _, _ = egressCtl("daemon-reload") }) |
| + } |
| + floor, err := json.Marshal(hostfloor.Floor{Min: 1, MinRelease: "v2.0.0"}) |
| + lifecycleCheck(t, "guard floor", err) |
| + auth, err := release.SignRootEnvelope(release.RootSigner(key), hostfloor.Authorization{Schema: 1, Purpose: "moves-protocol", DeploymentBucket: actor.ControlBucket, Key: hostfloor.Key, SHA256: hostfloor.Digest(floor)}) |
| + lifecycleCheck(t, "guard authorization", err) |
| + policy, err := json.Marshal(hostfloor.Policy{Schema: 1, DeploymentBucket: actor.ControlBucket, Mode: "armed", Floor: floor, Authorization: auth}) |
| + lifecycleCheck(t, "guard policy", err) |
| + identity, err := release.SignRootEnvelope(release.RootSigner(key), pointer) |
| + lifecycleCheck(t, "guard identity", err) |
| + enrollment, err := json.Marshal(hostfloor.Enrollment{Box: actor.Box, Enrollment: actor.Enrollment, InstanceID: actor.Cloud.InstanceID}) |
| + lifecycleCheck(t, "guard enrollment", err) |
| + for name, raw := range map[string][]byte{"policy": policy, "identity": identity, "enrollment": enrollment} { |
| + lifecycleCheck(t, "guard input", os.WriteFile("/etc/carlos/"+name+".json", raw, 0600)) |
| + } |
| + // Execute the production entry point in this isolated runner process; |
| + // no CLI child inherits the operator's credentials or working directory. |
| + t.Run("guard-arm", func(t *testing.T) { |
| + t.Setenv("CARLOS_DEPLOYMENT_BUCKET", actor.ControlBucket) |
| + t.Setenv("CARLOS_S3_ENDPOINT", activationS3Fixture(t, store)) |
| + previous := version.Build |
| + version.Build = "v2.0.0" |
| + defer func() { version.Build = previous }() |
| + RunSystemGuardArm([]string{"--policy", "/etc/carlos/policy.json", "--identity", "/etc/carlos/identity.json", "--enrollment", "/etc/carlos/enrollment.json"}) |
| + }) |
| + raw, err := os.ReadFile("/etc/systemd/system/carlos-edge.service.d/90-host-floor.conf") |
| + lifecycleCheck(t, "armed edge dependency", err) |
| + if string(raw) != "[Unit]\nRequires=carlos-system-recover.service\nAfter=carlos-system-recover.service\n[Service]\nExecStart=\nExecStart=/opt/carlos/system/guard/carlos system guard-exec edge\n" { |
| + t.Fatal("guard dependencies differ", string(raw)) |
| + } |
| + guard, err := os.Stat("/opt/carlos/system/guard/carlos") |
| + lifecycleCheck(t, "guard inode", err) |
| + current, err := os.Stat("/opt/carlos/carlos") |
| + lifecycleCheck(t, "executor inode", err) |
| + if os.SameFile(guard, current) { |
| + t.Fatal("guard must be an independent copy") |
| + } |
| +} |
diff --git a/internal/host/haplacement_wiring_test.go b/internal/host/haplacement_wiring_test.go| index dbfb18488..cdc11ed97 100644 |
| --- a/internal/host/haplacement_wiring_test.go |
| +++ b/internal/host/haplacement_wiring_test.go |
| @@ -2,6 +2,25 @@ package host |
| import ( |
| "context" |
| + "encoding/json" |
| + "fmt" |
| + "io" |
| + "net/http/httputil" |
| + "net/url" |
| + "os/exec" |
| + "path/filepath" |
| + "sync/atomic" |
| + |
| + "github.com/carlosframework/platform/internal/activator" |
| + "github.com/carlosframework/platform/internal/boxchoice" |
| + "github.com/carlosframework/platform/internal/edge" |
| + "github.com/carlosframework/platform/internal/hafresh" |
| + "github.com/carlosframework/platform/internal/instancectl" |
| + "github.com/carlosframework/platform/internal/lease" |
| + "github.com/carlosframework/platform/internal/lease/locktest" |
| + "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/release" |
| "net/http" |
| "net/http/httptest" |
| "os" |
| @@ -38,7 +57,7 @@ func TestHAPlacementPageWiring(t *testing.T) { |
| remaining time.Duration |
| } |
| got := make(chan page, 2) |
| - armHAPlacement(svc, func(ctx context.Context, level, subject, body string) error { |
| + armHAPlacementWitness(svc, func(ctx context.Context, level, subject, body string) error { |
| deadline, ok := ctx.Deadline() |
| if !ok { |
| t.Error("no deadline") |
| @@ -59,6 +78,24 @@ func TestHAPlacementPageWiring(t *testing.T) { |
| if rec.Code != 204 || haAwakeApps()["bab/app"] != 1 { |
| t.Fatalf("source does not read the armed Service: status %d apps %v", rec.Code, haAwakeApps()) |
| } |
| + store := release.NewDirStore(t.TempDir()) |
| + ident := edgesFile{Box: "box", Capabilities: []string{capRegionHA1}, Headroom: headroomFor([]string{capRegionHA1}, t.TempDir(), reg)} |
| + var last []byte |
| + if err := edgesFileWrite(context.Background(), store, reg, ident, "127.0.0.1", &last, true); err != nil { |
| + t.Fatal(err) |
| + } |
| + raw, _, err := store.Get(context.Background(), edgesFileKey("box")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var published edgesFile |
| + if err := json.Unmarshal(raw, &published); err != nil { |
| + t.Fatal(err) |
| + } |
| + if published.Headroom == nil || published.Headroom.Apps["bab/app"] != 1 { |
| + t.Fatalf("published Apps do not describe the armed Service: %s", raw) |
| + } |
| + |
| if svc.OnHAOverCapacity == nil { |
| t.Fatal("callback not armed") |
| } |
| @@ -72,3 +109,270 @@ func TestHAPlacementPageWiring(t *testing.T) { |
| t.Fatal("no page") |
| } |
| } |
| + |
| +func armHAPlacementWitness(svc *activator.Service, sink func(context.Context, string, string, string) error) { |
| + if os.Getenv("RHASIM_MUTATE") == "placement-skips-arm" { |
| + return |
| + } |
| + armHAPlacement(svc, func(ctx context.Context, level, subject, body string) error { |
| + if os.Getenv("RHASIM_MUTATE") == "placement-drops-page-subject" { |
| + subject = "" |
| + } |
| + return sink(ctx, level, subject, body) |
| + }) |
| +} |
| + |
| +func TestColdPlacementRequestBudget(t *testing.T) { |
| + for _, holder := range []string{"none", ""} { |
| + t.Run("holder="+holder, func(t *testing.T) { testColdPlacementRequestBudget(t, holder) }) |
| + } |
| +} |
| +func testColdPlacementRequestBudget(t *testing.T, holder string) { |
| + f := newColdPlacementProcesses(t) |
| + a, b := f.box("leo"), f.box("sophie") |
| + s := f.snapshot("leo", "sophie") |
| + started := time.Now() |
| + d := a.call(coldCommand{Op: "forward", Snapshot: s}).Decision |
| + if d.Ref != "sophie" || d.Kind != edge.Placement || a.reads() != 1 { |
| + t.Fatalf("cold choice %+v, ingress reads %d", d, a.reads()) |
| + } |
| + f.expiredOwner("other", "i-other") |
| + if answer := b.call(coldCommand{Op: "acquire"}); answer.Error == "" { |
| + t.Fatal("receiver took an unconfirmed expired owner") |
| + } |
| + a.call(coldCommand{Op: "note", Result: edge.ForwardResult{Ref: d.Ref, Gen: d.Gen, PeerGen: d.PeerGen, Kind: d.Kind, Outcome: edge.ForwardDone, Status: 503, Holder: holder}}) |
| + for i := 0; i < 2; i++ { |
| + if next := a.call(coldCommand{Op: "forward", Snapshot: s}).Decision; next.Ref != "" || next.Refuse || next.Unavailable { |
| + t.Fatal("next request did not preserve Base recovery", next) |
| + } |
| + if answer := a.call(coldCommand{Op: "acquire"}); answer.Error == "" { |
| + t.Fatal("survivor took an unconfirmed expired owner") |
| + } |
| + } |
| + if a.reads() != 3 || b.reads() != 1 || f.writes() != 0 { |
| + t.Fatalf("refusal budget: ingress %d GET, receiver %d GET, %d PUT", a.reads(), b.reads(), f.writes()) |
| + } |
| + |
| + time.Sleep(time.Until(started.Add(10*time.Second + 100*time.Millisecond))) |
| + a.call(coldCommand{Op: "forward", Snapshot: s}) |
| + if a.reads() != 4 { |
| + t.Fatalf("original observation deadline did not cause exactly one re-read: %d", a.reads()) |
| + } |
| +} |
| + |
| +func TestColdPlacementConditionalAcquireProcessIsolation(t *testing.T) { |
| + f := newColdPlacementProcesses(t) |
| + a, b := f.box("leo"), f.box("sophie") |
| + s := f.snapshot("leo", "sophie") |
| + other := f.snapshot("sophie", "leo") |
| + if d := a.call(coldCommand{Op: "forward", Snapshot: s}).Decision; d.Ref != "sophie" { |
| + t.Fatal(d) |
| + } |
| + if d := b.call(coldCommand{Op: "forward", Snapshot: other}).Decision; d.Ref != "leo" { |
| + t.Fatal(d) |
| + } |
| + answers := make(chan coldAnswer, 2) |
| + go func() { answers <- a.call(coldCommand{Op: "acquire"}) }() |
| + go func() { answers <- b.call(coldCommand{Op: "acquire"}) }() |
| + first, second := <-answers, <-answers |
| + if (first.Error == "") == (second.Error == "") || !first.HA && !second.HA { |
| + t.Fatalf("conditional acquire did not elect one HA owner: %+v %+v", first, second) |
| + } |
| +} |
| + |
| +const coldPlacementHost = "shop.example.com" |
| + |
| +type coldCommand struct { |
| + Op string |
| + Snapshot boxchoice.WakeSnapshot |
| + Result edge.ForwardResult |
| +} |
| +type coldAnswer struct { |
| + Decision edge.ForwardDecision |
| + Error string |
| + HA bool |
| +} |
| +type coldPlacementProcesses struct { |
| + t *testing.T |
| + store string |
| + fixture *locktest.LockFixture |
| + putCount atomic.Int64 |
| +} |
| +type coldPlacementProcess struct { |
| + t *testing.T |
| + input io.WriteCloser |
| + output *json.Decoder |
| + getCount atomic.Int64 |
| +} |
| + |
| +func newColdPlacementProcesses(t *testing.T) *coldPlacementProcesses { |
| + t.Helper() |
| + f := &coldPlacementProcesses{t: t, store: t.TempDir(), fixture: locktest.NewLockFixture(t)} |
| + rec := provision.Record{Schema: 1, Host: coldPlacementHost, Account: "bab", App: "shop", Channel: "stable", HA: true, CreatedAt: time.Now().UTC()} |
| + raw, err := json.Marshal(rec) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := release.NewDirStore(f.store).Put(t.Context(), provision.RecordKey(rec.Account, rec.App, rec.Host), raw, ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + return f |
| +} |
| +func (f *coldPlacementProcesses) snapshot(self, peer string) boxchoice.WakeSnapshot { |
| + s := boxchoice.WakeSnapshot{Enabled: true, Usable: true, Self: self, Region: "ie", Running: map[string]boxchoice.Load{}} |
| + for i, ref := range []string{self, peer} { |
| + s.Serving = append(s.Serving, boxchoice.Candidate{BoxID: ref, Generation: time.Now().UTC().Format(time.RFC3339), MemFreeMiB: int64(300 + 500*i), MemTotalMiB: 1000, DiskFreeMiB: 500, DiskTotalMiB: 1000}) |
| + } |
| + return s |
| +} |
| +func (f *coldPlacementProcesses) expiredOwner(ref, iid string) { |
| + raw, err := json.Marshal(hafresh.Lock{Generation: 1, Owner: hafresh.OwnerFor(hafresh.Self{Ref: ref, IID: iid}, 123, true), ExpiresAt: time.Now().Add(-time.Minute)}) |
| + if err != nil { |
| + f.t.Fatal(err) |
| + } |
| + f.fixture.PutLock("instances/"+coldPlacementHost, raw) |
| +} |
| +func (f *coldPlacementProcesses) writes() int64 { return f.putCount.Load() } |
| +func (f *coldPlacementProcesses) box(ref string) *coldPlacementProcess { |
| + t := f.t |
| + t.Helper() |
| + b := &coldPlacementProcess{t: t} |
| + endpoint, err := url.Parse(f.fixture.URL) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + proxy := httputil.NewSingleHostReverseProxy(endpoint) |
| + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + if strings.HasSuffix(r.URL.Path, "/lock.json") { |
| + if r.Method == "GET" { |
| + b.getCount.Add(1) |
| + } |
| + if r.Method == "PUT" { |
| + f.putCount.Add(1) |
| + } |
| + } |
| + proxy.ServeHTTP(w, r) |
| + })) |
| + t.Cleanup(server.Close) |
| + root := t.TempDir() |
| + log, err := os.Create(filepath.Join(root, "child.log")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { log.Close() }) |
| + cmd := exec.Command(os.Args[0], "-test.run=^TestColdPlacementProcess$", "-test.timeout=45s") |
| + cmd.Dir = root |
| + cmd.Env = []string{"PATH=" + os.Getenv("PATH"), "TMPDIR=" + os.Getenv("TMPDIR"), "HOME=" + root, "COLD_PLACEMENT_BOX=" + ref, "COLD_PLACEMENT_STORE=" + f.store, "COLD_PLACEMENT_ROOT=" + root, "CARLOS_S3_ENDPOINT=" + server.URL, "AWS_ACCESS_KEY_ID=test-key", "AWS_SECRET_ACCESS_KEY=test-secret", "AWS_EC2_METADATA_DISABLED=true", "AWS_CONFIG_FILE=/nonexistent", "AWS_SHARED_CREDENTIALS_FILE=/nonexistent", "AWS_REGION=eu-west-1"} |
| + cmd.Stderr = log |
| + b.input, err = cmd.StdinPipe() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + output, err := cmd.StdoutPipe() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + b.output = json.NewDecoder(output) |
| + if err := cmd.Start(); err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { |
| + b.input.Close() |
| + timer := time.AfterFunc(5*time.Second, func() { _ = cmd.Process.Kill() }) |
| + err := cmd.Wait() |
| + timer.Stop() |
| + if err != nil { |
| + raw, _ := os.ReadFile(log.Name()) |
| + t.Errorf("%s child: %v: %s", ref, err, raw) |
| + } |
| + }) |
| + if answer := b.call(coldCommand{Op: "ready"}); answer.Error != "" { |
| + t.Fatal(answer.Error) |
| + } |
| + return b |
| +} |
| +func (b *coldPlacementProcess) reads() int64 { return b.getCount.Load() } |
| +func (b *coldPlacementProcess) call(command coldCommand) coldAnswer { |
| + if err := json.NewEncoder(b.input).Encode(command); err != nil { |
| + b.t.Error(err) |
| + return coldAnswer{Error: err.Error()} |
| + } |
| + var answer coldAnswer |
| + if err := b.output.Decode(&answer); err != nil { |
| + b.t.Error(err) |
| + return coldAnswer{Error: err.Error()} |
| + } |
| + return answer |
| +} |
| +func TestColdPlacementProcess(t *testing.T) { |
| + ref := os.Getenv("COLD_PLACEMENT_BOX") |
| + if ref == "" { |
| + t.Skip("child process payload") |
| + } |
| + root := os.Getenv("COLD_PLACEMENT_ROOT") |
| + reg, err := registry.Open(filepath.Join(root, "registry.db")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer reg.Close() |
| + cfg := activator.Config{Bucket: locktest.FixtureBucket, Region: "eu-west-1", Prefix: "instances", Idle: time.Hour, Record: func(ctx context.Context, rt registry.Route) (provision.LifetimeEntry, error) { |
| + rec, _, err := provision.FindRecordByHost(ctx, release.NewDirStore(os.Getenv("COLD_PLACEMENT_STORE")), rt.Host) |
| + if err != nil { |
| + return provision.LifetimeEntry{}, err |
| + } |
| + if rec == nil { |
| + return provision.LifetimeEntry{}, os.ErrNotExist |
| + } |
| + return provision.LifetimeEntryOf(*rec) |
| + }} |
| + lease.SetSelf(hafresh.Self{Ref: ref, IID: "i-" + ref, Account: "111122223333", Region: "eu-west-1"}) |
| + if err := lease.SetObligationDir(filepath.Join(root, "obligations")); err != nil { |
| + t.Fatal(err) |
| + } |
| + data, run := filepath.Join(root, "data"), filepath.Join(root, "run") |
| + rt := registry.Route{Host: coldPlacementHost, Kind: "instance", Account: "bab", App: "shop", Status: "ready", Channel: "stable", HA: true, Provisioned: true, Hibernate: true, DBPath: provision.NestedDBPath(data, coldPlacementHost), Socket: filepath.Join(run, "instances", provision.InstanceID(coldPlacementHost), "app.sock")} |
| + if err := reg.Upsert(rt); err != nil { |
| + t.Fatal(err) |
| + } |
| + backend := &activator.ExecBackend{Cfg: cfg, Registry: reg, DataDir: data, RunDirOverride: run, Control: instancectl.NewClient(filepath.Join(root, "unused-control.sock"))} |
| + svc := activator.New(cfg, &activator.SplitBackend{Exec: backend, Unit: &activator.UnitBackend{}}, reg) |
| + if _, err := edge.New(reg, svc); err != nil { |
| + t.Fatal(err) |
| + } |
| + armHAPlacementWitness(svc, func(context.Context, string, string, string) error { return nil }) |
| + decoder, encoder := json.NewDecoder(os.Stdin), json.NewEncoder(os.Stdout) |
| + var held activator.Lease |
| + defer func() { |
| + if held != nil { |
| + _ = held.Release(context.Background()) |
| + } |
| + }() |
| + for { |
| + var command coldCommand |
| + if err := decoder.Decode(&command); err == io.EOF { |
| + return |
| + } else if err != nil { |
| + t.Fatal(err) |
| + } |
| + var answer coldAnswer |
| + switch command.Op { |
| + case "ready": |
| + case "forward": |
| + answer.Decision = svc.ForwardTarget(t.Context(), rt, func() boxchoice.WakeSnapshot { return command.Snapshot }) |
| + case "note": |
| + svc.NoteForward(rt.Host, command.Result) |
| + case "acquire": |
| + held, err = backend.Acquire(t.Context(), rt) |
| + if err != nil { |
| + answer.Error = err.Error() |
| + } else if ha, ok := held.(interface{ HA() bool }); ok { |
| + answer.HA = ha.HA() |
| + } |
| + default: |
| + answer.Error = fmt.Sprintf("unknown child operation %q", command.Op) |
| + } |
| + if err := encoder.Encode(answer); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| +} |
diff --git a/internal/sim/regionha/actions_test.go b/internal/sim/regionha/actions_test.go| index 97df872d7..43f864cf1 100644 |
| --- a/internal/sim/regionha/actions_test.go |
| +++ b/internal/sim/regionha/actions_test.go |
| @@ -4,6 +4,10 @@ import ( |
| "fmt" |
| "strconv" |
| "strings" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/activator" |
| + "github.com/carlosframework/platform/internal/edge" |
| "github.com/carlosframework/platform/internal/hafresh" |
| ) |
| @@ -97,6 +101,7 @@ func (w *world) acquireHA(b *box, h string, pre *pending) (*entry, string) { |
| return w.acquireLeaseLitestream(b, h) |
| } |
| v = w.view(h) |
| + b.Placement.AcquireReads++ |
| if why := w.classify(b, h, v); why != "" { |
| return nil, why |
| } |
| @@ -741,6 +746,8 @@ func (w *world) die(b *box) { |
| w.inFlight(b) |
| w.landLate() |
| b.Agent = agentDown |
| + b.Placement.Observations = map[string]placementObservation{} |
| + b.Placement.Peers = map[string]placementPeer{} |
| for _, h := range w.hosts { |
| for _, u := range b.Units[h] { |
| if !u.Straggler { |
| @@ -949,6 +956,30 @@ func idle(b *box, h string) bool { return b.Entries[h] == nil && b.Pending[h] == |
| func init() { |
| actions = append(actions, |
| + action{"placed-request", 12, func(w *world) bool { |
| + b, h := w.randomBox(), w.randomHost() |
| + if b.Agent != agentUp || b.Pending[h] != nil { |
| + return false |
| + } |
| + w.requestPlaced(b, h, false) |
| + w.event("placed-request") |
| + return true |
| + }}, |
| + action{"placement-fold", 3, func(w *world) bool { |
| + b := w.randomBox() |
| + w.foldPlacement(b) |
| + return true |
| + }}, |
| + action{"peer-wake-fault", 2, func(w *world) bool { |
| + b := w.randomBox() |
| + modes := []string{"none", "refuse", "hang", "zero", "out-of-view", "dial", ""} |
| + mode := modes[w.rng.Intn(len(modes))] |
| + if w.calm() { |
| + mode = "" |
| + } |
| + w.peerWakeFault(b.Self.Ref, mode) |
| + return true |
| + }}, |
| // A request at a random box: a write where the host is awake there, |
| // else a wake. |
| action{"request", 30, func(w *world) bool { |
| @@ -1124,3 +1155,217 @@ func init() { |
| }}, |
| ) |
| } |
| + |
| +func (w *world) peerWakeFault(ref, mode string) { w.peerFaults[ref] = mode } |
| +func (w *world) boxRef(ref string) *box { |
| + for _, b := range w.boxes { |
| + if b.Self.Ref == ref { |
| + return b |
| + } |
| + } |
| + return nil |
| +} |
| +func (w *world) requestPlaced(b *box, h string, hopped bool) { |
| + w.requestPlacedAt(b, h, hopped, 0) |
| + w.check() |
| +} |
| +func (w *world) requestPlacedAt(b *box, h string, hopped bool, depth int) { |
| + p := b.Placement |
| + p.MaxHops = max(p.MaxHops, depth) |
| + if depth > 1 { |
| + w.fail("hop", "request forwarded more than once") |
| + return |
| + } |
| + if b.Agent != agentUp || w.isTerminated(b) || !p.Routes[h] { |
| + return |
| + } |
| + if b.Entries[h] != nil { |
| + return |
| + } |
| + local := func() { |
| + p.Begins++ |
| + b.StaleNeg[h] = false // The request carries the born-HA route. |
| + w.logf("placed box%d %s local: %s", b.ID, h, w.wake(b, h, wakeOpts{}, nil)) |
| + if b.Entries[h] != nil { |
| + delete(p.Observations, h) |
| + } |
| + } |
| + if hopped && on("placement-onward-hop") { |
| + local() |
| + return |
| + } |
| + obs, ok := p.Observations[h] |
| + if ok && !obs.suspectUntil.IsZero() { |
| + if w.now().Before(obs.suspectUntil) { |
| + return |
| + } |
| + delete(p.Observations, h) |
| + ok = false |
| + } |
| + if !ok || !w.now().Before(obs.until) { |
| + p.FrontReads++ |
| + p.Sequence++ |
| + obs = placementObservation{view: w.view(h), until: w.now().Add(10 * time.Second), generation: p.Sequence} |
| + if !obs.view.Absent && obs.view.Lock.Release == nil && !w.now().After(obs.view.Lock.ExpiresAt) { |
| + if o, valid := hafresh.ParseOwner(obs.view.Lock.Owner); valid && o.HA && o.Ref != b.Self.Ref && o.IID != b.Self.IID { |
| + obs.holder = o.Ref |
| + obs.until = w.now().Add(time.Hour) |
| + } |
| + } |
| + p.Observations[h] = obs |
| + } |
| + s := w.coldSnapshot(b, h) |
| + v := obs.view |
| + if !on("placement-ignores-expired-owner") && !v.Absent && v.Lock.Release == nil && w.now().After(v.Lock.ExpiresAt) { |
| + v = hafresh.View{Absent: true} |
| + } |
| + if !on("placement-ignores-releaser") && v.Lock.Release != nil { |
| + m := *v.Lock.Release |
| + m.Clean = false |
| + v.Lock.Release = &m |
| + } |
| + if !on("placement-ignores-room") { |
| + for i := range s.Serving { |
| + s.Serving[i].MemFreeMiB = 1000 - s.Serving[i].MemFreeMiB |
| + } |
| + } |
| + peers := activator.PlacementPeerView{Suspect: map[string]bool{}} |
| + if on("placement-ignores-suspect-box") { |
| + for ref, e := range p.Peers { |
| + if w.now().Before(e.until) { |
| + peers.Suspect[ref] = true |
| + } |
| + } |
| + } |
| + observation := &v |
| + if p.ProbeError { |
| + observation = nil |
| + delete(p.Observations, h) |
| + } |
| + d := activator.DecidePlacement(placedRoute(h), b.Self, observation, s, peers, w.now()) |
| + // Caller regressions: incorrectly require placement capability or folded |
| + // membership before honoring the production rule's local/Base answer. |
| + if !on("placement-ignores-switch") && !s.Enabled && d.Kind == activator.Base { |
| + return |
| + } |
| + if !on("placement-requires-published-self-host") && !p.Hosts[h] && (d.Kind == activator.Base || d.Ref == b.Self.Ref) { |
| + return |
| + } |
| + ref, kind := d.Ref, edge.Placement |
| + if d.Kind == activator.Recovery { |
| + kind = edge.Recovery |
| + } |
| + if obs.holder != "" { |
| + ref = obs.holder |
| + kind = edge.Holder |
| + } else { |
| + if d.Kind == activator.Refuse { |
| + return |
| + } |
| + if d.Kind == activator.Base || ref == b.Self.Ref { |
| + local() |
| + return |
| + } |
| + } |
| + target := w.boxRef(ref) |
| + if target == nil { |
| + local() |
| + return |
| + } |
| + e, exists := p.Peers[ref] |
| + if !exists { |
| + p.Sequence++ |
| + e.epoch = p.Sequence |
| + p.Peers[ref] = e |
| + } |
| + token := e.epoch |
| + generation := obs.generation |
| + p.Attempts[ref]++ |
| + p.Hops++ |
| + if f := p.BeforeForward; f != nil { |
| + p.BeforeForward = nil |
| + f() |
| + } |
| + mode := w.peerFaults[ref] |
| + res := edge.ForwardResult{Ref: ref, Kind: kind, Outcome: edge.ForwardDone, Status: 204} |
| + if target.Agent != agentUp || w.isTerminated(target) { |
| + mode = "dial" |
| + } |
| + switch mode { |
| + case "none": |
| + res.Status = 503 |
| + res.Holder = "none" |
| + case "refuse": |
| + res.Status = 503 |
| + case "hang": |
| + res.Status = 502 |
| + case "zero": |
| + res.Status = 0 |
| + case "dial": |
| + res.Status = 503 |
| + res.Outcome = edge.ForwardUnreachable |
| + case "out-of-view": |
| + res.Status = 0 |
| + res.Outcome = edge.ForwardNotInView |
| + default: |
| + w.requestPlacedAt(target, h, true, depth+1) |
| + if target.Entries[h] == nil { |
| + res.Status = 503 |
| + res.Holder = "none" |
| + now := w.view(h) |
| + if !now.Absent && now.Lock.Release == nil && !w.now().After(now.Lock.ExpiresAt) { |
| + if owner, valid := hafresh.ParseOwner(now.Lock.Owner); valid && owner.HA { |
| + res.Holder = owner.Ref |
| + } |
| + } |
| + } |
| + } |
| + w.notePlaced(b, h, res, generation, token) |
| + if res.Outcome == edge.ForwardNotInView && (kind != edge.Placement || !on("placement-local-fallback")) { |
| + local() |
| + } |
| +} |
| +func (w *world) notePlaced(b *box, h string, res edge.ForwardResult, generation, token uint64) { |
| + p := b.Placement |
| + obs, ok := p.Observations[h] |
| + // Production discards hint outcomes after a local begin or a newer holder answer. |
| + if b.Entries[h] != nil || b.Pending[h] != nil || res.Kind != edge.Holder && ok && obs.holder != "" || res.Kind == edge.Holder && (!ok || obs.generation != generation) { |
| + return |
| + } |
| + e, ok := p.Peers[res.Ref] |
| + if !ok || e.epoch != token { |
| + return |
| + } |
| + named := res.Holder != "" && res.Holder != "none" |
| + success := res.Outcome == edge.ForwardDone && (res.Status == 101 || res.Status >= 200 && res.Status < 400) && res.Holder != "none" |
| + failure := res.Holder == "none" || res.Outcome != edge.ForwardDone || res.Status == 0 || res.Status == 502 || res.Status == 503 |
| + if named || success { |
| + e.until = time.Time{} |
| + } else if failure { |
| + if res.Kind == edge.Holder { |
| + if res.Outcome == edge.ForwardUnreachable { |
| + obs.suspectUntil = w.now().Add(10 * time.Second) |
| + p.Observations[h] = obs |
| + } else { |
| + delete(p.Observations, h) |
| + } |
| + return |
| + } |
| + if on("placement-refusal-clears-suspect") || res.Outcome == edge.ForwardUnreachable { |
| + e.until = w.now().Add(10 * time.Second) |
| + } |
| + if !on("placement-drops-negative-on-refusal") { |
| + delete(p.Observations, h) |
| + } |
| + } else { |
| + return |
| + } |
| + p.Sequence++ |
| + e.epoch = p.Sequence |
| + p.Peers[res.Ref] = e |
| + if named && ok && obs.generation == generation && w.now().Before(obs.until) { |
| + obs.holder = res.Holder |
| + obs.until = w.now().Add(time.Hour) |
| + p.Observations[h] = obs |
| + } |
| +} |
diff --git a/internal/sim/regionha/invariants_test.go b/internal/sim/regionha/invariants_test.go| index 12891dadc..da0a9ed9a 100644 |
| --- a/internal/sim/regionha/invariants_test.go |
| +++ b/internal/sim/regionha/invariants_test.go |
| @@ -132,3 +132,9 @@ func (w *world) checkLiveness() { |
| } |
| } |
| } |
| + |
| +func (w *world) requirePlaced(b *box, h string) { |
| + if b.Entries[h] == nil || b.Placement.Begins == 0 { |
| + w.fail("I5", "%s did not recover through an actual request on %s before the suspect deadline", h, b.Self.Ref) |
| + } |
| +} |
diff --git a/internal/sim/regionha/rules_test.go b/internal/sim/regionha/rules_test.go| index 8086851b3..ea1cac98f 100644 |
| --- a/internal/sim/regionha/rules_test.go |
| +++ b/internal/sim/regionha/rules_test.go |
| @@ -39,6 +39,17 @@ func on(rule string) bool { |
| // model hands them or does with their answer, the way a regression in a |
| // caller would. |
| var allRules = []string{ |
| + "placement-ignores-expired-owner", |
| + "placement-ignores-switch", |
| + "placement-ignores-suspect-box", |
| + "placement-refusal-clears-suspect", |
| + "placement-requires-published-self-host", |
| + "placement-drops-negative-on-refusal", |
| + "placement-ignores-releaser", |
| + "placement-ignores-room", |
| + "placement-local-fallback", |
| + "placement-onward-hop", |
| + |
| // the acquire table and the keep decision (I1, I2; spec §9.4, §5.3) |
| "expiry-authorizes", // DecideAcquire: another box's expired HA lease is refused, never taken |
| "keep-without-marker", // no marker in the lock (a re-taken own lease) restores; the release record alone never keeps |
diff --git a/internal/sim/regionha/sim_test.go b/internal/sim/regionha/sim_test.go| index b101d39d7..abc1c8a6b 100644 |
| --- a/internal/sim/regionha/sim_test.go |
| +++ b/internal/sim/regionha/sim_test.go |
| @@ -215,7 +215,7 @@ func TestEveryActionFires(t *testing.T) { |
| "reclassified", "late-ack", "failed-restore", "failed-after-replication", "crash-before-restore", |
| "marker-clean", "marker-unclean", "marker-owed", "obligation-discharged", |
| "release-held", "failed-wake-held", "ha-lock-on-legacy-path", "hang-resumed", "manifest-committed", |
| - "terminate", "takeover", "late-upload", "confirm-error", |
| + "terminate", "takeover", "late-upload", "confirm-error", "placed-request", |
| } { |
| if events[e] == 0 { |
| t.Errorf("no %s over 200 seeds", e) |
diff --git a/internal/sim/regionha/witness_test.go b/internal/sim/regionha/witness_test.go| index 650c595e8..b5550c104 100644 |
| --- a/internal/sim/regionha/witness_test.go |
| +++ b/internal/sim/regionha/witness_test.go |
| @@ -1,11 +1,19 @@ |
| package regionha |
| import ( |
| + "bytes" |
| + "crypto/sha256" |
| "fmt" |
| + |
| + "github.com/carlosframework/platform/internal/edge" |
| "math/rand" |
| "os" |
| "strings" |
| "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/activator" |
| + "github.com/carlosframework/platform/internal/boxchoice" |
| "github.com/carlosframework/platform/internal/hafresh" |
| ) |
| @@ -32,6 +40,17 @@ type witness struct { |
| } |
| var witnesses = []witness{ |
| + {"placement-ignores-expired-owner", "placement-ignores-expired-owner", "I5", "cold-wake request path", wPlacementExpiredOwner}, |
| + {"placement-ignores-switch", "placement-ignores-switch", "I5", "cold-wake request path", wPlacementSwitch}, |
| + {"placement-ignores-suspect-box", "placement-ignores-suspect-box", "I5", "cold-wake request path", wPlacementSuspect}, |
| + {"placement-refusal-clears-suspect", "placement-refusal-clears-suspect", "I5", "cold-wake request path", wPlacementRefusal}, |
| + {"placement-requires-published-self-host", "placement-requires-published-self-host", "I5", "cold-wake request path", wPlacementNewHost}, |
| + {"placement-drops-negative-on-refusal", "placement-drops-negative-on-refusal", "budget", "cold-wake request path", wPlacementBudget}, |
| + {"placement-ignores-releaser", "placement-ignores-releaser", "H4", "cold-wake request path", wPlacementReleaser}, |
| + {"placement-ignores-room", "placement-ignores-room", "H4", "cold-wake request path", wPlacementRoom}, |
| + {"placement-local-fallback", "placement-local-fallback", "hop", "cold-wake request path", wPlacementLost}, |
| + {"placement-onward-hop", "placement-onward-hop", "hop", "cold-wake request path", wPlacementHop}, |
| + |
| {"expiry-authorizes", "expiry-authorizes", "I1", |
| "plan: a hang past the TTL, then another box's wake, is refused; taken on expiry, the new box runs beside the hung one", wHangPastTTL}, |
| {"keep-without-marker", "keep-without-marker", "I2", |
| @@ -599,3 +618,327 @@ func TestKnownGapReusedHostnameLegacyWake(t *testing.T) { |
| t.Fatalf("never-reuse: B's wake: %s, lock %s", r, w.lockString(sh)) |
| } |
| } |
| + |
| +func placementWitness(w *world) (*box, *box) { |
| + A, B, C := w.abc() |
| + C.Placement.Published = false |
| + A.Placement.Free = 300 |
| + B.Placement.Free = 800 |
| + return A, B |
| +} |
| +func wPlacementExpiredOwner(t *testing.T, w *world) { |
| + A, B := placementWitness(w) |
| + w.serve(t, A) |
| + w.crash(A) |
| + w.restart(A, true) |
| + w.advance(ttlTicks + 1) |
| + w.requestPlaced(B, sh, false) |
| + w.requirePlaced(A, sh) |
| +} |
| +func wPlacementSwitch(t *testing.T, w *world) { |
| + A, _ := placementWitness(w) |
| + A.Placement.Enabled = false |
| + A.Placement.Published = false |
| + w.requestPlaced(A, sh, false) |
| + w.requirePlaced(A, sh) |
| +} |
| +func wPlacementSuspect(t *testing.T, w *world) { |
| + placementFailureWitness(t, w, []string{"dial"}) |
| +} |
| +func wPlacementRefusal(t *testing.T, w *world) { |
| + placementFailureWitness(t, w, []string{"none", "refuse", "hang", "zero", "out-of-view"}) |
| +} |
| +func placementFailureWitness(t *testing.T, w *world, modes []string) { |
| + for _, clean := range []bool{false, true} { |
| + for _, mode := range modes { |
| + x := newWitness() |
| + A, B := placementWitness(x) |
| + if clean { |
| + x.serve(t, B) |
| + x.sleepNow(B, sleepOpts{}) |
| + } |
| + x.peerWakeFault(B.Self.Ref, mode) |
| + x.requestPlaced(A, sh, false) |
| + if x.holds(sh) { |
| + x.fail("I5", "failed choice began a wake") |
| + } |
| + attempts := A.Placement.Attempts[B.Self.Ref] |
| + x.requestPlaced(A, sh, false) |
| + x.requirePlaced(A, sh) |
| + x.addPlacedHost("other") |
| + x.requestPlaced(A, "other", false) |
| + x.requirePlaced(A, "other") |
| + if A.Placement.Attempts[B.Self.Ref] != attempts { |
| + x.fail("I5", "suspect reference redialled before ten seconds") |
| + } |
| + w.violations = append(w.violations, x.violations...) |
| + w.trace = append(w.trace, x.trace...) |
| + } |
| + } |
| +} |
| +func wPlacementNewHost(t *testing.T, w *world) { |
| + A, B := placementWitness(w) |
| + A.Placement.Hosts[sh] = false |
| + B.Placement.Hosts[sh] = false |
| + w.requestPlaced(A, sh, false) |
| + w.requirePlaced(A, sh) |
| +} |
| +func wPlacementBudget(t *testing.T, w *world) { |
| + A, B := placementWitness(w) |
| + // Ingress observes a free lock; receiver sees an unconfirmed expired owner. |
| + A.Placement.BeforeForward = func() { |
| + w.s3[sh].Lock = w.leaseBody(1, hafresh.OwnerFor(w.boxes[2].Self, 1, true), w.now().Add(-tick)) |
| + w.s3[sh].ETag = w.newETag() |
| + } |
| + w.requestPlaced(A, sh, false) |
| + if A.Placement.FrontReads != 1 || B.Placement.AcquireReads != 1 { |
| + w.fail("budget", "first refusal reads %d/%d", A.Placement.FrontReads, B.Placement.AcquireReads) |
| + } |
| + w.requestPlaced(A, sh, false) |
| + w.requestPlaced(A, sh, false) |
| + if A.Placement.FrontReads != 1 || A.Placement.AcquireReads != 2 { |
| + w.fail("budget", "negative observation lost on refusal: front=%d acquire=%d", A.Placement.FrontReads, A.Placement.AcquireReads) |
| + } |
| + w.requestOffset += 10 * time.Second |
| + w.requestPlaced(A, sh, false) |
| + if A.Placement.FrontReads != 2 { |
| + w.fail("budget", "original observation deadline moved") |
| + } |
| +} |
| +func wPlacementReleaser(t *testing.T, w *world) { |
| + A, B := placementWitness(w) |
| + w.serve(t, A) |
| + w.sleepNow(A, sleepOpts{}) |
| + w.requestPlaced(B, sh, false) |
| + if A.Entries[sh] == nil { |
| + w.fail("H4", "eligible releaser lost to roomier peer") |
| + } |
| +} |
| +func wPlacementRoom(t *testing.T, w *world) { |
| + A, B := placementWitness(w) |
| + w.requestPlaced(A, sh, false) |
| + if B.Entries[sh] == nil { |
| + w.fail("H4", "free memory did not precede hash") |
| + } |
| +} |
| +func wPlacementLost(t *testing.T, w *world) { |
| + A, B := placementWitness(w) |
| + w.peerWakeFault(B.Self.Ref, "out-of-view") |
| + w.requestPlaced(A, sh, false) |
| + if A.Placement.Begins != 0 || w.holds(sh) { |
| + w.fail("hop", "lost placement fell back locally") |
| + } |
| +} |
| +func wPlacementHop(t *testing.T, w *world) { |
| + A, _ := placementWitness(w) |
| + w.requestPlaced(A, sh, true) |
| + if A.Placement.Hops != 0 || A.Entries[sh] == nil { |
| + w.fail("hop", "verified receiver forwarded onward") |
| + } |
| +} |
| +func TestPlacementPublicOrdering(t *testing.T) { |
| + w := newWitness() |
| + A, B := placementWitness(w) |
| + rt := placedRoute(sh) |
| + s := w.coldSnapshot(A, sh) |
| + v := hafresh.View{Absent: true} |
| + s.Running[B.Self.Ref] = boxchoice.Load{Apps: map[string]int{"bab/shop": 1}} |
| + d := activator.DecidePlacement(rt, A.Self, &v, s, activator.PlacementPeerView{}, w.now()) |
| + if d.Ref != A.Self.Ref { |
| + t.Fatal("app spread must precede free memory", d) |
| + } |
| + s.Running = nil |
| + s.Serving[0].MemFreeMiB = 149 |
| + d = activator.DecidePlacement(rt, A.Self, &v, s, activator.PlacementPeerView{}, w.now()) |
| + if d.Ref != B.Self.Ref { |
| + t.Fatal("ineligible memory candidate chosen", d) |
| + } |
| +} |
| + |
| +func TestPlacementPublicBoundaries(t *testing.T) { |
| + w := newWitness() |
| + A, B := placementWitness(w) |
| + s := w.coldSnapshot(A, sh) |
| + v := hafresh.View{Absent: true} |
| + decide := func(s boxchoice.WakeSnapshot) activator.PlacementDecision { |
| + return activator.DecidePlacement(placedRoute(sh), A.Self, &v, s, activator.PlacementPeerView{}, w.now()) |
| + } |
| + for _, boundary := range []struct { |
| + age time.Duration |
| + usable bool |
| + }{{15 * time.Minute, true}, {15*time.Minute + time.Second, false}, {-time.Minute, true}, {-time.Minute - time.Second, false}} { |
| + s.Serving[1].Generation = w.now().Add(-boundary.age).Format(time.RFC3339) |
| + d := decide(s) |
| + if (d.Ref == B.Self.Ref) != boundary.usable { |
| + t.Fatalf("age %v: %+v", boundary.age, d) |
| + } |
| + } |
| + s = w.coldSnapshot(A, sh) |
| + s.Serving[0].MemFreeMiB, s.Serving[1].MemFreeMiB = 150, 149 |
| + if d := decide(s); d.Ref != A.Self.Ref { |
| + t.Fatal("15 percent boundary", d) |
| + } |
| + s.Serving[0].DiskFreeMiB = 99 |
| + if d := decide(s); !d.OverCapacity { |
| + t.Fatal("10 percent disk refusal must page the fallback", d) |
| + } |
| + s.Serving[0].DiskFreeMiB = 100 |
| + if d := decide(s); d.Ref != A.Self.Ref || d.OverCapacity { |
| + t.Fatal("10 percent disk boundary", d) |
| + } |
| + s = w.coldSnapshot(A, sh) |
| + s.Serving[0].MemFreeMiB = s.Serving[1].MemFreeMiB |
| + ah, bh := sha256.Sum256([]byte(sh+"\x00"+A.Self.Ref)), sha256.Sum256([]byte(sh+"\x00"+B.Self.Ref)) |
| + want := A.Self.Ref |
| + if bytes.Compare(ah[:], bh[:]) < 0 { |
| + want = B.Self.Ref |
| + } |
| + if d := decide(s); d.Ref != want { |
| + t.Fatal("greatest SHA-256 must break the memory tie", d, want) |
| + } |
| + s.Serving[0], s.Serving[1] = s.Serving[1], s.Serving[0] |
| + if d := decide(s); d.Ref != want { |
| + t.Fatal("input order changed choice", d) |
| + } |
| +} |
| +func TestPlacementEvidenceDeclinesToAcquire(t *testing.T) { |
| + for _, mode := range []string{"stale-own", "no-own", "no-key", "read-error", "local-route"} { |
| + t.Run(mode, func(t *testing.T) { |
| + w := newWitness() |
| + A, B := placementWitness(w) |
| + switch mode { |
| + case "stale-own": |
| + A.Placement.Generation = w.now().Add(-16 * time.Minute) |
| + case "no-own": |
| + A.Placement.Published = false |
| + case "no-key": |
| + A.Placement.Key = false |
| + case "read-error": |
| + A.Placement.ProbeError = true |
| + case "local-route": |
| + A.Placement.Hosts[sh] = false |
| + B.Placement.Hosts[sh] = false |
| + } |
| + w.requestPlaced(A, sh, false) |
| + w.requirePlaced(A, sh) |
| + if len(w.violations) > 0 { |
| + t.Fatal(w.violations) |
| + } |
| + if A.Placement.Attempts[B.Self.Ref] != 0 { |
| + t.Fatal("unusable peer was attempted") |
| + } |
| + }) |
| + } |
| +} |
| +func TestPlacementAnswerEpochs(t *testing.T) { |
| + for _, named := range []bool{false, true} { |
| + w := newWitness() |
| + A, B := placementWitness(w) |
| + p := A.Placement |
| + p.Observations[sh] = placementObservation{view: hafresh.View{Absent: true}, until: w.now().Add(10 * time.Second), generation: 1} |
| + p.Peers[B.Self.Ref] = placementPeer{epoch: 2, until: w.now().Add(10 * time.Second)} |
| + p.Sequence = 2 |
| + answer := edge.ForwardResult{Ref: B.Self.Ref, Kind: edge.Placement, Outcome: edge.ForwardDone, Status: 204} |
| + if named { |
| + answer.Holder = B.Self.Ref |
| + answer.Status = 503 |
| + } |
| + w.notePlaced(A, sh, answer, 1, 2) |
| + if w.now().Before(p.Peers[B.Self.Ref].until) { |
| + t.Fatal("successful/holder-naming answer did not clear suspicion") |
| + } |
| + failure := edge.ForwardResult{Ref: B.Self.Ref, Kind: edge.Placement, Outcome: edge.ForwardUnreachable, Status: 503} |
| + w.notePlaced(A, sh, failure, 1, 2) |
| + if w.now().Before(p.Peers[B.Self.Ref].until) { |
| + t.Fatal("old failure re-poisoned newer answer") |
| + } |
| + } |
| + // A late failure survives observation expiry, but not local ownership or a known holder. |
| + for _, newer := range []string{"expired", "awake", "waking", "holder"} { |
| + w := newWitness() |
| + A, B := placementWitness(w) |
| + A.Placement.Peers[B.Self.Ref] = placementPeer{epoch: 1} |
| + A.Placement.Sequence = 1 |
| + if newer == "awake" { |
| + w.serve(t, A) |
| + } |
| + if newer == "waking" { |
| + A.Pending[sh] = &pending{} |
| + } |
| + if newer == "holder" { |
| + A.Placement.Observations[sh] = placementObservation{holder: A.Self.Ref, generation: 2} |
| + } |
| + w.notePlaced(A, sh, edge.ForwardResult{Ref: B.Self.Ref, Kind: edge.Placement, Outcome: edge.ForwardUnreachable, Status: 503}, 1, 1) |
| + suspect := w.now().Before(A.Placement.Peers[B.Self.Ref].until) |
| + if suspect != (newer == "expired") { |
| + t.Fatalf("%s: suspect=%v", newer, suspect) |
| + } |
| + } |
| +} |
| +func TestPlacementExpiredOwnerRequests(t *testing.T) { |
| + for _, proof := range []bool{true, false} { |
| + for _, ingress := range []int{0, 1} { |
| + w := newWitness() |
| + A, B := placementWitness(w) |
| + w.serve(t, A) |
| + w.crash(A) |
| + w.restart(A, proof) |
| + w.advance(ttlTicks) // equality is still held |
| + w.requestPlaced(w.boxes[ingress], sh, false) |
| + if w.holds(sh) { |
| + t.Fatal("equality authorized recovery") |
| + } |
| + w.advance(1) |
| + w.requestOffset += 11 * time.Second |
| + w.requestPlaced(w.boxes[ingress], sh, false) |
| + if (A.Entries[sh] != nil) != proof || B.Entries[sh] != nil { |
| + t.Fatalf("proof=%v ingress=%d: %s", proof, ingress, w.boxesState()) |
| + } |
| + } |
| + } |
| + w := newWitness() |
| + A, B := placementWitness(w) |
| + w.serve(t, A) |
| + w.terminate(A) |
| + w.advance(ttlTicks + 1) |
| + w.requestPlaced(B, sh, false) // Recovery hint fails against fresh publication. |
| + if w.holds(sh) { |
| + t.Fatal("failed recovery request fell back in the same request") |
| + } |
| + w.requestPlaced(B, sh, false) |
| + w.requirePlaced(B, sh) |
| + if len(w.violations) > 0 { |
| + t.Fatal(w.violations) |
| + } |
| +} |
| +func TestPlacementCompetingFoldCAS(t *testing.T) { |
| + w := newWitness() |
| + A, B := placementWitness(w) |
| + w.foldPlacement(A) |
| + w.foldPlacement(B) |
| + own := A.Placement.Fold[A.Self.Ref] |
| + own.Free = 900 |
| + A.Placement.Fold[A.Self.Ref] = own |
| + av, bv := w.view(sh), w.view(sh) |
| + da := activator.DecidePlacement(placedRoute(sh), A.Self, &av, w.coldSnapshot(A, sh), activator.PlacementPeerView{}, w.now()) |
| + db := activator.DecidePlacement(placedRoute(sh), B.Self, &bv, w.coldSnapshot(B, sh), activator.PlacementPeerView{}, w.now()) |
| + if da.Ref != A.Self.Ref || db.Ref != B.Self.Ref { |
| + t.Fatal("setup needs divergent preferences", da, db) |
| + } |
| + if why := w.classify(A, sh, av); why != "" { |
| + t.Fatal(why) |
| + } |
| + if why := w.classify(B, sh, bv); why != "" { |
| + t.Fatal(why) |
| + } |
| + if r := w.wake(A, sh, wakeOpts{}, &pending{View: av}); r != "served" { |
| + t.Fatal(r) |
| + } |
| + if r := w.wake(B, sh, wakeOpts{}, &pending{View: bv}); !strings.HasPrefix(r, "refused: held") { |
| + t.Fatal("CAS loser failed to reclassify", r) |
| + } |
| + w.check() |
| + if len(w.violations) > 0 { |
| + t.Fatal(w.violations) |
| + } |
| +} |
diff --git a/internal/sim/regionha/world_test.go b/internal/sim/regionha/world_test.go| index 7dc8e7ca6..11175e6e6 100644 |
| --- a/internal/sim/regionha/world_test.go |
| +++ b/internal/sim/regionha/world_test.go |
| @@ -8,7 +8,9 @@ import ( |
| "sort" |
| "time" |
| + "github.com/carlosframework/platform/internal/boxchoice" |
| "github.com/carlosframework/platform/internal/hafresh" |
| + "github.com/carlosframework/platform/internal/registry" |
| ) |
| // The model of region HA P1a for born-HA hosts (spec |
| @@ -192,6 +194,7 @@ func (a agentState) String() string { |
| // host legacy. Owed is the obligation store in memory, Disk what of it is |
| // on disk. |
| type box struct { |
| + Placement *placementState |
| ID int |
| Self hafresh.Self |
| PID int |
| @@ -210,17 +213,19 @@ type box struct { |
| } |
| type world struct { |
| - seed int64 |
| - rng *rand.Rand |
| - boxes []*box |
| - hosts []string |
| - s3 map[string]*prefix |
| - step int |
| - trace []string |
| - violations []string |
| - stats map[string]int // actions selected, by name |
| - done map[string]int // actions whose transition completed, by name |
| - events map[string]int // protocol outcomes, by name |
| + requestOffset time.Duration |
| + peerFaults map[string]string |
| + seed int64 |
| + rng *rand.Rand |
| + boxes []*box |
| + hosts []string |
| + s3 map[string]*prefix |
| + step int |
| + trace []string |
| + violations []string |
| + stats map[string]int // actions selected, by name |
| + done map[string]int // actions whose transition completed, by name |
| + events map[string]int // protocol outcomes, by name |
| // owed is the oracle's record of every marker whose PUT failed, by |
| // host and the ETag it was conditioned on: if the lock still carries |
| @@ -297,15 +302,16 @@ func newWorld(seed int64, verbose bool) *world { |
| func newWorldN(seed int64, rng *rand.Rand, n int, hosts []string) *world { |
| w := &world{ |
| - seed: seed, |
| - rng: rng, |
| - hosts: hosts, |
| - s3: map[string]*prefix{}, |
| - stats: map[string]int{}, |
| - done: map[string]int{}, |
| - events: map[string]int{}, |
| - owed: map[string]map[string]bool{}, |
| - nextPID: 100, |
| + seed: seed, |
| + peerFaults: map[string]string{}, |
| + rng: rng, |
| + hosts: hosts, |
| + s3: map[string]*prefix{}, |
| + stats: map[string]int{}, |
| + done: map[string]int{}, |
| + events: map[string]int{}, |
| + owed: map[string]map[string]bool{}, |
| + nextPID: 100, |
| terminated: map[string]int{}, |
| visibleAt: map[string]int{}, |
| @@ -317,6 +323,7 @@ func newWorldN(seed int64, rng *rand.Rand, n int, hosts []string) *world { |
| for i := 0; i < n; i++ { |
| w.boxes = append(w.boxes, &box{ |
| ID: i, |
| + Placement: newPlacementState(hosts), |
| Self: hafresh.Self{Ref: fmt.Sprintf("box%d", i), IID: fmt.Sprintf("i-%04d", i)}, |
| PID: w.newPID(), |
| Swept: true, |
| @@ -345,7 +352,7 @@ func (w *world) staleString() string { |
| return fmt.Sprint(out) |
| } |
| -func (w *world) now() time.Time { return epoch.Add(time.Duration(w.step) * tick) } |
| +func (w *world) now() time.Time { return epoch.Add(time.Duration(w.step) * tick).Add(w.requestOffset) } |
| func (w *world) newPID() int { w.nextPID++; return int(w.nextPID) } |
| func (w *world) newETag() string { w.nextETag++; return fmt.Sprintf("\"e%d\"", w.nextETag) } |
| @@ -630,6 +637,7 @@ func (w *world) pick() *action { |
| // and the liveness oracle (I5). |
| func (w *world) final() { |
| w.faultsOff = true |
| + w.peerFaults = map[string]string{} |
| for _, b := range w.boxes { |
| if w.isTerminated(b) { |
| continue |
| @@ -650,6 +658,7 @@ func (w *world) final() { |
| } |
| } |
| } |
| + w.finalPlacedRequests() |
| w.finalTakeovers() |
| w.checkLiveness() |
| w.logf("final: %d steps, %d violations", w.step, len(w.violations)) |
| @@ -705,3 +714,151 @@ func runSeed(seed int64, verbose bool) *world { |
| w.final() |
| return w |
| } |
| + |
| +type placementObservation struct { |
| + view hafresh.View |
| + until time.Time |
| + generation uint64 |
| + suspectUntil time.Time |
| + holder string |
| +} |
| +type placementPeer struct { |
| + epoch uint64 |
| + until time.Time |
| +} |
| +type placementState struct { |
| + Fold map[string]placementPublication |
| + ProbeError bool |
| + Enabled, Published, Key, Denied bool |
| + Generation time.Time |
| + Hosts, Routes map[string]bool |
| + Free int64 |
| + Apps map[string]int |
| + Observations map[string]placementObservation |
| + Peers map[string]placementPeer |
| + Sequence uint64 |
| + FrontReads, AcquireReads, Begins, Hops, MaxHops int |
| + Attempts map[string]int |
| + BeforeForward func() |
| +} |
| + |
| +func newPlacementState(hosts []string) *placementState { |
| + p := &placementState{Enabled: true, Published: true, Key: true, Free: 500, Hosts: map[string]bool{}, Routes: map[string]bool{}, Apps: map[string]int{}, Observations: map[string]placementObservation{}, Peers: map[string]placementPeer{}, Attempts: map[string]int{}} |
| + for _, h := range hosts { |
| + p.Hosts[h] = true |
| + p.Routes[h] = true |
| + } |
| + return p |
| +} |
| +func placedRoute(h string) registry.Route { |
| + return registry.Route{Host: h, Account: "bab", App: "shop", HA: true, Provisioned: true, Hibernate: true, Kind: "instance"} |
| +} |
| +func (w *world) addPlacedHost(h string) { |
| + w.hosts = append(w.hosts, h) |
| + w.s3[h] = &prefix{} |
| + w.owed[h] = map[string]bool{} |
| + for _, b := range w.boxes { |
| + b.Placement.Hosts[h] = true |
| + b.Placement.Routes[h] = true |
| + } |
| +} |
| + |
| +type placementPublication struct { |
| + Published, Denied bool |
| + Generation time.Time |
| + Hosts map[string]bool |
| + Free int64 |
| + Apps map[string]int |
| +} |
| + |
| +func (w *world) foldPlacement(b *box) { |
| + b.Placement.Fold = map[string]placementPublication{} |
| + for _, peer := range w.boxes { |
| + p := peer.Placement |
| + hosts, apps := map[string]bool{}, map[string]int{} |
| + for h, v := range p.Hosts { |
| + hosts[h] = v |
| + } |
| + for app, n := range p.Apps { |
| + apps[app] = n |
| + } |
| + at := p.Generation |
| + if at.IsZero() { |
| + at = w.now() |
| + } |
| + b.Placement.Fold[peer.Self.Ref] = placementPublication{Published: p.Published, Denied: p.Denied, Generation: at, Hosts: hosts, Free: p.Free, Apps: apps} |
| + } |
| +} |
| +func (w *world) coldSnapshot(b *box, h string) boxchoice.WakeSnapshot { |
| + p := b.Placement |
| + s := boxchoice.WakeSnapshot{Enabled: p.Enabled, Self: b.Self.Ref, Region: "ie", Running: map[string]boxchoice.Load{}} |
| + fold := p.Fold |
| + if fold == nil { |
| + w.foldPlacement(b) |
| + fold = p.Fold |
| + p.Fold = nil |
| + } |
| + own := fold[b.Self.Ref] |
| + s.LocalDenied = own.Denied |
| + s.Usable = own.Published && boxchoice.HeadroomFresh(own.Generation.Format(time.RFC3339), w.now()) |
| + if !s.Usable { |
| + return s |
| + } |
| + for _, peer := range w.boxes { |
| + q := fold[peer.Self.Ref] |
| + gen := q.Generation.Format(time.RFC3339) |
| + if !q.Published || q.Denied || !boxchoice.HeadroomFresh(gen, w.now()) { |
| + continue |
| + } |
| + if peer != b && (!p.Key || !q.Hosts[h]) { |
| + continue |
| + } |
| + if peer == b && !p.Routes[h] { |
| + continue |
| + } |
| + s.Serving = append(s.Serving, boxchoice.Candidate{BoxID: peer.Self.Ref, Generation: gen, MemFreeMiB: q.Free, MemTotalMiB: 1000, DiskFreeMiB: 500, DiskTotalMiB: 1000}) |
| + apps := map[string]int{} |
| + for app, n := range q.Apps { |
| + if n > 0 { |
| + apps[app] = n |
| + } |
| + } |
| + s.Running[peer.Self.Ref] = boxchoice.Load{Apps: apps} |
| + } |
| + return s |
| +} |
| + |
| +func (w *world) finalPlacedRequests() { |
| + for _, h := range w.hosts { |
| + if w.holds(h) || len(w.survivors()) == 0 { |
| + continue |
| + } |
| + v := w.view(h) |
| + eligible := v.Absent && w.s3[h].empty() || v.Lock.Release != nil |
| + if !v.Absent && v.Lock.Release == nil && w.now().After(v.Lock.ExpiresAt) { |
| + if o, valid := hafresh.ParseOwner(v.Lock.Owner); valid && o.HA { |
| + owner := w.boxRef(o.Ref) |
| + if owner != nil { |
| + eligible = w.isTerminated(owner) || w.sameBoxEmpty(owner, h) |
| + } |
| + } |
| + } |
| + if !eligible { |
| + continue |
| + } |
| + for attempt := 0; attempt < 3 && !w.holds(h); attempt++ { |
| + for _, b := range w.survivors() { |
| + w.requestPlaced(b, h, false) |
| + if w.holds(h) { |
| + break |
| + } |
| + } |
| + if !w.holds(h) && attempt == 1 { |
| + w.requestOffset += 11 * time.Second |
| + } |
| + } |
| + if !w.holds(h) { |
| + w.fail("I5", "%s stranded through placement requests before finalTakeovers", h) |
| + } |
| + } |
| +} |