oficina / alta Public

adopt: conditional write, preserved after snapshot, rollback

WriteAgentKeys runs Preflight itself, seals the baseline once, journals
the write before the conditional PUT, checks the receipt, and recovers a
412 or lost answer by rereading (522 §4.7). CaptureAfter stores the
after snapshot only when the baseline is preserved. RollbackAgentKeys
unsets only the values it wrote, then restarts through RestartCanonical
and completes only when the app has reverted.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev bf536a4ba78a7cc631d46ef4ef7fd6daf5ddb065 parent 66e7667
3 files changed, +1,806 −2
  • adopt/words.go +9 −2
  • adopt/write.go +640 −0
  • adopt/write_test.go +1,157 −0
diff --git a/adopt/words.go b/adopt/words.go
index 8217f13..e26e537 100644
--- a/adopt/words.go
+++ b/adopt/words.go
@@ -2,8 +2,9 @@
// go through the copy-review skill before merge (plan Task 14, step 5);
// a change here is a change of copy.
//
-// PENDING COPY REVIEW: WitnessSentence is a draft, not yet reviewed with
-// Paul. It is reviewed in Task 14 step 5 with the runner's other strings.
+// PENDING COPY REVIEW: WitnessSentence and WriteSummary are drafts, not
+// yet reviewed with Paul. They are reviewed in Task 14 step 5 with the
+// runner's other strings.
package adopt
import "amadan.net/oficina/alta/provision"
@@ -14,3 +15,9 @@ import "amadan.net/oficina/alta/provision"
func WitnessSentence(app provision.App) string {
return "I signed in to " + CanonicalHost(app) + " and it works as before"
}
+
+// WriteSummary is configure's dry-run description of the write: the two
+// keys and the bundle they are written to, never their values.
+func WriteSummary(keys [2]string, bundle string) string {
+ return "set " + keys[0] + ", " + keys[1] + " on " + bundle
+}
diff --git a/adopt/write.go b/adopt/write.go
new file mode 100644
index 0000000..a497122
--- /dev/null
+++ b/adopt/write.go
@@ -0,0 +1,640 @@
+// This file holds configure's one CARLOS write, the after snapshot that
+// proves it preserved everything else, and the journalled rollback. Every
+// write is conditional, journalled before it is sent, and recovered after
+// a lost answer or a 412 by rereading (522 §4.7), never by guessing.
+package adopt
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "net/http"
+ "regexp"
+ "slices"
+ "strings"
+
+ "amadan.net/oficina/alta/carlosop"
+ "amadan.net/oficina/alta/provision"
+)
+
+// Branch is what a reread after a lost answer or a 412 says of a write
+// (522 §4.7). The first that matches wins, preserved keys first. The zero
+// value is none of them.
+type Branch int
+
+const (
+ // Landed: every preserved key equals the baseline and both agent
+ // keys hold what was sent.
+ Landed Branch = iota + 1
+ // Retry: every preserved key equals the baseline and both agent keys
+ // are absent. Retry with the version just read.
+ Retry
+ // StopPreservedChanged: a preserved key changed or went.
+ StopPreservedChanged
+ // StopConflict: the agent keys are partly present, or one holds
+ // another digest or kind. Another writer touched them.
+ StopConflict
+)
+
+// RollbackBranch is what a reread says of a rollback. The first that
+// matches wins, in this order. The zero value is none of them.
+type RollbackBranch int
+
+const (
+ // RetryUnset: both agent keys hold exactly what the write sent.
+ RetryUnset RollbackBranch = iota + 1
+ // RolledBack: both agent keys are absent and every preserved key
+ // equals the baseline.
+ RolledBack
+ // StopForeign: one key alone is present, or either holds another
+ // digest or kind. The runner never unsets a value it did not write.
+ StopForeign
+ // StopPreservedChanged: both keys are absent but a preserved key
+ // changed, so the layer is not back at the baseline.
+ RollbackStopPreservedChanged
+)
+
+// The stops. Each is the end of the road for its app until Paul has
+// looked: the journal records it, and a resume refuses again.
+var (
+ ErrStopPreserved = errors.New("adopt: preserved-changed")
+ ErrStopConflict = errors.New("adopt: agent-keys-conflict")
+ ErrStopForeign = errors.New("adopt: agent-keys-foreign")
+)
+
+// maxAttempts bounds the PUTs of one write or one rollback.
+const maxAttempts = 3
+
+// sqidShape is a Home team sqid: the sqids alphabet, nothing else.
+var sqidShape = regexp.MustCompile(`^[A-Za-z0-9]{1,64}$`)
+
+func varsOf(l carlosop.Layer) map[string]carlosop.Var {
+ m := make(map[string]carlosop.Var, len(l.Vars))
+ for _, v := range l.Vars {
+ m[v.Key] = v
+ }
+ return m
+}
+
+// preservedEqual reports whether read holds every key of baseline other
+// than sent's, each with its kind and digest. A key read adds is not a
+// change: a platform writer's new key is reported elsewhere, never fatal.
+func preservedEqual(baseline, read carlosop.Layer, sent map[string]string) bool {
+ if baseline.Bundle != read.Bundle {
+ return false
+ }
+ now := varsOf(read)
+ for _, b := range baseline.Vars {
+ if _, ours := sent[b.Key]; ours {
+ continue
+ }
+ a, ok := now[b.Key]
+ if !ok || a.Kind != b.Kind || a.Digest != b.Digest {
+ return false
+ }
+ }
+ return true
+}
+
+// agentState counts sent's keys in read: those holding exactly what was
+// sent (a plain var with its digest), and those absent.
+func agentState(read carlosop.Layer, sent map[string]string) (mine, absent int) {
+ now := varsOf(read)
+ for k, v := range sent {
+ got, ok := now[k]
+ switch {
+ case !ok:
+ absent++
+ case got.Kind == "env" && got.Digest == carlosop.EnvDigest(v):
+ mine++
+ }
+ }
+ return mine, absent
+}
+
+// Classify takes 522 §4.7's first matching branch for a reread of the
+// write layer, against the baseline's stored layer and what was sent.
+func Classify(baseline, read carlosop.Layer, sent map[string]string) Branch {
+ if !preservedEqual(baseline, read, sent) {
+ return StopPreservedChanged
+ }
+ mine, absent := agentState(read, sent)
+ switch {
+ case len(sent) != 2:
+ return StopConflict
+ case mine == 2:
+ return Landed
+ case absent == 2:
+ return Retry
+ }
+ return StopConflict
+}
+
+// ClassifyRollback takes the first matching rollback branch. Our keys
+// are unset whatever else moved: a rollback stops delegated access, and
+// refusing it because a platform writer resealed some other key would
+// leave that access live.
+func ClassifyRollback(baseline, read carlosop.Layer, sent map[string]string) RollbackBranch {
+ mine, absent := agentState(read, sent)
+ switch {
+ case len(sent) != 2:
+ return StopForeign
+ case mine == 2:
+ return RetryUnset
+ case absent == 2 && preservedEqual(baseline, read, sent):
+ return RolledBack
+ case absent != 2:
+ return StopForeign
+ }
+ return RollbackStopPreservedChanged
+}
+
+// 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.
+var (
+ writeNext = map[string][]string{
+ "": {"sent"},
+ "sent": {"sent", "landed", "stopped"},
+ }
+ rollbackNext = map[string][]string{
+ "": {"sent", "unset", "stopped"},
+ "sent": {"sent", "unset", "stopped"},
+ "unset": {"unset", "restarted"},
+ }
+)
+
+func sameSent(a, b map[string]string) bool {
+ if len(a) != len(b) {
+ return false
+ }
+ for k, v := range a {
+ if bv, ok := b[k]; !ok || bv != v {
+ return false
+ }
+ }
+ return true
+}
+
+// advanceWrite journals next if the app's write may move to it, and if
+// it sends what the journal already says was sent.
+func advanceWrite(ctx context.Context, s *Store, next WriteRecord) error {
+ cur, ok, err := s.Write(ctx, next.App)
+ if err != nil {
+ return err
+ }
+ from := ""
+ if ok {
+ from = cur.State
+ if !sameSent(cur.Sent, next.Sent) {
+ return errors.New("adopt: sent-mismatch: the journal's write sent other values")
+ }
+ }
+ if !slices.Contains(writeNext[from], next.State) {
+ return fmt.Errorf("adopt: the write journal cannot go from %q to %q", from, next.State)
+ }
+ return s.SaveWrite(ctx, next)
+}
+
+// advanceRollback journals next if the app's rollback may move to it.
+func advanceRollback(ctx context.Context, s *Store, next RollbackRecord) error {
+ cur, ok, err := s.Rollback(ctx, next.App)
+ if err != nil {
+ return err
+ }
+ from := ""
+ if ok {
+ from = cur.State
+ }
+ if !slices.Contains(rollbackNext[from], next.State) {
+ return fmt.Errorf("adopt: the rollback journal cannot go from %q to %q", from, next.State)
+ }
+ return s.SaveRollback(ctx, next)
+}
+
+// stoppedErr is the error a stopped record answers with on a resume.
+func stoppedErr(code string) error {
+ stop := ErrStopConflict
+ switch code {
+ case "preserved-changed":
+ stop = ErrStopPreserved
+ case "agent-keys-foreign":
+ stop = ErrStopForeign
+ }
+ return fmt.Errorf("%w: the journal says stopped (%s)", stop, code)
+}
+
+// lost reports whether err leaves a write's outcome unknown, so that only
+// a reread can tell: a 412, or no answer at all. A refusal the console
+// answered (any other status) wrote nothing and is returned as it is.
+func lost(err error) bool {
+ if errors.Is(err, carlosop.ErrVersionMismatch) {
+ return true
+ }
+ var se *carlosop.StatusError
+ return !errors.As(err, &se) && !errors.Is(err, carlosop.ErrNoConditional) && !errors.Is(err, carlosop.ErrNotFound)
+}
+
+// exactly reports whether got names each of keys once and nothing else.
+func exactly(got []string, keys [2]string) bool {
+ return len(got) == 2 && got[0] != got[1] && slices.Contains(got, keys[0]) && slices.Contains(got, keys[1])
+}
+
+// writeReceiptOK checks a write's 200: it set exactly the two keys, unset
+// nothing, carries the digest of what was sent for each and no other, was
+// made against ifVersion, and moved no other layer.
+func writeReceiptOK(rc carlosop.Receipt, keys [2]string, sent map[string]string, ifVersion string) bool {
+ if !exactly(rc.Set, keys) || len(rc.Unset) != 0 || len(rc.UnsetAbsent) != 0 || rc.VersionBefore != ifVersion {
+ return false
+ }
+ if len(rc.Digests) != 2 {
+ return false
+ }
+ for _, k := range keys {
+ if rc.Digests[k] != carlosop.EnvDigest(sent[k]) {
+ return false
+ }
+ }
+ for _, o := range rc.Others {
+ // A side the console could not read is empty: not proof.
+ if o.Before == "" || o.Before != o.After {
+ return false
+ }
+ }
+ return true
+}
+
+// unsetReceiptOK checks a rollback's 200: the two keys, each removed or
+// already absent, once, and nothing set. Already absent is accepted so a
+// retry after a committed answer that was lost passes.
+func unsetReceiptOK(rc carlosop.Receipt, keys [2]string) bool {
+ if len(rc.Set) != 0 {
+ return false
+ }
+ return exactly(append(append([]string{}, rc.Unset...), rc.UnsetAbsent...), keys)
+}
+
+// WriteAgentKeys writes app's two agent keys, <P>_AGENT_ISSUER = Issuer
+// and <P>_AGENT_TEAM = sqid, in one conditional PUT to the canonical
+// host's write layer. It answers the dry-run description of the write.
+//
+// 1. A landed write is done: nothing is read or sent. A stopped one is
+// refused again. Once a rollback is journalled, configure refuses.
+// 2. Preflight runs on a fresh read, with mine set to the journal's sent
+// values; any code refuses it, with nothing written.
+// 3. The baseline comes from the journal, or is this preflight's
+// snapshot, sealed and stored. A journalled baseline that no longer
+// describes the host's identity or write layer refuses the write.
+// 4. The write is journalled as sent, then sent with if_version the
+// baseline's version.
+// 5. A 200 must carry a receipt for exactly this write
+// (receipt-mismatch, ErrStopConflict, otherwise).
+// 6. A 412 or a lost answer is reread and classified: landed is done;
+// retry resends with the version just read, at most three PUTs in
+// all (retry-exhausted); a stop is journalled and returned. The
+// baseline is never retaken.
+//
+// A console that refuses if_version (carlosop.ErrNoConditional) stops the
+// run with the record left at sent, code no-conditional. Without apply,
+// it reads and refuses as it would, and stores and sends nothing.
+func WriteAgentKeys(ctx context.Context, c *carlosop.Client, h *http.Client, s *Store, app provision.App, sqid string, apply bool) (string, error) {
+ switch {
+ case c == nil || h == nil || s == nil:
+ return "", errors.New("adopt: configure needs a console, a client and the journal")
+ case !sqidShape.MatchString(sqid):
+ return "", errors.New("adopt: the team is not a sqid")
+ }
+ keys := AgentKeys(app)
+ sent := map[string]string{keys[0]: Issuer, keys[1]: sqid}
+ if _, ok, err := s.Rollback(ctx, app.Slug); err != nil {
+ return "", err
+ } else if ok {
+ return "", errors.New("adopt: configure refused: rollback-recorded")
+ }
+ rec, have, err := s.Write(ctx, app.Slug)
+ if err != nil {
+ return "", err
+ }
+ if have {
+ if !sameSent(rec.Sent, sent) {
+ return "", errors.New("adopt: configure refused: sent-mismatch")
+ }
+ switch rec.State {
+ case "landed":
+ base, ok, err := s.Baseline(ctx, app.Slug)
+ if err != nil {
+ return "", err
+ }
+ if !ok {
+ return "", errors.New("adopt: the journal has a landed write and no baseline")
+ }
+ return WriteSummary(keys, base.Layer.Bundle), nil
+ case "stopped":
+ return "", stoppedErr(rec.Code)
+ }
+ }
+ var mine map[string]string
+ if have {
+ mine = rec.Sent
+ }
+ fresh, codes, err := Preflight(ctx, c, h, app, mine)
+ if err != nil {
+ return "", err
+ }
+ if len(codes) > 0 {
+ return "", errors.New("adopt: configure refused: " + strings.Join(codes, ", "))
+ }
+ base, ok, err := s.Baseline(ctx, app.Slug)
+ if err != nil {
+ return "", err
+ }
+ if ok {
+ var moved []string
+ if base.WriteLayer != fresh.WriteLayer || base.Layer.Bundle != fresh.Layer.Bundle {
+ moved = append(moved, "write-layer-moved")
+ }
+ for _, code := range SameIdentity(base.Identity, fresh.Identity) {
+ moved = append(moved, "identity-"+code)
+ }
+ if len(moved) > 0 {
+ return "", errors.New("adopt: configure refused: " + strings.Join(moved, ", "))
+ }
+ } else {
+ base = fresh
+ }
+ summary := WriteSummary(keys, base.Layer.Bundle)
+ if !apply {
+ return summary, nil
+ }
+ if !ok {
+ if err := s.SaveBaseline(ctx, app.Slug, base); err != nil {
+ return "", err
+ }
+ }
+ w := WriteRecord{App: app.Slug, State: "sent", Sent: sent}
+ if err := advanceWrite(ctx, s, w); err != nil {
+ return "", err
+ }
+ stop := func(code string, e error) (string, error) {
+ w.State, w.Code = "stopped", code
+ if err := advanceWrite(ctx, s, w); err != nil {
+ return "", err
+ }
+ return "", fmt.Errorf("%w (%s)", e, code)
+ }
+ ifVersion := base.Layer.Version
+ for attempt := 1; ; attempt++ {
+ rc, err := c.Put(ctx, app.Slug, carlosop.PutRequest{Environment: base.WriteLayer, Set: sent, IfVersion: ifVersion})
+ switch {
+ case err == nil:
+ if !writeReceiptOK(rc, keys, sent, ifVersion) {
+ // Kept, sealed, for Paul to look at.
+ w.Receipt = &rc
+ return stop("receipt-mismatch", ErrStopConflict)
+ }
+ w.State, w.Code, w.Receipt = "landed", "", &rc
+ if err := advanceWrite(ctx, s, w); err != nil {
+ return "", err
+ }
+ return summary, nil
+ case errors.Is(err, carlosop.ErrNoConditional):
+ w.Code = "no-conditional"
+ if serr := advanceWrite(ctx, s, w); serr != nil {
+ return "", serr
+ }
+ return "", err
+ case !lost(err):
+ return "", err
+ }
+ read, err := c.Config(ctx, app.Slug, base.WriteLayer)
+ if err != nil {
+ return "", err
+ }
+ switch Classify(base.Layer, read, sent) {
+ case Landed:
+ w.State, w.Code = "landed", ""
+ if err := advanceWrite(ctx, s, w); err != nil {
+ return "", err
+ }
+ return summary, nil
+ case StopPreservedChanged:
+ return stop("preserved-changed", ErrStopPreserved)
+ case Retry:
+ default:
+ return stop("agent-keys-conflict", ErrStopConflict)
+ }
+ if attempt >= maxAttempts {
+ w.Code = "retry-exhausted"
+ if err := advanceWrite(ctx, s, w); err != nil {
+ return "", err
+ }
+ return "", errors.New("adopt: retry-exhausted: the layer kept moving")
+ }
+ ifVersion = read.Version
+ }
+}
+
+// CaptureAfter takes and stores app's after snapshot, once the restart
+// has passed Delivered against the baseline. It needs the baseline and a
+// landed write, and refuses with ErrStopPreserved, storing nothing,
+// unless a fresh observation:
+//
+// - preserves the baseline (Preserved is empty: every key but the two
+// added, by digest, kind and source, every untouched layer and the
+// identity);
+// - holds both agent keys as plain vars from the write layer, with the
+// digests of what was sent (agent-key:<KEY>);
+// - holds no team-mode key (team-mode-<KEY>).
+//
+// A fresh probe that does not pass Delivered is after-not-delivered. A
+// key a platform writer added is not a refusal; NewKeys reports it.
+func CaptureAfter(ctx context.Context, c *carlosop.Client, h *http.Client, s *Store, app provision.App) (Snapshot, error) {
+ if s == nil {
+ return Snapshot{}, errors.New("adopt: no adoption journal")
+ }
+ base, ok, err := s.Baseline(ctx, app.Slug)
+ if err != nil {
+ return Snapshot{}, err
+ }
+ if !ok {
+ return Snapshot{}, errors.New("adopt: after-baseline-missing")
+ }
+ w, ok, err := s.Write(ctx, app.Slug)
+ if err != nil {
+ return Snapshot{}, err
+ }
+ if !ok || w.State != "landed" {
+ return Snapshot{}, errors.New("adopt: after-write-not-landed")
+ }
+ after, err := Observe(ctx, c, h, app)
+ if err != nil {
+ return Snapshot{}, err
+ }
+ keys := AgentKeys(app)
+ codes := Preserved(base, after, keys)
+ for _, k := range keys {
+ v := findVar(after.Vars, k)
+ if v == nil || v.Kind != "env" || v.From != layerName(base.WriteLayer) || v.Digest != carlosop.EnvDigest(w.Sent[k]) {
+ codes = append(codes, "agent-key:"+k)
+ }
+ }
+ for _, k := range TeamModeKeys(app, after.Vars) {
+ codes = append(codes, "team-mode-"+k)
+ }
+ if len(codes) > 0 {
+ return Snapshot{}, fmt.Errorf("%w: %s", ErrStopPreserved, strings.Join(sortedSet(codes), ", "))
+ }
+ if err := Delivered(base.Delivery, after.Delivery); err != nil {
+ return Snapshot{}, fmt.Errorf("adopt: after-not-delivered: %w", err)
+ }
+ if err := s.SaveAfter(ctx, app.Slug, after); err != nil {
+ return Snapshot{}, err
+ }
+ return after, nil
+}
+
+// RollbackAgentKeys removes the two agent keys configure wrote, then
+// restarts the canonical host until the app is back to its baseline
+// 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
+// (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.
+//
+// The restart goes through RestartAndWait, so through RestartCanonical's
+// dry run, and waits for Reverted against the baseline: removing the
+// stored keys does not stop the running process. Only then is the
+// rollback restarted. A restart that fails or never reverts leaves it at
+// unset with code restart-failed. Without apply, it reads, classifies and
+// makes the restart's dry run, and stores and sends nothing else.
+func RollbackAgentKeys(ctx context.Context, c *carlosop.Client, h *http.Client, s *Store, app provision.App, apply bool) error {
+ if c == nil || h == nil || s == nil {
+ return errors.New("adopt: rollback needs a console, a client and the journal")
+ }
+ keys := AgentKeys(app)
+ w, ok, err := s.Write(ctx, app.Slug)
+ if err != nil {
+ return err
+ }
+ if !ok {
+ return errors.New("adopt: rollback-nothing-written")
+ }
+ if len(w.Sent) != 2 || w.Sent[keys[0]] == "" || w.Sent[keys[1]] == "" {
+ return errors.New("adopt: the journal's write does not name the agent keys")
+ }
+ base, ok, err := s.Baseline(ctx, app.Slug)
+ if err != nil {
+ return err
+ }
+ if !ok {
+ return errors.New("adopt: rollback-baseline-missing")
+ }
+ rb, have, err := s.Rollback(ctx, app.Slug)
+ if err != nil {
+ return err
+ }
+ 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 {
+ if apply {
+ rb.State, rb.Code = "stopped", code
+ if err := advanceRollback(ctx, s, rb); err != nil {
+ return err
+ }
+ }
+ return fmt.Errorf("%w (%s)", e, code)
+ }
+ for attempt := 1; ; attempt++ {
+ read, err := c.Config(ctx, app.Slug, base.WriteLayer)
+ if err != nil {
+ return err
+ }
+ switch ClassifyRollback(base.Layer, read, w.Sent) {
+ case RolledBack:
+ if apply {
+ rb.State, rb.Code = "unset", ""
+ if err := advanceRollback(ctx, s, rb); err != nil {
+ return err
+ }
+ }
+ return rollbackRestart(ctx, c, h, s, app, base, rb, apply)
+ case StopForeign:
+ return stop("agent-keys-foreign", ErrStopForeign)
+ case RollbackStopPreservedChanged:
+ return stop("preserved-changed", ErrStopPreserved)
+ case RetryUnset:
+ default:
+ return stop("agent-keys-foreign", ErrStopForeign)
+ }
+ if !apply {
+ return rollbackRestart(ctx, c, h, s, app, base, rb, false)
+ }
+ if attempt > maxAttempts {
+ rb.State, rb.Code = "sent", "retry-exhausted"
+ if err := advanceRollback(ctx, s, rb); err != nil {
+ return err
+ }
+ return errors.New("adopt: retry-exhausted: the layer kept moving")
+ }
+ rb.State, rb.Code = "sent", ""
+ if err := advanceRollback(ctx, s, rb); err != nil {
+ return err
+ }
+ rc, err := c.Put(ctx, app.Slug, carlosop.PutRequest{Environment: base.WriteLayer, Unset: keys[:], IfVersion: read.Version})
+ switch {
+ case err == nil:
+ if !unsetReceiptOK(rc, keys) {
+ rb.Receipt = &rc
+ return stop("receipt-mismatch", ErrStopConflict)
+ }
+ rb.State, rb.Receipt = "unset", &rc
+ if err := advanceRollback(ctx, s, rb); err != nil {
+ return err
+ }
+ return rollbackRestart(ctx, c, h, s, app, base, rb, true)
+ case errors.Is(err, carlosop.ErrNoConditional):
+ rb.Code = "no-conditional"
+ if serr := advanceRollback(ctx, s, rb); serr != nil {
+ return serr
+ }
+ return err
+ case !lost(err):
+ return err
+ }
+ }
+}
+
+// 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.
+func rollbackRestart(ctx context.Context, c *carlosop.Client, h *http.Client, s *Store, app provision.App, base Snapshot, rb RollbackRecord, apply bool) error {
+ _, err := RestartAndWait(ctx, c, h, app, base.Identity, func(d Delivery) error { return Reverted(base.Delivery, d) }, apply)
+ if !apply {
+ return err
+ }
+ if err != nil {
+ rb.State, rb.Code = "unset", "restart-failed"
+ if serr := advanceRollback(ctx, s, rb); serr != nil {
+ return errors.Join(err, serr)
+ }
+ return err
+ }
+ rb.State, rb.Code = "restarted", ""
+ return advanceRollback(ctx, s, rb)
+}
diff --git a/adopt/write_test.go b/adopt/write_test.go
new file mode 100644
index 0000000..015ed9e
--- /dev/null
+++ b/adopt/write_test.go
@@ -0,0 +1,1157 @@
+package adopt
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "net/http/httputil"
+ "net/url"
+ "strconv"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/alta/carlosop"
+)
+
+// fixtureSQID is the team the fixture's writes name.
+const fixtureSQID = "tQx7kPa"
+
+// writeFixture is one app on a fake console with an adoption journal.
+type writeFixture struct {
+ *carlosFixture
+ s *Store
+}
+
+func newWriteFixture(t *testing.T, slug string) *writeFixture {
+ t.Helper()
+ return &writeFixture{carlosFixture: newCarlosFixture(t, slug), s: newJournal(t)}
+}
+
+func (w *writeFixture) configure(apply bool) (string, error) {
+ return WriteAgentKeys(context.Background(), w.c, w.h, w.s, w.app, fixtureSQID, apply)
+}
+
+func (w *writeFixture) rollback(apply bool) error {
+ return RollbackAgentKeys(context.Background(), w.c, w.h, w.s, w.app, apply)
+}
+
+// puts is how many PUT /config requests the fake console has seen.
+func (x *carlosFixture) puts() int {
+ n := 0
+ for _, r := range x.f.Requests() {
+ if r == "PUT /config" {
+ n++
+ }
+ }
+ return n
+}
+
+// stored reports which of the agent keys the default bundle holds, and
+// whether each holds what the fixture's write sends.
+func (w *writeFixture) stored(t *testing.T) (present, ours [2]bool) {
+ t.Helper()
+ vars, _, _ := w.f.Layer(w.app.Slug, "")
+ keys := AgentKeys(w.app)
+ sent := w.sent()
+ for i, k := range keys {
+ v, ok := vars[k]
+ present[i] = ok
+ ours[i] = ok && v.Kind == "env" && v.Value == sent[k]
+ }
+ return present, ours
+}
+
+func (w *writeFixture) sent() map[string]string {
+ keys := AgentKeys(w.app)
+ return map[string]string{keys[0]: Issuer, keys[1]: fixtureSQID}
+}
+
+func (w *writeFixture) writeRecord(t *testing.T) (WriteRecord, bool) {
+ t.Helper()
+ r, ok, err := w.s.Write(context.Background(), w.app.Slug)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return r, ok
+}
+
+func (w *writeFixture) rollbackRecord(t *testing.T) (RollbackRecord, bool) {
+ t.Helper()
+ r, ok, err := w.s.Rollback(context.Background(), w.app.Slug)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return r, ok
+}
+
+func (w *writeFixture) baseline(t *testing.T) Snapshot {
+ t.Helper()
+ b, ok, err := w.s.Baseline(context.Background(), w.app.Slug)
+ if err != nil || !ok {
+ t.Fatalf("no baseline (ok %v, err %v)", ok, err)
+ }
+ return b
+}
+
+// nothingWritten fails if the console saw a PUT, the journal holds a
+// baseline or a write, or either agent key is stored.
+func (w *writeFixture) nothingWritten(t *testing.T) {
+ t.Helper()
+ if n := w.puts(); n != 0 {
+ t.Fatalf("PUTs = %d, want none", n)
+ }
+ if _, ok, _ := w.s.Baseline(context.Background(), w.app.Slug); ok {
+ t.Fatal("a baseline was stored")
+ }
+ if _, ok := w.writeRecord(t); ok {
+ t.Fatal("a write was journalled")
+ }
+}
+
+// noValues fails if err's text carries a value, digest or version.
+func noValues(t *testing.T, err error) {
+ t.Helper()
+ if err == nil {
+ return
+ }
+ for _, bad := range []string{"vd1:", "cv1:", fixtureSQID, Issuer, valueOrigin, valueVersion} {
+ if strings.Contains(err.Error(), bad) {
+ t.Fatalf("error carries %q: %v", bad, err)
+ }
+ }
+}
+
+// process models the app's process: it loads the stored agent keys when
+// it restarts, and its operations door answers agent-access's challenge
+// only while the config it last loaded held both. It starts as if it had
+// loaded at the current restart count with loaded as given.
+func (x *carlosFixture) process(loaded bool) {
+ keys := AgentKeys(x.app)
+ host := CanonicalHost(x.app)
+ var mu sync.Mutex
+ seen := x.f.RestartCount(host)
+ x.site.ops = func(w http.ResponseWriter) {
+ mu.Lock()
+ if n := x.f.RestartCount(host); n != seen {
+ vars, _, _ := x.f.Layer(x.app.Slug, "")
+ _, a := vars[keys[0]]
+ _, b := vars[keys[1]]
+ seen, loaded = n, a && b
+ }
+ on := loaded
+ mu.Unlock()
+ if on {
+ agent401(w)
+ return
+ }
+ w.WriteHeader(http.StatusNotFound)
+ }
+}
+
+// configured writes the keys, restarts until Delivered and captures the
+// after snapshot, as the configure phase does.
+func (w *writeFixture) configured(t *testing.T) Snapshot {
+ t.Helper()
+ fastPolls(t, 5*time.Millisecond, 2*time.Second)
+ w.process(false)
+ if _, err := w.configure(true); err != nil {
+ t.Fatalf("WriteAgentKeys: %v", err)
+ }
+ base := w.baseline(t)
+ ctx := context.Background()
+ if _, err := RestartAndWait(ctx, w.c, w.h, w.app, base.Identity, func(d Delivery) error { return Delivered(base.Delivery, d) }, true); err != nil {
+ t.Fatalf("RestartAndWait: %v", err)
+ }
+ after, err := CaptureAfter(ctx, w.c, w.h, w.s, w.app)
+ if err != nil {
+ t.Fatalf("CaptureAfter: %v", err)
+ }
+ return after
+}
+
+// once runs f the first time the returned hook is called.
+func once(f func()) func(string) {
+ var o sync.Once
+ return func(string) { o.Do(f) }
+}
+
+// putRewriter puts a proxy in front of the fake console that edits the
+// receipt of every successful PUT /config answer.
+func (x *carlosFixture) putRewriter(t *testing.T, edit func(rc map[string]any)) {
+ t.Helper()
+ target, err := url.Parse(x.f.URL())
+ if err != nil {
+ t.Fatal(err)
+ }
+ rp := httputil.NewSingleHostReverseProxy(target)
+ rp.ModifyResponse = func(resp *http.Response) error {
+ if resp.Request.Method != http.MethodPut || resp.StatusCode != 200 {
+ return nil
+ }
+ raw, err := io.ReadAll(resp.Body)
+ resp.Body.Close()
+ if err != nil {
+ return err
+ }
+ var answer map[string]any
+ if err := json.Unmarshal(raw, &answer); err != nil {
+ return err
+ }
+ edit(answer["receipt"].(map[string]any))
+ if raw, err = json.Marshal(answer); err != nil {
+ return err
+ }
+ resp.Body = io.NopCloser(bytes.NewReader(raw))
+ resp.ContentLength = int64(len(raw))
+ resp.Header.Set("Content-Length", strconv.Itoa(len(raw)))
+ return nil
+ }
+ srv := httptest.NewServer(rp)
+ t.Cleanup(srv.Close)
+ x.c = carlosop.New(srv.URL, fixtureAccount, x.f.Token())
+ t.Cleanup(x.c.Close)
+}
+
+// ---- Configure: the preflight is enforced by the write itself ----
+
+func TestConfigureCallsPreflightEvenWhenInvokedDirectly(t *testing.T) {
+ cases := map[string]func(w *writeFixture){
+ "home issuer": func(w *writeFixture) { w.f.SetVar("docs", "", "DOCS_HOME_ISSUER", "https://id.elsewhere.example") },
+ "healthz": func(w *writeFixture) { w.site.health = 503 },
+ "moving": func(w *writeFixture) {
+ w.f.AddInstance(carlosop.Instance{Host: "docs.oficina.works", App: "docs", Slug: "s-docs", Channel: "stable", Region: "eu",
+ CreatedAt: time.Date(2026, 3, 1, 0, 0, 0, 0, time.UTC), RecordSeq: 4, Move: json.RawMessage(`{"to":"us"}`)})
+ },
+ }
+ for name, edit := range cases {
+ t.Run(name, func(t *testing.T) {
+ w := newWriteFixture(t, "docs")
+ edit(w)
+ for _, apply := range []bool{false, true} {
+ _, err := w.configure(apply)
+ if err == nil || !strings.Contains(err.Error(), "configure refused") {
+ t.Fatalf("apply %v: err = %v, want a preflight refusal", apply, err)
+ }
+ noValues(t, err)
+ }
+ w.nothingWritten(t)
+ })
+ }
+}
+
+func TestConfigureRefusesForeignAgentKeys(t *testing.T) {
+ w := newWriteFixture(t, "docs")
+ // Even the very values the runner would send: it did not write them.
+ for k, v := range w.sent() {
+ w.f.SetVar("docs", "", k, v)
+ }
+ _, err := w.configure(true)
+ if err == nil || !strings.Contains(err.Error(), "agent-keys-present") {
+ t.Fatalf("err = %v, want agent-keys-present", err)
+ }
+ noValues(t, err)
+ w.nothingWritten(t)
+}
+
+func TestConfigureRefusesTeamMode(t *testing.T) {
+ w := newWriteFixture(t, "docs")
+ w.f.SetVar("docs", "", "DOCS_TEAM_ID", "team-id-value")
+ _, err := w.configure(true)
+ if err == nil || !strings.Contains(err.Error(), "team-mode-DOCS_TEAM_ID") {
+ t.Fatalf("err = %v, want team-mode-DOCS_TEAM_ID", err)
+ }
+ w.nothingWritten(t)
+}
+
+func TestConfigureRefusesInheritingNeighbour(t *testing.T) {
+ w := newWriteFixture(t, "docs")
+ w.neighbour("bare.docs.example", "")
+ _, err := w.configure(true)
+ if err == nil || !strings.Contains(err.Error(), "inherits-bare.docs.example") {
+ t.Fatalf("err = %v, want inherits-bare.docs.example", err)
+ }
+ w.nothingWritten(t)
+}
+
+func TestConfigureRefusesBadTeam(t *testing.T) {
+ w := newWriteFixture(t, "docs")
+ for _, sqid := range []string{"", " tQx7kPa", "t-1", "tQx7kPa\n"} {
+ if _, err := WriteAgentKeys(context.Background(), w.c, w.h, w.s, w.app, sqid, true); err == nil {
+ t.Fatalf("sqid %q accepted", sqid)
+ }
+ }
+ w.nothingWritten(t)
+}
+
+// ---- The write ----
+
+func TestWriteHappyPathReceiptChecked(t *testing.T) {
+ w := newWriteFixture(t, "docs")
+ _, beforeVersion, _ := w.f.Layer("docs", "")
+ summary, err := w.configure(true)
+ if err != nil {
+ t.Fatalf("WriteAgentKeys: %v", err)
+ }
+ if summary != "set DOCS_AGENT_ISSUER, DOCS_AGENT_TEAM on default" {
+ t.Fatalf("summary = %q", summary)
+ }
+ if n := w.puts(); n != 1 {
+ t.Fatalf("PUTs = %d", n)
+ }
+ if _, ours := w.stored(t); ours != [2]bool{true, true} {
+ t.Fatalf("stored keys ours = %v", ours)
+ }
+ base := w.baseline(t)
+ if base.Layer.Version != beforeVersion || findVar(base.Vars, "DOCS_AGENT_TEAM") != nil {
+ t.Fatal("the baseline is not the layer before the write")
+ }
+ rec, ok := w.writeRecord(t)
+ if !ok || rec.State != "landed" || rec.Receipt == nil || rec.Code != "" {
+ t.Fatalf("write record %v state %q code %q", ok, rec.State, rec.Code)
+ }
+ if rec.Receipt.VersionBefore != beforeVersion || rec.Receipt.Digests["DOCS_AGENT_TEAM"] != carlosop.EnvDigest(fixtureSQID) {
+ t.Fatal("the journalled receipt is not the write's")
+ }
+ if rec.Sent["DOCS_AGENT_ISSUER"] != Issuer || rec.Sent["DOCS_AGENT_TEAM"] != fixtureSQID || len(rec.Sent) != 2 {
+ t.Fatal("the journal does not hold what was sent")
+ }
+
+ // Landed is the end: a second call sends nothing at all.
+ n := len(w.f.Requests())
+ if again, err := w.configure(true); err != nil || again != summary {
+ t.Fatalf("second call: %q %v", again, err)
+ }
+ if got := len(w.f.Requests()); got != n {
+ t.Fatalf("a landed write made %d more requests", got-n)
+ }
+ // A call naming another team never rides on the landed record.
+ if _, err := WriteAgentKeys(context.Background(), w.c, w.h, w.s, w.app, "tOther9", true); err == nil {
+ t.Fatal("a landed write accepted another team")
+ }
+}
+
+// A write to a named environment says so.
+func TestWriteSummaryNamesTheWriteLayer(t *testing.T) {
+ w := newWriteFixture(t, "docs")
+ w.f.SetVar("docs", "prod", "DOCS_HOME_ISSUER", HomeIssuerOrigin)
+ w.f.SetVar("docs", "prod", "DOCS_HOME_CONSUMER_ID", "docs")
+ w.f.AddInstance(carlosop.Instance{Host: "docs.oficina.works", App: "docs", Slug: "s-docs", Environment: "prod", Channel: "stable", Region: "eu",
+ CreatedAt: time.Date(2026, 3, 1, 0, 0, 0, 0, time.UTC), RecordSeq: 4, ReplicaAssignment: json.RawMessage(`{"boxes":["b1"]}`)})
+ summary, err := w.configure(true)
+ if err != nil {
+ t.Fatalf("WriteAgentKeys: %v", err)
+ }
+ if summary != "set DOCS_AGENT_ISSUER, DOCS_AGENT_TEAM on prod" {
+ t.Fatalf("summary = %q", summary)
+ }
+ vars, _, _ := w.f.Layer("docs", "prod")
+ if vars["DOCS_AGENT_TEAM"].Value != fixtureSQID {
+ t.Fatal("the keys were not written to the environment")
+ }
+ if dvars, _, _ := w.f.Layer("docs", ""); len(dvars) != 4 {
+ t.Fatalf("the default bundle changed: %d vars", len(dvars))
+ }
+}
+
+func TestWriteLostAnswerLanded(t *testing.T) {
+ w := newWriteFixture(t, "docs")
+ w.f.LoseNextAnswer()
+ if _, err := w.configure(true); err != nil {
+ t.Fatalf("WriteAgentKeys: %v", err)
+ }
+ if n := w.puts(); n != 1 {
+ t.Fatalf("PUTs = %d, want exactly one", n)
+ }
+ rec, _ := w.writeRecord(t)
+ if rec.State != "landed" || rec.Receipt != nil {
+ t.Fatalf("state %q receipt %v", rec.State, rec.Receipt != nil)
+ }
+ if _, ours := w.stored(t); ours != [2]bool{true, true} {
+ t.Fatalf("ours = %v", ours)
+ }
+}
+
+// A resume after a crash between the PUT and its journal entry: the
+// record still says sent, the keys are stored, and the resume finds the
+// write landed by rereading, never by writing over it.
+func TestWriteResumeAfterCrashFindsLanded(t *testing.T) {
+ w := newWriteFixture(t, "docs")
+ ctx := context.Background()
+ // The crash, as the journal and the console were left by it.
+ base, err := Observe(ctx, w.c, w.h, w.app)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := w.s.SaveBaseline(ctx, "docs", base); err != nil {
+ t.Fatal(err)
+ }
+ if err := w.s.SaveWrite(ctx, WriteRecord{App: "docs", State: "sent", Sent: w.sent()}); err != nil {
+ t.Fatal(err)
+ }
+ for k, v := range w.sent() {
+ w.f.SetVar("docs", "", k, v)
+ }
+ _, landedVersion, _ := w.f.Layer("docs", "")
+ if _, err := w.configure(true); err != nil {
+ t.Fatalf("resume: %v", err)
+ }
+ if rec, _ := w.writeRecord(t); rec.State != "landed" {
+ t.Fatalf("state %q after resume", rec.State)
+ }
+ // The one PUT carried the baseline version and was refused.
+ if n := w.puts(); n != 1 {
+ t.Fatalf("PUTs = %d", n)
+ }
+ if _, v, _ := w.f.Layer("docs", ""); v != landedVersion {
+ t.Fatal("the resume wrote over the landed keys")
+ }
+}
+
+func TestWriteRetriesAfterUnrelatedKeyAdded(t *testing.T) {
+ w := newWriteFixture(t, "docs")
+ _, beforeVersion, _ := w.f.Layer("docs", "")
+ w.f.BeforePut = once(func() { w.f.PlatformWrite("docs", "", "DOCS_MAIL_EVENTS_URL", "https://mail.example/hook") })
+ if _, err := w.configure(true); err != nil {
+ t.Fatalf("WriteAgentKeys: %v", err)
+ }
+ if n := w.puts(); n != 2 {
+ t.Fatalf("PUTs = %d, want a 412 then the retry", n)
+ }
+ base := w.baseline(t)
+ if base.Layer.Version != beforeVersion || findVar(base.Vars, "DOCS_MAIL_EVENTS_URL") != nil {
+ t.Fatal("the baseline moved: it was retaken after the retry")
+ }
+ for _, v := range base.Layer.Vars {
+ if v.Key == "DOCS_MAIL_EVENTS_URL" {
+ t.Fatal("the baseline absorbed the unrelated key")
+ }
+ }
+ rec, _ := w.writeRecord(t)
+ if rec.State != "landed" || rec.Receipt == nil || rec.Receipt.VersionBefore == beforeVersion {
+ t.Fatalf("state %q: the landed receipt is not the retry's", rec.State)
+ }
+ vars, _, _ := w.f.Layer("docs", "")
+ if _, ok := vars["DOCS_MAIL_EVENTS_URL"]; !ok {
+ t.Fatal("the retry lost the platform's key")
+ }
+}
+
+func TestWriteStopsWhenPreservedKeyResealed(t *testing.T) {
+ w := newWriteFixture(t, "docs")
+ w.f.BeforePut = once(func() { w.f.SetSecret("docs", "", "DOCS_INSTANCE_KEY") })
+ _, err := w.configure(true)
+ if !errors.Is(err, ErrStopPreserved) {
+ t.Fatalf("err = %v, want ErrStopPreserved", err)
+ }
+ noValues(t, err)
+ if n := w.puts(); n != 1 {
+ t.Fatalf("PUTs = %d", n)
+ }
+ if present, _ := w.stored(t); present != [2]bool{} {
+ t.Fatalf("keys present %v", present)
+ }
+ rec, _ := w.writeRecord(t)
+ if rec.State != "stopped" || rec.Code != "preserved-changed" {
+ t.Fatalf("state %q code %q", rec.State, rec.Code)
+ }
+ // Stopped is the end: a resume refuses and sends nothing.
+ n := w.puts()
+ if _, err := w.configure(true); !errors.Is(err, ErrStopPreserved) {
+ t.Fatalf("resume err = %v", err)
+ }
+ if w.puts() != n {
+ t.Fatal("a stopped write was sent again")
+ }
+}
+
+func TestWriteStopsOnPartialOrForeignAgentKeys(t *testing.T) {
+ cases := map[string]func(f *writeFixture){
+ "partial": func(w *writeFixture) { w.f.SetVar("docs", "", "DOCS_AGENT_ISSUER", Issuer) },
+ "foreign": func(w *writeFixture) {
+ w.f.SetVar("docs", "", "DOCS_AGENT_ISSUER", Issuer)
+ w.f.SetVar("docs", "", "DOCS_AGENT_TEAM", "tOther9")
+ },
+ "kind": func(w *writeFixture) {
+ w.f.SetVar("docs", "", "DOCS_AGENT_ISSUER", Issuer)
+ w.f.SetSecret("docs", "", "DOCS_AGENT_TEAM")
+ },
+ }
+ for name, edit := range cases {
+ t.Run(name, func(t *testing.T) {
+ w := newWriteFixture(t, "docs")
+ w.f.BeforePut = once(func() { edit(w) })
+ _, err := w.configure(true)
+ if !errors.Is(err, ErrStopConflict) {
+ t.Fatalf("err = %v, want ErrStopConflict", err)
+ }
+ noValues(t, err)
+ if n := w.puts(); n != 1 {
+ t.Fatalf("PUTs = %d: the other writer's keys were overwritten", n)
+ }
+ rec, _ := w.writeRecord(t)
+ if rec.State != "stopped" || rec.Code != "agent-keys-conflict" {
+ t.Fatalf("state %q code %q", rec.State, rec.Code)
+ }
+ })
+ }
+}
+
+func TestWriteRejectsMalformedReceipts(t *testing.T) {
+ other := "cv1:" + strings.Repeat("9", 64)
+ cases := map[string]func(rc map[string]any){
+ "extra set key": func(rc map[string]any) { rc["set"] = append(rc["set"].([]any), "DOCS_ORIGIN") },
+ "missing digest": func(rc map[string]any) { delete(rc["digests"].(map[string]any), "DOCS_AGENT_TEAM") },
+ "wrong digest": func(rc map[string]any) {
+ rc["digests"].(map[string]any)["DOCS_AGENT_TEAM"] = carlosop.EnvDigest("tOther9")
+ },
+ "unset not empty": func(rc map[string]any) { rc["unset"] = []any{"DOCS_ORIGIN"} },
+ "unset_absent set": func(rc map[string]any) { rc["unset_absent"] = []any{"DOCS_ORIGIN"} },
+ "others moved": func(rc map[string]any) {
+ rc["others"] = map[string]any{"default": map[string]any{"before": rc["version_before"], "after": other}}
+ },
+ "version before": func(rc map[string]any) { rc["version_before"] = other },
+ }
+ for name, edit := range cases {
+ t.Run(name, func(t *testing.T) {
+ w := newWriteFixture(t, "docs")
+ w.putRewriter(t, edit)
+ _, err := w.configure(true)
+ if !errors.Is(err, ErrStopConflict) {
+ t.Fatalf("err = %v, want ErrStopConflict", err)
+ }
+ noValues(t, err)
+ if n := w.puts(); n != 1 {
+ t.Fatalf("PUTs = %d", n)
+ }
+ rec, _ := w.writeRecord(t)
+ if rec.State != "stopped" || rec.Code != "receipt-mismatch" || rec.Receipt == nil {
+ t.Fatalf("state %q code %q", rec.State, rec.Code)
+ }
+ })
+ }
+}
+
+func TestWriteRefusesWithoutConditionalSupport(t *testing.T) {
+ w := newWriteFixture(t, "docs")
+ w.f.NoConditional()
+ _, err := w.configure(true)
+ if !errors.Is(err, carlosop.ErrNoConditional) {
+ t.Fatalf("err = %v, want ErrNoConditional", err)
+ }
+ if n := w.puts(); n != 1 {
+ t.Fatalf("PUTs = %d: retried a console that refuses if_version", n)
+ }
+ if present, _ := w.stored(t); present != [2]bool{} {
+ t.Fatal("keys were written")
+ }
+ // Nothing landed, so the record stays sent, with the reason.
+ rec, _ := w.writeRecord(t)
+ if rec.State != "sent" || rec.Code != "no-conditional" {
+ t.Fatalf("state %q code %q", rec.State, rec.Code)
+ }
+}
+
+func TestWriteGivesUpAfterThreeAttempts(t *testing.T) {
+ w := newWriteFixture(t, "docs")
+ n := 0
+ w.f.BeforePut = func(string) {
+ n++
+ w.f.PlatformWrite("docs", "", "DOCS_MAIL_EVENTS_URL", "https://mail.example/"+strconv.Itoa(n))
+ }
+ _, err := w.configure(true)
+ if err == nil || !strings.Contains(err.Error(), "retry-exhausted") {
+ t.Fatalf("err = %v, want retry-exhausted", err)
+ }
+ if got := w.puts(); got != 3 {
+ t.Fatalf("PUTs = %d, want 3", got)
+ }
+ rec, _ := w.writeRecord(t)
+ if rec.State != "sent" || rec.Code != "retry-exhausted" {
+ t.Fatalf("state %q code %q", rec.State, rec.Code)
+ }
+ // A resume once the writer is quiet lands, still on the first baseline.
+ w.f.BeforePut = nil
+ if _, err := w.configure(true); err != nil {
+ t.Fatalf("resume: %v", err)
+ }
+ if rec, _ := w.writeRecord(t); rec.State != "landed" {
+ t.Fatalf("state %q", rec.State)
+ }
+}
+
+func TestWriteDryRunSendsNothing(t *testing.T) {
+ w := newWriteFixture(t, "docs")
+ _, beforeVersion, _ := w.f.Layer("docs", "")
+ summary, err := w.configure(false)
+ if err != nil {
+ t.Fatalf("dry run: %v", err)
+ }
+ if summary != "set DOCS_AGENT_ISSUER, DOCS_AGENT_TEAM on default" {
+ t.Fatalf("summary = %q", summary)
+ }
+ w.nothingWritten(t)
+ if _, v, _ := w.f.Layer("docs", ""); v != beforeVersion {
+ t.Fatal("the layer moved")
+ }
+ for _, r := range w.f.Requests() {
+ if !strings.HasPrefix(r, "GET ") {
+ t.Fatalf("a dry run sent %q", r)
+ }
+ }
+}
+
+// A resume never writes against a baseline that describes another
+// instance or layer.
+func TestWriteRefusesWhenBaselineNoLongerDescribesTheHost(t *testing.T) {
+ w := newWriteFixture(t, "docs")
+ ctx := context.Background()
+ snap, err := Observe(ctx, w.c, w.h, w.app)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := w.s.SaveBaseline(ctx, "docs", snap); err != nil {
+ t.Fatal(err)
+ }
+ w.f.AddInstance(carlosop.Instance{Host: "docs.oficina.works", App: "docs", Slug: "s-docs-new", Channel: "stable", Region: "eu",
+ CreatedAt: time.Date(2026, 11, 1, 0, 0, 0, 0, time.UTC), RecordSeq: 9})
+ _, err = w.configure(true)
+ if err == nil || !strings.Contains(err.Error(), "identity-storage") {
+ t.Fatalf("err = %v, want identity-storage", err)
+ }
+ if n := w.puts(); n != 0 {
+ t.Fatalf("PUTs = %d", n)
+ }
+}
+
+func TestWriteRefusedOnceRollbackRecorded(t *testing.T) {
+ w := newWriteFixture(t, "docs")
+ if err := w.s.SaveRollback(context.Background(), RollbackRecord{App: "docs", State: "restarted"}); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := w.configure(true); err == nil || !strings.Contains(err.Error(), "rollback-recorded") {
+ t.Fatalf("err = %v, want rollback-recorded", err)
+ }
+ w.nothingWritten(t)
+}
+
+// ---- Classification ----
+
+func layerOf(vars ...carlosop.Var) carlosop.Layer {
+ return carlosop.Layer{Bundle: "default", Version: vA, Vars: vars}
+}
+
+func TestWriteClassifyBranchesInOrder(t *testing.T) {
+ sent := map[string]string{"DOCS_AGENT_ISSUER": Issuer, "DOCS_AGENT_TEAM": fixtureSQID}
+ iss := carlosop.Var{Key: "DOCS_AGENT_ISSUER", Kind: "env", Value: Issuer, Digest: carlosop.EnvDigest(Issuer)}
+ team := carlosop.Var{Key: "DOCS_AGENT_TEAM", Kind: "env", Value: fixtureSQID, Digest: carlosop.EnvDigest(fixtureSQID)}
+ sec := carlosop.Var{Key: "DOCS_INSTANCE_KEY", Kind: "secret", Digest: dA}
+ org := carlosop.Var{Key: "DOCS_ORIGIN", Kind: "env", Value: "o", Digest: dB}
+ base := layerOf(sec, org)
+ resealed := sec
+ resealed.Digest = dC
+ asSecret := sec
+ asSecret.Kind = "env"
+ foreignTeam := team
+ foreignTeam.Digest = carlosop.EnvDigest("tOther9")
+ secretTeam := carlosop.Var{Key: "DOCS_AGENT_TEAM", Kind: "secret", Digest: carlosop.EnvDigest(fixtureSQID)}
+ unrelated := carlosop.Var{Key: "DOCS_MAIL_EVENTS_URL", Kind: "env", Digest: dC}
+ cases := map[string]struct {
+ read carlosop.Layer
+ want Branch
+ }{
+ "landed": {layerOf(sec, org, iss, team), Landed},
+ "landed beside a new key": {layerOf(sec, org, iss, team, unrelated), Landed},
+ "absent": {layerOf(sec, org), Retry},
+ "absent beside a new key": {layerOf(sec, org, unrelated), Retry},
+ "resealed": {layerOf(resealed, org), StopPreservedChanged},
+ "gone": {layerOf(org), StopPreservedChanged},
+ "kind": {layerOf(asSecret, org), StopPreservedChanged},
+ "preserved first": {layerOf(resealed, org, iss), StopPreservedChanged},
+ "preserved first, landed": {layerOf(org, iss, team), StopPreservedChanged},
+ "partial": {layerOf(sec, org, iss), StopConflict},
+ "foreign": {layerOf(sec, org, iss, foreignTeam), StopConflict},
+ "secret of the sent value": {layerOf(sec, org, iss, secretTeam), StopConflict},
+ }
+ for name, tc := range cases {
+ if got := Classify(base, tc.read, sent); got != tc.want {
+ t.Errorf("%s: Classify = %d, want %d", name, got, tc.want)
+ }
+ }
+ other := layerOf(sec, org)
+ other.Bundle = "prod"
+ if got := Classify(base, other, sent); got != StopPreservedChanged {
+ t.Errorf("another bundle: %d", got)
+ }
+ if got := Classify(base, layerOf(sec, org), map[string]string{"DOCS_AGENT_ISSUER": Issuer}); got != StopConflict {
+ t.Errorf("one sent key: %d", got)
+ }
+ if Branch(0) == Landed || RollbackBranch(0) == RolledBack {
+ t.Error("a zero branch reads as done")
+ }
+}
+
+func TestRollbackClassifyBranchesInOrder(t *testing.T) {
+ sent := map[string]string{"DOCS_AGENT_ISSUER": Issuer, "DOCS_AGENT_TEAM": fixtureSQID}
+ iss := carlosop.Var{Key: "DOCS_AGENT_ISSUER", Kind: "env", Value: Issuer, Digest: carlosop.EnvDigest(Issuer)}
+ team := carlosop.Var{Key: "DOCS_AGENT_TEAM", Kind: "env", Value: fixtureSQID, Digest: carlosop.EnvDigest(fixtureSQID)}
+ sec := carlosop.Var{Key: "DOCS_INSTANCE_KEY", Kind: "secret", Digest: dA}
+ base := layerOf(sec)
+ resealed := sec
+ resealed.Digest = dC
+ foreignTeam := team
+ foreignTeam.Digest = carlosop.EnvDigest("tOther9")
+ secretTeam := carlosop.Var{Key: "DOCS_AGENT_TEAM", Kind: "secret", Digest: carlosop.EnvDigest(fixtureSQID)}
+ cases := map[string]struct {
+ read carlosop.Layer
+ want RollbackBranch
+ }{
+ "ours": {layerOf(sec, iss, team), RetryUnset},
+ "ours, another key resealed": {layerOf(resealed, iss, team), RetryUnset},
+ "absent": {layerOf(sec), RolledBack},
+ "one": {layerOf(sec, iss), StopForeign},
+ "foreign": {layerOf(sec, iss, foreignTeam), StopForeign},
+ "kind": {layerOf(sec, iss, secretTeam), StopForeign},
+ "absent, resealed": {layerOf(resealed), RollbackStopPreservedChanged},
+ "absent, gone": {layerOf(), RollbackStopPreservedChanged},
+ }
+ for name, tc := range cases {
+ if got := ClassifyRollback(base, tc.read, sent); got != tc.want {
+ t.Errorf("%s: ClassifyRollback = %d, want %d", name, got, tc.want)
+ }
+ }
+}
+
+// The journal's states move one way only.
+func TestWriteJournalTransitions(t *testing.T) {
+ ctx := context.Background()
+ sent := map[string]string{"DOCS_AGENT_ISSUER": Issuer, "DOCS_AGENT_TEAM": fixtureSQID}
+ wr := func(state string) WriteRecord { return WriteRecord{App: "docs", State: state, Sent: sent} }
+ for _, path := range [][]string{{"landed"}, {"stopped"}, {"sent", "landed", "sent"}, {"sent", "landed", "stopped"}, {"sent", "stopped", "sent"}, {"sent", "stopped", "landed"}} {
+ s := newJournal(t)
+ var err error
+ for _, st := range path {
+ if err = advanceWrite(ctx, s, wr(st)); err != nil {
+ break
+ }
+ }
+ if err == nil {
+ t.Errorf("write path %v accepted", path)
+ }
+ }
+ s := newJournal(t)
+ for _, st := range []string{"sent", "sent", "landed"} {
+ if err := advanceWrite(ctx, s, wr(st)); err != nil {
+ t.Fatalf("write %s: %v", st, err)
+ }
+ }
+ s = newJournal(t)
+ if err := advanceWrite(ctx, s, wr("sent")); err != nil {
+ t.Fatal(err)
+ }
+ if err := advanceWrite(ctx, s, WriteRecord{App: "docs", State: "sent", Sent: map[string]string{"DOCS_AGENT_ISSUER": Issuer, "DOCS_AGENT_TEAM": "tOther9"}}); err == nil {
+ t.Error("the sent values changed under a sent record")
+ }
+
+ 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"}} {
+ s := newJournal(t)
+ var err error
+ for _, st := range path {
+ if err = advanceRollback(ctx, s, rb(st)); err != nil {
+ break
+ }
+ }
+ if err == nil {
+ t.Errorf("rollback path %v accepted", path)
+ }
+ }
+ s = newJournal(t)
+ for _, st := range []string{"sent", "sent", "unset", "unset", "restarted"} {
+ if err := advanceRollback(ctx, s, rb(st)); err != nil {
+ t.Fatalf("rollback %s: %v", st, err)
+ }
+ }
+}
+
+// ---- The after snapshot ----
+
+func TestAfterSnapshotRefusesSecretResealedBeforeCapture(t *testing.T) {
+ cases := map[string]func(w *writeFixture){
+ "resealed": func(w *writeFixture) { w.f.SetSecret("docs", "", "DOCS_INSTANCE_KEY") },
+ "gone": func(w *writeFixture) { w.f.Unset("docs", "", "DOCS_ORIGIN") },
+ "agent key": func(w *writeFixture) { w.f.SetVar("docs", "", "DOCS_AGENT_TEAM", "tOther9") },
+ "agent gone": func(w *writeFixture) { w.f.Unset("docs", "", "DOCS_AGENT_ISSUER") },
+ "team mode": func(w *writeFixture) { w.f.SetVar("docs", "", "DOCS_TEAM_ID", "team-id-value") },
+ "overlay": func(w *writeFixture) { w.f.SetOverlay("docs", "docs.oficina.works", "DOCS_ORIGIN", "x") },
+ }
+ for name, edit := range cases {
+ t.Run(name, func(t *testing.T) {
+ fastPolls(t, 5*time.Millisecond, 2*time.Second)
+ w := newWriteFixture(t, "docs")
+ w.process(false)
+ if _, err := w.configure(true); err != nil {
+ t.Fatalf("WriteAgentKeys: %v", err)
+ }
+ base := w.baseline(t)
+ ctx := context.Background()
+ if _, err := RestartAndWait(ctx, w.c, w.h, w.app, base.Identity, func(d Delivery) error { return Delivered(base.Delivery, d) }, true); err != nil {
+ t.Fatalf("RestartAndWait: %v", err)
+ }
+ edit(w)
+ _, err := CaptureAfter(ctx, w.c, w.h, w.s, w.app)
+ if !errors.Is(err, ErrStopPreserved) {
+ t.Fatalf("err = %v, want ErrStopPreserved", err)
+ }
+ noValues(t, err)
+ if _, ok, _ := w.s.After(ctx, "docs"); ok {
+ t.Fatal("an after snapshot was stored")
+ }
+ })
+ }
+}
+
+func TestAfterSnapshotStoredWhenPreserved(t *testing.T) {
+ w := newWriteFixture(t, "docs")
+ after := w.configured(t)
+ got, ok, err := w.s.After(context.Background(), "docs")
+ if err != nil || !ok || got.Layer.Version != after.Layer.Version {
+ t.Fatalf("after snapshot not stored (ok %v, err %v)", ok, err)
+ }
+ if after.Delivery.Ops != OpsAgent401 {
+ t.Fatalf("after ops %q", after.Delivery.Ops)
+ }
+ if v := findVar(after.Vars, "DOCS_AGENT_TEAM"); v == nil || v.Digest != carlosop.EnvDigest(fixtureSQID) {
+ t.Fatal("the after snapshot lacks the sent team")
+ }
+}
+
+func TestAfterSnapshotAcceptsUnrelatedNewKey(t *testing.T) {
+ fastPolls(t, 5*time.Millisecond, 2*time.Second)
+ w := newWriteFixture(t, "docs")
+ w.process(false)
+ if _, err := w.configure(true); err != nil {
+ t.Fatal(err)
+ }
+ base := w.baseline(t)
+ ctx := context.Background()
+ if _, err := RestartAndWait(ctx, w.c, w.h, w.app, base.Identity, func(d Delivery) error { return Delivered(base.Delivery, d) }, true); err != nil {
+ t.Fatal(err)
+ }
+ w.f.PlatformWrite("docs", "", "DOCS_MAIL_EVENTS_URL", "https://mail.example/hook")
+ after, err := CaptureAfter(ctx, w.c, w.h, w.s, w.app)
+ if err != nil {
+ t.Fatalf("CaptureAfter: %v", err)
+ }
+ if got := NewKeys(base, after, AgentKeys(w.app)); len(got) != 1 || got[0] != "added:DOCS_MAIL_EVENTS_URL" {
+ t.Fatalf("NewKeys = %q", got)
+ }
+}
+
+func TestAfterSnapshotRefusesBeforeLandedOrDelivered(t *testing.T) {
+ w := newWriteFixture(t, "docs")
+ ctx := context.Background()
+ if _, err := CaptureAfter(ctx, w.c, w.h, w.s, w.app); err == nil {
+ t.Fatal("captured with no baseline or write")
+ }
+ if _, err := w.configure(true); err != nil {
+ t.Fatal(err)
+ }
+ // Written, not restarted: the operations door has not moved.
+ if _, err := CaptureAfter(ctx, w.c, w.h, w.s, w.app); err == nil || !strings.Contains(err.Error(), "after-not-delivered") {
+ t.Fatalf("err = %v, want after-not-delivered", err)
+ }
+ if _, ok, _ := w.s.After(ctx, "docs"); ok {
+ t.Fatal("an after snapshot was stored")
+ }
+}
+
+// ---- Rollback ----
+
+// rollbackPuts is how many PUTs the console saw after the configure phase.
+func (w *writeFixture) rollbackPuts(base int) int { return w.puts() - base }
+
+func TestRollbackHappyPath(t *testing.T) {
+ w := newWriteFixture(t, "docs")
+ w.configured(t)
+ p, r := w.puts(), w.f.RestartCount("docs.oficina.works")
+ if err := w.rollback(true); err != nil {
+ t.Fatalf("RollbackAgentKeys: %v", err)
+ }
+ if n := w.rollbackPuts(p); n != 1 {
+ t.Fatalf("rollback PUTs = %d", n)
+ }
+ if present, _ := w.stored(t); present != [2]bool{} {
+ t.Fatalf("keys still present %v", present)
+ }
+ rec, ok := w.rollbackRecord(t)
+ if !ok || rec.State != "restarted" || rec.Receipt == nil || rec.Code != "" {
+ t.Fatalf("rollback %v state %q code %q", ok, rec.State, rec.Code)
+ }
+ if got := w.f.RestartCount("docs.oficina.works"); got != r+1 {
+ t.Fatalf("restarts %d, want one more", got-r)
+ }
+ // Restarted is the end: a second call sends nothing.
+ n := len(w.f.Requests())
+ if err := w.rollback(true); err != nil {
+ t.Fatal(err)
+ }
+ if len(w.f.Requests()) != n {
+ t.Fatal("a finished rollback sent requests")
+ }
+}
+
+func TestRollbackDryRunSendsNothing(t *testing.T) {
+ w := newWriteFixture(t, "docs")
+ w.configured(t)
+ p, r := w.puts(), w.f.RestartCount("docs.oficina.works")
+ if err := w.rollback(false); err != nil {
+ t.Fatalf("dry run: %v", err)
+ }
+ if w.rollbackPuts(p) != 0 || w.f.RestartCount("docs.oficina.works") != r {
+ t.Fatal("a dry run wrote or restarted")
+ }
+ if _, ok := w.rollbackRecord(t); ok {
+ t.Fatal("a dry run journalled a rollback")
+ }
+ if _, ours := w.stored(t); ours != [2]bool{true, true} {
+ t.Fatal("a dry run removed the keys")
+ }
+}
+
+func TestRollbackLostAnswerRetryAcceptsUnsetAbsent(t *testing.T) {
+ w := newWriteFixture(t, "docs")
+ w.configured(t)
+ p := w.puts()
+ w.f.LoseNextAnswer()
+ if err := w.rollback(true); err != nil {
+ t.Fatalf("RollbackAgentKeys: %v", err)
+ }
+ if n := w.rollbackPuts(p); n != 1 {
+ t.Fatalf("rollback PUTs = %d, want exactly one", n)
+ }
+ if rec, _ := w.rollbackRecord(t); rec.State != "restarted" {
+ t.Fatalf("state %q", rec.State)
+ }
+
+ // The receipt rule itself: removed or already absent, both keys, and
+ // nothing set.
+ keys := AgentKeys(w.app)
+ ok := []carlosop.Receipt{
+ {Unset: []string{keys[0], keys[1]}},
+ {Unset: []string{keys[1]}, UnsetAbsent: []string{keys[0]}},
+ {UnsetAbsent: []string{keys[0], keys[1]}},
+ }
+ for i, rc := range ok {
+ if !unsetReceiptOK(rc, keys) {
+ t.Errorf("receipt %d refused", i)
+ }
+ }
+ bad := []carlosop.Receipt{
+ {Unset: []string{keys[0]}},
+ {Unset: []string{keys[0], keys[1], "DOCS_ORIGIN"}},
+ {Unset: []string{keys[0], keys[0]}},
+ {Unset: []string{keys[0]}, UnsetAbsent: []string{keys[0], keys[1]}},
+ {Unset: []string{keys[0], keys[1]}, Set: []string{"DOCS_ORIGIN"}},
+ }
+ for i, rc := range bad {
+ if unsetReceiptOK(rc, keys) {
+ t.Errorf("bad receipt %d accepted", i)
+ }
+ }
+}
+
+func TestRollbackRefusesForeignValue(t *testing.T) {
+ cases := map[string]func(w *writeFixture){
+ "another team": func(w *writeFixture) { w.f.SetVar("docs", "", "DOCS_AGENT_TEAM", "tOther9") },
+ "one key gone": func(w *writeFixture) { w.f.Unset("docs", "", "DOCS_AGENT_TEAM") },
+ "a secret": func(w *writeFixture) { w.f.SetSecret("docs", "", "DOCS_AGENT_ISSUER") },
+ }
+ for name, edit := range cases {
+ t.Run(name, func(t *testing.T) {
+ w := newWriteFixture(t, "docs")
+ w.configured(t)
+ edit(w)
+ p, r := w.puts(), w.f.RestartCount("docs.oficina.works")
+ for _, apply := range []bool{false, true} {
+ err := w.rollback(apply)
+ if !errors.Is(err, ErrStopForeign) {
+ t.Fatalf("apply %v: err = %v, want ErrStopForeign", apply, err)
+ }
+ noValues(t, err)
+ }
+ if w.rollbackPuts(p) != 0 || w.f.RestartCount("docs.oficina.works") != r {
+ t.Fatal("a foreign value was unset or the app restarted")
+ }
+ rec, _ := w.rollbackRecord(t)
+ if rec.State != "stopped" || rec.Code != "agent-keys-foreign" {
+ t.Fatalf("state %q code %q", rec.State, rec.Code)
+ }
+ })
+ }
+}
+
+func TestRollbackConflict412Rereads(t *testing.T) {
+ w := newWriteFixture(t, "docs")
+ w.configured(t)
+ p := w.puts()
+ w.f.BeforePut = once(func() { w.f.PlatformWrite("docs", "", "DOCS_MAIL_EVENTS_URL", "https://mail.example/hook") })
+ if err := w.rollback(true); err != nil {
+ t.Fatalf("RollbackAgentKeys: %v", err)
+ }
+ if n := w.rollbackPuts(p); n != 2 {
+ t.Fatalf("rollback PUTs = %d, want a 412 then the retry", n)
+ }
+ if present, _ := w.stored(t); present != [2]bool{} {
+ t.Fatal("keys still present")
+ }
+ vars, _, _ := w.f.Layer("docs", "")
+ if _, ok := vars["DOCS_MAIL_EVENTS_URL"]; !ok {
+ t.Fatal("the platform's key was lost")
+ }
+ if rec, _ := w.rollbackRecord(t); rec.State != "restarted" {
+ t.Fatalf("state %q", rec.State)
+ }
+}
+
+func TestRollbackCrashAfterUnsetResumesToRestart(t *testing.T) {
+ w := newWriteFixture(t, "docs")
+ w.configured(t)
+ ctx := context.Background()
+ // The crash: the unset landed and was journalled, the restart never ran.
+ for _, k := range AgentKeys(w.app) {
+ w.f.Unset("docs", "", k)
+ }
+ if err := w.s.SaveRollback(ctx, RollbackRecord{App: "docs", State: "unset"}); err != nil {
+ t.Fatal(err)
+ }
+ p, r := w.puts(), w.f.RestartCount("docs.oficina.works")
+ if err := w.rollback(true); err != nil {
+ t.Fatalf("resume: %v", err)
+ }
+ if w.rollbackPuts(p) != 0 {
+ t.Fatal("the resume sent the unset again")
+ }
+ if w.f.RestartCount("docs.oficina.works") != r+1 {
+ t.Fatal("the resume did not restart")
+ }
+ if rec, _ := w.rollbackRecord(t); rec.State != "restarted" {
+ t.Fatalf("state %q", rec.State)
+ }
+}
+
+func TestRollbackRestartFailureLeavesUnsetState(t *testing.T) {
+ w := newWriteFixture(t, "docs")
+ w.configured(t)
+ p := w.puts()
+ w.f.FailRestart(http.StatusServiceUnavailable)
+ if err := w.rollback(true); err == nil {
+ t.Fatal("a failed restart reported success")
+ }
+ rec, _ := w.rollbackRecord(t)
+ if rec.State != "unset" || rec.Code != "restart-failed" || rec.Receipt == nil {
+ t.Fatalf("state %q code %q", rec.State, rec.Code)
+ }
+ if present, _ := w.stored(t); present != [2]bool{} {
+ t.Fatal("keys still present")
+ }
+ w.f.FailRestart(0)
+ if err := w.rollback(true); err != nil {
+ t.Fatalf("resume: %v", err)
+ }
+ if n := w.rollbackPuts(p); n != 1 {
+ t.Fatalf("rollback PUTs = %d: the resume unset again", n)
+ }
+ if rec, _ := w.rollbackRecord(t); rec.State != "restarted" || rec.Code != "" {
+ t.Fatalf("state %q code %q", rec.State, rec.Code)
+ }
+}
+
+func TestRollbackUsesScopedDryRun(t *testing.T) {
+ w := newWriteFixture(t, "docs")
+ // A neighbour on an owned environment: the write never reaches it,
+ // and neither does the restart.
+ w.neighbour("staging.docs.example", "acme-docs")
+ w.f.SetVar("docs", "acme-docs", "DOCS_HOME_ISSUER", HomeIssuerOrigin)
+ w.f.Own("docs", "acme-docs", "alta")
+ w.configured(t)
+ start := len(w.f.Requests())
+ r := w.f.RestartCount("docs.oficina.works")
+ if err := w.rollback(true); err != nil {
+ t.Fatalf("RollbackAgentKeys: %v", err)
+ }
+ var doors []string
+ for _, req := range w.f.Requests()[start:] {
+ if req == "PUT /config" || strings.Contains(req, "restart") {
+ doors = append(doors, req)
+ }
+ }
+ // The unset, then the dry run, then the one real request.
+ want := []string{"PUT /config", "POST /restart/scope", "POST /restart/scope"}
+ if strings.Join(doors, "|") != strings.Join(want, "|") {
+ t.Fatalf("doors %q, want %q", doors, want)
+ }
+ if w.f.RestartCount("docs.oficina.works") != r+1 {
+ t.Fatal("the canonical host did not restart once")
+ }
+ w.noRestarts(t, "staging.docs.example")
+
+ // A dry run that resolves more than the host restarts nothing, and
+ // the rollback stays unset for a resume.
+ w2 := newWriteFixture(t, "docs")
+ w2.configured(t)
+ w2.dryRunRewriter(t, func(rt []map[string]any) []map[string]any {
+ return append(rt, map[string]any{"host": "staging.docs.example", "hibernate": false})
+ })
+ r2 := w2.f.RestartCount("docs.oficina.works")
+ err := w2.rollback(true)
+ if err == nil || !strings.Contains(err.Error(), "restart-scope-2") {
+ t.Fatalf("err = %v, want restart-scope-2", err)
+ }
+ if w2.f.RestartCount("docs.oficina.works") != r2 || w2.f.AppWideRestarts() != 0 {
+ t.Fatal("restarted past a wider dry run")
+ }
+ if rec, _ := w2.rollbackRecord(t); rec.State != "unset" || rec.Code != "restart-failed" {
+ t.Fatalf("state %q code %q", rec.State, rec.Code)
+ }
+}
+
+func TestRollbackCompleteOnlyWhenReverted(t *testing.T) {
+ w := newWriteFixture(t, "docs")
+ w.configured(t)
+ // The process ignores the restart: it keeps the delegated-access door.
+ w.site.ops = agent401
+ fastPolls(t, 5*time.Millisecond, 100*time.Millisecond)
+ err := w.rollback(true)
+ if err == nil || !strings.Contains(err.Error(), "restart-timeout") {
+ t.Fatalf("err = %v, want restart-timeout", err)
+ }
+ rec, _ := w.rollbackRecord(t)
+ if rec.State != "unset" || rec.Code != "restart-failed" {
+ t.Fatalf("state %q code %q: complete before Reverted", rec.State, rec.Code)
+ }
+ // The process reloads on its next restart; the resume restarts again.
+ w.process(true)
+ fastPolls(t, 5*time.Millisecond, 2*time.Second)
+ if err := w.rollback(true); err != nil {
+ t.Fatalf("resume: %v", err)
+ }
+ if rec, _ := w.rollbackRecord(t); rec.State != "restarted" {
+ t.Fatalf("state %q", rec.State)
+ }
+}
+
+func TestRollbackRefusesWithoutAWrite(t *testing.T) {
+ w := newWriteFixture(t, "docs")
+ if err := w.rollback(true); err == nil {
+ t.Fatal("rolled back an app with no write")
+ }
+ if w.puts() != 0 {
+ t.Fatal("sent a PUT")
+ }
+}