carlos / platform Public

console: usage review R1: bounded start check, overflow-checked sums

Each RunUsageFrom attempt runs under its own timeout
(usageFromAttemptTimeout, instanceStoreTimeout by default), and a request
waiting for the shared @from check takes a one-slot channel turn that
gives up at its own deadline (503 F6). The held @from has its own lock,
never held across a store call.

Every counter added across objects and both totals are checked for int64
overflow; an overflow fails the InstanceUsageRead run, answers 503 and
is never memoised.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 2f26b3e70aaf18b0fe943b64831695e97861324f parent be51dac
4 files changed, +303 −22
  • internal/console/apiusage.go +48 −12
  • internal/console/apiusage_test.go +68 −0
  • internal/console/usagefrom.go +62 −10
  • internal/console/usagefrom_test.go +125 −0
diff --git a/internal/console/apiusage.go b/internal/console/apiusage.go
index 0ce77d9a7..777299796 100644
--- a/internal/console/apiusage.go
+++ b/internal/console/apiusage.go
@@ -178,10 +178,13 @@ func (s *Server) handleAPIUsage(w http.ResponseWriter, r *http.Request) {
writeUsageEntry(w, e)
return
}
- var sums map[string]usage.InstanceCount
+ e := usageMemoEntry{at: now, status: http.StatusOK}
err = s.jobs.Run(ctx, "InstanceUsageRead", func(ctx context.Context) error {
- var err error
- sums, _, err = s.readInstanceUsage(ctx, acct.Sqid, app, usageDates(start, from, now), now)
+ sums, _, err := s.readInstanceUsage(ctx, acct.Sqid, app, usageDates(start, from, now), now)
+ if err != nil {
+ return err
+ }
+ e.resp, e.overCap, err = buildUsageResponse(app, month, start, sums, now)
return err
})
if err != nil {
@@ -189,8 +192,7 @@ func (s *Server) handleAPIUsage(w http.ResponseWriter, r *http.Request) {
usageUnavailable(w, msgUsageUnreadable)
return
}
- e := usageMemoEntry{at: now, status: http.StatusOK}
- if e.resp, e.overCap = buildUsageResponse(app, month, start, sums, now); e.overCap {
+ if e.overCap {
e.status = http.StatusConflict
}
s.usageMemo.put(key, e)
@@ -229,10 +231,37 @@ func usageDates(start, from, now time.Time) []string {
return out
}
+// errUsageOverflow is a sum past int64: a read fault, never a figure.
+var errUsageOverflow = errors.New("console: instance usage: a count is too large to sum")
+
+// addCounted is a+b, or errUsageOverflow when it does not fit an int64.
+func addCounted(a, b int64) (int64, error) {
+ sum := a + b
+ if (b > 0 && sum < a) || (b < 0 && sum > a) {
+ return 0, errUsageOverflow
+ }
+ return sum, nil
+}
+
+// addInstanceCount adds every counter of b into a, checked.
+func addInstanceCount(a *usage.InstanceCount, b usage.InstanceCount) error {
+ var err error
+ for _, f := range []struct {
+ into *int64
+ v int64
+ }{{&a.BytesOut, b.BytesOut}, {&a.Requests, b.Requests}, {&a.HopBytesOut, b.HopBytesOut}, {&a.HopRequests, b.HopRequests}} {
+ if *f.into, err = addCounted(*f.into, f.v); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
// buildUsageResponse is the answer from the summed counts: instances by
// host, "" as unattributed, total both together. overCap when more than
-// usageInstanceCap instances had traffic.
-func buildUsageResponse(app, month string, start time.Time, sums map[string]usage.InstanceCount, now time.Time) (usageResponse, bool) {
+// usageInstanceCap instances had traffic; errUsageOverflow when the total
+// does not fit an int64.
+func buildUsageResponse(app, month string, start time.Time, sums map[string]usage.InstanceCount, now time.Time) (usageResponse, bool, error) {
out := usageResponse{
App: app, Month: month,
From: start.Format(time.RFC3339),
@@ -241,8 +270,13 @@ func buildUsageResponse(app, month string, start time.Time, sums map[string]usag
ReadAt: now.UTC().Format(time.RFC3339),
}
for host, c := range sums {
- out.Total.BytesOut += c.BytesOut
- out.Total.Requests += c.Requests
+ var err error
+ if out.Total.BytesOut, err = addCounted(out.Total.BytesOut, c.BytesOut); err != nil {
+ return usageResponse{}, false, err
+ }
+ if out.Total.Requests, err = addCounted(out.Total.Requests, c.Requests); err != nil {
+ return usageResponse{}, false, err
+ }
if host == "" {
out.Unattributed = usageTotals{BytesOut: c.BytesOut, Requests: c.Requests}
continue
@@ -251,10 +285,10 @@ func buildUsageResponse(app, month string, start time.Time, sums map[string]usag
HopBytesOut: c.HopBytesOut, HopRequests: c.HopRequests})
}
if len(out.Instances) > usageInstanceCap {
- return usageResponse{}, true
+ return usageResponse{}, true, nil
}
sort.Slice(out.Instances, func(i, j int) bool { return out.Instances[i].Host < out.Instances[j].Host })
- return out, false
+ return out, false, nil
}
// instanceUsageDryBody is the smallest valid day object for key: the dry
@@ -332,7 +366,9 @@ func sumInstanceUsage(ctx context.Context, rs release.Store, sqid, app string, d
}
for host, c := range day.Instances {
cur := sums[host]
- cur.Add(c)
+ if err := addInstanceCount(&cur, c); err != nil {
+ return nil, fmt.Errorf("%w: %q in %s", err, host, key)
+ }
sums[host] = cur
}
}
diff --git a/internal/console/apiusage_test.go b/internal/console/apiusage_test.go
index e06f47517..2c3d9d58a 100644
--- a/internal/console/apiusage_test.go
+++ b/internal/console/apiusage_test.go
@@ -614,3 +614,71 @@ func TestUsageDayDateKnowsInstances(t *testing.T) {
}
}
}
+
+// TestUsageSumOverflowRefused (review R1 P2): a sum past int64, for one
+// host across objects or for the total across hosts, is a read fault: 503,
+// the run Failed, nothing memoised.
+func TestUsageSumOverflowRefused(t *testing.T) {
+ const big = int64(1) << 62
+ e := newUsageEnv(t)
+ s := e.fx.sqid
+ check := func(why string) {
+ t.Helper()
+ status, body, hdr := e.get(t, "2027-01")
+ if status != http.StatusServiceUnavailable || jsonField(t, body, "error") != msgUsageUnreadable || hdr.Get("Retry-After") != "60" {
+ t.Fatalf("%s: = %d %s, want 503 %q", why, status, body, msgUsageUnreadable)
+ }
+ if j := usageJob(t, e.fx.srv); j.State != JobFailed || !strings.Contains(j.Err, errUsageOverflow.Error()) {
+ t.Fatalf("%s: job = %+v, want Failed with the overflow", why, j)
+ }
+ // Nothing memoised: sane objects, the same minute, the new answer.
+ putDay(t, e.fx.rel, "b1", "2027-01-19", s, "kass", bytesOut(1))
+ putDay(t, e.fx.rel, "b1", "2027-01-20", s, "kass", bytesOut(2))
+ if out := e.okResponse(t, "2027-01"); out.Total.BytesOut != 3 {
+ t.Fatalf("%s repaired: total = %+v, want 3", why, out.Total)
+ }
+ e.advance(2 * time.Minute)
+ }
+ // One host across two dates.
+ putDay(t, e.fx.rel, "b1", "2027-01-19", s, "kass", bytesOut(big))
+ putDay(t, e.fx.rel, "b1", "2027-01-20", s, "kass", bytesOut(big))
+ check("one host across dates")
+ // The total across two hosts, each alone within range.
+ putDay(t, e.fx.rel, "b1", "2027-01-20", s, "kass", map[string]usage.InstanceCount{
+ "a.example.com": {BytesOut: big}, "": {BytesOut: big}})
+ check("the total across hosts")
+}
+
+// TestUsageSumOverflowEveryCounter: each of the four per-host counters,
+// summed across objects, and both totals, refuse an overflow.
+func TestUsageSumOverflowEveryCounter(t *testing.T) {
+ const big = int64(1) << 62
+ for _, c := range []usage.InstanceCount{{BytesOut: big}, {Requests: big}, {HopBytesOut: big}, {HopRequests: big}} {
+ cur := c
+ if err := addInstanceCount(&cur, c); !errors.Is(err, errUsageOverflow) {
+ t.Errorf("%+v twice: err = %v, want errUsageOverflow", c, err)
+ }
+ cur = c
+ if err := addInstanceCount(&cur, usage.InstanceCount{BytesOut: 1, Requests: 1, HopBytesOut: 1, HopRequests: 1}); err != nil {
+ t.Errorf("%+v plus one: err = %v", c, err)
+ }
+ }
+ e := newUsageEnv(t)
+ s := e.fx.sqid
+ dates := []string{"2027-01-19", "2027-01-20"}
+ for _, d := range dates {
+ putDay(t, e.fx.rel, "b1", d, s, "kass", map[string]usage.InstanceCount{"a.example.com": {HopRequests: big}})
+ }
+ if _, _, err := e.fx.srv.readInstanceUsage(context.Background(), s, "kass", dates, usageT0); !errors.Is(err, errUsageOverflow) {
+ t.Fatalf("one host's hop requests across dates: err = %v, want errUsageOverflow", err)
+ }
+ start := time.Date(2027, 1, 1, 0, 0, 0, 0, time.UTC)
+ for _, sums := range []map[string]usage.InstanceCount{
+ {"a.example.com": {BytesOut: big}, "b.example.com": {BytesOut: big}},
+ {"a.example.com": {Requests: big}, "": {Requests: big}},
+ } {
+ if _, _, err := buildUsageResponse("kass", "2027-01", start, sums, usageT0); !errors.Is(err, errUsageOverflow) {
+ t.Errorf("totals of %+v: err = %v, want errUsageOverflow", sums, err)
+ }
+ }
+}
diff --git a/internal/console/usagefrom.go b/internal/console/usagefrom.go
index 66d45847a..f0ec1b424 100644
--- a/internal/console/usagefrom.go
+++ b/internal/console/usagefrom.go
@@ -32,6 +32,12 @@ const usageFromEvery = time.Minute
// usageFromAttempts bounds the re-reads after lost CAS races in one check.
const usageFromAttempts = 4
+// usageFromAttemptTimeout bounds each of RunUsageFrom's checks, as the
+// route bounds its own (instanceStoreTimeout): a stalled store read must
+// not hold the check, and every request waiting on it, for ever. A
+// variable only so a test can show the bound quickly.
+var usageFromAttemptTimeout = instanceStoreTimeout
+
// usageFromVerdict is one check's answer: ok (Status 0) with the From held,
// or the route's refusal with its copy.
type usageFromVerdict struct {
@@ -46,12 +52,17 @@ type instanceUsageState struct {
// usageNow is the usage paths' clock seam: nil means time.Now. Tests
// set it; nothing in production does.
usageNow func() time.Time
- // usageFromMu serialises the checks, so one process writes @from once.
- usageFromMu sync.Mutex
+ // usageFromTurn serialises the checks that touch the store, so one
+ // process writes @from once. It is a one-slot channel rather than a
+ // mutex so a waiter gives up when its own context ends
+ // (acquireUsageFrom); made once (usageFromTurnOnce).
+ usageFromTurn chan struct{}
+ usageFromTurnOnce sync.Once
// usageFromHeld is the @from this process last read or wrote; nil
- // until then.
- usageFromHeld *usage.InstanceFrom
- usageMemo usageMemo
+ // until then. Under usageFromHeldMu, never held across a store call.
+ usageFromHeldMu sync.Mutex
+ usageFromHeld *usage.InstanceFrom
+ usageMemo usageMemo
}
func (s *Server) usageClock() time.Time {
@@ -61,6 +72,30 @@ func (s *Server) usageClock() time.Time {
return time.Now()
}
+// acquireUsageFrom takes the check's turn, or gives up with ctx's error
+// when ctx ends first. The caller releases it with releaseUsageFrom.
+func (s *Server) acquireUsageFrom(ctx context.Context) error {
+ s.usageFromTurnOnce.Do(func() { s.usageFromTurn = make(chan struct{}, 1) })
+ select {
+ case s.usageFromTurn <- struct{}{}:
+ return nil
+ case <-ctx.Done():
+ return fmt.Errorf("console: instance usage: wait for the attribution start check: %w", ctx.Err())
+ }
+}
+
+func (s *Server) releaseUsageFrom() { <-s.usageFromTurn }
+
+// heldUsageFrom is the held @from when it rests on the activation at.
+func (s *Server) heldUsageFrom(at time.Time) (usage.InstanceFrom, bool) {
+ s.usageFromHeldMu.Lock()
+ defer s.usageFromHeldMu.Unlock()
+ if h := s.usageFromHeld; h != nil && h.Activation.Equal(at) {
+ return *h, true
+ }
+ return usage.InstanceFrom{}, false
+}
+
// errUsageOff is the check's error on a console with the switch off: it
// never writes @from there.
var errUsageOff = errors.New("console: instance usage is switched off")
@@ -96,10 +131,17 @@ func (s *Server) usageFromCheck(ctx context.Context, now time.Time) (usageFromVe
case !verified:
return usageFromVerdict{Status: http.StatusServiceUnavailable, Msg: msgUsagePending}, nil
}
- s.usageFromMu.Lock()
- defer s.usageFromMu.Unlock()
- if h := s.usageFromHeld; h != nil && h.Activation.Equal(st.At) {
- return usageFromVerdict{From: *h}, nil
+ if f, ok := s.heldUsageFrom(st.At); ok {
+ return usageFromVerdict{From: f}, nil
+ }
+ // A request waiting here while another check stalls on the store gives
+ // up at its own deadline (the route answers 503).
+ if err := s.acquireUsageFrom(ctx); err != nil {
+ return usageFromVerdict{}, err
+ }
+ defer s.releaseUsageFrom()
+ if f, ok := s.heldUsageFrom(st.At); ok { // the check it waited for
+ return usageFromVerdict{From: f}, nil
}
if s.cfg.Releases == nil {
return usageFromVerdict{}, errors.New("console: instance usage: no deployment store")
@@ -112,7 +154,9 @@ func (s *Server) usageFromCheck(ctx context.Context, now time.Time) (usageFromVe
if err != nil {
return usageFromVerdict{}, err
}
+ s.usageFromHeldMu.Lock()
s.usageFromHeld = &f
+ s.usageFromHeldMu.Unlock()
return usageFromVerdict{From: f}, nil
}
return usageFromVerdict{}, errUsageFromRaced
@@ -188,7 +232,7 @@ func (s *Server) runUsageFrom(ctx context.Context, tick <-chan time.Time) {
return // nothing to write: off, or a history that never activates
}
for {
- v, err := s.usageFromCheck(ctx, s.usageClock())
+ v, err := s.usageFromAttempt(ctx)
if err != nil {
log.Printf("console: instance usage: check the attribution start: %v (checking again in a minute)", err)
} else if v.Status == 0 {
@@ -201,3 +245,11 @@ func (s *Server) runUsageFrom(ctx context.Context, tick <-chan time.Time) {
}
}
}
+
+// usageFromAttempt is one of RunUsageFrom's checks, bounded by
+// usageFromAttemptTimeout.
+func (s *Server) usageFromAttempt(ctx context.Context) (usageFromVerdict, error) {
+ ctx, cancel := context.WithTimeout(ctx, usageFromAttemptTimeout)
+ defer cancel()
+ return s.usageFromCheck(ctx, s.usageClock())
+}
diff --git a/internal/console/usagefrom_test.go b/internal/console/usagefrom_test.go
index 7cf5f7275..836128719 100644
--- a/internal/console/usagefrom_test.go
+++ b/internal/console/usagefrom_test.go
@@ -10,6 +10,7 @@ import (
"encoding/json"
"errors"
"net/http"
+ "net/http/httptest"
"os"
"sync"
"testing"
@@ -17,6 +18,7 @@ import (
"github.com/carlosframework/platform/internal/provision"
"github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/svcrole"
"github.com/carlosframework/platform/internal/usage"
)
@@ -431,3 +433,126 @@ func TestRunUsageFromStopsOnceHeld(t *testing.T) {
t.Fatalf("@from = %+v %v, want 2027-02-01", f, ok)
}
}
+
+// usageFromBlockStore holds the first read of @from until its context
+// ends, and records how it ended.
+type usageFromBlockStore struct {
+ release.Store
+ mu sync.Mutex
+ reads int
+ blocked chan struct{} // closed when the first read is held
+ released chan struct{} // closed when it gave up
+ err error
+ hadDeadline bool
+}
+
+func newUsageFromBlockStore() *usageFromBlockStore {
+ return &usageFromBlockStore{blocked: make(chan struct{}), released: make(chan struct{})}
+}
+
+func (s *usageFromBlockStore) Get(ctx context.Context, key string) ([]byte, string, error) {
+ if key == usage.InstanceFromKey {
+ s.mu.Lock()
+ s.reads++
+ first := s.reads == 1
+ s.mu.Unlock()
+ if first {
+ _, dl := ctx.Deadline()
+ close(s.blocked)
+ <-ctx.Done()
+ s.mu.Lock()
+ s.err, s.hadDeadline = ctx.Err(), dl
+ s.mu.Unlock()
+ close(s.released)
+ return nil, "", ctx.Err()
+ }
+ }
+ return s.Store.Get(ctx, key)
+}
+
+func usageFromBlockFixture(t *testing.T, bs *usageFromBlockStore) *consoleFixture {
+ t.Helper()
+ fx := newConsoleFixtureWith(t, consoleFixtureOptions{WithKey: true,
+ Tweak: func(c *Config) { c.InstanceUsage = true },
+ WrapReleases: func(st release.Store) release.Store { bs.Store = st; return bs }})
+ fx.srv.usageNow = func() time.Time { return usageT0 }
+ holdHosts(fx.srv, activeAt(usageAt1), true)
+ return fx
+}
+
+// TestUsageFromWaitGivesUp (review R1 P2): while the start-up check is
+// stalled on the store, a request waiting for it answers 503 at its own
+// deadline rather than waiting with it.
+func TestUsageFromWaitGivesUp(t *testing.T) {
+ bs := newUsageFromBlockStore()
+ fx := usageFromBlockFixture(t, bs)
+ tok := serviceToken(t, fx.st, OpsAccountID, "meter", "kass", svcrole.Usage)
+ runCtx, stop := context.WithCancel(context.Background())
+ done := make(chan struct{})
+ go func() {
+ fx.srv.runUsageFrom(runCtx, nil)
+ close(done)
+ }()
+ defer func() {
+ stop()
+ <-done
+ }()
+ <-bs.blocked
+
+ reqCtx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)
+ defer cancel()
+ req := httptest.NewRequest(http.MethodGet, fx.ts.URL+"/api/cli/apps/"+fx.sqid+"/kass/usage?month=2027-01", nil).WithContext(reqCtx)
+ req.Header.Set("Authorization", "Bearer "+tok)
+ rec := httptest.NewRecorder()
+ served := make(chan struct{})
+ go func() {
+ fx.srv.ServeHTTP(rec, req)
+ close(served)
+ }()
+ select {
+ case <-served:
+ case <-bs.released:
+ t.Fatal("the stalled check ended before the request answered")
+ }
+ if rec.Code != http.StatusServiceUnavailable || jsonField(t, rec.Body.String(), "error") != msgUsageUnreadable || rec.Header().Get("Retry-After") != "60" {
+ t.Fatalf("request waiting on a stalled check = %d %s (Retry-After %q), want 503 %q", rec.Code, rec.Body.String(), rec.Header().Get("Retry-After"), msgUsageUnreadable)
+ }
+
+ // The check itself gives up at its own context too.
+ ctx, cancelCheck := context.WithCancel(context.Background())
+ cancelCheck()
+ if _, err := fx.srv.usageFromCheck(ctx, usageT0); !errors.Is(err, context.Canceled) {
+ t.Fatalf("check with an ended context = %v, want context.Canceled", err)
+ }
+}
+
+// TestUsageFromAttemptBounded (review R1 P2): each start-up attempt has
+// its own deadline; the stalled one times out, and the next succeeds.
+func TestUsageFromAttemptBounded(t *testing.T) {
+ old := usageFromAttemptTimeout
+ usageFromAttemptTimeout = 50 * time.Millisecond
+ t.Cleanup(func() { usageFromAttemptTimeout = old })
+ bs := newUsageFromBlockStore()
+ fx := usageFromBlockFixture(t, bs)
+ tick := make(chan time.Time)
+ done := make(chan struct{})
+ go func() {
+ fx.srv.runUsageFrom(context.Background(), tick)
+ close(done)
+ }()
+ <-bs.released
+ bs.mu.Lock()
+ err, dl := bs.err, bs.hadDeadline
+ bs.mu.Unlock()
+ if !dl || !errors.Is(err, context.DeadlineExceeded) {
+ t.Fatalf("the stalled attempt ended with %v (deadline %v), want its own deadline", err, dl)
+ }
+ select {
+ case tick <- usageT0:
+ case <-done:
+ }
+ <-done
+ if f, ok := storeUsageFrom(t, fx.rel); !ok || f.From != "2027-02-01" {
+ t.Fatalf("@from = %+v %v, want the next attempt to write 2027-02-01", f, ok)
+ }
+}