Skip to content

compilation fixes#2830

Merged
akshaydeo merged 3 commits intomainfrom
04-18-compilation_fixes
Apr 18, 2026
Merged

compilation fixes#2830
akshaydeo merged 3 commits intomainfrom
04-18-compilation_fixes

Conversation

@akshaydeo
Copy link
Copy Markdown
Contributor

@akshaydeo akshaydeo commented Apr 18, 2026

Summary

Renames the ModelRequested field to OriginalModelRequested in BifrostErrorExtraFields and removes provider key arguments from several error construction helpers to reduce coupling between error reporting and provider identity.

Changes

  • Renamed ModelRequested to OriginalModelRequested in BifrostErrorExtraFields across all call sites in core/bifrost.go, tests, and provider code to better reflect that this field captures the model as originally requested before any routing or fallback logic.
  • Removed the provider key argument from NewBifrostOperationError calls in Anthropic provider code, simplifying the function signature.
  • Removed provider/model arguments from newBifrostCtxDoneError in tryStreamRequest, relying on context alone.
  • Removed the providerName argument from getRequestBodyForResponses in the Anthropic utils, updating the corresponding test call.
  • Updated executor.SubmitJob to accept a BifrostContext directly instead of separate vkValue and user values, and removed the redundant return at the end of handleAsyncCreate.
  • Fixed a panic(nil) in TestSafeReset to panic("") for Go 1.21+ compatibility where nil panics are not recoverable as error.
  • Removed stray blank lines in Anthropic provider stream handlers.

Type of change

  • Bug fix
  • Feature
  • Refactor
  • Documentation
  • Chore/CI

Affected areas

  • Core (Go)
  • Transports (HTTP)
  • Providers/Integrations
  • Plugins
  • UI (React)
  • Docs

How to test

go version
go test ./...

Screenshots/Recordings

N/A

Breaking changes

  • Yes
  • No

BifrostErrorExtraFields.ModelRequested has been renamed to OriginalModelRequested. Any consumers reading this field by name will need to update their references accordingly.

Related issues

N/A

Security considerations

None.

Checklist

  • I read docs/contributing/README.md and followed the guidelines
  • I added/updated tests where appropriate
  • I updated documentation where needed
  • I verified builds succeed (Go and UI)
  • I verified the CI pipeline passes locally if applicable

@CLAassistant
Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you sign our Contributor License Agreement before we can accept your contribution.
You have signed the CLA already but the status is still pending? Let us recheck it.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Apr 18, 2026

Caution

Review failed

Pull request was closed or merged during review

📝 Walkthrough

Summary by CodeRabbit

  • Bug Fixes

    • Corrected error-field naming so shutdown/drain errors report the original model more accurately.
    • Reduced redundant metadata in streaming request errors for clearer messages.
  • Chores

    • Harmonized internal error handling and updated related tests and job submission calls.
    • Adjusted streaming-log behavior to control whether raw streaming content is stored.
  • Breaking Changes

    • Provider create/update payloads no longer accept pricing_overrides.

Walkthrough

Refactors internal error metadata keys (ModelRequested → OriginalModelRequested), reduces provider-context args passed into Bifrost error constructors, changes SubmitJob calls to accept a full BifrostContext, removes pricing_overrides from provider payloads, and updates multiple tests and minor imports/streaming logging call.

Changes

Cohort / File(s) Summary
Bifrost core
core/bifrost.go, core/bifrost_test.go
Replaced ModelRequested with OriginalModelRequested in BifrostErrorExtraFields across shutdown/drain/error paths; tests updated; streaming context-done error now created with fewer contextual args.
Anthropic provider
core/providers/anthropic/anthropic.go, core/providers/anthropic/utils.go, core/providers/anthropic/utils_test.go
Removed provider key/name argument from NewBifrostOperationError(...) calls in chat/stream and raw-body stripping paths; adjusted test call signature for getRequestBodyForResponses.
Transports — async submission & router
transports/bifrost-http/handlers/... (async* handlers), transports/bifrost-http/integrations/router.go
Stopped passing bifrostCtx.GetUserValues() / vkValue into executor.SubmitJob; router now calls SubmitJob(bifrostCtx, resultTTL, operation, operationType) and async handlers updated accordingly.
Provider management handler
transports/bifrost-http/handlers/providers.go
Removed pricing_overrides field from providerCreatePayload and providerUpdatePayload, eliminating request-level pricing override parsing.
Tests — async job & decompression
framework/logstore/asyncjob_test.go, core/providers/utils/decompression_test.go
Refactored async job tests to construct and pass *schemas.BifrostContext to SubmitJob (removed context map usage); changed TestSafeReset subtest name and panic payload to non-nil.
Logging & plugins
plugins/logging/main.go, plugins/governance/utils.go
Streaming error logging call updated to pass shouldStoreRaw boolean to applyStreamingOutputToEntry; removed unused slices import in governance utils.
Misc tests
core/providers/anthropic/utils_test.go, core/bifrost_test.go
Adjusted tests to match changed function signatures and error-key updates.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Poem

