package staterpc import ( "context" "errors" "sync" "testing" "time" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" pb "github.com/samcharles93/archie-core/internal/contracts/state/v1" "github.com/samcharles93/archie-core/internal/domain/usage" ) // fakeStoreConn is a State Store connection whose RecordUsage RPC fails while // the store is down and keeps what it accepts once it is back. type fakeStoreConn struct { mu sync.Mutex down bool writes []usage.Record } func (f *fakeStoreConn) Invoke(_ context.Context, method string, args, _ any, _ ...grpc.CallOption) error { if method != pb.ExecutionService_RecordUsage_FullMethodName { return status.Error(codes.Unimplemented, method) } req, ok := args.(*pb.RecordUsageRequest) if !ok { return status.Error(codes.Internal, "unexpected RecordUsage request") } f.mu.Lock() defer f.mu.Unlock() if f.down { return status.Error(codes.Unavailable, "state store down") } f.writes = append(f.writes, usageValue(req.Record)) return nil } func (f *fakeStoreConn) NewStream(context.Context, *grpc.StreamDesc, string, ...grpc.CallOption) (grpc.ClientStream, error) { return nil, status.Error(codes.Unimplemented, "streams are not faked") } func (f *fakeStoreConn) setDown(down bool) { f.mu.Lock() f.down = down f.mu.Unlock() } func (f *fakeStoreConn) recorded() []usage.Record { f.mu.Lock() defer f.mu.Unlock() return append([]usage.Record(nil), f.writes...) } // A usage write that fails during a State Store outage is retried until the // store recovers: the record lands, unchanged, once the store is back. func TestRecordUsageSurvivesStoreOutage(t *testing.T) { conn := &fakeStoreConn{down: true} client := NewClient(conn) client.usageOutbox.minBackoff = time.Millisecond client.usageOutbox.maxBackoff = 5 * time.Millisecond t.Cleanup(func() { _ = client.Close() }) record := usage.Record{ Source: usage.SourceChat, Provider: "openai", Model: "gpt-test", InputTokens: 11, OutputTokens: 7, CachedTokens: 3, At: time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC), } if err := client.RecordUsage(context.Background(), record); err == nil { t.Fatal("RecordUsage during an outage = nil error, want the deferral reported") } if got := conn.recorded(); len(got) != 0 { t.Fatalf("store recorded %d rows during the outage, want 0", len(got)) } conn.setDown(false) deadline := time.Now().Add(5 * time.Second) for { if got := conn.recorded(); len(got) == 1 { landed := got[0] if landed.Source != record.Source || landed.Provider != record.Provider || landed.Model != record.Model || landed.InputTokens != record.InputTokens || landed.OutputTokens != record.OutputTokens || landed.CachedTokens != record.CachedTokens || !landed.At.Equal(record.At) { t.Fatalf("recorded %+v, want %+v", landed, record) } break } if time.Now().After(deadline) { t.Fatalf("store recorded %d rows after recovery, want 1", len(conn.recorded())) } time.Sleep(time.Millisecond) } // Once the store is back, a new write goes straight through. if err := client.RecordUsage(context.Background(), record); err != nil { t.Fatalf("RecordUsage after recovery = %v, want nil", err) } if got := conn.recorded(); len(got) != 2 { t.Fatalf("store recorded %d rows after recovery, want 2", len(got)) } } // The outbox is bounded: a record that does not fit is refused so the caller // reports the drop instead of the queue growing without limit. func TestUsageOutboxIsBounded(t *testing.T) { o := newUsageOutbox(func(context.Context, usage.Record) error { return errors.New("state store down") }) // The worker never gets past its first failed attempt, so the queue stays // full and the bound is deterministic. o.minBackoff = time.Hour o.maxBackoff = time.Hour t.Cleanup(o.stop) record := usage.Record{Source: usage.SourceChat, Provider: "p", Model: "m"} for i := range usageQueueBound { if !o.enqueue(record) { t.Fatalf("enqueue %d refused, want the queue to accept %d records", i, usageQueueBound) } } if o.enqueue(record) { t.Fatal("enqueue past the bound accepted, want a refusal") } }