| new file mode 100644 |
| index 000000000..dcffbeff4 |
| --- /dev/null |
| +++ b/internal/console/restore_sim_test.go |
| @@ -0,0 +1,1112 @@ |
| +package console |
| + |
| +// The restore guard (instance restore #658, plan Task 7; spec §4 "Guard"): |
| +// a restore may only return data written by the restoring account, app and |
| +// app lifetime. Two tests hold that rule. |
| +// |
| +// - TestRestoreRefusesUnmarkedPredecessor is the spec's fixed trace: the |
| +// state in which rev 3's timestamp rule admitted another owner's warm |
| +// database (CODEX-FINDINGS R2 finding 1, the backward clock). |
| +// - TestRestoreProvenanceSimulation drives the real create, delete, |
| +// recovery, purge, activation and restore paths through seeded random |
| +// sequences, beside a data oracle that tracks which account, app and app |
| +// lifetime wrote each hostname's data, and its own model of the |
| +// admission table. Every restore must agree with the model, and a 201 |
| +// must bring back only the restorer's own writes. |
| +// |
| +// The oracle's model is written from the plan's admission table and the |
| +// oracle's own state (what each action did, as the oracle understands the |
| +// real path), never by calling restoreProof, the store accessors or the |
| +// bucket. Where the model and the console disagree, about a create or a |
| +// restore, the run fails at that step with the seed and the trace. |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "math/rand" |
| + "net/http" |
| + "os" |
| + "os/exec" |
| + "path/filepath" |
| + "runtime" |
| + "strconv" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + lsfile "github.com/benbjohnson/litestream/file" |
| + |
| + "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +// ---- the stamp clock --------------------------------------------------------- |
| + |
| +// stampStore is the release store with the hostname history's clock under |
| +// test control. The mark and mode writers stamp with time.Now() |
| +// (hostsused.go markHost, hostsused_activate.go Activate, |
| +// managedhistory.go admitManagedHistory), which the cutover fixture's clock |
| +// does not reach. On a Put under provision.HostsUsedPrefix (marks and |
| +// @mode) it rewrites the body's "at" field to next(), and nothing else: |
| +// the key, the condition (create-only or CAS) and every other field pass |
| +// through unchanged, so a create-only mark still loses to one already there. |
| +type stampStore struct { |
| + release.Store |
| + next func() time.Time |
| +} |
| + |
| +func (s *stampStore) Put(ctx context.Context, key string, body []byte, ifMatch string) (string, error) { |
| + if strings.HasPrefix(key, provision.HostsUsedPrefix) && s.next != nil { |
| + body = restamp(body, s.next()) |
| + } |
| + return s.Store.Put(ctx, key, body, ifMatch) |
| +} |
| + |
| +// DeleteIfMatch passes the conditional delete through (ltStore reaches it |
| +// with release.DeleteIfMatch). |
| +func (s *stampStore) DeleteIfMatch(ctx context.Context, key, etag string) error { |
| + return release.DeleteIfMatch(ctx, s.Store, key, etag) |
| +} |
| + |
| +// restamp is body with its top-level "at" set to at. A body with no "at" |
| +// (@floor) or that is not a JSON object is returned as it came. |
| +func restamp(body []byte, at time.Time) []byte { |
| + var m map[string]json.RawMessage |
| + if err := json.Unmarshal(body, &m); err != nil { |
| + return body |
| + } |
| + if _, ok := m["at"]; !ok { |
| + return body |
| + } |
| + stamp, err := json.Marshal(at.UTC()) |
| + if err != nil { |
| + return body |
| + } |
| + m["at"] = stamp |
| + out, err := json.Marshal(m) |
| + if err != nil { |
| + return body |
| + } |
| + return out |
| +} |
| + |
| +// simEpoch is the stamp clock's zero; simAt(n) is n seconds after it. |
| +var simEpoch = time.Date(2026, 11, 8, 0, 0, 0, 0, time.UTC) |
| + |
| +func simAt(n int) time.Time { return simEpoch.Add(time.Duration(n) * time.Second) } |
| + |
| +// ---- the world ----------------------------------------------------------------- |
| + |
| +const simBlog = "blog" |
| + |
| +var ( |
| + simHosts = []string{ltOne, "two.shop.example.com", "three.shop.example.com"} |
| + simApps = []string{ltApp, simBlog} |
| +) |
| + |
| +// simWorld is one claims-off console under test: account bab with the apps |
| +// shop and blog on shop.example.com, one platform box b1 (placement ie, data |
| +// bucket data-ie) for activation to list, a console data bucket for the |
| +// staging check, and every hostname-history write stamped by the stamp |
| +// clock (stampStore under the ltStore the fixtures use). Beside it, the |
| +// oracle. |
| +type simWorld struct { |
| + t *testing.T |
| + l ltOn |
| + data *stagingStore |
| + clock int // the stamp clock, seconds after simEpoch |
| + o *simOracle |
| + seed int64 |
| + trace []string |
| + tally *simTally |
| +} |
| + |
| +// simTally counts what a run met: each restore, create and delete answer |
| +// or outcome, and the restores of a hostname holding data someone other |
| +// than the restorer wrote (every one of which must be refused). |
| +type simTally struct { |
| + answers, creates, deletes map[string]int |
| + foreign int |
| +} |
| + |
| +func newSimTally() *simTally { |
| + return &simTally{answers: map[string]int{}, creates: map[string]int{}, deletes: map[string]int{}} |
| +} |
| + |
| +func (s *simTally) String() string { |
| + var parts []string |
| + for _, c := range []string{"ok", "S1", "R1", "dup", "R2", "R4", "R6", "R8"} { |
| + parts = append(parts, fmt.Sprintf("%s %d", c, s.answers[c])) |
| + } |
| + out := "restores " + strings.Join(parts, ", ") + fmt.Sprintf(" (%d over another writer's data)", s.foreign) |
| + parts = nil |
| + for _, c := range []string{"ok", "S1", "C2", "S2", "held"} { |
| + parts = append(parts, fmt.Sprintf("%s %d", c, s.creates[c])) |
| + } |
| + out += "; creates " + strings.Join(parts, ", ") |
| + parts = nil |
| + for _, c := range append([]string{delNormal}, delFaults...) { |
| + parts = append(parts, fmt.Sprintf("%s %d", c, s.deletes[c])) |
| + } |
| + return out + "; deletes " + strings.Join(parts, ", ") |
| +} |
| + |
| +func newSimWorld(t *testing.T, lifetimesOn, qData bool) *simWorld { |
| + t.Helper() |
| + ctx := context.Background() |
| + l := newLifetimesFx(t) |
| + w := &simWorld{t: t, seed: -1, tally: newSimTally()} |
| + stamp := &stampStore{Store: l.fx.rel, next: func() time.Time { return simAt(w.clock) }} |
| + bucket := <Store{Store: stamp} |
| + srv := l.fx.srv |
| + srv.cfg.Releases = bucket |
| + w.l = ltOn{lifetimesFx: l, bucket: bucket} |
| + putHostsEdges(t, l.fx.rel, "b1", "ie", "data-ie") |
| + if _, err := l.fx.st.CreateAppIn(OpsAccountID, simBlog, "paul@keymail.dev", time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + enableInstances(t, l.fx, simBlog, provision.Manifest{Schema: 1, App: simBlog, Domain: "shop.example.com", Channel: "stable"}) |
| + if lifetimesOn { |
| + turnLifetimesOn(t, srv, l.clock) |
| + } |
| + // The console region's data bucket (the staging check) and an empty |
| + // replica root for the leftover rail: the box's warm databases are the |
| + // data this guard is about, and no replica object is ever written. |
| + w.data = &stagingStore{DirStore: release.NewDirStore(t.TempDir())} |
| + srv.cfg.SeedData, srv.cfg.HibernateBucket, srv.cfg.HomeRegion = w.data, "data-test", "ie" |
| + root := t.TempDir() |
| + srv.cfg.HibernatePrefix = "instances" |
| + srv.dbReplica = func(_ context.Context, prefix string) (replicaReader, error) { |
| + return lsfile.NewReplicaClient(filepath.Join(root, prefix)), nil |
| + } |
| + if mode, err := srv.hostsMode(ctx); err != nil || mode != provision.HostsModeIncomplete { |
| + t.Fatalf("fixture: mode %q %v, want incomplete", mode, err) |
| + } |
| + w.o = newSimOracle(lifetimesOn) |
| + if qData { |
| + // Another owner Q's warm database at the host's derived path on b1, |
| + // and nothing else: no replica object, mark, slot or allocation. |
| + // Q's ownership is known to the data oracle alone. |
| + w.o.host(ltOne).data = []simWriter{simQ} |
| + } |
| + return w |
| +} |
| + |
| +func (w *simWorld) srv() *Server { return w.l.fx.srv } |
| + |
| +func (w *simWorld) note(format string, args ...any) { |
| + w.trace = append(w.trace, fmt.Sprintf(format, args...)) |
| +} |
| + |
| +// fail stops the run with the seed and every step so far. |
| +func (w *simWorld) fail(format string, args ...any) { |
| + w.t.Helper() |
| + w.t.Fatalf("seed %d, step %d: %s\ntrace:\n %s", w.seed, len(w.trace), fmt.Sprintf(format, args...), strings.Join(w.trace, "\n ")) |
| +} |
| + |
| +// unit is a unit of record work admitted on, as a door's, done when the |
| +// caller is. |
| +func (w *simWorld) unit() (context.Context, func()) { |
| + srv := w.srv() |
| + u, ok, why := srv.lifetimesAdmit(context.Background(), true) |
| + if !ok || u.mode != cutoverOn { |
| + w.fail("admitted %v %q, want a unit on", ok, why) |
| + } |
| + return context.WithValue(srv.recordCtx(context.Background(), u), admittedUnitKey{}, u), u.done |
| +} |
| + |
| +// restartHistory is a console start as far as the history goes: the mode read |
| +// again and the start-up check run. |
| +func (w *simWorld) restartHistory() { |
| + srv := w.srv() |
| + srv.hosts.reset() |
| + srv.LoadHostsMode(context.Background()) |
| +} |
| + |
| +func (w *simWorld) activation() HostsActivation { |
| + return HostsActivation{DB: w.l.fx.st, Releases: w.l.bucket, Registry: w.srv().cfg.Registry, Floor: testFloor} |
| +} |
| + |
| +// ---- actions ------------------------------------------------------------------- |
| + |
| +// setClock moves the stamp clock to n, backwards or forwards. |
| +func (w *simWorld) setClock(n int) { |
| + w.note("clock %d -> %d", w.clock, n) |
| + w.clock = n |
| +} |
| + |
| +// activate is `console hosts-used activate` with the honest listing of b1: |
| +// every hostname whose data is on the box (the oracle's data map), and an |
| +// empty data-ie bucket. |
| +func (w *simWorld) activate() bool { |
| + ctx := context.Background() |
| + var box []string |
| + for _, h := range simHosts { |
| + if len(w.o.host(h).data) > 0 { |
| + box = append(box, h+".db") |
| + } |
| + } |
| + a := w.activation() |
| + roster, err := a.Roster(ctx) |
| + if err != nil { |
| + w.fail("roster: %v", err) |
| + } |
| + _, err = a.Activate(ctx, roster, clean(box, nil), nil) |
| + w.restartHistory() |
| + want := w.o.activateOK() |
| + w.note("activate listing %v: %v (model: ok %v)", box, err, want) |
| + if (err == nil) != want { |
| + w.fail("activate = %v, the model says ok %v", err, want) |
| + } |
| + if err == nil { |
| + w.o.activated() |
| + if !w.srv().hostsActive() { |
| + w.fail("activated, but the console's start-up check did not pass") |
| + } |
| + } |
| + return err == nil |
| +} |
| + |
| +func (w *simWorld) invalidate() bool { |
| + err := w.activation().Invalidate(context.Background()) |
| + w.restartHistory() |
| + want := w.o.mode == provision.HostsModeActive |
| + w.note("invalidate: %v (model: ok %v)", err, want) |
| + if (err == nil) != want { |
| + w.fail("invalidate = %v, the model says ok %v", err, want) |
| + } |
| + if err == nil { |
| + w.o.mode = provision.HostsModeInvalidated |
| + } |
| + return err == nil |
| +} |
| + |
| +// enrol is a managed fleet's preparation: it rewrites @mode.At (and adds |
| +// the fleet to the examined targets) under an active history, does nothing |
| +// under an incomplete one, and refuses an invalidated one. |
| +func (w *simWorld) enrol() { |
| + err := w.srv().admitManagedHistory(context.Background(), registry.Fleet{Name: "production", Account: "bab", Managed: true, Bucket: "bucket"}, "") |
| + want := w.o.mode != provision.HostsModeInvalidated |
| + w.note("enrol a managed fleet: %v (model: ok %v)", err, want) |
| + if (err == nil) != want { |
| + w.fail("enrol = %v, the model says ok %v", err, want) |
| + } |
| +} |
| + |
| +// cutover turns lifetimes on. |
| +func (w *simWorld) cutover() { |
| + turnLifetimesOn(w.t, w.srv(), w.l.clock) |
| + w.o.lifetimesOn = true |
| + w.note("cutover: lifetimes on") |
| +} |
| + |
| +// create is the instance door's ordinary create of host by app: the |
| +// lifetime create with lifetimes on, createRecordMarked with them off. |
| +func (w *simWorld) create(app, host string) string { |
| + want := w.o.createAnswer(app, host) |
| + code, _, body := rawReq(w.t, http.MethodPost, instancesURL(w.l.fx, "bab", app), w.l.member, `{"host":"`+host+`"}`) |
| + got := createClass(code, body, host) |
| + w.note("create %s/%s: %d %s (model: %s)", app, host, code, ltErr(body), want) |
| + w.tally.creates[got]++ |
| + if got != want { |
| + w.fail("create %s of %s = %d %s, the model says %s", host, app, code, strings.TrimSpace(body), want) |
| + } |
| + if got == "ok" { |
| + w.o.created(app, host) |
| + } |
| + return got |
| +} |
| + |
| +// The retirement outcomes a delete can have with lifetimes on. |
| +const ( |
| + delNormal = "normal" // the door |
| + delBegin = "begin" // the tombstone write fails: pending |
| + delN1 = "n1" // the slot write fails after the tombstone: pending |
| + delN2 = "n2" // the tombstone delete fails after the slot: pending |
| + delN3 = "n3" // the commit fails: pending |
| + delLostN1 = "lost-n1" // the tombstone lands and its answer is lost: pending |
| + delAbsent = "absent" // pending at begin, then the record vanishes before recovery |
| + delCleanup = "cleanup" // a corrupt body under the key at N1: a cleanup retirement |
| +) |
| + |
| +var delFaults = []string{delBegin, delN1, delN2, delN3, delLostN1, delAbsent, delCleanup} |
| + |
| +// del deletes app's record of host with the outcome named. A record from |
| +// lifetimes off, or any delete while they are off, goes through the door: |
| +// lazy migration and then the retirement with lifetimes on (never |
| +// restorable), the plain delete with them off. |
| +func (w *simWorld) del(app, host, outcome string) { |
| + h := w.o.host(host) |
| + if !w.o.lifetimesOn || h.rec.legacy { |
| + outcome = delNormal |
| + } |
| + ctx := context.Background() |
| + key := provision.RecordKey("bab", app, host) |
| + bucket := w.l.bucket |
| + var err error |
| + code := 0 |
| + switch outcome { |
| + case delNormal: |
| + var body string |
| + code, _, body = rawReq(w.t, http.MethodDelete, instancesURL(w.l.fx, "bab", app)+"/"+host, w.l.member, "") |
| + if code != http.StatusOK && code != http.StatusNoContent { |
| + w.fail("delete %s of %s = %d %s, want deleted", host, app, code, strings.TrimSpace(body)) |
| + } |
| + case delLostN1: |
| + b := &lostAnswer{ltStore: bucket, key: key} |
| + b.armed.Store(true) |
| + w.srv().cfg.Releases = b |
| + err = w.retire(app, host) |
| + w.srv().cfg.Releases = bucket |
| + if b.armed.Load() { |
| + w.fail("the tombstone write of %s never ran", host) |
| + } |
| + case delN3: |
| + drop := sqlFailRetirement(w.t, w.l.fx.st, "sim_fail_commit", "NEW.state = 'committed'") |
| + err = w.retire(app, host) |
| + drop() |
| + case delCleanup: |
| + // A body that does not decode lands under the key just before N1, |
| + // as another writer's would (TestCleanupConversionNotRestorable). |
| + bucket.setHook(onNth("put", key, 1, func() { |
| + _, etag, gerr := w.l.fx.rel.Get(ctx, key) |
| + if gerr != nil { |
| + w.t.Error(gerr) |
| + return |
| + } |
| + if _, perr := w.l.fx.rel.Put(ctx, key, []byte(`{"schema":1,"host":`), etag); perr != nil { |
| + w.t.Error(perr) |
| + } |
| + })) |
| + err = w.retire(app, host) |
| + bucket.setHook(nil) |
| + default: // begin, n1, n2, absent |
| + switch outcome { |
| + case delBegin, delAbsent: |
| + bucket.setHook(failNth("put", key, 1, false)) |
| + case delN1: |
| + bucket.setHook(failNth("put", provision.HostIncarnationKey(host), 1, false)) |
| + case delN2: |
| + bucket.setHook(failNth("delete-if-match", key, 1, false)) |
| + } |
| + err = w.retire(app, host) |
| + bucket.setHook(nil) |
| + if outcome == delAbsent && err != nil { |
| + if derr := w.l.fx.rel.Delete(ctx, key); derr != nil { |
| + w.fail("remove the record: %v", derr) |
| + } |
| + } |
| + } |
| + pending := outcome != delNormal && outcome != delCleanup |
| + w.tally.deletes[outcome]++ |
| + w.note("delete %s/%s (%s): %d %v", app, host, outcome, code, err) |
| + switch { |
| + case pending && !errors.Is(err, errLifetimePending): |
| + w.fail("delete %s of %s stopping at %s = %v, want pending", host, app, outcome, err) |
| + case !pending && err != nil: |
| + w.fail("delete %s of %s (%s) = %v", host, app, outcome, err) |
| + } |
| + w.o.deleted(app, host, outcome, pending) |
| +} |
| + |
| +// retire is the delete's retirement core, as the door runs it. |
| +func (w *simWorld) retire(app, host string) error { |
| + ctx, done := w.unit() |
| + defer done() |
| + return w.srv().retireRecordWithLifetime(ctx, "bab", app, host, retireAny) |
| +} |
| + |
| +// recover is one pass of the recovery worker. |
| +func (w *simWorld) recoverPass() { |
| + recoverOn(w.t, w.srv()) |
| + w.o.recovered() |
| + w.note("recover") |
| +} |
| + |
| +// wake is an instance woken on b1: the record's owner writes the |
| +// hostname's data, and the warm database stays on the box after a delete. |
| +func (w *simWorld) wake(host string) { |
| + h := w.o.host(host) |
| + who := simWriter{"bab", h.rec.app, h.rec.gen} |
| + h.data = append(h.data, who) |
| + w.note("wake %s: %s writes", host, who) |
| +} |
| + |
| +// purgeShop trashes shop, purges it with lifetimes on (every lifetime of |
| +// it retired), releases the name and creates shop again: a new app lifetime. |
| +func (w *simWorld) purgeShop() { |
| + ctx, done := w.unit() |
| + trashShop(w.t, w.l) |
| + err := purgeCore(w.t, w.srv(), ctx, time.Time{}) |
| + done() |
| + if err != nil { |
| + w.fail("purge shop: %v", err) |
| + } |
| + st := w.l.fx.st |
| + if err := st.PurgeAppRow(OpsAccountID, ltApp); err != nil { |
| + w.fail("purge shop's row: %v", err) |
| + } |
| + if _, err := st.CreateAppIn(OpsAccountID, ltApp, "paul@keymail.dev", time.Now()); err != nil { |
| + w.fail("create shop again: %v", err) |
| + } |
| + enableInstances(w.t, w.l.fx, ltApp, provision.Manifest{Schema: 1, App: ltApp, Domain: "shop.example.com", Channel: "stable"}) |
| + w.o.purged(ltApp) |
| + w.note("purge shop and create it again (lifetime %d)", w.o.gen[ltApp]) |
| +} |
| + |
| +// stage puts a move's staged copy under moves/<host>/, or takes it away. |
| +func (w *simWorld) stage(host string) { |
| + ctx := context.Background() |
| + key := "moves/" + host + "/build-state.json" |
| + h := w.o.host(host) |
| + var err error |
| + if h.staged { |
| + err = w.data.Delete(ctx, key) |
| + } else { |
| + _, err = w.data.Put(ctx, key, []byte("{}"), "") |
| + } |
| + if err != nil { |
| + w.fail("stage %s: %v", host, err) |
| + } |
| + h.staged = !h.staged |
| + w.note("staging of %s: %v", host, h.staged) |
| +} |
| + |
| +// restore is the instance door's restore of host by app. Its answer must |
| +// be the model's row (agreement), and a 201 must bring back only data the |
| +// restoring account, app and app lifetime wrote (safety). |
| +func (w *simWorld) restore(app, host string) string { |
| + want := w.o.restoreVerdict(app, host) |
| + code, _, body := rawReq(w.t, http.MethodPost, instancesURL(w.l.fx, "bab", app), w.l.member, `{"host":"`+host+`","restore":true}`) |
| + got := restoreClass(code, body, host, app) |
| + w.note("restore %s/%s: %d %s (model: %s)", app, host, code, ltErr(body), want) |
| + w.tally.answers[got]++ |
| + me := simWriter{"bab", app, w.o.gen[app]} |
| + for _, who := range w.o.host(host).data { |
| + if who == me { |
| + continue |
| + } |
| + w.tally.foreign++ |
| + if got == "ok" { |
| + w.fail("SAFETY: the restore of %s by %s answered 201, but %s wrote its data (writers %v)", host, me, who, w.o.host(host).data) |
| + } |
| + break |
| + } |
| + if got != want { |
| + w.fail("restore %s of %s = %d %s, the model's row is %s", host, app, code, strings.TrimSpace(body), want) |
| + } |
| + if got == "ok" { |
| + w.o.restored(app, host) |
| + } |
| + return got |
| +} |
| + |
| +// createClass names a create's answer. |
| +func createClass(code int, body, host string) string { |
| + msg := ltErr(body) |
| + switch { |
| + case code == http.StatusCreated: |
| + return "ok" |
| + case code == http.StatusConflict && msg == msgHostUsed(host): |
| + return "S1" |
| + case code == http.StatusConflict && msg == msgRestoreHint(host): |
| + return "C2" |
| + case code == http.StatusServiceUnavailable && msg == msgHostsInvalidated: |
| + return "S2" |
| + case code == http.StatusConflict && msg == msgInstanceExists(host): |
| + return "dup" |
| + case code == http.StatusConflict && strings.Contains(msg, host): |
| + return "held" |
| + } |
| + return fmt.Sprintf("other %d %q", code, msg) |
| +} |
| + |
| +// restoreClass names a restore's answer by the approved strings. |
| +func restoreClass(code int, body, host, app string) string { |
| + if code == http.StatusCreated { |
| + var reply struct { |
| + Host string `json:"host"` |
| + Restore bool `json:"restore"` |
| + } |
| + if err := json.Unmarshal([]byte(body), &reply); err != nil || !reply.Restore || reply.Host != host { |
| + return fmt.Sprintf("other 201 %s", body) |
| + } |
| + return "ok" |
| + } |
| + msg := ltErr(body) |
| + for class, a := range map[string]struct { |
| + code int |
| + msg string |
| + }{ |
| + "S1": {http.StatusConflict, msgHostUsed(host)}, |
| + "R1": {http.StatusServiceUnavailable, msgRestoreUnchecked(host)}, |
| + "dup": {http.StatusConflict, msgInstanceExists(host)}, |
| + "R2": {http.StatusConflict, msgRestoreUnavailable(host)}, |
| + "R4": {http.StatusConflict, msgRestoreEarlierApp(host, app)}, |
| + "R6": {http.StatusConflict, msgRestoreStaging(host)}, |
| + "R7": {http.StatusConflict, msgRestoreNotPlain(host)}, |
| + "R8": {http.StatusConflict, msgRestoreTooOld(host)}, |
| + } { |
| + if code == a.code && msg == a.msg { |
| + return class |
| + } |
| + } |
| + return fmt.Sprintf("other %d %q", code, msg) |
| +} |
| + |
| +// ---- the oracle ------------------------------------------------------------------ |
| + |
| +// simWriter is who wrote a hostname's data: an account, an app and the |
| +// oracle's count of that app's lifetimes (0 for the first, one more for |
| +// each purge and recreation under the name). |
| +type simWriter struct { |
| + account, app string |
| + gen int |
| +} |
| + |
| +func (s simWriter) String() string { return fmt.Sprintf("%s/%s#%d", s.account, s.app, s.gen) } |
| + |
| +// simQ is the fixture's other owner, whose data no record tracks. |
| +var simQ = simWriter{"qqq", "q", 0} |
| + |
| +// The oracle's view of one hostname: what each action left behind, by the |
| +// oracle's reading of the real path. |
| +type ( |
| + simMark struct { |
| + app string |
| + owned bool // false: an inventory mark, naming no one |
| + } |
| + simSlot struct { |
| + inc uint64 |
| + live bool |
| + app string |
| + } |
| + simAlloc struct { |
| + inc uint64 |
| + app string |
| + gen int |
| + origin bool // restore_origin |
| + restore bool // restore_of |
| + } |
| + simRet struct { |
| + inc uint64 |
| + app string |
| + restorable bool // normal, committed and proven |
| + } |
| + simRec struct { |
| + app string |
| + gen int |
| + legacy bool // written with lifetimes off: no slot, no allocation |
| + } |
| + simHost struct { |
| + data []simWriter |
| + mark *simMark |
| + slot *simSlot |
| + allocs []simAlloc // the non-void allocations, by incarnation |
| + ret *simRet // the newest retirement |
| + rec *simRec // the record under its owner's key, nil when none |
| + pending string // the outcome of a pending retirement, "" for none |
| + staged bool |
| + } |
| +) |
| + |
| +type simOracle struct { |
| + mode string |
| + lifetimesOn bool |
| + gen map[string]int |
| + hosts map[string]*simHost |
| +} |
| + |
| +func newSimOracle(lifetimesOn bool) *simOracle { |
| + return &simOracle{mode: provision.HostsModeIncomplete, lifetimesOn: lifetimesOn, gen: map[string]int{}, hosts: map[string]*simHost{}} |
| +} |
| + |
| +func (o *simOracle) host(h string) *simHost { |
| + if o.hosts[h] == nil { |
| + o.hosts[h] = &simHost{} |
| + } |
| + return o.hosts[h] |
| +} |
| + |
| +func (o *simOracle) anyPending() bool { |
| + for _, h := range o.hosts { |
| + if h.pending != "" { |
| + return true |
| + } |
| + } |
| + return false |
| +} |
| + |
| +// restoreVerdict is the admission table, row by row, on the oracle's state. |
| +// Row 1 (an unreadable source) has no case: the simulation injects no read |
| +// fault into a restore. Claims stay off throughout, and every request and |
| +// stored body is plain, in the console's home region (rows 10 and 11). |
| +func (o *simOracle) restoreVerdict(app, host string) string { |
| + h := o.host(host) |
| + // Row 2: the mark and the slot both name the account and app. |
| + if h.mark == nil || !h.mark.owned || h.mark.app != app || h.slot == nil || h.slot.app != app { |
| + return "S1" |
| + } |
| + // Row 3: anything pending for the host. |
| + if h.pending != "" { |
| + return "R1" |
| + } |
| + // Row 4: this app's own valid (numbered) record under the key. |
| + if h.rec != nil && h.rec.app == app && !h.rec.legacy { |
| + return "dup" |
| + } |
| + // Row 5: the platform. |
| + if o.mode != provision.HostsModeActive || !o.lifetimesOn { |
| + return "R2" |
| + } |
| + // Row 6: the slot. |
| + if h.slot.live { |
| + return "R8" |
| + } |
| + // Row 7 (Task 5's ruling): a row naming this account and app on |
| + // another app lifetime. A row naming anyone else is row 8. |
| + for _, a := range h.allocs { |
| + if a.app == app && a.gen != o.gen[app] { |
| + return "R4" |
| + } |
| + } |
| + // Row 8: the lineage from its origin. |
| + if len(h.allocs) == 0 { |
| + return "R8" |
| + } |
| + atSlot := false |
| + for i, a := range h.allocs { |
| + switch { |
| + case a.app != app: |
| + return "R8" |
| + case i == 0 && (!a.origin || a.restore): |
| + return "R8" |
| + case i > 0 && (a.origin || !a.restore): |
| + return "R8" |
| + } |
| + if a.inc == h.slot.inc { |
| + atSlot = true |
| + } |
| + } |
| + if !atSlot { |
| + return "R8" |
| + } |
| + // Row 9: the newest retirement. |
| + if h.ret == nil || !h.ret.restorable || h.ret.inc != h.slot.inc || h.ret.app != app { |
| + return "R8" |
| + } |
| + // Row 12: a move's staging. |
| + if h.staged { |
| + return "R6" |
| + } |
| + return "ok" |
| +} |
| + |
| +// createAnswer is what an ordinary create of host by app answers: another |
| +// app's record holds the host (the door's holder check), then an |
| +// invalidated history (S2), then a mark already there once active (S1, or |
| +// C2 with lifetimes on when a restore would pass), and otherwise 201. |
| +func (o *simOracle) createAnswer(app, host string) string { |
| + h := o.host(host) |
| + switch { |
| + case h.rec != nil && h.rec.app != app: |
| + return "held" |
| + case o.mode == provision.HostsModeInvalidated: |
| + return "S2" |
| + case o.mode == provision.HostsModeActive && h.mark != nil: |
| + if o.lifetimesOn && o.restoreVerdict(app, host) == "ok" { |
| + return "C2" |
| + } |
| + return "S1" |
| + } |
| + return "ok" |
| +} |
| + |
| +// nextInc is the incarnation the next allocation of host takes. |
| +func (h *simHost) nextInc() uint64 { |
| + var base uint64 |
| + if h.slot != nil { |
| + base = h.slot.inc |
| + } |
| + for _, a := range h.allocs { |
| + if a.inc > base { |
| + base = a.inc |
| + } |
| + } |
| + return base + 1 |
| +} |
| + |
| +// created: the mark (written only when there was none), and with lifetimes |
| +// on the allocation, the slot and the record. The allocation carries the |
| +// origin when lifetimes were on, the mode active, and this create wrote the |
| +// mark (spec §4 stage 2 item 3). |
| +func (o *simOracle) created(app, host string) { |
| + h := o.host(host) |
| + fresh := h.mark == nil |
| + if fresh { |
| + h.mark = &simMark{app: app, owned: true} |
| + } |
| + if !o.lifetimesOn { |
| + h.rec = &simRec{app: app, gen: o.gen[app], legacy: true} |
| + return |
| + } |
| + inc := h.nextInc() |
| + h.allocs = append(h.allocs, simAlloc{inc: inc, app: app, gen: o.gen[app], origin: fresh && o.mode == provision.HostsModeActive}) |
| + h.slot = &simSlot{inc: inc, live: true, app: app} |
| + h.rec = &simRec{app: app, gen: o.gen[app]} |
| +} |
| + |
| +// restored: the restore's allocation carries restore_of, never the origin. |
| +func (o *simOracle) restored(app, host string) { |
| + h := o.host(host) |
| + inc := h.nextInc() |
| + h.allocs = append(h.allocs, simAlloc{inc: inc, app: app, gen: o.gen[app], restore: true}) |
| + h.slot = &simSlot{inc: inc, live: true, app: app} |
| + h.rec = &simRec{app: app, gen: o.gen[app]} |
| +} |
| + |
| +// retired settles host's lifetime as retired by app; restorable is whether |
| +// the retirement is a proven normal one. |
| +func (o *simOracle) retired(app, host string, restorable bool) { |
| + h := o.host(host) |
| + if h.rec.legacy { |
| + // Lazy migration numbers the record at 1, then it is retired: no |
| + // allocation, never restorable. |
| + h.slot = &simSlot{inc: 1, app: app} |
| + restorable = false |
| + } |
| + h.slot.live = false |
| + h.ret = &simRet{inc: h.slot.inc, app: app, restorable: restorable} |
| + h.rec, h.pending = nil, "" |
| +} |
| + |
| +func (o *simOracle) deleted(app, host, outcome string, pending bool) { |
| + h := o.host(host) |
| + if !o.lifetimesOn { |
| + h.rec = nil // the plain delete: the mark stays, nothing else is written |
| + return |
| + } |
| + if pending { |
| + h.pending = outcome |
| + return |
| + } |
| + o.retired(app, host, outcome == delNormal) |
| +} |
| + |
| +// recovered: every pending retirement commits. A record that vanished |
| +// before recovery leaves no proven tombstone. |
| +func (o *simOracle) recovered() { |
| + for _, host := range simHosts { |
| + h := o.host(host) |
| + if h.pending != "" { |
| + o.retired(h.rec.app, host, h.pending != delAbsent) |
| + } |
| + } |
| +} |
| + |
| +// activateOK: activation refuses an active history and pending work. |
| +func (o *simOracle) activateOK() bool { |
| + return o.mode != provision.HostsModeActive && !o.anyPending() |
| +} |
| + |
| +// activated: every hostname with data on b1 or a record is marked, an |
| +// existing mark kept as it is; the mode is active. |
| +func (o *simOracle) activated() { |
| + for _, host := range simHosts { |
| + h := o.host(host) |
| + if h.mark == nil && (len(h.data) > 0 || h.rec != nil || h.slot != nil) { |
| + h.mark = &simMark{} |
| + } |
| + } |
| + o.mode = provision.HostsModeActive |
| +} |
| + |
| +// purged: every record of app retired (the purge's own retirements, which |
| +// the model never needs to be restorable: the next lifetime meets row 7 or |
| +// row 8 first), and a new app lifetime. |
| +func (o *simOracle) purged(app string) { |
| + for _, host := range simHosts { |
| + if h := o.host(host); h.rec != nil && h.rec.app == app { |
| + o.retired(app, host, false) |
| + } |
| + } |
| + o.gen[app]++ |
| +} |
| + |
| +// ---- the generator --------------------------------------------------------------- |
| + |
| +// step runs one action the generator picks among those the state allows. |
| +func (w *simWorld) step(rng *rand.Rand) { |
| + o := w.o |
| + type choice struct { |
| + weight int |
| + run func() |
| + } |
| + var cs []choice |
| + add := func(weight int, run func()) { cs = append(cs, choice{weight, run}) } |
| + if o.mode != provision.HostsModeActive { |
| + add(10, func() { w.activate() }) |
| + } |
| + if o.mode == provision.HostsModeActive { |
| + add(1, func() { w.invalidate() }) |
| + } |
| + add(1, w.enrol) |
| + add(1, func() { w.setClock(w.clock + rng.Intn(121) - 60) }) |
| + if !o.lifetimesOn { |
| + add(6, w.cutover) |
| + } |
| + if o.anyPending() { |
| + add(3, w.recoverPass) |
| + } else if o.lifetimesOn { |
| + add(1, w.purgeShop) |
| + } |
| + for _, host := range simHosts { |
| + h := o.host(host) |
| + add(1, func() { w.stage(host) }) |
| + if h.rec != nil && h.pending == "" { |
| + add(2, func() { w.wake(host) }) |
| + } |
| + for _, app := range simApps { |
| + // Restores lean towards the mark's own app, whose answers |
| + // reach past row 2; another app's are S1 at row 2. |
| + weight := 1 |
| + if h.mark != nil && h.mark.app == app { |
| + weight = 6 |
| + } |
| + add(weight, func() { w.restore(app, host) }) |
| + if h.pending != "" { |
| + continue |
| + } |
| + if h.rec == nil || h.rec.app != app { |
| + add(4, func() { w.create(app, host) }) |
| + } else { |
| + add(4, func() { |
| + outcome := delNormal |
| + if rng.Intn(3) == 0 { |
| + outcome = delFaults[rng.Intn(len(delFaults))] |
| + } |
| + w.del(app, host, outcome) |
| + }) |
| + } |
| + } |
| + } |
| + total := 0 |
| + for _, c := range cs { |
| + total += c.weight |
| + } |
| + n := rng.Intn(total) |
| + for _, c := range cs { |
| + if n < c.weight { |
| + c.run() |
| + return |
| + } |
| + n -= c.weight |
| + } |
| +} |
| + |
| +// ---- the fixed trace --------------------------------------------------------------- |
| + |
| +// TestRestoreRefusesUnmarkedPredecessor is spec §4 Guard's fixed trace. |
| +// Another owner Q's warm database is at one.shop.example.com's derived path |
| +// on b1, with no mark, slot or allocation. P (bab/shop) creates the host |
| +// with lifetimes on while the history is incomplete, without a wake (its |
| +// mark stamped 110). The clock steps back, and activation lists Q's file |
| +// (stamped 100), keeping P's mark. P deletes normally, and restores: R8, |
| +// because P's allocation carries no origin. Rev 3's rule (a create mark |
| +// naming P stamped after @mode) would have admitted it. |
| +func TestRestoreRefusesUnmarkedPredecessor(t *testing.T) { |
| + ctx := context.Background() |
| + w := newSimWorld(t, true, true) |
| + w.setClock(110) |
| + if got := w.create(ltApp, ltOne); got != "ok" { |
| + t.Fatalf("P's create = %s, want 201", got) |
| + } |
| + w.setClock(100) |
| + if !w.activate() { |
| + t.Fatal("activation refused") |
| + } |
| + w.del(ltApp, ltOne, delNormal) |
| + |
| + // The state before the restore, read straight from the bucket. |
| + acct := w.l.acct(t) |
| + life, err := w.l.fx.st.AppLife(acct.ID, ltApp) |
| + if err != nil || life == nil { |
| + t.Fatalf("shop's row: %+v %v", life, err) |
| + } |
| + mark, err := readHostMark(ctx, w.srv(), ltOne) |
| + if err != nil || mark == nil { |
| + t.Fatalf("mark = %+v %v, want P's", mark, err) |
| + } |
| + mode, _, err := provision.ReadHostsState(ctx, w.l.fx.rel) |
| + if err != nil || mode.Mode != provision.HostsModeActive { |
| + t.Fatalf("mode = %+v %v, want active", mode, err) |
| + } |
| + if !mark.At.Equal(simAt(110)) || !mode.At.Equal(simAt(100)) { |
| + t.Fatalf("stamps: mark %v, mode %v; want %v and %v", mark.At, mode.At, simAt(110), simAt(100)) |
| + } |
| + if mark.Account != acct.Sqid || mark.App != ltApp || mark.Source != "create" { |
| + t.Fatalf("mark = %+v, want P's create mark surviving activation", mark) |
| + } |
| + slot, _ := slotOf(t, w.l.fx.rel, ltOne) |
| + if slot == nil || slot.State != provision.SlotRetired || slot.Incarnation != 1 || slot.Account != acct.Sqid || slot.App != ltApp { |
| + t.Fatalf("slot = %+v, want P's, retired at 1", slot) |
| + } |
| + rows := lineage(t, w.l.fx.st, ltOne) |
| + if len(rows) != 1 || rows[0].RestoreOrigin || rows[0].RestoreOf != "" { |
| + t.Fatalf("lineage = %+v, want P's one allocation, with no origin", rows) |
| + } |
| + for _, a := range rows { |
| + if a.Account != acct.Sqid || a.App != ltApp || a.AppLifetime != life.Lifetime || a.State != lifetimeCommitted { |
| + t.Fatalf("allocation %+v, want P's, committed, in lifetime %s", a, life.Lifetime) |
| + } |
| + } |
| + e := evidenceOf(t, w.l.fx.st, ltOne) |
| + if !restoreGrade(e) || e.Incarnation != slot.Incarnation || e.Account != acct.Sqid || e.App != ltApp { |
| + t.Fatalf("retirement = %+v, want P's proven normal retirement at the slot's incarnation", e) |
| + } |
| + // Rev 3's rule on this state: a create mark naming P, stamped after |
| + // @mode (with every allocation P's, and the retirement restorable, as |
| + // above). It admits P, so the trace tells the two rules apart. |
| + if rev3 := mark.Source == "create" && mark.Account == acct.Sqid && mark.App == ltApp && mark.At.After(mode.At); !rev3 { |
| + t.Fatal("rev 3's rule refuses this state too; the trace does not discriminate") |
| + } |
| + if got := w.restore(ltApp, ltOne); got != "R8" { |
| + t.Fatalf("P's restore = %s, want R8", got) |
| + } |
| +} |
| + |
| +// ---- the simulation ---------------------------------------------------------------- |
| + |
| +// TestRestoreProvenanceSimulation is the randomized guard. It runs at |
| +// reduced priority: unless RESTORE_SIM_CHILD=1, it runs its own test binary |
| +// again under `nice -n 10` and answers with the child's result. |
| +func TestRestoreProvenanceSimulation(t *testing.T) { |
| + if os.Getenv("RESTORE_SIM_CHILD") != "1" { |
| + runNicedSimulation(t) |
| + return |
| + } |
| + requireNiced(t) |
| + simulateRestoreProvenance(t) |
| +} |
| + |
| +// runNicedSimulation runs the simulation in a child process under nice, |
| +// with this run's -short and its remaining deadline, streaming its output. |
| +func runNicedSimulation(t *testing.T) { |
| + nice, err := exec.LookPath("nice") |
| + if err != nil { |
| + t.Fatalf("nice is not on PATH (%v); the simulation runs only at reduced priority", err) |
| + } |
| + timeout := 5 * time.Minute |
| + if d, ok := t.Deadline(); ok { |
| + timeout = time.Until(d) |
| + } |
| + if timeout < time.Second { |
| + timeout = time.Second |
| + } |
| + args := []string{"-n", "10", os.Args[0], "-test.run", "^TestRestoreProvenanceSimulation$", "-test.v", |
| + "-test.timeout=" + timeout.Round(time.Second).String()} |
| + if testing.Short() { |
| + args = append(args, "-test.short=true") |
| + } |
| + cmd := exec.Command(nice, args...) |
| + cmd.Env = append(os.Environ(), "RESTORE_SIM_CHILD=1") |
| + cmd.Stdout, cmd.Stderr = os.Stdout, os.Stderr |
| + if err := cmd.Run(); err != nil { |
| + t.Fatalf("the niced simulation (%s %s): %v", nice, strings.Join(args, " "), err) |
| + } |
| +} |
| + |
| +// requireNiced fails the child unless it runs at nice 10 or more (on linux; |
| +// elsewhere the priority is not checked). |
| +func requireNiced(t *testing.T) { |
| + if runtime.GOOS != "linux" { |
| + t.Logf("priority not checked on %s", runtime.GOOS) |
| + return |
| + } |
| + n, err := niceValue() |
| + if err != nil { |
| + t.Fatalf("read the priority: %v", err) |
| + } |
| + if n < 10 { |
| + t.Fatalf("the simulation child runs at nice %d, want at least 10", n) |
| + } |
| + t.Logf("the simulation child runs at nice %d", n) |
| +} |
| + |
| +// simulateRestoreProvenance: the deterministic traces, then the seeds. |
| +// -short runs 50 seeds of 30 steps, otherwise 200 of 40. RESTORE_SIM_SEED |
| +// runs that one seed alone. |
| +func simulateRestoreProvenance(t *testing.T) { |
| + t.Run("invalidate and reactivate", func(t *testing.T) { |
| + w := newSimWorld(t, true, false) |
| + w.activate() |
| + w.create(ltApp, ltOne) |
| + w.del(ltApp, ltOne, delNormal) |
| + w.invalidate() |
| + if got := w.restore(ltApp, ltOne); got != "R2" { |
| + t.Fatalf("restore while invalidated = %s, want R2", got) |
| + } |
| + w.activate() |
| + if got := w.restore(ltApp, ltOne); got != "ok" { |
| + t.Fatalf("restore after reactivation = %s, want 201", got) |
| + } |
| + }) |
| + t.Run("a create with lifetimes off after activation, purged and recreated", func(t *testing.T) { |
| + // CODEX-FINDINGS R2 finding 2 through the real paths: the |
| + // lifetimes-off create is admitted by the active history and marks |
| + // the host, lifetimes turn on, the delete migrates and retires it, |
| + // and the app is purged and created again. No allocation names the |
| + // first lifetime's data, so the new lifetime is refused. |
| + w := newSimWorld(t, false, false) |
| + w.activate() |
| + w.create(ltApp, ltOne) |
| + w.wake(ltOne) |
| + w.cutover() |
| + w.del(ltApp, ltOne, delNormal) |
| + w.purgeShop() |
| + if got := w.restore(ltApp, ltOne); got != "R8" { |
| + t.Fatalf("restore by the new lifetime = %s, want R8", got) |
| + } |
| + }) |
| + t.Run("managed enrolment after the origin", func(t *testing.T) { |
| + w := newSimWorld(t, true, false) |
| + w.setClock(10) |
| + w.activate() |
| + w.setClock(20) |
| + w.create(ltApp, ltOne) |
| + w.del(ltApp, ltOne, delNormal) |
| + w.setClock(30) |
| + w.enrol() |
| + if got := w.restore(ltApp, ltOne); got != "ok" { |
| + t.Fatalf("restore after a managed enrolment = %s, want 201", got) |
| + } |
| + }) |
| + seeds, steps := 200, 40 |
| + if testing.Short() { |
| + seeds, steps = 50, 30 |
| + } |
| + first := 0 |
| + if s, err := strconv.Atoi(os.Getenv("RESTORE_SIM_SEED")); err == nil { |
| + first, seeds = s, s+1 |
| + } |
| + t.Logf("seeds %d to %d, %d steps each", first, seeds-1, steps) |
| + start := time.Now() |
| + tally := newSimTally() |
| + for seed := first; seed < seeds; seed++ { |
| + ok := t.Run(fmt.Sprintf("seed %d", seed), func(t *testing.T) { |
| + rng := rand.New(rand.NewSource(int64(seed))) |
| + w := newSimWorld(t, rng.Intn(2) == 0, rng.Intn(2) == 0) |
| + w.seed, w.tally = int64(seed), tally |
| + for i := 0; i < steps; i++ { |
| + w.step(rng) |
| + } |
| + }) |
| + if !ok { |
| + t.Fatalf("seed %d failed; RESTORE_SIM_SEED=%d runs it alone", seed, seed) |
| + } |
| + } |
| + t.Logf("%d seeds of %d steps in %v; %s", seeds-first, steps, time.Since(start).Round(time.Millisecond), tally) |
| +} |