-
Notifications
You must be signed in to change notification settings - Fork 1.4k
feat(coderd/x/chatd/chatdebug): add recorder, transport, and redaction #23915
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
22a09c8
feat(coderd/x/chatd/chatdebug): add recorder, transport, and redaction
ThomasK33 bdbf53b
fix(coderd/x/chatd/chatdebug): address remaining review feedback on P…
ThomasK33 90a4df5
fix(coderd/x/chatd/chatdebug): use case-insensitive Content-Type lookup
ThomasK33 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,277 @@ | ||
| package chatdebug | ||
|
|
||
| import ( | ||
| "context" | ||
| "sync" | ||
| "sync/atomic" | ||
| "time" | ||
|
|
||
| "charm.land/fantasy" | ||
| "github.com/google/uuid" | ||
|
|
||
| "cdr.dev/slog/v3" | ||
| ) | ||
|
|
||
| // RecorderOptions identifies the chat/model context for debug recording. | ||
| type RecorderOptions struct { | ||
| ChatID uuid.UUID | ||
| OwnerID uuid.UUID | ||
| Provider string | ||
| Model string | ||
| } | ||
|
|
||
| // WrapModel returns model unchanged when debug recording is disabled, or a | ||
| // debug wrapper when a service is available. | ||
| func WrapModel( | ||
| model fantasy.LanguageModel, | ||
| svc *Service, | ||
| opts RecorderOptions, | ||
| ) fantasy.LanguageModel { | ||
| if model == nil { | ||
| panic("chatdebug: nil LanguageModel") | ||
| } | ||
| if svc == nil { | ||
| return model | ||
| } | ||
| return &debugModel{inner: model, svc: svc, opts: opts} | ||
| } | ||
|
|
||
| type attemptSink struct { | ||
| mu sync.Mutex | ||
| attempts []Attempt | ||
| attemptCounter atomic.Int32 | ||
| } | ||
|
|
||
| func (s *attemptSink) nextAttemptNumber() int { | ||
| if s == nil { | ||
| panic("chatdebug: nil attemptSink") | ||
| } | ||
| return int(s.attemptCounter.Add(1)) | ||
| } | ||
|
|
||
| func (s *attemptSink) record(a Attempt) { | ||
| s.mu.Lock() | ||
| defer s.mu.Unlock() | ||
|
|
||
| s.attempts = append(s.attempts, a) | ||
| } | ||
|
|
||
| func (s *attemptSink) snapshot() []Attempt { | ||
| s.mu.Lock() | ||
| defer s.mu.Unlock() | ||
|
|
||
| attempts := make([]Attempt, len(s.attempts)) | ||
| copy(attempts, s.attempts) | ||
| return attempts | ||
| } | ||
|
|
||
| type attemptSinkKey struct{} | ||
|
|
||
| func withAttemptSink(ctx context.Context, sink *attemptSink) context.Context { | ||
| if sink == nil { | ||
| panic("chatdebug: nil attemptSink") | ||
| } | ||
| return context.WithValue(ctx, attemptSinkKey{}, sink) | ||
| } | ||
|
|
||
| func attemptSinkFromContext(ctx context.Context) *attemptSink { | ||
| sink, _ := ctx.Value(attemptSinkKey{}).(*attemptSink) | ||
| return sink | ||
| } | ||
|
|
||
| var stepCounters sync.Map // map[uuid.UUID]*atomic.Int32 | ||
|
ThomasK33 marked this conversation as resolved.
|
||
|
|
||
| func nextStepNumber(runID uuid.UUID) int32 { | ||
| val, _ := stepCounters.LoadOrStore(runID, &atomic.Int32{}) | ||
|
ThomasK33 marked this conversation as resolved.
ThomasK33 marked this conversation as resolved.
ThomasK33 marked this conversation as resolved.
|
||
| counter, ok := val.(*atomic.Int32) | ||
| if !ok { | ||
| panic("chatdebug: invalid step counter type") | ||
| } | ||
| return counter.Add(1) | ||
| } | ||
|
|
||
| // CleanupStepCounter removes per-run step counter and reference count | ||
| // state. This is used by tests and later stacked branches that have a | ||
| // real run lifecycle. | ||
| func CleanupStepCounter(runID uuid.UUID) { | ||
| stepCounters.Delete(runID) | ||
| runRefCounts.Delete(runID) | ||
| } | ||
|
|
||
| const stepFinalizeTimeout = 5 * time.Second | ||
|
|
||
| func stepFinalizeContext(ctx context.Context) (context.Context, context.CancelFunc) { | ||
| if ctx == nil { | ||
| panic("chatdebug: nil context") | ||
| } | ||
| return context.WithTimeout(context.WithoutCancel(ctx), stepFinalizeTimeout) | ||
| } | ||
|
|
||
| func syncStepCounter(runID uuid.UUID, stepNumber int32) { | ||
| val, _ := stepCounters.LoadOrStore(runID, &atomic.Int32{}) | ||
| counter, ok := val.(*atomic.Int32) | ||
| if !ok { | ||
| panic("chatdebug: invalid step counter type") | ||
| } | ||
| for { | ||
| current := counter.Load() | ||
| if current >= stepNumber { | ||
| return | ||
| } | ||
| if counter.CompareAndSwap(current, stepNumber) { | ||
| return | ||
| } | ||
| } | ||
| } | ||
|
|
||
| type stepHandle struct { | ||
| stepCtx *StepContext | ||
| sink *attemptSink | ||
| svc *Service | ||
| opts RecorderOptions | ||
| once sync.Once | ||
| mu sync.Mutex | ||
| status Status | ||
| response any | ||
| usage any | ||
| err any | ||
| metadata any | ||
| } | ||
|
|
||
| // beginStep validates preconditions, creates a debug step, and returns a | ||
| // handle plus an enriched context carrying StepContext and attemptSink. | ||
| // Returns (nil, original ctx) when debug recording should be skipped. | ||
| func beginStep( | ||
| ctx context.Context, | ||
| svc *Service, | ||
| opts RecorderOptions, | ||
| op Operation, | ||
| normalizedReq any, | ||
| ) (*stepHandle, context.Context) { | ||
| if svc == nil { | ||
| return nil, ctx | ||
| } | ||
|
|
||
| rc, ok := RunFromContext(ctx) | ||
| if !ok || rc.RunID == uuid.Nil { | ||
| return nil, ctx | ||
| } | ||
|
|
||
| chatID := opts.ChatID | ||
| if chatID == uuid.Nil { | ||
| chatID = rc.ChatID | ||
| } | ||
| if !svc.IsEnabled(ctx, chatID, opts.OwnerID) { | ||
| return nil, ctx | ||
| } | ||
|
|
||
| holder, reuseStep := reuseHolderFromContext(ctx) | ||
| if reuseStep { | ||
| holder.mu.Lock() | ||
| defer holder.mu.Unlock() | ||
| // Only reuse the cached handle if it belongs to the same run. | ||
| // A different RunContext means a new logical run, so we must | ||
| // create a fresh step to avoid cross-run attribution. | ||
| if holder.handle != nil && holder.handle.stepCtx.RunID == rc.RunID { | ||
| enriched := ContextWithStep(ctx, holder.handle.stepCtx) | ||
| enriched = withAttemptSink(enriched, holder.handle.sink) | ||
| return holder.handle, enriched | ||
| } | ||
| } | ||
|
|
||
| stepNum := nextStepNumber(rc.RunID) | ||
| step, err := svc.CreateStep(ctx, CreateStepParams{ | ||
| RunID: rc.RunID, | ||
| ChatID: chatID, | ||
| StepNumber: stepNum, | ||
|
ThomasK33 marked this conversation as resolved.
|
||
| Operation: op, | ||
| Status: StatusInProgress, | ||
| HistoryTipMessageID: rc.HistoryTipMessageID, | ||
| NormalizedRequest: normalizedReq, | ||
| }) | ||
| if err != nil { | ||
| svc.log.Warn(ctx, "failed to create chat debug step", | ||
| slog.Error(err), | ||
| slog.F("chat_id", chatID), | ||
| slog.F("run_id", rc.RunID), | ||
| slog.F("operation", op), | ||
| ) | ||
| return nil, ctx | ||
|
ThomasK33 marked this conversation as resolved.
|
||
| } | ||
|
|
||
| syncStepCounter(rc.RunID, step.StepNumber) | ||
| actualStepNumber := step.StepNumber | ||
| if actualStepNumber == 0 { | ||
| actualStepNumber = stepNum | ||
| } | ||
|
|
||
| sc := &StepContext{ | ||
| StepID: step.ID, | ||
| RunID: rc.RunID, | ||
| ChatID: chatID, | ||
| StepNumber: actualStepNumber, | ||
| Operation: op, | ||
| HistoryTipMessageID: rc.HistoryTipMessageID, | ||
| } | ||
| handle := &stepHandle{stepCtx: sc, sink: &attemptSink{}, svc: svc, opts: opts} | ||
| enriched := ContextWithStep(ctx, handle.stepCtx) | ||
| enriched = withAttemptSink(enriched, handle.sink) | ||
| if reuseStep { | ||
| holder.handle = handle | ||
| } | ||
|
|
||
| return handle, enriched | ||
| } | ||
|
|
||
| // finish updates the debug step with final status and data. | ||
| // sync.Once prevents data races when concurrent callers (e.g. | ||
| // retried stream wrappers sharing a reuse handle) both attempt | ||
| // to finalize the same step. Only the first finish call takes | ||
| // effect. | ||
| func (h *stepHandle) finish( | ||
| ctx context.Context, | ||
| status Status, | ||
| response any, | ||
| usage any, | ||
| errPayload any, | ||
| metadata any, | ||
| ) { | ||
| if h == nil || h.stepCtx == nil { | ||
| return | ||
| } | ||
|
|
||
| h.once.Do(func() { | ||
|
ThomasK33 marked this conversation as resolved.
ThomasK33 marked this conversation as resolved.
ThomasK33 marked this conversation as resolved.
ThomasK33 marked this conversation as resolved.
ThomasK33 marked this conversation as resolved.
ThomasK33 marked this conversation as resolved.
|
||
| h.mu.Lock() | ||
| h.status = status | ||
| h.response = response | ||
| h.usage = usage | ||
|
ThomasK33 marked this conversation as resolved.
|
||
| h.err = errPayload | ||
|
ThomasK33 marked this conversation as resolved.
|
||
| h.metadata = metadata | ||
| h.mu.Unlock() | ||
| if h.svc == nil { | ||
| return | ||
| } | ||
|
|
||
| updateCtx, cancel := stepFinalizeContext(ctx) | ||
| defer cancel() | ||
|
|
||
| if _, updateErr := h.svc.UpdateStep(updateCtx, UpdateStepParams{ | ||
| ID: h.stepCtx.StepID, | ||
| ChatID: h.stepCtx.ChatID, | ||
| Status: status, | ||
| NormalizedResponse: response, | ||
| Usage: usage, | ||
| Attempts: h.sink.snapshot(), | ||
| Error: errPayload, | ||
| Metadata: metadata, | ||
| FinishedAt: time.Now(), | ||
| }); updateErr != nil { | ||
| h.svc.log.Warn(updateCtx, "failed to finalize chat debug step", | ||
| slog.Error(updateErr), | ||
| slog.F("step_id", h.stepCtx.StepID), | ||
| slog.F("chat_id", h.stepCtx.ChatID), | ||
| slog.F("status", status), | ||
| ) | ||
| } | ||
| }) | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.