console-economics-speed: /fleet/economics reads its usage days concurrently and keeps settled days
A cold economics view (and /fleet/economics/accounts, which shares the sweep) read every day object of the period one after another: 168 S3 calls and about 4.3 s for month to date on the 27th in the perf fixture. - The period's day objects (each box's metrics rollup and edge day, each fleet box's rollup, the storage and census days) are read through readConcurrently, ten at a time with at most ten bodies held. The sweep's own code still decides on the bytes, so the answer is the same. The two box listings, the active scenario, the scenario listing and the bills are read alongside; errors are taken in the old order. - Settled days (every day before yesterday) are kept across views in a bounded cache keyed by object key (usagedays.go): only days from the first of last month, bodies of 1 MiB or less, 64 MiB in all, oldest days dropped first. Not-founds are kept; failed reads are not. The horizon comes from the writers: the box agent's sample buffer (samplerMaxBuf, about 2 h), edge days written only for the flush's day, create-only storage and census days. - statementsPass still reads every day of the month from the bucket and now leaves each settled day it read in that cache, so a cold view after the hourly pass reads only today and yesterday. No read is added. - prefetchStore keeps ListDirs answers like List's, so the dry pass's box listings are not repeated. Fixture, month to date on the 27th: nothing held 141 S3 calls, about 400 ms; settled days held 16 calls, about 110 ms; warm 0. The perf records keep over: with the new numbers.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
9 files changed,
+1,108
−53
internal/console/economicspass.go+78 −31internal/console/economicsspeed_test.go+633 −0internal/console/economicsview.go+28 −16internal/console/hotreads.go+19 −1internal/console/server.go+4 −0internal/console/testdata/perf-budgets.txt+2 −2internal/console/usageattrib_tags_test.go+2 −2internal/console/usageattrib_test.go+1 −1internal/console/usagedays.go+341 −0
CI failed — run details
diff --git a/internal/console/economicspass.go b/internal/console/economicspass.go| index 2ff843954..3b4711d7b 100644 |
| --- a/internal/console/economicspass.go |
| +++ b/internal/console/economicspass.go |
| @@ -367,14 +367,26 @@ type usageSweep struct { |
| // sweep and nothing else is still a covered day, exactly as before this |
| // function existed, even though the bytes themselves are read again by |
| // foldStorageAndCensus. |
| -func (s *Server) sweepUsage(ctx context.Context, from, to time.Time, attrib *usageAttribution) (*usageSweep, error) { |
| - metricsBoxes, err := s.cfg.Releases.ListDirs(ctx, metricsBoxesPrefix) |
| - if err != nil { |
| - return nil, fmt.Errorf("console: sweep usage: %w", err) |
| - } |
| - edgeBoxes, err := s.cfg.Releases.ListDirs(ctx, usage.EdgeBoxesPrefix) |
| - if err != nil { |
| - return nil, fmt.Errorf("console: sweep usage: %w", err) |
| +// |
| +// Every read goes through st: the bucket itself for statementsPass (through |
| +// the settled-day cache's filling wrapper, usagedays.go), and for the |
| +// dashboard a concurrent reader over that cache (readEconomicsUsage). Which |
| +// keys it reads follows from the two box listings and the dates alone, |
| +// never from a body, which is what lets readConcurrently fetch them ahead. |
| +func (s *Server) sweepUsage(ctx context.Context, st release.Store, from, to time.Time, attrib *usageAttribution) (*usageSweep, error) { |
| + var ( |
| + metricsBoxes, edgeBoxes []string |
| + mErr, eErr error |
| + ) |
| + runConcurrently( |
| + func() { metricsBoxes, mErr = st.ListDirs(ctx, metricsBoxesPrefix) }, |
| + func() { edgeBoxes, eErr = st.ListDirs(ctx, usage.EdgeBoxesPrefix) }, |
| + ) |
| + if mErr != nil { |
| + return nil, fmt.Errorf("console: sweep usage: %w", mErr) |
| + } |
| + if eErr != nil { |
| + return nil, fmt.Errorf("console: sweep usage: %w", eErr) |
| } |
| sweep := &usageSweep{ |
| @@ -418,7 +430,7 @@ func (s *Server) sweepUsage(ctx context.Context, from, to time.Time, attrib *usa |
| for _, boxPrefix := range metricsBoxes { |
| box := strings.TrimSuffix(strings.TrimPrefix(boxPrefix, metricsBoxesPrefix), "/") |
| - raw, _, gerr := s.cfg.Releases.Get(ctx, metrics.DayKey(box, date)) |
| + raw, _, gerr := st.Get(ctx, metrics.DayKey(box, date)) |
| if gerr != nil { |
| continue // missing = skip, uncovered by this box |
| } |
| @@ -482,7 +494,7 @@ func (s *Server) sweepUsage(ctx context.Context, from, to time.Time, attrib *usa |
| for _, boxPrefix := range edgeBoxes { |
| box := strings.TrimSuffix(strings.TrimPrefix(boxPrefix, usage.EdgeBoxesPrefix), "/") |
| - raw, _, gerr := s.cfg.Releases.Get(ctx, usage.EdgeDayKey(box, date)) |
| + raw, _, gerr := st.Get(ctx, usage.EdgeDayKey(box, date)) |
| if gerr != nil { |
| continue // missing = skip, uncovered by this box |
| } |
| @@ -520,7 +532,7 @@ func (s *Server) sweepUsage(ctx context.Context, from, to time.Time, attrib *usa |
| // its bytes are not accumulated: that needs statementsPass's |
| // ValidAccount guard and pass-scoped dedup logging. Missing = skip, |
| // uncovered by storage (metrics/edge may still have covered it). |
| - if raw, _, gerr := s.cfg.Releases.Get(ctx, usage.StorageDayKey(date)); gerr == nil { |
| + if raw, _, gerr := st.Get(ctx, usage.StorageDayKey(date)); gerr == nil { |
| var sd usage.StorageDay |
| if jerr := json.Unmarshal(raw, &sd); jerr == nil { |
| covered = true |
| @@ -559,8 +571,8 @@ func (s *Server) sweepUsage(ctx context.Context, from, to time.Time, attrib *usa |
| // badStorageKeys dedups a malformed storage-day key's log line at most once |
| // per key for this ONE CALL — matching the pre-split pass-scoped behaviour, |
| // since each of statementsPass and buildEconomicsView calls this exactly |
| -// once per invocation. |
| -func (s *Server) foldStorageAndCensus(ctx context.Context, from, to time.Time, dst map[string]map[string]float64) error { |
| +// once per invocation. Its reads go through st, as sweepUsage's do. |
| +func (s *Server) foldStorageAndCensus(ctx context.Context, st release.Store, from, to time.Time, dst map[string]map[string]float64) error { |
| touch := func(acct string) map[string]float64 { |
| mm := dst[acct] |
| if mm == nil { |
| @@ -578,7 +590,7 @@ func (s *Server) foldStorageAndCensus(ctx context.Context, from, to time.Time, d |
| y, mo, _ := d.Date() |
| daysInMonth := time.Date(y, mo+1, 0, 0, 0, 0, 0, time.UTC).Day() |
| - if raw, _, gerr := s.cfg.Releases.Get(ctx, usage.StorageDayKey(date)); gerr == nil { |
| + if raw, _, gerr := st.Get(ctx, usage.StorageDayKey(date)); gerr == nil { |
| var sd usage.StorageDay |
| if jerr := json.Unmarshal(raw, &sd); jerr != nil { |
| log.Printf("console: fold storage/census: parse %s: %v", usage.StorageDayKey(date), jerr) |
| @@ -613,7 +625,7 @@ func (s *Server) foldStorageAndCensus(ctx context.Context, from, to time.Time, d |
| // Census does not gate coverage (sweepUsage's covered-day sources are |
| // metrics/edge/storage only) but still feeds app_months when present. |
| - if raw, _, gerr := s.cfg.Releases.Get(ctx, usage.CensusDayKey(date)); gerr == nil { |
| + if raw, _, gerr := st.Get(ctx, usage.CensusDayKey(date)); gerr == nil { |
| var cd usage.CensusDay |
| if jerr := json.Unmarshal(raw, &cd); jerr != nil { |
| log.Printf("console: fold storage/census: parse %s: %v", usage.CensusDayKey(date), jerr) |
| @@ -780,7 +792,27 @@ func hasDeviceTag(tags string) bool { |
| // statements are a create-OR-REPLACE snapshot of the whole month to |
| // date, not an append-only ledger, so there is no "as of" boundary to |
| // honor. Modelling-grade, matching every other meter this pass derives. |
| -func (s *Server) fleetMeters(ctx context.Context, from, to time.Time) (map[string]map[string]float64, error) { |
| +// |
| +// Its reads go through st (see sweepUsage); the registry half is |
| +// fleetMeterBoxes, so a caller reading concurrently asks the registry once. |
| +func (s *Server) fleetMeters(ctx context.Context, st release.Store, from, to time.Time) (map[string]map[string]float64, error) { |
| + boxes, err := s.fleetMeterBoxes() |
| + if err != nil { |
| + return nil, err |
| + } |
| + return fleetMetersFrom(ctx, st, boxes, from, to), nil |
| +} |
| + |
| +// fleetMeterBox is one fleet box fleetMeters reads: its fleet and label, |
| +// the account it bills and whether it is a device. |
| +type fleetMeterBox struct { |
| + fleet, label, acct string |
| + device bool |
| +} |
| + |
| +// fleetMeterBoxes is every box registered to every fleet, ALL statuses (see |
| +// fleetMeters), in fleet then label order. |
| +func (s *Server) fleetMeterBoxes() ([]fleetMeterBox, error) { |
| reg, err := s.openPassRegistry() |
| if err != nil { |
| return nil, fmt.Errorf("console: fleet meters: %w", err) |
| @@ -790,23 +822,33 @@ func (s *Server) fleetMeters(ctx context.Context, from, to time.Time) (map[strin |
| return nil, fmt.Errorf("console: fleet meters: %w", err) |
| } |
| - type boxOwner struct { |
| - acct string |
| - device bool |
| - } |
| type boxKey struct{ fleet, label string } |
| - boxes := map[boxKey]boxOwner{} |
| - |
| + byKey := map[boxKey]fleetMeterBox{} |
| for _, f := range fleets { |
| fboxes, err := reg.ListFleetBoxes(f.Name) |
| if err != nil { |
| return nil, fmt.Errorf("console: fleet meters: list boxes %s: %w", f.Name, err) |
| } |
| for _, b := range fboxes { |
| - boxes[boxKey{fleet: f.Name, label: b.Label}] = boxOwner{acct: f.Account, device: hasDeviceTag(b.Tags)} |
| + byKey[boxKey{fleet: f.Name, label: b.Label}] = fleetMeterBox{fleet: f.Name, label: b.Label, acct: f.Account, device: hasDeviceTag(b.Tags)} |
| } |
| } |
| + boxes := make([]fleetMeterBox, 0, len(byKey)) |
| + for _, b := range byKey { |
| + boxes = append(boxes, b) |
| + } |
| + sort.Slice(boxes, func(i, j int) bool { |
| + if boxes[i].fleet != boxes[j].fleet { |
| + return boxes[i].fleet < boxes[j].fleet |
| + } |
| + return boxes[i].label < boxes[j].label |
| + }) |
| + return boxes, nil |
| +} |
| +// fleetMetersFrom is fleetMeters's read over boxes: one Get per box per day |
| +// in [from, to], through st. |
| +func fleetMetersFrom(ctx context.Context, st release.Store, boxes []fleetMeterBox, from, to time.Time) map[string]map[string]float64 { |
| out := map[string]map[string]float64{} |
| touch := func(acct string) map[string]float64 { |
| mm := out[acct] |
| @@ -819,12 +861,12 @@ func (s *Server) fleetMeters(ctx context.Context, from, to time.Time) (map[strin |
| fromDay := from.UTC().Truncate(24 * time.Hour) |
| toDay := to.UTC().Truncate(24 * time.Hour) |
| - for bk, owner := range boxes { |
| + for _, bk := range boxes { |
| meter := usage.MeterFleetBoxHoursServer |
| - if owner.device { |
| + if bk.device { |
| meter = usage.MeterFleetBoxHoursDevice |
| } |
| - fleetStore := release.NewPrefixStore(s.cfg.Releases, "fleets/"+bk.fleet+"/") |
| + fleetStore := release.NewPrefixStore(st, "fleets/"+bk.fleet+"/") |
| for d := fromDay; !d.After(toDay); d = d.AddDate(0, 0, 1) { |
| date := usage.DayOf(d) |
| key := metrics.DayKey(bk.label, date) |
| @@ -838,10 +880,10 @@ func (s *Server) fleetMeters(ctx context.Context, from, to time.Time) (map[strin |
| jobFailed(ctx, fmt.Errorf("fleet meters: parse fleets/%s/%s: %w", bk.fleet, key, jerr)) |
| continue |
| } |
| - touch(owner.acct)[meter] += rollupPresenceHours(roll) |
| + touch(bk.acct)[meter] += rollupPresenceHours(roll) |
| } |
| } |
| - return out, nil |
| + return out |
| } |
| // statementsPass folds the month's metrics, edge and storage days (plus |
| @@ -892,15 +934,20 @@ func (s *Server) statementsPass(ctx context.Context, now time.Time) error { |
| month := usage.MonthOf(nowUTC) |
| monthStart := time.Date(y, mo, 1, 0, 0, 0, 0, time.UTC) |
| - sweep, err := s.sweepUsage(ctx, monthStart, nowUTC, attrib) |
| + // The pass reads every day of the month from the bucket, as it always |
| + // has, and leaves each settled day it read in the dashboard's day cache |
| + // (usagedays.go): no read of its own is skipped or added, and the next |
| + // cold dashboard view finds the month's settled days already held. |
| + st := s.usageDayFiller(now) |
| + sweep, err := s.sweepUsage(ctx, st, monthStart, nowUTC, attrib) |
| if err != nil { |
| return fmt.Errorf("console: statements pass: %w", err) |
| } |
| meters := sweep.PerAccount // account -> meter -> value; folded into below |
| - if err := s.foldStorageAndCensus(ctx, monthStart, nowUTC, meters); err != nil { |
| + if err := s.foldStorageAndCensus(ctx, st, monthStart, nowUTC, meters); err != nil { |
| return fmt.Errorf("console: statements pass: %w", err) |
| } |
| - fleetMM, err := s.fleetMeters(ctx, monthStart, nowUTC) |
| + fleetMM, err := s.fleetMeters(ctx, st, monthStart, nowUTC) |
| if err != nil { |
| return fmt.Errorf("console: statements pass: %w", err) |
| } |
diff --git a/internal/console/economicsspeed_test.go b/internal/console/economicsspeed_test.go| new file mode 100644 |
| index 000000000..1021053db |
| --- /dev/null |
| +++ b/internal/console/economicsspeed_test.go |
| @@ -0,0 +1,633 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "fmt" |
| + "maps" |
| + "net/http" |
| + "reflect" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/economics" |
| + "github.com/carlosframework/platform/internal/metrics" |
| + "github.com/carlosframework/platform/internal/usage" |
| +) |
| + |
| +// The economics sweep's speed (console-economics-speed): its per-day reads |
| +// run concurrently, and settled days are kept across views. Every test |
| +// here runs over newPerfFixture, whose console reads a real S3 store over |
| +// the fake, and counts what reaches the fake. |
| + |
| +// econViewCold forgets LoadEconomics's per-period view cache, so the next |
| +// view sweeps; the settled-day cache is left as it is. |
| +func econViewCold(fx *consoleFixture) { |
| + c := &fx.srv.economicsCache |
| + c.mu.Lock() |
| + c.entries = nil |
| + c.mu.Unlock() |
| +} |
| + |
| +// econAllCold forgets the view cache and the settled-day cache: a console |
| +// that has read nothing for the page. |
| +func econAllCold(fx *consoleFixture) { |
| + econViewCold(fx) |
| + d := &fx.srv.usageDays |
| + d.mu.Lock() |
| + d.entries, d.bytes = nil, 0 |
| + d.mu.Unlock() |
| +} |
| + |
| +// econDates is every date from the first of last month to today, the days |
| +// any period the page offers can show. |
| +func econDates(now time.Time) []string { |
| + var out []string |
| + first, _ := time.Parse("2006-01-02", usageDayFirstKept(now)) |
| + for d := first; !d.After(now.UTC()); d = d.AddDate(0, 0, 1) { |
| + out = append(out, usage.DayOf(d)) |
| + } |
| + return out |
| +} |
| + |
| +// econPeriodDates is the dates period sweeps at now. |
| +func econPeriodDates(period string, now time.Time) []string { |
| + from, to := economicsPeriodBounds(period, now) |
| + var out []string |
| + for d := from.UTC().Truncate(24 * time.Hour); !d.After(to.UTC().Truncate(24 * time.Hour)); d = d.AddDate(0, 0, 1) { |
| + out = append(out, usage.DayOf(d)) |
| + } |
| + return out |
| +} |
| + |
| +// econRollup is a metrics day with one platform unit and one instance |
| +// whose hour the box tagged with acct, sized by n so that every day adds |
| +// something different. Every figure is a sum of binary fractions, so a |
| +// period's totals are exact in any order: the sweep adds a day's units in |
| +// map order, which varies from run to run. |
| +func econRollup(box, date, acct string, n int) metrics.DayRollup { |
| + cpu := 0.25 * float64(n%4+1) |
| + return metrics.DayRollup{V: 1, Box: box, Date: date, Hours: map[string]metrics.HourAgg{ |
| + "09": { |
| + Host: map[string]metrics.Agg{"cpu": {Avg: 0.5, N: 60}}, |
| + Units: map[string]map[string]metrics.Agg{ |
| + "caddy.service": {"cpu": {Avg: cpu, N: 60}, "mem_bytes": {Avg: 5e8, N: 60}}, |
| + "carlos-exec@shop.example.com": {"cpu": {Avg: cpu / 2, N: 60}, "mem_bytes": {Avg: 1e9, N: 60}}, |
| + }, |
| + Owned: map[string][]metrics.OwnedAgg{"carlos-exec@shop.example.com": {{ |
| + Owner: metrics.Owner{Account: acct, App: "kass"}, |
| + Metrics: map[string]metrics.Agg{"cpu": {Avg: cpu / 2, N: 60}, "mem_bytes": {Avg: 1e9, N: 60}}, |
| + }}}, |
| + }, |
| + }} |
| +} |
| + |
| +// seedEconomicsDays writes, for every date, both platform boxes' rollups, |
| +// an edge day for box-a, fleet-a's pi-1 rollup, and the storage and |
| +// census days, straight into the bucket (none of it counted). |
| +func seedEconomicsDays(t *testing.T, fx *consoleFixture, dates []string) { |
| + t.Helper() |
| + for i, date := range dates { |
| + econPut(t, fx, date, i) |
| + } |
| +} |
| + |
| +// econPut writes date's objects, sized by n. |
| +func econPut(t *testing.T, fx *consoleFixture, date string, n int) { |
| + t.Helper() |
| + ctx := context.Background() |
| + put := func(key string, v any) { |
| + t.Helper() |
| + raw, err := json.Marshal(v) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + _, etag, _ := fx.rel.Get(ctx, key) |
| + if _, err := fx.rel.Put(ctx, key, raw, etag); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + for _, box := range []string{"box-a", "box-b"} { |
| + put(metrics.DayKey(box, date), econRollup(box, date, fx.sqid, n)) |
| + } |
| + put("fleets/fleet-a/"+metrics.DayKey("pi-1", date), metrics.DayRollup{V: 1, Box: "pi-1", Date: date, |
| + Hours: map[string]metrics.HourAgg{"10": {Host: map[string]metrics.Agg{"cpu": {Avg: 0.1, N: 15 * (n%4 + 1)}}}}}) |
| + put(usage.EdgeDayKey("box-a", date), usage.EdgeDay{V: 1, Box: "box-a", Date: date, Hours: map[string]map[string]usage.EdgeRow{ |
| + "09": {"kass.carlosapp.dev": {Account: fx.sqid, App: "kass", Requests: int64(1000 * (n + 1)), BytesOut: int64(5e8) * int64(n%3+1)}}, |
| + }}) |
| + put(usage.StorageDayKey(date), usage.StorageDay{V: 1, Date: date, Apps: map[string]usage.AppStorage{ |
| + fx.sqid + "/kass": {BucketBytes: int64(1e9) * int64(n%5+1)}, |
| + }}) |
| + put(usage.CensusDayKey(date), usage.CensusDay{V: 1, Date: date, Accounts: map[string]usage.CensusAccount{ |
| + fx.sqid: {Apps: n%3 + 1, Routes: 2}, |
| + }}) |
| +} |
| + |
| +// econReference is the economics sweep as it read before |
| +// console-economics-speed: sweepUsage, foldStorageAndCensus and fleetMeters |
| +// one read after another straight from the bucket, fleet meters merged in |
| +// as buildEconomicsView merges them. |
| +type econRef struct { |
| + meters map[string]map[string]float64 |
| + boxes map[string]economics.BoxLoad |
| + covered, period int |
| + err error |
| +} |
| + |
| +func econReference(t *testing.T, fx *consoleFixture, period string, now time.Time) econRef { |
| + t.Helper() |
| + ctx := context.Background() |
| + from, to := economicsPeriodBounds(period, now) |
| + attrib, _, err := fx.srv.loadAttributionForEconomics() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + st := fx.srv.cfg.Releases |
| + sweep, err := fx.srv.sweepUsage(ctx, st, from, to, attrib) |
| + if err != nil { |
| + return econRef{err: err} |
| + } |
| + if err := fx.srv.foldStorageAndCensus(ctx, st, from, to, sweep.PerAccount); err != nil { |
| + return econRef{err: err} |
| + } |
| + fleet, err := fx.srv.fleetMeters(ctx, st, from, to) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for acct, mm := range fleet { |
| + dst := sweep.PerAccount[acct] |
| + if dst == nil { |
| + dst = map[string]float64{} |
| + sweep.PerAccount[acct] = dst |
| + } |
| + for m, v := range mm { |
| + dst[m] += v |
| + } |
| + } |
| + return econRef{meters: sweep.PerAccount, boxes: sweep.PerBox, covered: sweep.CoveredDays, period: sweep.PeriodDays} |
| +} |
| + |
| +// econMatches compares a view with the reference: every meter of every |
| +// account, exactly, every box's load, and the coverage. |
| +func econMatches(t *testing.T, label string, v *EconomicsView, ref econRef) { |
| + t.Helper() |
| + var pl economicsPayload |
| + if err := json.Unmarshal([]byte(v.DataJSON), &pl); err != nil { |
| + t.Fatal(err) |
| + } |
| + for acct, mm := range pl.Meters { |
| + want := ref.meters[acct] |
| + if len(want) == 0 && len(mm) == 0 { |
| + continue |
| + } |
| + if !reflect.DeepEqual(mm, want) { |
| + t.Errorf("%s: account %s meters\n got %v\n want %v", label, acct, mm, want) |
| + } |
| + } |
| + for acct, mm := range ref.meters { |
| + if _, ok := pl.Meters[acct]; !ok && len(mm) > 0 { |
| + t.Errorf("%s: account %s missing from the view", label, acct) |
| + } |
| + } |
| + if len(ref.meters) == 0 { |
| + t.Errorf("%s: the reference read no usage: the seeds missed", label) |
| + } |
| + if !reflect.DeepEqual(pl.BoxLoads, ref.boxes) { |
| + t.Errorf("%s: box loads\n got %v\n want %v", label, pl.BoxLoads, ref.boxes) |
| + } |
| + if v.CoveredDays != ref.covered || v.PeriodDays != ref.period { |
| + t.Errorf("%s: coverage %d/%d, want %d/%d", label, v.CoveredDays, v.PeriodDays, ref.covered, ref.period) |
| + } |
| +} |
| + |
| +// econView asks for the page (so the view is the one the route renders) |
| +// and returns the view it rendered from. |
| +func econView(t *testing.T, fx *consoleFixture, c *http.Client, path, period string) *EconomicsView { |
| + t.Helper() |
| + u := fx.ts.URL + path |
| + if period != "" { |
| + u += "?period=" + period |
| + } |
| + if st, _, body := get(t, c, u); st != http.StatusOK { |
| + t.Fatalf("%s = %d:\n%s", u, st, body) |
| + } |
| + v, err := fx.srv.LoadEconomics(context.Background(), period) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return v |
| +} |
| + |
| +// econDayGets is the day objects a recorder saw read, by key. |
| +func econDayGets(rec *s3Recorder) map[string]int { |
| + out := map[string]int{} |
| + for _, q := range rec.all() { |
| + if q.Method == http.MethodGet && q.Key != "" { |
| + if _, ok := usageDayDate(q.Key); ok { |
| + out[q.Key]++ |
| + } |
| + } |
| + } |
| + return out |
| +} |
| + |
| +// TestEconomicsViewsMatchTheSequentialSweep: over a seeded period, every |
| +// period's view is the sweep read one object after another from the bucket: |
| +// cold with nothing held, cold again with the settled days held, and cold |
| +// after the economics pass filled the cache. |
| +func TestEconomicsViewsMatchTheSequentialSweep(t *testing.T) { |
| + perfCaptureLogs(t) |
| + fx, _ := newPerfFixture(t) |
| + c := signInPaul(t, fx) |
| + seedEconomicsDays(t, fx, econDates(time.Now())) |
| + for _, period := range []string{"mtd", "last", "7d"} { |
| + ref := econReference(t, fx, period, time.Now()) |
| + if ref.err != nil { |
| + t.Fatal(ref.err) |
| + } |
| + econAllCold(fx) |
| + econMatches(t, period+" (nothing held)", econView(t, fx, c, "/fleet/economics", period), ref) |
| + econViewCold(fx) |
| + econMatches(t, period+" (settled days held)", econView(t, fx, c, "/fleet/economics/accounts", period), ref) |
| + econAllCold(fx) |
| + if err := fx.srv.statementsPass(context.Background(), time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + econMatches(t, period+" (after the pass)", econView(t, fx, c, "/fleet/economics", period), ref) |
| + } |
| +} |
| + |
| +// TestEconomicsColdViewReadsOnlyUnsettledDays: the first cold view reads |
| +// every day of the period once; a second cold view reads today's and |
| +// yesterday's objects again and no settled day; and after the economics |
| +// pass, a cold month-to-date view on a console that had read nothing reads |
| +// only the unsettled days too. |
| +func TestEconomicsColdViewReadsOnlyUnsettledDays(t *testing.T) { |
| + perfCaptureLogs(t) |
| + fx, lat := newPerfFixture(t) |
| + c := signInPaul(t, fx) |
| + now := time.Now() |
| + seedEconomicsDays(t, fx, econDates(now)) |
| + rec := recordS3(lat, nil) |
| + // Per day: both platform boxes' rollups, box-a's edge day, pi-1's |
| + // rollup, and the storage and census days. |
| + const perDay = 6 |
| + for _, period := range []string{"mtd", "last", "7d"} { |
| + dates := econPeriodDates(period, now) |
| + unsettled := 0 |
| + for _, d := range dates { |
| + if !usageDaySettled(d, now) { |
| + unsettled++ |
| + } |
| + } |
| + econAllCold(fx) |
| + rec.reset() |
| + econView(t, fx, c, "/fleet/economics", period) |
| + gets := econDayGets(rec) |
| + if len(gets) != perDay*len(dates) { |
| + t.Errorf("%s first cold view: %d day objects read, want %d (%d days)", period, len(gets), perDay*len(dates), len(dates)) |
| + } |
| + for k, n := range gets { |
| + if n > 1 { |
| + t.Errorf("%s first cold view: %s read %d times", period, k, n) |
| + } |
| + } |
| + econViewCold(fx) |
| + rec.reset() |
| + econView(t, fx, c, "/fleet/economics", period) |
| + gets = econDayGets(rec) |
| + for k := range gets { |
| + if date, _ := usageDayDate(k); usageDaySettled(date, now) { |
| + t.Errorf("%s second cold view: read settled %s again", period, k) |
| + } |
| + } |
| + if len(gets) != perDay*unsettled { |
| + t.Errorf("%s second cold view: %d day objects read, want %d (%d unsettled days):\n%v", period, len(gets), perDay*unsettled, unsettled, gets) |
| + } |
| + rec.reset() |
| + econView(t, fx, c, "/fleet/economics/accounts", period) |
| + if n := len(rec.all()); n != 0 { |
| + t.Errorf("%s warm view: %d S3 requests, want 0", period, n) |
| + } |
| + } |
| + |
| + econAllCold(fx) |
| + if err := fx.srv.statementsPass(context.Background(), now); err != nil { |
| + t.Fatal(err) |
| + } |
| + rec.reset() |
| + econView(t, fx, c, "/fleet/economics", "mtd") |
| + for k := range econDayGets(rec) { |
| + if date, _ := usageDayDate(k); usageDaySettled(date, now) { |
| + t.Errorf("cold view after the pass: read settled %s, which the pass had read", k) |
| + } |
| + } |
| +} |
| + |
| +// TestEconomicsRereadsUnsettledAndChangedDays: a change to today's or |
| +// yesterday's objects shows on the next cold view; a settled day is kept as |
| +// read until the economics pass reads it again, and the pass's copy shows |
| +// on the next cold view. |
| +func TestEconomicsRereadsUnsettledAndChangedDays(t *testing.T) { |
| + perfCaptureLogs(t) |
| + fx, _ := newPerfFixture(t) |
| + c := signInPaul(t, fx) |
| + now := time.Now() |
| + dates := econDates(now) |
| + seedEconomicsDays(t, fx, dates) |
| + // "last" and "mtd" between them cover yesterday, today and settled |
| + // days; each view is compared with the sequential sweep. |
| + check := func(label string) { |
| + t.Helper() |
| + for _, period := range []string{"mtd", "last"} { |
| + econViewCold(fx) |
| + econMatches(t, label+" "+period, econView(t, fx, c, "/fleet/economics", period), econReference(t, fx, period, now)) |
| + } |
| + } |
| + check("before any change") |
| + |
| + today, yesterday := dates[len(dates)-1], dates[len(dates)-2] |
| + econPut(t, fx, today, 101) |
| + econPut(t, fx, yesterday, 102) |
| + check("today and yesterday changed") |
| + |
| + // A settled day changed in the bucket (which its writers never do) is |
| + // kept as read until the economics pass reads it again. The pass reads |
| + // month to date, so take this month's first day when it is settled, and |
| + // otherwise last month's, read by the pass as it ran at that month's end. |
| + settled, period, passAt := dates[len(dates)-1][:8]+"01", "mtd", now |
| + if !usageDaySettled(settled, now) { |
| + settled, period = dates[0], "last" |
| + d, _ := time.Parse("2006-01-02", settled) |
| + passAt = time.Date(d.Year(), d.Month()+1, 0, 23, 0, 0, 0, time.UTC) |
| + } |
| + view := func() *EconomicsView { |
| + t.Helper() |
| + econViewCold(fx) |
| + return econView(t, fx, c, "/fleet/economics", period) |
| + } |
| + before := view() |
| + econPut(t, fx, settled, 103) |
| + if after := view(); after.DataJSON != before.DataJSON { |
| + t.Errorf("settled %s changed in the bucket: the cold view re-read it, want it kept until the pass reads it", settled) |
| + } |
| + if err := fx.srv.statementsPass(context.Background(), passAt); err != nil { |
| + t.Fatal(err) |
| + } |
| + after := view() |
| + if after.DataJSON == before.DataJSON { |
| + t.Errorf("settled %s: the view after the pass still shows the copy from before it", settled) |
| + } |
| + 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. |
| +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 |
| + var floods []string |
| + for _, date := range econPeriodDates("last", now) { |
| + if len(floods) == 3*readConcurrency { |
| + break |
| + } |
| + raw, err := json.Marshal(econRollup("flood", date, fx.sqid, len(floods))) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + body := append(raw, []byte(strings.Repeat(" ", huge-len(raw)))...) |
| + key := metrics.DayKey("flood", date) |
| + if _, err := fx.rel.Put(ctx, key, body, ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + 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() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + got, held := fx.srv.readEconomicsUsage(ctx, from, to, attrib, now) |
| + 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) * held.Largest; held.Peak > bound { |
| + t.Errorf("the sweep held %d bytes at once, over %d (%d bodies)", held.Peak, bound, readConcurrency) |
| + } |
| + for _, k := range floods { |
| + if _, ok := fx.srv.usageDays.get(k); ok { |
| + t.Errorf("the cache kept oversized %s", k) |
| + } |
| + } |
| + if _, bytes := fx.srv.usageDays.held(); bytes > usageDayCacheMaxBody { |
| + t.Errorf("the cache holds %d bytes after a sweep of oversized days", bytes) |
| + } |
| + |
| + rec := recordS3(lat, nil) |
| + econViewCold(fx) |
| + econMatches(t, "oversized 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]) |
| + } |
| + } |
| +} |
| + |
| +// 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 |
| +// it. A refused box listing or bill fails the view, and when both fail the |
| +// listing's error is the one returned, as before. |
| +func TestEconomicsFailedReadsMatchTheSequentialSweep(t *testing.T) { |
| + perfCaptureLogs(t) |
| + fx, lat := newPerfFixture(t) |
| + c := signInPaul(t, fx) |
| + now := time.Now() |
| + dates := econDates(now) |
| + seedEconomicsDays(t, fx, dates) |
| + refused := map[string]bool{ |
| + metrics.DayKey("box-a", dates[0]): true, // settled |
| + usage.StorageDayKey(dates[1]): true, // settled, read twice per view |
| + usage.EdgeDayKey("box-a", dates[len(dates)-1]): true, // today |
| + } |
| + failing := true |
| + rec := recordS3(lat, func(q s3Req) bool { return failing && q.Method == http.MethodGet && refused[q.Key] }) |
| + |
| + for _, period := range []string{"last", "mtd"} { |
| + ref := econReference(t, fx, period, now) |
| + if ref.err != nil { |
| + t.Fatal(ref.err) |
| + } |
| + econAllCold(fx) |
| + econMatches(t, period+" (refused)", econView(t, fx, c, "/fleet/economics", period), ref) |
| + econViewCold(fx) |
| + econMatches(t, period+" (refused, settled days held)", econView(t, fx, c, "/fleet/economics", period), ref) |
| + } |
| + failing = false |
| + rec.reset() |
| + for _, period := range []string{"last", "mtd"} { |
| + econViewCold(fx) |
| + econMatches(t, period+" (answered)", econView(t, fx, c, "/fleet/economics", period), econReference(t, fx, period, now)) |
| + } |
| + if n := econDayGets(rec)[metrics.DayKey("box-a", dates[0])]; n == 0 { |
| + t.Errorf("the refused settled day was not read once the bucket answered") |
| + } |
| + |
| + // A refused listing or bill fails the view; the listing's error first. |
| + month := usage.MonthOf(now.UTC()) |
| + for _, tc := range []struct { |
| + name string |
| + refuse func(q s3Req) bool |
| + errPart string |
| + }{ |
| + {"box listing", func(q s3Req) bool { return q.Key == "" && q.Prefix == metricsBoxesPrefix }, "sweep usage"}, |
| + {"bill", func(q s3Req) bool { return q.Key == economics.BillKey(month) }, "bill " + month}, |
| + {"listing and bill", func(q s3Req) bool { |
| + return (q.Key == "" && q.Prefix == metricsBoxesPrefix) || q.Key == economics.BillKey(month) |
| + }, "sweep usage"}, |
| + } { |
| + recordS3(lat, tc.refuse) |
| + econAllCold(fx) |
| + _, err := fx.srv.LoadEconomics(context.Background(), "mtd") |
| + if err == nil || !strings.Contains(err.Error(), "console: load economics: ") || !strings.Contains(err.Error(), tc.errPart) { |
| + t.Errorf("%s refused: LoadEconomics = %v, want a load economics error naming %q", tc.name, err, tc.errPart) |
| + } |
| + econAllCold(fx) |
| + if st, _, _ := get(t, c, fx.ts.URL+"/fleet/economics"); st != http.StatusInternalServerError { |
| + t.Errorf("%s refused: page = %d, want 500", tc.name, st) |
| + } |
| + } |
| + recordS3(lat, nil) |
| +} |
| + |
| +// TestEconomicsColdViewCounts pins the S3 requests a cold view makes over |
| +// the walk's own fixture (no usage seeded), and logs its time with the |
| +// walk's latency: nothing held, then the settled days held. Per day: both |
| +// platform boxes' rollups, pi-1's rollup, and the storage and census days |
| +// (five); per view: the two box listings, the active scenario, the |
| +// scenario listing and two bills (six). |
| +func TestEconomicsColdViewCounts(t *testing.T) { |
| + perfCaptureLogs(t) |
| + fx, lat := newPerfFixture(t) |
| + c := signInPaul(t, fx) |
| + now := time.Now() |
| + for _, route := range []string{"/fleet/economics", "/fleet/economics/accounts"} { |
| + for _, period := range []string{"mtd", "last"} { |
| + dates := econPeriodDates(period, now) |
| + unsettled := 0 |
| + for _, d := range dates { |
| + if !usageDaySettled(d, now) { |
| + unsettled++ |
| + } |
| + } |
| + path := route + "?period=" + period |
| + for _, pass := range []struct { |
| + name string |
| + cold func(*consoleFixture) |
| + want int |
| + }{ |
| + {"nothing held", econAllCold, 6 + 5*len(dates)}, |
| + {"settled days held", econViewCold, 6 + 5*unsettled}, |
| + {"warm", func(*consoleFixture) {}, 0}, |
| + } { |
| + pass.cold(fx) |
| + lat.Enable(true) |
| + r := perfOnce(fx, lat, c, perfTarget{Path: path, Expect: http.StatusOK}, func() { lat.Enable(false) }) |
| + if r.err != nil || r.status != http.StatusOK { |
| + t.Fatalf("%s: %v %d", path, r.err, r.status) |
| + } |
| + if r.s3 != int64(pass.want) { |
| + t.Errorf("%s (%s): %d S3 requests, want %d", path, pass.name, r.s3, pass.want) |
| + } |
| + t.Logf("%s (%s, %d days): %d S3 requests, first byte %v", path, pass.name, len(dates), r.s3, r.ttfb.Round(time.Millisecond)) |
| + } |
| + } |
| + } |
| +} |
| + |
| +// TestUsageDayDate: the cache knows exactly the five day-object families |
| +// the sweep reads, by their writers' key functions. |
| +func TestUsageDayDate(t *testing.T) { |
| + const d = "2026-10-03" |
| + for _, key := range []string{ |
| + metrics.DayKey("box-a", d), "fleets/fleet-a/" + metrics.DayKey("pi-1", d), |
| + usage.EdgeDayKey("box-a", d), usage.StorageDayKey(d), usage.CensusDayKey(d), |
| + } { |
| + if got, ok := usageDayDate(key); !ok || got != d { |
| + t.Errorf("usageDayDate(%q) = %q, %v; want %q", key, got, ok, d) |
| + } |
| + } |
| + for _, key := range []string{ |
| + "metrics/boxes/box-a/raw/2026-10-03-09.json", "economics/bills/2026-10.json", "usage/storage/x/2026-10-03.json", |
| + "fleets/metrics/boxes/pi/days/" + d + ".json", "metrics/boxes//days/" + d + ".json", "usage/census/2026-13-03.json", |
| + "status/boxes/box-a.json", |
| + } { |
| + if got, ok := usageDayDate(key); ok { |
| + t.Errorf("usageDayDate(%q) = %q, true; want not a day object", key, got) |
| + } |
| + } |
| +} |
| + |
| +// TestUsageDayCacheBounds: days outside the offered periods are dropped, |
| +// unsettled days and failed reads are never kept, and past the byte budget |
| +// the oldest days go first. |
| +func TestUsageDayCacheBounds(t *testing.T) { |
| + now := time.Date(2026, 10, 27, 12, 0, 0, 0, time.UTC) |
| + for date, want := range map[string]bool{"2026-10-25": true, "2026-10-26": false, "2026-10-27": false, "2026-09-01": true} { |
| + if got := usageDaySettled(date, now); got != want { |
| + t.Errorf("settled(%s) at %v = %v, want %v", date, now, got, want) |
| + } |
| + } |
| + var c usageDayCache |
| + c.put("usage/census/2026-08-31.json", "2026-08-31", []byte("{}"), "e", nil, now) |
| + if n, _ := c.held(); n != 0 { |
| + t.Errorf("kept a day before last month") |
| + } |
| + c.put("usage/census/2026-09-01.json", "2026-09-01", []byte("{}"), "e", nil, now) |
| + c.put("usage/census/2026-09-02.json", "2026-09-02", nil, "", fmt.Errorf("refused"), now) |
| + if n, _ := c.held(); n != 1 { |
| + t.Errorf("held %d entries, want the one read (a refused read is not kept)", n) |
| + } |
| + c.prune(time.Date(2026, 11, 1, 0, 0, 0, 0, time.UTC)) |
| + if n, b := c.held(); n != 0 || b != 0 { |
| + t.Errorf("after the month turned: %d entries, %d bytes, want none", n, b) |
| + } |
| + body := make([]byte, usageDayCacheMaxBody) |
| + days := int(usageDayCacheMaxBytes/usageDayCacheMaxBody) + 3 |
| + start := time.Date(2026, 9, 1, 0, 0, 0, 0, time.UTC) |
| + keys := map[string]string{} |
| + for i := range days { |
| + date := usage.DayOf(start.Add(time.Duration(i) * 24 * time.Hour / 2)) // two keys a day |
| + key := fmt.Sprintf("metrics/boxes/b%d/days/%s.json", i, date) |
| + keys[key] = date |
| + c.put(key, date, body, "e", nil, now) |
| + } |
| + if _, b := c.held(); b > usageDayCacheMaxBytes { |
| + t.Errorf("holds %d bytes, over the %d budget", b, usageDayCacheMaxBytes) |
| + } |
| + oldestKept := "9999" |
| + for k := range maps.Keys(c.entries) { |
| + oldestKept = min(oldestKept, c.entries[k].date) |
| + } |
| + for k, date := range keys { |
| + if _, ok := c.get(k); !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 24ff37471..0a9bc69a9 100644 |
| --- a/internal/console/economicsview.go |
| +++ b/internal/console/economicsview.go |
| @@ -414,13 +414,29 @@ func (s *Server) buildEconomicsView(ctx context.Context, period string) (*Econom |
| return nil, fmt.Errorf("console: load economics: %w", err) |
| } |
| - sweep, err := s.sweepUsage(sweepCtx, from, to, attrib) |
| - if err != nil { |
| - return nil, fmt.Errorf("console: load economics: %w", err) |
| - } |
| - if err := s.foldStorageAndCensus(sweepCtx, from, to, sweep.PerAccount); err != nil { |
| - return nil, fmt.Errorf("console: load economics: %w", err) |
| - } |
| + // The period's usage days, the active scenario, the scenario names and |
| + // the bills are read at once; their errors are then taken in the order |
| + // they were met when the reads ran one after another, so a failed view |
| + // fails with the same error. |
| + var ( |
| + used economicsUsage |
| + sc economics.Scenario |
| + scenarioWarning string |
| + scenarioNames []string |
| + namesErr error |
| + bills []economics.Bill |
| + billsErr error |
| + ) |
| + runConcurrently( |
| + func() { used, _ = s.readEconomicsUsage(sweepCtx, from, to, attrib, now) }, |
| + func() { sc, scenarioWarning = s.loadActiveScenario(sweepCtx) }, |
| + func() { scenarioNames, namesErr = s.listScenarioNames(sweepCtx) }, |
| + func() { bills, billsErr = s.loadRecentBills(sweepCtx, now) }, |
| + ) |
| + if used.err != nil { |
| + return nil, fmt.Errorf("console: load economics: %w", used.err) |
| + } |
| + sweep := used.sweep |
| // Fleet meters (Task 3's fleetMeters) fold into sweep.PerAccount exactly |
| // like statementsPass's own union merge (economicspass.go) — an account |
| @@ -440,7 +456,7 @@ func (s *Server) buildEconomicsView(ctx context.Context, period string) (*Econom |
| // TWO banners for the SAME missing registry (loadAttributionForEconomics's |
| // and this one, since fleetMeters opens that identical registry) — see |
| // the warning=="" guard below, which keeps it to one banner, one cause. |
| - if fleetMM, ferr := s.fleetMeters(sweepCtx, from, to); ferr != nil { |
| + if fleetMM, ferr := used.fleet, used.fleetErr; ferr != nil { |
| log.Printf("console: load economics: fleet meters unavailable: %v", ferr) |
| // Suppress a second banner when routes are ALREADY degraded |
| // (warning != "" here can only mean loadAttributionForEconomics found no |
| @@ -464,11 +480,8 @@ func (s *Server) buildEconomicsView(ctx context.Context, period string) (*Econom |
| } |
| } |
| - sc, scenarioWarning := s.loadActiveScenario(sweepCtx) |
| - |
| - scenarioNames, err := s.listScenarioNames(sweepCtx) |
| - if err != nil { |
| - return nil, fmt.Errorf("console: load economics: %w", err) |
| + if namesErr != nil { |
| + return nil, fmt.Errorf("console: load economics: %w", namesErr) |
| } |
| // Union of accounts to price: every account with usage this period plus |
| @@ -619,9 +632,8 @@ func (s *Server) buildEconomicsView(ctx context.Context, period string) (*Econom |
| } |
| sort.Slice(boxRows, func(i, j int) bool { return boxRows[i].Box < boxRows[j].Box }) |
| - bills, err := s.loadRecentBills(sweepCtx, now) |
| - if err != nil { |
| - return nil, fmt.Errorf("console: load economics: %w", err) |
| + if billsErr != nil { |
| + return nil, fmt.Errorf("console: load economics: %w", billsErr) |
| } |
| payload := economicsPayload{ |
diff --git a/internal/console/hotreads.go b/internal/console/hotreads.go| index 61aee5c42..3293de797 100644 |
| --- a/internal/console/hotreads.go |
| +++ b/internal/console/hotreads.go |
| @@ -104,6 +104,7 @@ type prefetchStore struct { |
| mu sync.Mutex |
| dry bool |
| lists map[string]listed |
| + dirs map[string]listed |
| mods map[string]listedMod |
| asked []string |
| pending map[string]*pendingGet |
| @@ -159,6 +160,23 @@ func (p *prefetchStore) List(ctx context.Context, prefix string) ([]string, erro |
| return slices.Clone(l.keys), l.err |
| } |
| +// ListDirs is List's twin for a reader that discovers its keys a level at |
| +// a time (the economics sweep's boxes): each prefix is listed once, by the |
| +// dry pass, and the real pass gets the same answer. |
| +func (p *prefetchStore) ListDirs(ctx context.Context, prefix string) ([]string, error) { |
| + p.mu.Lock() |
| + l, ok := p.dirs[prefix] |
| + p.mu.Unlock() |
| + if !ok { |
| + dirs, err := p.Store.ListDirs(ctx, prefix) |
| + l = listed{keys: dirs, err: err} |
| + p.mu.Lock() |
| + p.dirs[prefix] = l |
| + p.mu.Unlock() |
| + } |
| + return slices.Clone(l.keys), l.err |
| +} |
| + |
| func (p *prefetchStore) ListMod(ctx context.Context, prefix string) ([]release.KeyMod, error) { |
| p.mu.Lock() |
| l, ok := p.mods[prefix] |
| @@ -299,7 +317,7 @@ func readConcurrently[T any](ctx context.Context, st release.Store, dryBody []by |
| // readConcurrentlyStats is readConcurrently, and what it held. |
| func readConcurrentlyStats[T any](ctx context.Context, st release.Store, dryBody []byte, limit func(key string) int64, read func(release.Store) T) (T, prefetchStats) { |
| p := &prefetchStore{Store: st, dryBody: dryBody, limit: limit, dry: true, |
| - lists: map[string]listed{}, mods: map[string]listedMod{}, pending: map[string]*pendingGet{}, |
| + lists: map[string]listed{}, dirs: map[string]listed{}, mods: map[string]listedMod{}, pending: map[string]*pendingGet{}, |
| window: make(chan struct{}, readConcurrency)} |
| read(p) |
| p.mu.Lock() |
diff --git a/internal/console/server.go b/internal/console/server.go| index 1e287daba..2d8d88c22 100644 |
| --- a/internal/console/server.go |
| +++ b/internal/console/server.go |
| @@ -1165,6 +1165,10 @@ type Server struct { |
| // keyed by period so a cold sweep for one period never blocks a caller |
| // asking for another. |
| economicsCache economicsCache |
| + // usageDays holds the settled usage day objects the economics sweep |
| + // reads (usagedays.go), so a cold view reads only today and yesterday; |
| + // the hourly economics pass fills it as it reads. |
| + usageDays usageDayCache |
| // 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 |
diff --git a/internal/console/testdata/perf-budgets.txt b/internal/console/testdata/perf-budgets.txt| index 9c400c386..2e2c2d5e3 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: the cold view sweeps usage for every day of the period (162 S3 calls, about 4.1 s); warm views come from the 60 s cache (0 S3 calls) |
| -GET /fleet/economics/accounts over: shares /fleet/economics's sweep cache, so its own cold view is that same sweep (0 S3 calls warm) |
| +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/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/usageattrib_tags_test.go b/internal/console/usageattrib_tags_test.go| index d025d349c..73d74f09e 100644 |
| --- a/internal/console/usageattrib_tags_test.go |
| +++ b/internal/console/usageattrib_tags_test.go |
| @@ -64,7 +64,7 @@ func TestUsageTaggedCustomDomainCounted(t *testing.T) { |
| if err != nil { |
| t.Fatal(err) |
| } |
| - sweep, err := tb.fx.srv.sweepUsage(context.Background(), hours[0], hours[3], attrib) |
| + sweep, err := tb.fx.srv.sweepUsage(context.Background(), tb.fx.srv.cfg.Releases, hours[0], hours[3], attrib) |
| if err != nil { |
| t.Fatal(err) |
| } |
| @@ -140,7 +140,7 @@ func TestUsageTaggedReusedHostname(t *testing.T) { |
| if err != nil { |
| t.Fatal(err) |
| } |
| - sweep, err := fx.srv.sweepUsage(ctx, era[0], era[1].Add(time.Hour), attrib) |
| + sweep, err := fx.srv.sweepUsage(ctx, fx.srv.cfg.Releases, era[0], era[1].Add(time.Hour), attrib) |
| if err != nil { |
| t.Fatal(err) |
| } |
diff --git a/internal/console/usageattrib_test.go b/internal/console/usageattrib_test.go| index 7838ffe91..53dd83c5f 100644 |
| --- a/internal/console/usageattrib_test.go |
| +++ b/internal/console/usageattrib_test.go |
| @@ -287,7 +287,7 @@ func TestUsageReusedHostname(t *testing.T) { |
| if err != nil { |
| t.Fatal(err) |
| } |
| - sweep, err := fx.srv.sweepUsage(ctx, era[0], era[3], attrib) |
| + sweep, err := fx.srv.sweepUsage(ctx, fx.srv.cfg.Releases, era[0], era[3], attrib) |
| if err != nil { |
| t.Fatal(err) |
| } |
diff --git a/internal/console/usagedays.go b/internal/console/usagedays.go| new file mode 100644 |
| index 000000000..01fe8aa82 |
| --- /dev/null |
| +++ b/internal/console/usagedays.go |
| @@ -0,0 +1,341 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "os" |
| + "slices" |
| + "strings" |
| + "sync" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/metrics" |
| + "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/usage" |
| +) |
| + |
| +// The economics sweep's per-day usage objects (console-economics-speed). |
| +// /fleet/economics prices a period by reading every day of it: each box's |
| +// metrics rollup and edge day, each fleet box's rollup, and the day's |
| +// storage and census objects. An operator page is viewed seldom, so nearly |
| +// every view missed the 60 s view cache and read the whole period one |
| +// object after another. Two changes: |
| +// |
| +// - A view reads the period's objects concurrently (readConcurrently, |
| +// hotreads.go): readConcurrency at a time, with no more than that many |
| +// 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. |
| +// |
| +// 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 |
| +// settled day it read in the same cache (usageDayFiller), so the page's |
| +// next cold view finds the month's settled days held and reads only today |
| +// 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. |
| +const ( |
| + usageDayCacheMaxBody = 1 << 20 |
| + usageDayCacheMaxBytes = 64 << 20 |
| + usageDayEntryOverhead = 64 |
| +) |
| + |
| +// 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. |
| +type usageDayEntry struct { |
| + date string |
| + body []byte |
| + etag string |
| + absent error |
| +} |
| + |
| +func (e usageDayEntry) size(key string) int64 { |
| + return int64(len(key) + len(e.body) + len(e.etag) + usageDayEntryOverhead) |
| +} |
| + |
| +// usageDayCache holds settled day objects by key, for the days the page |
| +// can show: the first of last month (the "last" period's first day; "7d" |
| +// never reaches further back) up to the day before yesterday. Days that |
| +// leave that window are dropped by prune, which every view and every pass |
| +// runs first. |
| +type usageDayCache struct { |
| + mu sync.Mutex |
| + entries map[string]usageDayEntry |
| + bytes int64 |
| +} |
| + |
| +// usageDayDate is the date a usage day object's key names, for the five |
| +// families the economics sweep reads: metrics.DayKey under the platform |
| +// root or a fleet's prefix, usage.EdgeDayKey, usage.StorageDayKey and |
| +// usage.CensusDayKey. Any other key is not a day object (ok false), and is |
| +// read through untouched. |
| +func usageDayDate(key string) (date string, ok bool) { |
| + rest, ok := strings.CutSuffix(key, ".json") |
| + if !ok { |
| + return "", false |
| + } |
| + i := strings.LastIndexByte(rest, '/') |
| + if i < 0 { |
| + return "", false |
| + } |
| + date = rest[i+1:] |
| + if _, err := time.Parse("2006-01-02", date); err != nil { |
| + return "", false |
| + } |
| + if key == usage.StorageDayKey(date) || key == usage.CensusDayKey(date) { |
| + return date, true |
| + } |
| + dir := rest[:i] |
| + if fleetRest, ok := strings.CutPrefix(dir, "fleets/"); ok { |
| + j := strings.IndexByte(fleetRest, '/') |
| + if j <= 0 { |
| + return "", false |
| + } |
| + fleet := fleetRest[:j] |
| + box, ok := daysDirBox(fleetRest[j+1:], "metrics/boxes/") |
| + return date, ok && key == "fleets/"+fleet+"/"+metrics.DayKey(box, date) |
| + } |
| + if box, ok := daysDirBox(dir, "metrics/boxes/"); ok { |
| + return date, key == metrics.DayKey(box, date) |
| + } |
| + if box, ok := daysDirBox(dir, usage.EdgeBoxesPrefix); ok { |
| + return date, key == usage.EdgeDayKey(box, date) |
| + } |
| + return "", false |
| +} |
| + |
| +// daysDirBox is the box of a "<prefix><box>/days" directory. |
| +func daysDirBox(dir, prefix string) (string, bool) { |
| + rest, ok := strings.CutPrefix(dir, prefix) |
| + if !ok { |
| + return "", false |
| + } |
| + box, ok := strings.CutSuffix(rest, "/days") |
| + return box, ok && box != "" && !strings.Contains(box, "/") |
| +} |
| + |
| +// usageDaySettled reports whether date's objects have stopped changing by |
| +// now: true from the start of the second UTC day after it (date+2 00:00), |
| +// so today and yesterday are never settled. The writers bound a day's last |
| +// write well inside that: |
| +// |
| +// - A box's metrics rollup (and a fleet box's, the same agent under its |
| +// 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. |
| +// - 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). |
| +// - The storage and census days are create-only (usage.CreateDayObject) |
| +// and written only for the day the pass runs in |
| +// (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. |
| +func usageDaySettled(date string, now time.Time) bool { |
| + d, err := time.Parse("2006-01-02", date) |
| + if err != nil { |
| + return false |
| + } |
| + today := now.UTC().Truncate(24 * time.Hour) |
| + return !d.After(today.AddDate(0, 0, -2)) |
| +} |
| + |
| +// usageDayFirstKept is the oldest date the cache keeps at now: the first of |
| +// last month, the oldest day any period the page offers starts on. |
| +func usageDayFirstKept(now time.Time) string { |
| + now = now.UTC() |
| + first := time.Date(now.Year(), now.Month(), 1, 0, 0, 0, 0, time.UTC) |
| + return usage.DayOf(first.AddDate(0, -1, 0)) |
| +} |
| + |
| +func (c *usageDayCache) get(key string) (usageDayEntry, bool) { |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + e, ok := c.entries[key] |
| + return e, ok |
| +} |
| + |
| +// 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. |
| +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: |
| + c.mu.Lock() |
| + c.dropLocked(key) |
| + c.mu.Unlock() |
| + return |
| + case errors.Is(err, os.ErrNotExist): |
| + e = usageDayEntry{date: date, absent: err} |
| + default: |
| + return |
| + } |
| + if date < usageDayFirstKept(now) { |
| + return |
| + } |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + if c.entries == nil { |
| + c.entries = map[string]usageDayEntry{} |
| + } |
| + c.dropLocked(key) |
| + c.entries[key] = e |
| + c.bytes += e.size(key) |
| + for c.bytes > usageDayCacheMaxBytes { |
| + oldest := "" |
| + for k, o := range c.entries { |
| + if oldest == "" || o.date < c.entries[oldest].date || (o.date == c.entries[oldest].date && k < oldest) { |
| + oldest = k |
| + } |
| + } |
| + c.dropLocked(oldest) |
| + } |
| +} |
| + |
| +func (c *usageDayCache) dropLocked(key string) { |
| + if e, ok := c.entries[key]; ok { |
| + c.bytes -= e.size(key) |
| + delete(c.entries, key) |
| + } |
| +} |
| + |
| +// prune drops the days no period the page offers can show any more. |
| +func (c *usageDayCache) prune(now time.Time) { |
| + first := usageDayFirstKept(now) |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + for k, e := range c.entries { |
| + if e.date < first { |
| + c.dropLocked(k) |
| + } |
| + } |
| +} |
| + |
| +// held is the cache's entry count and bytes, for the tests. |
| +func (c *usageDayCache) held() (n int, bytes int64) { |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + return len(c.entries), c.bytes |
| +} |
| + |
| +// usageDayStore reads usage day objects through the settled-day cache. |
| +// Every other request passes through to the store untouched. |
| +// |
| +// 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. |
| +// |
| +// 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. |
| +type usageDayStore struct { |
| + release.Store |
| + cache *usageDayCache |
| + now time.Time |
| + use bool |
| + |
| + mu sync.Mutex |
| + view map[string]fetched |
| +} |
| + |
| +// usageDayReader is a page view's store over the cache, at now. |
| +func (s *Server) usageDayReader(now time.Time) *usageDayStore { |
| + s.usageDays.prune(now) |
| + return &usageDayStore{Store: s.cfg.Releases, cache: &s.usageDays, now: now, use: true, view: map[string]fetched{}} |
| +} |
| + |
| +// usageDayFiller is the economics pass's store: it reads the bucket and |
| +// fills the cache. |
| +func (s *Server) usageDayFiller(now time.Time) *usageDayStore { |
| + s.usageDays.prune(now) |
| + return &usageDayStore{Store: s.cfg.Releases, cache: &s.usageDays, now: now} |
| +} |
| + |
| +func (d *usageDayStore) Get(ctx context.Context, key string) ([]byte, string, error) { |
| + date, ok := usageDayDate(key) |
| + if !ok { |
| + return d.Store.Get(ctx, key) |
| + } |
| + settled := usageDaySettled(date, d.now) |
| + if settled && d.use { |
| + if e, hit := d.cache.get(key); hit { |
| + if e.absent != nil { |
| + return nil, "", e.absent |
| + } |
| + return e.body, e.etag, nil |
| + } |
| + } |
| + once := d.use && !settled && key == usage.StorageDayKey(date) |
| + if once { |
| + d.mu.Lock() |
| + f, seen := d.view[key] |
| + d.mu.Unlock() |
| + if seen { |
| + return f.body, f.etag, f.err |
| + } |
| + } |
| + body, etag, err := d.Store.Get(ctx, key) |
| + if settled { |
| + d.cache.put(key, date, body, etag, err, d.now) |
| + } |
| + 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() |
| + } |
| + return body, etag, err |
| +} |
| + |
| +// 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). |
| +type economicsUsage struct { |
| + sweep *usageSweep |
| + err error |
| + fleet map[string]map[string]float64 |
| + fleetErr error |
| +} |
| + |
| +// readEconomicsUsage is buildEconomicsView's per-day read: sweepUsage, |
| +// foldStorageAndCensus and fleetMeters, in that order, over a page view's |
| +// cache store, read concurrently. The registry is asked once, before. |
| +func (s *Server) readEconomicsUsage(ctx context.Context, from, to time.Time, attrib *usageAttribution, now time.Time) (economicsUsage, prefetchStats) { |
| + boxes, boxesErr := s.fleetMeterBoxes() |
| + 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 { |
| + sweep, err := s.sweepUsage(ctx, rs, from, to, attrib) |
| + if err != nil { |
| + return economicsUsage{err: err} |
| + } |
| + if err := s.foldStorageAndCensus(ctx, rs, from, to, sweep.PerAccount); err != nil { |
| + return economicsUsage{err: err} |
| + } |
| + out := economicsUsage{sweep: sweep, fleetErr: boxesErr} |
| + if boxesErr == nil { |
| + out.fleet = fleetMetersFrom(ctx, rs, boxes, from, to) |
| + } |
| + return out |
| + }) |
| +} |