carlos / platform Public

hafresh, lease: refuse a lock carrying an unknown carlos_ field

Slice 0 of region HA storage generations (spec §9). Later slices write
carlos_generation and carlos_release_g into lock.json; every binary from
this release on refuses such a lock outright, so this release is the
floor the generations gate needs.

- hafresh.DecodeLock fills View.Unknown: the body's top-level carlos_
  keys outside the known set (generation, expires_at, owner,
  carlos_release), sorted. Other keys are ignored (litestream may add
  its own). hafresh.UnknownFields is the shared check.
- DecideAcquire refuses with ReasonUnknownField ("unknown lock field")
  right after pool eligibility, before the marker, held and proof rows.
- The legacy take refuses with *HALockError when v.HAOn() or
  len(v.Unknown) > 0, writing nothing.
- lease.Tombstone (the offline move's take of an expired lock, through
  litestream's AcquireLease) refuses with ErrUnknownLockField, writing
  nothing.

Inert: no release writes these fields yet. No new requests.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev d28538deaeecb1f8f7b2e550ea75f86cdcb56c08 parent 7412166
8 files changed, +241 −19
  • internal/hafresh/acquire.go +10 −0
  • internal/hafresh/acquire_test.go +63 −0
  • internal/hafresh/lock.go +40 −4
  • internal/hafresh/lock_test.go +35 −0
  • internal/lease/ha_test.go +25 −0
  • internal/lease/legacytake.go +13 −6
  • internal/lease/tombstone.go +31 −9
  • internal/lease/tombstone_test.go +24 −0

Intent

Attributed to this commit: 20.7 g CO₂e (2,632,436 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on ha-generations-floor, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.

diff --git a/internal/hafresh/acquire.go b/internal/hafresh/acquire.go
index 2cf9c6b99..cf4e8e195 100644
--- a/internal/hafresh/acquire.go
+++ b/internal/hafresh/acquire.go
@@ -62,12 +62,19 @@ const (
ReasonOtherExpired = "another box's expired lease"
ReasonSameBox = "same box, proven empty"
ReasonTerminated = "holder terminated"
+ // ReasonUnknownField refuses a lock carrying a carlos_ field this
+ // binary does not know (View.Unknown): a later release wrote it.
+ ReasonUnknownField = "unknown lock field"
)
// DecideAcquire is the HA acquire's one table (I1), for HA hosts only.
// term is the lease term (lease.LeaseTTL in production):
//
// - absent: create (the caller still proves the prefix empty);
+// - present, carrying a carlos_ field this binary does not know
+// (View.Unknown): refuse, whatever else the lock says. A later release
+// wrote it (a storage-generations lock or release marker), and taking
+// it would ignore what the field means (spec §9, slice 0);
// - present, not HA-format: refuse, a leftover lock;
// - a clean or settled release marker: take;
// - an unsettled release marker: held until its At plus term, then take
@@ -88,6 +95,9 @@ func DecideAcquire(v View, self Self, now time.Time, term time.Duration, p Proof
if p.LocalEligible == nil || !p.LocalEligible() {
return Decision{Action: ActRefuse, Reason: ReasonPoolIneligible}
}
+ if len(v.Unknown) > 0 {
+ return Decision{Action: ActRefuse, Reason: ReasonUnknownField}
+ }
if v.Absent {
return Decision{Action: ActCreate, Reason: ReasonAbsent}
}
diff --git a/internal/hafresh/acquire_test.go b/internal/hafresh/acquire_test.go
index dabc21bb9..9e9fff96a 100644
--- a/internal/hafresh/acquire_test.go
+++ b/internal/hafresh/acquire_test.go
@@ -273,3 +273,66 @@ func TestMarkerSettledField(t *testing.T) {
}
}
}
+
+// Slice 0 (storage generations spec §9): a lock carrying a carlos_ field
+// this binary does not know is refused outright, whatever else it says.
+// The row sits right after pool eligibility, so it comes before the
+// marker row (a clean marker is not taken), the held row (no wait for an
+// expiry) and the proof rows (no proof is asked).
+func TestDecideAcquireRefusesUnknownField(t *testing.T) {
+ now := time.Unix(1_800_000_000, 0)
+ const term = 15 * time.Minute
+ self := Self{Ref: "a", IID: "i-a"}
+ asked := 0
+ p := Proofs{LocalEligible: func() bool { return true },
+ SameBoxEmpty: func() (bool, error) { asked++; return true, nil },
+ OwnerTerminated: func(string) (bool, error) { asked++; return true, nil }}
+ other, mine := OwnerFor(Self{Ref: "b", IID: "i-b"}, 9, true), OwnerFor(self, 9, true)
+ clean, _ := MarkerBody(3, Marker{V: 1, Box: "b", IID: "i-b", Clean: true, Settled: true, At: now})
+ body := func(owner string, expires time.Time) []byte {
+ b, _ := json.Marshal(Lock{Generation: 9, ExpiresAt: expires, Owner: owner})
+ return b
+ }
+ for _, c := range []struct {
+ name string
+ body []byte
+ was Action // the decision without the field
+ field string
+ }{
+ {"held HA lock", body(other, now.Add(time.Minute)), ActHeld, "carlos_generation"},
+ {"clean marker", clean, ActTake, "carlos_release_g"},
+ {"another box's expired lock, terminated", body(other, now.Add(-time.Minute)), ActTake, "carlos_generation"},
+ {"same box, proven empty", body(mine, now.Add(-time.Minute)), ActTake, "carlos_generation"},
+ {"leftover legacy lock", body("ip-10-0-0-1:77", now.Add(-time.Minute)), ActRefuse, "carlos_generation"},
+ } {
+ v, err := DecodeLock(c.body, "e1")
+ if err != nil {
+ t.Fatalf("%s: %v", c.name, err)
+ }
+ if d := DecideAcquire(v, self, now, term, p); d.Action != c.was {
+ t.Fatalf("%s without the field: %+v, want %v", c.name, d, c.was)
+ }
+ var m map[string]any
+ if err := json.Unmarshal(c.body, &m); err != nil {
+ t.Fatal(err)
+ }
+ m[c.field] = "g-00000000000000000003"
+ withField, _ := json.Marshal(m)
+ if v, err = DecodeLock(withField, "e2"); err != nil {
+ t.Fatalf("%s: %v", c.name, err)
+ }
+ asked = 0
+ d := DecideAcquire(v, self, now, term, p)
+ if d.Action != ActRefuse || d.Reason != ReasonUnknownField || !d.Until.IsZero() {
+ t.Errorf("%s with %s: %+v, want refuse %q", c.name, c.field, d, ReasonUnknownField)
+ }
+ if asked != 0 {
+ t.Errorf("%s with %s: %d proofs asked", c.name, c.field, asked)
+ }
+ }
+ // Pool eligibility still comes first.
+ v := View{Lock: Lock{ExpiresAt: now.Add(time.Minute), Owner: other}, Unknown: []string{"carlos_generation"}}
+ if d := DecideAcquire(v, self, now, term, Proofs{}); d.Reason != ReasonPoolIneligible {
+ t.Fatalf("ineligible box: %+v", d)
+ }
+}
diff --git a/internal/hafresh/lock.go b/internal/hafresh/lock.go
index 2cc57624d..6bce609be 100644
--- a/internal/hafresh/lock.go
+++ b/internal/hafresh/lock.go
@@ -4,6 +4,7 @@ import (
"encoding/json"
"errors"
"fmt"
+ "sort"
"strings"
"time"
)
@@ -74,10 +75,40 @@ type Lock struct {
// View is one read of a lock: absent, or the lock and the ETag it was read
// at. Every conditional write is made against exactly the ETag of the
// view it classified.
+//
+// Unknown lists, sorted, the lock body's carlos_ keys this binary does not
+// know (UnknownFields): a later release's lock, which every take refuses
+// (ReasonUnknownField). Nil when there are none.
type View struct {
- Absent bool
- Lock Lock
- ETag string
+ Absent bool
+ Lock Lock
+ ETag string
+ Unknown []string
+}
+
+// knownLockFields are the lock body keys this binary reads. Any other key
+// starting carlos_ was written by a later release (storage generations
+// writes carlos_generation and carlos_release_g), and a take that does not
+// know what it means must not write over it. Other keys are ignored:
+// litestream may add fields of its own.
+var knownLockFields = map[string]bool{"generation": true, "expires_at": true, "owner": true, "carlos_release": true}
+
+// UnknownFields is the sorted list of body's top-level carlos_ keys that
+// are not knownLockFields, nil when there are none. A body that is not a
+// JSON object is an error.
+func UnknownFields(body []byte) ([]string, error) {
+ var fields map[string]json.RawMessage
+ if err := json.Unmarshal(body, &fields); err != nil {
+ return nil, err
+ }
+ var unknown []string
+ for k := range fields {
+ if strings.HasPrefix(k, "carlos_") && !knownLockFields[k] {
+ unknown = append(unknown, k)
+ }
+ }
+ sort.Strings(unknown)
+ return unknown, nil
}
// MarkerOwnerPrefix starts a release marker's owner. A marker is never a
@@ -114,6 +145,7 @@ func MarkerBody(generation int64, m Marker) ([]byte, error) {
// DecodeLock reads a lock.json body read at etag. A body that is not a
// lock, or a lock with no expiry, is an error, never "free": absence is
// only ever S3's own answer, which the caller reads before calling this.
+// The view's Unknown lists the carlos_ fields this binary does not know.
func DecodeLock(body []byte, etag string) (View, error) {
var l Lock
if err := json.Unmarshal(body, &l); err != nil {
@@ -122,7 +154,11 @@ func DecodeLock(body []byte, etag string) (View, error) {
if l.ExpiresAt.IsZero() {
return View{}, errors.New("hafresh: the lock has no expiry")
}
- return View{Lock: l, ETag: etag}, nil
+ unknown, err := UnknownFields(body)
+ if err != nil {
+ return View{}, fmt.Errorf("hafresh: decode lock: %w", err)
+ }
+ return View{Lock: l, ETag: etag, Unknown: unknown}, nil
}
// HAOn reports whether the lock is HA-format: a release marker (the
diff --git a/internal/hafresh/lock_test.go b/internal/hafresh/lock_test.go
new file mode 100644
index 000000000..2e6773ccd
--- /dev/null
+++ b/internal/hafresh/lock_test.go
@@ -0,0 +1,35 @@
+package hafresh
+
+import (
+ "slices"
+ "testing"
+)
+
+// Slice 0 (storage generations spec §9): a lock body's carlos_ keys this
+// binary does not know are listed, sorted; keys it knows, and keys outside
+// the carlos_ namespace (Litestream may add its own), are not.
+func TestDecodeLockListsUnknownCarlosFields(t *testing.T) {
+ v, err := DecodeLock([]byte(`{"generation":3,"expires_at":"2026-11-17T00:00:00Z","owner":"box/v1;ref=a;iid=i-1;pid=1;ha=1","carlos_generation":"g-00000000000000000003","x_other":1}`), "e1")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !slices.Equal(v.Unknown, []string{"carlos_generation"}) {
+ t.Fatalf("Unknown %q, want [carlos_generation]", v.Unknown)
+ }
+ for body, want := range map[string][]string{
+ // Every key this binary knows, carlos_release included.
+ `{"generation":1,"expires_at":"1970-01-01T00:00:00Z","owner":"released/v1;ref=a","carlos_release":{"v":1,"box":"a"}}`: nil,
+ // Sorted, and a null value is still a field.
+ `{"generation":1,"expires_at":"1970-01-01T00:00:00Z","owner":"released/v1;ref=a;gen=1","carlos_release_g":{"v":1},"carlos_generation":null}`: {"carlos_generation", "carlos_release_g"},
+ // Prefix-exact: neither "carlos" alone nor "Carlos_x" is a carlos_ key.
+ `{"generation":1,"expires_at":"2030-01-01T00:00:00Z","owner":"ip-10-0-0-1:77","carlos":1,"Carlos_x":1}`: nil,
+ } {
+ v, err := DecodeLock([]byte(body), "")
+ if err != nil {
+ t.Fatalf("%s: %v", body, err)
+ }
+ if !slices.Equal(v.Unknown, want) {
+ t.Errorf("%s: Unknown %q, want %q", body, v.Unknown, want)
+ }
+ }
+}
diff --git a/internal/lease/ha_test.go b/internal/lease/ha_test.go
index 3aabeffa9..3c6bd2b3d 100644
--- a/internal/lease/ha_test.go
+++ b/internal/lease/ha_test.go
@@ -300,6 +300,31 @@ func TestLegacyAcquireRefusesHALock(t *testing.T) {
}
}
+// Slice 0 (storage generations spec §9): the legacy path refuses a lock
+// carrying a carlos_ field it does not know, even under a legacy owner
+// that has expired (which it would otherwise take), and writes nothing.
+func TestLegacyAcquireRefusesUnknownField(t *testing.T) {
+ var m map[string]any
+ if err := json.Unmarshal(leaseBody("ip-10-0-0-1:77", time.Now().Add(-time.Hour)), &m); err != nil {
+ t.Fatal(err)
+ }
+ m["carlos_generation"] = "g-00000000000000000009"
+ body, _ := json.Marshal(m)
+ fx := leasetest.NewLockFixture(t)
+ fx.PutLock("instances/h", body)
+ _, err := lease.Acquire(ctx, fx.Bucket, "instances/h", "")
+ var ha *lease.HALockError
+ if !errors.As(err, &ha) || !slices.Equal(ha.View.Unknown, []string{"carlos_generation"}) {
+ t.Fatalf("legacy path took a lock with an unknown field: %v", err)
+ }
+ if !bytes.Equal(fx.LockBody("instances/h"), body) {
+ t.Fatalf("the lock was rewritten: %s", fx.LockBody("instances/h"))
+ }
+ if w := writes(fx); !slices.Equal(w, []string{"PUT instances/h/lock.json"}) { // the create-only write, refused
+ t.Fatalf("writes %v", w)
+ }
+}
+
// r3.1 interleaving: the legacy take is conditional on the ETag it
// classified, and a lost condition is reclassified.
func TestLegacyTakeIsConditionalOnTheClassifiedETag(t *testing.T) {
diff --git a/internal/lease/legacytake.go b/internal/lease/legacytake.go
index 0b13f88fc..76b7462c1 100644
--- a/internal/lease/legacytake.go
+++ b/internal/lease/legacytake.go
@@ -8,6 +8,7 @@ import (
"fmt"
"io"
"log"
+ "strings"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
@@ -19,13 +20,18 @@ import (
)
// HALockError is the legacy acquire's answer for an HA-format lock (a
-// release marker, or an owner with ;ha=1): nothing was written, whatever
-// the caller believed about the host. The caller takes the HA acquire
-// instead and treats the host as HA from then on. View is the lock as it
-// was classified.
+// release marker, or an owner with ;ha=1), or for any lock carrying a
+// carlos_ field this binary does not know (View.Unknown, a later
+// release's lock): nothing was written, whatever the caller believed about
+// the host. The caller takes the HA acquire instead and treats the host as
+// HA from then on; that acquire refuses an unknown field too
+// (hafresh.ReasonUnknownField). View is the lock as it was classified.
type HALockError struct{ View hafresh.View }
func (e *HALockError) Error() string {
+ if len(e.View.Unknown) > 0 {
+ return fmt.Sprintf("lease: the lock carries fields this release does not know (%s; owner %q); the legacy acquire wrote nothing", strings.Join(e.View.Unknown, ", "), e.View.Lock.Owner)
+ }
return fmt.Sprintf("lease: the lock is HA-format (owner %q); the legacy acquire wrote nothing", e.View.Lock.Owner)
}
@@ -41,7 +47,8 @@ const takeRounds = 3
// present, in place of litestream's AcquireLease (which decodes an HA lock
// leniently and would take an expired one):
//
-// - an HA-format lock: *HALockError, nothing written;
+// - an HA-format lock, or one carrying a carlos_ field this binary does
+// not know: *HALockError, nothing written;
// - unexpired, written by this box under an earlier kernel boot
// (hafresh.PreviousBoot): taken at once, as an expired one is (#451);
// - unexpired otherwise (leaseFree is false): *HeldError, nothing written;
@@ -62,7 +69,7 @@ func takeLegacy(ctx context.Context, client lss3.S3API, l *lss3.Leaser, self haf
if v.Absent {
return nil
}
- if v.HAOn() {
+ if v.HAOn() || len(v.Unknown) > 0 {
return &HALockError{View: v}
}
if !leaseFree(v.Lock.ExpiresAt, time.Now()) {
diff --git a/internal/lease/tombstone.go b/internal/lease/tombstone.go
index 7f9969a21..947e6f8cb 100644
--- a/internal/lease/tombstone.go
+++ b/internal/lease/tombstone.go
@@ -40,6 +40,8 @@ import (
awss3 "github.com/aws/aws-sdk-go-v2/service/s3"
"github.com/benbjohnson/litestream"
lss3 "github.com/benbjohnson/litestream/s3"
+
+ "github.com/carlosframework/platform/internal/hafresh"
)
// TombstonePrefix starts the owner of every tombstone lease. The three
@@ -63,6 +65,10 @@ var (
// ErrTombstoneLost reports that the tombstone Reassert was asked to
// keep is absent or expired: the stop was lost. Nothing was written.
ErrTombstoneLost = errors.New("lease: the tombstone is absent or expired; the stop was lost")
+ // ErrUnknownLockField refuses a lock carrying a carlos_ field this
+ // binary does not know (hafresh.UnknownFields): a later release wrote
+ // it, and Tombstone does not write over it. Nothing was written.
+ ErrUnknownLockField = errors.New("lease: the lock carries fields this release does not know")
)
// leaseFree is the predicate litestream's AcquireLease applies to the lease
@@ -118,33 +124,43 @@ func tombstoneLeaser(ctx context.Context, bucket, location, region, owner string
// NoSuchKey is absence (lockAbsent); a garbled body, an oversized one or a
// lock with no expiry is an error, never "free".
func readLock(ctx context.Context, leaser *lss3.Leaser, key string) (lock *litestream.Lease, absent bool, err error) {
+ lock, _, absent, err = readLockFields(ctx, leaser, key)
+ return lock, absent, err
+}
+
+// readLockFields is readLock, plus the lock body's carlos_ fields this
+// binary does not know (hafresh.UnknownFields).
+func readLockFields(ctx context.Context, leaser *lss3.Leaser, key string) (lock *litestream.Lease, unknown []string, absent bool, err error) {
out, err := leaser.Client().GetObject(ctx, &awss3.GetObjectInput{Bucket: aws.String(leaser.Bucket), Key: aws.String(key)})
if err != nil {
if lockAbsent(err) {
- return nil, true, nil
+ return nil, nil, true, nil
}
- return nil, false, fmt.Errorf("lease: read %s: %w", key, err)
+ return nil, nil, false, fmt.Errorf("lease: read %s: %w", key, err)
}
defer out.Body.Close()
body, err := io.ReadAll(io.LimitReader(out.Body, lockBodyLimit+1))
if err != nil {
- return nil, false, fmt.Errorf("lease: read %s: %w", key, err)
+ return nil, nil, false, fmt.Errorf("lease: read %s: %w", key, err)
}
if len(body) > lockBodyLimit {
- return nil, false, fmt.Errorf("lease: %s is larger than a lock", key)
+ return nil, nil, false, fmt.Errorf("lease: %s is larger than a lock", key)
}
var l litestream.Lease
if err := json.Unmarshal(body, &l); err != nil {
- return nil, false, fmt.Errorf("lease: decode %s: %w", key, err)
+ return nil, nil, false, fmt.Errorf("lease: decode %s: %w", key, err)
}
if l.ExpiresAt.IsZero() {
- return nil, false, fmt.Errorf("lease: %s has no expiry", key)
+ return nil, nil, false, fmt.Errorf("lease: %s has no expiry", key)
}
if out.ETag == nil || *out.ETag == "" {
- return nil, false, fmt.Errorf("lease: %s came back without an ETag", key)
+ return nil, nil, false, fmt.Errorf("lease: %s came back without an ETag", key)
+ }
+ if unknown, err = hafresh.UnknownFields(body); err != nil {
+ return nil, nil, false, fmt.Errorf("lease: decode %s: %w", key, err)
}
l.ETag = *out.ETag
- return &l, false, nil
+ return &l, unknown, false, nil
}
func heldErr(l *litestream.Lease) error {
@@ -154,6 +170,8 @@ func heldErr(l *litestream.Lease) error {
// Tombstone writes the lease at s3://bucket/<location>/lock.json owned by
// owner (moved:<id>), expiring ttl from now (at most MaxTombstoneTTL).
//
+// - carrying a carlos_ field this binary does not know, live or not:
+// ErrUnknownLockField, nothing written;
// - absent, or expired (as Acquire reads it): created (IfNoneMatch "*") or
// replaced (IfMatch on the expired lease's ETag);
// - live and held by owner: nil and no write; the caller re-asserts with
@@ -176,10 +194,14 @@ func Tombstone(ctx context.Context, bucket, location, region, owner string, ttl
if err != nil {
return err
}
- cur, absent, err := readLock(ctx, leaser, key)
+ cur, unknown, absent, err := readLockFields(ctx, leaser, key)
if err != nil {
return err
}
+ if len(unknown) > 0 {
+ // A later release's lock (storage generations, spec §9 slice 0).
+ return fmt.Errorf("tombstone lease: %w (%s; owner %q)", ErrUnknownLockField, strings.Join(unknown, ", "), cur.Owner)
+ }
if !absent && !leaseFree(cur.ExpiresAt, time.Now()) {
if cur.Owner == owner {
return nil
diff --git a/internal/lease/tombstone_test.go b/internal/lease/tombstone_test.go
index abdc5e70b..616f0ea76 100644
--- a/internal/lease/tombstone_test.go
+++ b/internal/lease/tombstone_test.go
@@ -231,6 +231,30 @@ func TestTombstoneAndAcquireAgreeOnFree(t *testing.T) {
}
}
+// Slice 0 (storage generations spec §9): Tombstone takes an expired lock
+// over, so it refuses one carrying a carlos_ field this binary does not
+// know (a storage-generations lock or release marker), and writes nothing.
+func TestTombstoneRefusesUnknownField(t *testing.T) {
+ for _, field := range []string{"carlos_generation", "carlos_release_g"} {
+ s := tombFixture(t)
+ body, err := json.Marshal(map[string]any{"generation": 3, "expires_at": time.Now().Add(-time.Hour).UTC(), "owner": "box/v1;ref=b;iid=i-b;pid=7;ha=1", field: "g-00000000000000000003"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ s.Put("data", tombLoc+"/lock.json", body)
+ err = lease.Tombstone(context.Background(), "data", tombLoc, tombRegion, tombMove, time.Hour)
+ if !errors.Is(err, lease.ErrUnknownLockField) || !strings.Contains(err.Error(), field) {
+ t.Fatalf("%s: Tombstone = %v, want ErrUnknownLockField naming the field", field, err)
+ }
+ if _, after, _ := s.lock(t, tombLoc); !bytes.Equal(after, body) {
+ t.Fatalf("%s: lock.json changed: %s", field, after)
+ }
+ if s.writeCount() != 0 {
+ t.Fatalf("%s: Tombstone wrote %v", field, s.methods())
+ }
+ }
+}
+
// An own tombstone that has expired is free like any other: Tombstone writes
// a fresh one rather than reporting the dead one held.
func TestTombstoneRewritesItsOwnExpiredTombstone(t *testing.T) {