carlos / platform Public

host: flush instance counts once per batch into their date

The usage loop's per-instance flusher queues each drain as one batch,
grouped by usage/instances/<box>/<date>/<account>/<app>.json, and works
the queue oldest first: read, skip when this writer's marker already
names the batch, else merge and Put on the etag read (create-only when
absent). A failed part blocks later batches for that object until the
next tick. Buckets whose hour began more than 24h before the tick are
dropped before any write starts, as are buckets with no safe key; their
bytes show on the box status as instance_usage_dropped_bytes.

CARLOS_INSTANCE_USAGE=off disables the meter's per-instance map and arms
no flusher. Tests cover T1-T6 and T9 on DirStore with injected faults,
plus a seeded randomized simulation of faults, restarts and the horizon.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 964f7b7ce287875304fc4a862b55012280e1bd0d parent 9ece53c
8 files changed, +1,076 −13
  • internal/host/agent.go +11 −1
  • internal/host/applessroute_test.go +1 −1
  • internal/host/instance_usage.go +228 −0
  • internal/host/instance_usage_test.go +763 −0
  • internal/host/usage_loop.go +24 −4
  • internal/host/usage_loop_test.go +7 −7
  • internal/status/instanceusage_test.go +30 −0
  • internal/status/snapshot.go +12 −0
