diff --git a/internal/infrastructure/staterpc/client.go b/internal/infrastructure/staterpc/client.go index 5d628a34c..aa2ab663b 100644 --- a/internal/infrastructure/staterpc/client.go +++ b/internal/infrastructure/staterpc/client.go @@ -25,6 +25,7 @@ type Client struct { identity pb.IdentityServiceClient task pb.TaskServiceClient execution pb.ExecutionServiceClient + usageOutbox *usageOutbox review pb.ReviewServiceClient taskEvent pb.TaskEventServiceClient stats pb.StatsServiceClient @@ -44,10 +45,11 @@ type Client struct { controlPlane controlpb.ControlPlaneServiceClient } -// NewClient wraps conn's generated clients. Close is a no-op: the store -// service owns its own DB lifecycle. +// NewClient wraps conn's generated clients. The client keeps a local usage +// outbox: a RecordUsage write that fails is retried in the background until +// the store accepts it. Close stops that retry worker. func NewClient(conn grpc.ClientConnInterface) *Client { - return &Client{ + c := &Client{ packages: pb.NewPackageServiceClient(conn), taskGrant: pb.NewTaskGrantServiceClient(conn), harnessSecret: pb.NewHarnessSecretServiceClient(conn), @@ -73,13 +75,21 @@ func NewClient(conn grpc.ClientConnInterface) *Client { schedule: pb.NewScheduleServiceClient(conn), controlPlane: controlpb.NewControlPlaneServiceClient(conn), } + c.usageOutbox = newUsageOutbox(c.writeUsage) + return c } // ControlPlane returns the generic control-plane RPC client on the same authenticated connection. func (c *Client) ControlPlane() controlpb.ControlPlaneServiceClient { return c.controlPlane } -// Close is a no-op; the remote store service owns its own DB lifecycle. -func (c *Client) Close() error { return nil } +// Close stops the usage retry worker, dropping any records still queued. The +// remote store service owns its own DB lifecycle. +func (c *Client) Close() error { + if c.usageOutbox != nil { + c.usageOutbox.stop() + } + return nil +} var ( _ storecontract.HarnessSecretStore = (*Client)(nil) diff --git a/internal/infrastructure/staterpc/executions.go b/internal/infrastructure/staterpc/executions.go index 71cc7a62b..b8136b712 100644 --- a/internal/infrastructure/staterpc/executions.go +++ b/internal/infrastructure/staterpc/executions.go @@ -2,6 +2,7 @@ package staterpc import ( "context" + "fmt" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" @@ -94,8 +95,29 @@ func (s *executionServer) ListSteps(ctx context.Context, r *pb.ListStepsRequest) return &pb.ListStepsResponse{Steps: mapValues(steps, stepExecutionProto)}, nil } -// RecordUsage appends one model call's usage record. +// RecordUsage appends one model call's usage record. The write is durable +// against a State Store outage: when the RPC fails, the record is queued in +// the client's local outbox and retried until the store accepts it, so the +// call returns once the record is written or safely queued. A non-nil error +// reports a deferred write (queued for retry) or a full queue (record +// dropped); it never fails the model call that produced the record. func (c *Client) RecordUsage(ctx context.Context, r usage.Record) error { + err := c.writeUsage(ctx, r) + if err == nil { + return nil + } + if c.usageOutbox == nil { + return err + } + //nolint:contextcheck // A queued record outlives the call that produced it. + if c.usageOutbox.enqueue(r) { + return fmt.Errorf("usage record queued for retry: %w", err) + } + return fmt.Errorf("usage retry queue full (%d pending), record dropped: %w", usageQueueBound, err) +} + +// writeUsage makes the one RecordUsage RPC. +func (c *Client) writeUsage(ctx context.Context, r usage.Record) error { _, err := c.execution.RecordUsage(ctx, &pb.RecordUsageRequest{Record: usageProto(r)}) return unmapError(err) } diff --git a/internal/infrastructure/staterpc/usage_outbox.go b/internal/infrastructure/staterpc/usage_outbox.go new file mode 100644 index 000000000..f548bcd1b --- /dev/null +++ b/internal/infrastructure/staterpc/usage_outbox.go @@ -0,0 +1,118 @@ +package staterpc + +import ( + "context" + "sync" + "time" + + "github.com/samcharles93/archie-core/internal/domain/usage" +) + +// A usage record is written on the model-call path, so a State Store outage +// must not lose it: chat, title, sampling and curator usage cannot be rebuilt +// from events the way task usage can. The Client therefore carries a local +// outbox: a write that fails is queued and retried until the store accepts it. + +const ( + // usageQueueBound caps the outbox. A record that does not fit is refused + // so the caller can report the drop; the bound keeps a long outage from + // growing memory without limit. + usageQueueBound = 1024 + // usageAttemptTimeout bounds one retry's RPC. + usageAttemptTimeout = 10 * time.Second + // usageRetryMinBackoff is the first wait between retries. It doubles up + // to usageRetryMaxBackoff, so a dead store is not polled in a spin. + usageRetryMinBackoff = time.Second + usageRetryMaxBackoff = time.Minute +) + +// usageOutbox is a bounded FIFO of usage records waiting for the store. Its +// worker starts on the first enqueue and runs for the Client's life, parked +// while the queue is empty. +type usageOutbox struct { + write func(ctx context.Context, r usage.Record) error + + minBackoff time.Duration + maxBackoff time.Duration + + mu sync.Mutex + pending []usage.Record + notify chan struct{} + done chan struct{} + start sync.Once + stopped sync.Once +} + +func newUsageOutbox(write func(ctx context.Context, r usage.Record) error) *usageOutbox { + return &usageOutbox{ + write: write, + minBackoff: usageRetryMinBackoff, + maxBackoff: usageRetryMaxBackoff, + notify: make(chan struct{}, 1), + done: make(chan struct{}), + } +} + +// enqueue appends r for retry and wakes the worker. It reports false when the +// queue is full: the record is not queued and the caller must report the loss. +func (o *usageOutbox) enqueue(r usage.Record) bool { + o.mu.Lock() + if len(o.pending) >= usageQueueBound { + o.mu.Unlock() + return false + } + o.pending = append(o.pending, r) + o.mu.Unlock() + o.start.Do(func() { go o.run() }) + select { + case o.notify <- struct{}{}: + default: + } + return true +} + +// stop halts the worker; records still queued are dropped. +func (o *usageOutbox) stop() { + o.stopped.Do(func() { close(o.done) }) +} + +// run delivers the queue's head until the store accepts it, backing off +// between failed attempts, then moves to the next record. Retries are +// detached from any caller's cancellation: the record outlives the call that +// produced it. +func (o *usageOutbox) run() { + backoff := o.minBackoff + for { + o.mu.Lock() + if len(o.pending) == 0 { + o.mu.Unlock() + select { + case <-o.notify: + continue + case <-o.done: + return + } + } + record := o.pending[0] + o.mu.Unlock() + + ctx, cancel := context.WithTimeout(context.Background(), usageAttemptTimeout) + err := o.write(ctx, record) + cancel() + if err == nil { + o.mu.Lock() + o.pending = o.pending[1:] + o.mu.Unlock() + backoff = o.minBackoff + continue + } + timer := time.NewTimer(backoff) + select { + case <-timer.C: + case <-o.done: + timer.Stop() + return + } + backoff = min(backoff*2, o.maxBackoff) + } +} diff --git a/internal/infrastructure/staterpc/usage_outbox_test.go b/internal/infrastructure/staterpc/usage_outbox_test.go new file mode 100644 index 000000000..3ea26f326 --- /dev/null +++ b/internal/infrastructure/staterpc/usage_outbox_test.go @@ -0,0 +1,128 @@ +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") + } +} diff --git a/internal/infrastructure/taskmcp/mcp_sampling.go b/internal/infrastructure/taskmcp/mcp_sampling.go index 56af6991e..e085fc203 100644 --- a/internal/infrastructure/taskmcp/mcp_sampling.go +++ b/internal/infrastructure/taskmcp/mcp_sampling.go @@ -58,8 +58,13 @@ func SamplingHandler(llm *runtime.Runtime, cfg config.TaskConfig, record func(co } } +// usageWriteTimeout bounds the usage write: a dead store must not hold the +// sampling result beyond a few seconds. +const usageWriteTimeout = 5 * time.Second + // UsageRecorder records a task's MCP sampling calls against the task. -// A failed write is logged, never fails the call. +// A failed write is logged, never fails the call: the store client queues the +// record and retries it until the store accepts it. func UsageRecorder(store usage.Recorder, t *workflow.Task, log *slog.Logger) func(context.Context, string, chat.Usage) { return func(ctx context.Context, model string, used chat.Usage) { if store == nil || t == nil { @@ -70,7 +75,9 @@ func UsageRecorder(store usage.Recorder, t *workflow.Task, log *slog.Logger) fun InputTokens: int64(used.PromptTokens), OutputTokens: int64(used.CompletionTokens), CachedTokens: int64(used.CachedTokens), At: time.Now().UTC(), }.WithRef(model) - if err := store.RecordUsage(ctx, record); err != nil && log != nil { + writeCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), usageWriteTimeout) + defer cancel() + if err := store.RecordUsage(writeCtx, record); err != nil && log != nil { log.WarnContext(ctx, "record model usage failed", "model", model, "err", err) } }