oficina / alta Public

alta-adopt: rollback re-observes the host against the baseline first

Before every rollback mutation (each conditional unset, and the restart
of a rollback resumed at unset) the canonical host is re-observed,
config and identity only, with no delivery probe so a down app can
still be rolled back. A changed instance, environment binding, storage
or record stops it with identity-changed; any preserved key that
changed anywhere in the effective config or the write layer, or a layer
the write did not touch that moved, stops it with preserved-changed.
Both answer ErrStopPreserved and name fields and keys only.

The unset is conditional on the write layer that observation read. An
unset rollback may now go to stopped. observe makes no probe when given
no HTTP client; Observe and Preflight still require one.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev 183a3c46c4690cb7414f13111c709c2944304516 parent f8adb5a
4 files changed, +223 −27
  • adopt/snapshot.go +11 −1
  • adopt/snapshot_test.go +11 −5
  • adopt/write.go +77 −20
  • adopt/write_test.go +124 −1
diff --git a/adopt/snapshot.go b/adopt/snapshot.go
index e8f2f74..c57d52e 100644
--- a/adopt/snapshot.go
+++ b/adopt/snapshot.go
@@ -61,7 +61,8 @@ func plainValue(l carlosop.Layer, ev *carlosop.EffectiveVar) string {
// instance list it found that host in. The codes are the refusals that
// leave no snapshot to check: instance-missing, layer-overlay, and
// home-issuer-mismatch when the host has no Home issuer to locate the
-// write layer by.
+// write layer by. With h nil it makes no delivery probe, and the
+// snapshot's Delivery is empty: the config and identity alone.
func observe(ctx context.Context, c *carlosop.Client, h *http.Client, app provision.App) (Snapshot, []carlosop.Instance, []string, error) {
host := CanonicalHost(app)
all, err := c.Instances(ctx, app.Slug)
@@ -129,6 +130,9 @@ func observe(ctx context.Context, c *carlosop.Client, h *http.Client, app provis
}
snap.HomeConsumer = plainValue(src, cons)
}
+ if h == nil {
+ return snap, all, nil, nil
+ }
if snap.Delivery, err = Probe(ctx, h, provision.PublicOrigin(provision.AdoptionLabel, app.Slug)); err != nil {
return Snapshot{}, nil, nil, err
}
@@ -141,6 +145,9 @@ func observe(ctx context.Context, c *carlosop.Client, h *http.Client, app provis
// ID, and a delivery probe. A host whose write layer cannot be located is
// an error naming the code.
func Observe(ctx context.Context, c *carlosop.Client, h *http.Client, app provision.App) (Snapshot, error) {
+ if h == nil {
+ return Snapshot{}, errors.New("adopt: Observe needs a client for the delivery probe")
+ }
snap, _, codes, err := observe(ctx, c, h, app)
if err != nil {
return Snapshot{}, err
@@ -202,6 +209,9 @@ func inherits(eff carlosop.Effective, writeLayer string, keys [2]string) bool {
//
// An error is a read that failed; it is not a refusal to guess past.
func Preflight(ctx context.Context, c *carlosop.Client, h *http.Client, app provision.App, mine map[string]string) (Snapshot, []string, error) {
+ if h == nil {
+ return Snapshot{}, nil, errors.New("adopt: Preflight needs a client for the delivery probe")
+ }
snap, all, codes, err := observe(ctx, c, h, app)
if err != nil || len(codes) > 0 {
return snap, codes, err
diff --git a/adopt/snapshot_test.go b/adopt/snapshot_test.go
index 7652500..f1a3e06 100644
--- a/adopt/snapshot_test.go
+++ b/adopt/snapshot_test.go
@@ -43,6 +43,16 @@ func appNamed(t *testing.T, slug string) provision.App {
return a
}
+// fixtureInstance is the canonical host's instance record as the
+// fixture first stores it.
+func fixtureInstance(app provision.App) carlosop.Instance {
+ return carlosop.Instance{
+ Host: CanonicalHost(app), App: app.Slug, Slug: "s-" + app.Slug, Channel: "stable", Region: "eu",
+ CreatedAt: time.Date(2026, 3, 1, 0, 0, 0, 0, time.UTC), RecordSeq: 4,
+ ReplicaAssignment: json.RawMessage(`{"boxes":["b1"]}`),
+ }
+}
+
func newCarlosFixture(t *testing.T, slug string) *carlosFixture {
t.Helper()
app := appNamed(t, slug)
@@ -53,11 +63,7 @@ func newCarlosFixture(t *testing.T, slug string) *carlosFixture {
f.SetVar(app.Slug, "", p+"_HOME_CONSUMER_ID", provision.ConsumerID(provision.AdoptionLabel, app.Slug))
f.SetVar(app.Slug, "", p+"_ORIGIN", valueOrigin)
f.SetSecret(app.Slug, "", p+"_INSTANCE_KEY")
- f.AddInstance(carlosop.Instance{
- Host: CanonicalHost(app), App: app.Slug, Slug: "s-" + app.Slug, Channel: "stable", Region: "eu",
- CreatedAt: time.Date(2026, 3, 1, 0, 0, 0, 0, time.UTC), RecordSeq: 4,
- ReplicaAssignment: json.RawMessage(`{"boxes":["b1"]}`),
- })
+ f.AddInstance(fixtureInstance(app))
c := carlosop.New(f.URL(), fixtureAccount, f.Token())
t.Cleanup(c.Close)
diff --git a/adopt/write.go b/adopt/write.go
index 85e3548..65ffc19 100644
--- a/adopt/write.go
+++ b/adopt/write.go
@@ -154,9 +154,10 @@ func ClassifyRollback(baseline, read carlosop.Layer, sent map[string]string) Rol
// The journal's states move one way only. A write is sent, then landed
// or stopped; nothing follows either. A rollback is sent, then unset,
-// then restarted, or stopped instead; a rollback that finds the keys
-// already gone goes straight to unset. A state may repeat (a retry, a
-// failed restart), with its code updated.
+// then restarted, or stopped instead (an unset one too, when a change is
+// found before its restart); a rollback that finds the keys already gone
+// goes straight to unset. A state may repeat (a retry, a failed
+// restart), with its code updated.
var (
writeNext = map[string][]string{
"": {"sent"},
@@ -165,7 +166,7 @@ var (
rollbackNext = map[string][]string{
"": {"sent", "unset", "stopped"},
"sent": {"sent", "unset", "stopped"},
- "unset": {"unset", "restarted"},
+ "unset": {"unset", "restarted", "stopped"},
}
)
@@ -221,7 +222,7 @@ func advanceRollback(ctx context.Context, s *Store, next RollbackRecord) error {
func stoppedErr(code string) error {
stop := ErrStopConflict
switch code {
- case "preserved-changed":
+ case "preserved-changed", "identity-changed":
stop = ErrStopPreserved
case "agent-keys-foreign":
stop = ErrStopForeign
@@ -555,13 +556,19 @@ func CaptureAfter(ctx context.Context, c *carlosop.Client, h *http.Client, s *St
// shape. It is journalled, and a resume continues from the journal:
//
// - restarted is done; stopped is refused again;
-// - unset goes straight to the restart;
-// - otherwise the write layer is reread and classified
+// - before anything else, and again before every PUT, the host is
+// re-observed against the baseline (rollbackDrift): a changed
+// identity stops the rollback (identity-changed), as does any
+// preserved key that changed anywhere in the effective config, or a
+// layer the write did not touch that moved (preserved-changed);
+// - unset then goes straight to the restart;
+// - otherwise the write layer that observation read is classified
// (ClassifyRollback). RetryUnset journals sent and sends one
// conditional PUT unsetting both keys at the version just read; a
-// 412 or a lost answer is reread and classified again, at most three
-// PUTs in all. RolledBack goes to the restart without a PUT. A stop
-// is journalled and returned.
+// 412 or a lost answer is re-observed and classified again, at most
+// three PUTs in all. RolledBack goes to the restart without a PUT. A
+// malformed answer stops it (receipt-malformed). A stop is
+// journalled and returned.
//
// The restart goes through RestartAndWait, so through RestartCanonical's
// dry run, and waits for Reverted against the baseline: removing the
@@ -598,28 +605,41 @@ func RollbackAgentKeys(ctx context.Context, c *carlosop.Client, h *http.Client,
if !have {
rb = RollbackRecord{App: app.Slug}
}
- switch rb.State {
- case "restarted":
- return nil
- case "stopped":
- return stoppedErr(rb.Code)
- case "unset":
- return rollbackRestart(ctx, c, h, s, app, base, rb, apply)
- }
- stop := func(code string, e error) error {
+ stop := func(code string, e error, detail ...string) error {
if apply {
rb.State, rb.Code = "stopped", code
if err := advanceRollback(ctx, s, rb); err != nil {
return err
}
}
+ if len(detail) > 0 {
+ return fmt.Errorf("%w (%s): %s", e, code, strings.Join(detail, ", "))
+ }
return fmt.Errorf("%w (%s)", e, code)
}
+ switch rb.State {
+ case "restarted":
+ return nil
+ case "stopped":
+ return stoppedErr(rb.Code)
+ case "unset":
+ // The restart is a mutation too: the host is the baseline's, and
+ // keeps every preserved key, or a person looks first.
+ if _, code, diff, err := rollbackDrift(ctx, c, app, base); err != nil {
+ return err
+ } else if code != "" {
+ return stop(code, ErrStopPreserved, diff...)
+ }
+ return rollbackRestart(ctx, c, h, s, app, base, rb, apply)
+ }
for attempt := 1; ; attempt++ {
- read, err := c.Config(ctx, app.Slug, base.WriteLayer)
+ read, code, diff, err := rollbackDrift(ctx, c, app, base)
if err != nil {
return err
}
+ if code != "" {
+ return stop(code, ErrStopPreserved, diff...)
+ }
switch ClassifyRollback(base.Layer, read, w.Sent) {
case RolledBack:
if apply {
@@ -677,6 +697,43 @@ func RollbackAgentKeys(ctx context.Context, c *carlosop.Client, h *http.Client,
}
}
+// rollbackDrift re-observes app's canonical host, its identity and its
+// config only (no delivery probe: a rollback must reach an app that is
+// down), and compares it with the baseline, as every rollback mutation
+// needs first. It answers the write layer that observation read and,
+// when anything differs, the stop code and what differs, by field and
+// key name only:
+//
+// - identity-changed: no record answers for the host any more, or its
+// instance, environment binding, storage or record is not the
+// baseline's (identity-<field>);
+// - preserved-changed: any key of the baseline but the two agent keys
+// changed, went, changed kind or moved layer, in the effective config
+// or the write layer's stored vars, or a layer the write did not
+// touch moved (Preserved's codes), or the host's Home issuer can no
+// longer be located (observe's codes).
+func rollbackDrift(ctx context.Context, c *carlosop.Client, app provision.App, base Snapshot) (carlosop.Layer, string, []string, error) {
+ fresh, _, codes, err := observe(ctx, c, nil, app)
+ switch {
+ case err != nil:
+ return carlosop.Layer{}, "", nil, err
+ case slices.Contains(codes, "instance-missing"):
+ return carlosop.Layer{}, "identity-changed", codes, nil
+ case len(codes) > 0:
+ return carlosop.Layer{}, "preserved-changed", codes, nil
+ }
+ if id := SameIdentity(base.Identity, fresh.Identity); len(id) > 0 {
+ for i := range id {
+ id[i] = "identity-" + id[i]
+ }
+ return fresh.Layer, "identity-changed", id, nil
+ }
+ if diff := Preserved(base, fresh, AgentKeys(app)); len(diff) > 0 {
+ return fresh.Layer, "preserved-changed", diff, nil
+ }
+ return fresh.Layer, "", nil, nil
+}
+
// rollbackRestart restarts the canonical host and waits for Reverted
// against the baseline, then journals the rollback restarted. A failure
// journals it unset, code restart-failed, for a resume.
diff --git a/adopt/write_test.go b/adopt/write_test.go
index 0b79122..5f96eae 100644
--- a/adopt/write_test.go
+++ b/adopt/write_test.go
@@ -979,7 +979,7 @@ func TestWriteJournalTransitions(t *testing.T) {
}
rb := func(state string) RollbackRecord { return RollbackRecord{App: "docs", State: state} }
- for _, path := range [][]string{{"restarted"}, {"sent", "restarted"}, {"unset", "sent"}, {"unset", "restarted", "unset"}, {"stopped", "sent"}, {"unset", "stopped"}} {
+ for _, path := range [][]string{{"restarted"}, {"sent", "restarted"}, {"unset", "sent"}, {"unset", "restarted", "unset"}, {"stopped", "sent"}, {"unset", "stopped", "restarted"}, {"unset", "restarted", "stopped"}} {
s := newJournal(t)
var err error
for _, st := range path {
@@ -997,6 +997,13 @@ func TestWriteJournalTransitions(t *testing.T) {
t.Fatalf("rollback %s: %v", st, err)
}
}
+ // A change found before the restart stops a rollback already unset.
+ s = newJournal(t)
+ for _, st := range []string{"unset", "stopped"} {
+ if err := advanceRollback(ctx, s, rb(st)); err != nil {
+ t.Fatalf("rollback %s: %v", st, err)
+ }
+ }
}
// ---- The after snapshot ----
@@ -1276,6 +1283,122 @@ func TestRollbackStopsWhenPreservedKeyResealed(t *testing.T) {
}
}
+// rollbackRefused fails unless a rollback, dry run then applied, stops
+// with ErrStopPreserved and journals code, having unset and restarted
+// nothing. The error names what differs (want), never a value.
+func (w *writeFixture) rollbackRefused(t *testing.T, code, want string) {
+ t.Helper()
+ p, r := w.puts(), w.f.RestartCount("docs.oficina.works")
+ for _, apply := range []bool{false, true} {
+ err := w.rollback(apply)
+ if !errors.Is(err, ErrStopPreserved) {
+ t.Fatalf("apply %v: err = %v, want ErrStopPreserved", apply, err)
+ }
+ if !strings.Contains(err.Error(), want) {
+ t.Fatalf("apply %v: err = %v, want it to name %s", apply, err, want)
+ }
+ noValues(t, err)
+ }
+ if w.rollbackPuts(p) != 0 || w.f.RestartCount("docs.oficina.works") != r {
+ t.Fatal("the rollback unset or restarted past a change")
+ }
+ rec, _ := w.rollbackRecord(t)
+ if rec.State != "stopped" || rec.Code != code {
+ t.Fatalf("state %q code %q", rec.State, rec.Code)
+ }
+ // Stopped is final: a resume refuses again and sends nothing.
+ if err := w.rollback(true); !errors.Is(err, ErrStopPreserved) {
+ t.Fatalf("resume: err = %v", err)
+ }
+ if w.rollbackPuts(p) != 0 {
+ t.Fatal("a resume sent the unset")
+ }
+}
+
+// bindTo rebinds the canonical host's record to the environment env.
+func (w *writeFixture) bindTo(env string) {
+ in := fixtureInstance(w.app)
+ in.Environment = env
+ w.f.AddInstance(in)
+}
+
+// Preserved keys first, across the whole effective config: a preserved
+// key that changed in a layer other than the write layer stops the
+// rollback before anything is unset, as one in the write layer does.
+func TestRollbackStopsWhenPreservedChangedInAnotherLayer(t *testing.T) {
+ cases := map[string]struct {
+ edit func(w *writeFixture)
+ want string
+ }{
+ "secret resealed in the environment": {func(w *writeFixture) { w.f.SetSecret("docs", "production", "DOCS_DEK") }, "changed:DOCS_DEK"},
+ "secret gone from the environment": {func(w *writeFixture) { w.f.Unset("docs", "production", "DOCS_DEK") }, "gone:DOCS_DEK"},
+ "overlay covers a preserved key": {func(w *writeFixture) {
+ w.f.SetOverlay("docs", "docs.oficina.works", "DOCS_INSTANCE_KEY", "covered")
+ }, "from:DOCS_INSTANCE_KEY"},
+ }
+ for name, tc := range cases {
+ t.Run(name, func(t *testing.T) {
+ w := newWriteFixture(t, "docs")
+ // The host is bound to an environment that holds a secret of
+ // its own; the keys go to the default bundle.
+ w.f.SetSecret("docs", "production", "DOCS_DEK")
+ w.bindTo("production")
+ w.configured(t)
+ if w.baseline(t).WriteLayer != "" {
+ t.Fatal("the write layer is not the default bundle")
+ }
+ tc.edit(w)
+ w.rollbackRefused(t, "preserved-changed", tc.want)
+ if _, ours := w.stored(t); ours != [2]bool{true, true} {
+ t.Fatal("the keys were removed")
+ }
+ })
+ }
+}
+
+// The instance the rollback would reach is the one the baseline
+// observed, or nothing is unset: a changed environment binding, storage
+// or record stops it.
+func TestRollbackStopsWhenIdentityChanged(t *testing.T) {
+ cases := map[string]struct {
+ edit func(in *carlosop.Instance)
+ want string
+ }{
+ "environment binding": {func(in *carlosop.Instance) { in.Environment = "staging" }, "identity-environment"},
+ "storage": {func(in *carlosop.Instance) { in.Slug = "s-docs-moved" }, "identity-storage"},
+ "instance record": {func(in *carlosop.Instance) { in.RecordSeq++ }, "identity-record"},
+ }
+ for name, tc := range cases {
+ t.Run(name, func(t *testing.T) {
+ w := newWriteFixture(t, "docs")
+ w.f.SetVar("docs", "staging", "DOCS_STAGE", "1")
+ w.configured(t)
+ in := fixtureInstance(w.app)
+ tc.edit(&in)
+ w.f.AddInstance(in)
+ w.rollbackRefused(t, "identity-changed", tc.want)
+ if _, ours := w.stored(t); ours != [2]bool{true, true} {
+ t.Fatal("the keys were removed")
+ }
+ })
+ }
+}
+
+// A rollback resumed after its unset re-observes too: the restart is a
+// mutation, and a preserved key that changed since stops it.
+func TestRollbackResumeAfterUnsetStopsOnPreservedChange(t *testing.T) {
+ w := newWriteFixture(t, "docs")
+ w.configured(t)
+ for _, k := range AgentKeys(w.app) {
+ w.f.Unset("docs", "", k)
+ }
+ if err := w.s.SaveRollback(context.Background(), RollbackRecord{App: "docs", State: "unset"}); err != nil {
+ t.Fatal(err)
+ }
+ w.f.SetSecret("docs", "", "DOCS_INSTANCE_KEY")
+ w.rollbackRefused(t, "preserved-changed", "changed:DOCS_INSTANCE_KEY")
+}
+
// A 412 whose reread shows a preserved key resealed stops the rollback
// rather than retrying the unset.
func TestRollbackConflict412StopsOnResealedKey(t *testing.T) {