carlos / platform Public

Merge main into design-account-name-hosts

Brings in af871da0 (member backups 2a drill fixes, #898) and f2cf2828
(console claim picker).

One conflict, internal/provision/testdata/plan14-root-reads-chain.tsv:
main's member-backups-2a-landing line kept, account-subdomains last,
re-proposed with make census-propose on main's chain (seal bf37ccf4 ->
0ae4d72f). Only the internal/provision envelope moved, from main's
record_stamped.go and sidecar.go; no unit digest changed. Not yet
approved.

Main re-pinned the base write inventory in place, so the write census
tip (accountSubdomainsWriteCensusInventory on
memberBackups1WriteCensusInventory) needed no change.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev a6b19c7378d3ad46f0cb564caa8077d522677bbd parent d61b340parent af871da
40 files changed, +2,393 −176
  • docs/superpowers/notes/census-proposal-account-subdomains.md +1 −1
  • 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/console/demo_claim_choice_test.go +206 −18
  • internal/console/demo_claim_copy.go +49 −8
  • internal/console/demo_claim_footer_test.go +13 −11
  • internal/console/demo_claim_page.go +109 −13
  • internal/console/demo_claim_resume_browser_test.go +75 −3
  • internal/console/demo_claim_resume_test.go +17 −1
  • internal/console/demo_claim_status_page.go +6 −0
  • internal/console/demo_claim_ux_test.go +3 −3
  • internal/console/static/demo_claim.js +145 −11
  • internal/console/templates/demo_claim.html +72 −40
  • internal/console/testdata/demo_claim_resume_browser.mjs +108 −14
  • 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-account-subdomains.tsv +1 −1
  • internal/provision/testdata/plan14-root-reads-chain.tsv +2 −1
  • 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

Intent

Human

<task-notification> <task-id>a94c09830561f6f62</task-id> <tool-use-id>toolu_01GJeoxJJpVbZZKo8mBgPK8d</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/709ac745-ee81-4971-97b8-321e18b19cf6/tasks/a94c09830561f6f62.output</output-file> <status>completed</status> <summary>Agent "Implement Task 4: edge wildcard parents" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>**Status:** DONE. `TestNamespaceChangeRefreshesParentsOnRemoteOnlyEdge` no longer depends on timing, and it passed 30 runs plus 30 more at `-cpu=1,4`. **Commit:** `d61b3403 edge: wait on the watcher's record in the namespace parents test (T4)`, on top of `a627b21c`. Not pushed. **Cause:** the add half had the same two weaknesses as the removal half. Each phase sent only one tick and then checked the parents against a 2 s clock, so a slow or failed reload had no later tick to retry it. **Fix:** - The test now records each fingerprint the watcher handles, using the existing reload-hook test seam. The watcher only records after a successful reload, and the reload rebuilds the parents before it returns. - After each registry write, the test keeps ticking until the fingerprint of the state it just wrote is recorded. A failed reload is retried on the next tick, as in production. - The parent checks are then strict one-shot comparisons with no polling. The only clock left is a 30 s backstop. **Tests:** - `-count=30`: ok in 0.9 s; `-count=30 -cpu=1,4`: ok in 1.9 s. - The other Task 4 edge tests and `TestPlan14RootReadCensus` still pass; only a test file changed, so there is no census change. **Concerns:** `git commit` printed a `packed-refs.lock` "File exists" error, most likely from another session's git operation. The commit still landed: the branch points at `d61b3403` and the tree is clean. **Report:** /home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-account-name-hosts/.superpowers/sdd/2026-11-11-account-subdomains/task-4-report.md (new "Flake fix" section at the end)</result> <usage><subagent_tokens>171958</subagent_tokens><tool_uses>13</tool_uses><duration_ms>192260</duration_ms></usage> </task-notification>

Human

<task-notification> <task-id>bcf25ogz3</task-id> <tool-use-id>toolu_01HFBE3QUN83ZFR4Tn524kdj</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/709ac745-ee81-4971-97b8-321e18b19cf6/tasks/bcf25ogz3.output</output-file> <status>completed</status> <summary>Background command "Re-review the flake fix and wait for CI" completed (exit code 0)</summary> </task-notification>

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

