carlos / platform Public

console-economics-speed: review fixes: byte-capped streaming usage reads, deadline fails the sweep, late writes corrected

Astra round 1 (NOT READY), all three findings:

- P1: every usage day object is read streaming (usageDayStore passes Open
  through) and no further than usageDayReadCap, 8 MiB, and one byte; the
  concurrent read limits day keys to it too. An object over the cap is
  skipped as an unreadable day is, logged, and remembered while settled.
  A copy for the cache is kept only while the body is 1 MiB or less, so
  a read no longer holds the body twice. Ten reads hold at most 80 MiB.
- P2: a sweep whose context ran out fails (readEconomicsUsage and
  buildEconomicsView check the context before publishing), so a partial
  view is never returned or cached.
- P2: a kept settled day is read again once it is 6 h old
  (usageDayMaxAge): the sweep lists no day objects, so there is no listing
  ETag to check against. A late write from a box suspended across a month
  end shows within 6 h; this month's days within the hourly pass.

Tests: a fixed byte ceiling (window x cap) over objects 16 times the cap,
a usage read held past the deadline with the metadata answering, and a
device writing Oct 31 on Nov 2.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 6030c7d3500ccdff0a88b2816387a548a4243c11 parent 243f74f
4 files changed, +377 −70
  • internal/console/economicsspeed_test.go +152 −20
  • internal/console/economicsview.go +11 −1
  • internal/console/testdata/perf-budgets.txt +1 −1
  • internal/console/usagedays.go +213 −48
