oficina / alta Public

alta-adopt: a malformed receipt stops; only no answer is lost

carlosop now classifies a PUT's failures: ErrNoAnswer (transport
uncertainty, the only case a reread may settle), ErrMalformedAnswer (a
200 with no receipt, another bundle, a malformed digest or version, or
an unreadable body) and ErrNotSent (the guarding read failed, nothing
was sent).

lost() is now a whitelist of a 412 and ErrNoAnswer. A malformed answer
stops the write and the rollback with receipt-malformed instead of
being reread and recorded landed, and a resume refuses again. A Put
never sent is returned as it is, never reread or stopped on.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev f8adb5a64675adc60b4ad8063c84c1a90af186af parent dffa50c
4 files changed, +284 −27
  • adopt/write.go +28 −9
  • adopt/write_test.go +165 −6
  • carlosop/client.go +28 −12
  • carlosop/client_test.go +63 −0
diff --git a/adopt/write.go b/adopt/write.go
index d6153c5..85e3548 100644
--- a/adopt/write.go
+++ b/adopt/write.go
@@ -229,15 +229,25 @@ func stoppedErr(code string) error {
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.
+// lost reports whether err leaves a write's outcome to a reread: a 412,
+// or no answer at all (transport uncertainty). Nothing else is: a Put
+// never sent, or a refusal the console answered, wrote nothing and is
+// returned as it is; a malformed answer is a protocol failure, which
+// malformedAnswer stops on.
func lost(err error) bool {
- if errors.Is(err, carlosop.ErrVersionMismatch) {
- return true
+ if errors.Is(err, carlosop.ErrNotSent) || errors.Is(err, carlosop.ErrMalformedAnswer) {
+ return false
}
- var se *carlosop.StatusError
- return !errors.As(err, &se) && !errors.Is(err, carlosop.ErrNoConditional) && !errors.Is(err, carlosop.ErrNotFound)
+ return errors.Is(err, carlosop.ErrVersionMismatch) || errors.Is(err, carlosop.ErrNoAnswer)
+}
+
+// malformedAnswer reports whether the console answered a PUT with no
+// well-formed receipt for it. What it wrote is unknown, and a reread
+// cannot vouch for an answer that broke the protocol: the run stops. A
+// malformed answer to the read guarding a Put is not one: that PUT was
+// never sent.
+func malformedAnswer(err error) bool {
+ return errors.Is(err, carlosop.ErrMalformedAnswer) && !errors.Is(err, carlosop.ErrNotSent)
}
// exactly reports whether got names each of keys once and nothing else.
@@ -293,8 +303,13 @@ func unsetReceiptOK(rc carlosop.Receipt, keys [2]string) bool {
// 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;
+// (receipt-mismatch, ErrStopConflict, otherwise). One carlosop.Put
+// refuses as malformed (none, another bundle, a malformed digest or
+// version, unreadable) stops too (receipt-malformed): the console
+// answered, so it is not a lost answer, and no reread stands in for
+// the receipt.
+// 6. A 412 or a lost answer (no answer at all) 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.
@@ -395,6 +410,8 @@ func WriteAgentKeys(ctx context.Context, c *carlosop.Client, h *http.Client, s *
return "", err
}
return summary, nil
+ case malformedAnswer(err):
+ return stop("receipt-malformed", ErrStopConflict)
case errors.Is(err, carlosop.ErrNoConditional):
w.Code = "no-conditional"
if serr := advanceWrite(ctx, s, w); serr != nil {
@@ -646,6 +663,8 @@ func RollbackAgentKeys(ctx context.Context, c *carlosop.Client, h *http.Client,
return err
}
return rollbackRestart(ctx, c, h, s, app, base, rb, true)
+ case malformedAnswer(err):
+ return stop("receipt-malformed", ErrStopConflict)
case errors.Is(err, carlosop.ErrNoConditional):
rb.Code = "no-conditional"
if serr := advanceRollback(ctx, s, rb); serr != nil {
diff --git a/adopt/write_test.go b/adopt/write_test.go
index 793364a..0b79122 100644
--- a/adopt/write_test.go
+++ b/adopt/write_test.go
@@ -184,6 +184,21 @@ func once(f func()) func(string) {
// 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()
+ x.putAnswerRewriter(t, func(raw []byte) ([]byte, error) {
+ var answer map[string]any
+ if err := json.Unmarshal(raw, &answer); err != nil {
+ return nil, err
+ }
+ edit(answer["receipt"].(map[string]any))
+ return json.Marshal(answer)
+ })
+}
+
+// putAnswerRewriter puts a proxy in front of the fake console that
+// replaces the body of every successful PUT /config answer with what
+// edit makes of it. The write itself has landed by then.
+func (x *carlosFixture) putAnswerRewriter(t *testing.T, edit func(raw []byte) ([]byte, error)) {
t.Helper()
target, err := url.Parse(x.f.URL())
if err != nil {
@@ -199,12 +214,7 @@ func (x *carlosFixture) putRewriter(t *testing.T, edit func(rc map[string]any))
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 {
+ if raw, err = edit(raw); err != nil {
return err
}
resp.Body = io.NopCloser(bytes.NewReader(raw))
@@ -631,6 +641,121 @@ func TestWriteRejectsMalformedReceipts(t *testing.T) {
}
}
+// malformedAnswers are 200 answers to a PUT that carlosop.Put refuses as
+// no receipt for the write: absent, for another bundle, with a malformed
+// digest or version, or not JSON at all. The write landed each time; the
+// answer is a protocol failure, not a lost one.
+func malformedAnswers() map[string]func(raw []byte) ([]byte, error) {
+ answer := func(edit func(a map[string]any)) func([]byte) ([]byte, error) {
+ return func(raw []byte) ([]byte, error) {
+ var a map[string]any
+ if err := json.Unmarshal(raw, &a); err != nil {
+ return nil, err
+ }
+ edit(a)
+ return json.Marshal(a)
+ }
+ }
+ receipt := func(edit func(rc map[string]any)) func([]byte) ([]byte, error) {
+ return answer(func(a map[string]any) { edit(a["receipt"].(map[string]any)) })
+ }
+ return map[string]func([]byte) ([]byte, error){
+ "no receipt": answer(func(a map[string]any) { delete(a, "receipt") }),
+ "null receipt": answer(func(a map[string]any) { a["receipt"] = nil }),
+ "another bundle": receipt(func(rc map[string]any) { rc["bundle"] = "production" }),
+ "malformed digest": receipt(func(rc map[string]any) {
+ rc["digests"] = map[string]any{"DOCS_AGENT_TEAM": "vd1:zz"}
+ }),
+ "malformed version before": receipt(func(rc map[string]any) { rc["version_before"] = "cv1:XYZ" }),
+ "malformed version after": receipt(func(rc map[string]any) { rc["version_after"] = "v2" }),
+ "malformed others version": receipt(func(rc map[string]any) {
+ rc["others"] = map[string]any{"default": map[string]any{"before": "v1", "after": "v1"}}
+ }),
+ "unreadable answer": func([]byte) ([]byte, error) { return []byte("{not json"), nil },
+ }
+}
+
+// A malformed receipt is not a lost answer: the console answered, so a
+// reread proves nothing about what that answer said. The write stops,
+// and a resume refuses again without sending.
+func TestWriteStopsOnMalformedReceipts(t *testing.T) {
+ for name, edit := range malformedAnswers() {
+ t.Run(name, func(t *testing.T) {
+ w := newWriteFixture(t, "docs")
+ w.putAnswerRewriter(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-malformed" {
+ t.Fatalf("state %q code %q", rec.State, rec.Code)
+ }
+ if _, err := w.configure(true); !errors.Is(err, ErrStopConflict) {
+ t.Fatalf("resume: err = %v, want ErrStopConflict", err)
+ }
+ if n := w.puts(); n != 1 {
+ t.Fatalf("resume sent: PUTs = %d", n)
+ }
+ })
+ }
+}
+
+// Only an answer that never came is lost. A Put that was never sent
+// (its guarding read failed) is returned as it is: no reread, no retry,
+// no stop, the record left at sent.
+func TestWriteNotSentIsNotLost(t *testing.T) {
+ w := newWriteFixture(t, "docs")
+ reads, drop := 0, 0
+ target, err := url.Parse(w.f.URL())
+ if err != nil {
+ t.Fatal(err)
+ }
+ rp := httputil.NewSingleHostReverseProxy(target)
+ srv := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
+ if r.Method == http.MethodGet && r.URL.Path == "/api/cli/apps/"+fixtureAccount+"/docs/config" {
+ if reads++; reads == drop {
+ // A console answering with no version: Put refuses to send.
+ rw.Header().Set("Content-Type", "application/json")
+ _, _ = rw.Write([]byte(`{"bundle":"default","vars":[]}`))
+ return
+ }
+ }
+ rp.ServeHTTP(rw, r)
+ }))
+ t.Cleanup(srv.Close)
+ w.c = carlosop.New(srv.URL, fixtureAccount, w.f.Token())
+ t.Cleanup(w.c.Close)
+ // A dry run counts the preflight's reads of the layer; Put's own
+ // guarding read is the next one. Its malformed answer is not the
+ // write's receipt: nothing was sent.
+ if _, err := w.configure(false); err != nil {
+ t.Fatal(err)
+ }
+ pre := reads
+ reads, drop = 0, pre+1
+ _, err = w.configure(true)
+ if err == nil || errors.Is(err, ErrStopConflict) || errors.Is(err, ErrStopPreserved) {
+ t.Fatalf("err = %v, want the read's own failure", err)
+ }
+ if !errors.Is(err, carlosop.ErrNotSent) {
+ t.Fatalf("err = %v, want ErrNotSent", err)
+ }
+ if n := w.puts(); n != 0 {
+ t.Fatalf("PUTs = %d", n)
+ }
+ if reads != drop {
+ t.Fatalf("reads of the layer = %d, want %d: a Put never sent was reread", reads, drop)
+ }
+ if rec, _ := w.writeRecord(t); rec.State != "sent" {
+ t.Fatalf("state %q", rec.State)
+ }
+}
+
func TestWriteRefusesWithoutConditionalSupport(t *testing.T) {
w := newWriteFixture(t, "docs")
w.f.NoConditional()
@@ -1061,6 +1186,40 @@ func TestRollbackLostAnswerRetryAcceptsUnsetAbsent(t *testing.T) {
}
}
+// A malformed answer to the rollback's unset stops it, as for the write:
+// no reread, no restart, and a resume refuses again.
+func TestRollbackStopsOnMalformedReceipts(t *testing.T) {
+ for name, edit := range malformedAnswers() {
+ t.Run(name, func(t *testing.T) {
+ w := newWriteFixture(t, "docs")
+ w.configured(t)
+ w.putAnswerRewriter(t, edit)
+ p, r := w.puts(), w.f.RestartCount("docs.oficina.works")
+ err := w.rollback(true)
+ if !errors.Is(err, ErrStopConflict) {
+ t.Fatalf("err = %v, want ErrStopConflict", err)
+ }
+ noValues(t, err)
+ if n := w.rollbackPuts(p); n != 1 {
+ t.Fatalf("rollback PUTs = %d", n)
+ }
+ if w.f.RestartCount("docs.oficina.works") != r {
+ t.Fatal("restarted after a malformed receipt")
+ }
+ rec, _ := w.rollbackRecord(t)
+ if rec.State != "stopped" || rec.Code != "receipt-malformed" {
+ t.Fatalf("state %q code %q", rec.State, rec.Code)
+ }
+ if err := w.rollback(true); !errors.Is(err, ErrStopConflict) {
+ t.Fatalf("resume: err = %v, want ErrStopConflict", err)
+ }
+ if n := w.rollbackPuts(p); n != 1 {
+ t.Fatalf("resume sent: rollback PUTs = %d", n)
+ }
+ })
+ }
+}
+
func TestRollbackRefusesForeignValue(t *testing.T) {
cases := map[string]func(w *writeFixture){
"another team": func(w *writeFixture) { w.f.SetVar("docs", "", "DOCS_AGENT_TEAM", "tOther9") },
diff --git a/carlosop/client.go b/carlosop/client.go
index e42d5a6..b656860 100644
--- a/carlosop/client.go
+++ b/carlosop/client.go
@@ -47,6 +47,18 @@ var (
// console that predates it. Nothing was restarted, and nothing falls
// back to the app-wide door.
ErrNoScopedRestart = errors.New("carlosop: the console has no host-scoped restart")
+ // ErrNoAnswer is a request that got no answer: it failed in transit,
+ // timed out or was cancelled, or its answer could not be read. The
+ // console may or may not have acted on it; only a reread can tell.
+ ErrNoAnswer = errors.New("carlosop: no answer")
+ // ErrMalformedAnswer is a 2xx answer that is not what the door
+ // promises: unreadable, or a receipt that is absent, for another
+ // bundle, or carries a malformed digest or version. The console did
+ // answer, so this is a protocol failure, never a lost answer.
+ ErrMalformedAnswer = errors.New("carlosop: malformed answer")
+ // ErrNotSent is a Put refused before its request was sent, because
+ // the read guarding it failed: nothing was written.
+ ErrNotSent = errors.New("carlosop: PUT /config not sent")
)
// StatusError is any other non-2xx answer, a redirect included. Door is
@@ -233,7 +245,7 @@ func (c *Client) do(ctx context.Context, method, app, door, path string, body, o
defer resp.Body.Close()
raw, err := io.ReadAll(io.LimitReader(resp.Body, 4<<20))
if err != nil {
- return fmt.Errorf("carlosop: %s: could not read the answer", door)
+ return fmt.Errorf("carlosop: %s: could not read the answer: %w", door, ErrNoAnswer)
}
if resp.StatusCode < 200 || resp.StatusCode > 299 {
return &StatusError{Door: door, Code: resp.StatusCode}
@@ -241,7 +253,7 @@ func (c *Client) do(ctx context.Context, method, app, door, path string, body, o
if out != nil {
// The decoder's own error can quote the answer; it is dropped.
if json.Unmarshal(raw, out) != nil {
- return fmt.Errorf("carlosop: %s: unreadable answer", door)
+ return fmt.Errorf("carlosop: %s: unreadable answer: %w", door, ErrMalformedAnswer)
}
}
return nil
@@ -249,20 +261,20 @@ func (c *Client) do(ctx context.Context, method, app, door, path string, body, o
// transportError replaces a failed request's own text, which can quote
// what the console sent (a malformed redirect Location, say), with a fixed
-// sentence. It keeps only the classifications a caller acts on: the
-// context's cancellation or deadline (wrapped, for errors.Is) and a
-// timeout.
+// sentence. It keeps only the classifications a caller acts on: every
+// one is ErrNoAnswer, and the context's cancellation or deadline is
+// wrapped too, for errors.Is; a timeout is said as one.
func transportError(door string, err error) error {
var ne net.Error
switch {
case errors.Is(err, context.Canceled):
- return fmt.Errorf("carlosop: %s: %w", door, context.Canceled)
+ return fmt.Errorf("carlosop: %s: %w: %w", door, ErrNoAnswer, context.Canceled)
case errors.Is(err, context.DeadlineExceeded):
- return fmt.Errorf("carlosop: %s: %w", door, context.DeadlineExceeded)
+ return fmt.Errorf("carlosop: %s: %w: %w", door, ErrNoAnswer, context.DeadlineExceeded)
case errors.As(err, &ne) && ne.Timeout():
- return fmt.Errorf("carlosop: %s: the request timed out", door)
+ return fmt.Errorf("carlosop: %s: %w: the request timed out", door, ErrNoAnswer)
}
- return fmt.Errorf("carlosop: %s: the request failed before an answer", door)
+ return fmt.Errorf("carlosop: %s: %w: the request failed before an answer", door, ErrNoAnswer)
}
// as maps a status to the error callers act on, wrapping the status.
@@ -278,8 +290,9 @@ func as(err error, by map[int]error) error {
var notFound = map[int]error{http.StatusNotFound: ErrNotFound}
+// malformed is ErrMalformedAnswer, saying which door and why.
func malformed(door, why string) error {
- return fmt.Errorf("carlosop: %s answered %s", door, why)
+ return fmt.Errorf("carlosop: %s answered %s: %w", door, why, ErrMalformedAnswer)
}
// Config reads one stored layer: the default bundle for env "", else the
@@ -411,7 +424,10 @@ func (c *Client) Effective(ctx context.Context, app, host string) (Effective, er
// write's receipt.
//
// A 412 is ErrVersionMismatch and a 400 is ErrNoConditional; nothing was
-// written for either. IfVersion is required, travels as one JSON string in
+// written for either. A failed guarding read is ErrNotSent. No answer at
+// all is ErrNoAnswer: the write may have landed. A 200 that carries no
+// well-formed receipt for this bundle is ErrMalformedAnswer: the console
+// answered, and what it wrote is unknown. IfVersion is required, travels as one JSON string in
// the body (there is no If-Match), and is never combined with
// exec_delivery.
//
@@ -439,7 +455,7 @@ func (c *Client) Put(ctx context.Context, app string, r PutRequest) (Receipt, er
}
}
if _, err := c.Config(ctx, app, r.Environment); err != nil {
- return Receipt{}, fmt.Errorf("carlosop: PUT /config not sent: the layer's read failed or carried no version, so the console may not honour if_version: %w", err)
+ return Receipt{}, fmt.Errorf("%w: the layer's read failed or carried no version, so the console may not honour if_version: %w", ErrNotSent, err)
}
body := map[string]any{"if_version": r.IfVersion}
if r.Environment != "" {
diff --git a/carlosop/client_test.go b/carlosop/client_test.go
index 37d3ad3..b46ac1b 100644
--- a/carlosop/client_test.go
+++ b/carlosop/client_test.go
@@ -550,3 +550,66 @@ func TestPutRefusedWhenConsoleAnswersNoVersion(t *testing.T) {
c.Close()
}
}
+
+// A Put's failure says which kind it is, for the caller that recovers:
+// no answer is ErrNoAnswer (only a reread can tell), a 200 without a
+// well-formed receipt is ErrMalformedAnswer (the console answered), and
+// a failed guarding read is ErrNotSent. None is another.
+func TestPutClassifiesItsFailures(t *testing.T) {
+ layer := map[string]any{"bundle": "default", "version": v1, "vars": []any{}}
+ put := carlosop.PutRequest{Set: map[string]string{"K": "v"}, IfVersion: v1}
+ receipt := map[string]any{"bundle": "default", "version_before": v1, "version_after": v2, "changed": true,
+ "set": []string{"K"}, "unset": []string{}, "unset_absent": []string{}, "digests": map[string]string{"K": d1}}
+ with := func(k string, v any) map[string]any {
+ r := maps.Clone(receipt)
+ r[k] = v
+ return map[string]any{"result": "ok", "receipt": r}
+ }
+ cases := map[string]struct {
+ get, answer any // nil get: the layer; nil answer: the connection drops
+ raw string
+ want error
+ }{
+ "no answer": {answer: nil, want: carlosop.ErrNoAnswer},
+ "no receipt": {answer: map[string]any{"result": "ok"}, want: carlosop.ErrMalformedAnswer},
+ "another bundle": {answer: with("bundle", "beta"), want: carlosop.ErrMalformedAnswer},
+ "malformed digest": {answer: with("digests", map[string]string{"K": "vd1:zz"}), want: carlosop.ErrMalformedAnswer},
+ "malformed version before": {answer: with("version_before", "cv1:abc"), want: carlosop.ErrMalformedAnswer},
+ "malformed version after": {answer: with("version_after", "v2"), want: carlosop.ErrMalformedAnswer},
+ "unreadable": {raw: "{not json", want: carlosop.ErrMalformedAnswer},
+ "read without version": {get: map[string]any{"bundle": "default", "vars": []any{}}, answer: map[string]any{"result": "ok", "receipt": receipt}, want: carlosop.ErrNotSent},
+ }
+ all := []error{carlosop.ErrNoAnswer, carlosop.ErrMalformedAnswer, carlosop.ErrNotSent}
+ for name, tc := range cases {
+ t.Run(name, func(t *testing.T) {
+ srv, _ := rawConsole(t, func(w http.ResponseWriter, r *http.Request) {
+ switch {
+ case r.Method == http.MethodGet && tc.get != nil:
+ writeJSON(w, 200, tc.get)
+ case r.Method == http.MethodGet:
+ writeJSON(w, 200, layer)
+ case tc.raw != "":
+ w.WriteHeader(200)
+ _, _ = io.WriteString(w, tc.raw)
+ case tc.answer == nil:
+ if conn, _, err := w.(http.Hijacker).Hijack(); err == nil {
+ _ = conn.Close()
+ }
+ default:
+ writeJSON(w, 200, tc.answer)
+ }
+ })
+ c := carlosop.New(srv.URL, acct, []byte("svc_token"))
+ defer c.Close()
+ _, err := c.Put(ctx, "docs", put)
+ if !errors.Is(err, tc.want) {
+ t.Fatalf("err = %v, want %v", err, tc.want)
+ }
+ for _, other := range all {
+ if other != tc.want && errors.Is(err, other) && tc.want != carlosop.ErrNotSent {
+ t.Fatalf("err = %v is also %v", err, other)
+ }
+ }
+ })
+ }
+}