refactor(aibridge): stamp records when they are created (#29918)
Timestamps were set in `WrappedRecorder`, on the goroutine that delivered the record, and in local time. A record could therefore be stamped after the interception it belongs to had ended, and the value depended on delivery scheduling rather than on when the event happened. Stamp each record where it is created, in UTC. `WrappedRecorder` is left resolving clients, which is all it now does. Each PR targets the one before it. Together they are #29664, which stays open until the stack is merged; the tip of the stack is byte-identical to its tree. <details> <summary>Why the stack is ordered this way</summary> The final design is a chain of recorder decorators: +---------------------+ | AsyncRecorder | all records except the interception start +---------------------+ | LogRecorder | emit the structured record +---------------------+ | ValidatingRecorder | refuse malformed records +---------------------+ | caller middleware | record policy, e.g. drop content +---------------------+ | TraceRecorder | +---------------------+ | DRPCRecorder | acquire client, send to coderd +---------------------+ Ordering constraints: - The record type constants (1) are the vocabulary both emitters and the validator use, so they come first. - Validation (5) rejects unset timestamps, so records must already be stamped where they are created (3). Stamping at creation leaves `WrappedRecorder` doing nothing but client acquisition, which is why it is folded into `DRPCRecorder` (4) and not before. - coderd's server-time fallback (2) is what keeps a gateway of an older version from persisting zero times once the gateway owns stamping (3). - PRs 1 to 5 change no user-visible surface. Each deployment option then lands with the code that reads it: the log source with gateway-side emission (6), content recording with the filter that drops the records (7). Pool options are plumbed to the serving pool in 6, where the first option that needs them arrives, rather than as an unused hook beforehand. </details> --- 🤖 Raised by [Coder Agents](https://coder.com) on behalf of @SasSwart.
This commit is contained in:
1 parent
6054e46060
commit
a69d89bae6
11 files changed
+39
-14
No files matched your search
@@ -222,6 +222,7 @@ func newInterceptionProcessor(p provider.Provider, cbs *circuitbreaker.ProviderC
|
||||
interceptor.Setup(logger, asyncRecorder, mcpProxy)
|
||||
|
||||
if err := rec.RecordInterception(ctx, &recorder.InterceptionRecord{
|
||||
StartedAt: time.Now().UTC(),
|
||||
ID: interceptor.ID().String(),
|
||||
InitiatorID: actor.ID,
|
||||
Metadata: actor.Metadata,
|
||||
@@ -284,6 +285,7 @@ func newInterceptionProcessor(p provider.Provider, cbs *circuitbreaker.ProviderC
|
||||
}
|
||||
|
||||
_ = asyncRecorder.RecordInterceptionEnded(ctx, &recorder.InterceptionRecordEnded{
|
||||
EndedAt: time.Now().UTC(),
|
||||
ID: interceptor.ID().String(),
|
||||
CredentialHint: cred.Hint(),
|
||||
ErrorType: errType,
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/openai/openai-go/v3"
|
||||
@@ -277,6 +278,7 @@ func (i *interceptionBase) recordTokenUsage(ctx context.Context, msgID string, u
|
||||
}
|
||||
|
||||
_ = i.recorder.RecordTokenUsage(ctx, &recorder.TokenUsageRecord{
|
||||
CreatedAt: time.Now().UTC(),
|
||||
InterceptionID: i.ID().String(),
|
||||
MsgID: msgID,
|
||||
Input: calculateActualInputTokenUsage(usage),
|
||||
|
||||
@@ -135,6 +135,7 @@ func (i *BlockingInterception) ProcessRequest(w http.ResponseWriter, r *http.Req
|
||||
|
||||
if prompt != nil {
|
||||
_ = i.recorder.RecordPromptUsage(ctx, &recorder.PromptUsageRecord{
|
||||
CreatedAt: time.Now().UTC(),
|
||||
InterceptionID: i.ID().String(),
|
||||
MsgID: completion.ID,
|
||||
Prompt: *prompt,
|
||||
@@ -155,6 +156,7 @@ func (i *BlockingInterception) ProcessRequest(w http.ResponseWriter, r *http.Req
|
||||
pendingToolCalls = append(pendingToolCalls, toolCall)
|
||||
} else {
|
||||
_ = i.recorder.RecordToolUsage(ctx, &recorder.ToolUsageRecord{
|
||||
CreatedAt: time.Now().UTC(),
|
||||
InterceptionID: i.ID().String(),
|
||||
MsgID: completion.ID,
|
||||
ToolCallID: toolCall.ID,
|
||||
@@ -193,6 +195,7 @@ func (i *BlockingInterception) ProcessRequest(w http.ResponseWriter, r *http.Req
|
||||
args := i.unmarshalArgs(tc.Function.Arguments)
|
||||
res, err := tool.Call(ctx, args, i.tracer)
|
||||
_ = i.recorder.RecordToolUsage(ctx, &recorder.ToolUsageRecord{
|
||||
CreatedAt: time.Now().UTC(),
|
||||
InterceptionID: i.ID().String(),
|
||||
MsgID: completion.ID,
|
||||
ToolCallID: tc.ID,
|
||||
|
||||
@@ -265,6 +265,7 @@ func (i *StreamingInterception) ProcessRequest(w http.ResponseWriter, r *http.Re
|
||||
// Builtin tools are not intercepted.
|
||||
if i.getInjectedToolByName(toolCall.Name) == nil {
|
||||
_ = i.recorder.RecordToolUsage(streamCtx, &recorder.ToolUsageRecord{
|
||||
CreatedAt: time.Now().UTC(),
|
||||
InterceptionID: i.ID().String(),
|
||||
MsgID: processor.getMsgID(),
|
||||
ToolCallID: toolCall.ID,
|
||||
@@ -287,6 +288,7 @@ func (i *StreamingInterception) ProcessRequest(w http.ResponseWriter, r *http.Re
|
||||
|
||||
if prompt != nil {
|
||||
_ = i.recorder.RecordPromptUsage(streamCtx, &recorder.PromptUsageRecord{
|
||||
CreatedAt: time.Now().UTC(),
|
||||
InterceptionID: i.ID().String(),
|
||||
MsgID: processor.getMsgID(),
|
||||
Prompt: *prompt,
|
||||
@@ -375,6 +377,7 @@ func (i *StreamingInterception) ProcessRequest(w http.ResponseWriter, r *http.Re
|
||||
args := i.unmarshalArgs(toolCall.Arguments)
|
||||
toolRes, toolErr := tool.Call(streamCtx, args, i.tracer)
|
||||
_ = i.recorder.RecordToolUsage(streamCtx, &recorder.ToolUsageRecord{
|
||||
CreatedAt: time.Now().UTC(),
|
||||
InterceptionID: i.ID().String(),
|
||||
MsgID: processor.getMsgID(),
|
||||
ToolCallID: id,
|
||||
|
||||
@@ -182,6 +182,7 @@ func (i *interceptionBase) recordTokenUsage(ctx context.Context, msgID string, u
|
||||
}
|
||||
|
||||
usageRecord := recorder.TokenUsageRecord{
|
||||
CreatedAt: time.Now().UTC(),
|
||||
InterceptionID: i.ID().String(),
|
||||
MsgID: msgID,
|
||||
Input: usage.InputTokens,
|
||||
@@ -318,8 +319,9 @@ func (*interceptionBase) extractModelThoughts(msg *anthropic.Message) []*recorde
|
||||
continue
|
||||
}
|
||||
thoughtRecords = append(thoughtRecords, &recorder.ModelThoughtRecord{
|
||||
Content: variant.Thinking,
|
||||
Metadata: recorder.Metadata{"source": recorder.ThoughtSourceThinking},
|
||||
CreatedAt: time.Now().UTC(),
|
||||
Content: variant.Thinking,
|
||||
Metadata: recorder.Metadata{"source": recorder.ThoughtSourceThinking},
|
||||
})
|
||||
}
|
||||
return thoughtRecords
|
||||
|
||||
@@ -1670,6 +1670,11 @@ func TestRecordTokenUsage(t *testing.T) {
|
||||
|
||||
usages := rec.RecordedTokenUsages()
|
||||
require.Len(t, usages, 1)
|
||||
|
||||
// The record carries the time it was created; the rest of the
|
||||
// record is compared verbatim.
|
||||
require.False(t, usages[0].CreatedAt.IsZero(), "token usage was not stamped")
|
||||
usages[0].CreatedAt = time.Time{}
|
||||
require.Equal(t, tc.expected, usages[0])
|
||||
})
|
||||
}
|
||||
|
||||
@@ -142,6 +142,7 @@ func (i *BlockingInterception) ProcessRequest(w http.ResponseWriter, r *http.Req
|
||||
|
||||
if prompt != nil {
|
||||
_ = i.recorder.RecordPromptUsage(ctx, &recorder.PromptUsageRecord{
|
||||
CreatedAt: time.Now().UTC(),
|
||||
InterceptionID: i.ID().String(),
|
||||
MsgID: resp.ID,
|
||||
Prompt: *prompt,
|
||||
@@ -156,6 +157,7 @@ func (i *BlockingInterception) ProcessRequest(w http.ResponseWriter, r *http.Req
|
||||
// Capture any thinking blocks that were returned.
|
||||
for _, t := range i.extractModelThoughts(resp) {
|
||||
_ = i.recorder.RecordModelThought(ctx, &recorder.ModelThoughtRecord{
|
||||
CreatedAt: time.Now().UTC(),
|
||||
InterceptionID: i.ID().String(),
|
||||
Content: t.Content,
|
||||
Metadata: t.Metadata,
|
||||
@@ -177,6 +179,7 @@ func (i *BlockingInterception) ProcessRequest(w http.ResponseWriter, r *http.Req
|
||||
|
||||
// If tool is not injected, track it since the client will be handling it.
|
||||
_ = i.recorder.RecordToolUsage(ctx, &recorder.ToolUsageRecord{
|
||||
CreatedAt: time.Now().UTC(),
|
||||
InterceptionID: i.ID().String(),
|
||||
MsgID: resp.ID,
|
||||
ToolCallID: toolUse.ID,
|
||||
@@ -213,6 +216,7 @@ func (i *BlockingInterception) ProcessRequest(w http.ResponseWriter, r *http.Req
|
||||
res, err := tool.Call(ctx, tc.Input, i.tracer)
|
||||
|
||||
_ = i.recorder.RecordToolUsage(ctx, &recorder.ToolUsageRecord{
|
||||
CreatedAt: time.Now().UTC(),
|
||||
InterceptionID: i.ID().String(),
|
||||
MsgID: resp.ID,
|
||||
ToolCallID: tc.ID,
|
||||
|
||||
@@ -315,6 +315,7 @@ newStream:
|
||||
// Capture any thinking blocks that were returned.
|
||||
for _, t := range i.extractModelThoughts(&message) {
|
||||
_ = i.recorder.RecordModelThought(ctx, &recorder.ModelThoughtRecord{
|
||||
CreatedAt: time.Now().UTC(),
|
||||
InterceptionID: i.ID().String(),
|
||||
Content: t.Content,
|
||||
Metadata: t.Metadata,
|
||||
@@ -366,6 +367,7 @@ newStream:
|
||||
res, err := tool.Call(streamCtx, input, i.tracer)
|
||||
|
||||
_ = i.recorder.RecordToolUsage(streamCtx, &recorder.ToolUsageRecord{
|
||||
CreatedAt: time.Now().UTC(),
|
||||
InterceptionID: i.ID().String(),
|
||||
MsgID: message.ID,
|
||||
ToolCallID: id,
|
||||
@@ -490,6 +492,7 @@ newStream:
|
||||
}
|
||||
|
||||
_ = i.recorder.RecordToolUsage(streamCtx, &recorder.ToolUsageRecord{
|
||||
CreatedAt: time.Now().UTC(),
|
||||
InterceptionID: i.ID().String(),
|
||||
MsgID: message.ID,
|
||||
ToolCallID: variant.ID,
|
||||
@@ -521,6 +524,7 @@ newStream:
|
||||
|
||||
if promptFound {
|
||||
_ = i.recorder.RecordPromptUsage(ctx, &recorder.PromptUsageRecord{
|
||||
CreatedAt: time.Now().UTC(),
|
||||
InterceptionID: i.ID().String(),
|
||||
MsgID: message.ID,
|
||||
Prompt: prompt,
|
||||
|
||||
@@ -284,6 +284,7 @@ func (i *responsesInterceptionBase) recordUserPrompt(ctx context.Context, respon
|
||||
}
|
||||
|
||||
promptUsage := &recorder.PromptUsageRecord{
|
||||
CreatedAt: time.Now().UTC(),
|
||||
InterceptionID: i.ID().String(),
|
||||
MsgID: responseID,
|
||||
Prompt: prompt,
|
||||
@@ -296,6 +297,7 @@ func (i *responsesInterceptionBase) recordUserPrompt(ctx context.Context, respon
|
||||
func (i *responsesInterceptionBase) recordModelThoughts(ctx context.Context, response *responses.Response) {
|
||||
for _, t := range i.extractModelThoughts(response) {
|
||||
_ = i.recorder.RecordModelThought(ctx, &recorder.ModelThoughtRecord{
|
||||
CreatedAt: time.Now().UTC(),
|
||||
InterceptionID: i.ID().String(),
|
||||
Content: t.Content,
|
||||
Metadata: t.Metadata,
|
||||
@@ -346,6 +348,7 @@ func (i *responsesInterceptionBase) recordNonInjectedToolUsage(ctx context.Conte
|
||||
}
|
||||
|
||||
if err := i.recorder.RecordToolUsage(ctx, &recorder.ToolUsageRecord{
|
||||
CreatedAt: time.Now().UTC(),
|
||||
InterceptionID: i.ID().String(),
|
||||
MsgID: response.ID,
|
||||
// ItemID is always present; ToolCallID (call_id) is empty for
|
||||
@@ -395,6 +398,7 @@ func (i *responsesInterceptionBase) recordTokenUsage(ctx context.Context, respon
|
||||
}
|
||||
|
||||
if err := i.recorder.RecordTokenUsage(ctx, &recorder.TokenUsageRecord{
|
||||
CreatedAt: time.Now().UTC(),
|
||||
InterceptionID: i.ID().String(),
|
||||
MsgID: response.ID,
|
||||
Input: inputNonCacheTokens,
|
||||
@@ -429,8 +433,9 @@ func (*responsesInterceptionBase) extractModelThoughts(response *responses.Respo
|
||||
continue
|
||||
}
|
||||
thoughts = append(thoughts, &recorder.ModelThoughtRecord{
|
||||
Content: summary.Text,
|
||||
Metadata: recorder.Metadata{"source": recorder.ThoughtSourceReasoningSummary},
|
||||
CreatedAt: time.Now().UTC(),
|
||||
Content: summary.Text,
|
||||
Metadata: recorder.Metadata{"source": recorder.ThoughtSourceReasoningSummary},
|
||||
})
|
||||
}
|
||||
|
||||
@@ -453,8 +458,9 @@ func (*responsesInterceptionBase) extractModelThoughts(response *responses.Respo
|
||||
continue
|
||||
}
|
||||
thoughts = append(thoughts, &recorder.ModelThoughtRecord{
|
||||
Content: part.Text,
|
||||
Metadata: recorder.Metadata{"source": recorder.ThoughtSourceCommentary},
|
||||
CreatedAt: time.Now().UTC(),
|
||||
Content: part.Text,
|
||||
Metadata: recorder.Metadata{"source": recorder.ThoughtSourceCommentary},
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/openai/openai-go/v3"
|
||||
"github.com/openai/openai-go/v3/responses"
|
||||
@@ -179,6 +180,7 @@ func (i *responsesInterceptionBase) invokeInjectedTool(ctx context.Context, resp
|
||||
args := i.parseFunctionCallJSONArgs(ctx, fc.Arguments)
|
||||
res, err := tool.Call(ctx, args, i.tracer)
|
||||
_ = i.recorder.RecordToolUsage(ctx, &recorder.ToolUsageRecord{
|
||||
CreatedAt: time.Now().UTC(),
|
||||
InterceptionID: i.ID().String(),
|
||||
MsgID: responseID,
|
||||
ToolCallID: fc.CallID,
|
||||
|
||||
@@ -2,7 +2,6 @@ package recorder
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"golang.org/x/xerrors"
|
||||
)
|
||||
@@ -10,7 +9,6 @@ import (
|
||||
var _ Recorder = &WrappedRecorder{}
|
||||
|
||||
// WrappedRecorder is a convenience struct which implements Recorder and resolves a client before calling each method.
|
||||
// It also sets the start/creation time of each record.
|
||||
type WrappedRecorder struct {
|
||||
clientFn func(context.Context) (Recorder, error)
|
||||
}
|
||||
@@ -21,7 +19,6 @@ func (r *WrappedRecorder) RecordInterception(ctx context.Context, req *Intercept
|
||||
return xerrors.Errorf("acquire client: %w", err)
|
||||
}
|
||||
|
||||
req.StartedAt = time.Now()
|
||||
return client.RecordInterception(ctx, req)
|
||||
}
|
||||
|
||||
@@ -31,7 +28,6 @@ func (r *WrappedRecorder) RecordInterceptionEnded(ctx context.Context, req *Inte
|
||||
return xerrors.Errorf("acquire client: %w", err)
|
||||
}
|
||||
|
||||
req.EndedAt = time.Now().UTC()
|
||||
return client.RecordInterceptionEnded(ctx, req)
|
||||
}
|
||||
|
||||
@@ -41,7 +37,6 @@ func (r *WrappedRecorder) RecordPromptUsage(ctx context.Context, req *PromptUsag
|
||||
return xerrors.Errorf("acquire client: %w", err)
|
||||
}
|
||||
|
||||
req.CreatedAt = time.Now()
|
||||
return client.RecordPromptUsage(ctx, req)
|
||||
}
|
||||
|
||||
@@ -51,7 +46,6 @@ func (r *WrappedRecorder) RecordTokenUsage(ctx context.Context, req *TokenUsageR
|
||||
return xerrors.Errorf("acquire client: %w", err)
|
||||
}
|
||||
|
||||
req.CreatedAt = time.Now()
|
||||
return client.RecordTokenUsage(ctx, req)
|
||||
}
|
||||
|
||||
@@ -61,7 +55,6 @@ func (r *WrappedRecorder) RecordToolUsage(ctx context.Context, req *ToolUsageRec
|
||||
return xerrors.Errorf("acquire client: %w", err)
|
||||
}
|
||||
|
||||
req.CreatedAt = time.Now()
|
||||
return client.RecordToolUsage(ctx, req)
|
||||
}
|
||||
|
||||
@@ -71,7 +64,6 @@ func (r *WrappedRecorder) RecordModelThought(ctx context.Context, req *ModelThou
|
||||
return xerrors.Errorf("acquire client: %w", err)
|
||||
}
|
||||
|
||||
req.CreatedAt = time.Now()
|
||||
return client.RecordModelThought(ctx, req)
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user