diff --git a/internal/console/economicsspeed_test.go b/internal/console/economicsspeed_test.go
index 1021053db..b4f2ee1b9 100644
--- a/internal/console/economicsspeed_test.go
+++ b/internal/console/economicsspeed_test.go
@@ -3,11 +3,13 @@ package console
import (
"context"
"encoding/json"
+ "errors"
"fmt"
"maps"
"net/http"
"reflect"
"strings"
+ "sync/atomic"
"testing"
"time"
@@ -382,22 +384,37 @@ func TestEconomicsRereadsUnsettledAndChangedDays(t *testing.T) {
econMatches(t, "after the pass read changed "+settled, after, econReference(t, fx, period, now))
}
-// TestEconomicsOversizedUsageHoldsTheWindow: a box that writes many
-// oversized day objects costs a cold view at most readConcurrency bodies
-// at once, and the settled-day cache keeps none of them; the next cold
-// view reads them again, and the answer is the sequential sweep's.
+// TestEconomicsOversizedUsageHoldsTheWindow: a box that writes many usage
+// objects far over the read cap costs a cold view no more than
+// readConcurrency times the cap held at once, however large the objects;
+// each is read no further than one byte past the cap and skipped as an
+// unreadable day is. A settled one is remembered as over the cap, so the
+// next cold view does not read it again, and the answer is the sequential
+// sweep's over the objects within the cap.
func TestEconomicsOversizedUsageHoldsTheWindow(t *testing.T) {
perfCaptureLogs(t)
fx, lat := newPerfFixture(t)
c := signInPaul(t, fx)
ctx := context.Background()
now := time.Now()
- const huge = usageDayCacheMaxBody + 4096
+ seedEconomicsDays(t, fx, econDates(now))
+ prev := usageDayReadCap
+ usageDayReadCap = 64 << 10
+ t.Cleanup(func() { usageDayReadCap = prev })
+ ref := econReference(t, fx, "last", now)
+ if ref.err != nil {
+ t.Fatal(ref.err)
+ }
+ // Sixteen times the cap each, three windows' worth.
+ huge := int(16 * usageDayReadCap)
var floods []string
for _, date := range econPeriodDates("last", now) {
if len(floods) == 3*readConcurrency {
break
}
+ if !usageDaySettled(date, now) {
+ continue
+ }
raw, err := json.Marshal(econRollup("flood", date, fx.sqid, len(floods)))
if err != nil {
t.Fatal(err)
@@ -409,10 +426,6 @@ func TestEconomicsOversizedUsageHoldsTheWindow(t *testing.T) {
}
floods = append(floods, key)
}
- ref := econReference(t, fx, "last", now)
- if ref.err != nil {
- t.Fatal(ref.err)
- }
from, to := economicsPeriodBounds("last", now)
attrib, _, err := fx.srv.loadAttributionForEconomics()
@@ -423,32 +436,151 @@ func TestEconomicsOversizedUsageHoldsTheWindow(t *testing.T) {
if got.err != nil {
t.Fatal(got.err)
}
- if held.Largest < huge {
- t.Fatalf("the largest body held was %d bytes: the flood was not read", held.Largest)
+ if bound := int64(readConcurrency) * usageDayReadCap; held.Peak > bound {
+ t.Errorf("the sweep held %d bytes at once, over %d (%d bodies at the cap)", held.Peak, bound, readConcurrency)
}
- if bound := int64(readConcurrency) * held.Largest; held.Peak > bound {
- t.Errorf("the sweep held %d bytes at once, over %d (%d bodies)", held.Peak, bound, readConcurrency)
+ if held.Largest > usageDayReadCap {
+ t.Errorf("the sweep held a %d-byte body, over the %d-byte cap", held.Largest, usageDayReadCap)
+ }
+ if _, ok := got.sweep.PerBox["flood"]; ok {
+ t.Errorf("an over-cap rollup was counted: %v", got.sweep.PerBox["flood"])
}
for _, k := range floods {
- if _, ok := fx.srv.usageDays.get(k); ok {
- t.Errorf("the cache kept oversized %s", k)
+ e, ok := fx.srv.usageDays.get(k, now)
+ if !ok || !errors.Is(e.absent, errUsageDayTooLarge) || e.body != nil {
+ t.Errorf("%s: cache entry %v (held %v), want it remembered as over the cap, no body", k, e.absent, ok)
}
}
if _, bytes := fx.srv.usageDays.held(); bytes > usageDayCacheMaxBody {
- t.Errorf("the cache holds %d bytes after a sweep of oversized days", bytes)
+ t.Errorf("the cache holds %d bytes after a sweep of over-cap days", bytes)
}
rec := recordS3(lat, nil)
econViewCold(fx)
- econMatches(t, "oversized days", econView(t, fx, c, "/fleet/economics", "last"), ref)
+ econMatches(t, "over-cap days", econView(t, fx, c, "/fleet/economics", "last"), ref)
gets := econDayGets(rec)
for _, k := range floods {
- if gets[k] != 1 {
- t.Errorf("cold view: oversized %s read %d times, want once (it is never kept)", k, gets[k])
+ if gets[k] != 0 {
+ t.Errorf("cold view: over-cap %s read again %d times, want it remembered", k, gets[k])
}
}
}
+// TestEconomicsSweepPastItsDeadlineIsNotPublished: the scenario, its
+// listing and the bills answer at once while one usage day is held past
+// the sweep's deadline. The view fails with the deadline, as the reads one
+// after another did, and nothing is cached: the next view sweeps again.
+func TestEconomicsSweepPastItsDeadlineIsNotPublished(t *testing.T) {
+ perfCaptureLogs(t)
+ fx, lat := newPerfFixture(t)
+ c := signInPaul(t, fx)
+ now := time.Now()
+ dates := econDates(now)
+ seedEconomicsDays(t, fx, dates)
+ prev := economicsSweepTimeout
+ economicsSweepTimeout = 500 * time.Millisecond
+ t.Cleanup(func() { economicsSweepTimeout = prev })
+ held := metrics.DayKey("box-a", dates[len(dates)-1])
+ hold := make(chan struct{})
+ t.Cleanup(func() { close(hold) })
+ var metadata atomic.Int32
+ lat.Fake().OnRequest(func(r *http.Request) (int, <-chan struct{}) {
+ _, key, _ := strings.Cut(strings.TrimPrefix(r.URL.Path, "/"), "/")
+ if key == held {
+ return 0, hold
+ }
+ if strings.HasPrefix(key, "economics/") || r.URL.Query().Get("prefix") == economics.ScenariosPrefix {
+ metadata.Add(1)
+ }
+ return 0, nil
+ })
+ t.Cleanup(func() { lat.Fake().OnRequest(nil) })
+
+ econAllCold(fx)
+ start := time.Now()
+ _, err := fx.srv.LoadEconomics(context.Background(), "mtd")
+ if !errors.Is(err, context.DeadlineExceeded) {
+ t.Fatalf("LoadEconomics = %v, want the deadline", err)
+ }
+ if took := time.Since(start); took > 5*time.Second {
+ t.Errorf("the failed sweep took %v", took)
+ }
+ if metadata.Load() == 0 {
+ t.Errorf("no scenario or bill read: the test held the wrong request")
+ }
+ e := fx.srv.economicsCacheEntry("mtd")
+ e.mu.Lock()
+ cached := !e.at.IsZero() || e.view != nil
+ e.mu.Unlock()
+ if cached {
+ t.Errorf("a sweep past its deadline was cached")
+ }
+ if st, _, _ := get(t, c, fx.ts.URL+"/fleet/economics"); st != http.StatusInternalServerError {
+ t.Errorf("page = %d, want 500 while the day is held", st)
+ }
+}
+
+// TestEconomicsLateWriteAcrossTheMonthEnd: a device asleep across the month
+// end wakes on the 2nd and writes the 31st's last hours, and a box that had
+// written nothing for the 31st writes it. The console had already read the
+// 31st (settled since the 2nd began) and kept it. The hourly pass reads only
+// the new month, so the kept copy stands until it is usageDayMaxAge old;
+// the first sweep after that reads the 31st again and counts the late
+// hours.
+func TestEconomicsLateWriteAcrossTheMonthEnd(t *testing.T) {
+ perfCaptureLogs(t)
+ fx, _ := newPerfFixture(t)
+ ctx := context.Background()
+ woke := time.Date(2026, 11, 2, 10, 0, 0, 0, time.UTC)
+ const oct31 = "2026-10-31"
+ if !usageDaySettled(oct31, woke) {
+ t.Fatalf("%s is not settled at %v", oct31, woke)
+ }
+ hour := func(h int) time.Time { return time.Date(2026, 10, 31, h, 0, 0, 0, time.UTC) }
+ agg := metrics.HourAgg{Host: map[string]metrics.Agg{"cpu": {Avg: 0.5, N: 60}},
+ Units: map[string]map[string]metrics.Agg{"caddy.service": {"cpu": {Avg: 0.5, N: 60}}}}
+ if err := metrics.UpsertRollup(ctx, fx.rel, "box-a", hour(21), agg); err != nil {
+ t.Fatal(err)
+ }
+ attrib, _, err := fx.srv.loadAttributionForEconomics()
+ if err != nil {
+ t.Fatal(err)
+ }
+ hours := func(at time.Time) (a, b float64) {
+ t.Helper()
+ from, to := economicsPeriodBounds("last", at)
+ got, _ := fx.srv.readEconomicsUsage(ctx, from, to, attrib, at)
+ if got.err != nil {
+ t.Fatal(got.err)
+ }
+ return got.sweep.PerBox["box-a"].Hours, got.sweep.PerBox["box-b"].Hours
+ }
+ if a, b := hours(woke); a != 1 || b != 0 {
+ t.Fatalf("before the late writes: box-a %v hours, box-b %v, want 1 and 0", a, b)
+ }
+ // On the 2nd, the device writes the 31st's hours 22 and 23, and box-b
+ // its whole 31st.
+ for _, h := range []int{22, 23} {
+ if err := metrics.UpsertRollup(ctx, fx.rel, "box-a", hour(h), agg); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err := metrics.UpsertRollup(ctx, fx.rel, "box-b", hour(12), agg); err != nil {
+ t.Fatal(err)
+ }
+ later := woke.Add(time.Hour)
+ if err := fx.srv.statementsPass(ctx, later); err != nil {
+ t.Fatal(err)
+ }
+ if a, b := hours(later); a != 1 || b != 0 {
+ t.Errorf("an hour later: box-a %v hours, box-b %v, want the kept 1 and 0 (within usageDayMaxAge)", a, b)
+ }
+ aged := woke.Add(usageDayMaxAge)
+ if a, b := hours(aged); a != 3 || b != 1 {
+ t.Errorf("usageDayMaxAge later: box-a %v hours, box-b %v, want the late writes, 3 and 1", a, b)
+ }
+}
+
// TestEconomicsFailedReadsMatchTheSequentialSweep: a day object the bucket
// refuses is skipped, as it was when the reads ran in sequence, and is not
// remembered as absent: once the bucket answers, the next cold view reads
@@ -626,7 +758,7 @@ func TestUsageDayCacheBounds(t *testing.T) {
oldestKept = min(oldestKept, c.entries[k].date)
}
for k, date := range keys {
- if _, ok := c.get(k); !ok && date > oldestKept {
+ if _, ok := c.get(k, now); !ok && date > oldestKept {
t.Errorf("dropped %s (%s) while keeping older %s", k, date, oldestKept)
}
}
diff --git a/internal/console/economicsview.go b/internal/console/economicsview.go
index 0a9bc69a9..9cf334bb5 100644
--- a/internal/console/economicsview.go
+++ b/internal/console/economicsview.go
@@ -34,9 +34,13 @@ import (
const (
economicsCacheTTL = 60 * time.Second
economicsStaleServeCeiling = 2 * time.Minute
- economicsSweepTimeout = 15 * time.Second
)
+// economicsSweepTimeout bounds one buildEconomicsView; a sweep that runs
+// out of it fails rather than publishing what it had read. A variable only
+// so a test can run out of it quickly.
+var economicsSweepTimeout = 15 * time.Second
+
// EconomicsView is one priced period, ready to render.
type EconomicsView struct {
GeneratedAt time.Time
@@ -436,6 +440,12 @@ func (s *Server) buildEconomicsView(ctx context.Context, period string) (*Econom
if used.err != nil {
return nil, fmt.Errorf("console: load economics: %w", used.err)
}
+ // Every read above that met the deadline failed, and the ones that
+ // skip a failure (the fleet meters, the scenario) would leave a partial
+ // view: a view past its deadline is never published or cached.
+ if err := sweepCtx.Err(); err != nil {
+ return nil, fmt.Errorf("console: load economics: %w", err)
+ }
sweep := used.sweep
// Fleet meters (Task 3's fleetMeters) fold into sweep.PerAccount exactly
diff --git a/internal/console/testdata/perf-budgets.txt b/internal/console/testdata/perf-budgets.txt
index 2e2c2d5e3..075ffb746 100644
--- a/internal/console/testdata/perf-budgets.txt
+++ b/internal/console/testdata/perf-budgets.txt
@@ -74,7 +74,7 @@ GET /a/{sqid}/settings calls 2: the account telemetry settings and the storage e
GET /a/{sqid}/trash over: reads each trashed app's deleted.json marker (1 S3 call warm and cold per app)
GET /fleet over: the dashboard reads status/fleet.json, lists and reads every box report once each, and for a store operator lists and reads the storage entitlements, the same reads Boxes makes, all at once; operator pages are seldom viewed and carry no cache, and its SQLite reads add no remote call (12 S3 calls warm and cold, median about 133 ms, inside the budget; kept out of the timed walk, whose eleven views of it would cost 1.5 s of the walk's 10 s)
GET /fleet/boxes over: lists and reads every box report, reads status/fleet.json, and lists and reads the storage entitlements, all at once; operator pages are seldom viewed and carry no cache (12 S3 calls warm and cold, median about 133 ms, inside the budget; kept out of the timed walk as Dashboard is)
-GET /fleet/economics over: a cold view reads the period's usage days ten at a time and keeps the settled ones, every day before yesterday (console-economics-speed); month to date on the 27th, five objects a day and six more: 141 S3 calls, about 400 ms, with nothing held (was 168 one after another, about 4.3 s); 16 S3 calls, about 110 ms, once a view or the hourly economics pass has read the settled days; warm views come from the 60 s cache (0 S3 calls)
+GET /fleet/economics over: a cold view reads the period's usage days ten at a time, each no further than 8 MiB, and keeps the settled ones, every day before yesterday, for up to 6 h (console-economics-speed); month to date on the 27th, five objects a day and six more: 141 S3 calls, about 400 ms, with nothing held (was 168 one after another, about 4.3 s); 16 S3 calls, about 110 ms, once a view or the hourly economics pass has read the settled days; warm views come from the 60 s cache (0 S3 calls)
GET /fleet/economics/accounts over: shares /fleet/economics's sweep and its settled days, so its own cold view is that same sweep (141 S3 calls with nothing held, 16 with the settled days held, on the 27th); 0 S3 calls warm
GET /fleet/metrics over: a cold view reads every box's metrics hours for two days (about 120 S3 calls, counted in Overview's cold view); warm views are cached (0 S3 calls), and the walk never sees it cold: the app pages before it fill that cache and perfColdReset leaves it
GET /fleet/store over: lists the storage entitlements and the storage usage days and reads each pending application (3 S3 calls warm and cold, median about 80 ms)
diff --git a/internal/console/usagedays.go b/internal/console/usagedays.go
index 01fe8aa82..353bfafba 100644
--- a/internal/console/usagedays.go
+++ b/internal/console/usagedays.go
@@ -1,10 +1,13 @@
package console
import (
+ "bytes"
"context"
"errors"
+ "fmt"
+ "io"
+ "log"
"os"
- "slices"
"strings"
"sync"
"time"
@@ -26,9 +29,13 @@ import (
// bodies held at once, and the same answer, since the sweep's own code
// decides on exactly the bytes it read before.
// - Settled days are kept across views. A day's objects stop changing a
-// known time after the day ends (usageDaySettled), so a day before
-// that horizon is read once and kept; today and yesterday are read on
-// every cold view.
+// known time after the day ends (usageDaySettled), so a day before that
+// horizon is read once and kept for up to usageDayMaxAge; today and
+// yesterday are read on every cold view.
+//
+// Every usage object is read streaming and no further than usageDayReadCap
+// and one byte (a box writes what it likes under its own prefix): an object
+// over the cap is skipped as an unreadable day is, and logged.
//
// The hourly economics pass (statementsPass) already reads every day of the
// month to date from the bucket. It keeps reading them all, and leaves each
@@ -37,21 +44,38 @@ import (
// and yesterday. That adds no request.
// The cache's bounds. A body over usageDayCacheMaxBody is read on every
-// view and never kept (a box can write what it likes under its own
-// prefix); the whole cache holds at most usageDayCacheMaxBytes, counting
-// usageDayEntryOverhead and the key for every entry, a remembered absence
-// included. Past the budget the oldest days go first: month to date, the
-// page's default, is the last to lose its days.
+// view and never kept; the whole cache holds at most usageDayCacheMaxBytes,
+// counting usageDayEntryOverhead and the key for every entry, a remembered
+// absence included. Past the budget the oldest days go first: month to
+// date, the page's default, is the last to lose its days. An entry is
+// trusted for usageDayMaxAge after it was read, then read again.
const (
usageDayCacheMaxBody = 1 << 20
usageDayCacheMaxBytes = 64 << 20
usageDayEntryOverhead = 64
+ usageDayMaxAge = 6 * time.Hour
)
-// usageDayEntry is one settled day object: its body and ETag, or the error
-// that said it does not exist (os.ErrNotExist), returned again as it was.
+// usageDayReadCap is the most bytes the console reads of one usage day
+// object; past it the object is skipped. A day rollup indented as the box
+// agent writes it is about 23 KB per instance (cpu and memory, tagged with
+// its tenant) and an edge day about 5 KB per host, so 8 MiB holds a box
+// running some 350 instances, or serving some 1,600 hosts, all day: well
+// past any box today. Ten reads at a time (readConcurrency) hold at most
+// 80 MiB. A variable only so a test can show the bound with small objects.
+var usageDayReadCap int64 = 8 << 20
+
+// errUsageDayTooLarge is the read error of a usage day object over
+// usageDayReadCap. The sweep skips it as it skips any day it cannot read.
+var errUsageDayTooLarge = errors.New("console: usage day object over the read cap")
+
+// usageDayEntry is one settled day object read at at: its body and ETag,
+// or the error the read gave and will give again for the same object (it
+// does not exist, os.ErrNotExist, or it is over the cap,
+// errUsageDayTooLarge), returned again as it was.
type usageDayEntry struct {
date string
+ at time.Time
body []byte
etag string
absent error
@@ -131,11 +155,15 @@ func daysDirBox(dir, prefix string) (string, bool) {
// fleet's prefix) is written when an hour closes: metricsFlush rolls up
// every hour older than the current one still in its buffer
// (internal/host/metrics_loop.go:221-245), and that buffer holds at most
-// samplerMaxBuf (120) one-minute samples, about two hours
-// (metrics_loop.go:44, the cap enforced in tick, :148-152). The restart
-// repair backfillPrevHourRollup rolls up only the hour before the
-// process started (metrics_loop.go:291-322). So the last write to a day
-// lands about two hours after it ends, plus a five-minute flush.
+// samplerMaxBuf (120) one-minute samples, about two hours of a running
+// box (metrics_loop.go:44, the cap enforced in tick, :148-152). The
+// restart repair backfillPrevHourRollup rolls up only the hour before
+// the process started (metrics_loop.go:291-322). So the last write to a
+// day lands about two hours after it ends, plus a five-minute flush.
+// The cap counts samples, not their age: a box suspended with samples
+// in its buffer (a device asleep across a month end, say) writes them
+// to their old day when it wakes, however late. usageDayMaxAge is what
+// brings such a write to the page.
// - A box's edge day takes deltas for the day the flush runs in, never an
// earlier one (usage.UpsertEdgeDay, internal/usage/edge.go:117-122,
// called every five minutes with time.Now(), internal/host/usage_loop.go).
@@ -144,7 +172,13 @@ func daysDirBox(dir, prefix string) (string, bool) {
// (internal/console/economicspass.go censusPass and storagePass).
//
// A day becomes settled at least 24 hours after its end, past all of these
-// with a day's margin for clock skew and retries.
+// with a day's margin for clock skew and retries. A late write past that
+// (a suspended box, a box whose clock was wrong) is not caught by the
+// horizon: a kept day is read again once it is usageDayMaxAge old, and the
+// hourly pass reads every day of the month to date again, so such a write
+// shows within six hours, within an hour for this month's days. The sweep
+// lists only the box prefixes, never the day objects, so there is no
+// listing ETag to check a kept day against without a request.
func usageDaySettled(date string, now time.Time) bool {
d, err := time.Parse("2006-01-02", date)
if err != nil {
@@ -162,29 +196,35 @@ func usageDayFirstKept(now time.Time) string {
return usage.DayOf(first.AddDate(0, -1, 0))
}
-func (c *usageDayCache) get(key string) (usageDayEntry, bool) {
+// get is key's entry, when it was read less than usageDayMaxAge before now.
+func (c *usageDayCache) get(key string, now time.Time) (usageDayEntry, bool) {
c.mu.Lock()
defer c.mu.Unlock()
e, ok := c.entries[key]
- return e, ok
+ if !ok || now.Sub(e.at) >= usageDayMaxAge {
+ return usageDayEntry{}, false
+ }
+ return e, true
}
-// put keeps one settled read: a body no larger than usageDayCacheMaxBody,
-// or a not-found. Any other error says nothing about the day and changes
-// nothing; an oversized body drops a copy held from before. Past the
-// budget, the oldest days are dropped first, which may be this one.
+// put keeps one settled read, made at now: a body no larger than
+// usageDayCacheMaxBody (put keeps it; the caller must not change it), a
+// not-found or an object over the read cap. Any other error says nothing
+// about the day and changes nothing; tooBig (a body read whole but too
+// large to keep) drops a copy held from before. Past the budget, the
+// oldest days are dropped first, which may be this one.
func (c *usageDayCache) put(key, date string, body []byte, etag string, err error, now time.Time) {
var e usageDayEntry
switch {
- case err == nil && len(body) <= usageDayCacheMaxBody:
- e = usageDayEntry{date: date, body: slices.Clone(body), etag: etag}
case err == nil:
+ e = usageDayEntry{date: date, at: now, body: body, etag: etag}
+ case errors.Is(err, errUsageDayTooBigToKeep):
c.mu.Lock()
c.dropLocked(key)
c.mu.Unlock()
return
- case errors.Is(err, os.ErrNotExist):
- e = usageDayEntry{date: date, absent: err}
+ case errors.Is(err, os.ErrNotExist), errors.Is(err, errUsageDayTooLarge):
+ e = usageDayEntry{date: date, at: now, absent: err}
default:
return
}
@@ -237,17 +277,24 @@ func (c *usageDayCache) held() (n int, bytes int64) {
}
// usageDayStore reads usage day objects through the settled-day cache.
-// Every other request passes through to the store untouched.
+// Every other request passes through to the store untouched, Open included.
+//
+// A usage day object is read streaming (Open) and no further than
+// usageDayReadCap and one byte. While it is read, a copy is kept of a body
+// no larger than usageDayCacheMaxBody for the cache; a larger one is only
+// passed on. So one read holds at most the body its reader takes, plus a
+// copy of at most usageDayCacheMaxBody.
//
// A page view's store (use true) answers a settled day from the cache when
-// it holds it, and keeps each settled day it reads. Today's and yesterday's
-// storage days are read once per view rather than twice (sweepUsage reads
-// them for coverage and foldStorageAndCensus for bytes): at most two
-// bodies, each no larger than usageDayCacheMaxBody, held for the view.
+// it holds a read younger than usageDayMaxAge, and keeps each settled day it
+// reads. Today's and yesterday's storage days are read once per view rather
+// than twice (sweepUsage reads them for coverage and foldStorageAndCensus
+// for bytes): at most two bodies, each no larger than usageDayCacheMaxBody,
+// held for the view.
//
-// The economics pass's store (use false) reads everything from the bucket,
-// exactly as before, and keeps each settled day it read, replacing what
-// was held: so a day the pass has read is never older than the pass.
+// The economics pass's store (use false) reads everything from the bucket
+// and keeps each settled day it read, replacing what was held: so a day the
+// pass has read is never older than the pass.
type usageDayStore struct {
release.Store
cache *usageDayCache
@@ -258,6 +305,10 @@ type usageDayStore struct {
view map[string]fetched
}
+// errUsageDayTooBigToKeep is what a read leaves for the cache when it read
+// a body whole that is too large to keep: drop any copy held from before.
+var errUsageDayTooBigToKeep = errors.New("console: usage day object too large to keep")
+
// usageDayReader is a page view's store over the cache, at now.
func (s *Server) usageDayReader(now time.Time) *usageDayStore {
s.usageDays.prune(now)
@@ -271,18 +322,54 @@ func (s *Server) usageDayFiller(now time.Time) *usageDayStore {
return &usageDayStore{Store: s.cfg.Releases, cache: &s.usageDays, now: now}
}
+// usageDayLimit is readConcurrently's limit for the economics sweep: the
+// read cap for a usage day object, none for anything else.
+func usageDayLimit(key string) int64 {
+ if _, ok := usageDayDate(key); ok {
+ return usageDayReadCap
+ }
+ return 0
+}
+
+// Get is Open read whole: for a usage day object, no further than the cap.
func (d *usageDayStore) Get(ctx context.Context, key string) ([]byte, string, error) {
+ if _, ok := usageDayDate(key); !ok {
+ return d.Store.Get(ctx, key)
+ }
+ rc, etag, err := d.open(ctx, key)
+ if err != nil {
+ return nil, "", err
+ }
+ defer rc.Close()
+ body, err := io.ReadAll(rc)
+ if err != nil {
+ return nil, "", err
+ }
+ return body, etag, nil
+}
+
+// Open streams key (release.Opener). A usage day object comes from the
+// cache when it holds it, and otherwise from the store through a
+// usageDayRead.
+func (d *usageDayStore) Open(ctx context.Context, key string) (io.ReadCloser, string, error) {
+ return d.open(ctx, key)
+}
+
+// open is Open, under a name of its own: the claim authority census
+// (claim_authority_census_test.go) reviews every call of a method named
+// Open, and this one opens nothing but a read.
+func (d *usageDayStore) open(ctx context.Context, key string) (io.ReadCloser, string, error) {
date, ok := usageDayDate(key)
if !ok {
- return d.Store.Get(ctx, key)
+ return release.OpenObject(ctx, d.Store, key)
}
settled := usageDaySettled(date, d.now)
if settled && d.use {
- if e, hit := d.cache.get(key); hit {
+ if e, hit := d.cache.get(key, d.now); hit {
if e.absent != nil {
return nil, "", e.absent
}
- return e.body, e.etag, nil
+ return io.NopCloser(bytes.NewReader(e.body)), e.etag, nil
}
}
once := d.use && !settled && key == usage.StorageDayKey(date)
@@ -291,21 +378,92 @@ func (d *usageDayStore) Get(ctx context.Context, key string) ([]byte, string, er
f, seen := d.view[key]
d.mu.Unlock()
if seen {
- return f.body, f.etag, f.err
+ if f.err != nil {
+ return nil, "", f.err
+ }
+ return io.NopCloser(bytes.NewReader(f.body)), f.etag, nil
}
}
- body, etag, err := d.Store.Get(ctx, key)
- if settled {
- d.cache.put(key, date, body, etag, err, d.now)
+ // keep takes what a finished read leaves behind: a body small enough to
+ // keep, or an error that will be the same next time.
+ keep := func(body []byte, etag string, err error) {
+ if settled {
+ d.cache.put(key, date, body, etag, err, d.now)
+ }
+ if once && (err == nil || errors.Is(err, os.ErrNotExist) || errors.Is(err, errUsageDayTooLarge)) {
+ d.mu.Lock()
+ d.view[key] = fetched{body: body, etag: etag, err: err}
+ d.mu.Unlock()
+ }
}
- if once && (err == nil && len(body) <= usageDayCacheMaxBody || errors.Is(err, os.ErrNotExist)) {
- d.mu.Lock()
- d.view[key] = fetched{body: body, etag: etag, err: err}
- d.mu.Unlock()
+ rc, etag, err := release.OpenObject(ctx, d.Store, key)
+ if err != nil {
+ keep(nil, "", err)
+ return nil, "", err
+ }
+ return &usageDayRead{ctx: ctx, rc: rc, key: key, etag: etag, keeping: settled || once, keep: keep}, etag, nil
+}
+
+// usageDayRead is one usage day object streaming from the store. It never
+// asks for more than one byte past usageDayReadCap, and fails with
+// errUsageDayTooLarge once that byte has come. While the body is no larger
+// than usageDayCacheMaxBody it keeps a copy for the cache. When the read
+// ends, at the end of the body or at the cap, it hands keep the copy or
+// the error, once.
+type usageDayRead struct {
+ ctx context.Context
+ rc io.ReadCloser
+ key string
+ etag string
+ n int64
+ copy []byte
+ keeping bool
+ done bool
+ keep func(body []byte, etag string, err error)
+}
+
+func (r *usageDayRead) Read(p []byte) (int, error) {
+ if r.n > usageDayReadCap {
+ return 0, fmt.Errorf("%s: %w", r.key, errUsageDayTooLarge)
}
- return body, etag, err
+ if room := usageDayReadCap + 1 - r.n; int64(len(p)) > room {
+ p = p[:room]
+ }
+ n, err := r.rc.Read(p)
+ r.n += int64(n)
+ if r.keeping {
+ if int64(len(r.copy)+n) > usageDayCacheMaxBody {
+ r.keeping, r.copy = false, nil
+ } else {
+ r.copy = append(r.copy, p[:n]...)
+ }
+ }
+ if r.n > usageDayReadCap {
+ tooLarge := fmt.Errorf("%s: %w", r.key, errUsageDayTooLarge)
+ if !r.done {
+ r.done = true
+ log.Printf("console: sweep usage: %s is over %d bytes; skipped like an unreadable day", r.key, usageDayReadCap)
+ jobFailed(r.ctx, fmt.Errorf("sweep usage: %w", tooLarge))
+ r.keep(nil, "", tooLarge)
+ }
+ return n, tooLarge
+ }
+ if err == io.EOF && !r.done {
+ r.done = true
+ if r.keeping {
+ if r.copy == nil {
+ r.copy = []byte{}
+ }
+ r.keep(r.copy, r.etag, nil)
+ } else {
+ r.keep(nil, "", errUsageDayTooBigToKeep)
+ }
+ }
+ return n, err
}
+func (r *usageDayRead) Close() error { return r.rc.Close() }
+
// economicsUsage is what the dashboard reads per day for one period: the
// sweep with storage and census folded in (or the error either returned),
// and the fleet meters (or the error that degrades them to a warning).
@@ -324,7 +482,7 @@ func (s *Server) readEconomicsUsage(ctx context.Context, from, to time.Time, att
st := s.usageDayReader(now)
// "{}" decodes to an empty rollup, edge, storage and census day, which
// every reader here takes without a word.
- return readConcurrentlyStats(ctx, st, []byte("{}"), nil, func(rs release.Store) economicsUsage {
+ out, held := readConcurrentlyStats(ctx, st, []byte("{}"), usageDayLimit, func(rs release.Store) economicsUsage {
sweep, err := s.sweepUsage(ctx, rs, from, to, attrib)
if err != nil {
return economicsUsage{err: err}
@@ -338,4 +496,11 @@ func (s *Server) readEconomicsUsage(ctx context.Context, from, to time.Time, att
}
return out
})
+ // The sweep skips a day it cannot read, and a read cut off by the
+ // deadline is one: a sweep that ran out of time is a failed sweep, never
+ // partial totals.
+ if err := ctx.Err(); err != nil && out.err == nil {
+ out = economicsUsage{err: fmt.Errorf("console: sweep usage: %w", err)}
+ }
+ return out, held
}