🐇 I nibble keys and tidy threads,
OriginalModelRequested now softly spreads,
Errors lean and contexts ride whole,
Jobs carry stories from pole to pole,
A tiny rabbit applauds each gentle code shed.

🚥 Pre-merge checks | ✅ 1 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 36.36% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Title check ❓ Inconclusive Title is vague and generic, using 'compilation fixes' which does not convey the actual refactoring work: field renaming, signature changes, error decoupling, and async job handling updates. Replace with a more descriptive title like 'Refactor error reporting and async job handling' to better reflect the scope of changes across multiple components.
✅ Passed checks (1 passed)
Check name Status Explanation
Description check ✅ Passed Description is comprehensive, covering all major changes, breaking changes, and testing instructions. However, it lacks completion of the Checklist section with explicit checkmarks.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch 04-18-compilation_fixes

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 golangci-lint (2.11.4)

level=error msg="[linters_context] typechecking error: pattern ./...: directory prefix . does not contain main module or its selected dependencies"


Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown
Contributor Author

akshaydeo commented Apr 18, 2026

@github-actions
Copy link
Copy Markdown
Contributor

🧪 Test Suite Available

This PR can be tested by a repository admin.

Run tests for PR #2830

@akshaydeo akshaydeo marked this pull request as ready for review April 18, 2026 17:45
@greptile-apps
Copy link
Copy Markdown
Contributor

greptile-apps Bot commented Apr 18, 2026

Confidence Score: 2/5

Not safe to merge — multiple tests will panic and the stream-error path drops provider/model metadata.

Three P1 findings: nil dereference in SubmitJob production code, test suite panics across five test functions, and an incomplete error in the stream cancellation path. These need to be resolved before merging.

framework/logstore/asyncjob.go (nil guard), framework/logstore/asyncjob_test.go (nil receivers + dead contextValues), core/bifrost.go:5024 (missing PopulateExtraFields)

Important Files Changed

Filename Overview
framework/logstore/asyncjob.go SubmitJob now accepts *BifrostContext directly but lacks a nil guard — nil input causes a panic via getVirtualKeyFromContext and GetUserValues.
framework/logstore/asyncjob_test.go Multiple tests pass nil BifrostContext directly or call SetValue on nil, causing panics; PropagatesContextValues also declares contextValues but never applies them to any context.
core/bifrost.go Field rename (ModelRequested → OriginalModelRequested) is consistently applied; stream cancellation error at line 5024 is missing the PopulateExtraFields call present everywhere else.
core/bifrost_test.go Field rename updated correctly in test assertions; no new issues found.
transports/bifrost-http/handlers/asyncinference.go All 11 SubmitJob call sites correctly updated to the new 4-arg signature with bifrostCtx as first argument.
transports/bifrost-http/integrations/router.go handleAsyncCreate updated to pass bifrostCtx directly to SubmitJob; redundant return removed cleanly.
transports/bifrost-http/handlers/providers.go PricingOverrides removed from providerCreatePayload and providerUpdatePayload — silent breaking change not called out in the PR description.

