oficina / alta Public

adopt: bound restart polling; bind the witness to the after config

RestartAndWait waits and probes under a context bound to the 5-minute
limit, so a stalled probe is cut off and the limit's expiry is told
apart from the caller's cancellation. RecordWitness refuses unless the
fresh config equals the after snapshot's, digest for digest and layer
for layer. The witness sentence stays marked pending copy review.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev 23755aa21ccbffdf9bb2f8d4eeea4fa99b8d89e2 parent 23071b6
5 files changed, +250 −10
  • adopt/restart.go +19 −9
  • adopt/restart_test.go +59 −0
  • adopt/witness.go +81 −1
  • adopt/witness_test.go +88 −0
  • adopt/words.go +3 −0
diff --git a/adopt/restart.go b/adopt/restart.go
index 63a244c..6775e8a 100644
--- a/adopt/restart.go
+++ b/adopt/restart.go
@@ -92,25 +92,35 @@ func RestartAndWait(ctx context.Context, c *carlosop.Client, h *http.Client, app
if !apply {
return Probe(ctx, h, origin)
}
- deadline := time.Now().Add(pollLimit)
+ // Every wait and every probe runs under the limit's own context, so a
+ // stalled answer is cut off at the limit and nothing that finishes
+ // after it counts. Its expiry is told apart from the caller's.
+ poll, cancel := context.WithTimeout(ctx, pollLimit)
+ defer cancel()
var last Delivery
reason := errors.New("adopt: the app was not probed")
+ stopped := func() (Delivery, error) {
+ if err := ctx.Err(); err != nil {
+ return last, fmt.Errorf("adopt: stopped waiting for the restart: %w", err)
+ }
+ return last, fmt.Errorf("adopt: restart-timeout: %w", reason)
+ }
for {
// The restart is asynchronous, so the first probe waits too.
- if time.Now().Add(pollEvery).After(deadline) {
- return last, fmt.Errorf("adopt: restart-timeout: %w", reason)
- }
t := time.NewTimer(pollEvery)
select {
- case <-ctx.Done():
+ case <-poll.Done():
t.Stop()
- return last, fmt.Errorf("adopt: stopped waiting for the restart: %w", ctx.Err())
+ return stopped()
case <-t.C:
}
- d, err := Probe(ctx, h, origin)
+ // A probe that returns at all finished inside the limit: each of
+ // its requests ran under poll. One cut off by the limit is not a
+ // reason of its own, so the last real one is reported.
+ d, err := Probe(poll, h, origin)
if err != nil {
- if ctx.Err() != nil {
- return last, fmt.Errorf("adopt: stopped waiting for the restart: %w", ctx.Err())
+ if poll.Err() != nil {
+ return stopped()
}
reason = err
continue
diff --git a/adopt/restart_test.go b/adopt/restart_test.go
index 7ac761a..a5f2b44 100644
--- a/adopt/restart_test.go
+++ b/adopt/restart_test.go
@@ -6,12 +6,14 @@ import (
"encoding/json"
"errors"
"io"
+ "net"
"net/http"
"net/http/httptest"
"net/http/httputil"
"net/url"
"strconv"
"strings"
+ "sync"
"testing"
"time"
@@ -273,6 +275,9 @@ func TestRestartAndWaitTimesOut(t *testing.T) {
if !strings.Contains(err.Error(), "the delegated-access door is not answering") {
t.Fatalf("err = %v, want the last reason", err)
}
+ if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled) {
+ t.Fatalf("err = %v: the limit read as the caller's context", err)
+ }
if el := time.Since(start); el > 2*time.Second {
t.Fatalf("waited %v past a 120ms limit", el)
}
@@ -281,6 +286,57 @@ func TestRestartAndWaitTimesOut(t *testing.T) {
}
}
+// A probe whose answer never comes is cut off at the limit: the stalled
+// request is cancelled, and the run stops with restart-timeout well
+// before the probe client's own 10 s timeout.
+func TestRestartAndWaitCutsOffStalledProbeAtLimit(t *testing.T) {
+ fastPolls(t, 10*time.Millisecond, 150*time.Millisecond)
+ x := newCarlosFixture(t, "docs")
+ id := x.identity(t)
+ cancelled := make(chan struct{})
+ var once sync.Once
+ h := clientFor(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ <-r.Context().Done()
+ once.Do(func() { close(cancelled) })
+ }))
+ start := time.Now()
+ _, err := RestartAndWait(context.Background(), x.c, h, x.app, id, func(Delivery) error { return nil }, true)
+ if el := time.Since(start); el > 2*time.Second {
+ t.Fatalf("a stalled probe held the wait %v past a 150ms limit", el)
+ }
+ if err == nil || !strings.Contains(err.Error(), "restart-timeout") {
+ t.Fatalf("err = %v, want restart-timeout", err)
+ }
+ if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled) {
+ t.Fatalf("err = %v: the limit read as the caller's context", err)
+ }
+ // The probe the limit cut off is not reported as the app's failure.
+ if !strings.Contains(err.Error(), "the app was not probed") {
+ t.Fatalf("err = %v, want the reason from before the cut-off", err)
+ }
+ select {
+ case <-cancelled:
+ case <-time.After(2 * time.Second):
+ t.Fatal("the stalled request was never cancelled")
+ }
+}
+
+// clientFor is an http.Client whose every https origin lands on handler.
+func clientFor(t *testing.T, handler http.Handler) *http.Client {
+ t.Helper()
+ srv := httptest.NewTLSServer(handler)
+ t.Cleanup(srv.Close)
+ tr := srv.Client().Transport.(*http.Transport).Clone()
+ addr := srv.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"
+ t.Cleanup(tr.CloseIdleConnections)
+ return &http.Client{Transport: tr, Timeout: 10 * time.Second}
+}
+
func TestRestartAndWaitKeepsPollingThroughUnreachable(t *testing.T) {
fastPolls(t, 5*time.Millisecond, 2*time.Second)
x := newCarlosFixture(t, "docs")
@@ -312,6 +368,9 @@ func TestRestartAndWaitStopsOnCancel(t *testing.T) {
if !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("err = %v, want the context's", err)
}
+ if strings.Contains(err.Error(), "restart-timeout") {
+ t.Fatalf("err = %v: the caller's cancellation read as the limit", err)
+ }
if time.Since(start) > 5*time.Second {
t.Fatal("ignored the context")
}
diff --git a/adopt/witness.go b/adopt/witness.go
index d34e191..c1b5b0e 100644
--- a/adopt/witness.go
+++ b/adopt/witness.go
@@ -24,7 +24,10 @@ import (
// - a fresh observation's probe passes Delivered against the baseline
// (witness-not-delivered);
// - the fresh identity equals the after snapshot's
-// (witness-identity-<code>, one per SameIdentity code).
+// (witness-identity-<code>, one per SameIdentity code);
+// - the fresh config equals the after snapshot's, every key's digest,
+// kind and source and every layer's version
+// (witness-config-<code>, one per sameConfig code).
//
// The witness stores the sentence, the fresh identity and delivery, and
// the after snapshot's write-layer version: it is bound to what was
@@ -37,6 +40,8 @@ func RecordWitness(ctx context.Context, s *Store, c *carlosop.Client, h *http.Cl
return errors.New("adopt: no adoption journal")
}
sentence := WitnessSentence(app)
+ // Only leading and trailing space is dropped (a terminal line ends in
+ // a newline); case, inner spacing and punctuation must match exactly.
if apply && strings.TrimSpace(typed) != sentence {
return errors.New("adopt: witness-sentence-mismatch")
}
@@ -67,6 +72,12 @@ func RecordWitness(ctx context.Context, s *Store, c *carlosop.Client, h *http.Cl
}
return errors.New("adopt: " + strings.Join(codes, ", "))
}
+ if codes := sameConfig(after, fresh); len(codes) > 0 {
+ for i, code := range codes {
+ codes[i] = "witness-config-" + code
+ }
+ return errors.New("adopt: " + strings.Join(codes, ", "))
+ }
if !apply {
return nil
}
@@ -77,3 +88,72 @@ func RecordWitness(ctx context.Context, s *Store, c *carlosop.Client, h *http.Cl
At: time.Now().UTC(),
})
}
+
+// sameConfig lists, sorted, how b's config differs from a's, with key
+// and layer names only: added:<KEY>, gone:<KEY>, kind:<KEY>,
+// changed:<KEY> (digest) and from:<KEY> (source layer) over both the
+// effective config and the write layer's stored vars; layer:<name> for
+// any layer whose version moved, appeared or went (the write layer's
+// stored version included); write-layer when the write layer itself
+// differs. Unlike Preserved, no key is exempt: the witness describes
+// the after snapshot's config exactly.
+func sameConfig(a, b Snapshot) []string {
+ var out []string
+ if a.WriteLayer != b.WriteLayer || a.Layer.Bundle != b.Layer.Bundle {
+ out = append(out, "write-layer")
+ }
+ if a.Layer.Version != b.Layer.Version {
+ out = append(out, "layer:"+layerName(a.WriteLayer))
+ }
+ for name := range a.Layers {
+ if bv, ok := b.Layers[name]; !ok || bv != a.Layers[name] {
+ out = append(out, "layer:"+name)
+ }
+ }
+ for name := range b.Layers {
+ if _, ok := a.Layers[name]; !ok {
+ out = append(out, "layer:"+name)
+ }
+ }
+ type entry struct{ kind, digest, from string }
+ compare := func(am, bm map[string]entry) {
+ for k, av := range am {
+ bv, ok := bm[k]
+ switch {
+ case !ok:
+ out = append(out, "gone:"+k)
+ continue
+ case av.kind != bv.kind:
+ out = append(out, "kind:"+k)
+ }
+ if av.digest != bv.digest {
+ out = append(out, "changed:"+k)
+ }
+ if av.from != bv.from {
+ out = append(out, "from:"+k)
+ }
+ }
+ for k := range bm {
+ if _, ok := am[k]; !ok {
+ out = append(out, "added:"+k)
+ }
+ }
+ }
+ effective := func(s Snapshot) map[string]entry {
+ m := map[string]entry{}
+ for _, v := range s.Vars {
+ m[v.Key] = entry{v.Kind, v.Digest, v.From}
+ }
+ return m
+ }
+ stored := func(s Snapshot) map[string]entry {
+ m := map[string]entry{}
+ for _, v := range s.Layer.Vars {
+ m[v.Key] = entry{v.Kind, v.Digest, ""}
+ }
+ return m
+ }
+ compare(effective(a), effective(b))
+ compare(stored(a), stored(b))
+ return sortedSet(out)
+}
diff --git a/adopt/witness_test.go b/adopt/witness_test.go
index 2195732..0bc7a4f 100644
--- a/adopt/witness_test.go
+++ b/adopt/witness_test.go
@@ -209,3 +209,91 @@ func TestWitnessDryRunRecordsNothing(t *testing.T) {
}
w.noWitness(t)
}
+
+// The witness is bound to the after snapshot's config: any change since,
+// in any key's digest, kind or source, or any layer's version, refuses.
+func TestWitnessRefusesConfigChangedSinceAfter(t *testing.T) {
+ cases := map[string]struct {
+ change func(w *witnessFixture)
+ codes []string
+ }{
+ "unrelated key added": {func(w *witnessFixture) {
+ w.f.SetVar("docs", "", "DOCS_EXTRA", "x")
+ }, []string{"added:DOCS_EXTRA", "layer:default"}},
+ "secret resealed": {func(w *witnessFixture) {
+ w.f.SetSecret("docs", "", "DOCS_INSTANCE_KEY")
+ }, []string{"changed:DOCS_INSTANCE_KEY", "layer:default"}},
+ "agent key rewritten": {func(w *witnessFixture) {
+ w.f.SetVar("docs", "", "DOCS_AGENT_TEAM", "tm_other")
+ }, []string{"changed:DOCS_AGENT_TEAM", "layer:default"}},
+ "key unset": {func(w *witnessFixture) {
+ w.f.Unset("docs", "", "DOCS_ORIGIN")
+ }, []string{"gone:DOCS_ORIGIN", "layer:default"}},
+ "overlay moved": {func(w *witnessFixture) {
+ w.f.SetOverlay("docs", "docs.oficina.works", "DOCS_ORIGIN", "https://elsewhere.example")
+ }, []string{"from:DOCS_ORIGIN", "layer:overlay"}},
+ }
+ for name, tc := range cases {
+ t.Run(name, func(t *testing.T) {
+ w := newWitnessFixture(t, "docs")
+ tc.change(w)
+ err := w.record(WitnessSentence(w.app), true)
+ if err == nil || !strings.HasPrefix(err.Error(), "adopt: witness-config-") {
+ t.Fatalf("err = %v, want witness-config-<code>", err)
+ }
+ for _, code := range tc.codes {
+ if !strings.Contains(err.Error(), "witness-config-"+code) {
+ t.Fatalf("err = %v, want it to name %s", err, code)
+ }
+ }
+ for _, leak := range []string{"vd1:", "cv1:", "tm_other", "elsewhere"} {
+ if strings.Contains(err.Error(), leak) {
+ t.Fatalf("err = %v carries a value", err)
+ }
+ }
+ w.noWitness(t)
+ // A dry run refuses it too.
+ if err := w.record("", false); err == nil {
+ t.Fatal("dry run passed a changed config")
+ }
+ })
+ }
+}
+
+func TestSameConfigComparesEveryPart(t *testing.T) {
+ a := afterSnap()
+ if codes := sameConfig(a, afterSnap()); len(codes) > 0 {
+ t.Fatalf("identical snapshots differ: %v", codes)
+ }
+ cases := map[string]struct {
+ change func(s *Snapshot)
+ want string
+ }{
+ "effective digest": {func(s *Snapshot) { s.Vars[0].Digest = "vd1:other" }, "changed:" + a.Vars[0].Key},
+ "effective kind": {func(s *Snapshot) { s.Vars[0].Kind = "secret" }, "kind:" + a.Vars[0].Key},
+ "effective from": {func(s *Snapshot) { s.Vars[0].From = "environment" }, "from:" + a.Vars[0].Key},
+ "effective gone": {func(s *Snapshot) { s.Vars = s.Vars[1:] }, "gone:" + a.Vars[0].Key},
+ "stored digest": {func(s *Snapshot) { s.Layer.Vars[0].Digest = "vd1:other" }, "changed:" + a.Layer.Vars[0].Key},
+ "stored added": {func(s *Snapshot) {
+ s.Layer.Vars = append(s.Layer.Vars, carlosop.Var{Key: "DOCS_NEW", Kind: "env", Digest: "vd1:x"})
+ }, "added:DOCS_NEW"},
+ "write layer version": {func(s *Snapshot) { s.Layer.Version = "cv1:other" }, "layer:default"},
+ "write layer": {func(s *Snapshot) { s.WriteLayer = "staging" }, "write-layer"},
+ "other layer": {func(s *Snapshot) { s.Layers["environment"] = "cv1:other" }, "layer:environment"},
+ "layer gone": {func(s *Snapshot) { delete(s.Layers, "overlay") }, "layer:overlay"},
+ }
+ for name, tc := range cases {
+ t.Run(name, func(t *testing.T) {
+ b := afterSnap()
+ tc.change(&b)
+ codes := sameConfig(a, b)
+ found := false
+ for _, c := range codes {
+ found = found || c == tc.want
+ }
+ if !found {
+ t.Fatalf("codes = %q, want %q among them", codes, tc.want)
+ }
+ })
+ }
+}
diff --git a/adopt/words.go b/adopt/words.go
index db4e7cd..8217f13 100644
--- a/adopt/words.go
+++ b/adopt/words.go
@@ -1,6 +1,9 @@
// This file holds the words alta-adopt shows or asks Paul to type. They
// 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.
package adopt
import "amadan.net/oficina/alta/provision"