refactor: remove dead guardrails wrapper, cut redundancies, fix registry trim#449
Conversation
…try trim Quality pass focused on removing dead/duplicated code and one routing bug, while keeping behavior and test coverage intact. fix(registry): provider types were stored verbatim at registration while every reader except ProviderByType trimmed on lookup, so a configured type with surrounding whitespace (YAML/env) made type-based routing silently return nil. Normalize the type at registration; add a regression test. refactor(guardrails): delete the dead GuardedProvider wrapper (provider.go, 518 lines) and the unused RequestPatcher/BatchPreparer in executor.go. The live request path applies guardrails through WorkflowRequestPatcher / WorkflowBatchPreparer (wired in app.go); the wrapper was only reachable from its own tests. Live clone helpers moved to clone.go. Coverage of the shared rewrite functions (processGuardedChat/Responses/BatchRequest) is preserved via a trimmed test-only harness; the 6 pure-delegation tests were dropped and the server tests retargeted onto the live Workflow* patchers. refactor: assorted redundancy cleanups - - providers/router.go: collapse 3 near-identical Native*ProviderTypes loops into one providerTypesSupporting helper. - core/errors.go: add NewEmptyProviderResponseError, replacing 8 duplicated constructions in native_response_service.go and inference_execute.go. - replace 4 hand-rolled map[string]any clone helpers with stdlib maps.Clone. - anthropic: drop an unreachable len(tokens)==0 branch. Net ~-469 lines. go build/vet/test and gofmt all clean. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: ASSERTIVE Plan: Pro Run ID: 📒 Files selected for processing (5)
📝 WalkthroughWalkthroughAdds a dedicated empty-provider-response error used by gateway and native response paths. Moves guardrails request handling into a test harness with cloning helpers and workflow-aware test updates. Simplifies map cloning, trims registry input, removes one Anthropic validation check, and consolidates router capability filtering. ChangesEmpty Provider Response Error
Guardrails Workflow Refactor
Map Cloning and Provider Registry Cleanup
Sequence Diagram(s)sequenceDiagram
participant NativeResponseService
participant Provider
participant core
NativeResponseService->>Provider: GetResponse / CancelResponse / DeleteResponse
Provider-->>NativeResponseService: resp == nil
NativeResponseService->>core: NewEmptyProviderResponseError(providerType)
core-->>NativeResponseService: GatewayError (502 Bad Gateway)
sequenceDiagram
participant Test
participant GuardedProvider
participant processGuardedBatchRequest
participant batchrewrite
participant InnerProvider
Test->>GuardedProvider: CreateBatch(providerType, req)
GuardedProvider->>processGuardedBatchRequest: rewrite request
processGuardedBatchRequest-->>GuardedProvider: rewritten request
GuardedProvider->>batchrewrite: RecordPreparation
GuardedProvider->>InnerProvider: CreateBatch(rewritten)
InnerProvider-->>GuardedProvider: response or error
GuardedProvider->>batchrewrite: CleanupFileFromRouter / CleanupSupersededFileFromRouter
Estimated code review effort🎯 4 (Complex) | ⏱️ ~55 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
|
Codecov Report❌ Patch coverage is 📢 Thoughts on this report? Let us know! |
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@internal/guardrails/clone.go`:
- Around line 38-53: The fallback path in cloneMessageContent is returning the
original non-standard content value instead of cloning it, which breaks the
no-mutation contract. Update cloneMessageContent so the default branch in
internal/guardrails/clone.go either produces a real deep copy for unsupported
shapes or, if that is not feasible, explicitly documents the limitation and
restricts callers accordingly; use the existing cloneContentParts and
core.NormalizeContentParts flow to keep behavior consistent for all content
types.
In `@internal/guardrails/provider_harness_test.go`:
- Around line 25-28: The exported Options type in the test harness is too
generic and can collide with future package-level types in guardrails. Rename
the type in provider_harness_test.go to a more specific identifier such as
GuardedProviderOptions, and update all references to it in the harness helpers
and tests so the package namespace stays unambiguous.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: ASSERTIVE
Plan: Pro
Run ID: c789cca4-e7b2-4c19-b86e-eecd34bc9a09
📒 Files selected for processing (17)
internal/core/errors.gointernal/gateway/inference_execute.gointernal/guardrails/clone.gointernal/guardrails/executor.gointernal/guardrails/provider.gointernal/guardrails/provider_harness_test.gointernal/guardrails/provider_test.gointernal/guardrails/responses_message_apply.gointernal/providers/anthropic/request_translation.gointernal/providers/registry.gointernal/providers/registry_test.gointernal/providers/responses_adapter.gointernal/providers/router.gointernal/responsecache/stream_cache.gointernal/server/handlers_test.gointernal/server/native_response_service.gointernal/usage/extractor.go
💤 Files with no reviewable changes (3)
- internal/providers/anthropic/request_translation.go
- internal/guardrails/provider.go
- internal/guardrails/executor.go
- clone.go: document why the cloneMessageContent fallback returns the original (shared) reference for unrecognized content shapes — chat content is normalized to nil/string/[]ContentPart before reaching it and guardrails replace whole values rather than mutating in place, so the branch is defensive and the shared reference is safe. - provider_harness_test.go: rename the test-only Options type to GuardedProviderOptions so it can't collide with a future package-level type in package guardrails. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Summary
A focused code-quality pass: removes dead and duplicated code and fixes one routing bug, with no change to public API behavior and test coverage preserved. Net ~−469 lines.
Bug fix
fix(registry): Provider types were stored verbatim at registration while every reader exceptProviderByTypetrimmed on lookup. A configured type with surrounding whitespace (e.g. from YAML/env) therefore made type-based routing silently returnnil. The type is now normalized at registration alongside the name, so all lookups stay consistent. Added regression testTestProviderByTypeAndNameTrimConfiguredValues.Dead code removal
GuardedProviderwrapper (guardrails/provider.go, 518 lines) and the unusedRequestPatcher/BatchPreparerinexecutor.go(52 lines). The live request path applies guardrails throughWorkflowRequestPatcher/WorkflowBatchPreparer(wired inapp.go); the wrapper was only reachable from its own tests.guardrails/clone.go.processGuardedChat/processGuardedResponses/processGuardedBatchRequest) are still exercised end-to-end via a trimmed test-only harness (provider_harness_test.go). The 6 pure-delegation tests were dropped (they only checked that the wrapper forwarded to its inner provider), and the two server tests were retargeted onto the liveWorkflow*patchers.Redundancy cleanups
providers/router.go: collapsed 3 near-identicalNative{File,Batch,Response}ProviderTypesloops into oneproviderTypesSupportinghelper.core/errors.go: addedNewEmptyProviderResponseError, replacing 8 duplicatedNewProviderError(... "provider returned empty response" ...)constructions acrossnative_response_service.goandinference_execute.go.map[string]anyclone helpers with stdlibmaps.Clone(identicalnil → nilsemantics).anthropic: dropped an unreachablelen(tokens) == 0branch (strings.Splitnever returns empty).Verification
make test-race,make lint,go mod tidy,gofmt, and the hot-path performance guard all pass (enforced by pre-commit).Follow-up (not in this PR)
workflows/service.goduplicates a 6-way scope classification across 4 sites; unifying it cleanly means restructuring the snapshot and touches resolution-order logic, so it warrants its own reviewed PR.🤖 Generated with Claude Code
Summary by CodeRabbit
Bug Fixes
Tests