diff --git a/internal/host/agent.go b/internal/host/agent.go
index dac79e5b6..c3ede15be 100644
--- a/internal/host/agent.go
+++ b/internal/host/agent.go
@@ -1405,6 +1405,13 @@ func runAgent(args []string, buildClaims ClaimFactory) {
reload := func() { _ = e.Reload() }
layoutReload.Store(&reload)
m := edge.NewUsageMeter()
+ // The per-instance family's box switch: off, the meter keeps no
+ // per-instance counts and the usage loop arms no flusher.
+ instancesOff := instanceUsageOff(os.Getenv)
+ if instancesOff {
+ m.DisableInstances()
+ log.Printf("agent: instance usage off (CARLOS_INSTANCE_USAGE=off)")
+ }
e.EnableUsage(m)
// The plan rate ceiling (#358): the same plans snapshot the
// activator's idle hook reads, so a box without a plan catalog gets
@@ -1443,7 +1450,7 @@ func runAgent(args []string, buildClaims ClaimFactory) {
// without a route.
setProtectionSink(e.SetProtectionRecordOnly)
setAssetOwnersSource(e.AssetOwners)
- go usageLoop(m.Drain, am)
+ go usageLoop(m.Drain, am, !instancesOff)
// Edge request records (spec 2026-10-24-edge-request-protection-design):
// sampled 404 and rule-match records plus per-minute counts, filed
// into the log sink and shipped by logshipLoop. The same data dir as
@@ -5227,6 +5234,9 @@ func statusLoop(reg *registry.Registry, svc *activator.Service, buildStates func
// ExpiredCanaries answers spec §5 for this box's own routes; see
// countExpiredCanaries and the canaryStore/canaryPub comment above.
ExpiredCanaries: countExpiredCanaries(ctx, routes, canaryStore, canaryPub, time.Now()),
+ // The per-instance usage flusher's dropped bytes (instance usage
+ // spec §5), 0 while it is off or has dropped nothing.
+ InstanceUsageDroppedBytes: instanceUsageDroppedBytes(),
// LagSecs stays nil: litestream's per-DB replication lag isn't
// surfaced up to the agent process anywhere yet — the
// replication machinery (internal/lease's Replicator) lives
diff --git a/internal/host/applessroute_test.go b/internal/host/applessroute_test.go
index cddeaa67e..b13c4ada0 100644
--- a/internal/host/applessroute_test.go
+++ b/internal/host/applessroute_test.go
@@ -183,7 +183,7 @@ func TestLogshipAndAnalyticsDropAppLessRecords(t *testing.T) {
am.Observe(analytics.Obs{Acct: "bab", App: "web", Host: "web.example.com", Method: "GET", Status: 200, ContentType: "text/html", Path: "/", UA: "Mozilla/5.0 Safari", ClientIP: "1.2.3.4", Bytes: 10, When: now})
none := func() usage.EdgeFlush { return usage.EdgeFlush{} }
for i := 0; i < 2; i++ { // a second flush proves the bad delta was not re-queued
- if err := usageFlush(ctx, s, s, "box1", none, am, now); err != nil {
+ if err := usageFlush(ctx, s, s, "box1", none, am, nil, now); err != nil {
t.Fatal(err)
}
}
diff --git a/internal/host/instance_usage.go b/internal/host/instance_usage.go
new file mode 100644
index 000000000..6a232b991
--- /dev/null
+++ b/internal/host/instance_usage.go
@@ -0,0 +1,228 @@
+package host
+
+import (
+ "context"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "log"
+ "os"
+ "slices"
+ "sync/atomic"
+ "time"
+
+ "github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/usage"
+)
+
+// instanceHorizon is the drop horizon (spec §5 point 4): no write or retry
+// is started for a bucket whose hour began more than this long before the
+// tick. A bucket whose hour began exactly this long before is still written.
+const instanceHorizon = 24 * time.Hour
+
+// instanceBatch is one drain's per-instance counts, grouped by the object
+// they go to. owes shrinks as each object's part is written or dropped.
+type instanceBatch struct {
+ id string
+ owes map[string]map[usage.InstanceBucket]usage.InstanceCount // object key -> buckets
+}
+
+// instanceFlusher writes the per-instance meter's drains into their dated
+// objects (usage/instances/<box>/<date>/<account>/<app>.json), each batch
+// into each object at most once and, while it is queued, at least once
+// (spec §5). It keeps the batches not yet fully written in drain order; a
+// later batch is never written to an object while an earlier one still owes
+// it, so the object's applied[writer] always names the newest batch this
+// writer merged there. Add and Flush run on the usage loop's goroutine only;
+// DroppedBytes may be read from any goroutine.
+type instanceFlusher struct {
+ box string
+ writer string // this process's writer id, 16 hex characters
+ now func() time.Time
+ rnd io.Reader
+ queue []*instanceBatch
+ dropped atomic.Int64
+
+ // Test seams, nil in production: onAttempt sees each part before its
+ // write starts; onDrop sees each bucket the horizon drops.
+ onAttempt func(key string, buckets map[usage.InstanceBucket]usage.InstanceCount)
+ onDrop func(key string, b usage.InstanceBucket, c usage.InstanceCount)
+}
+
+// newInstanceFlusher draws the writer id from rnd (crypto/rand in
+// production).
+func newInstanceFlusher(box string, now func() time.Time, rnd io.Reader) *instanceFlusher {
+ f := &instanceFlusher{box: box, now: now, rnd: rnd}
+ f.writer = f.newID()
+ return f
+}
+
+// newID is 16 hex characters from rnd. Should rnd fail, the clock's
+// nanoseconds stand in: still distinct between this process's batches and
+// between processes in practice, which is all an id is for.
+func (f *instanceFlusher) newID() string {
+ var b [8]byte
+ if _, err := io.ReadFull(f.rnd, b[:]); err != nil {
+ log.Printf("agent: instance usage: random id: %v (using the clock)", err)
+ return fmt.Sprintf("%016x", uint64(f.now().UnixNano()))
+ }
+ return hex.EncodeToString(b[:])
+}
+
+// Add queues counts as one new batch, grouped by object key. Buckets whose
+// account or app cannot make a safe key are dropped here, logged and
+// counted in DroppedBytes: no retry could ever write them. Empty counts
+// queue nothing.
+func (f *instanceFlusher) Add(counts map[usage.InstanceBucket]usage.InstanceCount) {
+ if len(counts) == 0 {
+ return
+ }
+ owes := map[string]map[usage.InstanceBucket]usage.InstanceCount{}
+ for b, c := range counts {
+ key, err := usage.InstanceDayKey(f.box, usage.HourDate(b.Hour), b.Account, b.App)
+ if err != nil {
+ f.dropped.Add(c.BytesOut)
+ log.Printf("agent: instance usage: dropped %d bytes for account %q app %q: %v", c.BytesOut, b.Account, b.App, err)
+ continue
+ }
+ if owes[key] == nil {
+ owes[key] = map[usage.InstanceBucket]usage.InstanceCount{}
+ }
+ owes[key][b] = c
+ }
+ if len(owes) == 0 {
+ return
+ }
+ f.queue = append(f.queue, &instanceBatch{id: f.newID(), owes: owes})
+}
+
+// Flush works the queue once, oldest batch first (spec §5). A part past the
+// horizon is dropped; a part whose write fails stays owed and blocks every
+// later batch's part for the same object until the next tick. Batches that
+// owe nothing leave the queue.
+func (f *instanceFlusher) Flush(ctx context.Context, s release.Store) {
+ limit := f.now().Add(-instanceHorizon).Unix()
+ blocked := map[string]bool{}
+ for _, batch := range f.queue {
+ keys := make([]string, 0, len(batch.owes))
+ for k := range batch.owes {
+ keys = append(keys, k)
+ }
+ slices.Sort(keys)
+ for _, key := range keys {
+ buckets := batch.owes[key]
+ f.dropPastHorizon(key, buckets, limit)
+ if len(buckets) == 0 {
+ delete(batch.owes, key)
+ continue
+ }
+ if blocked[key] {
+ continue
+ }
+ if err := f.writePart(ctx, s, key, batch.id, buckets); err != nil {
+ blocked[key] = true
+ log.Printf("agent: instance usage: %s batch %s: %v (kept for the next tick)", key, batch.id, err)
+ continue
+ }
+ delete(batch.owes, key)
+ }
+ }
+ f.queue = slices.DeleteFunc(f.queue, func(b *instanceBatch) bool { return len(b.owes) == 0 })
+}
+
+// dropPastHorizon removes, from one part, every bucket whose hour began
+// before limit (Unix seconds), logging and counting its bytes.
+func (f *instanceFlusher) dropPastHorizon(key string, buckets map[usage.InstanceBucket]usage.InstanceCount, limit int64) {
+ var n int64
+ for b, c := range buckets {
+ if b.Hour*3600 >= limit {
+ continue
+ }
+ n += c.BytesOut
+ delete(buckets, b)
+ if f.onDrop != nil {
+ f.onDrop(key, b, c)
+ }
+ }
+ if n > 0 {
+ f.dropped.Add(n)
+ log.Printf("agent: instance usage: dropped %d bytes for %s, past the 24h horizon", n, key)
+ }
+}
+
+// writePart merges one batch's part into its object: read, skip when this
+// writer's marker already names the batch (a write that landed but whose
+// answer was lost), otherwise merge and Put conditional on the etag read,
+// create-only when absent. Up to three attempts on a lost race; any other
+// error is returned and the part stays owed.
+func (f *instanceFlusher) writePart(ctx context.Context, s release.Store, key, batch string, buckets map[usage.InstanceBucket]usage.InstanceCount) error {
+ if f.onAttempt != nil {
+ f.onAttempt(key, buckets)
+ }
+ counts := map[string]usage.InstanceCount{}
+ for b, c := range buckets {
+ cur := counts[b.Instance]
+ cur.Add(c)
+ counts[b.Instance] = cur
+ }
+ for attempt := 0; attempt < 3; attempt++ {
+ raw, etag, err := s.Get(ctx, key)
+ var day usage.InstanceDay
+ switch {
+ case err == nil:
+ if day, err = usage.DecodeInstanceDay(key, raw); err != nil {
+ return err
+ }
+ case errors.Is(err, os.ErrNotExist):
+ box, date, account, app, ok := usage.ParseInstanceDayKey(key)
+ if !ok {
+ return fmt.Errorf("%w: %s", usage.ErrInstanceKey, key)
+ }
+ day = usage.InstanceDay{V: 1, Box: box, Date: date, Account: account, App: app}
+ etag = "" // create-only Put
+ default:
+ return err
+ }
+ if day.Applied[f.writer] == batch {
+ return nil
+ }
+ day.Merge(f.writer, batch, counts)
+ out, err := json.Marshal(day)
+ if err != nil {
+ return err
+ }
+ if _, err := s.Put(ctx, key, out, etag); err == nil {
+ return nil
+ } else if !errors.Is(err, release.ErrCASConflict) {
+ return err
+ }
+ }
+ return errors.New("lost the write race three times")
+}
+
+// DroppedBytes is the bytes dropped since start: buckets past the horizon
+// and buckets with no safe key.
+func (f *instanceFlusher) DroppedBytes() int64 { return f.dropped.Load() }
+
+// Pending is how many batches are queued.
+func (f *instanceFlusher) Pending() int { return len(f.queue) }
+
+// instanceUsageOff is the box switch: CARLOS_INSTANCE_USAGE=off stops the
+// per-instance family on this box.
+func instanceUsageOff(getenv func(string) string) bool {
+ return getenv("CARLOS_INSTANCE_USAGE") == "off"
+}
+
+// activeInstanceFlusher is the usage loop's flusher, for the status tick's
+// dropped-bytes count. nil until the loop arms one, and while switched off.
+var activeInstanceFlusher atomic.Pointer[instanceFlusher]
+
+// instanceUsageDroppedBytes is the running flusher's DroppedBytes, or 0.
+func instanceUsageDroppedBytes() int64 {
+ if fl := activeInstanceFlusher.Load(); fl != nil {
+ return fl.DroppedBytes()
+ }
+ return 0
+}
diff --git a/internal/host/instance_usage_test.go b/internal/host/instance_usage_test.go
new file mode 100644
index 000000000..4742c68c9
--- /dev/null
+++ b/internal/host/instance_usage_test.go
@@ -0,0 +1,763 @@
+package host
+
+import (
+ "bytes"
+ "context"
+ "crypto/sha256"
+ "encoding/hex"
+ "errors"
+ "fmt"
+ "io"
+ "log"
+ "math/rand/v2"
+ "os"
+ "slices"
+ "strconv"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/edge"
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/usage"
+)
+
+var errInstanceFault = errors.New("test: injected store fault")
+
+// instanceHeldPut is a Put the fault store took and did not apply: its caller saw an
+// error, and land performs it later, conditional on the etag it carried.
+type instanceHeldPut struct {
+ key, etag string
+ body []byte
+}
+
+// instanceFaultStore wraps a DirStore. Each counter arms that many of the next
+// calls: failGets and failPuts return an error without touching the store;
+// loseAnswers applies the Put and returns an error; holdPuts takes the Put
+// aside for land. puts counts every Put the caller started; written
+// mirrors, per key, the last body a Put actually applied.
+type instanceFaultStore struct {
+ release.Store
+ failGets, failPuts, loseAnswers, holdPuts int
+ held []instanceHeldPut
+ puts int
+ written map[string][]byte
+}
+
+func newInstanceFaultStore(t *testing.T) *instanceFaultStore {
+ return &instanceFaultStore{Store: release.NewDirStore(t.TempDir()), written: map[string][]byte{}}
+}
+
+// instanceMemStore is Get, Put and List with DirStore's semantics (etag is
+// the body's SHA-256; Put "" is create-only, else replace-only on a matching
+// etag; ErrCASConflict otherwise), held in memory. The simulation runs on it
+// because DirStore syncs its directory on every Put, which makes thousands of
+// runs take minutes; every named test above runs on DirStore itself.
+type instanceMemStore struct {
+ release.Store // nil: the flusher calls only Get, Put and List
+ objs map[string][]byte
+}
+
+func (m *instanceMemStore) Get(_ context.Context, key string) ([]byte, string, error) {
+ b, ok := m.objs[key]
+ if !ok {
+ return nil, "", fmt.Errorf("memstore: %s: %w", key, os.ErrNotExist)
+ }
+ sum := sha256.Sum256(b)
+ return bytes.Clone(b), hex.EncodeToString(sum[:]), nil
+}
+
+func (m *instanceMemStore) Put(_ context.Context, key string, body []byte, ifMatch string) (string, error) {
+ cur, exists := m.objs[key]
+ sum := sha256.Sum256(cur)
+ switch {
+ case ifMatch == "" && exists:
+ return "", fmt.Errorf("memstore: %s exists: %w", key, release.ErrCASConflict)
+ case ifMatch != "" && (!exists || hex.EncodeToString(sum[:]) != ifMatch):
+ return "", fmt.Errorf("memstore: %s moved on: %w", key, release.ErrCASConflict)
+ }
+ m.objs[key] = bytes.Clone(body)
+ sum = sha256.Sum256(body)
+ return hex.EncodeToString(sum[:]), nil
+}
+
+func (m *instanceMemStore) List(_ context.Context, prefix string) ([]string, error) {
+ var keys []string
+ for k := range m.objs {
+ if strings.HasPrefix(k, prefix) {
+ keys = append(keys, k)
+ }
+ }
+ slices.Sort(keys)
+ return keys, nil
+}
+
+func (f *instanceFaultStore) Get(ctx context.Context, key string) ([]byte, string, error) {
+ if f.failGets > 0 {
+ f.failGets--
+ return nil, "", errInstanceFault
+ }
+ return f.Store.Get(ctx, key)
+}
+
+func (f *instanceFaultStore) Put(ctx context.Context, key string, body []byte, ifMatch string) (string, error) {
+ f.puts++
+ switch {
+ case f.failPuts > 0:
+ f.failPuts--
+ return "", errInstanceFault
+ case f.holdPuts > 0:
+ f.holdPuts--
+ f.held = append(f.held, instanceHeldPut{key: key, etag: ifMatch, body: bytes.Clone(body)})
+ return "", errInstanceFault
+ case f.loseAnswers > 0:
+ f.loseAnswers--
+ if _, err := f.apply(ctx, key, body, ifMatch); err != nil {
+ return "", err
+ }
+ return "", errInstanceFault
+ }
+ return f.apply(ctx, key, body, ifMatch)
+}
+
+func (f *instanceFaultStore) apply(ctx context.Context, key string, body []byte, ifMatch string) (string, error) {
+ etag, err := f.Store.Put(ctx, key, body, ifMatch)
+ if err == nil {
+ f.written[key] = bytes.Clone(body)
+ }
+ return etag, err
+}
+
+// land performs the oldest held Put now, conditional on its original etag.
+func (f *instanceFaultStore) land(ctx context.Context) error {
+ h := f.held[0]
+ f.held = f.held[1:]
+ _, err := f.apply(ctx, h.key, h.body, h.etag)
+ return err
+}
+
+type instanceClock struct{ t time.Time }
+
+func (c *instanceClock) now() time.Time { return c.t }
+
+func testRand(seed byte) io.Reader { return rand.NewChaCha8([32]byte{seed}) }
+
+func instanceRoute(account, app, host string) registry.Route {
+ return registry.Route{Host: host, App: app, Account: account, Kind: "instance"}
+}
+
+func readInstanceDay(t *testing.T, s release.Store, key string) usage.InstanceDay {
+ t.Helper()
+ raw, _, err := s.Get(context.Background(), key)
+ if err != nil {
+ t.Fatalf("get %s: %v", key, err)
+ }
+ d, err := usage.DecodeInstanceDay(key, raw)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return d
+}
+
+func dayBytes(d usage.InstanceDay) (n int64) {
+ for _, c := range d.Instances {
+ n += c.BytesOut
+ }
+ return n
+}
+
+func mustDayKey(t *testing.T, box, date, account, app string) string {
+ t.Helper()
+ k, err := usage.InstanceDayKey(box, date, account, app)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return k
+}
+
+func instanceKeys(t *testing.T, s release.Store, prefix string) []string {
+ t.Helper()
+ keys, err := s.List(context.Background(), prefix)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return keys
+}
+
+// T1: 23:58:30 November traffic drained at 00:03 on 1 December lands in 30
+// November's object, and nothing is written under 1 December.
+func TestInstanceFlushNovemberInDecember(t *testing.T) {
+ ctx := context.Background()
+ s := newInstanceFaultStore(t)
+ clk := &instanceClock{time.Date(2026, 11, 30, 23, 58, 30, 0, time.UTC)}
+ m := edge.NewUsageMeter()
+ m.SetClock(clk.now)
+ m.Record(instanceRoute("bab", "shop", "alpha.example.com"), "alpha.example.com", 1, 500, false)
+ clk.t = time.Date(2026, 12, 1, 0, 3, 0, 0, time.UTC)
+ fl := newInstanceFlusher("box1", clk.now, testRand(1))
+ if err := usageFlush(ctx, s, s, "box1", m.Drain, nil, fl, clk.t); err != nil {
+ t.Fatal(err)
+ }
+ d := readInstanceDay(t, s, mustDayKey(t, "box1", "2026-11-30", "bab", "shop"))
+ if got := d.Instances["alpha.example.com"]; got.BytesOut != 500 || got.Requests != 1 {
+ t.Fatalf("30 Nov counts = %+v, want 1 request, 500 bytes", got)
+ }
+ if keys := instanceKeys(t, s, usage.InstancesPrefix+"box1/2026-12-01/"); len(keys) != 0 {
+ t.Fatalf("wrote under 1 Dec: %v", keys)
+ }
+}
+
+// T2: the Puts at 00:03 and 00:08 fail; the 00:13 tick writes, once, still
+// into 30 November.
+func TestInstanceFlushLateRetry(t *testing.T) {
+ ctx := context.Background()
+ s := newInstanceFaultStore(t)
+ clk := &instanceClock{time.Date(2026, 11, 30, 23, 58, 30, 0, time.UTC)}
+ m := edge.NewUsageMeter()
+ m.SetClock(clk.now)
+ m.Record(instanceRoute("bab", "shop", "alpha.example.com"), "alpha.example.com", 1, 500, false)
+ fl := newInstanceFlusher("box1", clk.now, testRand(1))
+ s.failPuts = 2
+ for _, min := range []int{3, 8, 13} {
+ clk.t = time.Date(2026, 12, 1, 0, min, 0, 0, time.UTC)
+ _ = usageFlush(ctx, s, s, "box1", m.Drain, nil, fl, clk.t)
+ }
+ if fl.Pending() != 0 || s.puts != 3 {
+ t.Fatalf("pending %d, puts %d; want 0 and 3", fl.Pending(), s.puts)
+ }
+ d := readInstanceDay(t, s, mustDayKey(t, "box1", "2026-11-30", "bab", "shop"))
+ if got := dayBytes(d); got != 500 {
+ t.Fatalf("bytes = %d, want 500", got)
+ }
+ if keys := instanceKeys(t, s, usage.InstancesPrefix+"box1/2026-12-01/"); len(keys) != 0 {
+ t.Fatalf("wrote under 1 Dec: %v", keys)
+ }
+}
+
+func oneBucket(hour time.Time, account, app, host string, bytes int64) map[usage.InstanceBucket]usage.InstanceCount {
+ return map[usage.InstanceBucket]usage.InstanceCount{
+ {Hour: hour.Unix() / 3600, Account: account, App: app, Instance: host}: {Requests: 1, BytesOut: bytes},
+ }
+}
+
+// T3: the Put is applied but its answer is lost; the next tick reads its own
+// marker and Puts nothing.
+func TestInstanceFlushLostAnswer(t *testing.T) {
+ ctx := context.Background()
+ s := newInstanceFaultStore(t)
+ clk := &instanceClock{time.Date(2026, 11, 30, 10, 3, 0, 0, time.UTC)}
+ fl := newInstanceFlusher("box1", clk.now, testRand(1))
+ s.loseAnswers = 1
+ fl.Add(oneBucket(clk.t, "bab", "shop", "alpha.example.com", 500))
+ fl.Flush(ctx, s)
+ if fl.Pending() != 1 {
+ t.Fatalf("pending = %d after a lost answer, want 1", fl.Pending())
+ }
+ puts := s.puts
+ fl.Flush(ctx, s)
+ if fl.Pending() != 0 || s.puts != puts {
+ t.Fatalf("pending %d, puts %d -> %d; want 0 and no new Put", fl.Pending(), puts, s.puts)
+ }
+ if got := dayBytes(readInstanceDay(t, s, mustDayKey(t, "box1", "2026-11-30", "bab", "shop"))); got != 500 {
+ t.Fatalf("bytes = %d, want 500", got)
+ }
+}
+
+// T3: the first Put is held; the retry merges and lands; the held Put, let
+// go afterwards, fails its etag.
+func TestInstanceFlushDelayedRace(t *testing.T) {
+ ctx := context.Background()
+ s := newInstanceFaultStore(t)
+ clk := &instanceClock{time.Date(2026, 11, 30, 10, 3, 0, 0, time.UTC)}
+ fl := newInstanceFlusher("box1", clk.now, testRand(1))
+ key := mustDayKey(t, "box1", "2026-11-30", "bab", "shop")
+ // An existing object, so the held Put is a replace on an etag.
+ fl.Add(oneBucket(clk.t, "bab", "shop", "alpha.example.com", 100))
+ fl.Flush(ctx, s)
+ s.holdPuts = 1
+ fl.Add(oneBucket(clk.t, "bab", "shop", "alpha.example.com", 500))
+ fl.Flush(ctx, s)
+ if len(s.held) != 1 || fl.Pending() != 1 {
+ t.Fatalf("held %d, pending %d; want 1 and 1", len(s.held), fl.Pending())
+ }
+ fl.Flush(ctx, s)
+ if fl.Pending() != 0 {
+ t.Fatalf("pending = %d after the retry", fl.Pending())
+ }
+ if err := s.land(ctx); !errors.Is(err, release.ErrCASConflict) {
+ t.Fatalf("held Put landed with %v, want ErrCASConflict", err)
+ }
+ if got := dayBytes(readInstanceDay(t, s, key)); got != 600 {
+ t.Fatalf("bytes = %d, want 600", got)
+ }
+}
+
+// T3: two flushers of one box on one object, alternating batches: the total
+// is the sum, and both markers are kept.
+func TestInstanceFlushTwoWriters(t *testing.T) {
+ ctx := context.Background()
+ s := newInstanceFaultStore(t)
+ clk := &instanceClock{time.Date(2026, 11, 30, 10, 3, 0, 0, time.UTC)}
+ a := newInstanceFlusher("box1", clk.now, testRand(1))
+ b := newInstanceFlusher("box1", clk.now, testRand(2))
+ if a.writer == b.writer {
+ t.Fatal("two flushers share a writer id")
+ }
+ var want int64
+ for i, fl := range []*instanceFlusher{a, b, a, b, a} {
+ n := int64(10 * (i + 1))
+ want += n
+ fl.Add(oneBucket(clk.t, "bab", "shop", "alpha.example.com", n))
+ fl.Flush(ctx, s)
+ if fl.Pending() != 0 {
+ t.Fatalf("batch %d left pending", i)
+ }
+ }
+ d := readInstanceDay(t, s, mustDayKey(t, "box1", "2026-11-30", "bab", "shop"))
+ if got := dayBytes(d); got != want {
+ t.Fatalf("bytes = %d, want %d", got, want)
+ }
+ if d.Applied[a.writer] == "" || d.Applied[b.writer] == "" || len(d.Applied) != 2 {
+ t.Fatalf("applied = %v, want both writers", d.Applied)
+ }
+}
+
+// T4: batch X fails for object O and batch Y also owes O: Y waits that tick;
+// the next tick writes X, then Y, and the marker names Y.
+func TestInstanceFlushOrder(t *testing.T) {
+ ctx := context.Background()
+ s := newInstanceFaultStore(t)
+ clk := &instanceClock{time.Date(2026, 11, 30, 10, 3, 0, 0, time.UTC)}
+ fl := newInstanceFlusher("box1", clk.now, testRand(1))
+ key := mustDayKey(t, "box1", "2026-11-30", "bab", "shop")
+ var attempts []int64
+ fl.onAttempt = func(k string, buckets map[usage.InstanceBucket]usage.InstanceCount) {
+ for _, c := range buckets {
+ attempts = append(attempts, c.BytesOut)
+ }
+ }
+ fl.Add(oneBucket(clk.t, "bab", "shop", "alpha.example.com", 100)) // X
+ fl.Add(oneBucket(clk.t, "bab", "shop", "alpha.example.com", 7)) // Y
+ if fl.Pending() != 2 {
+ t.Fatalf("pending = %d, want 2", fl.Pending())
+ }
+ yID := fl.queue[1].id
+ s.failPuts = 1
+ fl.Flush(ctx, s)
+ if !slices.Equal(attempts, []int64{100}) || fl.Pending() != 2 {
+ t.Fatalf("first tick attempted %v, pending %d; want only X and both queued", attempts, fl.Pending())
+ }
+ fl.Flush(ctx, s)
+ if !slices.Equal(attempts, []int64{100, 100, 7}) || fl.Pending() != 0 {
+ t.Fatalf("attempts %v, pending %d; want X then Y", attempts, fl.Pending())
+ }
+ d := readInstanceDay(t, s, key)
+ if d.Applied[fl.writer] != yID || dayBytes(d) != 107 {
+ t.Fatalf("applied %v bytes %d; want %s and 107", d.Applied, dayBytes(d), yID)
+ }
+}
+
+// A bucket whose hour began exactly 24 h before the tick is written; at
+// 24 h and one second it is dropped, counted, and no Put is started.
+func TestInstanceFlushHorizon(t *testing.T) {
+ ctx := context.Background()
+ hour := time.Date(2026, 11, 30, 10, 0, 0, 0, time.UTC)
+ key := mustDayKey(t, "box1", "2026-11-30", "bab", "shop")
+
+ s := newInstanceFaultStore(t)
+ clk := &instanceClock{hour.Add(24 * time.Hour)}
+ fl := newInstanceFlusher("box1", clk.now, testRand(1))
+ fl.Add(oneBucket(hour, "bab", "shop", "alpha.example.com", 500))
+ fl.Flush(ctx, s)
+ if got := dayBytes(readInstanceDay(t, s, key)); got != 500 || fl.DroppedBytes() != 0 {
+ t.Fatalf("at 24h: bytes %d dropped %d; want 500 and 0", got, fl.DroppedBytes())
+ }
+
+ s = newInstanceFaultStore(t)
+ clk = &instanceClock{hour.Add(24*time.Hour + time.Second)}
+ fl = newInstanceFlusher("box1", clk.now, testRand(1))
+ attempted := 0
+ fl.onAttempt = func(string, map[usage.InstanceBucket]usage.InstanceCount) { attempted++ }
+ fl.Add(oneBucket(hour, "bab", "shop", "alpha.example.com", 500))
+ fl.Flush(ctx, s)
+ if fl.DroppedBytes() != 500 || s.puts != 0 || attempted != 0 || fl.Pending() != 0 {
+ t.Fatalf("past 24h: dropped %d puts %d attempts %d pending %d; want 500, 0, 0, 0",
+ fl.DroppedBytes(), s.puts, attempted, fl.Pending())
+ }
+}
+
+// An unsafe account's buckets are dropped and counted; the batch's other
+// objects are written and the queue empties.
+func TestInstanceFlushUnsafeKey(t *testing.T) {
+ ctx := context.Background()
+ s := newInstanceFaultStore(t)
+ clk := &instanceClock{time.Date(2026, 11, 30, 10, 3, 0, 0, time.UTC)}
+ fl := newInstanceFlusher("box1", clk.now, testRand(1))
+ h := clk.t.Unix() / 3600
+ fl.Add(map[usage.InstanceBucket]usage.InstanceCount{
+ {Hour: h, Account: "a/b", App: "shop", Instance: "x.example.com"}: {Requests: 1, BytesOut: 7},
+ {Hour: h, Account: "bab", App: "shop", Instance: "alpha.example.com"}: {Requests: 1, BytesOut: 500},
+ })
+ fl.Flush(ctx, s)
+ if fl.DroppedBytes() != 7 || fl.Pending() != 0 {
+ t.Fatalf("dropped %d pending %d; want 7 and 0", fl.DroppedBytes(), fl.Pending())
+ }
+ if got := dayBytes(readInstanceDay(t, s, mustDayKey(t, "box1", "2026-11-30", "bab", "shop"))); got != 500 {
+ t.Fatalf("bytes = %d, want 500", got)
+ }
+ if keys := instanceKeys(t, s, usage.InstancesPrefix); len(keys) != 1 {
+ t.Fatalf("keys = %v, want one", keys)
+ }
+}
+
+// T6: an exchange recorded at 00:00:05, though it began before midnight,
+// counts whole in the new day.
+func TestInstanceFlushSpanningResponse(t *testing.T) {
+ ctx := context.Background()
+ s := newInstanceFaultStore(t)
+ clk := &instanceClock{time.Date(2026, 12, 1, 0, 0, 5, 0, time.UTC)}
+ m := edge.NewUsageMeter()
+ m.SetClock(clk.now)
+ m.Record(instanceRoute("bab", "shop", "alpha.example.com"), "alpha.example.com", 1, 9000, false)
+ clk.t = time.Date(2026, 12, 1, 0, 3, 0, 0, time.UTC)
+ fl := newInstanceFlusher("box1", clk.now, testRand(1))
+ _ = usageFlush(ctx, s, s, "box1", m.Drain, nil, fl, clk.t)
+ if got := dayBytes(readInstanceDay(t, s, mustDayKey(t, "box1", "2026-12-01", "bab", "shop"))); got != 9000 {
+ t.Fatalf("1 Dec bytes = %d, want 9000", got)
+ }
+ if keys := instanceKeys(t, s, usage.InstancesPrefix+"box1/2026-11-30/"); len(keys) != 0 {
+ t.Fatalf("wrote under 30 Nov: %v", keys)
+ }
+}
+
+// T9: apps P and Q in one batch write two objects, each holding only its own
+// hosts; a later Q-only batch leaves P's object as it was.
+func TestInstanceFlushAppsApart(t *testing.T) {
+ ctx := context.Background()
+ s := newInstanceFaultStore(t)
+ clk := &instanceClock{time.Date(2026, 11, 30, 10, 3, 0, 0, time.UTC)}
+ fl := newInstanceFlusher("box1", clk.now, testRand(1))
+ h := clk.t.Unix() / 3600
+ fl.Add(map[usage.InstanceBucket]usage.InstanceCount{
+ {Hour: h, Account: "bab", App: "p", Instance: "p1.example.com"}: {Requests: 1, BytesOut: 10},
+ {Hour: h, Account: "bab", App: "q", Instance: "q1.example.com"}: {Requests: 2, BytesOut: 20},
+ })
+ fl.Flush(ctx, s)
+ pKey := mustDayKey(t, "box1", "2026-11-30", "bab", "p")
+ qKey := mustDayKey(t, "box1", "2026-11-30", "bab", "q")
+ p, q := readInstanceDay(t, s, pKey), readInstanceDay(t, s, qKey)
+ if len(p.Instances) != 1 || p.Instances["p1.example.com"].BytesOut != 10 {
+ t.Fatalf("P = %+v", p.Instances)
+ }
+ if len(q.Instances) != 1 || q.Instances["q1.example.com"].BytesOut != 20 {
+ t.Fatalf("Q = %+v", q.Instances)
+ }
+ before, _, _ := s.Get(ctx, pKey)
+ fl.Add(oneBucket(clk.t, "bab", "q", "q1.example.com", 5))
+ fl.Flush(ctx, s)
+ after, _, _ := s.Get(ctx, pKey)
+ if !bytes.Equal(before, after) {
+ t.Fatalf("P changed on a Q-only batch:\n%s\n%s", before, after)
+ }
+ if got := dayBytes(readInstanceDay(t, s, qKey)); got != 25 {
+ t.Fatalf("Q bytes = %d, want 25", got)
+ }
+}
+
+// Switched off, usageFlush writes no usage/instances/ key and the same
+// usage/edge/ bytes it writes with the flusher on.
+func TestInstanceFlushOffSwitch(t *testing.T) {
+ ctx := context.Background()
+ at := time.Date(2026, 11, 30, 10, 3, 0, 0, time.UTC)
+ run := func(fl *instanceFlusher) *instanceFaultStore {
+ s := newInstanceFaultStore(t)
+ m := edge.NewUsageMeter()
+ m.SetClock(func() time.Time { return at })
+ m.Record(instanceRoute("bab", "shop", "alpha.example.com"), "alpha.example.com", 3, 900, true)
+ if err := usageFlush(ctx, s, s, "box1", m.Drain, nil, fl, at); err != nil {
+ t.Fatal(err)
+ }
+ return s
+ }
+ off := run(nil)
+ on := run(newInstanceFlusher("box1", func() time.Time { return at }, testRand(1)))
+ if keys := instanceKeys(t, off, usage.InstancesPrefix); len(keys) != 0 {
+ t.Fatalf("off wrote %v", keys)
+ }
+ if keys := instanceKeys(t, on, usage.InstancesPrefix); len(keys) != 1 {
+ t.Fatalf("on wrote %v, want one key", keys)
+ }
+ key := usage.EdgeDayKey("box1", "2026-11-30")
+ a, _, errA := off.Get(ctx, key)
+ b, _, errB := on.Get(ctx, key)
+ if errA != nil || errB != nil || !bytes.Equal(a, b) {
+ t.Fatalf("edge day differs (%v, %v):\n%s\n%s", errA, errB, a, b)
+ }
+}
+
+// instanceSim is one run of TestInstanceFlushSimulation.
+type instanceSim struct {
+ t *testing.T
+ ctx context.Context
+ rng *rand.Rand
+ s *instanceFaultStore
+ clk *instanceClock
+ fl *instanceFlusher
+ old []*instanceFlusher // restarted flushers, for their dropped counts
+ pending map[usage.InstanceBucket]usage.InstanceCount
+ counted map[string]usage.InstanceCount // key -> sum of what its batches counted
+ markers map[string]map[string]bool // key -> writer ids ever written there
+ tainted map[string]bool // keys with a drop or a lost queue
+ nextRnd byte
+}
+
+var simAccounts = []string{"bab", "bdk", "a/b"}
+var simApps = []string{"p", "q"}
+var simHosts = []string{"", "one.example.com", "two.example.com"}
+
+func (sim *instanceSim) newFlusher() *instanceFlusher {
+ sim.nextRnd++
+ fl := newInstanceFlusher("box1", sim.clk.now, rand.NewChaCha8([32]byte{sim.nextRnd, byte(sim.rng.Uint32())}))
+ fl.onAttempt = func(key string, buckets map[usage.InstanceBucket]usage.InstanceCount) {
+ limit := sim.clk.t.Add(-24 * time.Hour).Unix()
+ for b := range buckets {
+ if b.Hour*3600 < limit {
+ sim.t.Fatalf("Put started for %s hour %d past the horizon at %s", key, b.Hour, sim.clk.t)
+ }
+ }
+ }
+ fl.onDrop = func(key string, _ usage.InstanceBucket, _ usage.InstanceCount) { sim.tainted[key] = true }
+ return fl
+}
+
+// add drains what was recorded into the flusher as one batch, counting it
+// against each object it owes.
+func (sim *instanceSim) add() {
+ for b, c := range sim.pending {
+ key, err := usage.InstanceDayKey("box1", usage.HourDate(b.Hour), b.Account, b.App)
+ if err != nil {
+ continue
+ }
+ cur := sim.counted[key]
+ cur.Add(c)
+ sim.counted[key] = cur
+ }
+ sim.fl.Add(sim.pending)
+ sim.pending = map[usage.InstanceBucket]usage.InstanceCount{}
+}
+
+func (sim *instanceSim) step() string {
+ switch sim.rng.IntN(10) {
+ case 0, 1:
+ // Mostly the last 20 hours, sometimes up to 30.
+ back := sim.rng.IntN(20 * 60)
+ if sim.rng.IntN(5) == 0 {
+ back = sim.rng.IntN(30 * 60)
+ }
+ at := sim.clk.t.Add(-time.Duration(back) * time.Minute)
+ b := usage.InstanceBucket{
+ Hour: at.Unix() / 3600,
+ Account: simAccounts[sim.rng.IntN(len(simAccounts))],
+ App: simApps[sim.rng.IntN(len(simApps))],
+ Instance: simHosts[sim.rng.IntN(len(simHosts))],
+ }
+ c := sim.pending[b]
+ c.Add(usage.InstanceCount{Requests: 1, BytesOut: int64(1 + sim.rng.IntN(1000))})
+ sim.pending[b] = c
+ return "record"
+ case 2:
+ sim.add()
+ return "add"
+ case 3:
+ sim.fl.Flush(sim.ctx, sim.s)
+ return "flush"
+ case 4:
+ if sim.rng.IntN(2) == 0 {
+ sim.s.failGets++
+ return "fail-get"
+ }
+ sim.s.failPuts++
+ return "fail-put"
+ case 5:
+ sim.s.loseAnswers++
+ return "lose-answer"
+ case 6:
+ sim.s.holdPuts++
+ return "hold"
+ case 7:
+ if len(sim.s.held) > 0 {
+ _ = sim.s.land(sim.ctx)
+ }
+ return "land"
+ case 8:
+ if sim.rng.IntN(4) == 0 {
+ for _, b := range sim.fl.queue {
+ for key := range b.owes {
+ sim.tainted[key] = true
+ }
+ }
+ sim.old = append(sim.old, sim.fl)
+ sim.fl = sim.newFlusher()
+ return "restart"
+ }
+ return "noop"
+ default:
+ sim.clk.t = sim.clk.t.Add(5 * time.Minute)
+ return "tick"
+ }
+}
+
+// check holds the invariants against the store's applied writes.
+func (sim *instanceSim) check(step int, op string) {
+ t := sim.t
+ held := map[string]bool{}
+ for _, h := range sim.s.held {
+ held[h.key] = true
+ }
+ queued := map[string]bool{}
+ for _, b := range sim.fl.queue {
+ for key := range b.owes {
+ queued[key] = true
+ }
+ }
+ for key, raw := range sim.s.written {
+ d, err := usage.DecodeInstanceDay(key, raw)
+ if err != nil {
+ t.Fatalf("step %d (%s): %v", step, op, err)
+ }
+ var got usage.InstanceCount
+ for _, c := range d.Instances {
+ got.Add(c)
+ }
+ want := sim.counted[key]
+ if got.BytesOut > want.BytesOut || got.Requests > want.Requests {
+ t.Fatalf("step %d (%s): %s holds %+v, more than its batches counted %+v", step, op, key, got, want)
+ }
+ if sim.markers[key] == nil {
+ sim.markers[key] = map[string]bool{}
+ }
+ for w := range sim.markers[key] {
+ if d.Applied[w] == "" {
+ t.Fatalf("step %d (%s): %s lost writer %s's marker", step, op, key, w)
+ }
+ }
+ for w := range d.Applied {
+ sim.markers[key][w] = true
+ }
+ if !sim.tainted[key] && !held[key] && !queued[key] && got != want {
+ t.Fatalf("step %d (%s): %s holds %+v, want %+v", step, op, key, got, want)
+ }
+ }
+ // A key counted but never written must be owed, held, or tainted.
+ for key, want := range sim.counted {
+ if _, ok := sim.s.written[key]; !ok && want.BytesOut > 0 && !sim.tainted[key] && !held[key] && !queued[key] {
+ t.Fatalf("step %d (%s): %s counted %+v but never written and not owed", step, op, key, want)
+ }
+ }
+}
+
+// T5: random interleavings of recording, draining, flushing, store faults,
+// held and lost writes, restarts and clock steps never count a byte twice,
+// never lose a marker and never start a Put past the horizon; with nothing
+// owed, held, dropped or lost, every object holds exactly what was counted.
+func TestInstanceFlushSimulation(t *testing.T) {
+ runs, steps := 2000, 300
+ if testing.Short() {
+ runs = 200
+ }
+ seed := uint64(time.Now().UnixNano())
+ if v := os.Getenv("INSTANCE_FLUSH_SEED"); v != "" {
+ n, err := strconv.ParseUint(v, 10, 64)
+ if err != nil {
+ t.Fatal(err)
+ }
+ seed = n
+ }
+ t.Logf("seed %d (rerun with INSTANCE_FLUSH_SEED=%d)", seed, seed)
+ out, flags := log.Writer(), log.Flags()
+ log.SetOutput(io.Discard)
+ t.Cleanup(func() { log.SetOutput(out); log.SetFlags(flags) })
+ ctx := context.Background()
+ for run := 0; run < runs; run++ {
+ rs := seed + uint64(run)
+ sim := &instanceSim{
+ t: t, ctx: ctx, rng: rand.New(rand.NewPCG(rs, 0x5eed)),
+ s: &instanceFaultStore{Store: &instanceMemStore{objs: map[string][]byte{}}, written: map[string][]byte{}},
+ clk: &instanceClock{time.Date(2026, 11, 29, 20, 0, 0, 0, time.UTC)},
+ pending: map[usage.InstanceBucket]usage.InstanceCount{},
+ counted: map[string]usage.InstanceCount{}, markers: map[string]map[string]bool{},
+ tainted: map[string]bool{},
+ }
+ sim.fl = sim.newFlusher()
+ for i := 0; i < steps; i++ {
+ op := sim.step()
+ if t.Failed() {
+ t.Fatalf("run seed %d", rs)
+ }
+ sim.check(i, op)
+ }
+ // Faults over: land what is held, add what is recorded and flush.
+ // The queue must empty, and every key not tainted by a drop or a
+ // lost queue then holds exactly what was counted.
+ sim.s.failGets, sim.s.failPuts, sim.s.loseAnswers, sim.s.holdPuts = 0, 0, 0, 0
+ for len(sim.s.held) > 0 {
+ _ = sim.s.land(ctx)
+ }
+ sim.add()
+ sim.fl.Flush(ctx, sim.s)
+ if sim.fl.Pending() != 0 {
+ t.Fatalf("run seed %d: %d batches still queued with no faults", rs, sim.fl.Pending())
+ }
+ sim.check(steps, "final")
+ // The mirror is what the store holds.
+ keys := instanceKeys(t, sim.s, usage.InstancesPrefix)
+ if len(keys) != len(sim.s.written) {
+ t.Fatalf("run seed %d: store has %d keys, mirror %d", rs, len(keys), len(sim.s.written))
+ }
+ for _, k := range keys {
+ raw, _, err := sim.s.Store.Get(ctx, k)
+ if err != nil || !bytes.Equal(raw, sim.s.written[k]) {
+ t.Fatalf("run seed %d: %s differs from the mirror (%v)", rs, k, err)
+ }
+ }
+ }
+}
+
+// The writer id is 16 hex characters from rnd, and each batch's id too.
+func TestInstanceFlushIDs(t *testing.T) {
+ clk := &instanceClock{time.Date(2026, 11, 30, 10, 3, 0, 0, time.UTC)}
+ fl := newInstanceFlusher("box1", clk.now, testRand(1))
+ fl.Add(oneBucket(clk.t, "bab", "shop", "alpha.example.com", 1))
+ for _, id := range []string{fl.writer, fl.queue[0].id} {
+ if len(id) != 16 || strings.Trim(id, "0123456789abcdef") != "" {
+ t.Fatalf("id %q is not 16 hex characters", id)
+ }
+ }
+ if fl.writer == fl.queue[0].id {
+ t.Fatal("batch id repeats the writer id")
+ }
+}
+
+// The box switch reads CARLOS_INSTANCE_USAGE=off exactly, and the status
+// tick reads the armed flusher's dropped bytes, or 0 with none armed.
+func TestInstanceFlushSwitchAndStatus(t *testing.T) {
+ for v, want := range map[string]bool{"off": true, "": false, "on": false, "0": false} {
+ if got := instanceUsageOff(func(string) string { return v }); got != want {
+ t.Errorf("CARLOS_INSTANCE_USAGE=%q: off = %v, want %v", v, got, want)
+ }
+ }
+ prev := activeInstanceFlusher.Load()
+ t.Cleanup(func() { activeInstanceFlusher.Store(prev) })
+ activeInstanceFlusher.Store(nil)
+ if got := instanceUsageDroppedBytes(); got != 0 {
+ t.Fatalf("no flusher: dropped = %d, want 0", got)
+ }
+ clk := &instanceClock{time.Date(2026, 11, 30, 10, 3, 0, 0, time.UTC)}
+ fl := newInstanceFlusher("box1", clk.now, testRand(1))
+ fl.Add(oneBucket(clk.t, "a/b", "shop", "x.example.com", 42))
+ activeInstanceFlusher.Store(fl)
+ if got := instanceUsageDroppedBytes(); got != 42 {
+ t.Fatalf("dropped = %d, want 42", got)
+ }
+}
diff --git a/internal/host/usage_loop.go b/internal/host/usage_loop.go
index 9eb447431..c620fe9e7 100644
--- a/internal/host/usage_loop.go
+++ b/internal/host/usage_loop.go
@@ -2,6 +2,7 @@ package host
import (
"context"
+ "crypto/rand"
"errors"
"log"
"os"
@@ -22,8 +23,19 @@ import (
// must NOT be rebased (same reasoning as log shipping — logship.go:54-61).
// A failed analytics batch is re-queued for the next tick; a failed usage
// write is returned but does not block the analytics flush.
-func usageFlush(ctx context.Context, s, raw release.Store, box string, drain func() usage.EdgeFlush, am *analytics.Meter, now time.Time) error {
- err := usage.UpsertEdgeDay(ctx, s, box, now, drain())
+//
+// fl is the per-instance flusher (nil when CARLOS_INSTANCE_USAGE=off): after
+// the edge day write, whatever that returned, the drain's Instances join its
+// queue as one batch and the queue is worked once against the same store s,
+// so a fleet box writes them under its prefix too. Its failures stay in its
+// queue for the next tick and never reach the returned error.
+func usageFlush(ctx context.Context, s, raw release.Store, box string, drain func() usage.EdgeFlush, am *analytics.Meter, fl *instanceFlusher, now time.Time) error {
+ f := drain()
+ err := usage.UpsertEdgeDay(ctx, s, box, now, f)
+ if fl != nil {
+ fl.Add(f.Instances)
+ fl.Flush(ctx, s)
+ }
if am == nil {
return err
}
@@ -56,7 +68,10 @@ func usageFlush(ctx context.Context, s, raw release.Store, box string, drain fun
// never fatal (the drained window is lost, the next one is not; modelling
// grade tolerates the gap). am is the analytics meter (nil disables the
// analytics half of the flush); its deltas are folded in on the same tick.
-func usageLoop(drain func() usage.EdgeFlush, am *analytics.Meter) {
+// instances arms the per-instance flusher (false when
+// CARLOS_INSTANCE_USAGE=off); it is published for the status tick's
+// dropped-bytes count.
+func usageLoop(drain func() usage.EdgeFlush, am *analytics.Meter, instances bool) {
defer func() {
if r := recover(); r != nil {
log.Printf("agent: usage loop panic, edge metering stopped for this process: %v", r)
@@ -77,10 +92,15 @@ func usageLoop(drain func() usage.EdgeFlush, am *analytics.Meter) {
}
s := release.NewPrefixStore(raw, resolveStatusPrefix(os.Getenv))
box := metricsBoxLabel(os.Getenv, readMachineID())
+ var fl *instanceFlusher
+ if instances {
+ fl = newInstanceFlusher(box, time.Now, rand.Reader)
+ activeInstanceFlusher.Store(fl)
+ }
log.Printf("agent: usage loop armed (5min flush), publishing to %s", target)
for {
time.Sleep(5 * time.Minute)
- if err := usageFlush(ctx, s, raw, box, drain, am, time.Now()); err != nil {
+ if err := usageFlush(ctx, s, raw, box, drain, am, fl, time.Now()); err != nil {
log.Printf("agent: usage flush: %v", err)
}
}
diff --git a/internal/host/usage_loop_test.go b/internal/host/usage_loop_test.go
index 0b9145326..7378a49f2 100644
--- a/internal/host/usage_loop_test.go
+++ b/internal/host/usage_loop_test.go
@@ -18,10 +18,10 @@ func TestUsageFlushWritesAndReflushesMerge(t *testing.T) {
rows := map[string]usage.EdgeRow{
"a.example.com": {Account: "bab", App: "hello", Requests: 3, BytesOut: 300},
}
- if err := usageFlush(ctx, s, s, "box1", func() usage.EdgeFlush { return usage.EdgeFlush{Rows: rows} }, nil, at); err != nil {
+ if err := usageFlush(ctx, s, s, "box1", func() usage.EdgeFlush { return usage.EdgeFlush{Rows: rows} }, nil, nil, at); err != nil {
t.Fatal(err)
}
- if err := usageFlush(ctx, s, s, "box1", func() usage.EdgeFlush { return usage.EdgeFlush{Rows: rows} }, nil, at.Add(5*time.Minute)); err != nil {
+ if err := usageFlush(ctx, s, s, "box1", func() usage.EdgeFlush { return usage.EdgeFlush{Rows: rows} }, nil, nil, at.Add(5*time.Minute)); err != nil {
t.Fatal(err)
}
raw, _, err := s.Get(ctx, usage.EdgeDayKey("box1", "2026-08-11"))
@@ -50,7 +50,7 @@ func TestUsageFlushCarriesGuardCounts(t *testing.T) {
Groups: map[string]int64{"probe/wordpress": 1},
}}}
}
- if err := usageFlush(ctx, s, s, "box1", drain, nil, at); err != nil {
+ if err := usageFlush(ctx, s, s, "box1", drain, nil, nil, at); err != nil {
t.Fatal(err)
}
raw, _, err := s.Get(ctx, usage.EdgeDayKey("box1", "2026-10-30"))
@@ -69,7 +69,7 @@ func TestUsageFlushCarriesGuardCounts(t *testing.T) {
func TestUsageFlushEmptyDrainWritesNothing(t *testing.T) {
s := release.NewDirStore(t.TempDir())
- err := usageFlush(context.Background(), s, s, "box1", func() usage.EdgeFlush { return usage.EdgeFlush{} }, nil, time.Now().UTC())
+ err := usageFlush(context.Background(), s, s, "box1", func() usage.EdgeFlush { return usage.EdgeFlush{} }, nil, nil, time.Now().UTC())
if err != nil {
t.Fatal(err)
}
@@ -87,7 +87,7 @@ func TestUsageFlushAlsoFlushesAnalytics(t *testing.T) {
now := time.Date(2026, 9, 7, 9, 30, 0, 0, time.UTC)
am := analytics.NewMeter(t.TempDir(), "box1", func() time.Time { return now })
am.Observe(analytics.Obs{Acct: "bab", App: "web", Host: "h", Method: "GET", Status: 200, ContentType: "text/html", Path: "/", UA: "Mozilla/5.0 Safari", ClientIP: "1.2.3.4", Bytes: 10, When: now})
- if err := usageFlush(ctx, s, s, "box1", func() usage.EdgeFlush { return usage.EdgeFlush{} }, am, now); err != nil {
+ if err := usageFlush(ctx, s, s, "box1", func() usage.EdgeFlush { return usage.EdgeFlush{} }, am, nil, now); err != nil {
t.Fatal(err)
}
sum, err := analytics.ReadRange(ctx, s, "bab", "web", now, now)
@@ -96,8 +96,8 @@ func TestUsageFlushAlsoFlushesAnalytics(t *testing.T) {
}
// A failed analytics flush re-queues; the next flush lands it.
am.Observe(analytics.Obs{Acct: "bab", App: "web", Host: "h", Method: "GET", Status: 200, ContentType: "text/html", Path: "/", UA: "Mozilla/5.0 Safari", ClientIP: "1.2.3.4", Bytes: 10, When: now})
- _ = usageFlush(ctx, s, failingStore{Store: s}, "box1", func() usage.EdgeFlush { return usage.EdgeFlush{} }, am, now)
- if err := usageFlush(ctx, s, s, "box1", func() usage.EdgeFlush { return usage.EdgeFlush{} }, am, now); err != nil {
+ _ = usageFlush(ctx, s, failingStore{Store: s}, "box1", func() usage.EdgeFlush { return usage.EdgeFlush{} }, am, nil, now)
+ if err := usageFlush(ctx, s, s, "box1", func() usage.EdgeFlush { return usage.EdgeFlush{} }, am, nil, now); err != nil {
t.Fatal(err)
}
if sum, _ := analytics.ReadRange(ctx, s, "bab", "web", now, now); sum.PV != 2 {
diff --git a/internal/status/instanceusage_test.go b/internal/status/instanceusage_test.go
new file mode 100644
index 000000000..771025d3e
--- /dev/null
+++ b/internal/status/instanceusage_test.go
@@ -0,0 +1,30 @@
+package status
+
+import (
+ "encoding/json"
+ "strings"
+ "testing"
+ "time"
+)
+
+// The per-instance usage flusher's dropped bytes reach the box snapshot as
+// instance_usage_dropped_bytes; nothing dropped omits the key, so the
+// snapshot is byte-identical to one written before the field existed.
+func TestCollectBoxCarriesInstanceUsageDroppedBytes(t *testing.T) {
+ now := time.Date(2026, 11, 30, 10, 0, 0, 0, time.UTC)
+ box := CollectBox(nil, Probes{InstanceUsageDroppedBytes: 4096}, now)
+ raw, err := json.Marshal(box)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if box.InstanceUsageDroppedBytes != 4096 || !strings.Contains(string(raw), `"instance_usage_dropped_bytes":4096`) {
+ t.Fatalf("snapshot = %s, want instance_usage_dropped_bytes 4096", raw)
+ }
+ raw, err = json.Marshal(CollectBox(nil, Probes{}, now))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if strings.Contains(string(raw), "instance_usage_dropped_bytes") {
+ t.Fatalf("nothing dropped still wrote the key: %s", raw)
+ }
+}
diff --git a/internal/status/snapshot.go b/internal/status/snapshot.go
index 0e2fcb727..826894a35 100644
--- a/internal/status/snapshot.go
+++ b/internal/status/snapshot.go
@@ -111,6 +111,10 @@ type Probes struct {
// zero; 0 is itself a real, confident answer when every canary route on
// the box is fresh, or there are none at all.
ExpiredCanaries *int
+ // InstanceUsageDroppedBytes is the per-instance usage flusher's dropped
+ // bytes since the agent started (Box.InstanceUsageDroppedBytes); 0 when
+ // nothing was dropped or the family is switched off.
+ InstanceUsageDroppedBytes int64
// Alerts is the box's alert-sink answer (see AlertDelivery), carried
// into Box.Metrics. nil means "never asked".
Alerts *AlertDelivery
@@ -1086,6 +1090,12 @@ type Box struct {
// and is never copied into FleetBox; "" (every box that is not managed)
// omits the key, so those snapshots are byte-identical to before.
ManagedKey string `json:"managed_key,omitempty"`
+ // InstanceUsageDroppedBytes is how many bytes of per-instance usage this
+ // box's agent has dropped since it started (instance usage spec §5): a
+ // bucket past the 24-hour write horizon, or one with no safe object key.
+ // A count, never which instance. 0 omits the key, so a box that dropped
+ // nothing (or predates the family) is byte-identical to before.
+ InstanceUsageDroppedBytes int64 `json:"instance_usage_dropped_bytes,omitempty"`
}
// replHealthyWithin is the lag under which replication counts as healthy.
@@ -1336,6 +1346,8 @@ func CollectBox(routes []registry.Route, p Probes, now time.Time) Box {
RestartPathRunning: p.RestartPathRunning,
ExpiredCanaries: p.ExpiredCanaries,
Sidecars: sidecars,
+
+ InstanceUsageDroppedBytes: p.InstanceUsageDroppedBytes,
}
// Metrics attaches only when something is known — an all-unknown Probes,