Comments Outside Diff (2)

  1. framework/logstore/asyncjob.go, line 89-115 (link)

    P1 Nil dereference when bifrostCtx is nil

    SubmitJob now receives the full *BifrostContext but has no nil guard. When bifrostCtx is nil, getVirtualKeyFromContext(bifrostCtx) calls GetStringFromContext(ctx, key) which dispatches ctx.Value(key) through the context.Context interface — a non-nil interface wrapping a nil pointer — and panics at bc.valueDelegate inside (*BifrostContext).Value. The same crash occurs at bifrostCtx.GetUserValues() on line 115. The tests TestSubmitJob_NilContextValues, TestSubmitJob_PropagatesContextValues, and TestSubmitJob_EmptyContextValues all pass a nil capturedCtx here and will panic at runtime.

    Fix by guarding both call sites:

    var userValues map[any]any
    if bifrostCtx != nil {
        userValues = bifrostCtx.GetUserValues()
    }
    virtualKeyValue := getVirtualKeyFromContext(bifrostCtx)

    And in getVirtualKeyFromContext:

    if ctx == nil {
        return nil
    }
  2. framework/logstore/asyncjob_test.go, line 86-115 (link)

    P1 contextValues map declared but never applied; assertions are dead

    contextValues is constructed on lines 90–94 but is never written into a BifrostContextcapturedCtx remains nil when passed to SubmitJob. The assertions on lines 111–113 will always fail because no source context carried those values.

    The test should create a real BifrostContext, populate it, and pass that:

    bifrostCtx := schemas.NewBifrostContext(context.Background(), schemas.NoDeadline)
    for k, v := range contextValues {
        bifrostCtx.SetValue(k, v)
    }
    job, err := executor.SubmitJob(bifrostCtx, 3600, operation, schemas.ChatCompletionRequest)

Reviews (3): Last reviewed commit: "remainng fixes" | Re-trigger Greptile

Comment thread core/providers/utils/decompression_test.go Outdated
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
core/bifrost.go (1)

5020-5024: ⚠️ Potential issue | 🟡 Minor

Populate extra fields before returning the stream cancellation error.

This branch now returns newBifrostCtxDoneError(...) directly, so cancelled stream requests lose request_type, provider, and original_model_requested metadata. The neighboring cancellation paths still populate those fields, so this becomes an inconsistent error shape for the same class of failure.

💡 Suggested fix
 	case <-ctx.Done():
 		// Do NOT releaseChannelMessage here — see the identical note in tryRequest.
 		// Worker still holds msg.ResponseStream/msg.Err; releasing now corrupts the
 		// next request that reuses those pooled channels.
-		return nil, newBifrostCtxDoneError(ctx, "while waiting for stream response")
+		bifrostErr := newBifrostCtxDoneError(ctx, "while waiting for stream response")
+		bifrostErr.PopulateExtraFields(req.RequestType, provider, model, model)
+		return nil, bifrostErr
 	}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@core/bifrost.go` around lines 5020 - 5024, The ctx.Done() cancellation branch
currently returns newBifrostCtxDoneError(...) directly and therefore omits
request metadata; update the branch in tryRequest/wherever the case <-ctx.Done()
lives to populate the same fields (request_type, provider,
original_model_requested) on the returned error before returning, mirroring the
neighboring cancellation paths — i.e., build the error via
newBifrostCtxDoneError(ctx, "...") then set its request_type, provider, and
original_model_requested fields (using the same variables used elsewhere in the
function) and return that populated error; do not call releaseChannelMessage
here (keep the existing note).
🧹 Nitpick comments (2)
core/providers/utils/decompression_test.go (1)

501-505: Align the subtest name/message with the new panic payload.

Line 502 now panics with "", but the subtest name and failure text still say “nil panic”. Please rename for clarity.

Suggested tweak
-	t.Run("panic_nil", func(t *testing.T) {
+	t.Run("panic_empty_string", func(t *testing.T) {
 		ok := safeReset(func() error { panic("") })
 		if ok {
-			t.Fatal("expected false for nil panic")
+			t.Fatal("expected false for panicking reset")
 		}
 	})
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@core/providers/utils/decompression_test.go` around lines 501 - 505, The
subtest name and failure message in the test for safeReset are misleading
because the panic payload is an empty string rather than nil; update the t.Run
label from "panic_nil" to something like "panic_empty_string" and change the
t.Fatal text ("expected false for nil panic") to reflect the empty-string
payload (e.g., "expected false for empty-string panic") so the test name and
failure message match the panic in the safeReset test.
core/bifrost_test.go (1)

1865-1867: Consider asserting OriginalModelRequested in both verification loops.

