carlos / platform Public

console: backups classifier and bounded, memoised read (#898)

replicaIntrinsic is the one rule for what kind of instance a record is,
as far as its copy goes: dbreads.ClassRefusal, then a demo, then the
pool and fleet placement. classifyBackups adds the region on top, so
db pull's forwarding of another region's instance is untouched.

resolveReplica now takes its pool and fleet checks from replicaPlacement
(the placement half of replicaIntrinsic) and dbClassRefusal takes its
refuse-or-not from replicaIntrinsic; both keep their errors and
messages byte for byte, pinned by goldens captured at 25cedabc.

backupsFor reads a replicated instance's position and history with one
dbdoor.PositionAndHistory call over at most 20,000 files within 10
seconds, one read in flight per host, kept 5 minutes. Nothing else
touches the bucket.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev cf2ef5d93feaffd2e511b4a1939d12d05aafc524 parent 25cedab
4 files changed, +788 −8
  • internal/console/apidb.go +14 −8
  • internal/console/backups.go +307 −0
  • internal/console/backups_test.go +464 −0
  • internal/console/server.go +3 −0

Intent

Human

<task-notification> <task-id>a9a870bf1a109b071</task-id> <tool-use-id>toolu_01WruLWvLF6SRHN2HYapJrcF</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/ab362fc0-f177-4a7f-a92e-4a29ea210aad/tasks/a9a870bf1a109b071.output</output-file> <status>completed</status> <summary>Agent "Implement slice 1 Task 1" 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_WITH_CONCERNS Commit: 25cedabc dbdoor: PositionAndHistory, one listing and one boundary rule (#898) Tests: `go test ./internal/dbdoor -run 'PositionAndHistory|Restore|PlanFrom|HistoryBoundary'` passed all 43 tests, 7 of them new. Every existing restore test passes unchanged. RED was "undefined: PositionAndHistory". A mutation that switches off the per-call listing cache makes the list-once and file-cap tests fail. gofmt, vet and `go build ./...` are clean. Concerns: - `internal/dbdoor` is in the root binary's census scope. I left census testdata alone for Task 6. - The brief doesn't say what a `maxFiles` of 0 or less means. I made it admit no files and documented that, so callers should pass a positive cap. - `PlanFrom` now uses the same per-call listing cache. Nothing changes in practice, because litestream already lists each level once per plan. - I added one test the brief didn't list: `TestPositionAndHistoryWithoutTimes`. It covers listings with no times giving `known=false`. Report: /home/paulca/amadan.net/carlos/platform/.claude/worktrees/member-backups-1/.superpowers/sdd/2026-11-11-member-backups-slice1/task-1-report.md</result> <usage><subagent_tokens>107871</subagent_tokens><tool_uses>23</tool_uses><duration_ms>313756</duration_ms></usage> </task-notification>

Human

<task-notification> <task-id>bnhq25mxc</task-id> <tool-use-id>toolu_014zqk3VdRMHrFPrrctJfvr8</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/ab362fc0-f177-4a7f-a92e-4a29ea210aad/tasks/bnhq25mxc.output</output-file> <status>completed</status> <summary>Background command "Astra review of slice 1 Task 1" completed (exit code 0)</summary> </task-notification>

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

diff --git a/internal/console/apidb.go b/internal/console/apidb.go
index b1d509534..ba1c94865 100644
--- a/internal/console/apidb.go
+++ b/internal/console/apidb.go
@@ -55,13 +55,15 @@ func (s *Server) resolveReplica(rec provision.Record, host string) (string, erro
if !provision.ValidHostShape(host) || rec.Host != host {
return "", fmt.Errorf("%w: %q", ErrBadHost, host)
}
- if rec.Pool != "" {
- return "", fmt.Errorf("%w: %s is in pool %q", ErrPooled, host, rec.Pool)
- }
- // A fleet placement is checked on its own, not left to the region
- // compare: the data is on the customer's box whatever this console's
+ // The pool and fleet rule is replicaIntrinsic's placement half (P-6),
+ // applied whatever the record's class, as it always was. A fleet
+ // placement is checked on its own, not left to the region compare:
+ // the data is on the customer's box whatever this console's
// CARLOS_REGION says.
- if _, fleet := registry.FleetPlacement(rec.Region); fleet {
+ switch _, reason := replicaPlacement(rec); reason {
+ case backupReasonPooled:
+ return "", fmt.Errorf("%w: %s is in pool %q", ErrPooled, host, rec.Pool)
+ case backupReasonFleet:
return "", fmt.Errorf("%w: %s is placed on fleet %q", ErrResidency, host, rec.Region)
}
if rec.Region != s.cfg.Region {
@@ -237,9 +239,13 @@ func (s *Server) resolveDBSource(ctx context.Context, acct *Account, actor, app,
// dbClassRefusal is the class rail as a sentence, or "" for an
// activator-managed exec instance: the only class whose database the
// platform replicates (spec §1 scope). Same three facts the move doors
-// refuse on; the fleet and pool cases are resolveReplica's. The rule lives
-// in dbreads.ClassRefusal (db region forward spec §8.2).
+// refuse on; the fleet and pool cases are resolveReplica's. Whether to
+// refuse is replicaIntrinsic's no_copy class (P-6); the sentence is a
+// demo's, else dbreads.ClassRefusal's (db region forward spec §8.2).
func dbClassRefusal(rec provision.Record) string {
+ if class, _ := replicaIntrinsic(rec); class != backupNoCopy {
+ return ""
+ }
if rec.Demo != nil {
return demoCopy["DEMO-DATA"]
}
diff --git a/internal/console/backups.go b/internal/console/backups.go
new file mode 100644
index 000000000..6f45888a7
--- /dev/null
+++ b/internal/console/backups.go
@@ -0,0 +1,307 @@
+// What the console knows about an instance's copy (member backups spec
+// 2026-11-11 §1): one classifier, shared with `carlos db pull`'s gate, and
+// one bounded, memoised read of the copy's position and history.
+
+package console
+
+import (
+ "context"
+ "errors"
+ "log"
+ "sync"
+ "time"
+
+ "github.com/carlosframework/platform/internal/dbdoor"
+ "github.com/carlosframework/platform/internal/dbreads"
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/regionlabel"
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+// backupClass is what the backups door says about an instance's copy.
+type backupClass string
+
+const (
+ // backupReplicated: the platform keeps a copy and this console reads it.
+ backupReplicated backupClass = "replicated"
+ // backupNoCopy: the platform keeps no copy of this database at all.
+ backupNoCopy backupClass = "no_copy"
+ // backupNotShown: a copy may exist, but this console does not show it.
+ backupNotShown backupClass = "not_shown"
+)
+
+// The reasons a backupsView gives, and its files values: API values
+// rather than copy. The page and the CLI turn them into sentences.
+const (
+ backupReasonNotInstance = "not_instance"
+ backupReasonOwnAddress = "own_address"
+ backupReasonNoSleep = "no_sleep"
+ backupReasonDemo = "demo"
+ backupReasonPooled = "pooled"
+ backupReasonFleet = "fleet"
+ backupReasonOtherRegion = "other_region"
+ backupReasonNothing = "nothing_replicated"
+ backupReasonTooLarge = "too_large_to_plan"
+ backupReasonUnavailable = "unavailable"
+
+ backupFilesNotCopied = "not_copied"
+ backupFilesNotShown = "not_shown"
+)
+
+// The read's bounds (spec §1, R1-13): files listed across every level,
+// the deadline on one read, and how long a read is kept per host.
+const (
+ backupsMaxFiles = 20000
+ backupsDeadline = 10 * time.Second
+ backupsMemoTTL = 5 * time.Minute
+ backupsMemoMax = 1024
+)
+
+// replicaIntrinsic is what kind of instance rec is, as far as its copy
+// goes, from the record alone: the facts that are true whichever console
+// asks. It is the one rule the backups door, resolveReplica and
+// dbClassRefusal share (P-6), so they never disagree about an instance.
+// The order is fixed: dbreads.ClassRefusal (its reason named from the
+// fields it reads, in its order: Kind, Addr or Addrs, HibernateOrDefault;
+// a Unit alone is no refusal), then a demo, then replicaPlacement's pool
+// and fleet.
+func replicaIntrinsic(rec provision.Record) (backupClass, string) {
+ if dbreads.ClassRefusal(rec) != "" {
+ switch {
+ case rec.Kind != "" && rec.Kind != "instance":
+ return backupNoCopy, backupReasonNotInstance
+ case rec.Addr != "" || len(rec.Addrs) > 0:
+ return backupNoCopy, backupReasonOwnAddress
+ default:
+ return backupNoCopy, backupReasonNoSleep
+ }
+ }
+ if rec.Demo != nil {
+ return backupNoCopy, backupReasonDemo
+ }
+ return replicaPlacement(rec)
+}
+
+// replicaPlacement is replicaIntrinsic's placement half: a pooled record's
+// data is on the pool box, a fleet-placed one's on the customer's box,
+// whatever this console's region. resolveReplica refuses on exactly these,
+// whatever the record's class, as it always has.
+func replicaPlacement(rec provision.Record) (backupClass, string) {
+ if rec.Pool != "" {
+ return backupNotShown, backupReasonPooled
+ }
+ if _, fleet := registry.FleetPlacement(rec.Region); fleet {
+ return backupNotShown, backupReasonFleet
+ }
+ return backupReplicated, ""
+}
+
+// classifyBackups is replicaIntrinsic, then the region: the backups door
+// reads only copies kept in this console's region, and says not_shown for
+// the rest. Region is kept out of replicaIntrinsic because it is not a
+// fact about the instance: db pull forwards another region's instance
+// (spec §1, R2-2), and that path is untouched.
+func classifyBackups(rec provision.Record, consoleRegion string) (backupClass, string) {
+ if class, reason := replicaIntrinsic(rec); class != backupReplicated {
+ return class, reason
+ }
+ if rec.Region != consoleRegion {
+ return backupNotShown, backupReasonOtherRegion
+ }
+ return backupReplicated, ""
+}
+
+// backupsView is the backups door's answer for one instance (spec §1).
+// Files is derived from HABorn: copies of files on disk are not made for
+// an instance that is not born HA, and not shown for one that is.
+type backupsView struct {
+ Class backupClass `json:"class"`
+ Reason string `json:"reason,omitempty"`
+ Region string `json:"region,omitempty"`
+ CopiedTo *backupsPosition `json:"copied_to,omitempty"`
+ HistoryFrom *time.Time `json:"history_from,omitempty"`
+ Files string `json:"files"`
+ HABorn bool `json:"-"`
+}
+
+// backupsPosition is the newest transaction a restore of the copy reaches
+// and the time it was written: the last change saved, not a check time.
+type backupsPosition struct {
+ Transaction uint64 `json:"transaction"`
+ WrittenAt time.Time `json:"written_at"`
+}
+
+// backupsFor is what the console knows about rec's copy. A record the
+// classifier does not admit is answered from the record alone, and the
+// bucket is never touched. An admitted one is read once per host per
+// backupsMemoTTL (s.backups): one PositionAndHistory over at most
+// backupsMaxFiles files within backupsDeadline.
+func (s *Server) backupsFor(ctx context.Context, rec provision.Record) backupsView {
+ var v backupsView
+ class, reason := classifyBackups(rec, s.cfg.Region)
+ switch {
+ case class != backupReplicated:
+ v = backupsView{Class: class, Reason: reason}
+ if reason == backupReasonOtherRegion {
+ v.Region = regionlabel.ForCode(rec.Region, s.regionHome(), s.regionNames()).Text
+ }
+ default:
+ v = s.backups.load(ctx, rec.Host, func(ctx context.Context) (backupsView, bool) {
+ return s.readBackups(ctx, rec)
+ })
+ }
+ v.HABorn = rec.HA
+ v.Files = backupFilesNotCopied
+ if v.HABorn {
+ v.Files = backupFilesNotShown
+ }
+ return v
+}
+
+// readBackups is one read of rec's copy. keep is false for a read that
+// failed rather than answered, so the next caller tries again.
+func (s *Server) readBackups(ctx context.Context, rec provision.Record) (v backupsView, keep bool) {
+ notShown := func(reason string) backupsView { return backupsView{Class: backupNotShown, Reason: reason} }
+ if s.cfg.HibernateBucket == "" || s.dbReplica == nil {
+ return notShown(backupReasonUnavailable), false
+ }
+ prefix, err := s.resolveReplica(rec, rec.Host)
+ if err != nil {
+ log.Printf("console: backups %s: resolve: %v", rec.Host, err)
+ return notShown(backupReasonUnavailable), false
+ }
+ rd, err := s.dbReplica(ctx, prefix)
+ if err != nil {
+ log.Printf("console: backups %s: replica client: %v", rec.Host, err)
+ return notShown(backupReasonUnavailable), false
+ }
+ plan, from, known, err := dbdoor.PositionAndHistory(ctx, rd, backupsMaxFiles)
+ switch {
+ case errors.Is(err, dbdoor.ErrNothingReplicated):
+ return notShown(backupReasonNothing), true
+ case errors.Is(err, dbdoor.ErrTooManyFiles), errors.Is(err, context.DeadlineExceeded):
+ return notShown(backupReasonTooLarge), true
+ case err != nil:
+ log.Printf("console: backups %s: read the copy: %v", rec.Host, err)
+ return notShown(backupReasonUnavailable), false
+ }
+ v = backupsView{Class: backupReplicated, CopiedTo: &backupsPosition{Transaction: plan.TXID, WrittenAt: plan.At}}
+ if known {
+ v.HistoryFrom = &from
+ }
+ return v, true
+}
+
+// backupsMemo holds each host's read for backupsMemoTTL, and the one read
+// in flight per host, which every concurrent caller for that host waits on
+// rather than starting its own (analyticsMemo's shape). A held view is
+// shared and must not be changed; backupsFor copies it by value.
+type backupsMemo struct {
+ mu sync.Mutex
+ m map[string]backupsMemoEntry
+ inflight map[string]*backupsMemoCall
+ // deadline bounds one read (zero: backupsDeadline) and now is the
+ // clock (nil: time.Now); both are test seams.
+ deadline time.Duration
+ now func() time.Time
+}
+
+type backupsMemoEntry struct {
+ at time.Time
+ v backupsView
+}
+
+type backupsMemoCall struct {
+ done chan struct{}
+ v backupsView
+ waiters int // callers waiting on this read, besides the one running it
+}
+
+func (c *backupsMemo) clock() time.Time {
+ if c.now != nil {
+ return c.now()
+ }
+ return time.Now()
+}
+
+// load is host's view: from the memo when held, else from the read in
+// flight for host, else from read, which this caller runs. The read runs
+// under its own deadline and not under the caller's cancellation, so a
+// caller that goes away does not fail the read for the callers waiting on
+// it; the deadline still bounds it. A waiter whose own context ends gives
+// up with unavailable.
+func (c *backupsMemo) load(ctx context.Context, host string, read func(context.Context) (backupsView, bool)) backupsView {
+ now := c.clock()
+ c.mu.Lock()
+ if e, ok := c.m[host]; ok && now.Sub(e.at) < backupsMemoTTL && !now.Before(e.at) {
+ c.mu.Unlock()
+ return e.v
+ }
+ if call, ok := c.inflight[host]; ok {
+ call.waiters++
+ c.mu.Unlock()
+ select {
+ case <-call.done:
+ return call.v
+ case <-ctx.Done():
+ return backupsView{Class: backupNotShown, Reason: backupReasonUnavailable}
+ }
+ }
+ if c.inflight == nil {
+ c.inflight = map[string]*backupsMemoCall{}
+ }
+ call := &backupsMemoCall{done: make(chan struct{})}
+ c.inflight[host] = call
+ deadline := c.deadline
+ if deadline <= 0 {
+ deadline = backupsDeadline
+ }
+ c.mu.Unlock()
+ keep := false
+ defer func() {
+ c.mu.Lock()
+ delete(c.inflight, host)
+ if keep {
+ c.putLocked(host, call.v, now)
+ }
+ c.mu.Unlock()
+ close(call.done)
+ }()
+ rctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), deadline)
+ defer cancel()
+ call.v, keep = read(rctx)
+ return call.v
+}
+
+// putLocked keeps host's view, read at now. Expired entries go first; past
+// backupsMemoMax the oldest goes. c.mu is held.
+func (c *backupsMemo) putLocked(host string, v backupsView, now time.Time) {
+ if c.m == nil {
+ c.m = map[string]backupsMemoEntry{}
+ }
+ for k, e := range c.m {
+ if now.Sub(e.at) >= backupsMemoTTL {
+ delete(c.m, k)
+ }
+ }
+ for len(c.m) >= backupsMemoMax {
+ oldest := ""
+ for k, e := range c.m {
+ if oldest == "" || e.at.Before(c.m[oldest].at) {
+ oldest = k
+ }
+ }
+ delete(c.m, oldest)
+ }
+ c.m[host] = backupsMemoEntry{at: now, v: v}
+}
+
+// waiting is how many callers wait on host's read in flight (tests).
+func (c *backupsMemo) waiting(host string) int {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ if call, ok := c.inflight[host]; ok {
+ return call.waiters
+ }
+ return 0
+}
diff --git a/internal/console/backups_test.go b/internal/console/backups_test.go
new file mode 100644
index 000000000..ab9ac6d2f
--- /dev/null
+++ b/internal/console/backups_test.go
@@ -0,0 +1,464 @@
+package console
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "io"
+ "path/filepath"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ lsfile "github.com/benbjohnson/litestream/file"
+ "github.com/superfly/ltx"
+
+ "github.com/carlosframework/platform/internal/dbdoor"
+ "github.com/carlosframework/platform/internal/demo"
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/regionlabel"
+)
+
+// backupsRegion is the console's region in most rows of backupsRows.
+const backupsRegion = "ie"
+
+// backupsRow is one record and the console region it is seen from.
+type backupsRow struct {
+ name string
+ rec provision.Record
+ console string // the console's CARLOS_REGION
+ class backupClass
+ reason string
+}
+
+func backupsYes() *bool { v := true; return &v }
+func backupsNo() *bool { v := false; return &v }
+
+// backupsRows is one row per reason classifyBackups gives, plus the rows
+// where two facts meet, so the first one wins in the stated order.
+func backupsRows() []backupsRow {
+ rec := func(slug string, mut func(*provision.Record)) provision.Record {
+ r := provision.Record{Host: slug + ".go.tito.io", Region: backupsRegion, Hibernate: backupsYes()}
+ if mut != nil {
+ mut(&r)
+ }
+ return r
+ }
+ demoOf := func(r *provision.Record) { r.Demo = &demo.Descriptor{ID: "d1", Host: r.Host} }
+ return []backupsRow{
+ {"replicated", rec("rep", nil), backupsRegion, backupReplicated, ""},
+ {"kind instance", rec("kin", func(r *provision.Record) { r.Kind = "instance" }), backupsRegion, backupReplicated, ""},
+ {"unit only", rec("unit", func(r *provision.Record) { r.Unit = "shop.service" }), backupsRegion, backupReplicated, ""},
+ {"single region", rec("single", func(r *provision.Record) { r.Region = "" }), "", backupReplicated, ""},
+ {"service route", rec("svc", func(r *provision.Record) { r.Kind = "service" }), backupsRegion, backupNoCopy, "not_instance"},
+ {"static route", rec("stat", func(r *provision.Record) { r.Kind = "static" }), backupsRegion, backupNoCopy, "not_instance"},
+ {"own address", rec("addr", func(r *provision.Record) { r.Addr = "127.0.0.1:9000" }), backupsRegion, backupNoCopy, "own_address"},
+ {"own addresses", rec("addrs", func(r *provision.Record) { r.Addrs = []string{"127.0.0.1:9000", "127.0.0.1:9001"} }), backupsRegion, backupNoCopy, "own_address"},
+ {"no sleep", rec("awake", func(r *provision.Record) { r.Hibernate = backupsNo() }), backupsRegion, backupNoCopy, "no_sleep"},
+ {"demo", rec("demo", demoOf), backupsRegion, backupNoCopy, "demo"},
+ {"pooled", rec("pool", func(r *provision.Record) { r.Pool = "shared" }), backupsRegion, backupNotShown, "pooled"},
+ {"fleet", rec("fleet", func(r *provision.Record) { r.Region = "fleet/acme" }), backupsRegion, backupNotShown, "fleet"},
+ {"fleet in the console's region", rec("fleetin", func(r *provision.Record) { r.Region = "fleet/acme" }), "fleet/acme", backupNotShown, "fleet"},
+ {"other region", rec("far", func(r *provision.Record) { r.Region = "uk" }), backupsRegion, backupNotShown, "other_region"},
+ {"home record on a regional console", rec("home", func(r *provision.Record) { r.Region = "" }), backupsRegion, backupNotShown, "other_region"},
+ {"pooled and no sleep", rec("poolawake", func(r *provision.Record) { r.Pool = "shared"; r.Hibernate = backupsNo() }), backupsRegion, backupNoCopy, "no_sleep"},
+ {"demo and no sleep", rec("demoawake", func(r *provision.Record) { demoOf(r); r.Hibernate = backupsNo() }), backupsRegion, backupNoCopy, "no_sleep"},
+ {"demo and pooled", rec("demopool", func(r *provision.Record) { demoOf(r); r.Pool = "shared" }), backupsRegion, backupNoCopy, "demo"},
+ {"pooled in another region", rec("poolfar", func(r *provision.Record) { r.Pool = "shared"; r.Region = "uk" }), backupsRegion, backupNotShown, "pooled"},
+ {"fleet that does not sleep", rec("fleetawake", func(r *provision.Record) { r.Region = "fleet/acme"; r.Hibernate = backupsNo() }), backupsRegion, backupNoCopy, "no_sleep"},
+ }
+}
+
+func TestClassifyBackupsTable(t *testing.T) {
+ for _, row := range backupsRows() {
+ t.Run(row.name, func(t *testing.T) {
+ class, reason := classifyBackups(row.rec, row.console)
+ if class != row.class || reason != row.reason {
+ t.Fatalf("classifyBackups = %q/%q, want %q/%q", class, reason, row.class, row.reason)
+ }
+ // Region is never an intrinsic fact: replicaIntrinsic says
+ // replicated wherever classifyBackups refuses only on region.
+ ic, ir := replicaIntrinsic(row.rec)
+ if row.reason == "other_region" {
+ if ic != backupReplicated || ir != "" {
+ t.Fatalf("replicaIntrinsic = %q/%q for an other-region row, want replicated", ic, ir)
+ }
+ } else if ic != row.class || ir != row.reason {
+ t.Fatalf("replicaIntrinsic = %q/%q, want %q/%q", ic, ir, row.class, row.reason)
+ }
+ })
+ }
+}
+
+// The oracle that keeps the door and `db pull` in agreement (spec §1
+// R2-2): classifyBackups says replicated exactly when resolveDBSource
+// admits the record, and an other-region refusal is db pull's residency
+// refusal, which it forwards.
+func TestClassifyBackupsAgreesWithResolveDBSource(t *testing.T) {
+ fx := dbFixture(t)
+ enableInstances(t, fx.consoleFixture, "titogo", titoManifest())
+ acct, err := fx.st.AccountBySqid("bab")
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, row := range backupsRows() {
+ t.Run(row.name, func(t *testing.T) {
+ putDBRecord(t, fx.consoleFixture, row.rec)
+ fx.srv.cfg.Region = row.console
+ class, reason := classifyBackups(row.rec, row.console)
+ _, err := fx.srv.resolveDBSource(t.Context(), acct, "alice@keymail.dev", "titogo", row.rec.Host)
+ if (class == backupReplicated) != (err == nil) {
+ t.Fatalf("classifyBackups = %q/%q but resolveDBSource = %v", class, reason, err)
+ }
+ if reason == "other_region" && !errors.Is(err, ErrResidency) {
+ t.Fatalf("other_region but resolveDBSource = %v, want ErrResidency (which db pull forwards)", err)
+ }
+ })
+ }
+}
+
+// resolveReplica and dbClassRefusal answer every row exactly as they did
+// before they called the shared classifier. The goldens were captured by
+// running the code at 25cedabc over backupsRows.
+func TestResolveReplicaUsesIntrinsic(t *testing.T) {
+ const demoMsg = "Only a verified claim can move a demo's data into a permanent app. Generic move, copy and import tools cannot do this. Demos have no backup."
+ golden := map[string]struct {
+ prefix, err, refusal string
+ is error
+ }{
+ "replicated": {"instances/rep.go.tito.io", "", "", nil},
+ "kind instance": {"instances/kin.go.tito.io", "", "", nil},
+ "unit only": {"instances/unit.go.tito.io", "", "", nil},
+ "single region": {"instances/single.go.tito.io", "", "", nil},
+ "service route": {"instances/svc.go.tito.io", "", "svc.go.tito.io is a service route. The platform keeps a database copy only for instances.", nil},
+ "static route": {"instances/stat.go.tito.io", "", "stat.go.tito.io is a static route. The platform keeps a database copy only for instances.", nil},
+ "own address": {"instances/addr.go.tito.io", "", "addr.go.tito.io is served from its own address, so the platform does not manage its database.", nil},
+ "own addresses": {"instances/addrs.go.tito.io", "", "addrs.go.tito.io is served from its own address, so the platform does not manage its database.", nil},
+ "no sleep": {"instances/awake.go.tito.io", "", "awake.go.tito.io does not sleep, so the platform does not keep a copy of its database.", nil},
+ "demo": {"instances/demo.go.tito.io", "", demoMsg, nil},
+ "pooled": {"", `db: pooled instances have no replica of their own: pool.go.tito.io is in pool "shared"`, "", ErrPooled},
+ "fleet": {"", `db: the instance's data is outside this region: fleet.go.tito.io is placed on fleet "fleet/acme"`, "", ErrResidency},
+ "fleet in the console's region": {"", `db: the instance's data is outside this region: fleetin.go.tito.io is placed on fleet "fleet/acme"`, "", ErrResidency},
+ "other region": {"", `db: the instance's data is outside this region: far.go.tito.io is homed in "uk", this console serves "ie"`, "", ErrResidency},
+ "home record on a regional console": {"", `db: the instance's data is outside this region: home.go.tito.io is homed in "", this console serves "ie"`, "", ErrResidency},
+ "pooled and no sleep": {"", `db: pooled instances have no replica of their own: poolawake.go.tito.io is in pool "shared"`, "poolawake.go.tito.io does not sleep, so the platform does not keep a copy of its database.", ErrPooled},
+ "demo and no sleep": {"instances/demoawake.go.tito.io", "", demoMsg, nil},
+ "demo and pooled": {"", `db: pooled instances have no replica of their own: demopool.go.tito.io is in pool "shared"`, demoMsg, ErrPooled},
+ "pooled in another region": {"", `db: pooled instances have no replica of their own: poolfar.go.tito.io is in pool "shared"`, "", ErrPooled},
+ "fleet that does not sleep": {"", `db: the instance's data is outside this region: fleetawake.go.tito.io is placed on fleet "fleet/acme"`, "fleetawake.go.tito.io does not sleep, so the platform does not keep a copy of its database.", ErrResidency},
+ }
+ rows := backupsRows()
+ if len(golden) != len(rows) {
+ t.Fatalf("%d goldens for %d rows", len(golden), len(rows))
+ }
+ for _, row := range rows {
+ t.Run(row.name, func(t *testing.T) {
+ want, ok := golden[row.name]
+ if !ok {
+ t.Fatalf("no golden for %q", row.name)
+ }
+ s := &Server{}
+ s.cfg.Region = row.console
+ s.cfg.HibernatePrefix = "instances"
+ prefix, err := s.resolveReplica(row.rec, row.rec.Host)
+ got := ""
+ if err != nil {
+ got = err.Error()
+ }
+ if prefix != want.prefix || got != want.err {
+ t.Fatalf("resolveReplica = %q, %q; want %q, %q", prefix, got, want.prefix, want.err)
+ }
+ if want.is != nil && !errors.Is(err, want.is) {
+ t.Fatalf("resolveReplica error %v is not %v", err, want.is)
+ }
+ if msg := dbClassRefusal(row.rec); msg != want.refusal {
+ t.Fatalf("dbClassRefusal = %q, want %q", msg, want.refusal)
+ }
+ })
+ }
+}
+
+func TestBackupsForReadsPositionAndHistory(t *testing.T) {
+ fx := dbFixture(t)
+ fx.replicate(t, dbTestHost, 3)
+ rd := lsfile.NewReplicaClient(filepath.Join(fx.root, "instances", dbTestHost))
+ plan, from, known, err := dbdoor.PositionAndHistory(t.Context(), rd, 20000)
+ if err != nil || !known {
+ t.Fatalf("PositionAndHistory = %v, known %v", err, known)
+ }
+
+ rec := provision.Record{Host: dbTestHost, Region: fx.srv.cfg.Region, Hibernate: backupsYes()}
+ v := fx.srv.backupsFor(t.Context(), rec)
+ if v.Class != backupReplicated || v.Reason != "" || v.Region != "" {
+ t.Fatalf("view = %+v, want replicated", v)
+ }
+ if v.CopiedTo == nil || v.CopiedTo.Transaction != plan.TXID || !v.CopiedTo.WrittenAt.Equal(plan.At) {
+ t.Fatalf("copied_to = %+v, want %d at %v", v.CopiedTo, plan.TXID, plan.At)
+ }
+ if v.HistoryFrom == nil || !v.HistoryFrom.Equal(from) {
+ t.Fatalf("history_from = %v, want %v", v.HistoryFrom, from)
+ }
+ if v.HABorn || v.Files != "not_copied" {
+ t.Fatalf("HABorn %v files %q, want false and not_copied", v.HABorn, v.Files)
+ }
+
+ // The same host born HA: the files line is not_shown. The position is
+ // the memoised one; HABorn is the record's own.
+ rec.HA = true
+ v = fx.srv.backupsFor(t.Context(), rec)
+ if !v.HABorn || v.Files != "not_shown" || v.CopiedTo == nil {
+ t.Fatalf("born HA view = %+v, want HABorn and files not_shown", v)
+ }
+
+ b, err := json.Marshal(v)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var keys map[string]json.RawMessage
+ if err := json.Unmarshal(b, &keys); err != nil {
+ t.Fatal(err)
+ }
+ for _, k := range []string{"class", "copied_to", "history_from", "files"} {
+ if _, ok := keys[k]; !ok {
+ t.Errorf("%s missing from %s", k, b)
+ }
+ }
+ for _, k := range []string{"reason", "region", "HABorn", "ha_born"} {
+ if _, ok := keys[k]; ok {
+ t.Errorf("%s present in %s", k, b)
+ }
+ }
+ var pos map[string]json.RawMessage
+ if err := json.Unmarshal(keys["copied_to"], &pos); err != nil || len(pos) != 2 || pos["transaction"] == nil || pos["written_at"] == nil {
+ t.Errorf("copied_to = %s, want exactly transaction and written_at", keys["copied_to"])
+ }
+}
+
+func TestBackupsForNotShownNeverReadsBucket(t *testing.T) {
+ fx := dbFixture(t)
+ fx.srv.dbReplica = func(context.Context, string) (replicaReader, error) {
+ t.Error("dbReplica called for a record the door does not read")
+ return nil, errors.New("no")
+ }
+ for _, row := range backupsRows() {
+ if row.class == backupReplicated {
+ continue
+ }
+ t.Run(row.name, func(t *testing.T) {
+ fx.srv.cfg.Region = row.console
+ v := fx.srv.backupsFor(t.Context(), row.rec)
+ if v.Class != row.class || v.Reason != row.reason {
+ t.Fatalf("view = %q/%q, want %q/%q", v.Class, v.Reason, row.class, row.reason)
+ }
+ if v.CopiedTo != nil || v.HistoryFrom != nil {
+ t.Fatalf("view = %+v carries a position", v)
+ }
+ if v.Files != "not_copied" {
+ t.Fatalf("files = %q, want not_copied", v.Files)
+ }
+ wantRegion := ""
+ if row.reason == "other_region" {
+ wantRegion = regionlabel.ForCode(row.rec.Region, fx.srv.regionHome(), fx.srv.regionNames()).Text
+ if wantRegion == "" {
+ t.Fatal("no region label to name")
+ }
+ }
+ if v.Region != wantRegion {
+ t.Fatalf("region = %q, want %q", v.Region, wantRegion)
+ }
+ })
+ }
+}
+
+func TestBackupsForNothingReplicated(t *testing.T) {
+ fx := dbFixture(t)
+ v := fx.srv.backupsFor(t.Context(), provision.Record{Host: dbTestHost, Region: fx.srv.cfg.Region, Hibernate: backupsYes()})
+ if v.Class != backupNotShown || v.Reason != "nothing_replicated" || v.CopiedTo != nil || v.HistoryFrom != nil {
+ t.Fatalf("view = %+v, want not_shown/nothing_replicated", v)
+ }
+ if fx.opens.Load() != 1 {
+ t.Fatalf("dbReplica opened %d times, want 1", fx.opens.Load())
+ }
+}
+
+// listedReplica lists n level-0 files, transactions 1..n one each, and
+// serves a header for any of them. gate, when set, holds every listing
+// until it is closed; entered is signalled on each listing.
+type listedReplica struct {
+ n int
+ at time.Time
+ gate chan struct{}
+ entered chan struct{}
+}
+
+func (r *listedReplica) LTXFiles(ctx context.Context, level int, _ ltx.TXID, _ bool) (ltx.FileIterator, error) {
+ if r.entered != nil {
+ select {
+ case r.entered <- struct{}{}:
+ default:
+ }
+ }
+ if r.gate != nil {
+ select {
+ case <-r.gate:
+ case <-ctx.Done():
+ return nil, ctx.Err()
+ }
+ }
+ if level != 0 {
+ return ltx.NewFileInfoSliceIterator(nil), nil
+ }
+ fs := make([]*ltx.FileInfo, r.n)
+ for i := range fs {
+ tx := ltx.TXID(i + 1)
+ fs[i] = &ltx.FileInfo{Level: 0, MinTXID: tx, MaxTXID: tx, Size: 100, CreatedAt: r.at.Add(time.Duration(i) * time.Second)}
+ }
+ return ltx.NewFileInfoSliceIterator(fs), nil
+}
+
+func (r *listedReplica) OpenLTXFile(_ context.Context, _ int, minTXID, maxTXID ltx.TXID, offset, size int64) (io.ReadCloser, error) {
+ h := ltx.Header{Version: ltx.Version, PageSize: 4096, Commit: 2, MinTXID: minTXID, MaxTXID: maxTXID, Timestamp: r.at.UnixMilli()}
+ b, err := h.MarshalBinary()
+ if err != nil {
+ return nil, err
+ }
+ end := offset + size
+ if size <= 0 || end > int64(len(b)) {
+ end = int64(len(b))
+ }
+ return io.NopCloser(bytes.NewReader(b[offset:end])), nil
+}
+
+// blockingReplica lists nothing until its context ends.
+type blockingReplica struct{}
+
+func (blockingReplica) LTXFiles(ctx context.Context, _ int, _ ltx.TXID, _ bool) (ltx.FileIterator, error) {
+ <-ctx.Done()
+ return nil, ctx.Err()
+}
+
+func (blockingReplica) OpenLTXFile(context.Context, int, ltx.TXID, ltx.TXID, int64, int64) (io.ReadCloser, error) {
+ return nil, errors.New("blockingReplica opens nothing")
+}
+
+func TestBackupsForBounds(t *testing.T) {
+ at := time.Date(2026, 11, 11, 9, 0, 0, 0, time.UTC)
+ rec := func(slug string) provision.Record {
+ return provision.Record{Host: slug + ".go.tito.io", Hibernate: backupsYes()}
+ }
+ serve := func(fx *dbFx, m map[string]replicaReader, opens *atomic.Int32) {
+ fx.srv.dbReplica = func(_ context.Context, prefix string) (replicaReader, error) {
+ opens.Add(1)
+ rd, ok := m[prefix]
+ if !ok {
+ t.Errorf("unexpected prefix %q", prefix)
+ return nil, errors.New("unexpected prefix")
+ }
+ return rd, nil
+ }
+ }
+
+ t.Run("file cap", func(t *testing.T) {
+ fx := dbFixture(t)
+ opens := new(atomic.Int32)
+ serve(fx, map[string]replicaReader{
+ "instances/cap.go.tito.io": &listedReplica{n: 20000, at: at},
+ "instances/over.go.tito.io": &listedReplica{n: 20001, at: at},
+ }, opens)
+ v := fx.srv.backupsFor(t.Context(), rec("cap"))
+ if v.Class != backupReplicated || v.CopiedTo == nil || v.CopiedTo.Transaction != 20000 {
+ t.Fatalf("20,000 files = %+v, want replicated at 20000", v)
+ }
+ v = fx.srv.backupsFor(t.Context(), rec("over"))
+ if v.Class != backupNotShown || v.Reason != "too_large_to_plan" || v.CopiedTo != nil {
+ t.Fatalf("20,001 files = %+v, want not_shown/too_large_to_plan", v)
+ }
+ })
+
+ t.Run("deadline", func(t *testing.T) {
+ fx := dbFixture(t)
+ fx.srv.backups.deadline = 50 * time.Millisecond
+ opens := new(atomic.Int32)
+ serve(fx, map[string]replicaReader{"instances/slow.go.tito.io": blockingReplica{}}, opens)
+ start := time.Now()
+ v := fx.srv.backupsFor(t.Context(), rec("slow"))
+ if v.Class != backupNotShown || v.Reason != "too_large_to_plan" {
+ t.Fatalf("blocked read = %+v, want not_shown/too_large_to_plan", v)
+ }
+ if d := time.Since(start); d > 5*time.Second {
+ t.Fatalf("blocked read took %v", d)
+ }
+ })
+
+ t.Run("one read per host, memoised", func(t *testing.T) {
+ fx := dbFixture(t)
+ now := at
+ var nowMu sync.Mutex
+ fx.srv.backups.now = func() time.Time { nowMu.Lock(); defer nowMu.Unlock(); return now }
+ gated := &listedReplica{n: 3, at: at, gate: make(chan struct{}), entered: make(chan struct{}, 1)}
+ opens := new(atomic.Int32)
+ serve(fx, map[string]replicaReader{"instances/busy.go.tito.io": gated}, opens)
+
+ views := make([]backupsView, 2)
+ var wg sync.WaitGroup
+ wg.Add(1)
+ go func() { defer wg.Done(); views[0] = fx.srv.backupsFor(context.Background(), rec("busy")) }()
+ select {
+ case <-gated.entered:
+ case <-time.After(5 * time.Second):
+ t.Fatal("the first read never listed")
+ }
+ wg.Add(1)
+ go func() { defer wg.Done(); views[1] = fx.srv.backupsFor(context.Background(), rec("busy")) }()
+ deadline := time.Now().Add(5 * time.Second)
+ for fx.srv.backups.waiting("busy.go.tito.io") != 1 {
+ if time.Now().After(deadline) {
+ t.Fatal("the second call never joined the read in flight")
+ }
+ time.Sleep(time.Millisecond)
+ }
+ close(gated.gate)
+ wg.Wait()
+ if n := opens.Load(); n != 1 {
+ t.Fatalf("two concurrent calls opened the replica %d times, want 1", n)
+ }
+ for i, v := range views {
+ if v.Class != backupReplicated || v.CopiedTo == nil || v.CopiedTo.Transaction != 3 {
+ t.Fatalf("view %d = %+v", i, v)
+ }
+ }
+
+ nowMu.Lock()
+ now = at.Add(5*time.Minute - time.Second)
+ nowMu.Unlock()
+ if v := fx.srv.backupsFor(t.Context(), rec("busy")); v.Class != backupReplicated || opens.Load() != 1 {
+ t.Fatalf("a call within 5 minutes = %+v after %d opens, want the memo and 1", v, opens.Load())
+ }
+ nowMu.Lock()
+ now = at.Add(5 * time.Minute)
+ nowMu.Unlock()
+ if v := fx.srv.backupsFor(t.Context(), rec("busy")); v.Class != backupReplicated || opens.Load() != 2 {
+ t.Fatalf("a call at 5 minutes = %+v after %d opens, want a fresh read", v, opens.Load())
+ }
+ })
+
+ t.Run("a failed read is unavailable and not kept", func(t *testing.T) {
+ fx := dbFixture(t)
+ opens := new(atomic.Int32)
+ fx.srv.dbReplica = func(context.Context, string) (replicaReader, error) {
+ opens.Add(1)
+ return nil, errors.New("s3: something broke")
+ }
+ for i := 1; i <= 2; i++ {
+ v := fx.srv.backupsFor(t.Context(), rec("broken"))
+ if v.Class != backupNotShown || v.Reason != "unavailable" {
+ t.Fatalf("failed read = %+v, want not_shown/unavailable", v)
+ }
+ if opens.Load() != int32(i) {
+ t.Fatalf("after %d calls opened %d times", i, opens.Load())
+ }
+ }
+ })
+}
diff --git a/internal/console/server.go b/internal/console/server.go
index d8b6f6032..475675f82 100644
--- a/internal/console/server.go
+++ b/internal/console/server.go
@@ -1312,6 +1312,9 @@ type Server struct {
// trafficMemo holds the Overview traffic card's counts for a minute
// (analyticsview.go, analyticsMemo).
trafficMemo analyticsMemo
+ // backups holds each host's backups read for five minutes, one read
+ // in flight per host (backups.go, backupsMemo).
+ backups backupsMemo
// storeSizer is the storage pass's test seam for sizing a provisioned
// tenant object store: nil means "use the real S3 sizer"
// (sizeProvisionedStore, economicspass.go); tests inject a fake so a