| 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) |
| + } |
| +} |