diff --git a/docs/superpowers/notes/census-proposal-account-subdomains.md b/docs/superpowers/notes/census-proposal-account-subdomains.md
index 1dc4e4c16..67ebb176b 100644
--- a/docs/superpowers/notes/census-proposal-account-subdomains.md
+++ b/docs/superpowers/notes/census-proposal-account-subdomains.md
@@ -40,6 +40,6 @@ New dispositions, which census-propose wrote and the reviewer checks against the
- other `changed registry schema`: closed only if it is the registry schema (re-pinned)
- reads `internal/registry/remote_dispatch.go:Registry.dispatchRemote`: +registry:Names, +registry:StringMap; keeps hint, task E2
-Seal: `b130b2d616e6476f056f4bd3dd5a5f64dd77aca49e95718ad6419ed0fd37f2d5` → `bc306a42e5d5c2c03d38c1e574a30b98e9cae71e209eec241bc33da0ae851314`.
+Seal: `bf37ccf4fdd0d81a1dba7370a393074b763841b349d45fb65de12a037faf01ea` → `0ae4d72ff0196d3eabb4acee069c6de61431c1a3bef669eb7ba5294104694eb8`.
Overlay: `internal/provision/testdata/plan14-root-reads-account-subdomains.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
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/console/demo_claim_choice_test.go b/internal/console/demo_claim_choice_test.go
index 147907e90..6bd815eb0 100644
--- a/internal/console/demo_claim_choice_test.go
+++ b/internal/console/demo_claim_choice_test.go
@@ -115,6 +115,13 @@ func TestDemoClaimStatusDoor(t *testing.T) {
t.Error("missing stopping explanation")
}
want := 2
+ if tc.state == "claiming" {
+ // Only a claiming payload says whether the commit has happened.
+ want = 3
+ if got["committed"] != (tc.phase == "committed") {
+ t.Errorf("%s: committed = %v", tc.phase, got["committed"])
+ }
+ }
if tc.phase == "done" {
want = 3
if got["url"] != "https://"+op.Target.Host {
@@ -192,9 +199,9 @@ func TestDemoClaimChoiceRoom(t *testing.T) {
reason, room string
}{
{"fits exactly", RoleOwner, 0, true, false, "", "Has room"},
- {"needs two slots", RoleMember, 1, true, false, "Not enough room: 2 of 3 apps and instances in use. This demo needs room for one app and its instance.", ""},
- {"full", RoleOwner, 2, true, false, "Full: 3 of 3 apps and instances in use", ""},
- {"over limit", RoleOwner, 3, true, false, "Full: 4 of 3 apps and instances in use", ""},
+ {"needs two slots", RoleMember, 1, true, false, demoClaimNoRoom, ""},
+ {"full", RoleOwner, 2, true, false, demoClaimFull, ""},
+ {"over limit", RoleOwner, 3, true, false, demoClaimFull, ""},
{"role", "viewer", 0, true, false, demoClaimRoleDenied, ""},
{"role at limit", "viewer", 2, true, false, demoClaimRoleDenied, ""},
{"plans off", RoleOwner, 1, false, false, "", ""},
@@ -227,8 +234,12 @@ func TestDemoClaimChoiceRoom(t *testing.T) {
if !strings.Contains(body, tc.reason) || !strings.Contains(body, `value="`+a.Sqid+`" disabled`) || strings.Contains(body, `action="/demo/claim/select"`) {
t.Error("ineligible account not disabled with its reason")
}
- if !strings.Contains(body, "You are signed in as") || !strings.Contains(body, `<span class="claim-detail">`+tc.reason+"</span>") {
- t.Error("no_accounts missing identity or muted reason")
+ if !strings.Contains(body, "You are signed in as") || !regexp.MustCompile(`<span class="chip chip-(stale|env)">`+regexp.QuoteMeta(tc.reason)+`</span>`).MatchString(body) {
+ t.Error("no_accounts missing identity or status chip")
+ }
+ note := map[string]string{demoClaimNoRoom: demoClaimNoRoomNote, demoClaimRoleDenied: demoClaimRoleDeniedNote}[tc.reason]
+ if note != "" && !strings.Contains(body, `<span class="claim-row-note">`+note+"</span>") {
+ t.Errorf("ineligible row missing its note %q", note)
}
} else if !strings.Contains(body, `type="hidden" name="accountId" value="`+a.Sqid+`"`) {
t.Error("eligible account lost")
@@ -240,18 +251,21 @@ func TestDemoClaimChoiceRoom(t *testing.T) {
if tc.room != "" && strings.Count(body, ">"+tc.room+"<") != 1 {
t.Errorf("single account must show exactly one %q line", tc.room)
}
- if tc.reason == "" || tc.role == "viewer" {
- if strings.Contains(body, "apps and instances") {
- t.Error("eligible or role-disabled account shows counts")
- }
- } else if strings.Count(body, tc.reason) != 1 {
- t.Error("capacity reason must appear once")
+ counted := tc.plans && !tc.fail && tc.role != "viewer"
+ if usage := fmt.Sprintf(demoClaimUsageOf, tc.instances+1, 3); counted != strings.Contains(body, `<span class="claim-usage">`+usage+"</span>") {
+ t.Errorf("usage %q shown = %v, want %v", usage, !counted, counted)
+ }
+ if !counted && strings.Contains(body, `class="claim-usage"`) {
+ t.Error("uncounted account shows a usage figure")
+ }
+ if tc.reason != "" && strings.Count(body, ">"+tc.reason+"<") != 1 {
+ t.Error("status chip must appear once")
}
if (!tc.plans || tc.role == "viewer") && spy.calls.Load() != 0 {
t.Error("plans off or role-disabled account read store")
}
if tc.plans && !tc.fail && tc.role != "viewer" {
- if !strings.Contains(body, ">Free plan<") {
+ if !strings.Contains(body, `<span class="chip chip-env">Free</span>`) {
t.Error("missing plan")
}
if isPlanCap(s.checkRunningThings(t.Context(), a, 2)) != (tc.instances >= 1) {
@@ -398,7 +412,7 @@ func TestDemoClaimProgressAndOutcome(t *testing.T) {
address := "https://a-long-permanent-app-name.account.apps.example.com"
copy := demoClaimBrowserCopy()
copy["completeHeading"] = "example is yours"
- if err := demoClaimPageTemplate.ExecuteTemplate(&rendered, "demo_claim.html", demoClaimPageData{Copy: copy, State: state, Step: 2, URL: address}); err != nil {
+ if err := demoClaimPageTemplate.ExecuteTemplate(&rendered, "demo_claim.html", demoClaimPageData{Copy: copy, State: state, Step: 2, URL: address, ConsoleURL: "/a/k3x9/apps/example", DeadlineIn: "240", DemoName: "example", DemoHost: "example-demo.example.com"}); err != nil {
t.Fatal(err)
}
body := rendered.String()
@@ -406,16 +420,29 @@ func TestDemoClaimProgressAndOutcome(t *testing.T) {
if !strings.Contains(body, `id="claim-status" class="claim-sr-only" role="status" aria-live="polite"`) || !strings.Contains(body, "#claim .claim-sr-only") {
t.Error("live status must use the scoped screen-reader-only class")
}
- if !strings.Contains(body, `data-step="2" aria-current="step">`) || !strings.Contains(body, `<strong>Starting your app</strong>`) {
+ if !strings.Contains(body, `aria-current="step">`) || !strings.Contains(body, `<strong>Starting your app</strong>`) || !regexp.MustCompile(`data-step="2" data-hints="[^"]+" aria-current="step"`).MatchString(body) {
t.Error("current step is not marked")
}
+ for _, want := range []string{`data-deadline-in="240"`, `role="progressbar"`, `id="claim-stuck"`, `id="claim-elapsed"`, demoClaimStuckHeading} {
+ if !strings.Contains(body, want) {
+ t.Errorf("progress view missing %q", want)
+ }
+ }
} else {
if !strings.Contains(body, `<h1 id="claim-heading" tabindex="-1">example is yours</h1>`) || strings.Contains(body, demoClaimComplete) {
t.Error("outcome must appear once, as the heading")
}
- link := regexp.MustCompile(`<a class="btn claim-open" href="([^"]+)" rel="noreferrer">([^<]+)</a>`).FindStringSubmatch(body)
- if len(link) != 3 || link[1] != address || link[2] != demoClaimUX45 || !strings.Contains(body, `<p class="claim-result-address">`+address+`</p>`) {
- t.Error("result link must display the permanent address")
+ // Two actions: the app in the console, and the live address as
+ // its own link opening a new tab, shown once.
+ if !strings.Contains(body, `<a class="btn claim-console" href="/a/k3x9/apps/example">`+demoClaimOpenConsole+`</a>`) {
+ t.Error("missing the console action")
+ }
+ link := regexp.MustCompile(`<a class="claim-open" href="([^"]+)" target="_blank" rel="noopener noreferrer"><span class="claim-open-address">([^<]+)</span><svg[^>]*aria-hidden="true"`).FindStringSubmatch(body)
+ if len(link) != 3 || link[1] != address || link[2] != address || !strings.Contains(body, demoClaimOpensNewTab) {
+ t.Error("result link must display the permanent address with an external-link icon")
+ }
+ if strings.Count(body, ">"+address+"<") != 2 || strings.Contains(body, "claim-result-address") {
+ t.Error("permanent address must show in the ticket and the action row only")
}
}
})
@@ -517,7 +544,7 @@ func TestDemoClaimChoiceAdmissionAndExemption(t *testing.T) {
if spy.calls.Load() != 0 {
t.Error("counted unavailable or exempt account")
}
- if strings.Contains(body, ">Free plan<") {
+ if strings.Contains(body, `<span class="chip chip-env">Free</span>`) {
t.Error("false plan label")
}
if !exempt && (!strings.Contains(body, "<p>unavailable</p>") || strings.Contains(body, demoClaimNoEligibleAccount)) {
@@ -549,3 +576,164 @@ func TestDemoClaimChoicePrivacy(t *testing.T) {
t.Error("another person's proved flow revealed summary or accounts")
}
}
+
+// A sponsored account's "unlimited" limit is a sentinel (sponsorMost). The
+// picker shows how many things run, never the sentinel and never a meter
+// that would sit empty against it.
+func TestDemoClaimChoiceUnlimitedUsage(t *testing.T) {
+ s, _, token := claimTestServer(t)
+ b := newClaimBrowser(t, s, token)
+ b.login("shop@example.com", MethodEmail, true)
+ a := claimAccount(t, s, 501, "shop@example.com", RoleOwner)
+ claimAccount(t, s, 502, "shop@example.com", RoleOwner)
+ s.cfg.PlanCatalog = examplePlanCatalog(t)
+ unlimited := sponsorUnlimited()
+ if _, err := s.store.SetAccountPlan(a.ID, "personal", nil, 0, PlanSourceSponsored, &unlimited, "test", "ops@example.com", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := s.store.CreateAppIn(a.ID, "shop", "shop@example.com", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ if choice := s.demoClaimAccountView(t.Context(), *a, true); choice.Limit != sponsorMost || choice.Usage != fmt.Sprintf(demoClaimUsage, 1) || choice.Status != demoClaimHasRoom {
+ t.Fatalf("sponsored choice = %+v", choice)
+ }
+ body := b.request("GET", "/demo/claim", nil).Body.String()
+ for _, banned := range []string{fmt.Sprint(int64(sponsorMost)), "<meter", "claim-slots"} {
+ if strings.Contains(body, banned) {
+ t.Errorf("sponsored account renders %q", banned)
+ }
+ }
+ if !strings.Contains(body, `<span class="claim-usage">1 running</span>`) || !strings.Contains(body, `<span class="claim-usage">0 of 3 running</span>`) {
+ t.Error("rows lack their usage figures")
+ }
+ for _, c := range []struct {
+ used, limit int
+ want string
+ }{{17, sponsorMost, "17 running"}, {3, 5, "3 of 5 running"}, {0, 0, ""}} {
+ if got := demoClaimUsageText(c.used, c.limit); got != c.want {
+ t.Errorf("usage(%d, %d) = %q, want %q", c.used, c.limit, got, c.want)
+ }
+ }
+}
+
+// Past demoClaimSearchFrom accounts the list gets a search box (hidden until
+// the script shows it); rows that can take the demo come first, each group
+// in its original order.
+func TestDemoClaimChoiceSearchAndOrder(t *testing.T) {
+ for _, n := range []int{demoClaimSearchFrom, demoClaimSearchFrom + 1} {
+ t.Run(fmt.Sprint(n), func(t *testing.T) {
+ s, _, token := claimTestServer(t)
+ b := newClaimBrowser(t, s, token)
+ b.login("shop@example.com", MethodEmail, true)
+ var want, viewers []string
+ for i := 0; i < n; i++ {
+ role := RoleOwner
+ if i%3 == 0 {
+ role = "viewer"
+ }
+ a := claimChoiceAccount(t, s, int64(501+i), "shop@example.com", role)
+ if role == "viewer" {
+ viewers = append(viewers, a.Sqid)
+ } else {
+ want = append(want, a.Sqid)
+ }
+ }
+ want = append(want, viewers...)
+ body := b.request("GET", "/demo/claim", nil).Body.String()
+ var got []string
+ for _, m := range regexp.MustCompile(`type="radio" name="accountId" value="([^"]+)"`).FindAllStringSubmatch(body, -1) {
+ got = append(got, m[1])
+ }
+ if strings.Join(got, ",") != strings.Join(want, ",") {
+ t.Errorf("row order %v, want %v", got, want)
+ }
+ searchable := n > demoClaimSearchFrom
+ if strings.Contains(body, `<p class="claim-search" hidden><input type="search" id="claim-search"`) != searchable || strings.Contains(body, `id="claim-search-empty"`) != searchable {
+ t.Errorf("search box shown = %v, want %v", !searchable, searchable)
+ }
+ if searchable && regexp.MustCompile(`id="claim-search"[^>]* name=`).MatchString(body) {
+ t.Error("search field would be posted with the choice")
+ }
+ })
+ }
+}
+
+// Status access does not establish console access. The claim's own browser
+// keeps seeing the result and the live address, but "Open in the console"
+// needs the signed-in person to be a member of the destination account now,
+// and the app to exist there.
+func TestDemoClaimDoneConsoleLinkNeedsMembership(t *testing.T) {
+ for _, condition := range []string{"member", "viewer", "membership removed", "other person", "app deleted", "signed out"} {
+ t.Run(condition, func(t *testing.T) {
+ s, _, b := claimSigninFixture(t)
+ b.login("shop@example.com", MethodEmail, true)
+ a := claimAccount(t, s, 801, "shop@example.com", RoleOwner)
+ if w := b.post("/demo/claim/select", url.Values{"accountId": {a.Sqid}}); w.Code != 303 {
+ t.Fatalf("select: %d %s", w.Code, w.Body)
+ }
+ if _, err := s.store.db.Exec(`UPDATE demo_claim_ops SET phase='done'`); err != nil {
+ t.Fatal(err)
+ }
+ switch condition {
+ case "viewer":
+ _, _ = s.store.db.Exec(`UPDATE memberships SET role='viewer' WHERE account_id=?`, a.ID)
+ case "membership removed":
+ _, _ = s.store.db.Exec(`DELETE FROM memberships WHERE account_id=?`, a.ID)
+ case "other person":
+ b.login("other@example.com", MethodEmail, true)
+ case "app deleted":
+ _, _ = s.store.db.Exec(`UPDATE apps SET deleted_at=1 WHERE account_id=?`, a.ID)
+ case "signed out":
+ b.session = ""
+ }
+ body := b.request("GET", "/demo/claim", nil).Body.String()
+ if !strings.Contains(body, `data-state="claimed"`) || !strings.Contains(body, `class="claim-open" href="https://`) {
+ t.Fatal("the claim's browser lost its result or live address")
+ }
+ wantLink := condition == "member" || condition == "viewer"
+ if got := strings.Contains(body, `class="btn claim-console"`); got != wantLink {
+ t.Errorf("console link shown = %v, want %v", got, wantLink)
+ }
+ })
+ }
+}
+
+// The commit is the claim's one-way boundary. The status payload and the
+// page say so, so the browser never judges a committed claim by the
+// rollback deadline.
+func TestDemoClaimStatusCommitted(t *testing.T) {
+ s, _, b := claimSigninFixture(t)
+ b.login("shop@example.com", MethodEmail, true)
+ a := claimAccount(t, s, 801, "shop@example.com", RoleOwner)
+ if w := b.post("/demo/claim/select", url.Values{"accountId": {a.Sqid}}); w.Code != 303 {
+ t.Fatalf("select: %d %s", w.Code, w.Body)
+ }
+ status := func() map[string]any {
+ t.Helper()
+ r := httptest.NewRequest("GET", "/demo/claim/status", nil)
+ r.Header.Set("Sec-Fetch-Site", "same-origin")
+ r.AddCookie(&http.Cookie{Name: browserClaimCookieName, Value: b.cookie})
+ w := httptest.NewRecorder()
+ s.mux.ServeHTTP(w, r)
+ var out map[string]any
+ if w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &out) != nil {
+ t.Fatalf("status: %d %s", w.Code, w.Body)
+ }
+ return out
+ }
+ for _, c := range []struct {
+ phase string
+ committed any
+ }{{"verifying", false}, {"committed", true}, {"done", nil}, {"aborting", nil}} {
+ if _, err := s.store.db.Exec(`UPDATE demo_claim_ops SET phase=?`, c.phase); err != nil {
+ t.Fatal(err)
+ }
+ if got := status()["committed"]; got != c.committed {
+ t.Errorf("%s: committed = %v, want %v", c.phase, got, c.committed)
+ }
+ body := b.request("GET", "/demo/claim", nil).Body.String()
+ if strings.Contains(body, "data-committed-for=") != (c.phase == "committed") {
+ t.Errorf("%s: page committed marker wrong", c.phase)
+ }
+ }
+}
diff --git a/internal/console/demo_claim_copy.go b/internal/console/demo_claim_copy.go
index 23086c70c..e5d62fb19 100644
--- a/internal/console/demo_claim_copy.go
+++ b/internal/console/demo_claim_copy.go
@@ -117,14 +117,26 @@ const (
demoClaimDestination = "This goes into %s."
// CLAIM-KEEP-IN: action after choosing an account.
demoClaimKeepIn = "Keep in %s"
- // CLAIM-ROOM-AVAILABLE: the account has room for the app and its instance.
+ // CLAIM-ROOM-AVAILABLE: status chip; the account has room for the app and its instance.
demoClaimHasRoom = "Has room"
- // CLAIM-ROOM-FULL: current use is at or above the catalog cap.
- demoClaimFull = "Full: %d of %d apps and instances in use"
- // CLAIM-ROOM-INSUFFICIENT: one slot remains, but the claim needs two.
- demoClaimNoRoom = "Not enough room: %d of %d apps and instances in use. This demo needs room for one app and its instance."
- // CLAIM-ROLE-DENIED: membership cannot create apps.
- demoClaimRoleDenied = "You can view this account but not add apps. Ask one of its owners."
+ // CLAIM-ROOM-FULL: status chip; current use is at or above the catalog cap.
+ demoClaimFull = "Full"
+ // CLAIM-ROOM-INSUFFICIENT: status chip; one slot remains, but the claim needs two.
+ demoClaimNoRoom = "No room"
+ // CLAIM-ROOM-INSUFFICIENT-NOTE: muted line under a no-room row.
+ demoClaimNoRoomNote = "Needs room for an app and its instance."
+ // CLAIM-ROLE-DENIED: status chip; membership cannot create apps.
+ demoClaimRoleDenied = "View only"
+ // CLAIM-ROLE-DENIED-NOTE: muted line under a view-only row.
+ demoClaimRoleDeniedNote = "Ask an owner to add apps."
+ // CLAIM-USAGE-CAPPED: row usage figure against a plan cap; used, limit.
+ demoClaimUsageOf = "%d of %d running"
+ // CLAIM-USAGE-UNLIMITED: row usage figure when the plan has no cap; used.
+ demoClaimUsage = "%d running"
+ // CLAIM-SEARCH-LABEL: search box label and placeholder above a long account list.
+ demoClaimSearchLabel = "Find an account"
+ // CLAIM-SEARCH-EMPTY: no account name matches the search.
+ demoClaimSearchEmpty = "No accounts match."
// CLAIM-STEP-COPYING: first progress step.
demoClaimCopying = "Copying your data"
// CLAIM-STEP-STARTING: second progress step.
@@ -187,10 +199,39 @@ const (
demoClaimUX75 = "Follow the directions on https://carlosframework.com/start"
demoClaimUX77 = "This app has already been kept"
demoClaimUX80 = "Sign in to the console"
- demoClaimPlan = "%s plan"
demoClaimOpening = "Opening your demo…"
)
+// Progress reassurance, the stuck state and the result actions.
+const (
+ // CLAIM-PROGRESS-LABEL: accessible name of the progress bar.
+ demoClaimProgressLabel = "Progress"
+ // CLAIM-ELAPSED: shown after 30 s of progress; {elapsed} is "45 s" or "1 min 10 s".
+ demoClaimElapsed = "{elapsed} so far. This can take a few minutes."
+ // CLAIM-STUCK-HEADING: past the server's own deadline and the claim still reports running.
+ demoClaimStuckHeading = "This is taking longer than it should."
+ // CLAIM-STUCK-DETAIL: what is true while stuck, and what to do.
+ demoClaimStuckDetail = "Nothing is lost. A move that does not finish is undone, and your demo goes back to how it was."
+ // CLAIM-STUCK-ACTION: reloads the page to read the claim's state again.
+ demoClaimStuckAction = "Check again"
+ // CLAIM-FINISHING-HEADING: committed (the move cannot be undone) but the
+ // last steps are slow. New after copy review; awaiting review.
+ demoClaimFinishingHeading = "Your app is yours now. It is still finishing."
+ // CLAIM-FINISHING-DETAIL: what is true while a committed claim finishes. New; awaiting review.
+ demoClaimFinishingDetail = "The move is done and stays done. The last steps are taking longer than usual."
+ // CLAIM-OPEN-CONSOLE: done page primary action, the app's page in the console.
+ demoClaimOpenConsole = "Open in the console"
+ // CLAIM-OPENS-NEW-TAB: screen-reader suffix on the live address link.
+ demoClaimOpensNewTab = "(opens in a new tab)"
+)
+
+// CLAIM-HINTS-*: reassurance lines that rotate under the active step, one at
+// a time, after the step's own detail line.
+var (
+ demoClaimHintsCopying = []string{"Pausing the demo so nothing changes mid-copy", "Packing up its saved data", "Checking everything arrived"}
+ demoClaimHintsStarting = []string{"Placing it on a server", "Restoring its saved data", "Waiting for its secure address", "Checking it answers", "Still working. A first start can take a minute or two."}
+)
+
// COUNTDOWN-01..14, with the controller's singular-unit ruling.
func demoClaimCountdown(seconds int64) (visible, accessible string) {
unit := func(n int64, name string) string {
diff --git a/internal/console/demo_claim_footer_test.go b/internal/console/demo_claim_footer_test.go
index 5c4754a95..c23234b12 100644
--- a/internal/console/demo_claim_footer_test.go
+++ b/internal/console/demo_claim_footer_test.go
@@ -11,19 +11,21 @@ import (
"testing"
)
-// The digests were taken from the claim page before the footer existed. With
-// neither item configured (or both invalid) the page is these exact bytes.
-const demoClaimFooterBaseStyleHash = "'sha256-0/eCVx0ZVcjLY0c+mSbXxujrLi96B+0QEsMyCIBaADI='"
+// The digests are the claim page with no footer, retaken when the page itself
+// or its script changes (the script tag carries the asset hash; last: the
+// claim-picker-rows review fixes). With neither item configured (or both
+// invalid) the page is these exact bytes.
+const demoClaimFooterBaseStyleHash = "'sha256-jbEMQSC7VKnO3PowM9lc1xx5+TuvoIMmes/XPpn9IEM='"
var demoClaimFooterBaseDigests = map[string]string{
- "template-zero": "48b65f39722b9f26dfd9e1cc74e99b8d25859993e4af6681e886e8a9b09c923f",
- "template-missing": "2c793c646d7199bba6a84e4c552992dfc8fd7d17111a108232b93e4fa92ec5a0",
- "template-error": "1e8177ca639ff61406cfc0bc9db173b6668ac924bf53b875da7a5ef0dd1961ae",
- "template-claimed": "ab4542a9b912449bbc637595e9f51f653b417940eee103e7970eadb710fd667e",
- "template-proof": "9ca3d70d40f86bffa5081768630b3524b60548f2e8ffcb26eaf10e0a0c9e6458",
- "error-page": "f6cd7ee22473fb614b2f247599a1dfe3eac1ce870268ad6332ebafc37fd49a09",
- "get-claim": "c67a7aa13e23edb1a78fec563c17d74f173fa5153dc4fea3c8a10d128c18395d",
- "get-kept": "6050a0a0f5516f8209baf8dcf4a6549986f4f97d1f0026889cc8ad5e1b4c5d93",
+ "template-zero": "307ae622a5541a738bd6d7117eaf00c2058afbc914e9a0f2e48157b3983356f2",
+ "template-missing": "c54a88efef115981799be2d80c0c47326d1fc2e7407cbcd6c96793be1026d8e1",
+ "template-error": "bc32157b2db3b29a739b840e0e9fc6c77c1ed9f7e93341b2a8caa06d41c6cf79",
+ "template-claimed": "fe5aef8746a63ac522ee05652393de418ced5bebc3b2e6894a0f7c4484fa070d",
+ "template-proof": "3c22418e10842d8cfad9a96518e011de43bf6c780b4db67546c2760c6dd81318",
+ "error-page": "d503dc9f496c8eaa8cf34e0ed15862ddf11ac91125d7dfc3451da6f8b13ab0ac",
+ "get-claim": "0d044d6e85e3f8db1a33c19e5e3844f76c7fe6dad9a1fd70da71a9aaeeca00e5",
+ "get-kept": "b7b65fb23266019375e2ec0a8764f15183fcc3450b0f69d0d3c5b218345bc6c5",
}
const (
diff --git a/internal/console/demo_claim_page.go b/internal/console/demo_claim_page.go
index 305973ad6..2216fed29 100644
--- a/internal/console/demo_claim_page.go
+++ b/internal/console/demo_claim_page.go
@@ -13,6 +13,7 @@ import (
"io"
"net/http"
"net/url"
+ "sort"
"strings"
"time"
)
@@ -59,7 +60,22 @@ type demoClaimPageData struct {
TimeLeft, TimeLeftAccessible, EndTime string
Step int
CanClaim, HasIntent, EmailPending bool
- Footer demoClaimFooter
+ // Searchable shows the account filter above a long list.
+ Searchable bool
+ // ConsoleURL is the claimed app's page in the console, for a reader who
+ // can open it; empty otherwise.
+ ConsoleURL string
+ // DeadlineIn is the seconds from render to the operation's server
+ // deadline (negative once past; empty with no operation). Past it the
+ // coordinator undoes an unfinished claim, so a claim that still reports
+ // progress well after it is stuck. Relative, so the browser's clock
+ // does not matter.
+ DeadlineIn string
+ // CommittedFor is set for a claim past its irreversible commit and still
+ // finishing: the seconds since the commit ("0" when unknown). Such a
+ // claim is never judged by the rollback deadline.
+ CommittedFor string
+ Footer demoClaimFooter
}
func (s *Server) demoClaimPageHeaders(w http.ResponseWriter, keymailOrigin string) {
@@ -169,6 +185,15 @@ func (s *Server) handleDemoClaimPage(w http.ResponseWriter, r *http.Request) {
setDemoClaimCookie(w, cookie, expiry)
p.State, p.Step = demoClaimProgressStep(op.Phase)
p.ExpiresAt = op.SourceExpiresAt
+ p.DeadlineIn = fmt.Sprint(op.Deadline.Unix() - time.Now().Unix())
+ if op.Phase == "committed" {
+ var at int64
+ _ = s.store.db.QueryRowContext(r.Context(), `SELECT committed_at FROM demo_claim_commits WHERE operation_id=?`, op.ID).Scan(&at)
+ p.CommittedFor = fmt.Sprint(max(0, time.Now().Unix()-at))
+ if at == 0 {
+ p.CommittedFor = "0"
+ }
+ }
p.App = op.Target.App
if d, err := s.store.demoByID(r.Context(), op.DemoID); err == nil {
p.DemoName, p.DemoHost = d.Name, d.Host
@@ -185,6 +210,7 @@ func (s *Server) handleDemoClaimPage(w http.ResponseWriter, r *http.Request) {
if canContinue {
if acct, err := s.store.AccountByID(op.Target.AccountID); err == nil && acct != nil && acct.Sqid == op.Target.Sqid {
p.AccountName, p.AccountSqid = acct.Name, acct.Sqid
+ p.ConsoleURL = s.demoClaimConsoleURL(address, acct, p.App)
p.Copy["sameChat"] = "Still in the chat where you built it?"
p.Copy["sameChatLine"] = fmt.Sprintf("Tell your agent: “I kept %s. It now lives at %s in my account %s.”", p.App, p.URL, acct.Name)
p.Copy["agentHeading"] = "Starting fresh, in a new chat or with another agent?"
@@ -252,6 +278,9 @@ func (s *Server) handleDemoClaimPage(w http.ResponseWriter, r *http.Request) {
}
}
}
+ // Accounts that can take the demo come first, each group in
+ // its original order. Sort before Single points into the slice.
+ sort.SliceStable(p.Accounts, func(i, j int) bool { return p.Accounts[i].Reason == "" && p.Accounts[j].Reason != "" })
if p.Eligible == 1 {
for i := range p.Accounts {
if p.Accounts[i].Reason == "" {
@@ -264,6 +293,7 @@ func (s *Server) handleDemoClaimPage(w http.ResponseWriter, r *http.Request) {
if resume && selection.Create && len(accounts) == 0 {
p.AutoSubmit = p.CanClaim
}
+ p.Searchable = p.Single == nil && len(p.Accounts) > demoClaimSearchFrom
if len(accounts) > 0 && p.Eligible == 0 {
p.State, p.CanClaim = "no_accounts", false
}
@@ -617,8 +647,7 @@ func demoClaimBrowserCopy() map[string]string {
"codeHeading": demoClaimUX16, "codeWorking": demoClaimUX20, "codeRecovery": demoClaimUX21, "changeAddress": demoClaimUX22,
"accountsHeading": demoClaimUX24, "accountsLabel": demoClaimUX26, "selectWorking": demoClaimUX34,
"copyingDetail": demoClaimUX38, "startingDetail": demoClaimUX40,
- "completeDetail": demoClaimUX44, "open": demoClaimUX45,
- "keepGoing": demoClaimUX47, "agentHeading": demoClaimUX48, "agentDetail": demoClaimUX49,
+ "completeDetail": demoClaimUX44, "keepGoing": demoClaimUX47, "agentHeading": demoClaimUX48, "agentDetail": demoClaimUX49,
"cliHeading": demoClaimUX52, "failureHeading": demoClaimUX61,
"expiredHeading": demoClaimUX72, "newDemo": demoClaimUX74, "newDemoLine": demoClaimUX75,
"keptHeading": demoClaimUX77, "consoleSignin": demoClaimUX80, "opening": demoClaimOpening,
@@ -663,6 +692,20 @@ func demoClaimBrowserCopy() map[string]string {
"disabled": demoClaimUnavailable,
"footerTerms": demoClaimFooterTerms,
"footerAbuse": demoClaimFooterAbuse,
+ "searchLabel": demoClaimSearchLabel,
+ "searchEmpty": demoClaimSearchEmpty,
+ "progressLabel": demoClaimProgressLabel,
+ "elapsed": demoClaimElapsed,
+ "stuckHeading": demoClaimStuckHeading,
+ "stuckDetail": demoClaimStuckDetail,
+ "stuckAction": demoClaimStuckAction,
+ "finishingHeading": demoClaimFinishingHeading,
+ "finishingDetail": demoClaimFinishingDetail,
+ "openConsole": demoClaimOpenConsole,
+ "opensNewTab": demoClaimOpensNewTab,
+ // Rotating lines travel as one attribute each, a line per hint.
+ "hintsCopying": strings.Join(demoClaimHintsCopying, "\n"),
+ "hintsStarting": strings.Join(demoClaimHintsStarting, "\n"),
}
}
@@ -703,14 +746,73 @@ func (s *Server) continueDemoClaimKeymail(w http.ResponseWriter, r *http.Request
s.continueKeymailSignin(w, r, flow, "/demo/claim")
}
+// demoClaimConsoleURL is the claimed app's console page, only when the
+// current session can open it: the signed-in person is a member (any role,
+// as the console's app pages ask) of the destination account and the app
+// exists there. The claim's status cookie shows progress and the live
+// address; it never establishes console access.
+func (s *Server) demoClaimConsoleURL(address string, acct *Account, app string) string {
+ if address == "" || acct == nil {
+ return ""
+ }
+ if role, err := s.store.Role(acct.ID, address); err != nil || role == "" {
+ return ""
+ }
+ if has, err := s.store.HasAppIn(acct.ID, app); err != nil || !has {
+ return ""
+ }
+ return "/a/" + url.PathEscape(acct.Sqid) + "/apps/" + url.PathEscape(app)
+}
+
+// demoClaimSearchFrom is the list length above which the picker offers a
+// search box: past it the list no longer fits a phone screen.
+const demoClaimSearchFrom = 6
+
// Room is a GET-only hint. Reservation still checks under its account lock.
+// Reason is the status chip of an account that cannot take the demo (empty
+// when it can); Room is the chip of one that can, when it was counted.
+// Status and StatusClass are the chip the row shows, Note a short muted line
+// for an ineligible row, and Usage the running count, never the "unlimited"
+// sentinel.
type demoClaimAccountChoice struct {
Sqid, Name, Plan, Room, Reason, Button string
- Slots []bool
+ Status, StatusClass, Note, Usage string
Used, Limit int
}
+// demoClaimUsageText is the row's running figure: "3 of 5 running" under a
+// cap, "17 running" when the plan has none (sponsorMost, as the billing page
+// treats it). A zero limit (not counted) shows nothing.
+func demoClaimUsageText(used, limit int) string {
+ switch {
+ case limit <= 0:
+ return ""
+ case int64(limit) >= sponsorMost:
+ return fmt.Sprintf(demoClaimUsage, used)
+ default:
+ return fmt.Sprintf(demoClaimUsageOf, used, limit)
+ }
+}
+
func (s *Server) demoClaimAccountView(ctx context.Context, a Account, count bool) demoClaimAccountChoice {
+ c := s.demoClaimAccountCount(ctx, a, count)
+ c.Usage = demoClaimUsageText(c.Used, c.Limit)
+ switch {
+ case c.Reason == demoClaimRoleDenied:
+ // The plan does not matter to someone who cannot add apps.
+ c.Plan = ""
+ c.Status, c.StatusClass, c.Note = c.Reason, "chip-env", demoClaimRoleDeniedNote
+ case c.Reason == demoClaimNoRoom:
+ c.Status, c.StatusClass, c.Note = c.Reason, "chip-stale", demoClaimNoRoomNote
+ case c.Reason != "":
+ c.Status, c.StatusClass = c.Reason, "chip-stale"
+ case c.Room != "":
+ c.Status, c.StatusClass = c.Room, "chip-health-ok"
+ }
+ return c
+}
+
+func (s *Server) demoClaimAccountCount(ctx context.Context, a Account, count bool) demoClaimAccountChoice {
c := demoClaimAccountChoice{Sqid: a.Sqid, Name: a.Name, Button: fmt.Sprintf(demoClaimKeepIn, a.Name)}
if !demoClaimCanCreate(a) {
c.Reason = demoClaimRoleDenied
@@ -722,7 +824,7 @@ func (s *Server) demoClaimAccountView(ctx context.Context, a Account, count bool
if row != nil {
name = row.Plan
}
- c.Plan = fmt.Sprintf(demoClaimPlan, planLabel(name))
+ c.Plan = planLabel(name)
}
}
if !count || c.Reason != "" || ctx.Err() != nil {
@@ -737,17 +839,11 @@ func (s *Server) demoClaimAccountView(ctx context.Context, a Account, count bool
return c
}
c.Used, c.Limit = n, limits.RunningThings
- // Keep the drawing bounded for large plans; the numeric ratio stays exact.
- if c.Limit <= 100 {
- for i := 0; i < c.Limit; i++ {
- c.Slots = append(c.Slots, i < n)
- }
- }
switch {
case n >= limits.RunningThings:
- c.Reason = fmt.Sprintf(demoClaimFull, n, limits.RunningThings)
+ c.Reason = demoClaimFull
case n+2 > limits.RunningThings:
- c.Reason = fmt.Sprintf(demoClaimNoRoom, n, limits.RunningThings)
+ c.Reason = demoClaimNoRoom
default:
c.Room = demoClaimHasRoom
}
diff --git a/internal/console/demo_claim_resume_browser_test.go b/internal/console/demo_claim_resume_browser_test.go
index 29ecc78cc..ad0295b09 100644
--- a/internal/console/demo_claim_resume_browser_test.go
+++ b/internal/console/demo_claim_resume_browser_test.go
@@ -45,7 +45,29 @@ func TestDemoClaimSelectStepUpHeadless(t *testing.T) {
mode.Store(4)
phase = "future-phase"
}
- if _, err := s.store.db.Exec(`UPDATE demo_claim_ops SET phase=?`, phase); err != nil {
+ // Past the server's deadline by more than the page's grace, and
+ // still reporting progress: the page must call it stuck.
+ deadline := time.Now().Add(5 * time.Minute).Unix()
+ if r.URL.Query().Get("testProgress") == "stuck" {
+ mode.Store(5)
+ phase = "verifying"
+ deadline = time.Now().Add(-100 * time.Second).Unix()
+ }
+ if r.URL.Query().Get("testProgress") == "starting" {
+ mode.Store(5)
+ phase = "verifying"
+ }
+ // Committed five minutes ago, well past the rollback deadline,
+ // and still finishing: never the rollback box, the finishing one.
+ if r.URL.Query().Get("testProgress") == "committed" {
+ mode.Store(6)
+ phase = "committed"
+ deadline = time.Now().Add(-1000 * time.Second).Unix()
+ if _, err := s.store.db.Exec(`INSERT OR REPLACE INTO demo_claim_commits(operation_id,demo_id,committed_at) SELECT id,demo_id,? FROM demo_claim_ops`, time.Now().Add(-300*time.Second).Unix()); err != nil {
+ t.Error(err)
+ }
+ }
+ if _, err := s.store.db.Exec(`UPDATE demo_claim_ops SET phase=?,deadline=?`, phase, deadline); err != nil {
t.Error(err)
}
}
@@ -72,6 +94,12 @@ func TestDemoClaimSelectStepUpHeadless(t *testing.T) {
if mode.Load() == 4 {
phase = "future-phase"
}
+ if mode.Load() == 5 {
+ phase = "verifying"
+ }
+ if mode.Load() == 6 {
+ phase = "committed"
+ }
if mode.Load() == 2 {
phase = "aborted"
}
@@ -164,9 +192,53 @@ func TestDemoClaimSelectStepUpHeadless(t *testing.T) {
}
}
}
+ // Thirty accounts, as one person had on production: sponsored (no cap),
+ // capped with room, full, short of room and view-only rows.
+ picker, _, pickerToken := claimTestServer(t)
+ picker.registerRoute(routeDecl{Pattern: "GET /static/{hash}/{file...}"}, picker.handleStatic)
+ pickerServer := httptest.NewServer(picker.mux)
+ defer pickerServer.Close()
+ picker.cfg.Origin = pickerServer.URL
+ picker.cfg.PlanCatalog = examplePlanCatalog(t)
+ many := newClaimBrowser(t, picker, pickerToken)
+ many.login("shop@example.com", MethodEmail, true)
+ unlimited := sponsorUnlimited()
+ for i := 1; i <= 30; i++ {
+ role := RoleOwner
+ if i%7 == 0 {
+ role = "viewer"
+ }
+ a := claimChoiceAccount(t, picker, int64(800+i), "shop@example.com", role)
+ if _, err := picker.store.db.Exec(`UPDATE accounts SET name=? WHERE id=?`, fmt.Sprintf("team-%02d", i), a.ID); err != nil {
+ t.Fatal(err)
+ }
+ apps, instances := i%2, 0
+ switch i {
+ case 1, 4, 12:
+ if _, err := picker.store.SetAccountPlan(a.ID, "personal", nil, 0, PlanSourceSponsored, &unlimited, "test", "ops@example.com", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ apps = 17
+ case 3, 10:
+ apps, instances = 1, 2
+ case 6:
+ apps, instances = 1, 1
+ }
+ for j := 0; j < apps; j++ {
+ if _, err := picker.store.CreateAppIn(a.ID, fmt.Sprintf("app%d", j), "shop@example.com", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ }
+ for j := 0; j < instances; j++ {
+ if _, err := picker.cfg.Releases.Put(t.Context(), provision.RecordKey(a.Sqid, "app0", fmt.Sprintf("app0-%d.example.com", j)), []byte(`{}`), ""); err != nil {
+ t.Fatal(err)
+ }
+ }
+ }
singleArgs, _ := json.Marshal(map[string]string{"target": singleServer.URL, "session": one.session, "cookie": one.cookie,
- "capacityTarget": capacityServer.URL, "capacitySession": room.session, "capacityCookie": room.cookie})
- ctx, cancel := context.WithTimeout(t.Context(), 120*time.Second)
+ "capacityTarget": capacityServer.URL, "capacitySession": room.session, "capacityCookie": room.cookie,
+ "pickerTarget": pickerServer.URL, "pickerSession": many.session, "pickerCookie": many.cookie})
+ ctx, cancel := context.WithTimeout(t.Context(), 180*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, node, "testdata/demo_claim_resume_browser.mjs", chromium, t.TempDir(), ts.URL, b.session, b.cookie, a.Sqid, os.Getenv("CARLOS_DEMO_CLAIM_SCREENSHOTS"), string(singleArgs))
output, err := cmd.CombinedOutput()
diff --git a/internal/console/demo_claim_resume_test.go b/internal/console/demo_claim_resume_test.go
index c0a347595..f070e339d 100644
--- a/internal/console/demo_claim_resume_test.go
+++ b/internal/console/demo_claim_resume_test.go
@@ -83,9 +83,20 @@ func TestDemoClaimSelectStepUpRoundTrip(t *testing.T) {
t.Fatal("resume must consume stash without claiming")
}
w = b.request("GET", "/demo/claim", nil)
- if !strings.Contains(w.Body.String(), `data-auto-submit`) || !strings.Contains(w.Body.String(), `value="`+a.Sqid+`" checked`) {
+ if !strings.Contains(w.Body.String(), `data-auto-submit`) || !strings.Contains(w.Body.String(), `<input type="hidden" name="accountId" value="`+a.Sqid+`">`) {
t.Fatalf("selected account was not resumed: %s", w.Body)
}
+ // The first paint of a resumed choice is the progress view: no
+ // account list flashes up before the script posts the choice.
+ body := w.Body.String()
+ for _, banned := range []string{`type="radio"`, `class="claim-card"`, demoClaimUX24, `id="claim-accounts"`, demoClaimIdentityLabel} {
+ if strings.Contains(body, banned) {
+ t.Errorf("auto-submit first paint shows the account list (%q)", banned)
+ }
+ }
+ if !strings.Contains(body, `<div id="claim-progress" data-stage="0" data-pending`) || !strings.Contains(body, `<h1 id="claim-heading" tabindex="-1">`+demoClaimPageTitle+`</h1>`) || !strings.Contains(body, "<noscript><button type=\"submit\">") {
+ t.Errorf("auto-submit first paint is not the progress view with a no-script button: %s", body)
+ }
if claimBrowserCount(t, s, "demo_claim_ops") != 0 {
t.Fatal("GET claimed")
}
@@ -107,6 +118,11 @@ func TestDemoClaimSelectStepUpRoundTrip(t *testing.T) {
if !strings.Contains(w.Body.String(), demoClaimCopying) {
t.Fatal("no claiming state")
}
+ // Reload or back after the automatic post renders the claim's
+ // progress, never the resumed choice again: nothing replays it.
+ if strings.Contains(w.Body.String(), "data-auto-submit") || strings.Contains(w.Body.String(), "data-pending") {
+ t.Fatal("a reload after the automatic post would post the choice again")
+ }
b.post("/demo/claim/select", url.Values{"accountId": {a.Sqid}})
if claimBrowserCount(t, s, "demo_claim_ops") != 1 {
t.Fatal("duplicate reservation")
diff --git a/internal/console/demo_claim_status_page.go b/internal/console/demo_claim_status_page.go
index 782719b1a..bd8f04f0f 100644
--- a/internal/console/demo_claim_status_page.go
+++ b/internal/console/demo_claim_status_page.go
@@ -38,6 +38,12 @@ func (s *Server) handleDemoClaimBrowserStatus(w http.ResponseWriter, r *http.Req
}
state, step := demoClaimProgressStep(op.Phase)
body := map[string]any{"state": state, "step": step}
+ // Past the commit the claim cannot be rolled back (demo_claim_transfer.go
+ // refuses an abort after it), and finishing may run past the deadline, so
+ // the page must not judge it by the rollback deadline.
+ if state == "claiming" {
+ body["committed"] = op.Phase == "committed"
+ }
if state == "claimed" {
body["url"] = "https://" + s.canon(r.Context()).host(op.Target.Host) // as the platform shows it (canonical.go)
}
diff --git a/internal/console/demo_claim_ux_test.go b/internal/console/demo_claim_ux_test.go
index d161b94b2..9763241cb 100644
--- a/internal/console/demo_claim_ux_test.go
+++ b/internal/console/demo_claim_ux_test.go
@@ -27,8 +27,8 @@ func TestDemoClaimUXProductionPages(t *testing.T) {
a := claimAccount(t, s, 801, "shop@example.com", RoleOwner)
s.cfg.PlanCatalog = examplePlanCatalog(t)
body = b.request("GET", "/demo/claim", nil).Body.String()
- if !strings.Contains(body, `class="claim-slots"`) {
- t.Error("no capacity drawing")
+ if !strings.Contains(body, `<span class="claim-usage">0 of 3 running</span>`) || !strings.Contains(body, `<span class="chip chip-health-ok">Has room</span>`) {
+ t.Error("no capacity figure or status chip")
}
if w := b.post("/demo/claim/select", url.Values{"accountId": {a.Sqid}}); w.Code != 303 {
t.Fatalf("select: %d %s", w.Code, w.Body)
@@ -43,7 +43,7 @@ func TestDemoClaimUXProductionPages(t *testing.T) {
t.Error("ticket lost after selection")
}
if phase == "done" {
- for _, want := range []string{"Open your app", "Still in the chat where you built it?", "No saved source for this app.", `data-state="claimed"`} {
+ for _, want := range []string{demoClaimOpenConsole, `class="claim-open"`, "Still in the chat where you built it?", "No saved source for this app.", `data-state="claimed"`} {
if !strings.Contains(body, want) {
t.Errorf("result missing %q", want)
}
diff --git a/internal/console/static/demo_claim.js b/internal/console/static/demo_claim.js
index a2edb27cb..209233e6e 100644
--- a/internal/console/static/demo_claim.js
+++ b/internal/console/static/demo_claim.js
@@ -29,6 +29,9 @@
const working = [];
addEventListener("pageshow", event => {
if (!event.persisted) return;
+ // Back to a resumed choice's first paint: it was posted already and is
+ // never posted again; read the claim's real state instead.
+ if (document.querySelector("#claim-progress[data-pending]")) { location.replace("/demo/claim"); return; }
submitted = false;
for (const [button, label] of working) {
button.disabled = false;
@@ -83,6 +86,25 @@
button.textContent = selected ? selected.dataset.button : button.dataset.neutral;
};
if (radios.length) { choice.addEventListener("change", update); update(); }
+ // The filter only hides rows: a checked radio stays checked out of view,
+ // and the search field has no name, so it is never posted.
+ const search = document.getElementById("claim-search");
+ if (search) {
+ const rows = [...choice.querySelectorAll("#claim-accounts .claim-card")];
+ const empty = document.getElementById("claim-search-empty");
+ search.parentElement.hidden = false;
+ search.addEventListener("keydown", event => { if (event.key === "Enter") event.preventDefault(); });
+ search.addEventListener("input", () => {
+ const query = search.value.trim().toLocaleLowerCase();
+ let shown = 0;
+ for (const row of rows) {
+ const name = row.querySelector(".claim-row-name").textContent.toLocaleLowerCase();
+ row.hidden = query !== "" && !name.includes(query);
+ if (!row.hidden) shown++;
+ }
+ empty.hidden = shown > 0;
+ });
+ }
}
const clock = claim.querySelector("time[datetime]");
if (clock) {
@@ -130,8 +152,98 @@
let stage = Number(progress.dataset.stage), since = performance.now(), failures = 0;
const setStatus = text => { if (status.textContent !== text) status.textContent = text; };
const hold = async () => { await wait(Math.max(0, minimum - (performance.now() - since))); };
+
+ // Reassurance while the server works. The bar is honest: each stage owns
+ // a band ending at the next stage's mark, and within it the bar eases
+ // toward that mark over the stage's usual time without reaching it. It
+ // never moves back. The server's stage is the only thing that crosses a mark.
+ const opened = performance.now();
+ const fill = progress.querySelector(".claim-bar i");
+ const elapsed = document.getElementById("claim-elapsed");
+ const stuck = document.getElementById("claim-stuck");
+ const calm = matchMedia("(prefers-reduced-motion: reduce)");
+ const marks = [0, 0.1, 0.55, 1];
+ const pace = [5000, 15000, 30000];
+ let entered = opened, shown = marks[Math.min(stage, 3)], rotation = 0, claimingPolls = 0, timers = [];
+ // Stuck: the server undoes an unfinished claim at its deadline (5 minutes
+ // after the account was chosen) and then reports "stopping". A claim
+ // that, on two polls, still reports progress 90 s after that deadline is
+ // stuck. With no deadline to read, 6.5 minutes without a stage change is
+ // (the 5-minute deadline plus the same 90 s).
+ const deadline = progress.dataset.deadlineIn === undefined ? NaN : opened + Number(progress.dataset.deadlineIn) * 1000;
+ // Committed: past the irreversible commit nothing is undone and the
+ // deadline no longer applies; the server finishes on its own retries,
+ // which back off up to minutes apart. Two minutes after the commit the
+ // page says so (the app is theirs, still finishing), never "undone".
+ const finishing = document.getElementById("claim-finishing");
+ const committedFor = progress.dataset.committedFor;
+ let committedAt = committedFor === undefined ? NaN : opened - Number(committedFor) * 1000;
+ const committed = () => Number.isFinite(committedAt);
+ const isStuck = () => {
+ if (committed()) return false;
+ return Number.isFinite(deadline)
+ ? claimingPolls >= 2 && performance.now() > deadline + 90000
+ : performance.now() - entered > 390000;
+ };
+ const isSlowFinish = () => committed() && claimingPolls >= 2 && performance.now() - committedAt > 120000;
+ const draw = () => {
+ if (fill) {
+ let value = 1;
+ if (committed() && stage === 2) {
+ // Verified and committed: only the last steps remain.
+ value = 0.9 + 0.1 * 0.97 * (1 - Math.exp(-(performance.now() - Math.max(committedAt, entered)) / 10000));
+ } else if (stage < 3) {
+ const from = marks[stage], to = marks[stage + 1];
+ value = from + (to - from) * 0.97 * (1 - Math.exp(-(performance.now() - entered) / pace[stage]));
+ }
+ shown = Math.max(shown, value);
+ fill.style.transform = `scaleX(${Math.max(shown, 0.03)})`;
+ fill.parentElement.setAttribute("aria-valuenow", String(Math.round(shown * 100)));
+ }
+ const seconds = Math.floor((performance.now() - opened) / 1000);
+ if (elapsed && seconds >= 30) {
+ elapsed.textContent = elapsed.dataset.template.replace("{elapsed}", seconds >= 60 ? `${Math.floor(seconds / 60)} min ${seconds % 60} s` : `${seconds} s`);
+ elapsed.hidden = false;
+ }
+ };
+ const restoreDetails = () => {
+ rotation = 0;
+ for (const detail of progress.querySelectorAll(".claim-step-detail[data-original]")) {
+ detail.textContent = detail.dataset.original;
+ detail.classList.remove("is-swapping");
+ }
+ };
+ const rotate = () => {
+ const step = progress.querySelector('[aria-current="step"][data-hints]');
+ const detail = step?.querySelector(".claim-step-detail");
+ // Once stuck, the page stops saying it is still working; once
+ // committed, the starting hints (placing, checking) are already done.
+ if (!detail || progress.dataset.stuck !== undefined || committed()) return;
+ if (detail.dataset.original === undefined) detail.dataset.original = detail.textContent;
+ const lines = [detail.dataset.original, ...step.dataset.hints.split("\n").filter(Boolean)];
+ rotation = (rotation + 1) % lines.length;
+ const swap = () => { detail.textContent = lines[rotation]; detail.classList.remove("is-swapping"); };
+ if (calm.matches) swap();
+ else { detail.classList.add("is-swapping"); setTimeout(swap, 200); }
+ };
+ // Stop the reassurance when the claim ends either way.
+ const settle = () => {
+ for (const timer of timers) clearInterval(timer);
+ timers = [];
+ restoreDetails();
+ stuck.hidden = true;
+ finishing.hidden = true;
+ delete progress.dataset.stuck;
+ };
+ draw();
+ timers.push(setInterval(draw, 500), setInterval(rotate, 4500));
+
const setStage = async n => {
stage = n;
+ entered = performance.now();
+ shown = Math.max(shown, marks[Math.min(n, 3)]);
+ restoreDetails();
+ draw();
progress.dataset.stage = String(n);
for (const step of progress.querySelectorAll("[data-step]")) {
const k = Number(step.dataset.step);
@@ -164,10 +276,14 @@
const url = new URL(result.url);
if (url.protocol !== "https:" || url.username || url.password) throw new Error();
const finished = document.getElementById("claim-finished");
- for (const link of claim.querySelectorAll("a.claim-new, .claim-open")) link.href = url.href;
+ // The fresh page carries the console link, which only it can name.
+ const actions = page.querySelector(".claim-result");
+ if (actions) claim.querySelector(".claim-result")?.replaceWith(document.importNode(actions, true));
+ for (const link of claim.querySelectorAll(".claim-open")) link.href = url.href;
+ for (const text of claim.querySelectorAll(".claim-open-address")) text.textContent = url.origin;
const address = claim.querySelector(".claim-address .claim-new");
if (address) address.textContent = url.host;
- claim.querySelector(".claim-result-address").textContent = url.href;
+ settle();
heading.textContent = claim.dataset.completeHeading;
claim.dataset.state = "claimed";
claim.querySelector(".claim-ticket")?.classList.add("is-settled");
@@ -176,7 +292,7 @@
progress.hidden = true;
setTimeout(() => claim.classList.remove("is-celebrating"), 1500);
};
- reload.hidden = true;
+ if (reload) reload.hidden = true;
const poll = async () => {
try {
const response = await fetch("/demo/claim/status", {
@@ -187,9 +303,13 @@
const result = await response.json();
if (!((result.state === "claiming" && [0, 1, 2].includes(result.step)) ||
(["stopping", "aborted"].includes(result.state) && result.step === 0) ||
- (result.state === "claimed" && result.step === 3))) throw new Error();
+ (result.state === "claimed" && result.step === 3)) ||
+ (result.committed !== undefined && typeof result.committed !== "boolean")) throw new Error();
if (result.state === "stopping" || result.state === "aborted") {
await hold();
+ settle();
+ progress.querySelector(".claim-bar")?.remove();
+ elapsed?.remove();
const failed = progress.querySelector('[aria-current="step"]');
if (failed) { failed.classList.add("is-failed"); failed.removeAttribute("aria-current"); }
progress.dataset.stage = "0";
@@ -200,20 +320,34 @@
} else {
await advance(result.step);
if (result.state === "claimed") { await hold(); await finish(result); return; }
+ claimingPolls++;
+ // The commit is the one-way boundary: from here the rollback
+ // promise is false, so its stuck box goes for good.
+ if (result.committed === true && !committed()) {
+ committedAt = performance.now();
+ stuck.hidden = true;
+ delete progress.dataset.stuck;
+ restoreDetails();
+ }
+ if (isStuck() && stuck.hidden) { stuck.hidden = false; progress.dataset.stuck = ""; restoreDetails(); }
+ if (isSlowFinish()) finishing.hidden = false;
}
failures = 0;
} catch (_) {
if (++failures >= 3) {
+ settle();
status.classList.remove("claim-sr-only");
setStatus(progress.dataset.pollFailed);
reload.hidden = false;
return;
}
}
- setTimeout(poll, 3000);
+ // Once stuck, keep checking, more slowly: a late finish still lands.
+ setTimeout(poll, stuck.hidden && finishing.hidden ? 3000 : 10000);
};
- // The initial stage is already painted by the server.
- paint().then(() => { since = performance.now(); setTimeout(poll, minimum); });
+ // The initial stage is already painted by the server. A selection still
+ // to be posted has no operation to poll yet: the form below posts it.
+ if (progress.dataset.pending === undefined) paint().then(() => { since = performance.now(); setTimeout(poll, minimum); });
}
if (!token) {
if (claim.dataset.reveal === "true" && claim.dataset.state === "claimed") {
@@ -225,13 +359,13 @@
}
if (opening) opening.hidden = true;
if (missing) missing.hidden = false;
+ // A resumed selection: the server painted the progress view first, so
+ // post the chosen account straight away. It goes through the page's one
+ // submit guard like a manual choice.
const selection = document.querySelector("form[data-auto-submit]");
if (selection) {
selection.removeAttribute("data-auto-submit");
- const status = document.getElementById("claim-resuming");
- try {
- if (selection.checkValidity()) { status.hidden = false; selection.requestSubmit(); }
- } catch (_) { status.hidden = true; }
+ selection.requestSubmit();
}
return;
}
diff --git a/internal/console/templates/demo_claim.html b/internal/console/templates/demo_claim.html
index 13788753c..040865493 100644
--- a/internal/console/templates/demo_claim.html
+++ b/internal/console/templates/demo_claim.html
@@ -11,14 +11,21 @@
#claim .claim-summary strong, #claim .claim-summary a { display: block; }
#claim .claim-summary p { margin: 0.5rem 0 0; }
#claim fieldset { border: 0; min-width: 0; margin: 1.5rem 0; }
-#claim legend { font-weight: 600; margin-bottom: 0.75rem; }
-#claim .claim-card { display: flex; align-items: flex-start; gap: 0.75rem; border: 1px solid var(--rule); border-radius: var(--rst-radius-sm); padding: 1rem; margin: 0 0 0.65rem; cursor: pointer; }
+#claim legend { margin-bottom: 0.6rem; font: 600 .78rem var(--mono); text-transform: uppercase; letter-spacing: .05em; color: var(--muted); }
+#claim .claim-card { display: grid; grid-template-columns: auto minmax(0,1fr) auto; align-items: center; gap: .3rem .75rem; border: 1px solid var(--rule); border-radius: var(--rst-radius-sm); padding: .55rem .8rem; margin: 0 0 .4rem; cursor: pointer; }
#claim .claim-card:has(:checked) { background: var(--accent-soft); border-color: var(--accent); }
#claim .claim-card:has(:focus-visible) { outline: 2px solid var(--accent); outline-offset: 2px; }
#claim [tabindex="-1"]:focus { outline: none; }
#claim .claim-card:has(:disabled) { color: var(--muted); background: var(--rst-surface-2); cursor: not-allowed; }
-#claim .claim-card input { flex: none; width: 1.1rem; height: 1.1rem; margin-top: 0.25rem; accent-color: var(--accent); }
-#claim .claim-card strong, #claim .claim-card .claim-detail { display: block; }
+#claim .claim-card input { flex: none; width: 1.1rem; height: 1.1rem; margin: 0; accent-color: var(--accent); }
+#claim .claim-row-name { font-weight: 600; overflow-wrap: anywhere; }
+#claim .claim-row-meta { display: flex; flex-wrap: wrap; align-items: center; justify-content: flex-end; gap: .4rem .5rem; font-size: .8rem; color: var(--muted); }
+#claim .claim-row-meta .chip { margin: 0; }
+#claim .claim-row-note { grid-column: 2 / -1; font-size: .85rem; color: var(--muted); }
+@media (max-width: 30rem) { #claim .claim-row-meta { grid-column: 2 / -1; justify-content: flex-start; } }
+#claim .claim-search { margin: 0 0 .75rem; }
+#claim .claim-search input { display: block; width: 100%; min-height: 44px; }
+#claim .claim-search-empty { color: var(--muted); }
#claim .claim-detail { color: var(--muted); font-size: 0.9rem; }
#claim .claim-single { margin: 1.5rem 0; }
#claim .claim-single p { margin-bottom: 0.35rem; }
@@ -52,7 +59,7 @@
#claim .claim-tile svg { width: 26px; height: 26px; }
#claim .claim-ticket-body { min-width: 0; display: grid; gap: .2rem; }
#claim .claim-address { display: grid; font: .84rem/1.5 ui-monospace,monospace; }
-#claim .claim-address a { grid-area: 1/1; color: var(--muted); text-decoration: none; }
+#claim .claim-address > * { grid-area: 1/1; color: var(--muted); text-decoration: none; }
#claim .claim-life { display: flex; align-items: center; gap: .4rem; font-size: .85rem; color: var(--muted); }
#claim .claim-clock { width: 16px; height: 16px; fill: none; stroke: var(--accent); stroke-width: 1.8; }
#claim .claim-tick, #claim .claim-new { display: none; }
@@ -63,11 +70,19 @@
#claim #code { font-size: 1.6rem; letter-spacing: .3em; text-align: center; }
#claim .claim-keymail { margin: 1rem 0; padding: 1rem 0; border-block: 1px solid var(--rule); font-size: .9rem; }
#claim .claim-keymail p { color: var(--muted); margin: .4rem 0 0; }
-#claim .claim-single { display: block; }
-#claim .claim-slots { display: flex; gap: 3px; flex-wrap: wrap; margin: .5rem 0; }
-#claim .claim-slots i { width: 18px; height: 5px; border-radius: 3px; background: var(--rule); }
-#claim .claim-slots i.used { background: var(--accent); }
-#claim .claim-card:has(:disabled) .used { background: var(--claim-warn); }
+#claim .claim-single { grid-template-columns: minmax(0,1fr) auto; cursor: default; }
+#claim .claim-single p { margin: 0; }
+@media (max-width: 30rem) { #claim .claim-single .claim-row-meta { grid-column: 1 / -1; } }
+#claim .claim-bar { height: 6px; border-radius: 3px; background: var(--rule); overflow: hidden; margin: 0 0 .4rem; }
+#claim .claim-bar i { display: block; height: 100%; border-radius: 3px; background: var(--accent); transform-origin: left; transform: scaleX(.03); transition: transform .5s linear; }
+#claim [data-stage="1"] .claim-bar i { transform: scaleX(.1); }
+#claim [data-stage="2"] .claim-bar i { transform: scaleX(.55); }
+#claim .claim-elapsed { font-size: .85rem; color: var(--muted); margin: 0 0 1rem; }
+#claim .claim-step-detail { transition: opacity .2s ease; }
+#claim .claim-step-detail.is-swapping { opacity: 0; }
+#claim .claim-stuck { border: 1px solid var(--rule); background: var(--accent-soft); border-radius: var(--rst-radius-sm); padding: 1rem; margin: 0 0 1.5rem; }
+#claim .claim-stuck p { margin: 0 0 .5rem; }
+#claim [data-stuck] [aria-current=step] .claim-node::before, #claim [data-stuck] [aria-current=step] .claim-node::after, #claim [data-stuck] .claim-track, #claim [data-stuck] .claim-track i, #claim [data-stuck] .claim-home { animation: none; }
#claim button[type=submit] { min-height: 50px; border-radius: 10px; }
#claim button.is-working { color: var(--rst-on-accent-fill); opacity: 1; }
#claim button.btn-secondary.is-working { color: var(--accent); }
@@ -86,7 +101,8 @@
#claim [data-stage="2"] .claim-home { animation: claim-breathe 1.6s ease-in-out infinite; }
#claim .claim-steps { list-style: none; padding: 0; }
#claim .claim-steps li { position: relative; min-height: 3rem; padding: 0 0 1.5rem 2.5rem; }
-#claim .claim-step-detail { display: block; font-weight: 400; font-size: .95rem; margin-top: .25rem; }
+#claim .claim-steps strong { font-size: 1.0625rem; }
+#claim .claim-step-detail { display: block; font-weight: 400; font-size: .85rem; margin-top: .25rem; }
#claim .claim-node { position: absolute; left: 0; top: 0; box-sizing: border-box; width: 26px; height: 26px; border: 2px solid var(--muted); border-radius: 50%; }
#claim .claim-node::before { content: ""; position: absolute; inset: -2px; box-sizing: border-box; width: 26px; height: 26px; border: 2px solid transparent; border-radius: 50%; transform-origin: center; }
#claim .claim-node::after { content: ""; position: absolute; inset: 0; margin: auto; width: 8px; height: 8px; background: var(--accent); border-radius: 50%; opacity: 0; }
@@ -98,11 +114,14 @@
#claim .claim-steps .is-done svg { opacity: 1; }
#claim .claim-steps .is-failed { color: var(--claim-warn); }
#claim .claim-steps .is-failed .claim-node { border-color: var(--claim-warn); }
-#claim .claim-result .claim-open { display: block; width: 100%; text-align: center; font-size: 2rem; font-weight: 700; padding: 1.25rem; border-radius: 12px; }
-#claim .claim-result-address { text-align: center; font: .85rem/1.5 ui-monospace,monospace; color: var(--muted); }
+#claim .claim-result { display: flex; flex-wrap: wrap; align-items: center; gap: .75rem 1.25rem; }
+#claim .claim-result .btn { border-radius: 10px; }
+#claim .claim-result .claim-open { display: inline-block; max-width: 100%; padding-block: .6rem; font: .9rem/1.4 ui-monospace,monospace; overflow-wrap: anywhere; }
+#claim .claim-result .claim-open .icon { width: 1em; height: 1em; margin-left: .35em; vertical-align: -.125em; }
#claim .claim-next { margin-top: 2rem; padding-top: 1.5rem; border-top: 1px solid var(--rule); }
-#claim .claim-next h2 { font-size: 1.15rem; }
-#claim .claim-next h3 { font-size: 1rem; margin-bottom: .3rem; }
+#claim .claim-next h2 { font-size: 1.4rem; }
+#claim .claim-next h3 { font-size: 1.0625rem; margin-bottom: .3rem; }
+#claim .claim-next p { font-size: .925rem; }
#claim .claim-next p { color: var(--muted); }
#claim .claim-paste { display: grid; grid-template-columns: minmax(0,1fr) auto; align-items: center; gap: .75rem; border: 1px solid var(--rule); padding: .6rem; border-radius: 10px; background: var(--rst-surface-2); }
#claim .claim-paste code { background: transparent; padding: 0; white-space: normal; overflow-wrap: anywhere; font-size: .84rem; }
@@ -153,11 +172,11 @@
{{if .DemoName}}<div class="claim-ticket{{if eq .State "claimed"}} is-settled{{end}}">
<span class="claim-tile" aria-hidden="true">{{icon "layers"}}</span>
<div class="claim-ticket-body"><strong>{{.DemoName}}</strong>
-<span class="claim-address"><a class="claim-old" href="https://{{.DemoHost}}" rel="noreferrer">{{.DemoHost}}</a><a class="claim-new" href="{{.URL}}" rel="noreferrer">{{.URL}}</a></span>
+<span class="claim-address"><a class="claim-old" href="https://{{.DemoHost}}" rel="noreferrer">{{.DemoHost}}</a><span class="claim-new">{{.URL}}</span></span>
<span class="claim-life"><svg class="claim-clock" viewBox="0 0 16 16" aria-hidden="true"><circle cx="8" cy="8" r="6"/><path class="claim-hands" d="M8 4v4l3 2"/><path class="claim-tick" d="M4 8l3 3 5-6"/></svg><time class="claim-old" datetime="{{.EndTime}}" title="{{.EndTime}}"><span aria-hidden="true">{{.TimeLeft}}</span><span class="claim-sr-only">{{.TimeLeftAccessible}}</span></time><span class="claim-new">{{.Copy.done}}</span></span></div>
<span class="claim-burst" aria-hidden="true"><i></i><i></i><i></i><i></i><i></i><i></i><i></i><i></i></span>
</div>{{end}}
-<h1 id="claim-heading" tabindex="-1">{{if eq .State "claimed"}}{{.Copy.completeHeading}}{{else if or (eq .State "stopping") (eq .State "aborted")}}{{.Copy.failureHeading}}{{else if .EmailPending}}{{.Copy.codeHeading}}{{else if and .Address (gt .Eligible 1)}}{{.Copy.accountsHeading}}{{else if eq .State "proof"}}{{.Copy.heading}}{{else}}{{.Copy.title}}{{end}}</h1>
+<h1 id="claim-heading" tabindex="-1">{{if eq .State "claimed"}}{{.Copy.completeHeading}}{{else if or (eq .State "stopping") (eq .State "aborted")}}{{.Copy.failureHeading}}{{else if .AutoSubmit}}{{.Copy.title}}{{else if .EmailPending}}{{.Copy.codeHeading}}{{else if and .Address (gt .Eligible 1)}}{{.Copy.accountsHeading}}{{else if eq .State "proof"}}{{.Copy.heading}}{{else}}{{.Copy.title}}{{end}}</h1>
{{if .Error}}<p role="alert">{{.Error}}</p><p><a href="/demo/claim">{{.Copy.back}}</a></p>{{end}}
{{if eq .State "no_accounts"}}<p>{{.Copy.identity}} <strong>{{.Address}}</strong></p><p>{{.Copy.noAccounts}}</p>
<fieldset class="claim-unavailable"><legend>{{.Copy.accountsLabel}}</legend>{{range .Accounts}}{{template "claim_card" .}}{{end}}</fieldset>{{end}}
@@ -168,23 +187,12 @@
<div id="claim-expired-next" hidden><p>{{.Copy.newDemo}}</p><div class="claim-paste"><code id="claim-new-demo">{{.Copy.newDemoLine}}</code><button class="btn-sm btn-secondary" type="button" data-copy-target="claim-new-demo" data-copy="{{.Copy.copy}}" data-copied="{{.Copy.copied}}" hidden>{{.Copy.copy}}</button></div></div>
<p id="claim-kept-next" hidden><a href="/?next=%2Fdemo%2Fclaim">{{.Copy.consoleSignin}}</a></p>
{{if eq .State "disabled"}}<p>{{.Copy.disabled}}</p>{{end}}
-{{if or (eq .State "claiming") (eq .State "stopping")}}
-<div id="claim-progress" data-stage="{{.Step}}" data-failure-heading="{{.Copy.failureHeading}}" data-neutral="{{.Copy.resuming}}" data-stopping="{{.Copy.stopping}}" data-copying="{{.Copy.copying}}" data-starting="{{.Copy.starting}}" data-done="{{.Copy.done}}" data-aborted="{{.Copy.aborted}}" data-poll-failed="{{.Copy.pollFailed}}">
-<p id="claim-status"{{if gt .Step 0}} class="claim-sr-only"{{end}} role="status" aria-live="polite">{{if eq .State "stopping"}}{{.Copy.stopping}}{{else if eq .Step 2}}{{.Copy.starting}}{{else if eq .Step 1}}{{.Copy.copying}}{{else}}<span class="claim-spinner" aria-hidden="true"></span>{{.Copy.resuming}}{{end}}</p>
-<div class="claim-transit" aria-hidden="true"><span>{{icon "layers"}}</span><span class="claim-track"><i></i><i></i><i></i></span><span class="claim-home">{{icon "server"}}</span></div>
-<ol class="claim-steps">
-<li data-step="1"{{if gt .Step 1}} class="is-done"{{end}}{{if eq .Step 1}} aria-current="step"{{end}}><span class="claim-node" aria-hidden="true"><svg viewBox="0 0 16 16"><path d="M3 8l3 3 7-7"/></svg></span><strong>{{.Copy.copying}}</strong><span class="claim-step-detail">{{.Copy.copyingDetail}}</span></li>
-<li data-step="2"{{if gt .Step 2}} class="is-done"{{end}}{{if eq .Step 2}} aria-current="step"{{end}}><span class="claim-node" aria-hidden="true"><svg viewBox="0 0 16 16"><path d="M3 8l3 3 7-7"/></svg></span><strong>{{.Copy.starting}}</strong><span class="claim-step-detail">{{.Copy.startingDetail}}</span></li>
-<li data-step="3"{{if eq .Step 3}} aria-current="step"{{end}}><span class="claim-node" aria-hidden="true"><svg viewBox="0 0 16 16"><path d="M3 8l3 3 7-7"/></svg></span><strong>{{.Copy.done}}</strong></li>
-</ol>
-
-<a id="claim-reload" href="/demo/claim">{{.Copy.reload}}</a>
-</div>{{end}}
+{{if or (eq .State "claiming") (eq .State "stopping")}}{{template "claim_progress" .}}{{end}}
{{if eq .State "aborted"}}<p>{{.Copy.aborted}}</p>{{end}}
{{if or (eq .State "claimed") (eq .State "claiming") (eq .State "stopping")}}
<div id="claim-finished"{{if ne .State "claimed"}} hidden{{end}}>
<p>{{.Copy.completeDetail}}</p>
-<p class="claim-result"><a class="btn claim-open" href="{{.URL}}" rel="noreferrer">{{.Copy.open}}</a></p><p class="claim-result-address">{{.URL}}</p>
+<p class="claim-result">{{with .ConsoleURL}}<a class="btn claim-console" href="{{.}}">{{$.Copy.openConsole}}</a>{{end}}<a class="claim-open" href="{{.URL}}" target="_blank" rel="noopener noreferrer"><span class="claim-open-address">{{.URL}}</span>{{icon "external-link"}}<span class="claim-sr-only"> {{.Copy.opensNewTab}}</span></a></p>
{{if .AccountSqid}}<section class="claim-next"><h2>{{.Copy.keepGoing}}</h2>
{{if .AccountSqid}}<h3>{{.Copy.sameChat}}</h3><p>{{.Copy.sameChatLine}}</p>
{{if .SourceSteps}}<h3>{{.Copy.agentHeading}}</h3><p>{{.Copy.agentDetail}}</p>
@@ -197,23 +205,31 @@
{{end}}
{{if and .HasIntent .CanClaim}}
{{if .Address}}
+{{if .AutoSubmit}}{{template "claim_progress" .}}
+<form method="post" action="/demo/claim/select" data-auto-submit>
+<input type="hidden" name="nonce" value="{{.Nonce}}"><input type="hidden" name="csrf" value="{{.CSRF}}">
+{{if .SelectedAccount}}<input type="hidden" name="accountId" value="{{.SelectedAccount}}">{{else}}<input type="hidden" name="create" value="1">{{end}}
+<noscript><button type="submit">{{.Copy.confirm}}</button></noscript>
+</form>
+{{else}}
<p>{{.Copy.identity}} <strong>{{.Address}}</strong></p>
-<form method="post" action="/demo/claim/select"{{if .AutoSubmit}} data-auto-submit{{end}}>
+<form method="post" action="/demo/claim/select">
<input type="hidden" name="nonce" value="{{.Nonce}}"><input type="hidden" name="csrf" value="{{.CSRF}}">
{{if .Single}}
-<fieldset><legend>{{.Copy.accountsLabel}}</legend><div class="claim-single claim-card"><p><strong>{{.Copy.destination}}</strong></p>{{with .Single.Plan}}<p class="claim-detail">{{.}}</p>{{end}}{{template "claim_slots" .Single}}{{with .Single.Room}}<p class="claim-detail">{{.}}</p>{{end}}</div>
+<fieldset><legend>{{.Copy.accountsLabel}}</legend><div class="claim-single claim-card"><p><strong>{{.Copy.destination}}</strong></p>{{template "claim_meta" .Single}}</div>
<input type="hidden" name="accountId" value="{{.Single.Sqid}}">
{{range .Accounts}}{{if .Reason}}{{template "claim_card" .}}{{end}}{{end}}</fieldset>
{{else if .Accounts}}
-<p>{{.Copy.accountsIntro}}</p><fieldset><legend>{{.Copy.accountsLabel}}</legend>
+<p>{{.Copy.accountsIntro}}</p>
+{{if .Searchable}}<p class="claim-search" hidden><input type="search" id="claim-search" aria-label="{{.Copy.searchLabel}}" placeholder="{{.Copy.searchLabel}}" aria-controls="claim-accounts" autocomplete="off" spellcheck="false"></p>{{end}}
+<fieldset id="claim-accounts"><legend>{{.Copy.accountsLabel}}</legend>
{{range .Accounts}}
-<label class="claim-card"><input type="radio" name="accountId" value="{{.Sqid}}"{{if eq .Sqid $.SelectedAccount}} checked{{end}}{{if .Reason}} disabled{{else}} required{{end}} data-button="{{.Button}}">
-<span><strong>{{.Name}}</strong>{{with .Plan}}<span class="claim-detail">{{.}}</span>{{end}}{{template "claim_slots" .}}{{with .Room}}<span class="claim-detail">{{.}}</span>{{end}}{{with .Reason}}<span class="claim-detail">{{.}}</span>{{end}}</span></label>
-{{end}}</fieldset>
+<label class="claim-card"><input type="radio" name="accountId" value="{{.Sqid}}"{{if .Reason}} disabled{{else}} required{{end}} data-button="{{.Button}}"><span class="claim-row-name">{{.Name}}</span>{{template "claim_meta" .}}{{with .Note}}<span class="claim-row-note">{{.}}</span>{{end}}</label>
+{{end}}{{if .Searchable}}<p id="claim-search-empty" class="claim-search-empty" aria-live="polite" hidden>{{.Copy.searchEmpty}}</p>{{end}}</fieldset>
{{else}}<p>{{.Copy.new}}</p><input type="hidden" name="create" value="1">{{end}}
-<p id="claim-resuming" role="status" hidden>{{.Copy.resuming}}</p>
<button type="submit" data-working="{{.Copy.selectWorking}}" data-neutral="{{.Copy.choose}}">{{.Copy.confirm}}</button>
</form>
+{{end}}
{{else}}
{{if .EmailPending}}
<p class="claim-intro">{{.Copy.codeIntro}}</p>
@@ -243,8 +259,24 @@
</html>
{{define "claim_card"}}
-<label class="claim-card"><input type="radio" name="accountId" value="{{.Sqid}}" disabled>
-<span><strong>{{.Name}}</strong>{{with .Plan}}<span class="claim-detail">{{.}}</span>{{end}}{{template "claim_slots" .}}{{with .Room}}<span class="claim-detail">{{.}}</span>{{end}}<span class="claim-detail">{{.Reason}}</span></span></label>
+<label class="claim-card"><input type="radio" name="accountId" value="{{.Sqid}}" disabled><span class="claim-row-name">{{.Name}}</span>{{template "claim_meta" .}}{{with .Note}}<span class="claim-row-note">{{.}}</span>{{end}}</label>
{{end}}
-{{define "claim_slots"}}{{if gt .Limit 0}}{{if .Slots}}<span class="claim-slots" aria-hidden="true">{{range .Slots}}<i{{if .}} class="used"{{end}}></i>{{end}}</span>{{else}}<meter min="0" max="{{.Limit}}" value="{{.Used}}" aria-label="{{.Room}}">{{.Used}} / {{.Limit}}</meter>{{end}}<span class="claim-detail">{{.Used}} / {{.Limit}}</span>{{end}}{{end}}
+{{define "claim_meta"}}<span class="claim-row-meta">{{with .Plan}}<span class="chip chip-env">{{.}}</span>{{end}}{{with .Usage}}<span class="claim-usage">{{.}}</span>{{end}}{{with .Status}}<span class="chip {{$.StatusClass}}">{{.}}</span>{{end}}</span>{{end}}
+
+{{define "claim_progress"}}
+<div id="claim-progress" data-stage="{{.Step}}"{{if .AutoSubmit}} data-pending{{end}}{{with .CommittedFor}} data-committed-for="{{.}}"{{end}}{{with .DeadlineIn}} data-deadline-in="{{.}}"{{end}} data-failure-heading="{{.Copy.failureHeading}}" data-neutral="{{.Copy.resuming}}" data-stopping="{{.Copy.stopping}}" data-copying="{{.Copy.copying}}" data-starting="{{.Copy.starting}}" data-done="{{.Copy.done}}" data-aborted="{{.Copy.aborted}}" data-poll-failed="{{.Copy.pollFailed}}">
+<p id="claim-status"{{if gt .Step 0}} class="claim-sr-only"{{end}} role="status" aria-live="polite">{{if eq .State "stopping"}}{{.Copy.stopping}}{{else if eq .Step 2}}{{.Copy.starting}}{{else if eq .Step 1}}{{.Copy.copying}}{{else}}<span class="claim-spinner" aria-hidden="true"></span>{{.Copy.resuming}}{{end}}</p>
+<div id="claim-stuck" class="claim-stuck" role="alert" hidden><p><strong>{{.Copy.stuckHeading}}</strong></p><p class="claim-detail">{{.Copy.stuckDetail}}</p><a class="btn btn-sm" href="/demo/claim">{{.Copy.stuckAction}}</a></div>
+<div id="claim-finishing" class="claim-stuck" role="status" hidden><p><strong>{{.Copy.finishingHeading}}</strong></p><p class="claim-detail">{{.Copy.finishingDetail}}</p></div>
+<div class="claim-transit" aria-hidden="true"><span>{{icon "layers"}}</span><span class="claim-track"><i></i><i></i><i></i></span><span class="claim-home">{{icon "server"}}</span></div>
+{{if ne .State "stopping"}}<div class="claim-bar" role="progressbar" aria-label="{{.Copy.progressLabel}}" aria-valuemin="0" aria-valuemax="100"><i></i></div>
+<p id="claim-elapsed" class="claim-elapsed" data-template="{{.Copy.elapsed}}" hidden></p>{{end}}
+<ol class="claim-steps">
+<li data-step="1" data-hints="{{.Copy.hintsCopying}}"{{if gt .Step 1}} class="is-done"{{end}}{{if eq .Step 1}} aria-current="step"{{end}}><span class="claim-node" aria-hidden="true"><svg viewBox="0 0 16 16"><path d="M3 8l3 3 7-7"/></svg></span><strong>{{.Copy.copying}}</strong><span class="claim-step-detail">{{.Copy.copyingDetail}}</span></li>
+<li data-step="2" data-hints="{{.Copy.hintsStarting}}"{{if gt .Step 2}} class="is-done"{{end}}{{if eq .Step 2}} aria-current="step"{{end}}><span class="claim-node" aria-hidden="true"><svg viewBox="0 0 16 16"><path d="M3 8l3 3 7-7"/></svg></span><strong>{{.Copy.starting}}</strong><span class="claim-step-detail">{{.Copy.startingDetail}}</span></li>
+<li data-step="3"{{if eq .Step 3}} aria-current="step"{{end}}><span class="claim-node" aria-hidden="true"><svg viewBox="0 0 16 16"><path d="M3 8l3 3 7-7"/></svg></span><strong>{{.Copy.done}}</strong></li>
+</ol>
+{{if not .AutoSubmit}}
+<a id="claim-reload" href="/demo/claim">{{.Copy.reload}}</a>{{end}}
+</div>{{end}}
diff --git a/internal/console/testdata/demo_claim_resume_browser.mjs b/internal/console/testdata/demo_claim_resume_browser.mjs
index 0de1d29b7..5b54820ea 100644
--- a/internal/console/testdata/demo_claim_resume_browser.mjs
+++ b/internal/console/testdata/demo_claim_resume_browser.mjs
@@ -51,11 +51,11 @@ async function key(key, code, number) {
await call('Input.dispatchKeyEvent', {type:'keyUp', key, code, windowsVirtualKeyCode:number});
}
async function capture(state) {
- await captureClaim(call, evaluate, screenshots, state);
+ await captureClaim(call, evaluate, screenshots, state, [360, 1280]);
await captureClaim(call, evaluate, '', state, [1100]);
assert.equal(security.length, 0, JSON.stringify(security));
}
-const timer = setTimeout(() => { chrome.kill('SIGKILL'); process.exitCode = 1; }, 115000);
+const timer = setTimeout(() => { chrome.kill('SIGKILL'); process.exitCode = 1; }, 175000);
try {
const created = await call('Target.createTarget', {url:'about:blank'}, false);
session = (await call('Target.attachToTarget', {targetId:created.targetId, flatten:true}, false)).sessionId;
@@ -74,10 +74,12 @@ try {
window.addEventListener('submit', event => {
const form = event.target;
if (form.getAttribute('action') !== '/demo/claim/select') return;
+ // A manual choice submits from the visible list with its button
+ // disabled; a resumed one from the progress view, with no list at all.
claimSubmitted(JSON.stringify({
- disabled:form.querySelector('button[type=submit]').disabled,
- visible:form.getBoundingClientRect().height > 0,
- auto:!document.getElementById('claim-resuming').hidden,
+ disabled:form.querySelector('button[type=submit]')?.disabled ?? null,
+ list:!!document.querySelector('#claim input[type=radio]'),
+ auto:!!document.querySelector('#claim-progress[data-pending]'),
account:new FormData(form).get('accountId')
}));
});
@@ -96,7 +98,7 @@ try {
await capture('one');
await call('Page.navigate',{url:single.target+'/demo/claim?long=1'});
await until('document.readyState === "complete" && document.querySelectorAll(".claim-card").length === 2');
- assert.equal(await evaluate('document.querySelector(".claim-card strong").textContent.length > 100'), true);
+ assert.equal(await evaluate('document.querySelector(".claim-card .claim-row-name").textContent.length > 100'), true);
assert.equal(await evaluate('document.querySelector(".claim-address .claim-old").textContent.length > 100'), true);
await evaluate('document.querySelector(".claim-card input").click()');
await capture('long-name');
@@ -108,9 +110,46 @@ try {
await until('document.readyState === "complete" && document.querySelectorAll(".claim-card").length === 2');
const capacityCards = await evaluate('Array.from(document.querySelectorAll(".claim-card"), card => ({text:card.innerText,disabled:card.querySelector("input").disabled}))');
assert(capacityCards.every(card=>card.disabled));
- assert(capacityCards.some(card=>card.text.includes('Full: 3 of 3 apps and instances in use')));
- assert(capacityCards.some(card=>card.text.includes('Not enough room: 2 of 3 apps and instances in use. This demo needs room for one app and its instance.')));
+ assert(capacityCards.some(card=>card.text.includes('Full') && card.text.includes('3 of 3 running')));
+ assert(capacityCards.some(card=>card.text.includes('No room') && card.text.includes('2 of 3 running') && card.text.includes('Needs room for an app and its instance.')));
await capture('capacity');
+ // The thirty-account picker: one line per account, no sentinel, no meter,
+ // the accounts that can take it first, and a search box that filters.
+ await call('Network.setCookies', {cookies:[
+ {name:'carlos_console_session',value:single.pickerSession,url:single.pickerTarget,path:'/',httpOnly:true,sameSite:'Lax'},
+ {name:'carlos_demo_claim_flow',value:single.pickerCookie,url:single.pickerTarget,path:'/demo/claim',httpOnly:true,secure:true,sameSite:'Lax'}
+ ]});
+ await call('Page.navigate',{url:single.pickerTarget+'/demo/claim'});
+ await until('document.readyState === "complete" && document.querySelectorAll(".claim-card").length === 30');
+ assert.equal(await evaluate('document.body.innerText.includes("2305843009213693951") || !!document.querySelector("meter")'), false, 'sentinel or meter shown');
+ assert.equal(await evaluate('document.querySelector(".claim-search").hidden'), false, 'script did not reveal the search box');
+ assert.deepEqual(await evaluate('(() => { const d = Array.from(document.querySelectorAll(".claim-card input"), i => i.disabled); return d.indexOf(true) === -1 || d.slice(d.indexOf(true)).every(Boolean); })()'), true, 'eligible rows must come first');
+ assert.equal(await evaluate('Array.from(document.querySelectorAll(".claim-card")).some(c => c.innerText.includes("17 running") && c.innerText.includes("Has room"))'), true, 'sponsored row');
+ assert.equal(await evaluate('Array.from(document.querySelectorAll(".claim-card")).some(c => c.innerText.includes("View only") && c.innerText.includes("Ask an owner"))'), true, 'viewer row');
+ // A row is one line at desktop width: its height is a single line plus padding.
+ await call('Emulation.setDeviceMetricsOverride', {width:1280, height:900, deviceScaleFactor:1, mobile:false});
+ assert.equal(await evaluate('Array.from(document.querySelectorAll(".claim-card:has(input:not(:disabled))")).every(c => c.getBoundingClientRect().height < 56)'), true, 'eligible rows wrap at desktop width');
+ await captureClaim(call, evaluate, screenshots, 'picker-30', [360, 1280]);
+ await evaluate('document.querySelector(".claim-card input:not(:disabled)").click()');
+ const pickedLabel = await evaluate('document.querySelector("#claim button[type=submit]").textContent');
+ await evaluate('document.getElementById("claim-search").focus()');
+ for (const ch of 'TEAM-2') await call('Input.insertText', {text:ch});
+ await until('Array.from(document.querySelectorAll(".claim-card")).filter(c => !c.hidden).length === 10');
+ assert.equal(await evaluate('Array.from(document.querySelectorAll(".claim-card")).filter(c => !c.hidden).every(c => c.querySelector(".claim-row-name").textContent.startsWith("team-2"))'), true);
+ assert.equal(await evaluate('document.querySelector(".claim-card input:checked")?.closest("label").hidden'), true, 'test needs the chosen row filtered out');
+ assert.equal(await evaluate('document.querySelector("#claim button[type=submit]").textContent'), pickedLabel, 'filtering changed the choice');
+ const submissionsBefore = submissions.length;
+ await key('Enter', 'Enter', 13);
+ await new Promise(r => setTimeout(r, 300));
+ assert.equal(submissions.length, submissionsBefore, 'Enter in the search box submitted the form');
+ assert.equal(await evaluate('location.pathname + location.search'), '/demo/claim');
+ await captureClaim(call, evaluate, screenshots, 'picker-search', [360, 1280]);
+ for (const ch of 'zz') await call('Input.insertText', {text:ch});
+ await until('document.getElementById("claim-search-empty").hidden === false');
+ assert.equal(await evaluate('document.querySelectorAll(".claim-card:not([hidden])").length'), 0);
+ assert.equal(await evaluate('!!document.querySelector(".claim-card input:checked")'), true, 'a filtered-out choice was cleared');
+ await captureClaim(call, evaluate, screenshots, 'picker-empty', [360]);
+ process.stdout.write('picker: thirty rows, eligible first, search filters, Enter stays put\n');
await call('Network.setCookies', {cookies:[
{name:'carlos_console_session',value:sessionToken,url:target,path:'/',httpOnly:true,sameSite:'Lax'},
{name:'carlos_demo_claim_flow',value:flowCookie,url:target,path:'/demo/claim',httpOnly:true,secure:true,sameSite:'Lax'}
@@ -147,8 +186,10 @@ try {
await evaluate(`document.querySelector('input[value='+${JSON.stringify(account)}+']').click()`);
assert.equal(await evaluate('document.querySelectorAll("script").length'),1);
assert.equal(await evaluate('document.querySelector("#claim button[type=submit]").textContent'), 'Keep in Personal projects');
- assert.equal(await evaluate('Array.from(document.querySelectorAll(".claim-card:has(input:not(:disabled))")).every(card => card.innerText.includes("Has room") && !card.innerText.includes("apps and instances"))'),true);
- assert.deepEqual(await evaluate('Array.from(document.querySelectorAll(".claim-card:has(input:disabled) .claim-detail")).map(el => el.textContent)'),['Free plan', 'You can view this account but not add apps. Ask one of its owners.']);
+ assert.equal(await evaluate('Array.from(document.querySelectorAll(".claim-card:has(input:not(:disabled))")).every(card => card.innerText.includes("Has room") && card.innerText.includes(" running"))'),true);
+ assert.deepEqual(await evaluate('Array.from(document.querySelectorAll(".claim-card:has(input:disabled) .chip, .claim-card:has(input:disabled) .claim-row-note")).map(el => el.textContent)'),['View only', 'Ask an owner to add apps.']);
+ assert.equal(await evaluate('document.querySelector(".claim-card:last-of-type input").disabled'),true,'the view-only account must sort last');
+ assert.equal(await evaluate('!!document.querySelector(".claim-search")'),false,'three accounts need no search box');
await capture('many');
await evaluate(`const form = document.querySelector('form[action="/demo/claim/select"]'); form.addEventListener('submit', event => event.preventDefault(), {once:true}); form.requestSubmit(); document.querySelector('#claim input[type=radio]:not(:disabled)').click()`);
assert.equal(await evaluate('document.querySelector("#claim button[type=submit]").disabled'),true,'radio change re-enabled submitted button');
@@ -162,9 +203,9 @@ try {
assert.equal(await evaluate('location.hash'),'');
assert.equal(security.length,0,JSON.stringify(security));
assert.deepEqual(submissions, [
- {disabled:true,visible:true,auto:false,account},
- {disabled:true,visible:true,auto:true,account}
- ],'manual and automatic submissions must disable the button, retain the form and preserve the selected account');
+ {disabled:true,list:true,auto:false,account},
+ {disabled:null,list:false,auto:true,account}
+ ],'a manual choice disables its button; a resumed one posts the same account from the progress view, with no list painted');
process.stdout.write('after: keyboard choice, redirect, callback, JS auto-submit; no CSP violations\n');
await until('document.querySelector("li[aria-current=step]")?.dataset.step === "2"');
assert.equal(await evaluate('document.getElementById("claim-status").textContent'),'Starting your app');
@@ -180,7 +221,11 @@ try {
assert.equal(await evaluate('window.liveWrites'),0,'unchanged poll rewrote live region');
await until('document.getElementById("claim").dataset.state === "claimed"');
await capture('done');
- assert.equal(await evaluate('document.querySelector(".claim-result a").textContent'),'Open your app');
+ assert.equal(await evaluate('document.querySelector(".claim-result .claim-console").textContent'),'Open in the console');
+ assert.equal(await evaluate('document.querySelector(".claim-result .claim-console").pathname.startsWith('+JSON.stringify('/a/'+account+'/apps/')+')'),true,'console link must name the claimed account');
+ assert.equal(await evaluate('document.querySelector(".claim-result .claim-open").target'),'_blank');
+ assert.equal(await evaluate('new URL(document.querySelector(".claim-result .claim-open").href).origin === document.querySelector(".claim-result .claim-open-address").textContent'),true);
+ assert.equal(await evaluate('document.querySelector(".claim-result .claim-open svg").getAttribute("aria-hidden")'),'true');
assert.equal(await evaluate('document.querySelector("#claim h1").textContent.endsWith(" is yours")'),true);
assert.equal(await evaluate('document.querySelector(".claim-command").open'),false);
await evaluate('document.querySelector(".claim-command").open = true');
@@ -250,6 +295,55 @@ try {
assert.equal(await evaluate('document.getElementById("claim-status").textContent'),'Keeping your demo in the account you chose…');
assert.equal(await evaluate('document.querySelectorAll("[aria-current=step]").length'),0);
process.stdout.write('fallback: stopped after three failures, retained no-script reload, stopped on abort; no CSP violations\n');
+ // A long "Starting your app": the bar sits inside the step's band and
+ // never goes back, and the step's detail rotates through reassurance.
+ await call('Page.navigate',{url:target+'/demo/claim?testProgress=starting'});
+ await until('document.querySelector("li[aria-current=step]")?.dataset.step === "2"');
+ const original = await evaluate('document.querySelector("li[aria-current=step] .claim-step-detail").textContent');
+ const bar = 'Number(document.querySelector(".claim-bar").getAttribute("aria-valuenow"))';
+ const first = await evaluate(bar);
+ assert(first >= 55 && first < 100, 'bar outside the starting band: '+first);
+ await until('document.querySelector("li[aria-current=step] .claim-step-detail").textContent !== '+JSON.stringify(original));
+ const later = await evaluate(bar);
+ assert(later >= first && later < 100, 'bar went back or finished early: '+first+' then '+later);
+ assert.equal(await evaluate('document.getElementById("claim-elapsed").hidden'),true,'elapsed shown before 30 s');
+ assert.equal(await evaluate('document.getElementById("claim-stuck").hidden'),true,'stuck before the deadline');
+ await capture('starting-hint');
+ // Past the server's deadline plus grace, still reporting progress: stuck.
+ await call('Page.navigate',{url:target+'/demo/claim?testProgress=stuck'});
+ await until('!!document.getElementById("claim-progress")');
+ assert.equal(await evaluate('document.getElementById("claim-stuck").hidden'),true,'stuck before polling');
+ await until('document.getElementById("claim-stuck")?.hidden === false');
+ assert.equal(await evaluate('document.getElementById("claim-stuck").getAttribute("role")'),'alert');
+ assert.equal(await evaluate('document.querySelector("#claim-stuck a").getAttribute("href")'),'/demo/claim');
+ assert.equal(await evaluate('document.querySelectorAll("#claim-stuck a").length'),1,'only the really-long case offers Check again');
+ assert.equal(await evaluate('document.getElementById("claim-progress").hasAttribute("data-stuck")'),true);
+ assert.equal(await evaluate('document.querySelector("li[aria-current=step] .claim-step-detail").textContent'),original,'stuck page still rotates reassurance');
+ await capture('stuck');
+ assert.equal(security.length,0,JSON.stringify(security));
+ process.stdout.write('reassurance: bar in band and monotonic, hints rotate, stuck after the deadline\n');
+ // Past the irreversible commit the rollback deadline does not apply: an
+ // overdue committed claim says it is the person's and still finishing,
+ // never that it will be undone.
+ await call('Page.navigate',{url:target+'/demo/claim?testProgress=committed'});
+ await until('!!document.getElementById("claim-progress")?.dataset.committedFor');
+ const committedPolls = statusRequests;
+ await until('document.getElementById("claim-finishing")?.hidden === false');
+ assert(statusRequests >= committedPolls + 2, 'finishing shown before two polls');
+ assert.equal(await evaluate('document.getElementById("claim-stuck").hidden'),true,'committed claim shown the rollback box');
+ assert.equal(await evaluate('document.getElementById("claim-progress").hasAttribute("data-stuck")'),false);
+ assert.equal(await evaluate('document.getElementById("claim-finishing").innerText.includes("undone")'),false);
+ assert.equal(await evaluate('document.getElementById("claim-finishing").getAttribute("role")'),'status');
+ // The page re-checks by itself; a finishing claim offers nothing to press.
+ assert.equal(await evaluate('document.querySelectorAll("#claim-finishing a, #claim-finishing button").length'),0,'finishing box has an action');
+ const finishingPolls = statusRequests;
+ for (let i=0; i<120 && statusRequests === finishingPolls; i++) await new Promise(r=>setTimeout(r,100));
+ assert(statusRequests > finishingPolls, 'finishing box stopped checking');
+ assert(await evaluate(bar) >= 90, 'committed bar below its band');
+ await capture('committed-finishing');
+ assert.equal(await evaluate('document.getElementById("claim-stuck").hidden'),true,'rollback box appeared later');
+ assert.equal(security.length,0,JSON.stringify(security));
+ process.stdout.write('committed: no rollback promise past the commit; finishing message instead\n');
} finally {
clearTimeout(timer);
const closed = new Promise(resolve => chrome.once('exit',resolve));
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 a0feab11a..51471ccb6 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-account-subdomains.tsv b/internal/provision/testdata/plan14-root-reads-account-subdomains.tsv
index bbaaee3c1..2490387d5 100644
--- a/internal/provision/testdata/plan14-root-reads-account-subdomains.tsv
+++ b/internal/provision/testdata/plan14-root-reads-account-subdomains.tsv
@@ -36,6 +36,6 @@ internal/registry/registry.go Registry.migrate legacy accepted-legacy accepted-l
@coverage internal/domains d2c7a0dc9c164bb764dc65a5e004c8cc12ce575e2413204a1040f0c1ba228a12
@coverage internal/edge 2f9527a8be433bf2d560cd1293ea04e8e357898ed7241a5854bc403a79cd9aad
@coverage internal/host 9388ccee0b3287e82898e47c0b6da2991fe9a20ff3c0c600e59dbf2ed89210d3
-@coverage internal/provision 8b7747ecb67234457618a5ab9f2454823520065ddac23360be60fd93d26ec131
+@coverage internal/provision ece6d1472866798be1b2678c10aa0fad027b4e3e135861b46b8f7a5829cd31b7
@coverage internal/registry 87edc805294acb90abb7637f64fd174bd8ced08978783dbb2631855082955582
@fields ?,A,Account,Accounts,AcquiredGeneration,AddedAt,Addr,Addrs,Adoption,Alias,Aliases,Alive,AllowAbsent,App,AppsDomain,Archives,Args,AssetGen,AssetsOff,Assigned,Assignment,At,Attempts,B,Backing,Basis,Binding,Blocked,Body,BoxLabel,Bucket,BuildState,By,Callback,CallbackError,CallbackFailed,Canary,Caps,CertExpiresAt,Changed,Channel,CheckedAt,Claim,ClaimIncarnation,ClaimOwner,ClaimOwnership,ClaimRowID,ClaimStamp,Class,Code,Column,ConnGen,Connected,Contents,Copies,Count,CreatedAt,Cursor,DBPath,DNSCheckedAt,DNSStatus,Deadline,Default,DeleteUncertain,Demand,DemoExpiresAt,DemoHost,DemoID,DemoLifetime,Departure,DepartureIID,DepartureRef,Departures,Digest,DoneBefore,DrainingSince,Due,DueAt,Duty,EdgesETag,EgressAllow,EnrolledAt,Env,EnvBefore,Environment,Error,ErrorKind,ExcludeHosts,ExpectGood,ExpectOp,ExpectPair,Expected,ExpectedPair,F,Failed,FenceGen,Field,FillLegacyRegistration,Fleet,FleetBox,FleetBoxes,FleetLabel,Fleets,Found,From,FromDB,FromOp,FromSock,Gate,Generation,GoodDemand,GoodDigest,GoodVersion,HA,HAJournal,Hash,Health,Held,Hibernate,Hint,Hints,HoldOp,HolderEpoch,HolderIID,HolderRef,HomeAccount,HomeApp,HomeHost,HomeLink,HomeLinkApp,HomeLinkApps,Host,Hosts,ID,IID,Id,IdValue,Identity,Idle,IdleSeconds,Import,ImportGate,Inbox,Incarnation,InventoryGeneration,Journal,Keep,Key,KeyFP,Keys,Kind,Label,LabelledAt,LastAt,LastBlocked,LastError,LastMs,LastPage,LastStatus,Lifetime,Limit,Link,LinkID,LinkSeen,LockETag,LockGeneration,Managed,MaxRun,MaxRunSeconds,MessageID,Method,Moved,Ms,Name,Names,Next,NextAt,NextAttempt,NextDue,NextGood,NextValue,NotBefore,Now,Number,Number64,Observation,Observed,ObservedValue,Offset,Old,Oldest,On,OnConflict,Op,Original,Owner,Ownership,P,Page,PagesOff,Pair,Path,Paths,PermissionAlerted,Phase,Platform,PolicyExpiresAt,Pool,Prefix,Prev,PrevVersion,ProofDigest,ProofKey,Provisioned,Pub,RDs,RateLimit,Raw,Receipt,ReceivedAt,RecordDigest,RecordKey,Ref,Region,Regional,Registration,Replica,ReplicaIncarnation,ReplicaLife,ReplicaRevision,Replicas,Replication,Rescan,Result,Retirement,RetryCount,Revision,RotateGen,RotatePending,Route,Routes,Row,Rows,Runtime,Scan,SecretsKeyFP,SecretsKeySetAt,SecretsKeySetBy,SecretsPub,Seed,SeedID,SeedSource,SeenAt,Seq,Sequence,ServingSeq,ServingURL,ServingVersion,Size,Slug,Socket,Spec,Sqid,StartedAt,State,Stateless,Status,StatusNamed,Steering,StringMap,Summary,T,TValue,Tags,Target,Targets,Text,Timer,Timers,Times,To,ToDB,ToOp,ToSock,Token,TokenHash,Tunnel,TunnelURL,Type,Unit,UnlinkPending,Unresolved,UpdateSettings,Ver,Version,ViewKey,Visited,W,Waiting,Wake,WakeDigest,WakeIncarnation,Walk,Wildcards,closed,conn,connect,ctx,d,dec,done,enc,full,input,output,path,readOnly,remote,slot,sql,wait
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv
index 1fccd8a79..98822ce93 100644
--- a/internal/provision/testdata/plan14-root-reads-chain.tsv
+++ b/internal/provision/testdata/plan14-root-reads-chain.tsv
@@ -177,4 +177,5 @@ 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-account-subdomains.tsv bc306a42e5d5c2c03d38c1e574a30b98e9cae71e209eec241bc33da0ae851314
+plan14-root-reads-member-backups-2a-landing.tsv bf37ccf4fdd0d81a1dba7370a393074b763841b349d45fb65de12a037faf01ea
+plan14-root-reads-account-subdomains.tsv 0ae4d72ff0196d3eabb4acee069c6de61431c1a3bef669eb7ba5294104694eb8
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)
+ }
+}