carlos / platform Public

member backups 2a: drill fixes before flagship (#898)

R1: the nightly restore drill doesn't test a replica while an offline
move's landed copy awaits promotion (staging under moves/<host>/ means
unverified/moving, checked at the bracket's open and close), so it can't
pass on a stale copy or fail on a mixed one. R1b/R1c: the bracket also
compares the record's LastMove and its stored version (S3 version ID and
last-modified, free on the existing GET), so legacy moves and any record
write mid-test make the verdict unverified. R2: restores go through a
read-only client over the planner's listing (12 LISTs per host, was 20).
R3: home-region boxes (empty CARLOS_REGION) run the drill, matching home
records exactly. Also fixes the TestLargeManifestReleaseThenKeep CI flake
(TestMoveTicketsPausePoints leaked a running stop).

Reviews: Astra code review (fixed), Fable scoped re-review, census rounds
1-2 READY (#280).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Squashed from member-backups-2a-landing into main.
claude agent, operated by paul@keymail.dev af871da0fab66ab4cdc46ac64dae245131f93855 parent f2cf282
27 files changed, +1,587 −51
  • docs/superpowers/notes/census-proposal-member-backups-2a-landing.md +23 −0
  • docs/superpowers/notes/reviews/CODEX-FINDINGS-census-member-backups-2a-landing-R2.md +15 −0
  • docs/superpowers/notes/reviews/CODEX-FINDINGS-census-member-backups-2a-landing.md +12 −0
  • docs/superpowers/notes/reviews/CODEX-REVIEW-BRIEF-census-member-backups-2a-landing-R2.md +4 −0
  • docs/superpowers/notes/reviews/CODEX-REVIEW-BRIEF-census-member-backups-2a-landing.md +5 −0
  • internal/activator/handover_test.go +21 −1
  • internal/dbdoor/plan_from.go +31 −0
  • internal/dbdoor/plan_from_test.go +43 −0
  • internal/lease/check.go +49 −0
  • internal/lease/check_test.go +79 −0
  • internal/ops/drillidentity.go +56 −16
  • internal/ops/hibernate_verify.go +100 −11
  • internal/ops/hibernate_verify_families_test.go +1 −1
  • internal/ops/hibernate_verify_home_test.go +109 −0
  • internal/ops/hibernate_verify_restore_test.go +72 −8
  • internal/ops/hibernate_verify_staging_test.go +338 −0
  • internal/ops/hibernate_verify_stamp_test.go +289 −0
  • internal/ops/hibernate_verify_test.go +30 −10
  • internal/ops/ops.go +6 −3
  • internal/provision/plan9_b8_census_test.go +6 −1
  • internal/provision/record_stamped.go +45 −0
  • internal/provision/record_stamped_test.go +64 −0
  • internal/provision/sidecar.go +6 −0
  • internal/provision/testdata/plan14-root-reads-chain.tsv +1 −0
  • internal/provision/testdata/plan14-root-reads-member-backups-2a-landing.tsv +12 −0
  • internal/release/stamped.go +75 −0
  • internal/release/stamped_test.go +95 −0

CI passed — run details

diff --git a/docs/superpowers/notes/census-proposal-member-backups-2a-landing.md b/docs/superpowers/notes/census-proposal-member-backups-2a-landing.md
new file mode 100644
index 000000000..3f8587602
--- /dev/null
+++ b/docs/superpowers/notes/census-proposal-member-backups-2a-landing.md
@@ -0,0 +1,23 @@
+# Census approval: member-backups-2a-landing
+
+Ruling `census-ruling-member-backups-2a-landing`. The independent reviewer approves or rejects every change below, 1 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26).
+
+| unit | change | read sites | what changed |
+|---|---|---|---|
+| `internal/ops/ops.go` `hibernateRun.run` | body | unchanged (1) | R3 (#898): an empty CARLOS_REGION (a home-region box) is the home region and no longer refuses; the bracket matches records whose region is "" exactly. A malformed non-empty region still refuses (dbreads.ValidRegion, or a fleet/<name> placement). No read added or changed: the same refusals in the same order (root first, then self.json, then the region gate), the same stores. Package envelopes: internal/ops adds one read-only bounded ListPage (one key) of moves/<host>/ in the drill's own data bucket at each end of a host's bracket (R1), and the bracket compares the record's LastMove (R1b) and the record object's stamp (R1c: ETag, version id, last-modified) at open and close, all from the same record GET it already made (now provision.GetRecordStamped / GetSidecarRecordStamped); internal/provision adds those two read-only getters (decodeSidecarAt shared with GetSidecarRecord, no writer touched); internal/release adds GetStamped, S3Store.GetStamped and ObjectStamp; internal/lease adds VerifyReaderAt and a read-only litestream client (R2); internal/dbdoor adds PlanListed, the planner's listing as a list/open reader (R2). The drill runs as carlos and refuses root. |
+
+Envelopes re-pinned: `internal/dbdoor`, `internal/lease`, `internal/ops`, `internal/provision`, `internal/release`.
+
+Review: a model from the other family than the author reads the branch's diff against main on the amadan.net remote (`origin` or `amadan`, whichever points at amadan.net) and gives a verdict for every unit and every re-pinned envelope above. For a unit, compare the change with its recorded disposition and basis below; for an envelope, read every changed function in the package and what it reaches. Reject if the change lets root open, run, query or follow anything it did not before from a path or input a tenant, an app or a box agent can create, write or name; if it weakens a check, refusal, validation, argument or environment the basis relies on; or if the diff cannot settle either. Otherwise approve. Record each verdict on #280 with the tip. A rejected unit goes back to the author to correct; nothing escalates to the census owner.
+
+Recorded dispositions, which each change must still satisfy:
+
+- `internal/ops/ops.go` `hibernateRun.run`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-member-backups-2a;basis=new, the drill (carlos ops hibernate-verify, user carlos): the verb's body, moved out of runHibernateVerify so a test can run it whole. First of all it refuses root (Root, from os.Geteuid() == 0 in runHibernateVerify): one log line, exit 1, before any monitor file is read, the deployment store opened or the registry opened (census round 1 P1, ls284: self.json, which the carlos user writes, names the record a run replaces). Then, as before: boxself.ReadFresh of self.json (refuses to run without a fresh record), dbreads.ValidRegion(CARLOS_REGION), openDeployStore, registry.Open(RegPath) (its +file:Open, the same registry the old body opened, closed after HibernatingHosts), dbverify.Load of this box's own control/verify/<ref>.json, selectHosts (verify-assign.json on a group box), MkdirTemp under the unit's on-disk TMPDIR, the drill, and dbverify.Publish to control/verify/<ref>.json only. Final fix wave (still refusing root first): the self.json read is retried every 15 s for up to 5 minutes (SelfWait, the same boxself.ReadFresh), a fleet box's CARLOS_REGION fleet/<name> is accepted beside dbreads.ValidRegion, it calls clearCrashedScratch on its own TmpDir right after the root refusal and the hibernate-config check, before the self record and both empty-fleet returns (re-review item 9), and its publisher now writes through dbverify.PublishOver (the same Get-then-CAS Put of control/verify/<ref>.json, also parsing the record it reads to drop hosts a landing removed). No new read source.
+
+New dispositions, which census-propose wrote and the reviewer checks against the unit's reads and the diff:
+
+- new `internal/release/stamped.go:S3Store.GetStamped`: reads +file:ReadAll; written legacy, accepted-legacy, frozen
+
+Seal: `b130b2d616e6476f056f4bd3dd5a5f64dd77aca49e95718ad6419ed0fd37f2d5` → `bf37ccf4fdd0d81a1dba7370a393074b763841b349d45fb65de12a037faf01ea`.
+
+Overlay: `internal/provision/testdata/plan14-root-reads-member-backups-2a-landing.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
diff --git a/docs/superpowers/notes/reviews/CODEX-FINDINGS-census-member-backups-2a-landing-R2.md b/docs/superpowers/notes/reviews/CODEX-FINDINGS-census-member-backups-2a-landing-R2.md
new file mode 100644
index 000000000..d1e690b41
--- /dev/null
+++ b/docs/superpowers/notes/reviews/CODEX-FINDINGS-census-member-backups-2a-landing-R2.md
@@ -0,0 +1,15 @@
+Reviewed `445ed3be..1eb84b682eb44db5ab4e7ab6fea9f84ec85e9ee9`, census round 2 of 3. Round 1 had no findings to carry forward. No new P1, P2, or P3 findings.
+
+| Unit / envelope | Verdict | Evidence |
+|---|---|---|
+| `hibernateRun.run` | **Approve** | Root refusal remains before monitor reads and store access. Its body is unchanged this round. [ops.go:449](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/mb-2a-landing/internal/ops/ops.go:449) |
+| `S3Store.GetStamped` | **Approve** | Same bucket, key, request, error mapping and body read as `Get`; metadata comes from that same response. The new `legacy / accepted-legacy` disposition fits these reads. [stamped.go:57](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/mb-2a-landing/internal/release/stamped.go:57) |
+| `internal/release` | **Approve** | Dispatch adds no writes or alternate read source. Fallback retains ordinary `Get`; stamp comparison checks all three fields. [stamped.go:28](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/mb-2a-landing/internal/release/stamped.go:28) |
+| `internal/provision` | **Approve** | Both stamped getters retain existing keys and decoding checks, including instance retirement refusal. The extracted sidecar validation is unchanged; all three record-write-census entries remain read-only key sites. [record_stamped.go:18](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/mb-2a-landing/internal/provision/record_stamped.go:18), [sidecar.go:344](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/mb-2a-landing/internal/provision/sidecar.go:344), [census:1024](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/mb-2a-landing/internal/provision/plan9_b8_census_test.go:1024) |
+| `internal/ops` | **Approve** | Existing identity and move refusals remain. A changed record stamp now discards the result; record-read failures still propagate. No new root authority. [drillidentity.go:115](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/mb-2a-landing/internal/ops/drillidentity.go:115) |
+| `internal/dbdoor` | **Approve** | Code and envelope pin are unchanged from round 1. `PlanListed` still exposes only listing and opening. [plan_from.go:172](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/mb-2a-landing/internal/dbdoor/plan_from.go:172) |
+| `internal/lease` | **Approve** | Code and envelope pin are unchanged from round 1. The restore wrapper still refuses every replica write and deletion. [check.go:277](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/mb-2a-landing/internal/lease/check.go:277) |
+
+`git diff --check` passed. Targeted tests, including both censuses, could not start because the read-only sandbox prevented Go from creating its work directory. `GOCACHE` remained unset. No files changed, subagents spawned, or full suites run.
+
+**READY**
\ No newline at end of file
diff --git a/docs/superpowers/notes/reviews/CODEX-FINDINGS-census-member-backups-2a-landing.md b/docs/superpowers/notes/reviews/CODEX-FINDINGS-census-member-backups-2a-landing.md
new file mode 100644
index 000000000..c85ea676e
--- /dev/null
+++ b/docs/superpowers/notes/reviews/CODEX-FINDINGS-census-member-backups-2a-landing.md
@@ -0,0 +1,12 @@
+Reviewed `178dcfe5..445ed3be813a146dad69bc5ea86fda98a9ce6875`, census round 1 of 3. No P1, P2, or P3 findings.
+
+| Unit / envelope | Verdict | Evidence |
+|---|---|---|
+| `hibernateRun.run` | **Approve** | Root is refused before monitor reads or store access at [ops.go:449](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/mb-2a-landing/internal/ops/ops.go:449). The empty-region exception retains malformed-region refusal at [ops.go:481](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/mb-2a-landing/internal/ops/ops.go:481) and exact record-region matching at [drillidentity.go:82](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/mb-2a-landing/internal/ops/drillidentity.go:82). The ls284 boundary remains intact. |
+| `internal/ops` | **Approve** | Staging uses the configured data bucket at [hibernate_verify.go:239](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/mb-2a-landing/internal/ops/hibernate_verify.go:239), with a one-key, host-delimited listing and error refusal at [hibernate_verify.go:508](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/mb-2a-landing/internal/ops/hibernate_verify.go:508). `LastMove` comparison uses the existing record read and discards results spanning a completed move at [drillidentity.go:104](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/mb-2a-landing/internal/ops/drillidentity.go:104). No new root authority. |
+| `internal/lease` | **Approve** | `VerifyReaderAt` uses the existing restore/check/cleanup path through a wrapper whose write and deletion methods unconditionally return `ErrReadOnly`; it does not expose the v0.3 client interface. [check.go:277](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/mb-2a-landing/internal/lease/check.go:277) |
+| `internal/dbdoor` | **Approve** | `PlanListed` retains the existing planner and returns a concrete wrapper exposing only list/open methods. Cached listings are reused; object opens retain the underlying reader’s errors. [plan_from.go:172](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/mb-2a-landing/internal/dbdoor/plan_from.go:172) |
+
+Targeted tests could not start: the read-only sandbox prevented Go from creating its work directory. `GOCACHE` remained unset. No files changed, no subagents spawned, and no full suites run.
+
+**READY**
\ No newline at end of file
diff --git a/docs/superpowers/notes/reviews/CODEX-REVIEW-BRIEF-census-member-backups-2a-landing-R2.md b/docs/superpowers/notes/reviews/CODEX-REVIEW-BRIEF-census-member-backups-2a-landing-R2.md
new file mode 100644
index 000000000..c0bdd765c
--- /dev/null
+++ b/docs/superpowers/notes/reviews/CODEX-REVIEW-BRIEF-census-member-backups-2a-landing-R2.md
@@ -0,0 +1,4 @@
+# Census review: member-backups-2a-landing, round 2 of 3
+
+Repo carlos/platform, branch member-backups-2a-landing, commit 1eb84b682eb44db5ab4e7ab6fea9f84ec85e9ee9. Round 1 (CODEX-FINDINGS-census-member-backups-2a-landing.md) was READY at 445ed3be (seal 45c6afd0). Since then R1c (a29c2252, 6cc46369, census 1eb84b68, seal bf37ccf4): the drill's identity bracket compares the record's stored version via new stamped reads (release.GetStamped / S3Store.GetStamped, a new unit; provision.GetRecordStamped / GetSidecarRecordStamped as read-only record-write-census key-sites); envelopes dbdoor, lease, ops, provision, release re-pinned.
+Review git diff 445ed3be..1eb84b682eb44db5ab4e7ab6fea9f84ec85e9ee9 against AGENTS.md "The census: the reviewer decides" (reject if root can open, run, query or follow anything new from tenant/app/agent-writable input, or a check weakens). Verdict per changed unit/envelope citing lines; then READY, READY AFTER FIXES, or NOT READY. Do not edit files, spawn other models, or run full suites; leave GOCACHE unset.
diff --git a/docs/superpowers/notes/reviews/CODEX-REVIEW-BRIEF-census-member-backups-2a-landing.md b/docs/superpowers/notes/reviews/CODEX-REVIEW-BRIEF-census-member-backups-2a-landing.md
new file mode 100644
index 000000000..ea60f3502
--- /dev/null
+++ b/docs/superpowers/notes/reviews/CODEX-REVIEW-BRIEF-census-member-backups-2a-landing.md
@@ -0,0 +1,5 @@
+# Census review: member-backups-2a-landing, round 1 of 3
+
+Repo carlos/platform, branch member-backups-2a-landing, commit 445ed3be813a146dad69bc5ea86fda98a9ce6875; diff 178dcfe5..445ed3be813a146dad69bc5ea86fda98a9ce6875.
+Card docs/superpowers/notes/census-proposal-member-backups-2a-landing.md (unit internal/ops hibernateRun.run; envelopes internal/ops, internal/lease, internal/dbdoor; seal b130b2d6 -> 45c6afd0).
+Reject per AGENTS.md "The census: the reviewer decides" if root can now open, run, query or follow anything new from tenant/app/agent-writable input, or a check is weakened; ls284 precedent (root refuses monitor files) must still hold. Look at: the drill's new listing of moves/<host>/ in the box's own data bucket, the read-only restore client, the empty-region gate. Verdict per unit/envelope citing lines; then READY, READY AFTER FIXES, or NOT READY. Do not edit files, spawn other models, or run full suites; leave GOCACHE unset.
diff --git a/internal/activator/handover_test.go b/internal/activator/handover_test.go
index 86d9ef3e4..114b48ff3 100644
--- a/internal/activator/handover_test.go
+++ b/internal/activator/handover_test.go
@@ -13,6 +13,7 @@ import (
"github.com/carlosframework/platform/internal/boxchoice"
"github.com/carlosframework/platform/internal/edge"
"github.com/carlosframework/platform/internal/instancectl"
+ "github.com/carlosframework/platform/internal/lease"
"github.com/carlosframework/platform/internal/registry"
)
@@ -408,7 +409,11 @@ func TestMoveTicketsPausePoints(t *testing.T) {
}
}
d := s.a.MoveState(s.rt, askClient)
- go s.stopForTest(e)
+ stopDone := make(chan struct{})
+ go func() {
+ defer close(stopDone)
+ s.stopForTest(e)
+ }()
<-stopping
ctx, cancel := context.WithCancel(t.Context())
r := edge.WithMoveTicket(httptest.NewRequestWithContext(ctx, http.MethodGet, "https://shop.example.com/", nil), d.Done)
@@ -434,6 +439,21 @@ func TestMoveTicketsPausePoints(t *testing.T) {
t.Fatal(err)
}
close(finish)
+ // The stop runs on past finish: its release writes the lock's
+ // marker. It must have finished, marker written, before this test
+ // returns and its fixture closes; otherwise the marker's PUT fails,
+ // is owed into lease's process-wide obligation store, and the next
+ // test's acquire settles it against that test's fixture (the stray
+ // PUT TestLargeManifestReleaseThenKeep saw on CI, #898).
+ <-stopDone
+ if !s.stoppedFor(e) {
+ t.Fatal("the subtest ended with its stop still running")
+ }
+ for _, o := range lease.PendingObligations() {
+ if strings.HasSuffix(o.Key, s.lockKey()) {
+ t.Fatalf("the subtest left a release marker owed for %s", o.Key)
+ }
+ }
})
}
diff --git a/internal/dbdoor/plan_from.go b/internal/dbdoor/plan_from.go
index 0e3587739..92f1df000 100644
--- a/internal/dbdoor/plan_from.go
+++ b/internal/dbdoor/plan_from.go
@@ -158,6 +158,37 @@ func PlanFrom(ctx context.Context, rd ReplicaReader, at time.Time) (RestorePlan,
return planFrom(ctx, &listing{rd: rd, asOf: !at.IsZero(), maxFiles: -1}, at)
}
+// PlanListed plans the newest copy exactly as PlanFrom(ctx, rd,
+// time.Time{}) does, and returns with it the listing it planned from as a
+// reader (the nightly drill's restore, member backups 2a R2). Its LTXFiles
+// answers each level from what the plan listed (a level the plan did not
+// list is listed once, then kept) and its OpenLTXFile reads rd, so a
+// restore pinned to the plan's TXID through it lists nothing again and
+// reads the same snapshot of the replica the plan did. A file compacted
+// away since still answers its open with rd's error (os.ErrNotExist from
+// the S3 client), which is the caller's cue to plan again. The reader has
+// only those two methods: no write is reachable through it, not even by
+// type assertion.
+func PlanListed(ctx context.Context, rd ReplicaReader) (RestorePlan, ReplicaReader, error) {
+ l := &listing{rd: rd, maxFiles: -1}
+ plan, err := planFrom(ctx, l, time.Time{})
+ if err != nil {
+ return RestorePlan{}, nil, err
+ }
+ return plan, listedReader{l: l}, nil
+}
+
+// listedReader is a listing's read half and nothing else.
+type listedReader struct{ l *listing }
+
+func (r listedReader) LTXFiles(ctx context.Context, level int, seek ltx.TXID, useMetadata bool) (ltx.FileIterator, error) {
+ return r.l.LTXFiles(ctx, level, seek, useMetadata)
+}
+
+func (r listedReader) OpenLTXFile(ctx context.Context, level int, minTXID, maxTXID ltx.TXID, offset, size int64) (io.ReadCloser, error) {
+ return r.l.OpenLTXFile(ctx, level, minTXID, maxTXID, offset, size)
+}
+
// planFrom is PlanFrom over a listing the caller made, so the caller can
// read the same listing afterwards.
func planFrom(ctx context.Context, l *listing, at time.Time) (RestorePlan, error) {
diff --git a/internal/dbdoor/plan_from_test.go b/internal/dbdoor/plan_from_test.go
index 37ccd126d..b696b8c91 100644
--- a/internal/dbdoor/plan_from_test.go
+++ b/internal/dbdoor/plan_from_test.go
@@ -16,6 +16,7 @@ import (
"github.com/superfly/ltx"
"github.com/carlosframework/platform/internal/dbdoor/dbdoortest"
+ "github.com/carlosframework/platform/internal/lease"
)
// metaSpy records every useMetadata the listing passes down: the box must
@@ -410,3 +411,45 @@ func TestPositionAndHistoryFileCap(t *testing.T) {
t.Fatalf("PositionAndHistory over %d files capped at %d = %v, known %v; want ErrTooManyFiles", n, n-1, err, known)
}
}
+
+// PlanListed plans what PlanFrom plans and hands back the listing it
+// planned from as a reader: a restore pinned to the plan's TXID through it
+// lists nothing again (each level once in all, member backups 2a R2), and
+// the reader has no method that writes, not even by type assertion.
+func TestPlanListedRestoresThroughItsListing(t *testing.T) {
+ t.Parallel()
+ dir := t.TempDir()
+ dbdoortest.Replicate(t, dir, 3)
+ want, err := PlanFrom(context.Background(), lsfile.NewReplicaClient(dir), time.Time{})
+ if err != nil {
+ t.Fatal(err)
+ }
+ rd := &countingLists{ReplicaReader: lsfile.NewReplicaClient(dir), lists: map[int]int{}}
+ plan, listed, err := PlanListed(context.Background(), rd)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !reflect.DeepEqual(plan, want) {
+ t.Fatalf("PlanListed planned %+v, PlanFrom %+v", plan, want)
+ }
+ if _, ok := listed.(litestream.ReplicaClient); ok {
+ t.Fatal("the listed reader is a full replica client: its holder can reach write methods")
+ }
+ if _, err := lease.VerifyReaderAt(context.Background(), listed, "hib/x.example.com", t.TempDir(), plan.TXID); err != nil {
+ t.Fatalf("restore through the listing: %v", err)
+ }
+ for level := 0; level <= litestream.SnapshotLevel; level++ {
+ if n := rd.lists[level]; n != 1 {
+ t.Errorf("level %d listed %d times by the plan and the restore, want once", level, n)
+ }
+ }
+}
+
+// An empty replica is ErrNothingReplicated, with no reader.
+func TestPlanListedAnEmptyReplica(t *testing.T) {
+ t.Parallel()
+ _, listed, err := PlanListed(context.Background(), lsfile.NewReplicaClient(t.TempDir()))
+ if !errors.Is(err, ErrNothingReplicated) || listed != nil {
+ t.Fatalf("PlanListed on an empty replica = %v, %v; want ErrNothingReplicated and no reader", listed, err)
+ }
+}
diff --git a/internal/lease/check.go b/internal/lease/check.go
index 79a9340a4..4d9ca8bb1 100644
--- a/internal/lease/check.go
+++ b/internal/lease/check.go
@@ -7,6 +7,7 @@ import (
"errors"
"fmt"
"io"
+ "log/slog"
"os"
"path/filepath"
"sync"
@@ -259,6 +260,54 @@ func VerifyClientAt(ctx context.Context, client litestream.ReplicaClient, prefix
})
}
+// ReplicaReader is the read half of a replica client: list a level and
+// open a file, nothing that writes. dbdoor.ReplicaReader is the same
+// interface; a planner's listing is one.
+type ReplicaReader interface {
+ LTXFiles(ctx context.Context, level int, seek ltx.TXID, useMetadata bool) (ltx.FileIterator, error)
+ OpenLTXFile(ctx context.Context, level int, minTXID, maxTXID ltx.TXID, offset, size int64) (io.ReadCloser, error)
+}
+
+// VerifyReaderAt is VerifyClientAt over a reader that can only list and
+// open (member backups 2a, R2): the nightly drill restores through the
+// listing it planned from, so it lists each level once and holds nothing
+// that can write. litestream's restore needs a full client, so it is given
+// readOnlyClient, whose three writing methods have no body but ErrReadOnly,
+// whatever rd is underneath.
+func VerifyReaderAt(ctx context.Context, rd ReplicaReader, prefix, dir string, txid uint64) (uint32, error) {
+ return VerifyClientAt(ctx, readOnlyClient{rd: rd}, prefix, dir, txid)
+}
+
+// ErrReadOnly is every write a verify restore's client is asked for.
+var ErrReadOnly = errors.New("lease: this replica client is read-only; a verify restore never writes a replica")
+
+// readOnlyClient is a litestream.ReplicaClient made of a ReplicaReader. It
+// must never implement litestream.ReplicaClientV3, or Restore would take
+// the v0.3 path.
+type readOnlyClient struct{ rd ReplicaReader }
+
+func (c readOnlyClient) Type() string { return "carlos-verify-read-only" }
+func (c readOnlyClient) Init(context.Context) error { return nil }
+func (c readOnlyClient) SetLogger(*slog.Logger) {}
+
+func (c readOnlyClient) LTXFiles(ctx context.Context, level int, seek ltx.TXID, useMetadata bool) (ltx.FileIterator, error) {
+ return c.rd.LTXFiles(ctx, level, seek, useMetadata)
+}
+
+func (c readOnlyClient) OpenLTXFile(ctx context.Context, level int, minTXID, maxTXID ltx.TXID, offset, size int64) (io.ReadCloser, error) {
+ return c.rd.OpenLTXFile(ctx, level, minTXID, maxTXID, offset, size)
+}
+
+func (c readOnlyClient) WriteLTXFile(context.Context, int, ltx.TXID, ltx.TXID, io.Reader) (*ltx.FileInfo, error) {
+ return nil, ErrReadOnly
+}
+
+func (c readOnlyClient) DeleteLTXFiles(context.Context, []*ltx.FileInfo) error { return ErrReadOnly }
+
+func (c readOnlyClient) DeleteAll(context.Context) error { return ErrReadOnly }
+
+var _ litestream.ReplicaClient = readOnlyClient{}
+
// ErrCheckFailed marks a CheckDB error (and so a VerifyReplicaAt error)
// that proves the copy damaged: integrity_check answered something other
// than "ok", SQLite itself reported the file corrupt or not a database, or
diff --git a/internal/lease/check_test.go b/internal/lease/check_test.go
index 6d9ae2791..22715bf2f 100644
--- a/internal/lease/check_test.go
+++ b/internal/lease/check_test.go
@@ -678,3 +678,82 @@ func TestVerifyClientAt(t *testing.T) {
}
assertEmptyDir(t, dir)
}
+
+// writeTrap is a full replica client that fails the test on any write: what
+// a reader handed to VerifyReaderAt may really be underneath.
+type writeTrap struct {
+ *lsfile.ReplicaClient
+ t *testing.T
+}
+
+func (w writeTrap) WriteLTXFile(context.Context, int, ltx.TXID, ltx.TXID, io.Reader) (*ltx.FileInfo, error) {
+ w.t.Error("a verify restore wrote an LTX file")
+ return nil, errors.New("trap")
+}
+
+func (w writeTrap) DeleteLTXFiles(context.Context, []*ltx.FileInfo) error {
+ w.t.Error("a verify restore deleted LTX files")
+ return errors.New("trap")
+}
+
+func (w writeTrap) DeleteAll(context.Context) error {
+ w.t.Error("a verify restore deleted the replica")
+ return errors.New("trap")
+}
+
+// listOpen is only the read half of a replica client.
+type listOpen struct{ rd ReplicaReader }
+
+func (l listOpen) LTXFiles(ctx context.Context, level int, seek ltx.TXID, useMetadata bool) (ltx.FileIterator, error) {
+ return l.rd.LTXFiles(ctx, level, seek, useMetadata)
+}
+
+func (l listOpen) OpenLTXFile(ctx context.Context, level int, minTXID, maxTXID ltx.TXID, offset, size int64) (io.ReadCloser, error) {
+ return l.rd.OpenLTXFile(ctx, level, minTXID, maxTXID, offset, size)
+}
+
+// VerifyReaderAt is VerifyClientAt over a reader that can only list and
+// open (member backups 2a, R2): the same pinned restore, check, counter and
+// sweep, and a client handed to litestream whose writes have no body but
+// ErrReadOnly, whatever the reader is underneath.
+func TestVerifyReaderAt(t *testing.T) {
+ replica, txids := replicatedBatches(t)
+ want, _ := restoredHeader(t, replica, txids[1])
+ trap := writeTrap{ReplicaClient: lsfile.NewReplicaClient(replica), t: t}
+ dir := t.TempDir()
+ got, err := VerifyReaderAt(context.Background(), listOpen{rd: trap}, "hib/x.example.com", dir, uint64(txids[1]))
+ if err != nil || got != want {
+ t.Fatalf("VerifyReaderAt = %d, %v; want %d", got, err, want)
+ }
+ assertEmptyDir(t, dir)
+
+ // The client litestream is given refuses every write, even over a
+ // reader whose dynamic type could write, and is never a v0.3 client.
+ c := readOnlyClient{rd: trap}
+ if _, err := c.WriteLTXFile(context.Background(), 0, 1, 1, strings.NewReader("x")); !errors.Is(err, ErrReadOnly) {
+ t.Fatalf("WriteLTXFile = %v, want ErrReadOnly", err)
+ }
+ if err := c.DeleteLTXFiles(context.Background(), nil); !errors.Is(err, ErrReadOnly) {
+ t.Fatalf("DeleteLTXFiles = %v, want ErrReadOnly", err)
+ }
+ if err := c.DeleteAll(context.Background()); !errors.Is(err, ErrReadOnly) {
+ t.Fatalf("DeleteAll = %v, want ErrReadOnly", err)
+ }
+ if _, ok := any(c).(litestream.ReplicaClientV3); ok {
+ t.Fatal("the read-only client is a v0.3 client; Restore would take the v0.3 path")
+ }
+}
+
+// A planned object gone before the download reads it still reaches the
+// caller as os.ErrNotExist through the read-only client, so the drill
+// replans.
+func TestVerifyReaderAtMissingObject(t *testing.T) {
+ replica, txids := replicatedBatches(t)
+ dir := t.TempDir()
+ rd := &vanishingClient{ReplicaClient: lsfile.NewReplicaClient(replica), dir: replica}
+ _, err := VerifyReaderAt(context.Background(), rd, "hib/x.example.com", dir, uint64(txids[1]))
+ if !errors.Is(err, os.ErrNotExist) || errors.Is(err, ErrCheckFailed) || errors.Is(err, ErrNoReplica) {
+ t.Fatalf("VerifyReaderAt with a vanished object = %v, want os.ErrNotExist", err)
+ }
+ assertEmptyDir(t, dir)
+}
diff --git a/internal/ops/drillidentity.go b/internal/ops/drillidentity.go
index 28da68058..81e60206f 100644
--- a/internal/ops/drillidentity.go
+++ b/internal/ops/drillidentity.go
@@ -39,6 +39,36 @@ type drillRecord struct {
account, app, host, region string
created time.Time
moving bool
+ lastMove string // moveStamp of the record's LastMove
+ // stamp is the record object's stamp from the same read (ETag, and
+ // on the versioned deployment bucket its version id and time).
+ stamp release.ObjectStamp
+}
+
+// drillIdentity is what the bracket captures at its open and confirms at
+// its close: the instance's identity, which the verdict publishes, and two
+// things only the bracket sees. lastMove stamps the record's latest
+// closed move: Move is set only from a move's prepare to its close, so a
+// whole move that began and closed between the two reads (R1b) shows as a
+// new outcome in LastMove. record is the record object's stamp, which
+// changes on every write of it: a legacy move (MovesEnabled false) closes
+// through MoveComplete and writes no LastMove, and a round trip there and
+// back leaves the record's bytes, and so its ETag, as they were, but not
+// its version (Astra's review of R1b).
+type drillIdentity struct {
+ dbreads.Identity
+ lastMove string
+ record release.ObjectStamp
+}
+
+// moveStamp is the record's latest closed move, every field of it ("" when
+// it has none): a different move, outcome or close time is a different
+// stamp.
+func moveStamp(m *provision.MoveOutcome) string {
+ if m == nil {
+ return ""
+ }
+ return fmt.Sprintf("%q %q %s %g", m.ID, m.Outcome, m.At.UTC().Format(time.RFC3339Nano), m.OfflineS)
}
// captureDrillIdentity is the opening half of the drill's bracket: the
@@ -49,23 +79,24 @@ type drillRecord struct {
// its placement); dbreads.CodeMoving, with the identity, when the instance
// is mid-move. detail says why for a code. err is a record that could not
// be read or whose identity cannot be computed.
-func captureDrillIdentity(ctx context.Context, s release.Store, region string, rt HibernatingRoute) (id dbreads.Identity, code, detail string, err error) {
+func captureDrillIdentity(ctx context.Context, s release.Store, region string, rt HibernatingRoute) (id drillIdentity, code, detail string, err error) {
rec, detail, err := readDrillRecord(ctx, s, rt)
if err != nil || detail != "" {
if detail != "" {
- return dbreads.Identity{}, codeNoRecord, detail, nil
+ return drillIdentity{}, codeNoRecord, detail, nil
}
- return dbreads.Identity{}, "", "", err
+ return drillIdentity{}, "", "", err
}
if rec.region != region {
- return dbreads.Identity{}, codeNoRecord,
+ return drillIdentity{}, codeNoRecord,
fmt.Sprintf("its record places it in %q, not this box's %q", rec.region, region), nil
}
inc, err := provision.Incarnation(rec.account, rec.app, rec.host, rec.created)
if err != nil {
- return dbreads.Identity{}, "", "", fmt.Errorf("the record's identity: %w", err)
+ return drillIdentity{}, "", "", fmt.Errorf("the record's identity: %w", err)
}
- id = dbreads.Identity{Account: rec.account, App: rec.app, Host: rec.host, Region: region, Incarnation: inc}
+ id = drillIdentity{Identity: dbreads.Identity{Account: rec.account, App: rec.app, Host: rec.host, Region: region, Incarnation: inc},
+ lastMove: rec.lastMove, record: rec.stamp}
if rec.moving {
return id, dbreads.CodeMoving, "", nil
}
@@ -73,25 +104,34 @@ func captureDrillIdentity(ctx context.Context, s release.Store, region string, r
}
// confirmDrillIdentity is the closing half: captureDrillIdentity again for
-// want's host, and dbreads.CodeRecordChanged unless it finds want. A record
-// that has gone (or left this region) since the bracket opened is
-// CodeRecordChanged, never codeNoRecord, and a change outranks a move.
-func confirmDrillIdentity(ctx context.Context, s release.Store, rt HibernatingRoute, want dbreads.Identity) (code string, err error) {
+// want's host, and dbreads.CodeRecordChanged unless it finds want's
+// identity. A record that has gone (or left this region) since the
+// bracket opened is CodeRecordChanged, never codeNoRecord, and a change
+// outranks a move. The same identity mid-move, or with another latest
+// closed move, is dbreads.CodeMoving: a move ran inside the test (R1b).
+// Otherwise any write of the record object between the two reads is
+// CodeRecordChanged, whatever it left in the bytes: the record a verdict
+// is bound to must be the one the test began on.
+func confirmDrillIdentity(ctx context.Context, s release.Store, rt HibernatingRoute, want drillIdentity) (code string, err error) {
got, code, _, err := captureDrillIdentity(ctx, s, want.Region, rt)
switch {
case err != nil:
return "", err
- case code == codeNoRecord, got != want:
+ case code == codeNoRecord, got.Identity != want.Identity:
+ return dbreads.CodeRecordChanged, nil
+ case code == dbreads.CodeMoving, got.lastMove != want.lastMove:
+ return dbreads.CodeMoving, nil
+ case !got.record.Same(want.record):
return dbreads.CodeRecordChanged, nil
}
- return code, nil
+ return "", nil
}
// readDrillRecord reads rt's record from its family. A host with none, or
// whose record names another host, is a detail saying so and no error.
func readDrillRecord(ctx context.Context, s release.Store, rt HibernatingRoute) (drillRecord, string, error) {
if !rt.Sidecar {
- rec, err := provision.GetRecord(ctx, s, rt.Account, rt.App, rt.Host)
+ rec, st, err := provision.GetRecordStamped(ctx, s, rt.Account, rt.App, rt.Host)
if errors.Is(err, os.ErrNotExist) {
return drillRecord{}, "this box has the host, but there is no instance record for it", nil
}
@@ -99,13 +139,13 @@ func readDrillRecord(ctx context.Context, s release.Store, rt HibernatingRoute)
return drillRecord{}, "", err
}
return drillRecord{account: rec.Account, app: rec.App, host: rec.Host, region: rec.Region,
- created: rec.CreatedAt, moving: rec.Move != nil}, "", nil
+ created: rec.CreatedAt, moving: rec.Move != nil, lastMove: moveStamp(rec.LastMove), stamp: st}, "", nil
}
name, ok := sidecarName(rt.Host)
if !ok {
return drillRecord{}, "this box has a sidecar route whose host names no sidecar", nil
}
- rec, err := provision.GetSidecarRecord(ctx, s, rt.Account, rt.App, name)
+ rec, st, err := provision.GetSidecarRecordStamped(ctx, s, rt.Account, rt.App, name)
if errors.Is(err, os.ErrNotExist) {
return drillRecord{}, "this box has the sidecar, but there is no sidecar record for it", nil
}
@@ -115,7 +155,7 @@ func readDrillRecord(ctx context.Context, s release.Store, rt HibernatingRoute)
if rec.Host != rt.Host {
return drillRecord{}, fmt.Sprintf("the sidecar record %q names host %q, not this one", name, rec.Host), nil
}
- return drillRecord{account: rec.Account, app: rec.App, host: rec.Host, region: rec.Region, created: rec.CreatedAt}, "", nil
+ return drillRecord{account: rec.Account, app: rec.App, host: rec.Host, region: rec.Region, created: rec.CreatedAt, stamp: st}, "", nil
}
// sidecarName is the sidecar name a sidecar host carries, its first label
diff --git a/internal/ops/hibernate_verify.go b/internal/ops/hibernate_verify.go
index e3b053137..ce0bd223d 100644
--- a/internal/ops/hibernate_verify.go
+++ b/internal/ops/hibernate_verify.go
@@ -27,6 +27,7 @@ import (
"os"
"slices"
"sort"
+ "strings"
"sync"
"syscall"
"time"
@@ -137,8 +138,25 @@ var (
openReplica = func(ctx context.Context, bucket, prefix, region string) (dbdoor.ReplicaReader, error) {
return lease.ReadReplicaClient(ctx, bucket, prefix, region)
}
- verifyAt = lease.VerifyReplicaAt
- lockState = lease.LockState
+ // verifyAt restores the planned position through the planner's own
+ // listing (member backups 2a, R2): it holds a reader that can only list
+ // and open, and lists nothing the plan did not.
+ verifyAt = lease.VerifyReaderAt
+ lockState = lease.LockState
+ // openStaging opens this box's data bucket for the staged-copy check
+ // (stagedCopy): the bucket a move stages into and the activator's
+ // first wake promotes from. Once per run.
+ openStaging = func(ctx context.Context, bucket, region string) (release.PageLister, error) {
+ st, err := lease.NewFilesStore(ctx, bucket, region)
+ if err != nil {
+ return nil, err
+ }
+ pl, ok := st.(release.PageLister)
+ if !ok {
+ return nil, errors.New("the data bucket has no bounded listing")
+ }
+ return pl, nil
+ }
localFreshness = hibernateFreshness
// publishTicker is the run's publication clock: ticks every d, and a
// stop.
@@ -155,7 +173,8 @@ var (
// Drill is one run's settings. Cfg names the hibernate bucket; Store is the
// deployment bucket the provision records are read from; Region is this
-// box's region, which an instance's record must name; SelfRef is this
+// box's region, which an instance's record must name exactly ("" on a
+// home-region box, whose records carry ""); SelfRef is this
// box's reference, the owner its lease locks carry; TmpDir is the on-disk
// scratch each restore lands in.
//
@@ -174,6 +193,11 @@ type Drill struct {
Budget time.Duration
Max int
PublishEvery time.Duration
+
+ // staging is the data bucket the staged-copy check lists, opened once
+ // by VerifyHibernating; stagingErr is why it could not be.
+ staging release.PageLister
+ stagingErr error
}
// VerifyHibernating restore-drills the given hosts in order and returns a
@@ -202,7 +226,8 @@ type Drill struct {
//
// Each host is bracketed (P-11): its record is read before planning and
// again after the last replica byte, and any difference discards what the
-// restore found. Freshness is judged only on the box that provably holds
+// restore found. So is its move staging (R1): a staged copy waiting for
+// the first wake's promotion at either end is unverified, moving. Freshness is judged only on the box that provably holds
// the live lease (P-14).
func VerifyHibernating(ctx context.Context, d Drill, hosts []HibernatingRoute, now func() time.Time, publish func(map[string]dbverify.Verdict) bool) map[string]dbverify.Verdict {
start := now()
@@ -211,6 +236,7 @@ func VerifyHibernating(ctx context.Context, d Drill, hosts []HibernatingRoute, n
runCtx, cancel = context.WithTimeout(ctx, d.Budget)
}
defer cancel()
+ d.staging, d.stagingErr = openStaging(runCtx, d.Cfg.Bucket, d.Cfg.Region)
var res runResults
if publish != nil && d.PublishEvery > 0 {
@@ -371,7 +397,7 @@ func (d Drill) drillOne(ctx context.Context, rt HibernatingRoute, now func() tim
}
return unverified(ReasonRecordUnreadable, err.Error())
}
- v.Identity = dbverify.Identity(id)
+ v.Identity = dbverify.Identity(id.Identity)
switch code {
case codeNoRecord:
// No record of the host's family in this region when the test
@@ -381,6 +407,18 @@ func (d Drill) drillOne(ctx context.Context, rt HibernatingRoute, now func() tim
case dbreads.CodeMoving:
return unverified(ReasonMoving, "the instance was moving when the test began")
}
+ // A move that has landed here and not yet been promoted by the first
+ // wake (R1): its record is at rest, but the copy the instance will wake
+ // from is the staged one, not the replica this would test. Not tested;
+ // and when the staging cannot be read, nothing is either.
+ switch staged, err := d.stagedCopy(ctx, rt.Host); {
+ case err != nil && ctx.Err() != nil:
+ return dbverify.Verdict{}, false
+ case err != nil:
+ return unverified(ReasonStorageUnavailable, err.Error())
+ case staged:
+ return unverified(ReasonMoving, "the instance was moving when the test began")
+ }
// Each host restores into its own scratch directory, removed whatever
// happens, so an abandoned download leaves nothing behind.
@@ -419,6 +457,17 @@ func (d Drill) drillOne(ctx context.Context, rt HibernatingRoute, now func() tim
if code != "" {
return unverified(bracketReason(code), "the instance changed during the test, so its result was discarded")
}
+ // The staging again: a move's copy that arrived during the test (a
+ // landing, or its promotion racing the restore) discards the result,
+ // so neither a stale pass nor a mixed-lineage failure can stand.
+ switch staged, err := d.stagedCopy(ctx, rt.Host); {
+ case err != nil && ctx.Err() != nil:
+ return dbverify.Verdict{}, false
+ case err != nil:
+ return unverified(ReasonStorageUnavailable, "the move staging could not be read again after the restore, so its result was discarded: "+err.Error())
+ case staged:
+ return unverified(ReasonMoving, "the instance changed during the test, so its result was discarded")
+ }
v.VerifiedAt = now().UTC()
switch res.kind {
@@ -445,6 +494,41 @@ func (d Drill) drillOne(ctx context.Context, rt HibernatingRoute, now func() tim
return v, true
}
+// stagedCopy reports whether a move's staged copy of host waits under
+// moves/<host>/ in this box's data bucket (member backups 2a, R1). That is
+// what the activator's first wake trusts (promoteStagedReplica): any
+// object there, of any name, is mirrored over instances/<host>/ before
+// the restore, because staging wins over the own prefix. While one waits,
+// the replica the drill would test is not the instance's: after an offline
+// move lands it is empty, or an orphan of an earlier stay on this box that
+// restores clean. The listing asks for one key, read-only, as the
+// console's restore staging check does (hostHasStaging); the trailing
+// slash keeps app.example.co from seeing app.example.com's keys. An error
+// is returned, never read as nothing staged.
+func (d Drill) stagedCopy(ctx context.Context, host string) (bool, error) {
+ if d.stagingErr != nil {
+ return false, fmt.Errorf("move staging: %w", d.stagingErr)
+ }
+ if d.staging == nil {
+ return false, errors.New("move staging: the data bucket was not opened")
+ }
+ prefix := activator.MovesPrefix(host)
+ if host == "" || !strings.HasSuffix(prefix, "/") {
+ return false, fmt.Errorf("move staging: no staging prefix for %q", host)
+ }
+ keys, err := d.staging.ListPage(ctx, prefix, "", 1)
+ if err != nil {
+ return false, fmt.Errorf("move staging: list %s: %w", prefix, err)
+ }
+ if len(keys) == 0 {
+ return false, nil
+ }
+ if !strings.HasPrefix(keys[0], prefix) {
+ return false, fmt.Errorf("move staging: the listing of %s returned %q, outside it", prefix, keys[0])
+ }
+ return true, nil
+}
+
// bracketReason is the verdict reason for a bracket code.
func bracketReason(code string) string {
if code == dbreads.CodeMoving {
@@ -453,7 +537,8 @@ func bracketReason(code string) string {
return ReasonRecordChanged
}
-// restore plans the newest copy and restores exactly the planned position.
+// restore plans the newest copy and restores exactly the planned position,
+// through the plan's own listing (R2), so the restore lists nothing again.
// Compaction between the two can make that position unrestorable, or
// remove an object the plan named before its header or contents are read
// (os.ErrNotExist, as the S3 client reports a missing key); that is not a
@@ -471,7 +556,7 @@ func bracketReason(code string) string {
func (d Drill) restore(ctx context.Context, prefix, dir string) restoreResult {
var last restoreResult
for attempt := 0; attempt < 2; attempt++ {
- plan, err := d.plan(ctx, prefix)
+ plan, listed, err := d.plan(ctx, prefix)
switch {
case errors.Is(err, dbdoor.ErrNothingReplicated):
return restoreResult{kind: restoreNothing, err: err}
@@ -481,7 +566,7 @@ func (d Drill) restore(ctx context.Context, prefix, dir string) restoreResult {
case err != nil:
return restoreResult{kind: restoreUnavailable, err: fmt.Errorf("plan: %w", err)}
}
- counter, err := verifyAt(ctx, d.Cfg.Bucket, prefix, d.Cfg.Region, dir, plan.TXID)
+ counter, err := verifyAt(ctx, listed, prefix, dir, plan.TXID)
switch {
case err == nil:
return restoreResult{kind: restoreClean, plan: plan, counter: counter}
@@ -536,12 +621,16 @@ func storageError(err error) bool {
errors.As(err, &perr) || errors.As(err, &lerr) || errors.As(err, &serr) || errors.As(err, &errno)
}
-func (d Drill) plan(ctx context.Context, prefix string) (dbdoor.RestorePlan, error) {
+// plan plans the newest copy and returns the listing it planned from, the
+// only reader the restore is given: each level is listed once per attempt,
+// and a file compacted away since answers os.ErrNotExist, which plans
+// again.
+func (d Drill) plan(ctx context.Context, prefix string) (dbdoor.RestorePlan, dbdoor.ReplicaReader, error) {
rd, err := openReplica(ctx, d.Cfg.Bucket, prefix, d.Cfg.Region)
if err != nil {
- return dbdoor.RestorePlan{}, err
+ return dbdoor.RestorePlan{}, nil, err
}
- return dbdoor.PlanFrom(ctx, rd, time.Time{})
+ return dbdoor.PlanListed(ctx, rd)
}
// freshness judges whether a clean replica is still tracking its source,
diff --git a/internal/ops/hibernate_verify_families_test.go b/internal/ops/hibernate_verify_families_test.go
index 800a4eb2f..78f051ace 100644
--- a/internal/ops/hibernate_verify_families_test.go
+++ b/internal/ops/hibernate_verify_families_test.go
@@ -228,7 +228,7 @@ func TestDrillIdentityLeavesTheDbReadRuleAlone(t *testing.T) {
}
id, code, _, err := captureDrillIdentity(context.Background(), fx.store, fxRegion,
HibernatingRoute{Host: "resident.example.com", Account: fxAccount, App: fxApp})
- if err != nil || code != "" || dbverify.Identity(id) != idFor(t, "resident.example.com", fxRegion, fxCreated) {
+ if err != nil || code != "" || dbverify.Identity(id.Identity) != idFor(t, "resident.example.com", fxRegion, fxCreated) {
t.Fatalf("captureDrillIdentity = %+v, %q, %v", id, code, err)
}
}
diff --git a/internal/ops/hibernate_verify_home_test.go b/internal/ops/hibernate_verify_home_test.go
new file mode 100644
index 000000000..21060a91c
--- /dev/null
+++ b/internal/ops/hibernate_verify_home_test.go
@@ -0,0 +1,109 @@
+package ops
+
+import (
+ "context"
+ "strings"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/dbverify"
+ "github.com/carlosframework/platform/internal/lease"
+ "github.com/carlosframework/platform/internal/provision"
+)
+
+// Member backups 2a, R3: a home-region box has no CARLOS_REGION, and its
+// instances' records carry region "". An empty region is the home region:
+// the drill runs there and binds verdicts to records whose region is ""
+// exactly. Nothing else is loosened: a malformed region still refuses, and
+// a record in another region still does not match.
+
+// A home box (region "") drills a home instance end to end through the
+// real run path, restore included, and publishes its verdict, bound to the
+// home record. A record in another region on the same box is no_record.
+func TestRunHibernateVerifyHomeBoxDrillsHomeInstances(t *testing.T) {
+ const home, away = "home.example.com", "away.example.com"
+ fx := newRunFx(t, home, away)
+ fx.putRecord(fxAccount, home, fxCreated, func(r *provision.Record) { r.Region = "" })
+ fx.putRecord(fxAccount, away, fxCreated, func(r *provision.Record) { r.Region = "uk" })
+ swap(t, &verifyAt, lease.VerifyReaderAt)
+ fx.writeSelf(fxSelf, false)
+ r := fx.runner()
+ r.Region = ""
+ if code := r.run(context.Background()); code != 0 {
+ t.Fatalf("a home box exited %d:\n%s", code, fx.logs)
+ }
+ if strings.Contains(fx.logs.String(), "NOT RUN") {
+ t.Fatalf("a home box did not run:\n%s", fx.logs)
+ }
+ rec := fx.published(fxSelf)
+ v := rec.Hosts[home]
+ if !v.OK() || v.TXID != fx.plan().TXID {
+ t.Fatalf("home instance: published %+v, want passed at txid %d", v, fx.plan().TXID)
+ }
+ if want := idFor(t, home, "", fxCreated); v.Identity != want {
+ t.Fatalf("home instance: identity %+v, want %+v", v.Identity, want)
+ }
+ if a := rec.Hosts[away]; a.Result != dbverify.ResultUnverified || a.Reason != dbverify.ReasonNoRecord {
+ t.Fatalf("a record in another region on a home box: %+v, want unverified/no_record", a)
+ }
+ fx.scratchEmpty()
+}
+
+// The exact match runs both ways: a region box does not take a home
+// record, and a home record that leaves for a region while it is tested
+// is record_changed at the close.
+func TestDrillHomeRegionMatchesExactly(t *testing.T) {
+ const host = "home.example.com"
+ t.Run("a region box and a home record", func(t *testing.T) {
+ fx := newDrillFx(t, host)
+ fx.putRecord(fxAccount, host, fxCreated, func(r *provision.Record) { r.Region = "" })
+ d := fx.drill() // region uk
+ v := fx.run(context.Background(), d, fx.routes(host), nil)[host]
+ if v.Result != dbverify.ResultUnverified || v.Reason != dbverify.ReasonNoRecord {
+ t.Fatalf("verdict %+v, want unverified/no_record", v)
+ }
+ })
+ t.Run("a home record leaving during the test", func(t *testing.T) {
+ fx := newDrillFx(t, host)
+ fx.putRecord(fxAccount, host, fxCreated, func(r *provision.Record) { r.Region = "" })
+ fx.stubVerify(func(context.Context, string, string, uint64) (uint32, error) {
+ fx.putRecord(fxAccount, host, fxCreated, func(r *provision.Record) { r.Region = "uk" })
+ return 1, nil
+ })
+ d := fx.drill()
+ d.Region = ""
+ v := fx.run(context.Background(), d, fx.routes(host), nil)[host]
+ if v.Result != dbverify.ResultUnverified || v.Reason != ReasonRecordChanged {
+ t.Fatalf("verdict %+v, want unverified/record_changed", v)
+ }
+ })
+}
+
+// A malformed region still refuses: nothing drilled, nothing published.
+func TestRunHibernateVerifyRefusesAMalformedRegion(t *testing.T) {
+ for _, region := range []string{" ", "UK", "eu west", "fleet/", "uk/", "-uk"} {
+ t.Run(region, func(t *testing.T) {
+ fx := newRunFx(t, "a.example.com")
+ fx.writeSelf(fxSelf, false)
+ restored := false
+ fx.stubVerify(func(context.Context, string, string, uint64) (uint32, error) {
+ restored = true
+ return 1, nil
+ })
+ r := fx.runner()
+ r.Region = region
+ if code := r.run(context.Background()); code != 1 {
+ t.Fatalf("CARLOS_REGION %q: exited %d, want 1", region, code)
+ }
+ if restored || !strings.Contains(fx.logs.String(), "is not a region") {
+ t.Fatalf("CARLOS_REGION %q: restored %v, log:\n%s", region, restored, fx.logs)
+ }
+ keys, err := fx.store.List(context.Background(), "control/")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(keys) != 0 {
+ t.Fatalf("CARLOS_REGION %q: published %v", region, keys)
+ }
+ })
+ }
+}
diff --git a/internal/ops/hibernate_verify_restore_test.go b/internal/ops/hibernate_verify_restore_test.go
index 5f3a9d083..f93049d5b 100644
--- a/internal/ops/hibernate_verify_restore_test.go
+++ b/internal/ops/hibernate_verify_restore_test.go
@@ -121,8 +121,8 @@ func (c *missingClient) OpenLTXFile(ctx context.Context, level int, minTXID, max
// A planned object that disappears before its header or contents are read
// goes through the same bounded replan as an unreachable transaction
-// (Astra P2-3), through the real planner (dbdoor.PlanFrom) and the real
-// downloader and restore (lease.VerifyClientAt): a replan that finds the
+// (Astra P2-3), through the real planner (dbdoor.PlanListed) and the real
+// downloader and restore (lease.VerifyReaderAt): a replan that finds the
// history whole passes, and history still missing on the second plan is
// unverified, plan_moved, never a failure.
func TestVerifyHibernatingReplansAMissingObject(t *testing.T) {
@@ -152,9 +152,7 @@ func TestVerifyHibernatingReplansAMissingObject(t *testing.T) {
plans++
return client, nil
})
- swap(t, &verifyAt, func(ctx context.Context, _, prefix, _, dir string, txid uint64) (uint32, error) {
- return lease.VerifyClientAt(ctx, client, prefix, dir, txid)
- })
+ swap(t, &verifyAt, lease.VerifyReaderAt) // the production restore, over the planner's listing
v := fx.run(context.Background(), fx.drill(), fx.routes(host), nil)[host]
if v.Result != c.result || v.Reason != c.reason {
t.Fatalf("verdict %s/%s, want %s/%s (%+v)", v.Result, v.Reason, c.result, c.reason, v)
@@ -235,12 +233,78 @@ func TestVerifyHibernatingRealCorruptionFails(t *testing.T) {
swap(t, &openReplica, func(context.Context, string, string, string) (dbdoor.ReplicaReader, error) {
return client, nil
})
- swap(t, &verifyAt, func(ctx context.Context, _, prefix, _, dir string, txid uint64) (uint32, error) {
- return lease.VerifyClientAt(ctx, client, prefix, dir, txid)
- })
+ swap(t, &verifyAt, lease.VerifyReaderAt) // the production restore, over the planner's listing
v := fx.run(context.Background(), fx.drill(), fx.routes(host), nil)[host]
if v.Result != dbverify.ResultFailed || v.Reason != ReasonRestoreError || !strings.Contains(v.Detail, "integrity_check") {
t.Fatalf("verdict %+v, want failed/restore_error from integrity_check", v)
}
fx.scratchEmpty()
}
+
+// countingReader counts every listing of each level, per prefix, that a
+// drill makes through the reader openReplica hands it. Its dynamic type is
+// a full file replica client, which could write: the drill must not reach
+// that.
+type countingReader struct {
+ *lsfile.ReplicaClient
+ mu *sync.Mutex
+ lists map[string]map[int]int
+ prefix string
+ t *testing.T
+}
+
+func (c *countingReader) LTXFiles(ctx context.Context, level int, seek ltx.TXID, useMetadata bool) (ltx.FileIterator, error) {
+ c.mu.Lock()
+ if c.lists[c.prefix] == nil {
+ c.lists[c.prefix] = map[int]int{}
+ }
+ c.lists[c.prefix][level]++
+ c.mu.Unlock()
+ return c.ReplicaClient.LTXFiles(ctx, level, seek, useMetadata)
+}
+
+func (c *countingReader) WriteLTXFile(context.Context, int, ltx.TXID, ltx.TXID, io.Reader) (*ltx.FileInfo, error) {
+ c.t.Error("the drill wrote an LTX file")
+ return nil, errors.New("trap")
+}
+
+func (c *countingReader) DeleteLTXFiles(context.Context, []*ltx.FileInfo) error {
+ c.t.Error("the drill deleted LTX files")
+ return errors.New("trap")
+}
+
+func (c *countingReader) DeleteAll(context.Context) error {
+ c.t.Error("the drill deleted a replica")
+ return errors.New("trap")
+}
+
+// The production restore (verifyAt as shipped) reads through the planner's
+// own listing (member backups 2a, R2): each level of each host is listed
+// once per run, by the plan, and never again by the restore (10 LISTs a
+// host, not 20), and nothing the drill holds can write the replica.
+func TestVerifyHibernatingListsEachLevelOncePerHost(t *testing.T) {
+ hosts := []string{"a.example.com", "b.example.com"}
+ fx := newDrillFx(t, hosts...)
+ swap(t, &verifyAt, lease.VerifyReaderAt) // the production restore, not the fixture's stub
+ var mu sync.Mutex
+ lists := map[string]map[int]int{}
+ swap(t, &openReplica, func(_ context.Context, _, prefix, _ string) (dbdoor.ReplicaReader, error) {
+ return &countingReader{ReplicaClient: lsfile.NewReplicaClient(fx.replica), mu: &mu, lists: lists, prefix: prefix, t: t}, nil
+ })
+ got := fx.run(context.Background(), fx.drill(), fx.routes(hosts...), nil)
+ for _, h := range hosts {
+ if v := got[h]; !v.OK() {
+ t.Fatalf("%s: verdict %+v, want passed", h, v)
+ }
+ levels := lists[fx.prefix(h)]
+ for level := 0; level <= litestream.SnapshotLevel; level++ {
+ if n := levels[level]; n != 1 {
+ t.Errorf("%s: level %d listed %d times, want once", h, level, n)
+ }
+ }
+ if len(levels) != litestream.SnapshotLevel+1 {
+ t.Errorf("%s: listed levels %v, want 0 to %d", h, levels, litestream.SnapshotLevel)
+ }
+ }
+ fx.scratchEmpty()
+}
diff --git a/internal/ops/hibernate_verify_staging_test.go b/internal/ops/hibernate_verify_staging_test.go
new file mode 100644
index 000000000..c6eaff6bf
--- /dev/null
+++ b/internal/ops/hibernate_verify_staging_test.go
@@ -0,0 +1,338 @@
+package ops
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "io/fs"
+ "os"
+ "path/filepath"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/activator"
+ "github.com/carlosframework/platform/internal/dbdoor"
+ "github.com/carlosframework/platform/internal/dbdoor/dbdoortest"
+ "github.com/carlosframework/platform/internal/dbverify"
+ "github.com/carlosframework/platform/internal/lease"
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+// Member backups 2a, R1: after an offline move lands on a box and before
+// the instance's first wake promotes the staged copy, the replica under
+// instances/<host>/ is not the instance's. On a box the instance stayed on
+// before it is an orphan of that stay, which restores clean. The drill
+// recognises "landed, awaiting promotion" by what the promotion itself
+// trusts (activator promoteStagedReplica): any object under moves/<host>/
+// in this box's data bucket, where staging wins over the own prefix.
+
+// stagingSpy is the fixture's data bucket as the staged-copy check reads
+// it: it records each listing's prefix, refuses an unbounded one, and
+// fails with fx.stagingErr when that is set.
+type stagingSpy struct{ fx *drillFx }
+
+func (s stagingSpy) ListPage(ctx context.Context, prefix, startAfter string, limit int) ([]string, error) {
+ s.fx.mu.Lock()
+ s.fx.stagingList = append(s.fx.stagingList, prefix)
+ err := s.fx.stagingErr
+ s.fx.mu.Unlock()
+ if limit != 1 || startAfter != "" {
+ s.fx.t.Errorf("staging listed %q after %q, limit %d; want one key from the start", prefix, startAfter, limit)
+ }
+ if err != nil {
+ return nil, err
+ }
+ return s.fx.staging.ListPage(ctx, prefix, startAfter, limit)
+}
+
+// stage puts a move's staged copy of host where the stager puts it: every
+// object of a real replica (the shared one), under activator.MovesPrefix,
+// at the same relative keys as the source's instances/<host>/ prefix.
+func (fx *drillFx) stage(host string) {
+ fx.t.Helper()
+ err := filepath.WalkDir(fx.replica, func(p string, de fs.DirEntry, err error) error {
+ if err != nil || de.IsDir() {
+ return err
+ }
+ rel, err := filepath.Rel(fx.replica, p)
+ if err != nil {
+ return err
+ }
+ body, err := os.ReadFile(p)
+ if err != nil {
+ return err
+ }
+ _, err = fx.staging.Put(context.Background(), activator.MovesPrefix(host)+filepath.ToSlash(rel), body, "")
+ return err
+ })
+ if err != nil {
+ fx.t.Fatal(err)
+ }
+ keys, err := fx.staging.List(context.Background(), activator.MovesPrefix(host))
+ if err != nil || len(keys) == 0 {
+ fx.t.Fatalf("fixture: staged %v, %v", keys, err)
+ }
+}
+
+// listedStaging is how many times the staged-copy check listed host's
+// staging prefix.
+func (fx *drillFx) listedStaging(host string) int {
+ fx.mu.Lock()
+ defer fx.mu.Unlock()
+ n := 0
+ for _, p := range fx.stagingList {
+ if p == activator.MovesPrefix(host) {
+ n++
+ }
+ }
+ return n
+}
+
+// countPlans counts the replica openings per prefix, so a test can see
+// that a host was never planned.
+func (fx *drillFx) countPlans() map[string]int {
+ plans := map[string]int{}
+ real := openReplica
+ swap(fx.t, &openReplica, func(ctx context.Context, bucket, prefix, region string) (dbdoor.ReplicaReader, error) {
+ fx.mu.Lock()
+ plans[prefix]++
+ fx.mu.Unlock()
+ return real(ctx, bucket, prefix, region)
+ })
+ return plans
+}
+
+// Landed, not promoted, with an old orphan copy that restores clean under
+// instances/<host>/: unverified, moving, and nothing is planned or
+// restored. The control host (no staging, the same orphan lineage) passes
+// through the production restore, so the moving verdict is the staging's
+// doing, not the replica's.
+func TestDrillLandedCopyAwaitingPromotionIsMoving(t *testing.T) {
+ const landed, control = "landed.example.com", "control.example.com"
+ fx := newDrillFx(t, landed, control)
+ swap(t, &verifyAt, lease.VerifyReaderAt)
+ plans := fx.countPlans()
+ fx.stage(landed)
+
+ got := fx.run(context.Background(), fx.drill(), fx.routes(landed, control), nil)
+
+ v := got[landed]
+ if v.Result != dbverify.ResultUnverified || v.Reason != ReasonMoving || v.Detail != "the instance was moving when the test began" {
+ t.Fatalf("landed host: verdict %+v, want unverified/moving with the bracket-open detail", v)
+ }
+ if v.TXID != 0 || v.RestoredBytes != 0 {
+ t.Fatalf("landed host: verdict carries a restore (%+v)", v)
+ }
+ if n := plans[fx.prefix(landed)]; n != 0 {
+ t.Fatalf("landed host planned %d times, want never", n)
+ }
+ if n := fx.listedStaging(landed); n != 1 {
+ t.Fatalf("landed host's staging listed %d times, want once (at the bracket's open)", n)
+ }
+ if c := got[control]; !c.OK() {
+ t.Fatalf("control host (same orphan lineage, nothing staged): verdict %+v, want passed", c)
+ }
+ fx.scratchEmpty()
+}
+
+// A move's staged copy that arrives while the host is under test (its
+// promotion racing the restore): whatever the restore found, damaged or
+// clean, the verdict is unverified, moving. Never failed, never passed.
+// Either the staging is still there at the close, or the promotion
+// completed (a distinct new replica mirrored over the one under test, its
+// staging dropped before the close) and the move's close is in the
+// record's LastMove; the legacy move, which writes no LastMove, is
+// TestDrillLegacyRoundTripInsideTheTestIsNeverAResult's.
+func TestDrillStagedCopyArrivingDuringTheTestIsMoving(t *testing.T) {
+ const host = "a.example.com"
+ mixed := fmt.Errorf("%w: integrity_check: page 4 corrupt", lease.ErrCheckFailed)
+ newReplica := t.TempDir()
+ dbdoortest.Replicate(t, newReplica, 5)
+ for name, c := range map[string]struct {
+ duringPlan bool // the copy lands while the plan lists, not while the restore reads
+ promoted bool // the promotion completes and drops the staging before the close
+ restoreErr error // what the restore reports, over its own result
+ }{
+ "mixed lineage reads as damage": {restoreErr: mixed},
+ "old lineage restores clean": {},
+ "lands while planning": {duringPlan: true},
+ "lands while planning, damage": {duringPlan: true, restoreErr: mixed},
+ "promoted, old copy restored": {promoted: true},
+ "promoted, mixed read": {promoted: true, restoreErr: mixed},
+ } {
+ t.Run(name, func(t *testing.T) {
+ fx := newDrillFx(t, host)
+ hostDir := filepath.Join(t.TempDir(), "replica")
+ copyTree(t, fx.replica, hostDir)
+ fx.replicaFor[fx.prefix(host)] = hostDir
+ land := func() {
+ if !c.promoted {
+ fx.stage(host)
+ return
+ }
+ fx.stageFrom(host, newReplica)
+ copyTree(t, newReplica, hostDir) // the first wake's promotion: an exact mirror
+ fx.dropStaging(host)
+ fx.putRecord(fxAccount, host, fxCreated, func(r *provision.Record) {
+ r.LastMove = &provision.MoveOutcome{ID: "mv_in", Outcome: "done", At: time.Date(2026, 11, 12, 3, 0, 30, 0, time.UTC)}
+ })
+ }
+ if c.duringPlan {
+ fx.onList[fx.prefix(host)] = land
+ }
+ swap(t, &verifyAt, func(ctx context.Context, rd lease.ReplicaReader, prefix, dir string, txid uint64) (uint32, error) {
+ counter, err := lease.VerifyReaderAt(ctx, rd, prefix, dir, txid) // the real restore of what was planned
+ if !c.duringPlan {
+ land()
+ }
+ if c.restoreErr != nil {
+ return 0, c.restoreErr
+ }
+ return counter, err
+ })
+ v := fx.run(context.Background(), fx.drill(), fx.routes(host), nil)[host]
+ if v.Result != dbverify.ResultUnverified || v.Reason != ReasonMoving {
+ t.Fatalf("verdict %+v, want unverified/moving", v)
+ }
+ // With staging left, the close's record check passes and its
+ // staging check decides; with the promotion done, the record
+ // check decides first.
+ want := 2
+ if c.promoted {
+ want = 1
+ }
+ if n := fx.listedStaging(host); n != want {
+ t.Fatalf("staging listed %d times, want %d", n, want)
+ }
+ fx.scratchEmpty()
+ })
+ }
+}
+
+// Promoted (the first wake mirrored the staged copy over instances/<host>/
+// and dropped the staging): the drill is what it was, through the
+// production restore, and the staging check costs one bounded listing at
+// each end of the bracket.
+func TestDrillPromotedCopyIsUnchanged(t *testing.T) {
+ const host = "a.example.com"
+ fx := newDrillFx(t, host)
+ swap(t, &verifyAt, lease.VerifyReaderAt)
+ v := fx.run(context.Background(), fx.drill(), fx.routes(host), nil)[host]
+ if !v.OK() || v.TXID != fx.plan().TXID {
+ t.Fatalf("verdict %+v, want passed at txid %d", v, fx.plan().TXID)
+ }
+ if n := fx.listedStaging(host); n != 2 {
+ t.Fatalf("staging listed %d times, want twice (open and close)", n)
+ }
+ fx.scratchEmpty()
+}
+
+// The staging prefix ends in a slash, so one host's staged copy is not
+// another's whose name it begins (app.example.co is not
+// app.example.com).
+func TestDrillStagingIsPerHost(t *testing.T) {
+ const staged, other = "a.example.com", "a.example.co"
+ fx := newDrillFx(t, staged, other)
+ fx.stage(staged)
+ got := fx.run(context.Background(), fx.drill(), fx.routes(staged, other), nil)
+ if v := got[staged]; v.Reason != ReasonMoving {
+ t.Fatalf("%s: verdict %+v, want moving", staged, v)
+ }
+ if v := got[other]; !v.OK() {
+ t.Fatalf("%s: verdict %+v, want passed (another host's staging)", other, v)
+ }
+}
+
+// When the staging cannot be read, whether the instance is awaiting
+// promotion is unknown: unverified, storage_unavailable, never a pass and
+// never a failure, at either end of the bracket, and with no restore when
+// it is the open that cannot tell.
+func TestDrillStagingUnreadableIsNeverAPass(t *testing.T) {
+ const host = "a.example.com"
+ denied := errors.New("AccessDenied: list moves/")
+
+ t.Run("at the open", func(t *testing.T) {
+ fx := newDrillFx(t, host)
+ fx.stagingErr = denied
+ v := fx.run(context.Background(), fx.drill(), fx.routes(host), nil)[host]
+ if v.Result != dbverify.ResultUnverified || v.Reason != ReasonStorageUnavailable || v.Detail == "" {
+ t.Fatalf("verdict %+v, want unverified/storage_unavailable with the error", v)
+ }
+ if len(fx.verifies) != 0 {
+ t.Fatal("restored a host whose staging could not be read")
+ }
+ })
+ for name, restoreErr := range map[string]error{
+ "at the close, clean restore": nil,
+ "at the close, damaged restore": fmt.Errorf("%w: integrity_check: page 4 corrupt", lease.ErrCheckFailed),
+ } {
+ t.Run(name, func(t *testing.T) {
+ fx := newDrillFx(t, host)
+ fx.stubVerify(func(context.Context, string, string, uint64) (uint32, error) {
+ fx.mu.Lock()
+ fx.stagingErr = denied
+ fx.mu.Unlock()
+ return 1, restoreErr
+ })
+ v := fx.run(context.Background(), fx.drill(), fx.routes(host), nil)[host]
+ if v.Result != dbverify.ResultUnverified || v.Reason != ReasonStorageUnavailable {
+ t.Fatalf("verdict %+v, want unverified/storage_unavailable", v)
+ }
+ fx.scratchEmpty()
+ })
+ }
+ t.Run("the bucket cannot be opened", func(t *testing.T) {
+ fx := newDrillFx(t, host, "b.example.com")
+ swap(t, &openStaging, func(context.Context, string, string) (release.PageLister, error) {
+ return nil, errors.New("load aws config: no region")
+ })
+ got := fx.run(context.Background(), fx.drill(), fx.routes(host, "b.example.com"), nil)
+ for h, v := range got {
+ if v.Result != dbverify.ResultUnverified || v.Reason != ReasonStorageUnavailable {
+ t.Fatalf("%s: verdict %+v, want unverified/storage_unavailable", h, v)
+ }
+ }
+ if len(got) != 2 || len(fx.verifies) != 0 {
+ t.Fatalf("verdicts %d, restores %d; want 2 and none", len(got), len(fx.verifies))
+ }
+ })
+}
+
+// R1b: the bracket carries the record's latest closed move (LastMove). A
+// LastMove already there when the test began is history and changes
+// nothing; one replaced by another move's outcome during the test means a
+// whole move ran inside it, which is moving.
+func TestDrillBracketSeesACompletedMove(t *testing.T) {
+ const host = "a.example.com"
+ earlier := &provision.MoveOutcome{ID: "mv_old", Outcome: "done", At: time.Date(2026, 10, 1, 0, 0, 0, 0, time.UTC)}
+ for name, c := range map[string]struct {
+ during *provision.MoveOutcome // LastMove written while the restore runs; nil leaves it
+ result string
+ reason string
+ }{
+ "history at rest": {nil, dbverify.ResultPassed, ""},
+ "another move closed": {&provision.MoveOutcome{ID: "mv_new", Outcome: "done", At: time.Date(2026, 11, 12, 3, 0, 30, 0, time.UTC)},
+ dbverify.ResultUnverified, ReasonMoving},
+ "a move rolled back": {&provision.MoveOutcome{ID: "mv_new", Outcome: "rolled_back", At: time.Date(2026, 11, 12, 3, 0, 30, 0, time.UTC)},
+ dbverify.ResultUnverified, ReasonMoving},
+ } {
+ t.Run(name, func(t *testing.T) {
+ fx := newDrillFx(t)
+ fx.putRecord(fxAccount, host, fxCreated, func(r *provision.Record) { r.LastMove = earlier })
+ fx.stubVerify(func(context.Context, string, string, uint64) (uint32, error) {
+ if c.during != nil {
+ fx.putRecord(fxAccount, host, fxCreated, func(r *provision.Record) { r.LastMove = c.during })
+ }
+ return 1, nil
+ })
+ v := fx.run(context.Background(), fx.drill(), fx.routes(host), nil)[host]
+ if v.Result != c.result || v.Reason != c.reason {
+ t.Fatalf("verdict %s/%s, want %s/%s (%+v)", v.Result, v.Reason, c.result, c.reason, v)
+ }
+ if want := idFor(t, host, fxRegion, fxCreated); v.Identity != want {
+ t.Fatalf("published identity %+v, want %+v: the move stamp is the bracket's, not the verdict's", v.Identity, want)
+ }
+ })
+ }
+}
diff --git a/internal/ops/hibernate_verify_stamp_test.go b/internal/ops/hibernate_verify_stamp_test.go
new file mode 100644
index 000000000..6c1aaffba
--- /dev/null
+++ b/internal/ops/hibernate_verify_stamp_test.go
@@ -0,0 +1,289 @@
+package ops
+
+import (
+ "context"
+ "fmt"
+ "io/fs"
+ "os"
+ "path/filepath"
+ "strconv"
+ "sync"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/activator"
+ "github.com/carlosframework/platform/internal/dbdoor"
+ "github.com/carlosframework/platform/internal/dbdoor/dbdoortest"
+ "github.com/carlosframework/platform/internal/dbverify"
+ "github.com/carlosframework/platform/internal/lease"
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+// Astra's review of R1b: a legacy move (MovesEnabled false) completes
+// through MoveComplete, which clears Move and flips Region without writing
+// LastMove. A round trip there and back inside one host's test, with the
+// first wake's promotion done and its staging dropped before the close,
+// leaves the record's bytes as they were, so its identity, its LastMove,
+// its ETag (a content hash) and both staging checks all match. The bracket
+// therefore also compares the record's stamp: on the versioned deployment
+// bucket every write has a new version id, whatever its bytes.
+
+// versionedStore is a DirStore with S3's versioning: every Put and Delete
+// of a key is a new version, and GetStamped reports the current one with
+// the ETag (DirStore's, a content hash like SSE-S3's MD5).
+type versionedStore struct {
+ *release.DirStore
+ mu sync.Mutex
+ versions map[string]int
+}
+
+func newVersionedStore(dir string) *versionedStore {
+ return &versionedStore{DirStore: release.NewDirStore(dir), versions: map[string]int{}}
+}
+
+func (v *versionedStore) bump(key string) {
+ v.mu.Lock()
+ v.versions[key]++
+ v.mu.Unlock()
+}
+
+func (v *versionedStore) Put(ctx context.Context, key string, body []byte, ifMatch string) (string, error) {
+ etag, err := v.DirStore.Put(ctx, key, body, ifMatch)
+ if err == nil {
+ v.bump(key)
+ }
+ return etag, err
+}
+
+func (v *versionedStore) Delete(ctx context.Context, key string) error {
+ err := v.DirStore.Delete(ctx, key)
+ if err == nil {
+ v.bump(key)
+ }
+ return err
+}
+
+func (v *versionedStore) GetStamped(ctx context.Context, key string) ([]byte, release.ObjectStamp, error) {
+ body, etag, err := v.DirStore.Get(ctx, key)
+ if err != nil {
+ return nil, release.ObjectStamp{}, err
+ }
+ v.mu.Lock()
+ n := v.versions[key]
+ v.mu.Unlock()
+ return body, release.ObjectStamp{ETag: etag, VersionID: "v" + strconv.Itoa(n)}, nil
+}
+
+var _ release.StampedGetter = (*versionedStore)(nil)
+
+// legacyMove drives host's record to region `to` through the transitions a
+// legacy move makes, as the box's move pass applies them (SetRecordMove):
+// request, ready, cutting, and MoveComplete, which flips Region and clears
+// Move and writes no LastMove.
+func (fx *drillFx) legacyMove(host, to string) {
+ fx.t.Helper()
+ ctx := context.Background()
+ for _, mut := range []func(*provision.Record) error{
+ provision.MoveRequest(to, fx.clock.Now()),
+ provision.MovePromoteReady(fx.clock.Now()),
+ provision.MoveMarkCutting(),
+ provision.MoveComplete(),
+ } {
+ if _, err := provision.SetRecordMove(ctx, fx.store, fxAccount, fxApp, host, mut); err != nil {
+ fx.t.Fatalf("legacy move of %s to %s: %v", host, to, err)
+ }
+ }
+ if rec := fx.record(host); rec.Region != to || rec.Move != nil || rec.LastMove != nil {
+ fx.t.Fatalf("fixture: after the legacy move the record is in %q, move %+v, last move %+v", rec.Region, rec.Move, rec.LastMove)
+ }
+}
+
+// copyTree replaces dst's contents with src's: a file replica mirrored
+// exactly, as the promotion's MirrorPrefix does (own keys the source lacks
+// are deleted).
+func copyTree(t *testing.T, src, dst string) {
+ t.Helper()
+ if err := os.RemoveAll(dst); err != nil {
+ t.Fatal(err)
+ }
+ err := filepath.WalkDir(src, func(p string, de fs.DirEntry, err error) error {
+ if err != nil {
+ return err
+ }
+ rel, err := filepath.Rel(src, p)
+ if err != nil {
+ return err
+ }
+ out := filepath.Join(dst, rel)
+ if de.IsDir() {
+ return os.MkdirAll(out, 0o755)
+ }
+ b, err := os.ReadFile(p)
+ if err != nil {
+ return err
+ }
+ return os.WriteFile(out, b, 0o644)
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+}
+
+// stageFrom puts a move's staged copy of host under moves/<host>/: every
+// object of the replica in dir, at its relative key.
+func (fx *drillFx) stageFrom(host, dir string) {
+ fx.t.Helper()
+ err := filepath.WalkDir(dir, func(p string, de fs.DirEntry, err error) error {
+ if err != nil || de.IsDir() {
+ return err
+ }
+ rel, err := filepath.Rel(dir, p)
+ if err != nil {
+ return err
+ }
+ b, err := os.ReadFile(p)
+ if err != nil {
+ return err
+ }
+ _, err = fx.staging.Put(context.Background(), activator.MovesPrefix(host)+filepath.ToSlash(rel), b, "")
+ return err
+ })
+ if err != nil {
+ fx.t.Fatal(err)
+ }
+}
+
+// dropStaging deletes every staged key of host, as the first wake's
+// dropStagedReplica does once its restore succeeds.
+func (fx *drillFx) dropStaging(host string) {
+ fx.t.Helper()
+ keys, err := fx.staging.List(context.Background(), activator.MovesPrefix(host))
+ if err != nil || len(keys) == 0 {
+ fx.t.Fatalf("fixture: nothing staged to drop (%v)", err)
+ }
+ for _, k := range keys {
+ if err := fx.staging.Delete(context.Background(), k); err != nil {
+ fx.t.Fatal(err)
+ }
+ }
+}
+
+// A legacy round trip (uk -> us -> uk) with the returning move's staged
+// copy promoted over the replica under test and its staging dropped, all
+// inside the host's test. The old and new replicas are distinct lineages.
+// Whether the restore read the old copy before the round trip (a stale
+// pass), the promoted new copy after it, or reported damage from a mixed
+// read, the verdict is unverified, record_changed: never passed, never
+// failed. The fixture proves the record's bytes, ETag and LastMove come
+// back unchanged and staging is gone at the close, so only the stamp can
+// see it.
+func TestDrillLegacyRoundTripInsideTheTestIsNeverAResult(t *testing.T) {
+ const host = "a.example.com"
+ newReplica := t.TempDir()
+ dbdoortest.Replicate(t, newReplica, 5)
+ for name, c := range map[string]struct {
+ restoreFirst bool // the restore reads before the round trip, else after the promotion
+ damage error // what the restore reports instead of its own result, when set
+ }{
+ "old copy restored, then the round trip": {restoreFirst: true},
+ "round trip, then the promoted copy": {},
+ "round trip, then a mixed read": {damage: fmt.Errorf("%w: integrity_check: page 4 corrupt", lease.ErrCheckFailed)},
+ } {
+ t.Run(name, func(t *testing.T) {
+ fx := newDrillFx(t, host)
+ hostDir := filepath.Join(t.TempDir(), "replica")
+ copyTree(t, fx.replica, hostDir)
+ fx.replicaFor[fx.prefix(host)] = hostDir
+ _, etagBefore, err := fx.store.Get(context.Background(), provision.RecordKey(fxAccount, fxApp, host))
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ roundTrip := func() {
+ fx.legacyMove(host, "us")
+ fx.legacyMove(host, fxRegion)
+ fx.stageFrom(host, newReplica)
+ copyTree(t, newReplica, hostDir) // the first wake's promotion: an exact mirror
+ fx.dropStaging(host)
+ _, etagAfter, err := fx.store.Get(context.Background(), provision.RecordKey(fxAccount, fxApp, host))
+ if err != nil || etagAfter != etagBefore {
+ t.Fatalf("fixture: the round trip changed the record's bytes (etag %q -> %q, %v); it must not, to be the case under test", etagBefore, etagAfter, err)
+ }
+ }
+ swap(t, &verifyAt, func(ctx context.Context, rd lease.ReplicaReader, prefix, dir string, txid uint64) (uint32, error) {
+ var counter uint32
+ var err error
+ if c.restoreFirst {
+ counter, err = lease.VerifyReaderAt(ctx, rd, prefix, dir, txid)
+ roundTrip()
+ } else {
+ roundTrip()
+ counter, err = lease.VerifyReaderAt(ctx, rd, prefix, dir, txid)
+ }
+ if c.damage != nil {
+ return 0, c.damage
+ }
+ return counter, err
+ })
+ plans := 0
+ real := openReplica
+ swap(t, &openReplica, func(ctx context.Context, bucket, prefix, region string) (dbdoor.ReplicaReader, error) {
+ plans++
+ return real(ctx, bucket, prefix, region)
+ })
+
+ v := fx.run(context.Background(), fx.drill(), fx.routes(host), nil)[host]
+ if v.Result != dbverify.ResultUnverified || v.Reason != ReasonRecordChanged {
+ t.Fatalf("verdict %s/%s, want unverified/record_changed (%+v)", v.Result, v.Reason, v)
+ }
+ if v.TXID != 0 || v.RestoredBytes != 0 {
+ t.Fatalf("a discarded restore left its findings in the verdict: %+v", v)
+ }
+ // Staging was empty at the open (listed once) and dropped before
+ // the close, whose record check decided first: no staging check
+ // could have seen this.
+ if n := fx.listedStaging(host); n != 1 {
+ t.Fatalf("staging listed %d times, want once, at the open", n)
+ }
+ if keys, err := fx.staging.List(context.Background(), activator.MovesPrefix(host)); err != nil || len(keys) != 0 {
+ t.Fatalf("staging at the close: %v, %v; want none", keys, err)
+ }
+ fx.scratchEmpty()
+ })
+ }
+}
+
+// Any write of the record during the test is a change, even one that
+// leaves its bytes as they were: unverified, record_changed. A record
+// nobody wrote passes, as before.
+func TestDrillAnyRecordWriteDuringTheTestIsAChange(t *testing.T) {
+ const host = "a.example.com"
+ for name, c := range map[string]struct {
+ write bool
+ result string
+ reason string
+ }{
+ "untouched": {false, dbverify.ResultPassed, ""},
+ "rewritten, same bytes": {true, dbverify.ResultUnverified, ReasonRecordChanged},
+ } {
+ t.Run(name, func(t *testing.T) {
+ fx := newDrillFx(t, host)
+ fx.stubVerify(func(context.Context, string, string, uint64) (uint32, error) {
+ if c.write {
+ raw, etag, err := fx.store.Get(context.Background(), provision.RecordKey(fxAccount, fxApp, host))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := fx.store.Put(context.Background(), provision.RecordKey(fxAccount, fxApp, host), raw, etag); err != nil {
+ t.Fatal(err)
+ }
+ }
+ return 1, nil
+ })
+ v := fx.run(context.Background(), fx.drill(), fx.routes(host), nil)[host]
+ if v.Result != c.result || v.Reason != c.reason {
+ t.Fatalf("verdict %s/%s, want %s/%s (%+v)", v.Result, v.Reason, c.result, c.reason, v)
+ }
+ })
+ }
+}
diff --git a/internal/ops/hibernate_verify_test.go b/internal/ops/hibernate_verify_test.go
index a93f85e60..2f2f7fa8e 100644
--- a/internal/ops/hibernate_verify_test.go
+++ b/internal/ops/hibernate_verify_test.go
@@ -185,11 +185,17 @@ type drillFx struct {
cfg *activator.Config
tmp string
- mu sync.Mutex
- replicaFor map[string]string // prefix -> replica dir
- onList map[string]func() // prefix -> hook run when planning lists it
- verifies []uint64 // the txids verifyAt was asked for
- localReads atomic.Int32
+ // staging is this box's data bucket as the staged-copy check reads
+ // it: a move's staged copy lands under moves/<host>/ here.
+ staging *release.DirStore
+
+ mu sync.Mutex
+ stagingErr error // when set, every staged-copy listing fails with it
+ stagingList []string // the prefixes the staged-copy check listed, in order
+ replicaFor map[string]string // prefix -> replica dir
+ onList map[string]func() // prefix -> hook run when planning lists it
+ verifies []uint64 // the txids verifyAt was asked for
+ localReads atomic.Int32
}
var (
@@ -229,7 +235,7 @@ func newDrillFx(t *testing.T, hosts ...string) *drillFx {
t.Helper()
fx := &drillFx{
t: t,
- store: release.NewDirStore(t.TempDir()),
+ store: newVersionedStore(t.TempDir()), // versioned, as the deployment bucket is
replica: sharedReplica(t),
empty: t.TempDir(),
clock: &fakeClock{t: at("2026-11-12T03:00:00Z")},
@@ -237,6 +243,7 @@ func newDrillFx(t *testing.T, hosts ...string) *drillFx {
tmp: t.TempDir(),
replicaFor: map[string]string{},
onList: map[string]func(){},
+ staging: release.NewDirStore(t.TempDir()),
}
for _, h := range hosts {
fx.putRecord(fxAccount, h, time.Date(2026, 9, 1, 0, 0, 0, 0, time.UTC), nil)
@@ -254,12 +261,18 @@ func newDrillFx(t *testing.T, hosts ...string) *drillFx {
}
return &hookReader{ReplicaReader: lsfile.NewReplicaClient(dir), hook: hook}, nil
})
- swap(t, &verifyAt, func(context.Context, string, string, string, string, uint64) (uint32, error) {
+ swap(t, &verifyAt, func(context.Context, lease.ReplicaReader, string, string, uint64) (uint32, error) {
return 1, nil
})
swap(t, &lockState, func(context.Context, string, string, string) (bool, string, time.Time, error) {
return false, "", time.Time{}, nil
})
+ swap(t, &openStaging, func(_ context.Context, bucket, region string) (release.PageLister, error) {
+ if bucket != fx.cfg.Bucket || region != fx.cfg.Region {
+ t.Errorf("staging opened in %s/%s, want %s/%s", bucket, region, fx.cfg.Bucket, fx.cfg.Region)
+ }
+ return stagingSpy{fx: fx}, nil
+ })
real := localFreshness
swap(t, &localFreshness, func(dbPath string, counter uint32) (freshness, string) {
fx.localReads.Add(1)
@@ -270,9 +283,9 @@ func newDrillFx(t *testing.T, hosts ...string) *drillFx {
// stubVerify replaces the restore; it records the txid it was asked for.
func (fx *drillFx) stubVerify(fn func(ctx context.Context, prefix, dir string, txid uint64) (uint32, error)) {
- swap(fx.t, &verifyAt, func(ctx context.Context, bucket, prefix, region, dir string, txid uint64) (uint32, error) {
- if bucket != fx.cfg.Bucket || region != fx.cfg.Region {
- fx.t.Errorf("restore from %s/%s, want %s/%s", bucket, region, fx.cfg.Bucket, fx.cfg.Region)
+ swap(fx.t, &verifyAt, func(ctx context.Context, rd lease.ReplicaReader, prefix, dir string, txid uint64) (uint32, error) {
+ if rd == nil {
+ fx.t.Error("restore with no reader: it must read the planner's listing")
}
fx.mu.Lock()
fx.verifies = append(fx.verifies, txid)
@@ -616,6 +629,13 @@ func TestVerifyHibernatingBracket(t *testing.T) {
r.Move = &provision.MoveState{ID: "mv_x", To: "ie", State: "requested"}
})
}, ReasonMoving},
+ // A whole move began and closed inside the test (R1b): Move was
+ // never seen, but the close left its outcome in LastMove.
+ "a move completed": {func(fx *drillFx) {
+ fx.putRecord(fxAccount, host, time.Date(2026, 9, 1, 0, 0, 0, 0, time.UTC), func(r *provision.Record) {
+ r.LastMove = &provision.MoveOutcome{ID: "mv_x", Outcome: "done", At: time.Date(2026, 11, 12, 3, 0, 30, 0, time.UTC)}
+ })
+ }, ReasonMoving},
}
outcomes := map[string]struct {
empty bool
diff --git a/internal/ops/ops.go b/internal/ops/ops.go
index 324c57d59..843976418 100644
--- a/internal/ops/ops.go
+++ b/internal/ops/ops.go
@@ -407,7 +407,7 @@ type hibernateRun struct {
Root bool
Cfg *activator.Config
OpenStore func(context.Context) (release.Store, error)
- Region string // CARLOS_REGION: the region an instance's record must name
+ Region string // CARLOS_REGION: the region an instance's record must name; "" on a home-region box
DataDir string
RegPath string
TmpDir string
@@ -474,8 +474,11 @@ func (r hibernateRun) run(ctx context.Context) int {
return 1
}
// A fleet box's region is its placement (fleet/<name>), which its
- // records name too.
- if _, fleet := registry.FleetPlacement(r.Region); !dbreads.ValidRegion(r.Region) && !fleet {
+ // records name too. A home-region box has no CARLOS_REGION, and its
+ // instances' records carry region "": an empty region is the home
+ // region, which the bracket matches exactly (R3). Anything else that
+ // is not a region still refuses.
+ if _, fleet := registry.FleetPlacement(r.Region); r.Region != "" && !dbreads.ValidRegion(r.Region) && !fleet {
r.Logf("hibernate-verify: NOT RUN: CARLOS_REGION %q is not a region, so no verdict could be bound to an instance", r.Region)
return 1
}
diff --git a/internal/provision/plan9_b8_census_test.go b/internal/provision/plan9_b8_census_test.go
index 5070f0d32..da2d560c0 100644
--- a/internal/provision/plan9_b8_census_test.go
+++ b/internal/provision/plan9_b8_census_test.go
@@ -1021,7 +1021,12 @@ var plan9B8CensusInventory = []censusEntry{
{"internal/provision/sidecar.go", "claimRawPutSidecarManifest", "nonrecord", "key:SidecarManifestKey,sel:Put", "66401ceb2d42a4fe11bc99441adc129db9698ebe767a6349dc11ac9c0e1ccc3d"},
{"internal/provision/sidecar.go", "claimRawPutSidecarManifestIfMatch", "nonrecord", "key:SidecarManifestKey,sel:Put", "89038c29241c04ab629e0fe90af058bc38a5cce3e3a73d1466293c69c620b9e8"},
{"internal/provision/sidecar.go", "CreateSidecarRecord", "record-writer", "key:CreateSidecarRecord,key:SidecarRecordKey,key:WriteRecord", "93de6854447d263138da0b47c325dd608a2bce699f00c5de1367c323528158c8"},
- {"internal/provision/sidecar.go", "GetSidecarRecord", "key-site", "key:SidecarRecordKey", "0acb1da9d9e825e8ae17c50535ca62f606ece6e4bcffd410ec57319125947481"},
+ // Re-digested for member-backups-2a-landing (R1c, #898): the body's decode and path check moved, unchanged, into decodeSidecarAt, which GetSidecarRecordStamped shares. Same single Get of SidecarRecordKey; no write.
+ {"internal/provision/sidecar.go", "GetSidecarRecord", "key-site", "key:SidecarRecordKey", "8ebba63b266ab1a3c27f9f2b3cdefa94abe937962e02ee5d97fac9a2fae62645"},
+ // Added for member-backups-2a-landing (R1c, #898): GetRecord's read with the object's stamp, one GET of RecordKey through release.GetStamped, the same decode, path check and retired refusal; no write. The restore drill's bracket reads records through it.
+ {"internal/provision/record_stamped.go", "GetRecordStamped", "key-site", "key:RecordKey", "60144e9a0b8d2ef73bb524969aba0b8a30c9eda0f4dee82cbf49bdb30958b189"},
+ // Added for member-backups-2a-landing (R1c, #898): GetSidecarRecord's read with the object's stamp, one GET of SidecarRecordKey through release.GetStamped, decodeSidecarAt's checks; no write.
+ {"internal/provision/record_stamped.go", "GetSidecarRecordStamped", "key-site", "key:SidecarRecordKey", "80ac9047061ffb727b91b4eb9b8706a3f5c5acc90a0afbe19d00b6042e25fe21"},
{"internal/provision/sidecar.go", "ListSidecarRecords", "key-site", "key:SidecarsPrefix", "1e9fcdf53f04a9fd9ffb35574f7f63e778307d0deda8f34150b36047443fddf0"},
{"internal/provision/sidecar.go", "DeleteSidecarRecord", "key-site", "key:SidecarRecordKey", "b4dc694473fdf9e9787e15a11bf701a24e6bc32f0bf83245ad949ec7408b81e6"},
{"internal/provision/sidecar_reconcile.go", "ReconcileSidecars", "key-site", "key:ParseSidecarKey,key:SidecarRecordKey,lit:sidecars", "f9afc65bd1fb5dcba13fc6fa386b6decadcba2c509c9020acb36bab7fc1b6da2"},
diff --git a/internal/provision/record_stamped.go b/internal/provision/record_stamped.go
new file mode 100644
index 000000000..6450c9760
--- /dev/null
+++ b/internal/provision/record_stamped.go
@@ -0,0 +1,45 @@
+package provision
+
+import (
+ "context"
+ "fmt"
+ "os"
+
+ "github.com/carlosframework/platform/internal/release"
+)
+
+// GetRecordStamped is GetRecord with the record's stamp from the same read
+// (release.GetStamped: the ETag, and on a versioned bucket the version id
+// and last-modified time). A reader that brackets its work between two
+// reads of a record compares the stamps: a write between them shows even
+// when it left the bytes as they were, such as a legacy move there and
+// back (member backups 2a, the restore drill's bracket). It refuses what
+// GetRecord refuses: a body disagreeing with its path, a retired record.
+func GetRecordStamped(ctx context.Context, s release.Store, acct, app, host string) (*Record, release.ObjectStamp, error) {
+ raw, st, err := release.GetStamped(ctx, s, RecordKey(acct, app, host))
+ if err != nil {
+ return nil, release.ObjectStamp{}, err
+ }
+ rec, err := decodeRecordAt(raw, acct, app, host)
+ if err != nil {
+ return nil, release.ObjectStamp{}, err
+ }
+ if rec.Retired {
+ return nil, release.ObjectStamp{}, fmt.Errorf("provision: record %s/%s/%s: retired: %w", acct, app, host, os.ErrNotExist)
+ }
+ return rec, st, nil
+}
+
+// GetSidecarRecordStamped is GetSidecarRecord with the record's stamp from
+// the same read, as GetRecordStamped.
+func GetSidecarRecordStamped(ctx context.Context, s release.Store, acct, app, name string) (*SidecarRecord, release.ObjectStamp, error) {
+ raw, st, err := release.GetStamped(ctx, s, SidecarRecordKey(acct, app, name))
+ if err != nil {
+ return nil, release.ObjectStamp{}, err
+ }
+ rec, err := decodeSidecarAt(raw, acct, app, name)
+ if err != nil {
+ return nil, release.ObjectStamp{}, err
+ }
+ return rec, st, nil
+}
diff --git a/internal/provision/record_stamped_test.go b/internal/provision/record_stamped_test.go
new file mode 100644
index 000000000..8f7d7312b
--- /dev/null
+++ b/internal/provision/record_stamped_test.go
@@ -0,0 +1,64 @@
+package provision
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "os"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/release"
+)
+
+// The stamped reads return what GetRecord and GetSidecarRecord return,
+// with the record's stamp from the same read (release.GetStamped), and
+// refuse what they refuse.
+func TestRecordStampedReads(t *testing.T) {
+ ctx := context.Background()
+ s := release.NewDirStore(t.TempDir())
+ created := time.Date(2026, 9, 1, 0, 0, 0, 0, time.UTC)
+ put := func(key string, v any) string {
+ t.Helper()
+ body, err := json.Marshal(v)
+ if err != nil {
+ t.Fatal(err)
+ }
+ etag, err := s.Put(ctx, key, body, "")
+ if err != nil {
+ t.Fatal(err)
+ }
+ return etag
+ }
+
+ etag := put(RecordKey("bab", "shop", "a.example.com"), Record{Account: "bab", App: "shop", Host: "a.example.com", Region: "uk", CreatedAt: created})
+ rec, st, err := GetRecordStamped(ctx, s, "bab", "shop", "a.example.com")
+ want, _ := GetRecord(ctx, s, "bab", "shop", "a.example.com")
+ if err != nil || rec == nil || rec.Host != want.Host || rec.Region != want.Region || st.ETag != etag {
+ t.Fatalf("GetRecordStamped = %+v, %+v, %v; want GetRecord's record with ETag %q", rec, st, err, etag)
+ }
+ put(RecordKey("bab", "shop", "liar.example.com"), Record{Account: "bab", App: "shop", Host: "other.example.com"})
+ if _, _, err := GetRecordStamped(ctx, s, "bab", "shop", "liar.example.com"); !errors.Is(err, ErrRecordCorrupt) {
+ t.Fatalf("a record disagreeing with its path = %v, want ErrRecordCorrupt", err)
+ }
+ put(RecordKey("bab", "shop", "gone.example.com"), Record{Account: "bab", App: "shop", Host: "gone.example.com", Retired: true})
+ if _, _, err := GetRecordStamped(ctx, s, "bab", "shop", "gone.example.com"); !errors.Is(err, os.ErrNotExist) {
+ t.Fatalf("a retired record = %v, want os.ErrNotExist", err)
+ }
+ if _, _, err := GetRecordStamped(ctx, s, "bab", "shop", "none.example.com"); !errors.Is(err, os.ErrNotExist) {
+ t.Fatalf("no record = %v, want os.ErrNotExist", err)
+ }
+
+ setag := put(SidecarRecordKey("bab", "shop", "worker"), SidecarRecord{Account: "bab", App: "shop", Name: "worker", Host: "worker.example", Region: "uk"})
+ sc, sst, err := GetSidecarRecordStamped(ctx, s, "bab", "shop", "worker")
+ if err != nil || sc == nil || sc.Host != "worker.example" || sst.ETag != setag {
+ t.Fatalf("GetSidecarRecordStamped = %+v, %+v, %v; want the record with ETag %q", sc, sst, err, setag)
+ }
+ put(SidecarRecordKey("bab", "shop", "liar"), SidecarRecord{Account: "bab", App: "shop", Name: "other"})
+ if _, _, err := GetSidecarRecordStamped(ctx, s, "bab", "shop", "liar"); err == nil {
+ t.Fatal("a sidecar record disagreeing with its path was accepted")
+ }
+ if _, _, err := GetSidecarRecordStamped(ctx, s, "bab", "shop", "none"); !errors.Is(err, os.ErrNotExist) {
+ t.Fatalf("no sidecar record = %v, want os.ErrNotExist", err)
+ }
+}
diff --git a/internal/provision/sidecar.go b/internal/provision/sidecar.go
index adb794683..5d12d53bb 100644
--- a/internal/provision/sidecar.go
+++ b/internal/provision/sidecar.go
@@ -346,6 +346,12 @@ func GetSidecarRecord(ctx context.Context, s release.Store, acct, app, name stri
if err != nil {
return nil, err
}
+ return decodeSidecarAt(raw, acct, app, name)
+}
+
+// decodeSidecarAt decodes a sidecar record read from acct/app/name's key,
+// refusing one whose body names another path.
+func decodeSidecarAt(raw []byte, acct, app, name string) (*SidecarRecord, error) {
var rec SidecarRecord
if err := json.Unmarshal(raw, &rec); err != nil {
return nil, fmt.Errorf("provision: sidecar record %s/%s/%s: %w", acct, app, name, err)
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv
index 0362759c8..d6f6b1922 100644
--- a/internal/provision/testdata/plan14-root-reads-chain.tsv
+++ b/internal/provision/testdata/plan14-root-reads-chain.tsv
@@ -177,3 +177,4 @@ plan14-root-reads-member-backups-1.tsv b3d35a0bd7c0500c74efbe5e8f566adb623696d31
plan14-root-reads-gvisor-empty-execstart.tsv 44b11f63c98595a70e62124034bdf5185c5a58561e99e3e269141557cf13880f
plan14-root-reads-demo-referrer-same-origin.tsv 44b11f63c98595a70e62124034bdf5185c5a58561e99e3e269141557cf13880f
plan14-root-reads-member-backups-2a.tsv b130b2d616e6476f056f4bd3dd5a5f64dd77aca49e95718ad6419ed0fd37f2d5
+plan14-root-reads-member-backups-2a-landing.tsv bf37ccf4fdd0d81a1dba7370a393074b763841b349d45fb65de12a037faf01ea
diff --git a/internal/provision/testdata/plan14-root-reads-member-backups-2a-landing.tsv b/internal/provision/testdata/plan14-root-reads-member-backups-2a-landing.tsv
new file mode 100644
index 000000000..7bd70c334
--- /dev/null
+++ b/internal/provision/testdata/plan14-root-reads-member-backups-2a-landing.tsv
@@ -0,0 +1,12 @@
+# Census overlay member-backups-2a-landing, written by census-propose (#369). census-ruling-member-backups-2a-landing, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-member-backups-2a-landing.md.
+# 1 body, 0 sites, 5 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
+# 1 new dispositions: 0 reads re-frozen at their disposition with the claim, 1 new units frozen accepted-legacy, 0 quiet units retired while they read nothing, 0 other.
+@legacy 63bf12546697dcaffa77ef79345a6d64f42454f33d78d61f09be367ce587269e internal/ops/ops.go hibernateRun.run legacy accepted-legacy accepted-legacy;rev3=census-ruling-member-backups-2a;basis=new, the drill (carlos ops hibernate-verify, user carlos): the verb's body, moved out of runHibernateVerify so a test can run it whole. First of all it refuses root (Root, from os.Geteuid() == 0 in runHibernateVerify): one log line, exit 1, before any monitor file is read, the deployment store opened or the registry opened (census round 1 P1, ls284: self.json, which the carlos user writes, names the record a run replaces). Then, as before: boxself.ReadFresh of self.json (refuses to run without a fresh record), dbreads.ValidRegion(CARLOS_REGION), openDeployStore, registry.Open(RegPath) (its +file:Open, the same registry the old body opened, closed after HibernatingHosts), dbverify.Load of this box's own control/verify/<ref>.json, selectHosts (verify-assign.json on a group box), MkdirTemp under the unit's on-disk TMPDIR, the drill, and dbverify.Publish to control/verify/<ref>.json only. Final fix wave (still refusing root first): the self.json read is retried every 15 s for up to 5 minutes (SelfWait, the same boxself.ReadFresh), a fleet box's CARLOS_REGION fleet/<name> is accepted beside dbreads.ValidRegion, it calls clearCrashedScratch on its own TmpDir right after the root refusal and the hibernate-config check, before the self record and both empty-fleet returns (re-review item 9), and its publisher now writes through dbverify.PublishOver (the same Get-then-CAS Put of control/verify/<ref>.json, also parsing the record it reads to drop hosts a landing removed). No new read source.;rev3=census-ruling-member-backups-2a-landing;basis=R3 (#898): an empty CARLOS_REGION (a home-region box) is the home region and no longer refuses; the bracket matches records whose region is "" exactly. A malformed non-empty region still refuses (dbreads.ValidRegion, or a fleet/<name> placement). No read added or changed: the same refusals in the same order (root first, then self.json, then the region gate), the same stores. Package envelopes: internal/ops adds one read-only bounded ListPage (one key) of moves/<host>/ in the drill's own data bucket at each end of a host's bracket (R1), and the bracket compares the record's LastMove (R1b) and the record object's stamp (R1c: ETag, version id, last-modified) at open and close, all from the same record GET it already made (now provision.GetRecordStamped / GetSidecarRecordStamped); internal/provision adds those two read-only getters (decodeSidecarAt shared with GetSidecarRecord, no writer touched); internal/release adds GetStamped, S3Store.GetStamped and ObjectStamp; internal/lease adds VerifyReaderAt and a read-only litestream client (R2); internal/dbdoor adds PlanListed, the planner's listing as a list/open reader (R2). The drill runs as carlos and refuses root. file:Open@2401 66b3cf4a1c7a1aa63f7a99683542437e0d127a9ea9aaa1f77e527d3cdea2ae95
+@legacy 0c9496233bb25b4e80520f9b09aa45345e68d2a8b97e035788c60fa5eade02f4 internal/release/stamped.go S3Store.GetStamped legacy accepted-legacy accepted-legacy;rev3=census-ruling-member-backups-2a-landing;basis=new (R1c, #898): S3Store.Get with the version id and last-modified time the same GetObject response carries, as an ObjectStamp. The same single GetObject of the caller's key in s.Bucket that Get makes, the same NoSuchKey -> os.ErrNotExist mapping, the body read whole as Get reads it. No new read source and no write; its one caller is provision.GetRecordStamped/GetSidecarRecordStamped (via release.GetStamped) for the restore drill's bracket, run as carlos. file:ReadAll@379 55c81f7247e5a1283b21b63b0ee4a386142b3932a616f6e481e4d0442ad47d34
+internal/ops/ops.go hibernateRun.run legacy accepted-legacy accepted-legacy;rev3=census-ruling-member-backups-2a;basis=new, the drill (carlos ops hibernate-verify, user carlos): the verb's body, moved out of runHibernateVerify so a test can run it whole. First of all it refuses root (Root, from os.Geteuid() == 0 in runHibernateVerify): one log line, exit 1, before any monitor file is read, the deployment store opened or the registry opened (census round 1 P1, ls284: self.json, which the carlos user writes, names the record a run replaces). Then, as before: boxself.ReadFresh of self.json (refuses to run without a fresh record), dbreads.ValidRegion(CARLOS_REGION), openDeployStore, registry.Open(RegPath) (its +file:Open, the same registry the old body opened, closed after HibernatingHosts), dbverify.Load of this box's own control/verify/<ref>.json, selectHosts (verify-assign.json on a group box), MkdirTemp under the unit's on-disk TMPDIR, the drill, and dbverify.Publish to control/verify/<ref>.json only. Final fix wave (still refusing root first): the self.json read is retried every 15 s for up to 5 minutes (SelfWait, the same boxself.ReadFresh), a fleet box's CARLOS_REGION fleet/<name> is accepted beside dbreads.ValidRegion, it calls clearCrashedScratch on its own TmpDir right after the root refusal and the hibernate-config check, before the self record and both empty-fleet returns (re-review item 9), and its publisher now writes through dbverify.PublishOver (the same Get-then-CAS Put of control/verify/<ref>.json, also parsing the record it reads to drop hosts a landing removed). No new read source.;rev3=census-ruling-member-backups-2a-landing;basis=R3 (#898): an empty CARLOS_REGION (a home-region box) is the home region and no longer refuses; the bracket matches records whose region is "" exactly. A malformed non-empty region still refuses (dbreads.ValidRegion, or a fleet/<name> placement). No read added or changed: the same refusals in the same order (root first, then self.json, then the region gate), the same stores. Package envelopes: internal/ops adds one read-only bounded ListPage (one key) of moves/<host>/ in the drill's own data bucket at each end of a host's bracket (R1), and the bracket compares the record's LastMove (R1b) and the record object's stamp (R1c: ETag, version id, last-modified) at open and close, all from the same record GET it already made (now provision.GetRecordStamped / GetSidecarRecordStamped); internal/provision adds those two read-only getters (decodeSidecarAt shared with GetSidecarRecord, no writer touched); internal/release adds GetStamped, S3Store.GetStamped and ObjectStamp; internal/lease adds VerifyReaderAt and a read-only litestream client (R2); internal/dbdoor adds PlanListed, the planner's listing as a list/open reader (R2). The drill runs as carlos and refuses root. file:Open@2401 66b3cf4a1c7a1aa63f7a99683542437e0d127a9ea9aaa1f77e527d3cdea2ae95
+internal/release/stamped.go S3Store.GetStamped legacy accepted-legacy accepted-legacy;rev3=census-ruling-member-backups-2a-landing;basis=new (R1c, #898): S3Store.Get with the version id and last-modified time the same GetObject response carries, as an ObjectStamp. The same single GetObject of the caller's key in s.Bucket that Get makes, the same NoSuchKey -> os.ErrNotExist mapping, the body read whole as Get reads it. No new read source and no write; its one caller is provision.GetRecordStamped/GetSidecarRecordStamped (via release.GetStamped) for the restore drill's bracket, run as carlos. file:ReadAll@379 55c81f7247e5a1283b21b63b0ee4a386142b3932a616f6e481e4d0442ad47d34
+@coverage internal/dbdoor d098eeed2df73ced7f8db62effcb0de0df192151977dbb97e76f8631b5ec3709
+@coverage internal/lease e42e312f5032bb6d38913e153f16d0999974c5083ca4788afc7cb821d8424451
+@coverage internal/ops 09af441c92d612fa06c16ebd78feba73695220833e4136dad0cc0af66b8dad27
+@coverage internal/provision adf9a5c5490e3488380c74183649cc934163af467fe87f3b896096c00e782399
+@coverage internal/release 07a35eafe197f949a5df5f2e8df1b94691815fb47c77ed8ba906642a3e2a151a
diff --git a/internal/release/stamped.go b/internal/release/stamped.go
new file mode 100644
index 000000000..1e19fbd89
--- /dev/null
+++ b/internal/release/stamped.go
@@ -0,0 +1,75 @@
+package release
+
+import (
+ "context"
+ "fmt"
+ "io"
+ "os"
+ "time"
+
+ "github.com/aws/aws-sdk-go-v2/aws"
+ awss3 "github.com/aws/aws-sdk-go-v2/service/s3"
+)
+
+// ObjectStamp is what identifies one write of an object, as a read saw it.
+// ETag is a content hash on the stores in use (S3 SSE-S3: the body's MD5;
+// DirStore: its sha256), so two writes of the same bytes share it.
+// VersionID (a versioned bucket's id for this write, "" where the store
+// has none) and LastModified (S3's, to the second; zero where the store
+// gives none) tell them apart. A reader that must know whether anything
+// wrote the object between two reads compares stamps, not bodies.
+type ObjectStamp struct {
+ ETag string
+ VersionID string
+ LastModified time.Time
+}
+
+// Same reports whether two stamps name the same write.
+func (a ObjectStamp) Same(b ObjectStamp) bool {
+ return a.ETag == b.ETag && a.VersionID == b.VersionID && a.LastModified.Equal(b.LastModified)
+}
+
+// StampedGetter is the optional half of Store whose read also returns the
+// object's stamp, from the same request. Type-asserted like PageLister;
+// GetStamped falls back to Get where it is missing.
+type StampedGetter interface {
+ GetStamped(ctx context.Context, key string) ([]byte, ObjectStamp, error)
+}
+
+var _ StampedGetter = (*S3Store)(nil)
+
+// GetStamped reads key from s with its stamp: the store's own stamped
+// read when it has one, else Get's body and ETag. A missing key is
+// os.ErrNotExist, as Get reports it.
+func GetStamped(ctx context.Context, s Store, key string) ([]byte, ObjectStamp, error) {
+ if sg, ok := s.(StampedGetter); ok {
+ return sg.GetStamped(ctx, key)
+ }
+ body, etag, err := s.Get(ctx, key)
+ if err != nil {
+ return nil, ObjectStamp{}, err
+ }
+ return body, ObjectStamp{ETag: etag}, nil
+}
+
+// GetStamped is Get with the version id and last-modified time the same
+// GetObject response carries: no extra request.
+func (s *S3Store) GetStamped(ctx context.Context, key string) ([]byte, ObjectStamp, error) {
+ out, err := s.Client.GetObject(ctx, &awss3.GetObjectInput{Bucket: &s.Bucket, Key: &key})
+ if err != nil {
+ if s3NotFound(err) {
+ return nil, ObjectStamp{}, fmt.Errorf("s3store: %s: %w", key, os.ErrNotExist)
+ }
+ return nil, ObjectStamp{}, err
+ }
+ defer out.Body.Close()
+ b, err := io.ReadAll(out.Body)
+ if err != nil {
+ return nil, ObjectStamp{}, err
+ }
+ st := ObjectStamp{ETag: aws.ToString(out.ETag), VersionID: aws.ToString(out.VersionId)}
+ if out.LastModified != nil {
+ st.LastModified = out.LastModified.UTC()
+ }
+ return b, st, nil
+}
diff --git a/internal/release/stamped_test.go b/internal/release/stamped_test.go
new file mode 100644
index 000000000..7924174b1
--- /dev/null
+++ b/internal/release/stamped_test.go
@@ -0,0 +1,95 @@
+package release
+
+import (
+ "context"
+ "errors"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/aws/aws-sdk-go-v2/aws"
+ "github.com/aws/aws-sdk-go-v2/credentials"
+ awss3 "github.com/aws/aws-sdk-go-v2/service/s3"
+)
+
+// GetStamped reads the body and what identifies this write of the object
+// from one GetObject: the ETag, the version id and the last-modified
+// time. On a versioned SSE-S3 bucket two writes of the same bytes share
+// an ETag (the body's MD5) and differ in version id and time, which is
+// what a reader bracketing its own work needs to see (member backups 2a,
+// Astra's review of R1b).
+func TestS3GetStampedCarriesTheVersion(t *testing.T) {
+ t.Parallel()
+ const etag = `"same-bytes-md5"`
+ versions := []string{"v1", "v2"}
+ times := []string{"Thu, 12 Nov 2026 03:00:00 GMT", "Thu, 12 Nov 2026 03:04:00 GMT"}
+ var reqs atomic.Int32
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ n := int(reqs.Add(1)) - 1
+ if r.URL.Path == "/b/gone" {
+ w.WriteHeader(http.StatusNotFound)
+ _, _ = w.Write([]byte(`<Error><Code>NoSuchKey</Code></Error>`))
+ return
+ }
+ w.Header().Set("ETag", etag)
+ w.Header().Set("x-amz-version-id", versions[n%2])
+ w.Header().Set("Last-Modified", times[n%2])
+ _, _ = w.Write([]byte("body"))
+ }))
+ defer srv.Close()
+ client := awss3.New(awss3.Options{
+ Region: "us-east-1",
+ Credentials: credentials.NewStaticCredentialsProvider("k", "s", ""),
+ BaseEndpoint: aws.String(srv.URL),
+ UsePathStyle: true,
+ Retryer: aws.NopRetryer{},
+ })
+ s := &S3Store{Client: client, Bucket: "b"}
+ ctx := context.Background()
+
+ body, first, err := GetStamped(ctx, s, "k")
+ if err != nil || string(body) != "body" {
+ t.Fatalf("first read: %q, %v", body, err)
+ }
+ _, second, err := GetStamped(ctx, s, "k")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if n := reqs.Load(); n != 2 {
+ t.Fatalf("%d requests for two reads, want one each", n)
+ }
+ if first.ETag != etag || first.VersionID != "v1" || !first.LastModified.Equal(time.Date(2026, 11, 12, 3, 0, 0, 0, time.UTC)) {
+ t.Fatalf("first stamp %+v", first)
+ }
+ if first.Same(second) || second.VersionID != "v2" || second.ETag != first.ETag {
+ t.Fatalf("two writes of the same bytes: stamps %+v and %+v must differ, by version and time only", first, second)
+ }
+ if !first.Same(first) {
+ t.Fatal("a stamp is not the same as itself")
+ }
+ if _, _, err := GetStamped(ctx, s, "gone"); !errors.Is(err, os.ErrNotExist) {
+ t.Fatalf("a missing key = %v, want os.ErrNotExist", err)
+ }
+}
+
+// A store with no versions (DirStore) stamps a read with its ETag alone,
+// from its ordinary Get.
+func TestGetStampedFallsBackToTheETag(t *testing.T) {
+ t.Parallel()
+ ctx := context.Background()
+ d := NewDirStore(t.TempDir())
+ if _, err := d.Put(ctx, "a.json", []byte("one"), ""); err != nil {
+ t.Fatal(err)
+ }
+ body, st, err := GetStamped(ctx, d, "a.json")
+ _, etag, _ := d.Get(ctx, "a.json")
+ if err != nil || string(body) != "one" || st != (ObjectStamp{ETag: etag}) {
+ t.Fatalf("GetStamped = %q, %+v, %v; want the body and ETag %q only", body, st, err, etag)
+ }
+ if _, _, err := GetStamped(ctx, d, "absent.json"); !errors.Is(err, os.ErrNotExist) {
+ t.Fatalf("a missing key = %v, want os.ErrNotExist", err)
+ }
+}