You now populate OriginalModelRequested in the constructed shutdown errors, but the receive-side assertions currently validate only provider/request type. Adding model assertions will pin this behavior and catch regressions earlier.

Suggested test assertion additions
@@
 			if bifrostErr.ExtraFields.RequestType != schemas.ChatCompletionRequest {
 				t.Errorf("message %d: expected requestType %v, got %v",
 					i, schemas.ChatCompletionRequest, bifrostErr.ExtraFields.RequestType)
 			}
+			if bifrostErr.ExtraFields.OriginalModelRequested != "gpt-4" {
+				t.Errorf("message %d: expected original model %q, got %q",
+					i, "gpt-4", bifrostErr.ExtraFields.OriginalModelRequested)
+			}
@@
 			if bifrostErr.ExtraFields.RequestType != schemas.ChatCompletionRequest {
 				t.Errorf("message %d: expected requestType %v, got %v",
 					i, schemas.ChatCompletionRequest, bifrostErr.ExtraFields.RequestType)
 			}
+			if bifrostErr.ExtraFields.OriginalModelRequested != "gpt-4" {
+				t.Errorf("message %d: expected original model %q, got %q",
+					i, "gpt-4", bifrostErr.ExtraFields.OriginalModelRequested)
+			}

Also applies to: 2403-2405

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@core/bifrost_test.go` around lines 1865 - 1867, The test populates
OriginalModelRequested in the constructed shutdown errors but the two
receive-side verification loops only assert provider and request type; update
both verification loops to also assert that the received error's
OriginalModelRequested equals the expected model (use the same mod variable used
when constructing the errors) so regressions are caught—add checks alongside the
existing r.RequestType and provKey assertions for the received error structs.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@transports/bifrost-http/integrations/router.go`:
- Line 1506: The calls in transports/bifrost-http/handlers/asyncinference.go are
passing an extra fifth argument (bifrostCtx.GetUserValues()) to SubmitJob, but
the refactored SubmitJob signature only accepts four parameters (bifrostCtx,
resultTTL, operation, operationType) and already extracts user values inside
framework/logstore/asyncjob.go (see SubmitJob implementation around line 115).
Update all SubmitJob invocations in asyncinference.go to remove the trailing
bifrostCtx.GetUserValues() argument so they match the four-argument form used in
router.go and the SubmitJob implementation.

---

Outside diff comments:
In `@core/bifrost.go`:
- Around line 5020-5024: The ctx.Done() cancellation branch currently returns
newBifrostCtxDoneError(...) directly and therefore omits request metadata;
update the branch in tryRequest/wherever the case <-ctx.Done() lives to populate
the same fields (request_type, provider, original_model_requested) on the
returned error before returning, mirroring the neighboring cancellation paths —
i.e., build the error via newBifrostCtxDoneError(ctx, "...") then set its
request_type, provider, and original_model_requested fields (using the same
variables used elsewhere in the function) and return that populated error; do
not call releaseChannelMessage here (keep the existing note).

---

Nitpick comments:
In `@core/bifrost_test.go`:
- Around line 1865-1867: The test populates OriginalModelRequested in the
constructed shutdown errors but the two receive-side verification loops only
assert provider and request type; update both verification loops to also assert
that the received error's OriginalModelRequested equals the expected model (use
the same mod variable used when constructing the errors) so regressions are
caught—add checks alongside the existing r.RequestType and provKey assertions
for the received error structs.

