| index 4742c68c9..edb61ef18 100644 |
| --- a/internal/host/instance_usage_test.go |
| +++ b/internal/host/instance_usage_test.go |
| @@ -5,6 +5,7 @@ import ( |
| "context" |
| "crypto/sha256" |
| "encoding/hex" |
| + "encoding/json" |
| "errors" |
| "fmt" |
| "io" |
| @@ -35,11 +36,17 @@ type instanceHeldPut struct { |
| // 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. |
| +// aside for land; competes runs compete, once, inside the next Put of an |
| +// instance object, after the caller's Get and before its Put reaches the |
| +// store, so that Put meets whatever compete wrote. 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 |
| + competes int |
| + compete func(ctx context.Context, key string) |
| + competing bool |
| held []instanceHeldPut |
| puts int |
| written map[string][]byte |
| @@ -103,6 +110,12 @@ func (f *instanceFaultStore) Get(ctx context.Context, key string) ([]byte, strin |
| |
| func (f *instanceFaultStore) Put(ctx context.Context, key string, body []byte, ifMatch string) (string, error) { |
| f.puts++ |
| + if f.competes > 0 && !f.competing && f.compete != nil && strings.HasPrefix(key, usage.InstancesPrefix) { |
| + f.competes-- |
| + f.competing = true |
| + f.compete(ctx, key) |
| + f.competing = false |
| + } |
| switch { |
| case f.failPuts > 0: |
| f.failPuts-- |
| @@ -359,7 +372,7 @@ func TestInstanceFlushOrder(t *testing.T) { |
| } |
| |
| // 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. |
| +// 24 h and one nanosecond 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) |
| @@ -375,7 +388,7 @@ func TestInstanceFlushHorizon(t *testing.T) { |
| } |
| |
| s = newInstanceFaultStore(t) |
| - clk = &instanceClock{hour.Add(24*time.Hour + time.Second)} |
| + clk = &instanceClock{hour.Add(24*time.Hour + time.Nanosecond)} |
| fl = newInstanceFlusher("box1", clk.now, testRand(1)) |
| attempted := 0 |
| fl.onAttempt = func(string, map[usage.InstanceBucket]usage.InstanceCount) { attempted++ } |
| @@ -496,20 +509,98 @@ func TestInstanceFlushOffSwitch(t *testing.T) { |
| } |
| } |
| |
| +// rivalWrite merges one count into key as another writer would, straight |
| +// into the store underneath any fault, and returns what it added. |
| +func rivalWrite(ctx context.Context, s *instanceFaultStore, key, writer, batch string, n int64) (usage.InstanceCount, error) { |
| + day := usage.InstanceDay{} |
| + raw, etag, err := s.Store.Get(ctx, key) |
| + switch { |
| + case err == nil: |
| + if day, err = usage.DecodeInstanceDay(key, raw); err != nil { |
| + return usage.InstanceCount{}, err |
| + } |
| + case errors.Is(err, os.ErrNotExist): |
| + box, date, account, app, _ := usage.ParseInstanceDayKey(key) |
| + day = usage.InstanceDay{V: 1, Box: box, Date: date, Account: account, App: app} |
| + etag = "" |
| + default: |
| + return usage.InstanceCount{}, err |
| + } |
| + c := usage.InstanceCount{Requests: 1, BytesOut: n} |
| + day.Merge(writer, batch, map[string]usage.InstanceCount{"rival.example.com": c}) |
| + out, err := json.Marshal(day) |
| + if err != nil { |
| + return usage.InstanceCount{}, err |
| + } |
| + _, err = s.apply(ctx, key, out, etag) |
| + return c, err |
| +} |
| + |
| +// A competing write between the flusher's Get and its Put makes that Put a |
| +// real etag conflict: the flusher re-reads, merges on top and lands, so the |
| +// object holds both counts and both markers. |
| +func TestInstanceFlushConflictRetries(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") |
| + for _, existing := range []bool{false, true} { // create-only, then replace |
| + s.competes = 1 |
| + s.compete = func(ctx context.Context, k string) { |
| + if _, err := rivalWrite(ctx, s, k, "rival", fmt.Sprint(existing), 7); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + puts := s.puts |
| + fl.Add(oneBucket(clk.t, "bab", "shop", "alpha.example.com", 500)) |
| + fl.Flush(ctx, s) |
| + if fl.Pending() != 0 || s.puts != puts+2 { |
| + t.Fatalf("existing=%v: pending %d, puts %d; want 0 and a conflict then a retry", existing, fl.Pending(), s.puts-puts) |
| + } |
| + } |
| + d := readInstanceDay(t, s, key) |
| + if got := dayBytes(d); got != 1014 || d.Applied["rival"] != "true" || d.Applied[fl.writer] == "" { |
| + t.Fatalf("bytes %d applied %v; want 1014 and both writers", got, d.Applied) |
| + } |
| +} |
| + |
| // 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 |
| + t *testing.T |
| + ctx context.Context |
| + rng *rand.Rand |
| + s *instanceFaultStore |
| + clk *instanceClock |
| + fls [2]*instanceFlusher // two live writers of one box |
| + flushing int // index of the flusher in Flush |
| + rivals int // rival batches written |
| + 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 |
| +} |
| + |
| +// flush runs live flusher i; compete, inside it, runs the other one and |
| +// then a rival writer, both between i's Get and Put. |
| +func (sim *instanceSim) flush(i int) { |
| + prev := sim.flushing |
| + sim.flushing = i |
| + sim.fls[i].Flush(sim.ctx, sim.s) |
| + sim.flushing = prev |
| +} |
| + |
| +func (sim *instanceSim) compete(ctx context.Context, key string) { |
| + sim.flush(1 - sim.flushing) |
| + sim.rivals++ |
| + c, err := rivalWrite(ctx, sim.s, key, "rival", strconv.Itoa(sim.rivals), int64(1+sim.rng.IntN(100))) |
| + if err != nil { |
| + sim.t.Fatalf("rival write %s: %v", key, err) |
| + } |
| + cur := sim.counted[key] |
| + cur.Add(c) |
| + sim.counted[key] = cur |
| } |
| |
| var simAccounts = []string{"bab", "bdk", "a/b"} |
| @@ -520,9 +611,9 @@ 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() |
| + cutoff := sim.clk.t.Add(-24 * time.Hour) |
| for b := range buckets { |
| - if b.Hour*3600 < limit { |
| + if time.Unix(b.Hour*3600, 0).Before(cutoff) { |
| sim.t.Fatalf("Put started for %s hour %d past the horizon at %s", key, b.Hour, sim.clk.t) |
| } |
| } |
| @@ -531,9 +622,9 @@ func (sim *instanceSim) newFlusher() *instanceFlusher { |
| return fl |
| } |
| |
| -// add drains what was recorded into the flusher as one batch, counting it |
| -// against each object it owes. |
| -func (sim *instanceSim) add() { |
| +// add drains what was recorded into live flusher i as one batch, counting |
| +// it against each object it owes. |
| +func (sim *instanceSim) add(i int) { |
| for b, c := range sim.pending { |
| key, err := usage.InstanceDayKey("box1", usage.HourDate(b.Hour), b.Account, b.App) |
| if err != nil { |
| @@ -543,12 +634,13 @@ func (sim *instanceSim) add() { |
| cur.Add(c) |
| sim.counted[key] = cur |
| } |
| - sim.fl.Add(sim.pending) |
| + sim.fls[i].Add(sim.pending) |
| sim.pending = map[usage.InstanceBucket]usage.InstanceCount{} |
| } |
| |
| func (sim *instanceSim) step() string { |
| - switch sim.rng.IntN(10) { |
| + live := sim.rng.IntN(2) |
| + switch sim.rng.IntN(11) { |
| case 0, 1: |
| // Mostly the last 20 hours, sometimes up to 30. |
| back := sim.rng.IntN(20 * 60) |
| @@ -567,10 +659,10 @@ func (sim *instanceSim) step() string { |
| sim.pending[b] = c |
| return "record" |
| case 2: |
| - sim.add() |
| + sim.add(live) |
| return "add" |
| case 3: |
| - sim.fl.Flush(sim.ctx, sim.s) |
| + sim.flush(live) |
| return "flush" |
| case 4: |
| if sim.rng.IntN(2) == 0 { |
| @@ -592,18 +684,28 @@ func (sim *instanceSim) step() string { |
| return "land" |
| case 8: |
| if sim.rng.IntN(4) == 0 { |
| - for _, b := range sim.fl.queue { |
| + for _, b := range sim.fls[live].queue { |
| for key := range b.owes { |
| sim.tainted[key] = true |
| } |
| } |
| - sim.old = append(sim.old, sim.fl) |
| - sim.fl = sim.newFlusher() |
| + sim.fls[live] = sim.newFlusher() |
| return "restart" |
| } |
| return "noop" |
| + case 9: |
| + sim.s.competes++ |
| + return "compete" |
| default: |
| - sim.clk.t = sim.clk.t.Add(5 * time.Minute) |
| + // Five minutes and a sub-second jitter, or now and then to just |
| + // past the next hour, so the horizon is met at full clock precision |
| + // (a bucket 24 h and under a second old). |
| + jitter := time.Duration(sim.rng.IntN(int(time.Second))) |
| + if sim.rng.IntN(4) == 0 { |
| + sim.clk.t = sim.clk.t.Truncate(time.Hour).Add(time.Hour + jitter) |
| + return "tick-hour" |
| + } |
| + sim.clk.t = sim.clk.t.Add(5*time.Minute + jitter) |
| return "tick" |
| } |
| } |
| @@ -616,9 +718,11 @@ func (sim *instanceSim) check(step int, op string) { |
| held[h.key] = true |
| } |
| queued := map[string]bool{} |
| - for _, b := range sim.fl.queue { |
| - for key := range b.owes { |
| - queued[key] = true |
| + for _, fl := range sim.fls { |
| + for _, b := range fl.queue { |
| + for key := range b.owes { |
| + queued[key] = true |
| + } |
| } |
| } |
| for key, raw := range sim.s.written { |
| @@ -689,7 +793,8 @@ func TestInstanceFlushSimulation(t *testing.T) { |
| counted: map[string]usage.InstanceCount{}, markers: map[string]map[string]bool{}, |
| tainted: map[string]bool{}, |
| } |
| - sim.fl = sim.newFlusher() |
| + sim.s.compete = sim.compete |
| + sim.fls = [2]*instanceFlusher{sim.newFlusher(), sim.newFlusher()} |
| for i := 0; i < steps; i++ { |
| op := sim.step() |
| if t.Failed() { |
| @@ -700,14 +805,16 @@ func TestInstanceFlushSimulation(t *testing.T) { |
| // 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 |
| + sim.s.failGets, sim.s.failPuts, sim.s.loseAnswers, sim.s.holdPuts, sim.s.competes = 0, 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.add(0) |
| + for i := range sim.fls { |
| + sim.flush(i) |
| + if n := sim.fls[i].Pending(); n != 0 { |
| + t.Fatalf("run seed %d: flusher %d has %d batches queued with no faults", rs, i, n) |
| + } |
| } |
| sim.check(steps, "final") |
| // The mirror is what the store holds. |
| @@ -761,3 +868,26 @@ func TestInstanceFlushSwitchAndStatus(t *testing.T) { |
| t.Fatalf("dropped = %d, want 42", got) |
| } |
| } |
| + |
| +// An unsafe account/app logs once per process however many drains carry |
| +// it, while every drain's bytes are counted. |
| +func TestInstanceFlushUnsafeKeyLogsOnce(t *testing.T) { |
| + unsafeInstanceSeen.Clear() |
| + t.Cleanup(unsafeInstanceSeen.Clear) |
| + logged := captureLog(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 |
| + for i := 0; i < 3; i++ { |
| + fl.Add(map[usage.InstanceBucket]usage.InstanceCount{ |
| + {Hour: h, Account: "c/d", App: "shop", Instance: "one.example.com"}: {Requests: 1, BytesOut: 10}, |
| + {Hour: h, Account: "c/d", App: "shop", Instance: "two.example.com"}: {Requests: 1, BytesOut: 5}, |
| + }) |
| + if got, want := fl.DroppedBytes(), int64(15*(i+1)); got != want { |
| + t.Fatalf("drain %d: dropped = %d, want %d", i, got, want) |
| + } |
| + } |
| + if n := strings.Count(logged(), `account "c/d" app "shop"`); n != 1 { |
| + t.Fatalf("logged %d times, want once:\n%s", n, logged()) |
| + } |
| +} |