carlos / platform Public

sim: model storage generations; minio: a live take

The region HA model now writes generations locks for hosts in
generations mode (fast on every box): the take reads head.json, plans
at G's newest L0 with its bound, copies into g-N, restores or keeps,
fences the files manifest and switches If-Match; late writes and late
switch PUTs are tagged by generation; retirement runs in the
background. New invariants G1, I1g, G2, I2g and R8; takeover-before-
expiry and expiry-authorizes restated for generations locks under
fast. Eleven new rules, each with a witness; the three retirement
guards are caught together only (expected-outcomes.txt).
TestKnownGapBoundLostOnCrashMidTake documents that a crash mid-take
drops the min_txid bound.

TestGenerationTakeMinio runs the take through a recording proxy to
MinIO (CopyObject ?versionId= with If-None-Match: *, head.json 412,
the held late write, the copy by version) and pins the store's
refusal of a request signed 16 minutes off; 30-minio-contract runs it
and requires every subtest's PASS line.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 485254b61db0b758cefd9a950c3ba399aaf85d49 parent 5b84a70
10 files changed, +1,999 −47
  • .amadan/ci.d/30-minio-contract +50 −0
  • internal/lease/gentake_minio_test.go +565 −0
  • internal/sim/regionha/actions_test.go +101 −35
  • internal/sim/regionha/expected-outcomes.txt +15 −3
  • internal/sim/regionha/generations_test.go +1,081 −0
  • internal/sim/regionha/invariants_test.go +49 −0
  • internal/sim/regionha/rules_test.go +24 −3
  • internal/sim/regionha/sim_test.go +4 −0
  • internal/sim/regionha/witness_test.go +29 −0
  • internal/sim/regionha/world_test.go +81 −6
diff --git a/.amadan/ci.d/30-minio-contract b/.amadan/ci.d/30-minio-contract
index bcb0e5c98..f8c7f500b 100755
--- a/.amadan/ci.d/30-minio-contract
+++ b/.amadan/ci.d/30-minio-contract
@@ -576,4 +576,54 @@ for name in TestHeldHandoverTwoBoxMinio TestHeldHandoverLostLeaseMinio; do
fi
done
+# The storage generations take (spec 2026-11-12 §4, §8; plan Task 11):
+# CopyObject by version id with If-None-Match: * on the destination,
+# head.json's If-Match 412 on a stale ETag, a held late write landing in
+# the earlier holder's generation, and the store's refusal of a request
+# signed more than 15 minutes off (retirement's safety rests on it). The
+# take copies exact object versions, so it needs a versioned bucket of its
+# own; the user may read versions (the copies) and delete versions (the
+# test's cleanup). Same rule as above: the test skips without
+# CARLOS_MINIO_TEST, so the parent's and every subtest's PASS line must
+# appear.
+"$mc" --quiet mb local/gen-take
+"$mc" --quiet version enable local/gen-take
+cat >"$rundir/gen-take.json" <<'EOF'
+{"Version": "2012-10-17", "Statement": [
+ {"Effect": "Allow", "Action": ["s3:ListBucket", "s3:ListBucketVersions"], "Resource": ["arn:aws:s3:::gen-take"]},
+ {"Effect": "Allow", "Action": ["s3:GetObject", "s3:GetObjectVersion", "s3:PutObject", "s3:DeleteObject", "s3:DeleteObjectVersion"], "Resource": ["arn:aws:s3:::gen-take/*"]}
+]}
+EOF
+"$mc" --quiet admin policy create local gen-take "$rundir/gen-take.json"
+"$mc" --quiet admin user add local gentake gentakesecret1
+"$mc" --quiet admin policy attach local gen-take --user gentake
+
+out6=$rundir/test-gentake.log
+set +e
+CARLOS_MINIO_TEST=1 \
+ MINIO_ENDPOINT="http://127.0.0.1:$port" \
+ MINIO_GEN_BUCKET=gen-take \
+ MINIO_GEN_KEY=gentake \
+ MINIO_GEN_SECRET=gentakesecret1 \
+ go test ./internal/lease/ -run '^TestGenerationTakeMinio$' -count=1 -v >"$out6" 2>&1
+test_status=$?
+set -e
+cat "$out6"
+if [ "$test_status" -ne 0 ]; then
+ exit "$test_status"
+fi
+if ! grep -q '^--- PASS: TestGenerationTakeMinio (' "$out6"; then
+ echo >&2
+ echo "the generation take test did not PASS: it was skipped, filtered out, or renamed." >&2
+ echo "It skips unless CARLOS_MINIO_TEST=1. Check the env block above and that" >&2
+ echo "TestGenerationTakeMinio still exists in internal/lease." >&2
+ exit 1
+fi
+for sub in take switch-412 copy-version skew; do
+ if ! grep -q "^ --- PASS: TestGenerationTakeMinio/$sub (" "$out6"; then
+ echo "the generation take subtest $sub did not PASS: skipped, filtered out, or renamed" >&2
+ exit 1
+ fi
+done
+
echo "minio contract: PASS"
diff --git a/internal/lease/gentake_minio_test.go b/internal/lease/gentake_minio_test.go
new file mode 100644
index 000000000..1a71ef5d1
--- /dev/null
+++ b/internal/lease/gentake_minio_test.go
@@ -0,0 +1,565 @@
+package lease_test
+
+import (
+ "bytes"
+ "context"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "net/http/httputil"
+ "net/url"
+ "os"
+ "path/filepath"
+ "slices"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/aws/aws-sdk-go-v2/aws"
+ v4 "github.com/aws/aws-sdk-go-v2/aws/signer/v4"
+ "github.com/aws/aws-sdk-go-v2/credentials"
+ awss3 "github.com/aws/aws-sdk-go-v2/service/s3"
+ "github.com/aws/smithy-go"
+ smithyhttp "github.com/aws/smithy-go/transport/http"
+
+ "github.com/carlosframework/platform/internal/hafresh"
+ "github.com/carlosframework/platform/internal/lease"
+ "github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/replicagen"
+)
+
+// TestGenerationTakeMinio is the storage generations take (spec 2026-11-12
+// §4, §5.1, §8; plan Task 11) against a real MinIO, the only store-side
+// behaviour the take and retirement rest on that no fake shows:
+//
+// - take: a holder's upload is held in flight while a successor takes on
+// the termination proof (fast); the take's copies are CopyObject with
+// ?versionId= and If-None-Match: * on the destination, and MinIO
+// refuses a second copy onto it; head.json's If-Match refuses a stale
+// ETag; the held upload lands afterwards in the earlier holder's
+// generation, and nothing read through head.json sees it;
+// - switch-412: head.json changes between a take's read and its switch,
+// so the switch gets MinIO's 412 (lease.ErrHeadMoved), deletes
+// nothing, and the release carries the take's bound (min_txid);
+// - copy-version: a copy by version id copies that version, whatever
+// the source key holds now (G3);
+// - skew: a request signed more than 15 minutes off the store's clock is
+// refused, one signed a minute off is accepted. Retirement deletes a
+// generation that left history at once, by this box's clock
+// (RetireGrace, an hour, is what covers the error), so its safety
+// rests on the store refusing a box whose clock is further off than
+// that: provider-neutral, it is pinned here, for the delete and the
+// listing retirement sends.
+//
+// It skips without CARLOS_MINIO_TEST=1. With it, every MINIO_GEN_* variable
+// must be set: MINIO_ENDPOINT, MINIO_GEN_BUCKET (a versioned bucket),
+// MINIO_GEN_KEY and MINIO_GEN_SECRET. .amadan/ci.d/30-minio-contract runs
+// it and requires each subtest's PASS line.
+func TestGenerationTakeMinio(t *testing.T) {
+ if os.Getenv("CARLOS_MINIO_TEST") != "1" {
+ t.Skip("set CARLOS_MINIO_TEST=1 and the MINIO_GEN_* env vars to run the generation take against MinIO")
+ }
+ m := minioGen{
+ endpoint: genMinioEnv(t, "MINIO_ENDPOINT"),
+ bucket: genMinioEnv(t, "MINIO_GEN_BUCKET"),
+ key: genMinioEnv(t, "MINIO_GEN_KEY"),
+ secret: genMinioEnv(t, "MINIO_GEN_SECRET"),
+ }
+ t.Run("take", m.take)
+ t.Run("switch-412", m.switch412)
+ t.Run("copy-version", m.copyVersion)
+ t.Run("skew", m.skew)
+}
+
+// genMinioEnv is a required variable: with CARLOS_MINIO_TEST=1 a missing
+// one fails, never skips.
+func genMinioEnv(t *testing.T, name string) string {
+ t.Helper()
+ v := os.Getenv(name)
+ if v == "" {
+ t.Fatalf("CARLOS_MINIO_TEST=1 but %s is not set", name)
+ }
+ return v
+}
+
+// minioGen is the MinIO the test runs against: a versioned bucket and a
+// user scoped to it.
+type minioGen struct {
+ endpoint, bucket, key, secret string
+}
+
+// copyReq is one CopyObject that reached MinIO through the fixture: the
+// destination key, its x-amz-copy-source and If-None-Match, and the
+// status MinIO answered.
+type copyReq struct {
+ phase, dst, source, ifNoneMatch string
+ status int
+}
+
+// minioCopies records every CopyObject the fixture forwards.
+type minioCopies struct {
+ mu sync.Mutex
+ reqs []copyReq
+}
+
+func (c *minioCopies) in(phase string) []copyReq {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ var out []copyReq
+ for _, r := range c.reqs {
+ if r.phase == phase {
+ out = append(out, r)
+ }
+ }
+ return out
+}
+
+// fixture is a genFixture whose server is a recording reverse proxy to
+// MinIO (the take tests' hooks, phases and partitions work unchanged),
+// under a host location of its own; every version under it is deleted
+// when the test ends. The lease's clients reach it through
+// CARLOS_S3_ENDPOINT with the scoped user's keys.
+func (m minioGen) fixture(t *testing.T) (*genFixture, *minioCopies) {
+ t.Helper()
+ target, err := url.Parse(m.endpoint)
+ if err != nil {
+ t.Fatal(err)
+ }
+ proxy := &httputil.ReverseProxy{Rewrite: func(pr *httputil.ProxyRequest) {
+ pr.SetURL(target)
+ pr.Out.Host = pr.In.Host // the client signed the proxy's host
+ }}
+ fx := &genFixture{bucket: m.bucket, loc: fmt.Sprintf("instances/gen-%d.shop.example.com", time.Now().UnixNano()), region: "us-east-1"}
+ copies := &minioCopies{}
+ inner := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ source := r.Header.Get("x-amz-copy-source")
+ if r.Method != http.MethodPut || source == "" {
+ proxy.ServeHTTP(w, r)
+ return
+ }
+ sw := &statusWriter{ResponseWriter: w}
+ proxy.ServeHTTP(sw, r)
+ fx.mu.Lock()
+ phase := fx.phase
+ fx.mu.Unlock()
+ dst, _ := url.PathUnescape(strings.TrimPrefix(r.URL.EscapedPath(), "/"+m.bucket+"/"))
+ copies.mu.Lock()
+ copies.reqs = append(copies.reqs, copyReq{phase: phase, dst: dst, source: source, ifNoneMatch: r.Header.Get("If-None-Match"), status: sw.status})
+ copies.mu.Unlock()
+ })
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ key, _ := url.PathUnescape(strings.TrimPrefix(r.URL.EscapedPath(), "/"+fx.bucket+"/"))
+ if r.Method == http.MethodPut || r.Method == http.MethodPost {
+ body, err := io.ReadAll(r.Body)
+ if err != nil {
+ return
+ }
+ r.Body = io.NopCloser(bytes.NewReader(body))
+ if r.Method == http.MethodPost && r.URL.Query().Has("delete") {
+ keys := deleteObjectKeys(body)
+ fx.record(r, keys)
+ fx.serve(w, r, inner, keys)
+ return
+ }
+ }
+ fx.record(r, []string{key})
+ fx.serve(w, r, inner, []string{key})
+ }))
+ t.Cleanup(srv.Close)
+ t.Setenv("AWS_ACCESS_KEY_ID", m.key)
+ t.Setenv("AWS_SECRET_ACCESS_KEY", m.secret)
+ t.Setenv("AWS_SESSION_TOKEN", "")
+ t.Setenv("AWS_EC2_METADATA_DISABLED", "true")
+ t.Setenv("AWS_CONFIG_FILE", filepath.Join(t.TempDir(), "absent"))
+ t.Setenv("AWS_SHARED_CREDENTIALS_FILE", filepath.Join(t.TempDir(), "absent"))
+ t.Setenv("CARLOS_S3_ENDPOINT", srv.URL)
+ if fx.st, err = lease.NewFilesStore(ctx, fx.bucket, fx.region); err != nil {
+ t.Fatal(err)
+ }
+ if fx.vs, err = lease.NewVersionedS3(ctx, map[string]string{fx.bucket: fx.region}); err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { m.deleteAll(t, fx.vs, fx.loc+"/") }) // runs before srv.Close
+ return fx, copies
+}
+
+// deleteAll removes every version and delete marker under prefix.
+func (m minioGen) deleteAll(t *testing.T, vs lease.VersionedStore, prefix string) {
+ t.Helper()
+ all, err := vs.ListVersions(context.Background(), m.bucket, prefix)
+ if err != nil {
+ t.Logf("cleanup: list %s: %v", prefix, err)
+ return
+ }
+ for _, v := range all {
+ if err := vs.DeleteVersion(context.Background(), m.bucket, v.Key, v.VersionID); err != nil {
+ t.Logf("cleanup: delete %s@%s: %v", v.Key, v.VersionID, err)
+ }
+ }
+}
+
+// currentBodies is every current object under prefix, by key.
+func currentBodies(t *testing.T, fx *genFixture, prefix string) map[string][]byte {
+ t.Helper()
+ all, err := fx.vs.ListVersions(ctx, fx.bucket, prefix)
+ if err != nil {
+ t.Fatal(err)
+ }
+ out := map[string][]byte{}
+ for _, v := range all {
+ if !v.IsLatest || v.DeleteMarker {
+ continue
+ }
+ body, err := fx.vs.GetVersion(ctx, fx.bucket, v.Key, v.VersionID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ out[v.Key] = body
+ }
+ return out
+}
+
+// parseCopySource splits an x-amz-copy-source into its key under bucket
+// and its versionId.
+func parseCopySource(t *testing.T, bucket, source string) (key, version string) {
+ t.Helper()
+ path, query, _ := strings.Cut(source, "?")
+ key, err := url.PathUnescape(strings.TrimPrefix(strings.TrimPrefix(path, "/"), bucket+"/"))
+ if err != nil {
+ t.Fatalf("copy source %q: %v", source, err)
+ }
+ q, err := url.ParseQuery(query)
+ if err != nil {
+ t.Fatalf("copy source %q: %v", source, err)
+ }
+ return key, q.Get("versionId")
+}
+
+// take is the late-write witness (spec §12, first two items) on MinIO.
+func (m minioGen) take(t *testing.T) {
+ const ttl = time.Hour // A's lock is unexpired throughout: B takes on the proof (fast)
+ haBox(t)
+ fx, copies := m.fixture(t)
+ lw := newLateWrites(t, fx)
+ a, aPath, aGen := genHolderA(t, fx, ttl)
+ aPrefix := replicagen.Prefix(fx.loc, aGen)
+
+ // A's next upload reaches MinIO's front door and is held there
+ // unapplied, and A dies: the lock is still A's.
+ lw.partition(aPrefix)
+ witnessExec(t, aPath, `INSERT INTO t (body) VALUES ('a-only')`)
+ synced := make(chan error, 1)
+ go func() { synced <- a.SyncAndWait(ctx) }()
+ for deadline := time.Now().Add(10 * time.Second); len(lw.heldKeys()) == 0; time.Sleep(20 * time.Millisecond) {
+ if time.Now().After(deadline) {
+ t.Fatal("fixture: no write of A's reached the proxy")
+ }
+ }
+
+ boxB()
+ fx.setPhase("b")
+ staleHead, staleETag, found := fx.head(t) // head.json as B's take reads it: A's
+ if !found {
+ t.Fatal("A's first wake wrote no head.json")
+ }
+ terminated := func(iid string) (bool, error) { return iid == "i-a", nil }
+ bHeld, err := acquireB(fx, ttl, hafresh.Proofs{LocalEligible: func() bool { return true }, OwnerTerminated: terminated, GenerationsFast: true})
+ if err != nil {
+ t.Fatalf("B with fast, A terminated: %v", err)
+ }
+ bGen := replicagen.Name(bHeld.LockGeneration())
+ bPrefix := replicagen.Prefix(fx.loc, bGen)
+ bTake, err := bHeld.StartGeneration(ctx, fx.st, fx.vs, lease.TakeOptions{Self: selfB, Lifetime: "L2"})
+ if err != nil {
+ t.Fatalf("B's take: %v", err)
+ }
+ if bTake.Generation != bGen || bTake.Predecessor != aGen {
+ t.Fatalf("B's take: %s from %s, want %s from %s", bTake.Generation, bTake.Predecessor, bGen, aGen)
+ }
+
+ // The copies: CopyObject of an exact version of A's generation, into
+ // B's, create-only; MinIO answered each 200.
+ cs := copies.in("b")
+ if len(cs) == 0 {
+ t.Fatal("B's take sent no CopyObject")
+ }
+ for _, c := range cs {
+ src, ver := parseCopySource(t, fx.bucket, c.source)
+ if ver == "" || !strings.HasPrefix(src, aPrefix) || !strings.HasPrefix(c.dst, bPrefix) || c.ifNoneMatch != "*" || c.status != http.StatusOK {
+ t.Errorf("B's copy %+v: want %s...?versionId=<id> -> %s..., If-None-Match *, 200", c, aPrefix, bPrefix)
+ }
+ }
+ // If-None-Match: * on the destination is MinIO's: a second copy of the
+ // same version onto it is refused (412), and nothing changes.
+ src, ver := parseCopySource(t, fx.bucket, cs[0].source)
+ before := currentBodies(t, fx, bPrefix)
+ if _, _, err := fx.vs.CopyVersion(ctx, fx.bucket, src, ver, fx.bucket, cs[0].dst, true); !errors.Is(err, lease.ErrDestinationExists) {
+ t.Fatalf("a second create-only copy onto %s: %v, want ErrDestinationExists (MinIO's 412)", cs[0].dst, err)
+ }
+ if after := currentBodies(t, fx, bPrefix); !mapsEqualBytes(before, after) {
+ t.Fatal("the refused copy changed B's generation")
+ }
+
+ bPath := filepath.Join(t.TempDir(), "w.example.com.db")
+ if ok, err := lease.RestoreTake(ctx, bPath, bTake); err != nil || !ok {
+ t.Fatalf("B's restore: %v %v", ok, err)
+ }
+ if n := witnessCount(t, bPath, `body = 'a-only'`); n != 0 {
+ t.Fatalf("B's restore holds A's unanswered write (%d)", n)
+ }
+ if err := bTake.Switch(ctx); err != nil {
+ t.Fatalf("B's switch: %v", err)
+ }
+ // head.json's If-Match is MinIO's: the ETag B's take read is stale now.
+ if _, err := lease.PutHead(ctx, fx.st, fx.loc, staleHead, staleETag); !errors.Is(err, release.ErrCASConflict) {
+ t.Fatalf("head.json PUT If-Match a stale ETag: %v, want release.ErrCASConflict (412)", err)
+ }
+ b, err := bHeld.Replicate(ctx, bPath, 0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ witnessExec(t, bPath, `INSERT INTO t (body) VALUES ('b-only')`)
+ if err := b.SyncAndWait(ctx); err != nil {
+ t.Fatal(err)
+ }
+ bBodies := currentBodies(t, fx, bPrefix)
+
+ // A's held upload lands, after B's take, B's switch and B's write.
+ fx.setPhase("late")
+ lw.land(t)
+ select {
+ case <-synced:
+ case <-time.After(30 * time.Second):
+ t.Fatal("fixture: A's sync never returned after the heal")
+ }
+ done, cancel := context.WithCancel(ctx)
+ cancel()
+ a.Abandon(done)
+ for _, k := range lw.heldKeys() {
+ if !strings.HasPrefix(k, aPrefix) {
+ t.Errorf("A's late write %s is outside its generation %s", k, aGen)
+ }
+ }
+ after := currentBodies(t, fx, bPrefix)
+ for k, body := range bBodies {
+ if !bytes.Equal(after[k], body) {
+ t.Errorf("A's late write changed the successor's %s", k)
+ }
+ }
+ if h, _, _ := fx.head(t); h.Generation != bGen {
+ t.Fatalf("head.json names %s after the late write, want %s", h.Generation, bGen)
+ }
+ if err := b.Close(ctx); err != nil {
+ t.Fatal(err)
+ }
+
+ // Through head.json: B's history, without A's late write.
+ cPath := filepath.Join(t.TempDir(), "w.example.com.db")
+ if ok, err := lease.Restore(ctx, cPath, fx.bucket, fx.loc, fx.region); err != nil || !ok {
+ t.Fatalf("restore after the late write: %v %v", ok, err)
+ }
+ for where, want := range map[string]int{`body = 'b-only'`: 1, `body = 'a-only'`: 0, `body LIKE 'row-%'`: 10} {
+ if got := witnessCount(t, cPath, where); got != want {
+ t.Errorf("restore after the late write: %s %d, want %d", where, got, want)
+ }
+ }
+ // A's write is there, in A's generation only.
+ aRead, err := lease.BindReplica(ctx, fx.bucket, fx.loc, fx.region, aGen)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got := restoreAt(t, aRead, time.Time{}); !slices.Contains(got, "a-only") {
+ t.Errorf("A's generation restored %v: the late write did not land there", got)
+ }
+}
+
+// switch412 is §4 step 5's 412 on MinIO: head.json changes between the
+// take's read and its switch.
+func (m minioGen) switch412(t *testing.T) {
+ haBox(t)
+ fx, _ := m.fixture(t)
+ aGen, txid := fx.seed(t, time.Hour, 3)
+ boxB()
+ bHeld := fx.acquire(t, time.Hour) // over A's clean marker: at once
+ fx.setPhase("b")
+ head, etag, found := fx.head(t)
+ if !found || head.Generation != aGen {
+ t.Fatalf("head.json %+v found %v, want %s", head, found, aGen)
+ }
+ bTake, err := bHeld.StartGeneration(ctx, fx.st, fx.vs, lease.TakeOptions{Self: selfB, Lifetime: "L2", HeadRead: true, Head: head, HeadETag: etag, HeadFound: true})
+ if err != nil {
+ t.Fatalf("B's take: %v", err)
+ }
+ // head.json changes under the take (a late switch of an earlier take
+ // stands here: the same head, rewritten with another created_by.at,
+ // If-Match the ETag B read, which MinIO accepts).
+ moved := head
+ moved.CreatedBy.At = head.CreatedBy.At.Add(time.Second)
+ if _, err := lease.PutHead(ctx, fx.st, fx.loc, moved, etag); err != nil {
+ t.Fatalf("head.json PUT If-Match its current ETag: %v", err)
+ }
+ if err := bTake.Switch(ctx); !errors.Is(err, lease.ErrHeadMoved) || !errors.Is(err, release.ErrCASConflict) {
+ t.Fatalf("B's switch after head.json moved: %v, want ErrHeadMoved over MinIO's 412", err)
+ }
+ if h, _, _ := fx.head(t); h.Generation != aGen || !h.CreatedBy.At.Equal(moved.CreatedBy.At) {
+ t.Fatalf("head.json after B's 412: %+v, want the moved head of %s", h, aGen)
+ }
+ // The abandoned take deletes nothing: its copies stay for retirement.
+ if d := fx.deletes("b"); len(d) != 0 {
+ t.Fatalf("B's abandoned take deleted %v", d)
+ }
+ if got := currentBodies(t, fx, replicagen.Prefix(fx.loc, bTake.Generation)); len(got) == 0 {
+ t.Fatalf("B's abandoned %s holds nothing", bTake.Generation)
+ }
+ // Its release is settled and carries the take's bound (min_txid).
+ if err := bHeld.Release(ctx); err != nil {
+ t.Fatal(err)
+ }
+ body, etag, err := fx.st.Get(ctx, fx.loc+"/lock.json")
+ if err != nil {
+ t.Fatal(err)
+ }
+ v, err := hafresh.DecodeLock(body, etag)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if r := v.Lock.Release; r == nil || !r.Gen || !r.Settled || r.MinTXID != txid {
+ t.Fatalf("B's release left %+v, want a settled generations marker with min_txid %d", v.Lock, txid)
+ }
+}
+
+// copyVersion is G3 on MinIO: a copy names a source version, and a later
+// write to the source key does not reach it.
+func (m minioGen) copyVersion(t *testing.T) {
+ fx, _ := m.fixture(t)
+ src, dst := fx.loc+"/g-src/0000/0000000000000001-0000000000000001.ltx", fx.loc+"/g-dst/0000/0000000000000001-0000000000000001.ltx"
+ v1, err := fx.vs.PutIfAbsent(ctx, fx.bucket, src, []byte("first"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ // A later write to the source key: a plain PUT, a new current version.
+ if _, err := m.skewClient(0).PutObject(ctx, &awss3.PutObjectInput{Bucket: aws.String(fx.bucket), Key: aws.String(src), Body: strings.NewReader("second, a later write")}); err != nil {
+ t.Fatal(err)
+ }
+ if _, _, err := fx.vs.CopyVersion(ctx, fx.bucket, src, v1, fx.bucket, dst, true); err != nil {
+ t.Fatalf("copy %s@%s: %v", src, v1, err)
+ }
+ if got := currentBodies(t, fx, fx.loc+"/g-dst/")[dst]; string(got) != "first" {
+ t.Fatalf("the copy of version %s holds %q, want %q", v1, got, "first")
+ }
+}
+
+// skewedSigner is the SDK's own SigV4 signer with its signing time moved
+// by offset: a box whose clock is that far off the store's.
+type skewedSigner struct {
+ inner *v4.Signer
+ offset time.Duration
+}
+
+func (s skewedSigner) SignHTTP(ctx context.Context, creds aws.Credentials, r *http.Request, payloadHash, service, region string, signingTime time.Time, optFns ...func(*v4.SignerOptions)) error {
+ return s.inner.SignHTTP(ctx, creds, r, payloadHash, service, region, signingTime.Add(s.offset), optFns...)
+}
+
+// skewClient is an S3 client straight to MinIO whose signing clock is
+// offset off, with no retry (a retry would only repeat the answer).
+func (m minioGen) skewClient(offset time.Duration) *awss3.Client {
+ return awss3.New(awss3.Options{
+ Region: "us-east-1",
+ Credentials: credentials.NewStaticCredentialsProvider(m.key, m.secret, ""),
+ BaseEndpoint: aws.String(m.endpoint),
+ UsePathStyle: true,
+ RetryMaxAttempts: 1,
+ HTTPSignerV4: skewedSigner{offset: offset, inner: v4.NewSigner(func(o *v4.SignerOptions) {
+ o.DisableURIPathEscaping = true // as the S3 client's default signer
+ })},
+ RequestChecksumCalculation: aws.RequestChecksumCalculationWhenRequired,
+ ResponseChecksumValidation: aws.ResponseChecksumValidationWhenRequired,
+ })
+}
+
+// refusedForSkew reports a store's refusal of a request's signing time:
+// RequestTimeTooSkewed, or the provider's own 403 for it.
+func refusedForSkew(err error) bool {
+ var ae smithy.APIError
+ if errors.As(err, &ae) && ae.ErrorCode() == "RequestTimeTooSkewed" {
+ return true
+ }
+ var re *smithyhttp.ResponseError
+ return errors.As(err, &re) && re.HTTPStatusCode() == http.StatusForbidden
+}
+
+// skew pins the store's clock check that retirement's safety relies on.
+func (m minioGen) skew(t *testing.T) {
+ run := fmt.Sprintf("skew-%d/", time.Now().UnixNano())
+ key := run + "instances/shop.example.com/g-00000000000000000001/0000/0000000000000001-0000000000000001.ltx"
+ right := m.skewClient(0)
+ t.Cleanup(func() {
+ out, err := right.ListObjectVersions(context.Background(), &awss3.ListObjectVersionsInput{Bucket: aws.String(m.bucket), Prefix: aws.String(run)})
+ if err != nil {
+ t.Logf("cleanup: %v", err)
+ return
+ }
+ for _, v := range out.Versions {
+ _, _ = right.DeleteObject(context.Background(), &awss3.DeleteObjectInput{Bucket: aws.String(m.bucket), Key: v.Key, VersionId: v.VersionId})
+ }
+ for _, d := range out.DeleteMarkers {
+ _, _ = right.DeleteObject(context.Background(), &awss3.DeleteObjectInput{Bucket: aws.String(m.bucket), Key: d.Key, VersionId: d.VersionId})
+ }
+ })
+ if _, err := right.PutObject(ctx, &awss3.PutObjectInput{Bucket: aws.String(m.bucket), Key: aws.String(key), Body: strings.NewReader("ltx")}); err != nil {
+ t.Fatalf("put with the right clock: %v", err)
+ }
+ present := func() bool {
+ t.Helper()
+ _, err := right.HeadObject(ctx, &awss3.HeadObjectInput{Bucket: aws.String(m.bucket), Key: aws.String(key)})
+ var re *smithyhttp.ResponseError
+ if errors.As(err, &re) && re.HTTPStatusCode() == http.StatusNotFound {
+ return false
+ }
+ if err != nil {
+ t.Fatalf("head with the right clock: %v", err)
+ }
+ return true
+ }
+ for _, off := range []time.Duration{16 * time.Minute, -16 * time.Minute} {
+ c := m.skewClient(off)
+ _, err := c.ListObjectVersions(ctx, &awss3.ListObjectVersionsInput{Bucket: aws.String(m.bucket), Prefix: aws.String(run)})
+ if !refusedForSkew(err) {
+ t.Errorf("a listing signed %v off: %v, want RequestTimeTooSkewed (403)", off, err)
+ }
+ _, err = c.DeleteObject(ctx, &awss3.DeleteObjectInput{Bucket: aws.String(m.bucket), Key: aws.String(key)})
+ if !refusedForSkew(err) {
+ t.Errorf("a delete signed %v off: %v, want RequestTimeTooSkewed (403)", off, err)
+ }
+ if !present() {
+ t.Fatalf("a delete signed %v off removed %s", off, key)
+ }
+ }
+ for _, off := range []time.Duration{time.Minute, -time.Minute} {
+ c := m.skewClient(off)
+ if _, err := c.ListObjectVersions(ctx, &awss3.ListObjectVersionsInput{Bucket: aws.String(m.bucket), Prefix: aws.String(run)}); err != nil {
+ t.Errorf("a listing signed %v off: %v, want accepted", off, err)
+ }
+ }
+ if _, err := m.skewClient(time.Minute).DeleteObject(ctx, &awss3.DeleteObjectInput{Bucket: aws.String(m.bucket), Key: aws.String(key)}); err != nil {
+ t.Fatalf("a delete signed a minute off: %v, want accepted", err)
+ }
+ if present() {
+ t.Fatalf("a delete signed a minute off left %s current", key)
+ }
+}
+
+func mapsEqualBytes(a, b map[string][]byte) bool {
+ if len(a) != len(b) {
+ return false
+ }
+ for k, v := range a {
+ if w, ok := b[k]; !ok || !bytes.Equal(v, w) {
+ return false
+ }
+ }
+ return true
+}
diff --git a/internal/sim/regionha/actions_test.go b/internal/sim/regionha/actions_test.go
index fc8ac3f26..2c5e12a43 100644
--- a/internal/sim/regionha/actions_test.go
+++ b/internal/sim/regionha/actions_test.go
@@ -10,6 +10,7 @@ import (
"github.com/carlosframework/platform/internal/edge"
"github.com/carlosframework/platform/internal/hafresh"
+ "github.com/carlosframework/platform/internal/replicagen"
)
// ---- the acquire (lease.AcquireHA, classifyAndTake; Tasks 6 and 9) ----
@@ -41,17 +42,25 @@ func (w *world) decideAcquire(b *box, h string, v hafresh.View) hafresh.Decision
proof = func() (bool, error) { return true, nil }
}
if !on("takeover-before-expiry") && !v.Absent && v.Lock.Release == nil && !w.now().After(v.Lock.ExpiresAt) {
+ o, ok := hafresh.ParseOwner(v.Lock.Owner)
+ if v.Generations() && ok && o.IID != "" {
+ // A generations lock under fast: a caller that takes the
+ // unexpired lock without the termination or emptiness proof the
+ // fast rows require.
+ return hafresh.Decision{Action: hafresh.ActTake, Reason: "unexpired, unproven"}
+ }
// A caller that asks EC2 first and treats a confirmed termination
// as the lease's end: it hands the table an expiry in the past.
- if o, ok := hafresh.ParseOwner(v.Lock.Owner); ok && o.IID != "" && o.IID != b.Self.IID {
+ if ok && o.IID != "" && o.IID != b.Self.IID {
if gone, err := w.ownerTerminated(o.IID); err == nil && gone {
v.Lock.ExpiresAt = w.now().Add(-tick)
}
}
}
- // GenerationsFast is the switch's `fast`; it changes the table only for
- // a generations lock, which this model does not write yet (Task 11
- // models generations), so it decides nothing here today.
+ // GenerationsFast is every box's switch, `fast`: it changes the table
+ // only for a generations lock (View.Generations), which a host in
+ // generations mode writes (take). For any other lock the table is the
+ // one above it, whatever the flag says.
d := hafresh.DecideAcquire(v, b.Self, w.now(), ttlTicks*tick, hafresh.Proofs{LocalEligible: func() bool { return true }, SameBoxEmpty: proof, OwnerTerminated: w.ownerTerminated, GenerationsFast: true})
if !on("expiry-authorizes") && d.Action == hafresh.ActRefuse && d.Reason == hafresh.ReasonOtherExpired {
d = hafresh.Decision{Action: hafresh.ActTake, Reason: "expired"}
@@ -78,17 +87,23 @@ func (w *world) classify(b *box, h string, v hafresh.View) string {
}
// take writes the next lease over v, conditional on it, owned by b's agent
-// process: generation 1 over an absent lock, v's plus one otherwise.
+// process: generation 1 over an absent lock, v's plus one otherwise. An HA
+// take writes a generations lock (carlos_generation g-N) when the host's
+// switch is on, or over a generations lock (the mode is sticky).
func (w *world) take(b *box, h string, v hafresh.View, ha bool) *entry {
gen := int64(1)
if !v.Absent {
gen = v.Lock.Generation + 1
}
+ name := ""
+ if ha && (w.s3[h].GenMode || v.Generations()) {
+ name = replicagen.Name(gen)
+ }
expires := w.now().Add(ttlTicks * tick)
- if !w.putLock(h, w.leaseBody(gen, hafresh.OwnerFor(b.Self, b.PID, ha), expires), v) {
+ if !w.putLock(h, w.leaseBodyG(gen, hafresh.OwnerFor(b.Self, b.PID, ha), expires, name), v) {
return nil
}
- return &entry{Host: h, HA: ha, ETag: w.s3[h].ETag, Gen: gen, Expires: expires, View: v}
+ return &entry{Host: h, HA: ha, ETag: w.s3[h].ETag, Gen: gen, Expires: expires, View: v, GenName: name}
}
// acquireHA is the classify-and-take loop, at most three rounds. pre is a
@@ -151,6 +166,14 @@ type wakeOpts struct {
// and before the restore read or touched the local copy. The lock is
// left as this box's lease, with no release marker.
CrashBeforeRestore bool
+
+ // A generations take: TakeDelay pauses it after its restore, its fence
+ // and switch running that many ticks later (0: at once); RetireDelay is
+ // when its retirement pass runs after the switch (0: the next tick);
+ // Retried marks the one retry after a lost fence or switch.
+ TakeDelay int
+ RetireDelay int
+ Retried bool
}
// wake is a request's wake of h at b, which has no entry for it. pre is a
@@ -225,6 +248,9 @@ func (w *world) wake(b *box, h string, o wakeOpts, pre *pending) string {
w.releaseUnclean(b, h, e, 0, true, o.MarkerFails)
return "late ack"
}
+ if e.GenName != "" {
+ return w.wakeGen(b, h, e, o)
+ }
l := w.local(b, h)
if e.View.Absent {
// A first wake: the prefix was proven empty, so boot fresh.
@@ -248,14 +274,7 @@ func (w *world) wake(b *box, h string, o wakeOpts, pre *pending) string {
w.logf("box%d: %s: keep=%v (%s)", b.ID, h, keep, reason)
}
w.startWake(b, h, e, l)
- if o.FailAfterRepl {
- w.event("failed-after-replication")
- w.tenantWrite(b, h, false)
- w.sync(b, h, false)
- w.closeHA(b, h, o.MarkerFails, o.Straggler)
- return "failed after replication"
- }
- return "served"
+ return w.afterServe(b, h, o)
}
func viewWord(v hafresh.View) string {
@@ -306,7 +325,11 @@ func (w *world) startWake(b *box, h string, e *entry, l *localCopy) {
b.Units[h] = append(b.Units[h], &unit{Running: true})
e.Uploaded = l.TXID
pub := &publisher{Box: b.ID, PID: b.PID, Host: h, Gen: p.Gen, Last: p.Files}
- if l.Record != nil {
+ if e.GenName != "" {
+ // The files fence's write is the publisher's baseline, over the
+ // tree the take kept or restored.
+ pub.Last, pub.GenHost = l.Files, true
+ } else if l.Record != nil {
// A keep: a restore or a fresh boot removed the record. The
// publisher continues from the manifest the record names.
pub.Gen, pub.Last = genSeq(l.Record.Marker.FilesGen), l.Files
@@ -404,7 +427,11 @@ func (w *world) checkpoint(l *localCopy) {
func (w *world) sync(b *box, h string, ckpt bool) {
e, l := b.Entries[h], b.Local[h]
if l.TXID > e.Uploaded {
- w.replicaWrite(b, b.PID, h, l.TXID, l.Ver)
+ if e.GenName != "" {
+ w.genWrite(b, b.PID, h, e.ReplGen, e.Uploaded+1, l.TXID, l.Ver, fmt.Sprintf("replica write txid %d", l.TXID))
+ } else {
+ w.replicaWrite(b, b.PID, h, l.TXID, l.Ver)
+ }
e.Uploaded = l.TXID
}
if ckpt && !l.WALEmpty {
@@ -437,7 +464,11 @@ func (w *world) manifestWrite(b *box, pub *publisher, f files) bool {
w.logf("box%d: %s: the manifest was superseded; the publisher stops", b.ID, pub.Host)
return false
}
- w.checkHolder(b, pub.PID, pub.Host, fmt.Sprintf("manifest commit gen %d", p.Gen+1))
+ if pub.GenHost {
+ w.checkGenManifest(b, pub)
+ } else {
+ w.checkHolder(b, pub.PID, pub.Host, fmt.Sprintf("manifest commit gen %d", p.Gen+1))
+ }
p.Gen++
p.Files = f
pub.Gen, pub.Last = p.Gen, f
@@ -500,7 +531,7 @@ func (w *world) renew(b *box, h string) {
return
}
expires := w.now().Add(ttlTicks * tick)
- if !w.putLock(h, w.leaseBody(e.Gen, hafresh.OwnerFor(b.Self, b.PID, e.HA), expires), hafresh.View{ETag: e.ETag}) {
+ if !w.putLock(h, w.leaseBodyG(e.Gen, hafresh.OwnerFor(b.Self, b.PID, e.HA), expires, e.GenName), hafresh.View{ETag: e.ETag}) {
w.event("lease-lost")
w.logf("box%d: %s: the renewal lost its condition; the lease is lost and the host stops", b.ID, h)
w.stopMain(b, h)
@@ -570,7 +601,7 @@ func (w *world) tryRelease(b *box, h string) {
return
}
l := b.Local[h]
- base := hafresh.Marker{V: 1, Box: b.Self.Ref, IID: b.Self.IID, Lifetime: w.lifetime(h), At: w.now()}
+ base := hafresh.Marker{V: 1, Box: b.Self.Ref, IID: b.Self.IID, Lifetime: w.lifetime(h), At: w.now(), Gen: e.GenName != ""}
if !on("marker-before-final") {
m := base
m.TXID, m.FilesGen, m.Clean = e.Uploaded, w.gen(e.Pub.Gen), true
@@ -642,6 +673,7 @@ func (w *world) writeRecord(l *localCopy, m hafresh.Marker) {
// If-Match its ETag. A failure is an obligation, persisted before the
// error returns; a 412 means the lease is no longer ours.
func (w *world) putMarker(b *box, h string, e *entry, m hafresh.Marker, fails bool) {
+ m.Gen = e.GenName != ""
body, err := hafresh.MarkerBody(e.Gen, m)
if err != nil {
w.fail("MODEL", "MarkerBody: %v", err)
@@ -667,7 +699,11 @@ func (w *world) putMarker(b *box, h string, e *entry, m hafresh.Marker, fails bo
} else {
w.event("marker-unclean")
}
- w.logf("box%d: %s: released with a marker (clean %v, txid %d, files %s)", b.ID, h, m.Clean, m.TXID, m.FilesGen)
+ w.markerLanded(h, m)
+ w.logf("box%d: %s: released with a marker (clean %v, txid %d, files %s, min_txid %d)", b.ID, h, m.Clean, m.TXID, m.FilesGen, m.MinTXID)
+ if m.Clean && e.ReplGen != "" && !w.scripted && w.fault(20) {
+ w.hideNewest(h, e.ReplGen, 1+w.rng.Intn(4))
+ }
}
// releaseUnclean is every release but the clean one: the acquire's cleanup
@@ -681,7 +717,7 @@ func (w *world) releaseUnclean(b *box, h string, e *entry, txid uint64, settled,
w.logf("box%d: %s: released by deleting the lock", b.ID, h)
return
}
- m := hafresh.Marker{V: 1, Box: b.Self.Ref, IID: b.Self.IID, Lifetime: w.lifetime(h), TXID: txid, At: w.now(), Settled: settled}
+ m := hafresh.Marker{V: 1, Box: b.Self.Ref, IID: b.Self.IID, Lifetime: w.lifetime(h), TXID: txid, At: w.now(), Settled: settled, MinTXID: w.preSwitchBound(e)}
w.putMarker(b, h, e, m, markerFails)
}
@@ -730,6 +766,9 @@ func (w *world) retryObligation(b *box, ob *obligation, fails bool) bool {
delete(b.Owed, ob.Host)
delete(b.Disk, ob.Host)
if w.putLock(ob.Host, ob.Body, hafresh.View{ETag: ob.ETag}) {
+ if v := w.view(ob.Host); v.Lock.Release != nil {
+ w.markerLanded(ob.Host, *v.Lock.Release)
+ }
w.event("obligation-discharged")
w.logf("box%d: %s: the owed marker is written", b.ID, ob.Host)
} else {
@@ -770,6 +809,7 @@ func (w *world) die(b *box) {
b.Pending = map[string]*pending{}
b.Owed = map[string]*obligation{}
b.Strays = nil
+ b.Retire = nil
b.AcquiredHere = map[string]bool{}
b.Swept = false
}
@@ -796,16 +836,22 @@ func (w *world) terminate(b *box) {
// lateWrite is an upload a dead agent process sent before it died: a
// replica upload (TXID, Ver), or a files manifest commit (Pub, Files). It
-// lands at step At, under the dead process's pid.
+// lands at step At, under the dead process's pid. A generations holder's
+// replica upload is tagged with the generation it was sent to (Gen) and
+// the first TXID it covers (Min); a generations take that died with its
+// switch in flight sends head.json's PUT (Switch).
type lateWrite struct {
- Box *box
- PID int
- Host string
- At int
- TXID uint64
- Ver int
- Pub *publisher
- Files files
+ Box *box
+ PID int
+ Host string
+ At int
+ TXID uint64
+ Ver int
+ Pub *publisher
+ Files files
+ Gen string
+ Min uint64
+ Switch *genTake
}
// inFlight is what b's dying agent process had sent and not seen settle:
@@ -825,6 +871,14 @@ func (w *world) inFlight(b *box) {
if e == nil || stepOf(e.Expires) <= w.step {
continue
}
+ if e.taking() {
+ // A take between its restore and its switch: nothing
+ // replicated, but its fence and switch may be in flight.
+ if w.pct(50) {
+ w.inFlightSwitch(b, h, w.landing(e))
+ }
+ continue
+ }
if l != nil && (l.TXID > e.Uploaded || e.Releasing == nil) && w.pct(50) {
if l.TXID == e.Uploaded {
w.tenantWrite(b, h, false)
@@ -861,6 +915,9 @@ func (w *world) lateUpload(b *box, h string, replica bool, at int) {
if replica {
l := b.Local[h]
lw.TXID, lw.Ver = l.TXID, l.Ver
+ if e := b.Entries[h]; e != nil && e.GenName != "" {
+ lw.Gen, lw.Min = e.ReplGen, e.Uploaded+1
+ }
what = fmt.Sprintf("replica upload txid %d", l.TXID)
} else {
pub := b.Entries[h].Pub
@@ -881,9 +938,14 @@ func (w *world) landLate() {
continue
}
w.logf("box%d: %s: an upload sent by the dead pid %d lands", lw.Box.ID, lw.Host, lw.PID)
- if lw.Pub != nil {
+ switch {
+ case lw.Switch != nil:
+ w.landSwitch(lw)
+ case lw.Pub != nil:
w.manifestWrite(lw.Box, lw.Pub, lw.Files)
- } else {
+ case lw.Gen != "":
+ w.genWrite(lw.Box, lw.PID, lw.Host, lw.Gen, lw.Min, lw.TXID, lw.Ver, fmt.Sprintf("replica upload txid %d", lw.TXID))
+ default:
w.replicaWrite(lw.Box, lw.PID, lw.Host, lw.TXID, lw.Ver)
}
}
@@ -948,6 +1010,10 @@ func (w *world) randomWakeOpts() wakeOpts {
}
o.SettleFails = w.fault(30)
o.MarkerFails = w.fault(15)
+ if w.fault(30) {
+ o.TakeDelay = 1 + w.rng.Intn(8)
+ }
+ o.RetireDelay = 1 + w.rng.Intn(3)
return o
}
@@ -1000,7 +1066,7 @@ func init() {
return false
}
if e := b.Entries[h]; e != nil {
- if e.Releasing != nil {
+ if e.Releasing != nil || e.taking() {
return false
}
w.tenantWrite(b, h, w.pct(40))
@@ -1057,7 +1123,7 @@ func init() {
b, h := w.randomBox(), w.randomHost()
o := w.randomSleepOpts()
e := b.Entries[h]
- if b.Agent != agentUp || e == nil || e.Releasing != nil {
+ if b.Agent != agentUp || e == nil || e.Releasing != nil || e.taking() {
return false
}
w.sleep(b, h, o)
diff --git a/internal/sim/regionha/expected-outcomes.txt b/internal/sim/regionha/expected-outcomes.txt
index 8a7573cd7..0d8f6128f 100644
--- a/internal/sim/regionha/expected-outcomes.txt
+++ b/internal/sim/regionha/expected-outcomes.txt
@@ -5,6 +5,18 @@
# by the random sweep only at N seeds or more; below N its miss is
# expected.
#
-# No rule is listed: every rule in rules_test.go is caught alone, by the
-# random sweep and by its own witness (TestWitnessRulesKnown requires one
-# witness per rule).
+# Every rule not listed below is caught alone, by the random sweep or by
+# its own witness (TestWitnessRulesKnown requires one witness per rule).
+#
+# The three guards of a storage-generations retirement pass (lease
+# RetireGenerations) are defence in depth against a stale pass: a pass
+# that runs after its holder let go. The lease check stops such a pass; a
+# generation at or above the holder's lock generation is never a
+# candidate; an abandoned generation goes only when every object is over
+# a day old. Any one of them alone keeps every generation a later
+# head.json names or a take builds (wGenRetireStale holds under every
+# proper subset), so each alone is missed; the three together are caught
+# by that witness (run: mutate.sh BIN N gen-retire-checks-lease,gen-retire-below-mine,gen-retire-abandoned-age).
+gen-retire-checks-lease missed
+gen-retire-below-mine missed
+gen-retire-abandoned-age missed
diff --git a/internal/sim/regionha/generations_test.go b/internal/sim/regionha/generations_test.go
new file mode 100644
index 000000000..2f57e5670
--- /dev/null
+++ b/internal/sim/regionha/generations_test.go
@@ -0,0 +1,1081 @@
+package regionha
+
+import (
+ "fmt"
+ "sort"
+ "strconv"
+ "strings"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/hafresh"
+ "github.com/carlosframework/platform/internal/replicagen"
+)
+
+// Storage generations (spec
+// docs/superpowers/specs/2026-11-12-region-ha-storage-generations-design.md,
+// §2 G1-G5, §4, §5, §7, §8). A host in generations mode has head.json
+// (headObj) and a set of generations (generation), each a self-contained
+// prefix of LTX objects. Every take writes lock generation N with
+// carlos_generation g-N and starts g-N: it reads head.json, plans at the
+// current generation's newest L0, copies the plan into g-N, restores (or
+// keeps), fences the files manifest and switches head.json to g-N with
+// If-Match (lease.StartGeneration, Take.Switch; activator
+// restoreHAGenerations). The holder then replicates only into g-N; a late
+// write of an earlier holder lands in that holder's own generation. Every
+// box's switch is `fast` (hafresh.Proofs.GenerationsFast), so a
+// generations lock is taken before its expiry on a termination or
+// emptiness proof, and an unsettled marker opens at once (§5.3).
+//
+// The model's own scale: a tick is a minute, so the restore window (seven
+// days) and the abandoned age (a day) are scaled down to historyTicks and
+// abandonedTicks, inside the walk. The model's uploads are all L0 files
+// (one sync is one file, covering the TXIDs it uploaded), so a
+// generation's newest L0 is its newest object.
+//
+// The invariants this adds (invariants_test.go):
+// - G1, own prefix: every replica write into a generation comes from the
+// process whose take created it;
+// - I1g: no late write ever lands in the generation head.json names
+// while the lock's holder replicates into it (a write of a process
+// that does not hold the lock, replica or files manifest, never lands
+// where the serving holder reads and writes), and no restore reads two
+// generations or a retired one;
+// - G2, one authority: while a holder that switched holds the lock,
+// head.json names its generation;
+// - I2g, the bound: a take never starts below the TXID a clean release
+// recorded, carried by every release before a switch as min_txid;
+// - R8, retirement: a retirement pass never deletes a generation
+// head.json names (current, predecessor or history) or that a take is
+// building or serving.
+
+const (
+ rootGen = replicagen.Root
+ historyTicks = 60 // SnapshotRetention + RetireGrace, scaled
+ abandonedTicks = 30 // lease.AbandonedAge, scaled
+)
+
+// genObj is one LTX object of a generation, covering Min..Max, holding the
+// content version Ver at Max. ListedAt is the first step a listing shows
+// it (a file the start rule must not miss; see hideNewest).
+type genObj struct {
+ Min, Max uint64
+ Ver int
+ Box, PID int
+ At int
+ ListedAt int
+}
+
+// generation is one g-<N>: the take that created it (its holder process),
+// its objects, and the TXID its copy ended at. Base is set only by the
+// gen-copy mutation: the start refers to Base's objects at or below Start
+// instead of copying them. Deleted is retirement's work.
+type generation struct {
+ Name string
+ LockGen int64
+ Box, PID int
+ Objs []genObj
+ Start uint64
+ Base string
+ CreatedAt int
+ Deleted bool
+}
+
+func (g *generation) newest() (uint64, int) {
+ var txid uint64
+ var ver int
+ for _, o := range g.Objs {
+ if o.Max >= txid {
+ txid, ver = o.Max, o.Ver
+ }
+ }
+ return txid, ver
+}
+
+// histEntry is a head.json history entry: an earlier generation and the
+// step it stopped being current.
+type histEntry struct {
+ Gen string
+ EndedAt int
+}
+
+// headObj is head.json (lease.Head) with its ETag.
+type headObj struct {
+ Gen string
+ ETag string
+ LockGen int64
+ Pred string
+ Start uint64
+ CreatedAt int
+ History []histEntry
+}
+
+// names is every generation the head names: current, predecessor, history.
+func (hd *headObj) names() []string {
+ out := []string{hd.Gen}
+ if hd.Pred != "" {
+ out = append(out, hd.Pred)
+ }
+ for _, e := range hd.History {
+ out = append(out, e.Gen)
+ }
+ return out
+}
+
+func (hd headObj) clone() headObj {
+ hd.History = append([]histEntry(nil), hd.History...)
+ return hd
+}
+
+// genTake is one take of a new generation (lease.Take): g-N, the
+// generation G it copied from, the TXID T the copy ends at, head.json as
+// step 1 read it, the bound it enforced, the manifest generation its
+// files restore read (the fence's If-Match), and, for a take whose switch
+// is still to come, the step it runs.
+type genTake struct {
+ Gen string
+ LockGen int64
+ From string
+ T uint64
+ Empty bool
+ Found bool
+ ETag string
+ Prev headObj
+ Bound uint64
+ FilesBase int
+ DoneAt int
+ RetireDelay int
+ Retried bool
+}
+
+// retirePass is a holder's retirement pass (lease.Held.Retire), started
+// in the background once it switched: the head its switch wrote, its lock
+// generation, the history entries that switch dropped, and the step it
+// runs.
+type retirePass struct {
+ Host string
+ Head headObj
+ Mine int64
+ Left []string
+ At int
+}
+
+// genOn turns the storage-generations switch on for h, on every box, as
+// `fast` (CARLOS_HA_GENERATIONS=fast).
+func (w *world) genOn(h string) {
+ p := w.s3[h]
+ if p.GenMode {
+ return
+ }
+ p.GenMode = true
+ if p.Gens == nil {
+ p.Gens = map[string]*generation{}
+ }
+ w.event("gen-switch-on")
+ w.logf("%s: the storage generations switch is on (fast) on every box", h)
+}
+
+func genLockGen(name string) (int64, bool) {
+ s, ok := strings.CutPrefix(name, "g-")
+ if !ok || len(s) != 20 {
+ return 0, false
+ }
+ n, err := strconv.ParseInt(s, 10, 64)
+ return n, err == nil
+}
+
+// holdsLock reports whether b's process pid holds h's lock now (checkHolder
+// without its failure).
+func (w *world) holdsLock(b *box, pid int, h string) bool {
+ v := w.view(h)
+ if v.Absent || v.Lock.Release != nil {
+ return false
+ }
+ o, ok := hafresh.ParseOwner(v.Lock.Owner)
+ return ok && o.Ref == b.Self.Ref && o.IID == b.Self.IID && o.PID == pid
+}
+
+// lockHolder is the box and entry that hold h's lock now: the lease whose
+// ETag an awake entry holds. nil when the lock is absent, a marker, or a
+// lease whose process is gone.
+func (w *world) lockHolder(h string) (*box, *entry) {
+ p := w.s3[h]
+ if p.ETag == "" {
+ return nil, nil
+ }
+ for _, b := range w.boxes {
+ if e := b.Entries[h]; e != nil && e.ETag == p.ETag {
+ return b, e
+ }
+ }
+ return nil, nil
+}
+
+// rootObjs is the root layout's LTX files as objects (the root generation,
+// @root): each upload covers the TXIDs after the one before it. A second
+// upload of one TXID is the same key: the later version is current.
+func (w *world) rootObjs(h string) []genObj {
+ p := w.s3[h]
+ if p.RootRetired {
+ return nil
+ }
+ chain := append([]ltx(nil), p.Chain...)
+ sort.SliceStable(chain, func(i, j int) bool { return chain[i].TXID < chain[j].TXID })
+ var out []genObj
+ prev := uint64(0)
+ for _, c := range chain {
+ if c.TXID == prev && len(out) > 0 {
+ out[len(out)-1].Ver = c.Ver
+ continue
+ }
+ out = append(out, genObj{Min: prev + 1, Max: c.TXID, Ver: c.Ver, Box: c.Box, PID: c.PID})
+ prev = c.TXID
+ }
+ return out
+}
+
+// listGen is a ListObjectVersions of one generation's prefix at this step:
+// its current objects a listing shows now.
+func (w *world) listGen(h, name string) []genObj {
+ if name == rootGen {
+ return w.rootObjs(h)
+ }
+ g := w.s3[h].Gens[name]
+ if g == nil || g.Deleted {
+ return nil
+ }
+ var out []genObj
+ for _, o := range g.Objs {
+ if o.ListedAt <= w.step {
+ out = append(out, o)
+ }
+ }
+ return out
+}
+
+// hasObjects reports whether a ListDirs of the location shows generation
+// name: it holds at least one current object.
+func (w *world) hasObjects(h, name string) bool {
+ if name == rootGen {
+ return len(w.rootObjs(h)) > 0
+ }
+ g := w.s3[h].Gens[name]
+ return g != nil && !g.Deleted && len(g.Objs) > 0
+}
+
+// genState is generation name's position and content as a restore of it
+// ends: its newest object (with a Base, the gen-copy mutation, Base's
+// objects at or below Start count too). No checks: checkServe's view.
+func (w *world) genState(h, name string) (uint64, int, []string) {
+ if name == rootGen {
+ p := w.s3[h]
+ return p.MaxTXID, p.HeadVer, []string{rootGen}
+ }
+ g := w.s3[h].Gens[name]
+ if g == nil {
+ return 0, 0, nil
+ }
+ txid, ver := g.newest()
+ from := []string{name}
+ if g.Base != "" {
+ from = append(from, g.Base)
+ if txid == 0 {
+ for _, o := range w.baseObjs(h, g.Base) {
+ if o.Max <= g.Start && o.Max >= txid {
+ txid, ver = o.Max, o.Ver
+ }
+ }
+ }
+ }
+ return txid, ver, from
+}
+
+func (w *world) baseObjs(h, name string) []genObj {
+ if name == rootGen {
+ return w.rootObjs(h)
+ }
+ if g := w.s3[h].Gens[name]; g != nil && !g.Deleted {
+ return g.Objs
+ }
+ return nil
+}
+
+// readGen is a restore of generation name (lease.RestoreTake): I1g's read
+// half, one generation and never a retired one.
+func (w *world) readGen(h, name, what string) (uint64, int) {
+ txid, ver, from := w.genState(h, name)
+ if from == nil {
+ w.fail("MODEL", "%s: %s of %s, which does not exist", h, what, name)
+ return 0, 0
+ }
+ if len(from) > 1 {
+ w.fail("I1g", "%s: %s reads %d generations %v; a restore binds one (G5)", h, what, len(from), from)
+ }
+ for _, n := range from {
+ if g := w.s3[h].Gens[n]; g != nil && g.Deleted || n == rootGen && w.s3[h].RootRetired {
+ w.fail("I1g", "%s: %s reads %s, which retirement deleted", h, what, n)
+ }
+ }
+ return txid, ver
+}
+
+// planStart is lease.PlanStart over the model: one listing of the current
+// generation G (head.json's, or @root), T its newest L0, and a plan from
+// TXID 1 to exactly T, or a refusal. bound is the take's lower bound (a
+// clean marker's TXID, or the min_txid a failed take carried forward).
+func (w *world) planStart(h string, found bool, head headObj, bound uint64) (from string, T uint64, plan []genObj, empty bool, refusal string) {
+ from = rootGen
+ if found {
+ from = head.Gen
+ }
+ listed := w.listGen(h, from)
+ for _, o := range listed {
+ if o.Max > T {
+ T = o.Max
+ }
+ }
+ if T == 0 {
+ if len(listed) == 0 && (!found || head.Start == 0 && head.Pred == "") {
+ if bound > 0 {
+ return from, 0, nil, false, "clean_marker_above_l0"
+ }
+ return from, 0, nil, true, ""
+ }
+ return from, 0, nil, false, "no_l0"
+ }
+ if bound > T {
+ return from, T, nil, false, "clean_marker_above_l0"
+ }
+ pos := uint64(0)
+ for pos < T {
+ best := -1
+ for i, o := range listed {
+ if o.Min <= pos+1 && o.Max > pos && o.Max <= T && (best < 0 || o.Max >= listed[best].Max) {
+ best = i
+ }
+ }
+ if best < 0 {
+ return from, T, nil, false, "no_plan_to_l0"
+ }
+ plan = append(plan, listed[best])
+ pos = listed[best].Max
+ }
+ return from, T, plan, false, ""
+}
+
+// viewBound is hafresh.Marker.TakeBound of the marker an acquire took
+// over: 0 over an absent lock or a held one.
+func viewBound(v hafresh.View) uint64 {
+ if !v.Absent && v.Lock.Release != nil {
+ return v.Lock.Release.TakeBound()
+ }
+ return 0
+}
+
+// preSwitchBound is the min_txid a release of e writes (lease
+// preSwitchBound): for a generations lock whose take has not switched
+// head.json, the bound that take enforced or would have; 0 otherwise.
+func (w *world) preSwitchBound(e *entry) uint64 {
+ if e.GenName == "" || e.Switched || !on("gen-min-txid") {
+ return 0
+ }
+ b := viewBound(e.View)
+ if e.Take != nil && e.Take.Bound > b {
+ b = e.Take.Bound
+ }
+ return b
+}
+
+// genWrite is one replica upload of a generations holder, covering
+// min..max, into gen: the writer's own generation, where its confined
+// client (§5.1) puts every request, a late one included. G1 and I1g's
+// write half are checked as it lands.
+func (w *world) genWrite(b *box, pid int, h, gen string, min, max uint64, ver int, what string) {
+ p := w.s3[h]
+ if !on("gen-confined-writer") && p.Head != nil {
+ gen = p.Head.Gen // the write lands where head.json points as it lands
+ }
+ if !w.holdsLock(b, pid, h) && p.Head != nil && gen == p.Head.Gen {
+ if hb, he := w.lockHolder(h); he != nil && he.Switched && he.ReplGen == gen {
+ w.fail("I1g", "%s: a late %s by box%d (pid %d) lands in %s, the generation head.json names, while box%d serves from it (lock %s)",
+ h, what, b.ID, pid, gen, hb.ID, w.lockString(h))
+ }
+ }
+ g := p.Gens[gen]
+ if g == nil {
+ w.fail("MODEL", "%s: %s by box%d into %s, which no take created", h, what, b.ID, gen)
+ return
+ }
+ if g.Box != b.ID || g.PID != pid {
+ w.fail("G1", "%s: %s by box%d (pid %d) lands in %s, which the take of box%d (pid %d) created",
+ h, what, b.ID, pid, gen, g.Box, g.PID)
+ }
+ if top, _ := g.newest(); max <= top {
+ w.fail("I1", "box%d (pid %d) uploaded txid %d into %s of %s, which already holds %d", b.ID, pid, max, gen, h, top)
+ }
+ g.Objs = append(g.Objs, genObj{Min: min, Max: max, Ver: ver, Box: b.ID, PID: pid, At: w.step, ListedAt: w.step})
+ w.logf("box%d: %s: uploaded txid %d..%d into %s", b.ID, h, min, max, gen)
+}
+
+// checkGenManifest is I1's manifest half restated for a generations
+// holder's publisher: a commit of a process that does not hold the lock
+// may land before the successor's files fence (which then fails, or the
+// successor restores it), never once the successor serves.
+func (w *world) checkGenManifest(b *box, pub *publisher) {
+ if w.holdsLock(b, pub.PID, pub.Host) {
+ return
+ }
+ if hb, he := w.lockHolder(pub.Host); he != nil && he.Switched {
+ w.fail("I1g", "%s: a late manifest commit by box%d (pid %d) lands while box%d serves (lock %s)",
+ pub.Host, b.ID, pub.PID, hb.ID, w.lockString(pub.Host))
+ }
+}
+
+// ---- the take (lease.StartGeneration, Take.Switch; activator restoreHAGenerations) ----
+
+// wakeGen is the rest of a wake whose acquire wrote a generations lock:
+// the take's steps 0-4, the keep or the restore, then (now, or at DoneAt
+// when the take pauses) the files fence and the switch.
+func (w *world) wakeGen(b *box, h string, e *entry, o wakeOpts) string {
+ p := w.s3[h]
+ l := w.local(b, h)
+ t := &genTake{Gen: e.GenName, LockGen: e.Gen, Bound: viewBound(e.View), RetireDelay: o.RetireDelay, Retried: o.Retried}
+ e.Take, e.ReplGen = t, e.GenName
+ if e.View.Absent {
+ // Step 0, a first wake over a proven-empty prefix: head.json for an
+ // empty g-N, create-only; boot fresh.
+ p.Gens[t.Gen] = &generation{Name: t.Gen, LockGen: e.Gen, Box: b.ID, PID: b.PID, CreatedAt: w.step}
+ t.Empty, t.FilesBase = true, p.Gen
+ w.setAside(l)
+ w.fresh(l)
+ w.event("gen-first")
+ w.event("fresh")
+ return w.finishTake(b, h, e, o)
+ }
+ if e.View.Lock.Release == nil && w.cleanBound[h] > 0 {
+ // The lock is a held lease, not a marker: a take after the clean
+ // release died before its own release, and the bound it carried
+ // died with it; a held lock records none (known gap,
+ // TestKnownGapBoundLostOnCrashMidTake). The oracle follows the
+ // production rule: the bound travels in markers only.
+ w.logf("%s: the bound %d is not in the held lock this take is over (known gap)", h, w.cleanBound[h])
+ w.event("gen-bound-lost")
+ w.cleanBound[h] = 0
+ }
+ if p.Head != nil {
+ t.Found, t.ETag, t.Prev = true, p.Head.ETag, p.Head.clone()
+ }
+ from, T, plan, empty, refusal := w.planStart(h, t.Found, t.Prev, t.Bound)
+ if refusal != "" {
+ w.event("gen-refused")
+ w.event("gen-refused-" + refusal)
+ w.logf("box%d: %s: the generation start is refused: %s (bound %d, newest L0 %d)", b.ID, h, refusal, t.Bound, T)
+ w.releaseUnclean(b, h, e, 0, true, o.MarkerFails)
+ return "refused: generation " + refusal
+ }
+ if !on("gen-new-prefix") && from != rootGen {
+ // Mutated: no new generation. The holder restores and replicates
+ // into G itself, as the shared prefix did (no copy, no switch).
+ t.From, t.T, e.ReplGen = from, T, from
+ return w.keepOrRestore(b, h, e, o, l, true)
+ }
+ t.From, t.T, t.Empty = from, T, empty
+ g := &generation{Name: t.Gen, LockGen: e.Gen, Box: b.ID, PID: b.PID, Start: T, CreatedAt: w.step}
+ if on("gen-copy") {
+ for _, x := range plan {
+ x.At, x.ListedAt = w.step, w.step
+ g.Objs = append(g.Objs, x)
+ }
+ } else if !empty {
+ g.Base = from // mutated: the start refers to G's objects
+ }
+ p.Gens[t.Gen] = g
+ w.event("gen-take")
+ if from == rootGen && !empty {
+ w.event("gen-from-root")
+ }
+ w.logf("box%d: %s: took %s from %s at txid %d (%d objects copied, bound %d)", b.ID, h, t.Gen, from, T, len(g.Objs), t.Bound)
+ return w.keepOrRestore(b, h, e, o, l, false)
+}
+
+// keepOrRestore is the keep rule (DecideKeep, and the take started
+// exactly at the marker's TXID) or the restore of the take's generation,
+// then the rest of the take, now or when it pauses.
+func (w *world) keepOrRestore(b *box, h string, e *entry, o wakeOpts, l *localCopy, shared bool) string {
+ p := w.s3[h]
+ t := e.Take
+ keep, reason := w.decideKeep(b, h, e.View, l.now())
+ if keep && (e.View.Lock.Release == nil || t.T != e.View.Lock.Release.TXID) {
+ keep, reason = false, fmt.Sprintf("take-txid %d", t.T)
+ }
+ if keep {
+ t.FilesBase = genSeq(e.View.Lock.Release.FilesGen)
+ w.event("kept")
+ } else {
+ w.setAside(l)
+ if o.RestoreFails {
+ w.event("failed-restore")
+ w.releaseUnclean(b, h, e, 0, true, o.MarkerFails)
+ return "failed restore"
+ }
+ txid, ver := w.readGen(h, e.ReplGen, fmt.Sprintf("box%d's restore", b.ID))
+ c := w.newClock()
+ *l = localCopy{
+ DBExists: true, DB: hafresh.FileID{Inode: w.newInode(), Size: 4096, MtimeNs: c, CtimeNs: c}, WALEmpty: true,
+ TXID: txid, Ver: ver, Tree: true, Files: p.Files, TreeMeta: w.newClock(),
+ }
+ t.FilesBase = p.Gen
+ w.event("restored")
+ }
+ w.logf("box%d: %s: keep=%v (%s)", b.ID, h, keep, reason)
+ if shared {
+ e.Switched = true
+ w.startWake(b, h, e, l)
+ return w.afterServe(b, h, o)
+ }
+ if o.TakeDelay > 0 {
+ t.DoneAt = w.step + o.TakeDelay
+ b.Entries[h] = e
+ w.event("gen-take-paused")
+ w.logf("box%d: %s: the take's fence and switch run at step %d", b.ID, h, t.DoneAt)
+ return "taking"
+ }
+ return w.finishTake(b, h, e, o)
+}
+
+// finishTake is the take's last steps: the files fence (§7), the switch
+// of head.json (§4 step 5), then serving and, in the background, the
+// retirement pass (§8). A lost condition abandons the take: nothing is
+// deleted, the lease goes back settled with its bound, and the wake
+// retries once from the acquire.
+func (w *world) finishTake(b *box, h string, e *entry, o wakeOpts) string {
+ p := w.s3[h]
+ t := e.Take
+ if p.ETag != e.ETag {
+ // Take.Switch checks the lease before its PUT: a lost lease fails
+ // the take, and nothing is written.
+ delete(b.Entries, h)
+ w.event("gen-take-lease-lost")
+ w.logf("box%d: %s: the take's lease is lost before its switch (lock %s)", b.ID, h, w.lockString(h))
+ return "failed: lease lost"
+ }
+ if on("gen-files-fence") {
+ if p.Gen != t.FilesBase {
+ w.event("gen-fence-lost")
+ w.logf("box%d: %s: the files fence lost its condition (manifest %d, restored from %d)", b.ID, h, p.Gen, t.FilesBase)
+ return w.abandon(b, h, e)
+ }
+ w.fence(b, h)
+ }
+ if !w.switchHead(h, t) {
+ w.event("gen-switch-412")
+ w.logf("box%d: %s: the switch to %s got 412: head.json moved", b.ID, h, t.Gen)
+ if on("gen-switch-412-abandons") {
+ return w.abandon(b, h, e)
+ }
+ } else {
+ w.event("gen-switch")
+ }
+ e.Switched = true
+ delay := t.RetireDelay
+ if delay <= 0 {
+ delay = 1
+ }
+ b.Retire = append(b.Retire, &retirePass{Host: h, Head: p.Head.clone(), Mine: e.Gen, Left: t.leftNames(p.Head), At: w.step + delay})
+ w.startWake(b, h, e, b.Local[h])
+ return w.afterServe(b, h, o)
+}
+
+// afterServe is what a wake does once it serves: a failure after
+// replication started, or nothing.
+func (w *world) afterServe(b *box, h string, o wakeOpts) string {
+ if o.FailAfterRepl {
+ w.event("failed-after-replication")
+ w.tenantWrite(b, h, false)
+ w.sync(b, h, false)
+ w.closeHA(b, h, o.MarkerFails, o.Straggler)
+ return "failed after replication"
+ }
+ return "served"
+}
+
+// leftNames is the history entries the switch to head dropped: the
+// pre-trim history less what head keeps.
+func (t *genTake) leftNames(head *headObj) []string {
+ if head == nil || head.Gen != t.Gen {
+ return nil
+ }
+ kept := map[string]bool{}
+ for _, e := range head.History {
+ kept[e.Gen] = true
+ }
+ var left []string
+ for _, e := range t.history(0) {
+ if !kept[e.Gen] {
+ left = append(left, e.Gen)
+ }
+ }
+ return left
+}
+
+// history is the switch's pre-trim history: the generation step 1 read
+// (or @root), ended now, then its own history.
+func (t *genTake) history(now int) []histEntry {
+ prev := rootGen
+ if t.Found {
+ prev = t.Prev.Gen
+ }
+ return append([]histEntry{{Gen: prev, EndedAt: now}}, t.Prev.History...)
+}
+
+// fence is the files fence's write: the manifest rewritten unchanged with
+// this lock's generation in it.
+func (w *world) fence(b *box, h string) {
+ p := w.s3[h]
+ p.Gen++
+ w.logf("box%d: %s: fenced the files manifest (gen %d)", b.ID, h, p.Gen)
+}
+
+// switchHead is the switch's PUT of head.json for t's generation,
+// If-Match the ETag step 1 read (create-only when there was none). false
+// is a 412. A landed switch is where I2g's bound is checked and R8's
+// names: nothing it names is retired.
+func (w *world) switchHead(h string, t *genTake) bool {
+ p := w.s3[h]
+ ok := p.Head == nil
+ if t.Found {
+ ok = p.Head != nil && p.Head.ETag == t.ETag
+ }
+ if !ok && on("gen-switch-if-match") {
+ return false
+ }
+ nh := &headObj{Gen: t.Gen, ETag: w.newETag(), LockGen: t.LockGen, Start: t.T, CreatedAt: w.step}
+ if t.From != "" {
+ if !t.Empty {
+ nh.Pred = t.From
+ }
+ for _, e := range t.history(w.step) {
+ if e.EndedAt > w.step-historyTicks {
+ nh.History = append(nh.History, e)
+ }
+ }
+ }
+ for _, n := range nh.names() {
+ if g := p.Gens[n]; g != nil && g.Deleted || n == rootGen && p.RootRetired && n != nh.Gen {
+ w.fail("R8", "%s: head.json for %s names %s, which retirement deleted", h, t.Gen, n)
+ }
+ }
+ if t.T < w.cleanBound[h] {
+ w.fail("I2g", "%s: %s starts at txid %d, below txid %d a clean release recorded", h, t.Gen, t.T, w.cleanBound[h])
+ }
+ w.cleanBound[h] = 0
+ p.Head = nh
+ w.logf("%s: head.json names %s (predecessor %q, start %d, history %v)", h, nh.Gen, nh.Pred, nh.Start, nh.History)
+ return true
+}
+
+// abandon is a take whose fence or switch lost its condition: it deletes
+// nothing, releases settled (it never replicated) with its bound, and the
+// wake retries once from the acquire.
+func (w *world) abandon(b *box, h string, e *entry) string {
+ t := e.Take
+ w.event("gen-abandoned")
+ w.releaseUnclean(b, h, e, 0, true, false)
+ if t.Retried || b.Agent != agentUp {
+ return "abandoned"
+ }
+ r := w.wake(b, h, wakeOpts{Retried: true}, nil)
+ w.logf("box%d: %s: the take's retry: %s", b.ID, h, r)
+ return "retried: " + r
+}
+
+// tickTakes finishes the paused takes that are due on b (the take's fence
+// and switch run in the wake; only the model pauses them).
+func (w *world) tickTakes(b *box) {
+ for _, h := range w.hosts {
+ if e := b.Entries[h]; e != nil && e.Take != nil && !e.Switched && e.Take.DoneAt > 0 && w.step >= e.Take.DoneAt {
+ w.logf("box%d: %s: the paused take resumes: %s", b.ID, h, w.finishTake(b, h, e, wakeOpts{}))
+ }
+ }
+}
+
+// inFlightSwitch is a dying holder's take whose fence landed and whose
+// switch PUT is still in flight, landing at step at.
+func (w *world) inFlightSwitch(b *box, h string, at int) {
+ e := b.Entries[h]
+ if e == nil || e.Take == nil || e.Switched {
+ return
+ }
+ p := w.s3[h]
+ if on("gen-files-fence") {
+ if p.Gen != e.Take.FilesBase {
+ return
+ }
+ w.fence(b, h)
+ }
+ t := *e.Take
+ w.late = append(w.late, &lateWrite{Box: b, PID: b.PID, Host: h, At: at, Switch: &t})
+ w.event("gen-late-switch-sent")
+ w.logf("box%d: %s: pid %d dies with the switch to %s in flight; it lands at step %d", b.ID, h, b.PID, t.Gen, at)
+}
+
+func (w *world) landSwitch(lw *lateWrite) {
+ if w.switchHead(lw.Host, lw.Switch) {
+ w.event("gen-late-switch-landed")
+ } else {
+ w.event("gen-late-switch-412")
+ w.logf("%s: the late switch to %s got 412", lw.Host, lw.Switch.Gen)
+ }
+}
+
+// hideNewest is the condition the start rule refuses on (§4 step 4): a
+// file a clean marker covers is missing from the listing, here the newest
+// object of gen, for d steps.
+func (w *world) hideNewest(h, gen string, d int) {
+ g := w.s3[h].Gens[gen]
+ if g == nil || len(g.Objs) == 0 {
+ return
+ }
+ i := len(g.Objs) - 1
+ for j, o := range g.Objs {
+ if o.Max > g.Objs[i].Max {
+ i = j
+ }
+ }
+ g.Objs[i].ListedAt = w.step + d
+ w.event("gen-listing-gap")
+ w.logf("%s: the newest file of %s (txid %d) is missing from listings until step %d", h, gen, g.Objs[i].Max, w.step+d)
+}
+
+// ---- retirement (lease.RetireGenerations) ----
+
+// tickRetire runs b's retirement passes that are due.
+func (w *world) tickRetire(b *box) {
+ var keep []*retirePass
+ for _, rp := range b.Retire {
+ if w.step < rp.At {
+ keep = append(keep, rp)
+ continue
+ }
+ w.retire(b, rp)
+ }
+ b.Retire = keep
+}
+
+// retire is one pass for the holder of lock generation rp.Mine whose
+// switch wrote rp.Head: it checks its lease, lists the location, keeps
+// head's generation, predecessor and history, and deletes what left
+// history and abandoned generations below its own that are over
+// abandonedTicks old.
+func (w *world) retire(b *box, rp *retirePass) {
+ h := rp.Host
+ p := w.s3[h]
+ if e := b.Entries[h]; on("gen-retire-checks-lease") && (e == nil || e.Gen != rp.Mine || e.ETag != p.ETag) {
+ w.event("gen-retire-stopped")
+ w.logf("box%d: %s: the retirement pass stops: the lease is no longer held", b.ID, h)
+ return
+ }
+ keep := map[string]bool{rp.Head.Gen: true}
+ if on("gen-retire-keeps-history") {
+ for _, n := range rp.Head.names() {
+ keep[n] = true
+ }
+ }
+ left := map[string]bool{}
+ for _, n := range rp.Left {
+ left[n] = true
+ }
+ var names []string
+ for n := range p.Gens {
+ names = append(names, n)
+ }
+ sort.Strings(names)
+ names = append(names, rootGen)
+ for _, n := range names {
+ if keep[n] || !w.hasObjects(h, n) {
+ continue
+ }
+ if n != rootGen {
+ m, ok := genLockGen(n)
+ if !ok || on("gen-retire-below-mine") && m >= rp.Mine {
+ continue
+ }
+ }
+ if !left[n] && on("gen-retire-abandoned-age") && w.youngGen(h, n) {
+ w.event("gen-kept-young")
+ continue
+ }
+ w.retireGen(b, h, n, left[n])
+ }
+}
+
+func (w *world) youngGen(h, name string) bool {
+ for _, o := range w.baseObjs(h, name) {
+ if o.At > w.step-abandonedTicks {
+ return true
+ }
+ }
+ return false
+}
+
+// retireGen deletes generation name's current objects. R8: it is named by
+// no head.json and built or served by no take.
+func (w *world) retireGen(b *box, h, name string, left bool) {
+ p := w.s3[h]
+ if p.Head != nil {
+ for _, n := range p.Head.names() {
+ if n == name {
+ w.fail("R8", "%s: box%d's retirement deletes %s, which head.json (%s) names", h, b.ID, name, p.Head.Gen)
+ }
+ }
+ }
+ for _, x := range w.boxes {
+ if e := x.Entries[h]; e != nil && e.ReplGen == name {
+ w.fail("R8", "%s: box%d's retirement deletes %s, which box%d's take builds or serves", h, b.ID, name, x.ID)
+ }
+ }
+ if name == rootGen {
+ p.RootRetired = true
+ w.event("gen-retired-root")
+ } else {
+ g := p.Gens[name]
+ g.Deleted, g.Objs = true, nil
+ }
+ if left {
+ w.event("gen-retired-left")
+ } else {
+ w.event("gen-retired-abandoned")
+ }
+ w.logf("box%d: %s: retired %s (left history %v)", b.ID, h, name, left)
+}
+
+// markerLanded is the oracle's record of a release marker that landed: a
+// clean one on a generations host sets I2g's bound, its TXID.
+func (w *world) markerLanded(h string, m hafresh.Marker) {
+ if w.s3[h].GenMode && m.Clean && m.TXID > w.cleanBound[h] {
+ w.cleanBound[h] = m.TXID
+ }
+}
+
+func (w *world) headString(h string) string {
+ p := w.s3[h]
+ if p.Head == nil {
+ return "no head.json"
+ }
+ return fmt.Sprintf("head %s (pred %q)", p.Head.Gen, p.Head.Pred)
+}
+
+// ---- witnesses (witness_test.go's table) ----
+
+var g1, g2, g3, g4 = replicagen.Name(1), replicagen.Name(2), replicagen.Name(3), replicagen.Name(4)
+
+func wGenHangPastTTL(t *testing.T, w *world) {
+ w.genOn(sh)
+ wHangPastTTL(t, w)
+}
+
+func wGenTakeoverNeedsProof(t *testing.T, w *world) {
+ w.genOn(sh)
+ A, B, _ := w.abc()
+ w.serve(t, A)
+ w.write(A, false)
+ w.syncNow(A, false)
+ r := w.req(B, wakeOpts{})
+ expect(t, "takeover-before-expiry", strings.HasPrefix(r, "refused: held"), "B's wake over the live A's generations lease: %s", r)
+ w.advance(2)
+}
+
+func wGenLateWrite(t *testing.T, w *world) {
+ w.genOn(sh)
+ A, B, _ := w.abc()
+ w.serve(t, A) // a first wake: g-1
+ w.write(A, false)
+ w.syncNow(A, false)
+ w.write(A, false)
+ w.lateUpload(A, sh, true, w.step+3) // txid 2, landing in 3 ticks
+ w.terminate(A)
+ w.check()
+ w.advance(1) // EC2 shows A terminated; its lease has 14 ticks left
+ r := w.req(B, wakeOpts{})
+ expect(t, "gen-new-prefix", r == "served" && w.events["takeover"] == 1 && w.s3[sh].Head.Gen == g2,
+ "B's wake over the terminated A's unexpired lease: %s, %s", r, w.headString(sh))
+ w.write(B, false)
+ w.syncNow(B, false) // B's txid 2, into g-2
+ w.advance(3) // A's txid 2 lands, in g-1
+ if on("gen-new-prefix") && on("gen-confined-writer") {
+ top, _ := w.s3[sh].Gens[g1].newest()
+ expect(t, "gen-confined-writer", top == 2, "A's late upload is not in g-1 (newest %d)", top)
+ }
+}
+
+func wGenCopy(t *testing.T, w *world) {
+ w.genOn(sh)
+ A, B, _ := w.abc()
+ w.serve(t, A)
+ w.write(A, false)
+ w.syncNow(A, true)
+ w.sleepNow(A, sleepOpts{})
+ restored := w.events["restored"]
+ r := w.req(B, wakeOpts{})
+ expect(t, "gen-copy", r == "served" && w.events["restored"] == restored+1 && len(w.s3[sh].Gens[g2].Objs) == 1,
+ "B's take of A's clean marker: %s", r)
+}
+
+// genTakePaused is the setup of the switch witnesses: A serves g-1,
+// writes, releases clean, takes again (lock 2) with its switch paused,
+// and dies with that switch in flight, landing in land ticks. The agent
+// restarts with its sweep.
+func genTakePaused(t *testing.T, w *world, land int) *box {
+ w.genOn(sh)
+ A, _, _ := w.abc()
+ w.serve(t, A)
+ w.write(A, false)
+ w.syncNow(A, false)
+ w.sleepNow(A, sleepOpts{})
+ if r := w.req(A, wakeOpts{TakeDelay: 10}); r != "taking" {
+ t.Errorf("setup: A's take of lock 2: %s", r)
+ }
+ w.inFlightSwitch(A, sh, w.step+land)
+ w.crash(A)
+ w.restart(A, true)
+ w.check()
+ return A
+}
+
+func wGenSwitchIfMatch(t *testing.T, w *world) {
+ A := genTakePaused(t, w, 3)
+ r := w.req(A, wakeOpts{}) // lock 3 over A's own unexpired lease, on the emptiness proof (fast)
+ expect(t, "gen-switch-if-match", r == "served" && w.s3[sh].Head.Gen == g3, "A's take of lock 3: %s, %s", r, w.headString(sh))
+ w.advance(4) // lock 2's switch lands, If-Match the ETag it read
+ expect(t, "gen-switch-if-match", w.s3[sh].Head.Gen == g3 && w.events["gen-late-switch-412"] == 1,
+ "the late switch: %s, 412s %d", w.headString(sh), w.events["gen-late-switch-412"])
+}
+
+func wGenSwitch412(t *testing.T, w *world) {
+ A := genTakePaused(t, w, 2)
+ r := w.req(A, wakeOpts{TakeDelay: 3}) // lock 3 copies g-1; its switch runs in 3 ticks
+ if r != "taking" {
+ t.Errorf("setup: A's take of lock 3: %s", r)
+ }
+ w.advance(4) // lock 2's switch lands first; lock 3's gets 412, abandons, and its retry (lock 4) copies g-2 and serves
+ e := A.Entries[sh]
+ expect(t, "gen-switch-412-abandons", e != nil && e.ReplGen == g4 && w.s3[sh].Head.Gen == g4 && w.s3[sh].Head.Pred == g2 && w.events["gen-abandoned"] == 1,
+ "after the 412: %s, %s", w.headString(sh), w.lockString(sh))
+}
+
+func wGenFilesFence(t *testing.T, w *world) {
+ w.genOn(sh)
+ A, B, _ := w.abc()
+ w.serve(t, A)
+ w.write(A, true)
+ w.syncNow(A, false)
+ w.startSnapshot(A, sh, 10)
+ w.lateUpload(A, sh, false, w.step+3) // the snapshot's commit is in flight, landing in 3 ticks
+ w.terminate(A)
+ w.check()
+ w.advance(1)
+ r := w.req(B, wakeOpts{})
+ expect(t, "gen-files-fence", r == "served", "B's wake over the terminated A's lease: %s", r)
+ w.advance(3) // A's commit lands after B's fence
+ expect(t, "gen-files-fence", w.s3[sh].Files == B.Local[sh].Files, "the manifest holds %+v, B serves %+v", w.s3[sh].Files, B.Local[sh].Files)
+}
+
+func wGenMinTXID(t *testing.T, w *world) {
+ w.genOn(sh)
+ A, B, C := w.abc()
+ w.serve(t, A)
+ w.write(A, false)
+ w.syncNow(A, false)
+ w.write(A, false)
+ w.syncNow(A, false)
+ w.sleepNow(A, sleepOpts{}) // clean, txid 2
+ w.hideNewest(sh, g1, 6)
+ r := w.req(B, wakeOpts{})
+ expect(t, "gen-min-txid", r == "refused: generation clean_marker_above_l0", "B over A's clean marker: %s", r)
+ v := w.view(sh)
+ expect(t, "gen-min-txid", v.Lock.Release != nil && v.Lock.Release.Settled && v.Lock.Release.MinTXID == 2, "B's release left %s", w.lockString(sh))
+ r = w.req(C, wakeOpts{})
+ expect(t, "gen-min-txid", r == "refused: generation clean_marker_above_l0", "C over B's settled marker: %s", r)
+ w.advance(6)
+ r = w.req(C, wakeOpts{})
+ expect(t, "gen-min-txid", r == "served" && C.Local[sh].TXID == 2, "C once the file is listed: %s", r)
+}
+
+func wGenRetireHistory(t *testing.T, w *world) {
+ w.genOn(sh)
+ A, B, _ := w.abc()
+ w.serve(t, A)
+ w.write(A, false)
+ w.syncNow(A, false)
+ w.sleepNow(A, sleepOpts{})
+ w.advance(abandonedTicks + 1) // g-1's objects are over a day old
+ w.serve(t, B) // head.json: g-2, predecessor g-1, history [g-1]
+ w.advance(2) // B's retirement pass
+ g := w.s3[sh].Gens[g1]
+ expect(t, "gen-retire-keeps-history", !g.Deleted && w.s3[sh].Head.Pred == g1, "after B's pass: g-1 deleted %v, %s", g.Deleted, w.headString(sh))
+}
+
+func wGenRetireStale(t *testing.T, w *world) {
+ w.genOn(sh)
+ A, B, _ := w.abc()
+ w.serve(t, A)
+ w.write(A, false)
+ w.syncNow(A, false)
+ w.sleepNow(A, sleepOpts{})
+ if r := w.req(A, wakeOpts{RetireDelay: 3}); r != "served" { // lock 2, g-2; its pass runs in 3 ticks
+ t.Errorf("setup: A's take of lock 2: %s", r)
+ }
+ w.write(A, false)
+ w.syncNow(A, false)
+ w.sleepNow(A, sleepOpts{}) // A lets go before its pass runs
+ if r := w.req(B, wakeOpts{TakeDelay: 5}); r != "taking" {
+ t.Errorf("setup: B's take of lock 3: %s", r)
+ }
+ w.advance(3) // A's pass runs
+ w.advance(3) // B switches and serves
+ e := B.Entries[sh]
+ expect(t, "gen-retire-checks-lease", e != nil && e.Switched && !w.s3[sh].Gens[g3].Deleted, "B after A's pass: %s, %s", w.headString(sh), w.lockString(sh))
+}
+
+// TestKnownGapBoundLostOnCrashMidTake documents a known gap, not a rule:
+// the bound a clean release sets (its TXID) travels in markers only. A
+// take over the clean marker whose box dies before it releases leaves its
+// own held lease, which records no bound, so the next take over that
+// lease (here the same box, on the emptiness proof) plans from 0 and, if
+// the file the clean marker covers is still missing from the listing,
+// starts below it. Production has the same shape: Held.viewBound is 0
+// over a held lock, and the activator passes a bound only from a marker.
+// The oracle (I2g) follows production: a take over a held lease clears
+// it (gen-bound-lost). This test asserts the loss, so closing the gap
+// (a bound in the held lock) shows up here.
+func TestKnownGapBoundLostOnCrashMidTake(t *testing.T) {
+ saved := mutated
+ mutated = ""
+ defer func() { mutated = saved }()
+ w := newWitness()
+ w.genOn(sh)
+ A, B, _ := w.abc()
+ w.serve(t, A)
+ w.write(A, false)
+ w.syncNow(A, false)
+ w.write(A, false)
+ w.syncNow(A, false)
+ w.sleepNow(A, sleepOpts{}) // clean, txid 2
+ w.hideNewest(sh, g1, 10)
+ if r := w.req(B, wakeOpts{CrashBeforeRestore: true}); r != "crashed before restore" {
+ t.Fatalf("B's take over A's clean marker: %s", r)
+ }
+ w.restart(B, true)
+ w.check()
+ if r := w.req(B, wakeOpts{}); r != "served" {
+ t.Fatalf("B's take over its own held lease: %s", r)
+ }
+ if got := B.Local[sh].TXID; got != 1 || w.events["gen-bound-lost"] != 1 {
+ dump(t, w)
+ t.Fatalf("B serves txid %d (bound lost %d times); the known gap is a start at txid 1", got, w.events["gen-bound-lost"])
+ }
+ if len(w.violations) > 0 {
+ dump(t, w)
+ t.Fatalf("violations: %v", w.violations)
+ }
+ t.Logf("known gap, as asserted: B serves txid %d, below txid 2 the clean release recorded", B.Local[sh].TXID)
+}
diff --git a/internal/sim/regionha/invariants_test.go b/internal/sim/regionha/invariants_test.go
index 903c22e0a..73cf510f3 100644
--- a/internal/sim/regionha/invariants_test.go
+++ b/internal/sim/regionha/invariants_test.go
@@ -32,6 +32,32 @@ import (
// finalization has given each one a confirmation and a fault-free wake
// (finalTakeovers). With no live box, I5 does not apply to that host.
//
+// Storage generations restate I1's write half and add five invariants for
+// a host in generations mode (generations_test.go; spec 2026-11-12 §2,
+// §4, §5.3, §7, §8). Every take there starts its own generation, so a
+// late write of an earlier holder is no longer a second writer of the
+// successor's history: it lands in the earlier holder's generation. With
+// the switch at `fast`, a generations lock is taken before its expiry on
+// a termination or emptiness proof, and I1's state half (one running
+// unit) is what keeps that take honest: a pre-expiry take without the
+// proof runs beside a live owner. For a lock that is not a generations
+// lock every statement above is unchanged (an expired lease of another
+// box is never taken on expiry alone, nor a terminated owner's before its
+// expiry: a late write there is I1's).
+// - G1, own prefix: every replica write into a generation comes from
+// the process whose take created it.
+// - I1g: no late write ever lands in the generation head.json names
+// while the lock's holder replicates into it (nor, for the files
+// manifest, once the holder serves: its fence came first), and no
+// restore reads two generations or a retired one.
+// - G2, one authority: while a holder that switched holds the lock,
+// head.json names the generation it replicates into.
+// - I2g, the bound: a switch never starts its generation below the TXID
+// a clean release recorded (min_txid carries it across the releases
+// of takes that never switched).
+// - R8, retirement: no pass deletes a generation head.json names or a
+// take builds or serves.
+//
// MODEL is the model's own consistency: a lock that does not decode.
// fail records a violation of invariant inv, once per invariant id.
@@ -77,6 +103,21 @@ func (w *world) check() {
w.fail("I1", "%s runs %d units at once: %s (lock %s)", h, len(where), strings.Join(where, ", "), w.lockString(h))
}
}
+ w.checkGenHeads()
+}
+
+// checkGenHeads is G2: a holder that switched, while it holds the lock,
+// replicates into the generation head.json names.
+func (w *world) checkGenHeads() {
+ for _, h := range w.hosts {
+ b, e := w.lockHolder(h)
+ if e == nil || !e.Switched || e.ReplGen == "" {
+ continue
+ }
+ if p := w.s3[h]; p.Head == nil && e.ReplGen != rootGen || p.Head != nil && p.Head.Gen != e.ReplGen {
+ w.fail("G2", "%s: box%d holds the lock and serves from %s, but %s (lock %s)", h, b.ID, e.ReplGen, w.headString(h), w.lockString(h))
+ }
+ }
}
// checkHolder is I1's write half: what is about to be written to h's
@@ -97,6 +138,14 @@ func (w *world) checkServe(b *box, h string) {
w.fail("A1", "tenant served before group admission")
}
l, p := b.Local[h], w.s3[h]
+ if e := b.Entries[h]; e != nil && e.GenName != "" {
+ txid, ver, _ := w.genState(h, e.ReplGen)
+ if l.TXID != txid || l.Ver != ver || l.Files != p.Files {
+ w.fail("I2", "box%d serves %s from txid %d (content %d, files %+v), but %s holds txid %d (content %d) and the manifest %+v (lock %s)",
+ b.ID, h, l.TXID, l.Ver, l.Files, e.ReplGen, txid, ver, p.Files, w.lockString(h))
+ }
+ return
+ }
if l.TXID != p.MaxTXID || l.Ver != p.HeadVer || l.Files != p.Files {
w.fail("I2", "box%d serves %s from txid %d (content %d, files %+v), but S3 holds txid %d (content %d, files %+v) (lock %s)",
b.ID, h, l.TXID, l.Ver, l.Files, p.MaxTXID, p.HeadVer, p.Files, w.lockString(h))
diff --git a/internal/sim/regionha/rules_test.go b/internal/sim/regionha/rules_test.go
index 26ff4e3fe..663d64e3c 100644
--- a/internal/sim/regionha/rules_test.go
+++ b/internal/sim/regionha/rules_test.go
@@ -109,7 +109,28 @@ var allRules = []string{
"failed-wake-before-slice-empty", // cleanupFailedWake and the reaper hold an HA release until the host's slice reads empty (haHostEmpty, final review F1)
// takeover of a terminated box's hosts (P1b-1, N-HA9)
- "takeover-unconfirmed", // Proofs.OwnerTerminated: true only once EC2 shows the owner terminated, never for a box alive or hung
- "takeover-before-expiry", // the takeover row needs the lock expired too: an upload the dead process sent lands within its lease (N-HA9)
- "no-takeover", // a survivor of the pool takes a terminated owner's expired lock: the host comes back
+ "takeover-unconfirmed", // Proofs.OwnerTerminated: true only once EC2 shows the owner terminated, never for a box alive or hung
+ // takeover-before-expiry: a lock that is not a generations lock is taken
+ // only once expired, on a termination proof too (an upload the dead
+ // process sent lands within its lease, N-HA9); a generations lock under
+ // fast is taken before its expiry only on a termination or emptiness
+ // proof (storage generations §5.3: the late upload lands in the dead
+ // holder's own generation). expiry-authorizes is unchanged by fast: an
+ // expired lease of another box is never taken on expiry alone, a
+ // generations lock's included.
+ "takeover-before-expiry",
+ "no-takeover", // a survivor of the pool takes a terminated owner's expired lock: the host comes back
+
+ // storage generations (spec 2026-11-12 §4, §5, §7, §8; generations_test.go)
+ "gen-new-prefix", // take step 2: every take starts its own generation g-N and replicates only there, never into G (G1)
+ "gen-copy", // take steps 3-4: the start is a copy of G's planned objects into g-N, never a reference to G (G3, G5)
+ "gen-switch-if-match", // step 5: head.json's switch is conditional on the ETag step 1 read (G2)
+ "gen-switch-412-abandons", // step 5, 412: the take abandons (a settled release with its bound, one retry) and never serves g-N
+ "gen-confined-writer", // §5.1: every write, a late one included, lands in its writer's own generation, never where head.json points
+ "gen-files-fence", // §7: the take fences the files manifest before its switch; a lost fence fails the wake
+ "gen-min-txid", // release: a release before the switch carries the take's bound as min_txid
+ "gen-retire-keeps-history", // §8: retirement keeps head's generation, predecessor and every history entry
+ "gen-retire-below-mine", // §8: only generations below the holder's lock generation are retired
+ "gen-retire-abandoned-age", // §8: an abandoned generation is retired only when every object is over a day old
+ "gen-retire-checks-lease", // §8: the pass checks the holder's lease before each generation
}
diff --git a/internal/sim/regionha/sim_test.go b/internal/sim/regionha/sim_test.go
index abc1c8a6b..7a0c76e10 100644
--- a/internal/sim/regionha/sim_test.go
+++ b/internal/sim/regionha/sim_test.go
@@ -216,6 +216,10 @@ func TestEveryActionFires(t *testing.T) {
"marker-clean", "marker-unclean", "marker-owed", "obligation-discharged",
"release-held", "failed-wake-held", "ha-lock-on-legacy-path", "hang-resumed", "manifest-committed",
"terminate", "takeover", "late-upload", "confirm-error", "placed-request",
+ // storage generations (generations_test.go)
+ "gen-switch-on", "gen-first", "gen-take", "gen-from-root", "gen-switch", "gen-take-paused",
+ "gen-listing-gap", "gen-refused", "gen-retired-left", "gen-retired-root", "gen-retired-abandoned",
+ "gen-kept-young", "gen-retire-stopped", "gen-bound-lost",
} {
if events[e] == 0 {
t.Errorf("no %s over 200 seeds", e)
diff --git a/internal/sim/regionha/witness_test.go b/internal/sim/regionha/witness_test.go
index 94f07cd31..f43548449 100644
--- a/internal/sim/regionha/witness_test.go
+++ b/internal/sim/regionha/witness_test.go
@@ -124,6 +124,35 @@ var witnesses = []witness{
"A is terminated with a replica upload in flight that lands at TTL - 2; B's wake right after visibility is held; a take before expiry lets A's upload land under B's lease", wTakeoverBeforeExpiry},
{"no-takeover", "no-takeover", "I5",
"r2.2: A is terminated while it holds the host, and no request comes until the finalization; a survivor that never takes over leaves the host down", wNoTakeover},
+
+ // storage generations (generations_test.go), and the two acquire rules
+ // restated for a generations lock under fast
+ {"expiry-authorizes", "expiry-authorizes", "I1",
+ "generations, fast: A hangs past the TTL, alive; B's wake over A's expired generations lock is refused as without fast; taken on expiry, B runs beside the hung box's unit", wGenHangPastTTL},
+ {"takeover-before-expiry", "takeover-before-expiry", "I1",
+ "generations, fast: A serves, alive; B's wake over A's unexpired generations lock is held, no proof; taken without one, B runs beside A", wGenTakeoverNeedsProof},
+ {"gen-new-prefix", "gen-new-prefix", "G1",
+ "A is terminated with an upload in flight; B takes at once on the proof (fast) and writes; a take that reuses A's generation writes into it, where A's upload lands", wGenLateWrite},
+ {"gen-confined-writer", "gen-confined-writer", "I1g",
+ "A is terminated with an upload in flight; B takes at once on the proof (fast), switches and writes; A's upload lands in A's generation, or (unconfined) in B's, which head.json names", wGenLateWrite},
+ {"gen-copy", "gen-copy", "I1g",
+ "A releases clean; B's take copies A's generation into its own and restores it; a start that refers to A's objects makes B's restore read two generations", wGenCopy},
+ {"gen-switch-if-match", "gen-switch-if-match", "G2",
+ "A's take pauses before its switch and the agent dies with the switch in flight; the restarted agent takes again (emptiness proof, fast), switches and serves; the late switch gets 412, or, unconditional, moves head.json back under the server", wGenSwitchIfMatch},
+ {"gen-switch-412-abandons", "gen-switch-412-abandons", "G2",
+ "A dies with its take's switch in flight; the restarted agent's take pauses; the late switch lands first, so the new switch gets 412: it abandons and retries, or (mutated) serves a generation head.json does not name", wGenSwitch412},
+ {"gen-files-fence", "gen-files-fence", "I1g",
+ "A is terminated with a files snapshot commit in flight; B takes at once on the proof (fast) and serves; A's commit lands after B's fence and fails its condition, or (no fence) lands under the server", wGenFilesFence},
+ {"gen-min-txid", "gen-min-txid", "I2g",
+ "A releases clean at txid 2 and its file is missing from the listing; B's take is refused and releases with min_txid 2; C over B's settled marker is refused too until the file is listed; without min_txid C starts at txid 1", wGenMinTXID},
+ {"gen-retire-keeps-history", "gen-retire-keeps-history", "R8",
+ "A releases clean and a day passes; B copies A's generation and switches; B's retirement pass keeps its predecessor, or (mutated) deletes the generation head.json names as predecessor and history", wGenRetireHistory},
+ {"gen-retire-checks-lease", "gen-retire-checks-lease,gen-retire-below-mine,gen-retire-abandoned-age", "R8",
+ "A switches lock 2, then lets go before its retirement pass runs, and B's take copies into g-3 and pauses; A's stale passes (lock 1's and lock 2's) delete a generation head.json names or B builds only with all three guards gone: the lease check, below-mine and the abandoned age each keep it alone", wGenRetireStale},
+ {"gen-retire-below-mine", "gen-retire-checks-lease,gen-retire-below-mine,gen-retire-abandoned-age", "R8",
+ "the stale retirement pass (as gen-retire-checks-lease)", wGenRetireStale},
+ {"gen-retire-abandoned-age", "gen-retire-checks-lease,gen-retire-below-mine,gen-retire-abandoned-age", "R8",
+ "the stale retirement pass (as gen-retire-checks-lease)", wGenRetireStale},
}
// TestWitnesses is the deterministic half of the mutation evidence.
diff --git a/internal/sim/regionha/world_test.go b/internal/sim/regionha/world_test.go
index 13d793a3c..594d31dd5 100644
--- a/internal/sim/regionha/world_test.go
+++ b/internal/sim/regionha/world_test.go
@@ -67,11 +67,31 @@ type prefix struct {
Gen int
Files files
Planted bool
+
+ // Storage generations (generations_test.go): GenMode is the switch,
+ // on (fast) for every box; Head is head.json (nil: absent, the root
+ // layout); Gens the g-* generations. The root layout's own LTX files
+ // are Chain above, the generation @root, until RootRetired.
+ GenMode bool
+ Head *headObj
+ Gens map[string]*generation
+ RootRetired bool
}
// empty is lease.PrefixEmpty: nothing at all stored under the prefix but
-// lock.json (one LIST, max-keys 1).
-func (p *prefix) empty() bool { return len(p.Chain) == 0 && p.Gen == 0 && !p.Planted }
+// lock.json (one LIST, max-keys 1): no root LTX file, manifest, head.json
+// or generation object.
+func (p *prefix) empty() bool {
+ if len(p.Chain) != 0 || p.Gen != 0 || p.Planted || p.Head != nil {
+ return false
+ }
+ for _, g := range p.Gens {
+ if len(g.Objs) > 0 {
+ return false
+ }
+ }
+ return true
+}
// localCopy is one box's local state of a host: the database file's
// identity, its WAL, its position and content, the files tree, and the
@@ -136,6 +156,7 @@ type publisher struct {
Last files
Inflight *snapshot
Broken bool
+ GenHost bool // a generations holder's: I1g's manifest half applies
}
// entry is an awake host in an agent's memory: the lease it holds (ETag,
@@ -143,6 +164,12 @@ type publisher struct {
// uploaded position and the files publisher. Releasing is set once the
// sleep has stopped the main unit, while the release waits for the host's
// slice to read empty.
+//
+// A generations lock's entry also carries GenName (the lock's
+// carlos_generation, g-N), its take (Take), whether the take has switched
+// head.json (Switched: only then does it serve and replicate), and the
+// generation it replicates into (ReplGen: g-N, or G under the
+// gen-new-prefix mutation).
type entry struct {
Host string
HA bool
@@ -153,8 +180,16 @@ type entry struct {
Uploaded uint64
Pub *publisher
Releasing *sleepOpts
+ GenName string
+ ReplGen string
+ Take *genTake
+ Switched bool
}
+// taking reports whether e is a generations take that has not switched:
+// it holds the lease and neither serves nor replicates.
+func (e *entry) taking() bool { return e.Take != nil && !e.Switched }
+
// obligation is an owed marker write: Body to the host's lock.json,
// If-Match ETag.
type obligation struct {
@@ -211,6 +246,7 @@ type box struct {
Disk map[string]*obligation
Pending map[string]*pending
Strays []*publisher
+ Retire []*retirePass
}
type world struct {
@@ -241,6 +277,13 @@ type world struct {
terminated map[string]int
visibleAt map[string]int
+ // genFlip is the step each host's generations switch turns on, for the
+ // hosts migrated mid-walk; cleanBound is I2g's oracle, the TXID of the
+ // last clean release a take of a generations host must reach (cleared
+ // by a switch).
+ genFlip map[string]int
+ cleanBound map[string]uint64
+
// late are the uploads dead agent processes had in flight, each landing
// at its step (lateUpload).
late []*lateWrite
@@ -297,7 +340,20 @@ func newWorld(seed int64, verbose bool) *world {
}
}
}
- w.logf("world seed %d: %d boxes, hosts %v, stale negative entries %s, terminations %v", seed, n, w.hosts, w.staleString(), w.terminations)
+ // Storage generations: a third of the hosts stay off, a third are born
+ // generations, a third turn on mid-walk (the migration from @root).
+ var gens []string
+ for _, h := range w.hosts {
+ switch w.rng.Intn(3) {
+ case 1:
+ w.genOn(h)
+ gens = append(gens, h)
+ case 2:
+ w.genFlip[h] = 50 + w.rng.Intn(chaosSteps-50)
+ gens = append(gens, fmt.Sprintf("%s@%d", h, w.genFlip[h]))
+ }
+ }
+ w.logf("world seed %d: %d boxes, hosts %v, stale negative entries %s, terminations %v, generations %v", seed, n, w.hosts, w.staleString(), w.terminations, gens)
return w
}
@@ -316,6 +372,8 @@ func newWorldN(seed int64, rng *rand.Rand, n int, hosts []string) *world {
terminated: map[string]int{},
visibleAt: map[string]int{},
+ genFlip: map[string]int{},
+ cleanBound: map[string]uint64{},
}
for _, h := range hosts {
w.s3[h] = &prefix{}
@@ -429,7 +487,13 @@ func (w *world) deleteLock(h, etag string) bool {
// leaseBody is the lock.json a take or a renewal writes (litestream.Lease's
// JSON: generation, expires_at, owner).
func (w *world) leaseBody(gen int64, owner string, expires time.Time) []byte {
- b, err := json.Marshal(hafresh.Lock{Generation: gen, ExpiresAt: expires, Owner: owner})
+ return w.leaseBodyG(gen, owner, expires, "")
+}
+
+// leaseBodyG is leaseBody for a storage-generations lock: carlos_generation
+// genName ("" writes none).
+func (w *world) leaseBodyG(gen int64, owner string, expires time.Time, genName string) []byte {
+ b, err := json.Marshal(hafresh.Lock{Generation: gen, ExpiresAt: expires, Owner: owner, GenName: genName})
if err != nil {
panic(err)
}
@@ -442,9 +506,9 @@ func (w *world) lockString(h string) string {
case v.Absent:
return "absent"
case v.Lock.Release != nil:
- return fmt.Sprintf("marker{box %s clean %v txid %d gen %d}", v.Lock.Release.Box, v.Lock.Release.Clean, v.Lock.Release.TXID, v.Lock.Generation)
+ return fmt.Sprintf("marker{box %s clean %v txid %d gen %d g %v min %d}", v.Lock.Release.Box, v.Lock.Release.Clean, v.Lock.Release.TXID, v.Lock.Generation, v.Lock.Release.Gen, v.Lock.Release.MinTXID)
}
- return fmt.Sprintf("lease{%s gen %d expires %s %s}", v.Lock.Owner, v.Lock.Generation, v.Lock.ExpiresAt.Sub(epoch), v.ETag)
+ return fmt.Sprintf("lease{%s gen %d %s expires %s %s}", v.Lock.Owner, v.Lock.Generation, v.Lock.GenName, v.Lock.ExpiresAt.Sub(epoch), v.ETag)
}
// ---- EC2 ----
@@ -554,6 +618,8 @@ func (w *world) tick() {
if b.Agent != agentUp {
continue
}
+ w.tickTakes(b)
+ w.tickRetire(b)
for _, h := range w.hosts {
if e := b.Entries[h]; e != nil && e.Releasing != nil {
w.tryRelease(b, h)
@@ -562,6 +628,10 @@ func (w *world) tick() {
if e == nil {
continue
}
+ if e.taking() {
+ w.renew(b, h)
+ continue
+ }
if e.Pub != nil {
w.publishTick(b, h, e)
}
@@ -585,6 +655,11 @@ func (w *world) tick() {
// invariants.
func (w *world) doStep() {
w.step++
+ for _, h := range w.hosts {
+ if at, ok := w.genFlip[h]; ok && at == w.step {
+ w.genOn(h)
+ }
+ }
w.tick()
a := w.pick()
if a != nil {