In `@core/providers/utils/decompression_test.go`:
- Around line 501-505: The subtest name and failure message in the test for
safeReset are misleading because the panic payload is an empty string rather
than nil; update the t.Run label from "panic_nil" to something like
"panic_empty_string" and change the t.Fatal text ("expected false for nil
panic") to reflect the empty-string payload (e.g., "expected false for
empty-string panic") so the test name and failure message match the panic in the
safeReset test.
🪄 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: CHILL

Plan: Pro

Run ID: 807b5fc1-fdc8-4939-9152-71d50a49b13f

📥 Commits

Reviewing files that changed from the base of the PR and between c23c91c and 604a985.

📒 Files selected for processing (7)
  • core/bifrost.go
  • core/bifrost_test.go
  • core/providers/anthropic/anthropic.go
  • core/providers/anthropic/utils.go
  • core/providers/anthropic/utils_test.go
  • core/providers/utils/decompression_test.go
  • transports/bifrost-http/integrations/router.go

Comment thread transports/bifrost-http/integrations/router.go
Comment thread transports/bifrost-http/integrations/router.go
@akshaydeo akshaydeo mentioned this pull request Apr 18, 2026
18 tasks
Copy link
Copy Markdown
Contributor Author

akshaydeo commented Apr 18, 2026

Merge activity

  • Apr 18, 6:49 PM UTC: A user started a stack merge that includes this pull request via Graphite.
  • Apr 18, 6:49 PM UTC: @akshaydeo merged this pull request with Graphite.

@akshaydeo akshaydeo merged commit 4559d6a into main Apr 18, 2026
11 of 17 checks passed
@akshaydeo akshaydeo deleted the 04-18-compilation_fixes branch April 18, 2026 18:49
Comment on lines 161 to +187
@@ -188,11 +183,8 @@ func TestSubmitJob_AsyncFlagOverridesContextValues(t *testing.T) {
func TestSubmitJob_OperationFailure_PreservesContext(t *testing.T) {
executor := newTestAsyncExecutor(t)

contextValues := map[any]any{
schemas.BifrostContextKeyVirtualKey: "sk-bf-test",
}

var capturedCtx *schemas.BifrostContext
capturedCtx.SetValue(schemas.BifrostContextKeyVirtualKey, "sk-bf-test")
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Nil pointer dereference before SubmitJob in two tests

TestSubmitJob_AsyncFlagOverridesContextValues (line 166) and TestSubmitJob_OperationFailure_PreservesContext (line 187) both call capturedCtx.SetValue(...) on an uninitialised var capturedCtx *schemas.BifrostContext (nil). (*BifrostContext).SetValue accesses bc.blockRestrictedWrites.Load() unconditionally, so both tests panic before reaching SubmitJob. Each should initialise capturedCtx with schemas.NewBifrostContext(...) first.

ALSEDLAH pushed a commit to ALSEDLAH/bifrost that referenced this pull request Apr 20, 2026
…smoke

T006: framework/logstore/rdb_user_rankings_test.go — seeds 3 users +
one empty-user_id row across known time windows, asserts totals,
ordering by total_requests DESC, trend computation against
hand-calculated previous-period expectation (50% delta for alice),
exclusion of empty user_id. Passes on golang:1.26-alpine.

T009: ui/tests/e2e/enterprise/user-rankings.spec.ts — navigates
dashboard → User Rankings tab, asserts user-rankings-view testid,
absence of feature-status-panel, and row-click drilldown to
/workspace/logs?user_ids=... (runner infra still pending per spec
001 T031 carryover).

Side fixes:
- asyncjob_test.go:90 — mute unused var `contextValues` left over
  from upstream PR maximhq#2830 that was blocking the package from
  compiling at all.
- specs/002 research.md row 20 flipped from "descope → panel" to
  "shipped in spec 003".
- specs/003 tasks.md T006/T009/T011/T013/T014 marked done; T012
  (changelog) skipped — no changelog convention in this repo.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
ALSEDLAH pushed a commit to ALSEDLAH/bifrost that referenced this pull request Apr 20, 2026
…smoke

T006: framework/logstore/rdb_user_rankings_test.go — seeds 3 users +
one empty-user_id row across known time windows, asserts totals,
ordering by total_requests DESC, trend computation against
hand-calculated previous-period expectation (50% delta for alice),
exclusion of empty user_id. Passes on golang:1.26-alpine.

T009: ui/tests/e2e/enterprise/user-rankings.spec.ts — navigates
dashboard → User Rankings tab, asserts user-rankings-view testid,
absence of feature-status-panel, and row-click drilldown to
/workspace/logs?user_ids=... (runner infra still pending per spec
001 T031 carryover).

Side fixes:
- asyncjob_test.go:90 — mute unused var `contextValues` left over
  from upstream PR maximhq#2830 that was blocking the package from
  compiling at all.
- specs/002 research.md row 20 flipped from "descope → panel" to
  "shipped in spec 003".
- specs/003 tasks.md T006/T009/T011/T013/T014 marked done; T012
  (changelog) skipped — no changelog convention in this repo.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants