package adopt // The rehearsal: the whole adoption in the order Paul runs it, against // the in-memory Home, the fake console and the six apps' origins. Home // preflights, CARLOS preflight, initialize, Plan A, configure (with its // delivery check) for each app, Plan B for the canary, Plan C. Then the // same run killed at every act, Home's and CARLOS's, and resumed by a // fresh process. import ( "bytes" "context" "database/sql" "encoding/json" "errors" "fmt" "io" "log/slog" "net" "net/http" "net/http/httptest" "net/http/httputil" "net/url" "path/filepath" "reflect" "slices" "strings" "sync" "testing" "time" "amadan.net/oficina/alta/carlosop" "amadan.net/oficina/alta/carlosop/fakecarlos" "amadan.net/oficina/alta/console" "amadan.net/oficina/alta/homeop" "amadan.net/oficina/alta/homeop/fakehome" "amadan.net/oficina/alta/provision" family "amadan.net/rastrillo/rastrillo/crypto" ) const rehearsalOwner = "rehearsal-owner-canary@oficina.test" // crashPoint is where a CARLOS process dies: on its first request of that // kind for an app, once per app. Before: the request never reaches the // console. After: the console has acted, and the answer never arrives. type crashPoint string const ( noCrash crashPoint = "" beforePut crashPoint = "before-put" afterPut crashPoint = "after-put" afterRestart crashPoint = "after-restart" ) // rehearsal is one adoption, start to finish. type rehearsal struct { t *testing.T mu sync.Mutex now time.Time home *fakehome.Home hc *homeop.Client carlos *fakecarlos.Fake h *http.Client // the apps' origins path string // the state database ps *provision.Store js *Store cfg provision.Config actsMu sync.Mutex acts []string // every Home act, in order sites map[string]*appSite // CARLOS crashes: which apps have died at the point already, and what // the console saw. crashed map[string]bool puts map[string]int // PUT /config reaching the console, per app foreign []string // an unset of a value the runner did not write sealed map[string][]byte // each baseline's sealed bytes, as first seen before map[string]layerState release chan struct{} zombies sync.WaitGroup cancels []context.CancelFunc closers []func() sqid string planARun int64 } // layerState is an app's two stored layers: the canonical host's default // bundle and its neighbour's own environment. type layerState struct { def, env map[string]fakecarlos.Var defVer, envVer string } // appSite is one app's process: it serves agent-access's challenge only // once a restart has loaded both of its agent keys. type appSite struct { mu sync.Mutex seen int loaded bool } func neighbourHost(app string) string { return "staging." + app + ".example" } func neighbourEnv(app string) string { return "acme-" + app } func newRehearsal(t *testing.T) *rehearsal { t.Helper() r := &rehearsal{t: t, now: time.Unix(2_000_000_000, 0), sites: map[string]*appSite{}, crashed: map[string]bool{}, puts: map[string]int{}, sealed: map[string][]byte{}, before: map[string]layerState{}, release: make(chan struct{})} // First registered, so it runs last: a dead process is let go, waited // for, and only then are its console door and journal closed. t.Cleanup(func() { close(r.release) for _, c := range r.cancels { c() } r.zombies.Wait() for i := len(r.closers) - 1; i >= 0; i-- { r.closers[i]() } }) fastPolls(t, 5*time.Millisecond, 2*time.Second) key, err := family.Generate() if err != nil { t.Fatal(err) } pre := homeop.Token() const credOrigin, dirOrigin = HomeIssuerOrigin, "https://oficina.works" r.home = fakehome.New(key.SignPub(), pre, credOrigin, dirOrigin, r.clock) pins := r.home.SharePins() r.home.AddPerson(rehearsalOwner) for _, a := range provision.Slugs() { r.home.AddEnvConsumer(a, homeop.CanonicalOrigin(a)) } roles := map[string]homeop.Role{} for name, origin := range map[string]string{homeop.Credential: credOrigin, homeop.Directory: dirOrigin} { srv := httptest.NewServer(r.home.Handler(name)) t.Cleanup(srv.Close) roles[name] = homeop.Role{Name: name, Origin: origin, URL: srv.URL, Installation: pins.Installation, Registry: pins.Registry, Device: pins.Device} } r.hc = &homeop.Client{Key: key, Prefilter: pre, Roles: roles, Now: r.clock} r.carlos = fakecarlos.New(fixtureAccount) t.Cleanup(r.carlos.Close) r.carlos.BeforePut = func(app string) { r.mu.Lock() r.puts[app]++ r.mu.Unlock() } for _, a := range provision.Apps { p := a.Prefix r.carlos.SetVar(a.Slug, "", p+"_HOME_ISSUER", HomeIssuerOrigin) r.carlos.SetVar(a.Slug, "", p+"_HOME_CONSUMER_ID", provision.ConsumerID(provision.AdoptionLabel, a.Slug)) r.carlos.SetVar(a.Slug, "", p+"_ORIGIN", valueOrigin) r.carlos.SetSecret(a.Slug, "", p+"_INSTANCE_KEY") r.carlos.SetSecret(a.Slug, "", p+"_DB_KEY") r.carlos.AddInstance(carlosop.Instance{ Host: routeOf(a), App: a.Slug, Slug: "s-" + a.Slug, Channel: "stable", Region: "eu", CreatedAt: time.Date(2026, 3, 1, 0, 0, 0, 0, time.UTC), RecordSeq: 4, ReplicaAssignment: json.RawMessage(`{"boxes":["b1"]}`), }) attachCanonical(r.carlos, a) // A neighbour on its own owned environment: it shares no layer // with the canonical host, so it never sees the keys, and it is // never restarted. r.carlos.SetVar(a.Slug, neighbourEnv(a.Slug), p+"_HOME_ISSUER", HomeIssuerOrigin) r.carlos.SetSecret(a.Slug, neighbourEnv(a.Slug), p+"_INSTANCE_KEY") r.carlos.Own(a.Slug, neighbourEnv(a.Slug), "alta") r.carlos.AddInstance(carlosop.Instance{Host: neighbourHost(a.Slug), App: a.Slug, Slug: "s-n-" + a.Slug, Environment: neighbourEnv(a.Slug), Channel: "stable", Region: "eu", CreatedAt: time.Date(2026, 4, 1, 0, 0, 0, 0, time.UTC)}) r.sites[a.Slug] = &appSite{} r.before[a.Slug] = r.layers(a.Slug) } site := httptest.NewTLSServer(http.HandlerFunc(r.site)) t.Cleanup(site.Close) tr := site.Client().Transport.(*http.Transport).Clone() addr := site.Listener.Addr().String() tr.DialContext = func(ctx context.Context, network, _ string) (net.Conn, error) { var d net.Dialer return d.DialContext(ctx, network, addr) } tr.TLSClientConfig.ServerName = "example.com" r.h = &http.Client{Transport: tr, Timeout: 10 * time.Second} r.path = filepath.Join(t.TempDir(), "alta.db") r.ps, r.js = r.journal() r.cfg = provision.Config{ Store: r.ps, Home: r.hc, Console: &console.Client{HTTP: &http.Client{Transport: offlineNet{}}, Base: "https://console.invalid", Account: fixtureAccount, Tokens: map[string]string{}}, Public: &http.Client{Transport: offlineNet{}}, HomeCfg: provision.HomeConfig{Issuer: credOrigin, Directory: dirOrigin, Provisioner: r.home.ProvisioningPublic()}, Account: fixtureAccount, Now: r.clock, Logger: slog.New(slog.NewTextHandler(io.Discard, nil)), AfterAct: func(key string) error { r.actsMu.Lock() r.acts = append(r.acts, key) r.actsMu.Unlock() return nil }, } return r } func (r *rehearsal) clock() time.Time { r.mu.Lock() defer r.mu.Unlock() return r.now } func (r *rehearsal) tick(d time.Duration) { r.mu.Lock() defer r.mu.Unlock() r.now = r.now.Add(d) } // journal opens the state database as a fresh process does. func (r *rehearsal) journal() (*provision.Store, *Store) { r.t.Helper() db, err := provision.OpenDB(r.path) if err != nil { r.t.Fatal(err) } r.closers = append(r.closers, func() { db.Close() }) ps, err := provision.NewStore(context.Background(), db, bytes.Repeat([]byte{4}, 32), r.clock, Schema) if err != nil { r.t.Fatal(err) } js, err := NewStore(ps) if err != nil { r.t.Fatal(err) } return ps, js } func (r *rehearsal) layers(app string) layerState { var s layerState s.def, s.defVer, _ = r.carlos.Layer(app, "") s.env, s.envVer, _ = r.carlos.Layer(app, neighbourEnv(app)) return s } func (r *rehearsal) site(w http.ResponseWriter, req *http.Request) { host, _, err := net.SplitHostPort(req.Host) if err != nil { host = req.Host } slug := strings.TrimSuffix(host, ".oficina.works") switch req.URL.Path { case "/api/version": w.Header().Set("X-Carlos-Version", valueVersion) _, _ = io.WriteString(w, valueVersion) case "/healthz": w.WriteHeader(http.StatusOK) case "/api/v1/operations": switch a, _ := provision.AppBySlug(slug); { case r.serving(slug): agent401(w) case BaselineOps(a) == OpsApp401: app401(w) case BaselineOps(a) == OpsAgent401: baseOps401(w) // Base's own door, held through adoption default: http.NotFound(w, req) } default: http.NotFound(w, req) } } func (r *rehearsal) serving(slug string) bool { s, ok := r.sites[slug] a, known := provision.AppBySlug(slug) if !ok || !known { return false } s.mu.Lock() defer s.mu.Unlock() if n := r.carlos.RestartCount(routeOf(a)); n != s.seen { vars, _, _ := r.carlos.Layer(slug, "") keys := AgentKeys(a) _, i := vars[keys[0]] _, t := vars[keys[1]] s.seen, s.loaded = n, i && t } return s.loaded } // ---- Home's half ---- func (r *rehearsal) confirm(kind string) { r.t.Helper() if err := r.home.Confirm(homeop.Directory, ""); err != nil { r.t.Fatal(err) } if kind == homeop.KindInitialize { return } owner := "" if kind == homeop.KindCreateTeam { owner = rehearsalOwner } if err := r.home.Confirm(homeop.Credential, owner); err != nil { r.t.Fatal(err) } } // drive advances run until it is done or failed, each pass a fresh // engine, as alta-adopt advance is: a pass killed by AfterAct resumes in // the next. func (r *rehearsal) drive(run int64, obs provision.Observer) provision.Run { r.t.Helper() var out provision.Run for i := 0; i < 30; i++ { cfg := r.cfg if obs != nil { cfg.Observer = obs } if err := provision.New(cfg).Advance(context.Background(), run); err != nil { var fl *provision.Fail if errors.As(err, &fl) { r.t.Fatalf("run %d failed: %s", run, fl.Code) } } var err error if out, err = r.ps.Run(context.Background(), run); err != nil { r.t.Fatal(err) } if out.State == "done" || out.State == "failed" { return out } r.tick(5 * time.Second) } return out } func (r *rehearsal) engine(obs provision.Observer) *provision.Engine { cfg := r.cfg if obs != nil { cfg.Observer = obs } return provision.New(cfg) } // homePreflight is alta-adopt home-preflight --apply: Paul's pasted // counts, both roles inspected, recorded only when nothing is refused. func (r *rehearsal) homePreflight(phase string) { r.t.Helper() counts := map[string]int64{} for _, q := range HomeQueries() { counts[q[strings.LastIndex(q, " ")+1:]] = 0 } if phase == PhasePrePlanA { counts["roster_generation"], counts["roster_operator_receipts"] = 1, 1 } rec, codes, err := CheckHome(context.Background(), r.hc, r.ps, counts, phase) if err != nil || len(codes) > 0 { r.t.Fatalf("home preflight %s: %v %v", phase, codes, err) } if err := r.js.SaveHomePreflight(context.Background(), rec); err != nil { r.t.Fatal(err) } } func (r *rehearsal) initialize() { r.t.Helper() run, err := r.engine(nil).StartInitialize(context.Background(), provision.InitializeAttestation) if err != nil { r.t.Fatal(err) } r.confirm(homeop.KindInitialize) if got := r.drive(run, nil); got.State != "done" { r.t.Fatalf("initialize: %s %s", got.State, got.Code) } } func (r *rehearsal) planA() { r.t.Helper() run, err := r.engine(nil).StartAdoption(context.Background(), "Oficina", rehearsalOwner) if err != nil { r.t.Fatal(err) } r.planARun = run r.confirm(homeop.KindCreateTeam) if got := r.drive(run, nil); got.State != "done" || got.Code != "awaiting-configuration" { r.t.Fatalf("plan A: %s %s", got.State, got.Code) } team, err := r.ps.Team(context.Background(), provision.AdoptionLabel) if err != nil || team.TeamSQID == "" { r.t.Fatalf("no seeded team: %v", err) } r.sqid = team.TeamSQID } // observer is the activation gate as alta-adopt builds it, over a fresh // console client. func (r *rehearsal) observer() *Observer { c := carlosop.New(r.carlos.URL(), fixtureAccount, r.carlos.Token()) r.closers = append(r.closers, c.Close) artifacts := map[string]string{} for _, a := range provision.Slugs() { artifacts[a] = sha256Hex(valueVersion) } return &Observer{C: c, H: r.h, S: r.js, Artifacts: artifacts, Now: r.clock} } // activate is Plan B or C: alta-adopt activate --apply, the two // confirmations, then advance until done. func (r *rehearsal) activate(apps ...string) { r.t.Helper() // Each plan waits out the last one's window. r.tick(homeop.WindowLifetime * time.Second) obs := r.observer() run, err := r.engine(obs).ActivateAdopted(context.Background(), apps) if err != nil { r.t.Fatalf("activate %v: %v", apps, err) } r.confirm(homeop.KindAddApps) if got := r.drive(run, obs); got.State != "done" { r.t.Fatalf("activate %v: %s %s", apps, got.State, got.Code) } } // ---- CARLOS's half: each step is a process that may die ---- // proc is one alta-adopt process's console client, through a door that // kills the process at its crash point: the request is held for good // (before) or answered to no one (after). From then on the door forwards // nothing, and process.await cuts the process off (its journal handle // closed, its context cancelled), so nothing it does next, even after // its client's own timeout, reaches the console or the journal. type proc struct { c *carlosop.Client dead chan struct{} once sync.Once } func (p *proc) die() { p.once.Do(func() { close(p.dead) }) } func (r *rehearsal) newProc(point crashPoint) *proc { p := &proc{dead: make(chan struct{})} target, err := url.Parse(r.carlos.URL()) if err != nil { r.t.Fatal(err) } rp := httputil.NewSingleHostReverseProxy(target) // A connection the console dropped is dropped here too: the runner // meets a lost answer, never a 502 of the door's making. rp.ErrorHandler = func(http.ResponseWriter, *http.Request, error) { panic(http.ErrAbortHandler) } hold := func() { <-r.release panic(http.ErrAbortHandler) } srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { select { case <-p.dead: hold() default: } body, _ := io.ReadAll(req.Body) req.Body = io.NopCloser(bytes.NewReader(body)) app, kind := r.classify(req, body) hit := kind == "put" && (point == beforePut || point == afterPut) || kind == "restart" && point == afterRestart if hit && r.dies(app) { if point == beforePut { p.die() hold() } rp.ServeHTTP(httptest.NewRecorder(), req) p.die() hold() } rp.ServeHTTP(w, req) })) p.c = carlosop.New(srv.URL, fixtureAccount, r.carlos.Token()) r.closers = append(r.closers, srv.Close, p.c.Close) return p } // dies reports whether app has yet to die at the crash point, and marks // it dead. func (r *rehearsal) dies(app string) bool { r.mu.Lock() defer r.mu.Unlock() if r.crashed[app] { return false } r.crashed[app] = true return true } // classify names a console request's app and kind ("put", "restart" for // a scoped restart that is not a dry run, or ""), and checks every unset // against the stored values: the runner unsets only what it wrote. func (r *rehearsal) classify(req *http.Request, body []byte) (app, kind string) { parts := strings.Split(strings.TrimPrefix(req.URL.Path, "/api/cli/apps/"), "/") if len(parts) < 3 { return "", "" } app, door := parts[1], "/"+strings.Join(parts[2:], "/") switch { case req.Method == http.MethodPut && door == "/config": var w struct { Environment string `json:"environment"` Unset []string `json:"unset"` } _ = json.Unmarshal(body, &w) if a, ok := provision.AppBySlug(app); ok && len(w.Unset) > 0 { vars, _, _ := r.carlos.Layer(app, w.Environment) keys := AgentKeys(a) ours := map[string]string{keys[0]: Issuer, keys[1]: r.sqid} for _, k := range w.Unset { if v, ok := vars[k]; ok && (v.Kind != "env" || v.Value != ours[k]) { r.mu.Lock() r.foreign = append(r.foreign, app+":"+k) r.mu.Unlock() } } } return app, "put" case req.Method == http.MethodPost && door == "/restart/scope": var w struct { DryRun bool `json:"dry_run"` } if json.Unmarshal(body, &w) == nil && !w.DryRun { return app, "restart" } } return app, "" } // step runs fn as one alta-adopt process at a time, killed at point the // first time app reaches it, until a process finishes. A dead process is // cut off where it died; the next one opens the journal afresh. func (r *rehearsal) step(app string, point crashPoint, fn func(ctx context.Context, c *carlosop.Client, js *Store) error) (deaths int) { r.t.Helper() for { died, err := r.spawn(point, fn).await() if !died { if err != nil { r.t.Fatalf("%s: %v", app, err) } return deaths } deaths++ if deaths > 1 { r.t.Fatalf("%s died twice", app) } r.sawBaseline(app) } } // processLimit bounds how long one process may run before it either // finishes or dies: a test that hangs fails here, not at the package // timeout. const processLimit = time.Minute // process is one alta-adopt process: fn on its own console door, journal // handle and context. type process struct { r *rehearsal p *proc db *sql.DB cancel context.CancelFunc done chan error } func (r *rehearsal) spawn(point crashPoint, fn func(ctx context.Context, c *carlosop.Client, js *Store) error) *process { x := &process{r: r, p: r.newProc(point), done: make(chan error, 1)} ps, js := r.journal() x.db = ps.DB() ctx, cancel := context.WithCancel(context.Background()) x.cancel = cancel r.cancels = append(r.cancels, cancel) r.zombies.Add(1) go func() { defer r.zombies.Done() x.done <- fn(ctx, x.p.c, js) }() return x } // await waits, at most processLimit, for the process to finish (its // error) or die (died). A process dies while blocked in its console // request, so it is cut off there and then: its journal handle is closed // and its context cancelled. Whatever it tries next fails at once, // whatever the client's own timeout: a write to the journal finds the // handle closed, and its console door forwards nothing more. func (x *process) await() (died bool, err error) { x.r.t.Helper() select { case err := <-x.done: return false, err case <-x.p.dead: x.db.Close() x.cancel() return true, nil case <-time.After(processLimit): x.r.t.Fatalf("a process neither finished nor died within %s", processLimit) return false, nil } } // sawBaseline keeps app's sealed baseline bytes the first time they are // seen; checkBaselines fails if any has moved since. func (r *rehearsal) sawBaseline(app string) { r.t.Helper() var b []byte err := r.ps.DB().QueryRow("SELECT sealed FROM adopt_baselines WHERE app=?", app).Scan(&b) if errors.Is(err, sql.ErrNoRows) { return } if err != nil { r.t.Fatal(err) } if _, ok := r.sealed[app]; !ok { r.sealed[app] = b } } func (r *rehearsal) checkBaselines() { r.t.Helper() for app, want := range r.sealed { var got []byte if err := r.ps.DB().QueryRow("SELECT sealed FROM adopt_baselines WHERE app=?", app).Scan(&got); err != nil { r.t.Fatal(err) } if !bytes.Equal(got, want) { r.t.Fatalf("%s: the sealed baseline moved", app) } } } // configure is alta-adopt configure --app --apply: the write, then, unless // the after snapshot is already taken, the restart until delivered and // the after snapshot, then the delivery check. func configureApp(ctx context.Context, c *carlosop.Client, h *http.Client, js *Store, a provision.App, sqid string) error { if _, err := WriteAgentKeys(ctx, c, h, js, a, sqid, sha256Hex(valueVersion), true); err != nil { return err } if _, ok, err := js.After(ctx, a.Slug); err != nil { return err } else if !ok { base, ok, err := js.Baseline(ctx, a.Slug) if err != nil || !ok { return fmt.Errorf("no baseline: %v", err) } if _, err := RestartAndWait(ctx, c, h, a, base.Identity, func(d Delivery) error { return Delivered(a, base.Delivery, d) }, true); err != nil { return err } if _, err := CaptureAfter(ctx, c, h, js, a); err != nil { return err } } return CheckDelivery(ctx, js, c, h, a, sha256Hex(valueVersion)) } func (r *rehearsal) configure(a provision.App, point crashPoint) int { r.t.Helper() deaths := r.step(a.Slug, point, func(ctx context.Context, c *carlosop.Client, js *Store) error { return configureApp(ctx, c, r.h, js, a, r.sqid) }) r.sawBaseline(a.Slug) return deaths } func (r *rehearsal) rollback(a provision.App, point crashPoint) int { r.t.Helper() return r.step(a.Slug, point, func(ctx context.Context, c *carlosop.Client, js *Store) error { return RollbackAgentKeys(ctx, c, r.h, js, a, true) }) } // carlosPreflight is alta-adopt preflight: every app clean. func (r *rehearsal) carlosPreflight() { r.t.Helper() c := carlosop.New(r.carlos.URL(), fixtureAccount, r.carlos.Token()) defer c.Close() for _, a := range provision.Apps { if _, codes, err := Preflight(context.Background(), c, r.h, a, nil); err != nil || len(codes) > 0 { r.t.Fatalf("preflight %s: %v %v", a.Slug, codes, err) } } } // ---- the run ---- // options bends one run: where a CARLOS process dies, and a hook on every // Home act. type options struct { configure crashPoint lose bool // the first answer to each app's PUT is lost afterAct func(string) error } // run is the whole adoption, in order, through Plan C. func (r *rehearsal) run(o options) { r.t.Helper() if o.afterAct != nil { record := r.cfg.AfterAct r.cfg.AfterAct = func(key string) error { if err := o.afterAct(key); err != nil { return err } return record(key) } } r.untilPlanA() for _, a := range provision.Apps { if o.lose { r.carlos.LoseNextAnswer() } if deaths := r.configure(a, o.configure); o.configure != noCrash && deaths != 1 { r.t.Fatalf("%s: died %d times at %s", a.Slug, deaths, o.configure) } } r.activate(CanaryApp) var rest []string for _, s := range provision.Slugs() { if s != CanaryApp { rest = append(rest, s) } } r.activate(rest...) } // untilPlanA is the run through Plan A: both preflights, initialize, the // wait for its window to lapse, the second Home preflight, Plan A. func (r *rehearsal) untilPlanA() { r.t.Helper() r.homePreflight(PhasePreInitialize) r.carlosPreflight() r.initialize() // pre-plan-a refuses while the initialize window is open. r.tick(homeop.WindowLifetime * time.Second) r.homePreflight(PhasePrePlanA) r.planA() } // ---- what must hold at the end ---- // adopted fails unless the run ended as it must: six live routes, every // preserved digest equal along baseline, after and fresh, each layer // changed by the two keys alone, nothing else restarted, nothing // committed twice at Home. func (r *rehearsal) adopted() { r.t.Helper() t := r.t ctx := context.Background() for _, s := range provision.Slugs() { if st := r.home.InstanceState(s); st != "live" { t.Fatalf("%s is %q at Home, want live", s, st) } } reqs := r.home.Requests() onceEachRequest(t, reqs) for _, s := range provision.Slugs() { for _, action := range []string{homeop.DirectoryProvision, homeop.CredentialRegister, homeop.DirectoryVerify, homeop.DirectoryActivate} { if n := countRequests(reqs, action+":"+s); n != 1 { t.Fatalf("%s:%s committed %d times", action, s, n) } } } c := carlosop.New(r.carlos.URL(), fixtureAccount, r.carlos.Token()) defer c.Close() for _, a := range provision.Apps { keys := AgentKeys(a) base, ok, err := r.js.Baseline(ctx, a.Slug) if err != nil || !ok { t.Fatalf("%s: no baseline", a.Slug) } after, ok, err := r.js.After(ctx, a.Slug) if err != nil || !ok { t.Fatalf("%s: no after snapshot", a.Slug) } fresh, err := Observe(ctx, c, r.h, a) if err != nil { t.Fatal(err) } if p := Preserved(base, after, keys); len(p) > 0 { t.Fatalf("%s: after not preserved: %v", a.Slug, p) } if p := Preserved(base, fresh, keys); len(p) > 0 { t.Fatalf("%s: drifted: %v", a.Slug, p) } for _, v := range base.Vars { if v.Key == keys[0] || v.Key == keys[1] { t.Fatalf("%s: the baseline held %s", a.Slug, v.Key) } for _, snap := range []Snapshot{after, fresh} { w := findVar(snap.Vars, v.Key) if w == nil || w.Digest != v.Digest || w.Kind != v.Kind || w.From != v.From { t.Fatalf("%s: %s not preserved", a.Slug, v.Key) } } } if len(after.Vars) != len(base.Vars)+2 || len(fresh.Vars) != len(base.Vars)+2 { t.Fatalf("%s: %d vars before, %d after, %d now", a.Slug, len(base.Vars), len(after.Vars), len(fresh.Vars)) } // Each stored layer differs by the two keys alone. was, now := r.before[a.Slug], r.layers(a.Slug) if len(now.def) != len(was.def)+2 { t.Fatalf("%s: default bundle %d keys, was %d", a.Slug, len(now.def), len(was.def)) } for k, v := range was.def { if now.def[k] != v { t.Fatalf("%s: %s changed", a.Slug, k) } } if now.def[keys[0]] != (fakecarlos.Var{Kind: "env", Value: Issuer}) || now.def[keys[1]] != (fakecarlos.Var{Kind: "env", Value: r.sqid}) { t.Fatalf("%s: the agent keys are not as written", a.Slug) } if now.envVer != was.envVer || !reflect.DeepEqual(now.env, was.env) { t.Fatalf("%s: the neighbour's environment changed", a.Slug) } if n := r.carlos.RestartCount(neighbourHost(a.Slug)); n != 0 { t.Fatalf("%s restarted %d times", neighbourHost(a.Slug), n) } if n := r.carlos.RestartCount(routeOf(a)); n < 1 || n > 2 { t.Fatalf("%s restarted %d times", routeOf(a), n) } } if n := r.carlos.AppWideRestarts(); n != 0 { t.Fatalf("app-wide restarts %d", n) } r.checkBaselines() r.noForeignUnset() } func (r *rehearsal) noForeignUnset() { r.t.Helper() r.mu.Lock() defer r.mu.Unlock() if len(r.foreign) > 0 { r.t.Fatalf("unset a value the runner did not write: %v", r.foreign) } } func (r *rehearsal) putsOf(app string) int { r.mu.Lock() defer r.mu.Unlock() return r.puts[app] } func onceEachRequest(t *testing.T, reqs []string) { t.Helper() seen := map[string]int{} for _, q := range reqs { if seen[q]++; seen[q] > 1 { t.Fatalf("%s committed twice: %v", q, reqs) } } } func countRequests(reqs []string, entry string) int { n := 0 for _, q := range reqs { if q == entry { n++ } } return n } // ---- the tests ---- func TestRehearsalFullRun(t *testing.T) { r := newRehearsal(t) r.run(options{}) r.adopted() for _, a := range provision.Apps { if n := r.putsOf(a.Slug); n != 1 { t.Fatalf("%s: %d PUTs, want one", a.Slug, n) } if n := r.carlos.RestartCount(routeOf(a)); n != 1 { t.Fatalf("%s: %d restarts, want one", a.Slug, n) } } if !slices.Contains(r.home.Requests(), homeop.DirectoryActivate+":"+CanaryApp) { t.Fatal("the canary was not activated") } } // The same run, killed once at each act. Home's: after the act took effect // at Home and before Alta recorded it (AfterAct). CARLOS's: before the // PUT reaches the console, after it lands with its answer lost to a dead // process, after the restart, and mid-rollback. A fresh process resumes // from the journal each time. func TestRehearsalCrashAfterEveryAct(t *testing.T) { clean := newRehearsal(t) clean.run(options{}) acts := slices.Clone(clean.acts) want := clean.home.Requests() if len(acts) < 2+2*len(provision.Apps)+2*len(provision.Apps) { t.Fatalf("acts %v", acts) } for i, key := range acts { t.Run(fmt.Sprintf("home-%02d-%s", i, key), func(t *testing.T) { r := newRehearsal(t) n, crashed := 0, false r.run(options{afterAct: func(string) error { if n == i && !crashed { crashed = true return errors.New("kill -9") } n++ return nil }}) if !crashed { t.Fatalf("act %d never reached", i) } r.adopted() if got := r.home.Requests(); !reflect.DeepEqual(sortedCopy(got), sortedCopy(want)) { t.Fatalf("requests\n got %v\nwant %v", got, want) } for _, a := range provision.Apps { if n := r.putsOf(a.Slug); n != 1 { t.Fatalf("%s: %d PUTs", a.Slug, n) } } }) } for _, point := range []crashPoint{beforePut, afterPut, afterRestart} { t.Run("carlos-"+string(point), func(t *testing.T) { r := newRehearsal(t) r.run(options{configure: point}) r.adopted() for _, a := range provision.Apps { if n := r.putsOf(a.Slug); n < 1 || n > 2 { t.Fatalf("%s: %d PUTs", a.Slug, n) } } }) } t.Run("carlos-answer-lost", func(t *testing.T) { r := newRehearsal(t) r.run(options{lose: true}) r.adopted() for _, a := range provision.Apps { if n := r.putsOf(a.Slug); n != 1 { t.Fatalf("%s: %d PUTs, want exactly one", a.Slug, n) } } }) // Mid-rollback: every app configured and its delivery checked, then // rolled back, each killed once at the point. for _, point := range []crashPoint{beforePut, afterPut, afterRestart} { t.Run("rollback-"+string(point), func(t *testing.T) { r := newRehearsal(t) r.untilPlanA() for _, a := range provision.Apps { r.configure(a, noCrash) } r.crashed = map[string]bool{} for _, a := range provision.Apps { if deaths := r.rollback(a, point); deaths != 1 { t.Fatalf("%s: died %d times", a.Slug, deaths) } } ctx := context.Background() for _, a := range provision.Apps { rec, ok, err := r.js.Rollback(ctx, a.Slug) if err != nil || !ok || rec.State != "restarted" { t.Fatalf("%s: rollback %q %v", a.Slug, rec.State, err) } if n := r.putsOf(a.Slug); n < 1 || n > 2 { t.Fatalf("%s: %d PUTs", a.Slug, n) } was, now := r.before[a.Slug], r.layers(a.Slug) if !reflect.DeepEqual(now.def, was.def) || !reflect.DeepEqual(now.env, was.env) || now.envVer != was.envVer { t.Fatalf("%s: the layers are not back to the baseline", a.Slug) } if r.carlos.RestartCount(neighbourHost(a.Slug)) != 0 { t.Fatalf("%s: the neighbour restarted", a.Slug) } if r.home.InstanceState(a.Slug) != "pending" { t.Fatalf("%s is %q at Home", a.Slug, r.home.InstanceState(a.Slug)) } } if r.carlos.AppWideRestarts() != 0 { t.Fatal("an app-wide restart") } r.checkBaselines() r.noForeignUnset() onceEachRequest(t, r.home.Requests()) }) } // A process killed before its unset, and another writer then puts its // own team in the key: the resume stops and unsets nothing. t.Run("rollback-foreign-after-crash", func(t *testing.T) { r := newRehearsal(t) r.untilPlanA() a, _ := provision.AppBySlug("docs") r.configure(a, noCrash) r.crashed = map[string]bool{} dying := r.spawn(beforePut, func(ctx context.Context, c *carlosop.Client, js *Store) error { return RollbackAgentKeys(ctx, c, r.h, js, a, true) }) if died, err := dying.await(); !died { t.Fatalf("the rollback finished (%v) instead of dying before its unset", err) } r.sawBaseline(a.Slug) keys := AgentKeys(a) r.carlos.SetVar("docs", "", keys[1], "tForeignTeam") p2 := r.newProc(noCrash) _, js2 := r.journal() err := RollbackAgentKeys(context.Background(), p2.c, r.h, js2, a, true) r.noForeignUnset() if !errors.Is(err, ErrStopForeign) { t.Fatalf("resume: %v, want ErrStopForeign", err) } vars, _, _ := r.carlos.Layer("docs", "") if vars[keys[1]].Value != "tForeignTeam" || vars[keys[0]].Value != Issuer { t.Fatal("the resume unset a value it did not write") } if n := r.putsOf("docs"); n != 1 { t.Fatalf("%d PUTs, want the write alone", n) } r.checkBaselines() r.noForeignUnset() }) } // A process killed in its PUT stays dead: it is cut off at once, not when // its console client gives up (60 s), and what it tries afterwards, a // journal write here, lands nowhere. func TestRehearsalDeadProcessTouchesNothing(t *testing.T) { r := newRehearsal(t) _, version, _ := r.carlos.Layer("docs", "") keys := AgentKeys(appNamed(t, "docs")) x := r.spawn(beforePut, func(ctx context.Context, c *carlosop.Client, js *Store) error { _, err := c.Put(ctx, "docs", carlosop.PutRequest{Set: map[string]string{keys[0]: Issuer, keys[1]: fixtureSQID}, IfVersion: version}) if err == nil { return errors.New("the PUT was answered") } // Whatever a dead process would do next. return js.SaveDeliveryCheck(context.Background(), DeliveryCheck{App: "docs"}) }) if died, err := x.await(); !died { t.Fatalf("the process finished (%v) instead of dying in its PUT", err) } select { case err := <-x.done: if err == nil { t.Fatal("the dead process wrote to the journal") } case <-time.After(10 * time.Second): t.Fatal("the dead process was not cut off") } var n int if err := r.ps.DB().QueryRow("SELECT count(*) FROM adopt_witnesses").Scan(&n); err != nil || n != 0 { t.Fatalf("journal delivery checks %d (%v)", n, err) } if n := r.putsOf("docs"); n != 0 { t.Fatalf("%d PUTs reached the console", n) } } func sortedCopy(s []string) []string { c := slices.Clone(s) slices.Sort(c) return c }